diff --git a/.gitattributes b/.gitattributes index fc9f2ec3c5d103aed4c1b0e453f4fe34848ef990..98675c6ce845bd89f5945a55bf53b0359558620a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -411,3 +411,7 @@ material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space: material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_Manual_4connected/1908284_m.tif filter=lfs diff=lfs merge=lfs -text material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_Manual_4connected/1908324_m.tif filter=lfs diff=lfs merge=lfs -text material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908288/1908288.tif filter=lfs diff=lfs merge=lfs -text +material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908300/1908300.tif filter=lfs diff=lfs merge=lfs -text +material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908266/1908266.tif filter=lfs diff=lfs merge=lfs -text +material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_Manual_4connected/1908306_m.tif filter=lfs diff=lfs merge=lfs -text +material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_TSEM/Image_Registration/Output/1908274/1908274.tif filter=lfs diff=lfs merge=lfs -text diff --git a/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_Manual_4connected/1908306_m.tif b/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_Manual_4connected/1908306_m.tif new file mode 100644 index 0000000000000000000000000000000000000000..3ab387fd43b09b81364a9d2e9d4d630e76192074 --- /dev/null +++ b/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_Manual_4connected/1908306_m.tif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:58e3056fd6787f289d448f6b6a65889606523d4c92b274d209696c6b1926637d +size 787398 diff --git a/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908266/1908266.tif b/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908266/1908266.tif new file mode 100644 index 0000000000000000000000000000000000000000..3b3bc65659a72bdeaee3ec093f81dc1bf02888b9 --- /dev/null +++ b/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908266/1908266.tif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:06e6f39552276a3ff7cb0fad456267b4c856822f1dfeee15df3ddaae15600ff0 +size 729295 diff --git a/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908300/1908300.tif b/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908300/1908300.tif new file mode 100644 index 0000000000000000000000000000000000000000..16fd3aba5d326ee3b85c1738296a0b3ccef052f0 --- /dev/null +++ b/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908300/1908300.tif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:af9220e2d6a88a2503158405d918fa9b9e5e7e53b1e82d5fcbfb8c0047022511 +size 729295 diff --git a/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_TSEM/Image_Registration/Output/1908274/1908274.tif b/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_TSEM/Image_Registration/Output/1908274/1908274.tif new file mode 100644 index 0000000000000000000000000000000000000000..10d44f93362e1e1be2098b44253aa486f674bc82 --- /dev/null +++ b/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_TSEM/Image_Registration/Output/1908274/1908274.tif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a921e40cec79557e7a34df777ed6ab1e3e1453fb35711cbb39cdbcd1c2c4ddd +size 741748 diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/lib/__pycache__/deepreload.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/lib/__pycache__/deepreload.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a8b2a37fd82d507ca10dae32854728501952996 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/lib/__pycache__/deepreload.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/lib/clipboard.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/lib/clipboard.py new file mode 100644 index 0000000000000000000000000000000000000000..e0bf80b075563d76939e9565981ca4426510c582 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/lib/clipboard.py @@ -0,0 +1,102 @@ +""" Utilities for accessing the platform's clipboard. +""" + +import os +import subprocess + +from IPython.core.error import TryNext +import IPython.utils.py3compat as py3compat + + +class ClipboardEmpty(ValueError): + pass + + +def win32_clipboard_get(): + """ Get the current clipboard's text on Windows. + + Requires Mark Hammond's pywin32 extensions. + """ + try: + import win32clipboard + except ImportError as e: + raise TryNext("Getting text from the clipboard requires the pywin32 " + "extensions: http://sourceforge.net/projects/pywin32/") from e + win32clipboard.OpenClipboard() + try: + text = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT) + except (TypeError, win32clipboard.error): + try: + text = win32clipboard.GetClipboardData(win32clipboard.CF_TEXT) + text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING) + except (TypeError, win32clipboard.error) as e: + raise ClipboardEmpty from e + finally: + win32clipboard.CloseClipboard() + return text + + +def osx_clipboard_get() -> str: + """ Get the clipboard's text on OS X. + """ + p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'], + stdout=subprocess.PIPE) + bytes_, stderr = p.communicate() + # Text comes in with old Mac \r line endings. Change them to \n. + bytes_ = bytes_.replace(b'\r', b'\n') + text = py3compat.decode(bytes_) + return text + + +def tkinter_clipboard_get(): + """ Get the clipboard's text using Tkinter. + + This is the default on systems that are not Windows or OS X. It may + interfere with other UI toolkits and should be replaced with an + implementation that uses that toolkit. + """ + try: + from tkinter import Tk, TclError + except ImportError as e: + raise TryNext("Getting text from the clipboard on this platform requires tkinter.") from e + + root = Tk() + root.withdraw() + try: + text = root.clipboard_get() + except TclError as e: + raise ClipboardEmpty from e + finally: + root.destroy() + text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING) + return text + + +def wayland_clipboard_get(): + """Get the clipboard's text under Wayland using wl-paste command. + + This requires Wayland and wl-clipboard installed and running. + """ + if os.environ.get("XDG_SESSION_TYPE") != "wayland": + raise TryNext("wayland is not detected") + + try: + with subprocess.Popen(["wl-paste"], stdout=subprocess.PIPE) as p: + raw, err = p.communicate() + if p.wait(): + raise TryNext(err) + except FileNotFoundError as e: + raise TryNext( + "Getting text from the clipboard under Wayland requires the wl-clipboard " + "extension: https://github.com/bugaevc/wl-clipboard" + ) from e + + if not raw: + raise ClipboardEmpty + + try: + text = py3compat.decode(raw) + except UnicodeDecodeError as e: + raise ClipboardEmpty from e + + return text diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/lib/demo.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/lib/demo.py new file mode 100644 index 0000000000000000000000000000000000000000..ebffd54abde77fad773a98c8058585f7843ef715 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/lib/demo.py @@ -0,0 +1,672 @@ +"""Module for interactive demos using IPython. + +This module implements a few classes for running Python scripts interactively +in IPython for demonstrations. With very simple markup (a few tags in +comments), you can control points where the script stops executing and returns +control to IPython. + + +Provided classes +---------------- + +The classes are (see their docstrings for further details): + + - Demo: pure python demos + + - IPythonDemo: demos with input to be processed by IPython as if it had been + typed interactively (so magics work, as well as any other special syntax you + may have added via input prefilters). + + - LineDemo: single-line version of the Demo class. These demos are executed + one line at a time, and require no markup. + + - IPythonLineDemo: IPython version of the LineDemo class (the demo is + executed a line at a time, but processed via IPython). + + - ClearMixin: mixin to make Demo classes with less visual clutter. It + declares an empty marquee and a pre_cmd that clears the screen before each + block (see Subclassing below). + + - ClearDemo, ClearIPDemo: mixin-enabled versions of the Demo and IPythonDemo + classes. + +Inheritance diagram: + +.. inheritance-diagram:: IPython.lib.demo + :parts: 3 + +Subclassing +----------- + +The classes here all include a few methods meant to make customization by +subclassing more convenient. Their docstrings below have some more details: + + - highlight(): format every block and optionally highlight comments and + docstring content. + + - marquee(): generates a marquee to provide visible on-screen markers at each + block start and end. + + - pre_cmd(): run right before the execution of each block. + + - post_cmd(): run right after the execution of each block. If the block + raises an exception, this is NOT called. + + +Operation +--------- + +The file is run in its own empty namespace (though you can pass it a string of +arguments as if in a command line environment, and it will see those as +sys.argv). But at each stop, the global IPython namespace is updated with the +current internal demo namespace, so you can work interactively with the data +accumulated so far. + +By default, each block of code is printed (with syntax highlighting) before +executing it and you have to confirm execution. This is intended to show the +code to an audience first so you can discuss it, and only proceed with +execution once you agree. There are a few tags which allow you to modify this +behavior. + +The supported tags are: + +# stop + + Defines block boundaries, the points where IPython stops execution of the + file and returns to the interactive prompt. + + You can optionally mark the stop tag with extra dashes before and after the + word 'stop', to help visually distinguish the blocks in a text editor: + + # --- stop --- + + +# silent + + Make a block execute silently (and hence automatically). Typically used in + cases where you have some boilerplate or initialization code which you need + executed but do not want to be seen in the demo. + +# auto + + Make a block execute automatically, but still being printed. Useful for + simple code which does not warrant discussion, since it avoids the extra + manual confirmation. + +# auto_all + + This tag can _only_ be in the first block, and if given it overrides the + individual auto tags to make the whole demo fully automatic (no block asks + for confirmation). It can also be given at creation time (or the attribute + set later) to override what's in the file. + +While _any_ python file can be run as a Demo instance, if there are no stop +tags the whole file will run in a single block (no different that calling +first %pycat and then %run). The minimal markup to make this useful is to +place a set of stop tags; the other tags are only there to let you fine-tune +the execution. + +This is probably best explained with the simple example file below. You can +copy this into a file named ex_demo.py, and try running it via:: + + from IPython.lib.demo import Demo + d = Demo('ex_demo.py') + d() + +Each time you call the demo object, it runs the next block. The demo object +has a few useful methods for navigation, like again(), edit(), jump(), seek() +and back(). It can be reset for a new run via reset() or reloaded from disk +(in case you've edited the source) via reload(). See their docstrings below. + +Note: To make this simpler to explore, a file called "demo-exercizer.py" has +been added to the "docs/examples/core" directory. Just cd to this directory in +an IPython session, and type:: + + %run demo-exercizer.py + +and then follow the directions. + +Example +------- + +The following is a very simple example of a valid demo file. + +:: + + #################### EXAMPLE DEMO ############################### + '''A simple interactive demo to illustrate the use of IPython's Demo class.''' + + print('Hello, welcome to an interactive IPython demo.') + + # The mark below defines a block boundary, which is a point where IPython will + # stop execution and return to the interactive prompt. The dashes are actually + # optional and used only as a visual aid to clearly separate blocks while + # editing the demo code. + # stop + + x = 1 + y = 2 + + # stop + + # the mark below makes this block as silent + # silent + + print('This is a silent block, which gets executed but not printed.') + + # stop + # auto + print('This is an automatic block.') + print('It is executed without asking for confirmation, but printed.') + z = x + y + + print('z =', x) + + # stop + # This is just another normal block. + print('z is now:', z) + + print('bye!') + ################### END EXAMPLE DEMO ############################ +""" + + +#***************************************************************************** +# Copyright (C) 2005-2006 Fernando Perez. +# +# Distributed under the terms of the BSD License. The full license is in +# the file COPYING, distributed as part of this software. +# +#***************************************************************************** + +import os +import re +import shlex +import sys +import pygments +from pathlib import Path + +from IPython.utils.text import marquee +from IPython.utils import openpy +from IPython.utils import py3compat +__all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError'] + +class DemoError(Exception): pass + +def re_mark(mark): + return re.compile(r'^\s*#\s+\s+%s\s*$' % mark,re.MULTILINE) + +class Demo(object): + + re_stop = re_mark(r'-*\s?stop\s?-*') + re_silent = re_mark('silent') + re_auto = re_mark('auto') + re_auto_all = re_mark('auto_all') + + def __init__(self,src,title='',arg_str='',auto_all=None, format_rst=False, + formatter='terminal', style='default'): + """Make a new demo object. To run the demo, simply call the object. + + See the module docstring for full details and an example (you can use + IPython.Demo? in IPython to see it). + + Inputs: + + - src is either a file, or file-like object, or a + string that can be resolved to a filename. + + Optional inputs: + + - title: a string to use as the demo name. Of most use when the demo + you are making comes from an object that has no filename, or if you + want an alternate denotation distinct from the filename. + + - arg_str(''): a string of arguments, internally converted to a list + just like sys.argv, so the demo script can see a similar + environment. + + - auto_all(None): global flag to run all blocks automatically without + confirmation. This attribute overrides the block-level tags and + applies to the whole demo. It is an attribute of the object, and + can be changed at runtime simply by reassigning it to a boolean + value. + + - format_rst(False): a bool to enable comments and doc strings + formatting with pygments rst lexer + + - formatter('terminal'): a string of pygments formatter name to be + used. Useful values for terminals: terminal, terminal256, + terminal16m + + - style('default'): a string of pygments style name to be used. + """ + if hasattr(src, "read"): + # It seems to be a file or a file-like object + self.fname = "from a file-like object" + if title == '': + self.title = "from a file-like object" + else: + self.title = title + else: + # Assume it's a string or something that can be converted to one + self.fname = src + if title == '': + (filepath, filename) = os.path.split(src) + self.title = filename + else: + self.title = title + self.sys_argv = [src] + shlex.split(arg_str) + self.auto_all = auto_all + self.src = src + + try: + ip = get_ipython() # this is in builtins whenever IPython is running + self.inside_ipython = True + except NameError: + self.inside_ipython = False + + if self.inside_ipython: + # get a few things from ipython. While it's a bit ugly design-wise, + # it ensures that things like color scheme and the like are always in + # sync with the ipython mode being used. This class is only meant to + # be used inside ipython anyways, so it's OK. + self.ip_ns = ip.user_ns + self.ip_colorize = ip.pycolorize + self.ip_showtb = ip.showtraceback + self.ip_run_cell = ip.run_cell + self.shell = ip + + self.formatter = pygments.formatters.get_formatter_by_name(formatter, + style=style) + self.python_lexer = pygments.lexers.get_lexer_by_name("py3") + self.format_rst = format_rst + if format_rst: + self.rst_lexer = pygments.lexers.get_lexer_by_name("rst") + + # load user data and initialize data structures + self.reload() + + def fload(self): + """Load file object.""" + # read data and parse into blocks + if hasattr(self, 'fobj') and self.fobj is not None: + self.fobj.close() + if hasattr(self.src, "read"): + # It seems to be a file or a file-like object + self.fobj = self.src + else: + # Assume it's a string or something that can be converted to one + self.fobj = openpy.open(self.fname) + + def reload(self): + """Reload source from disk and initialize state.""" + self.fload() + + self.src = "".join(openpy.strip_encoding_cookie(self.fobj)) + src_b = [b.strip() for b in self.re_stop.split(self.src) if b] + self._silent = [bool(self.re_silent.findall(b)) for b in src_b] + self._auto = [bool(self.re_auto.findall(b)) for b in src_b] + + # if auto_all is not given (def. None), we read it from the file + if self.auto_all is None: + self.auto_all = bool(self.re_auto_all.findall(src_b[0])) + else: + self.auto_all = bool(self.auto_all) + + # Clean the sources from all markup so it doesn't get displayed when + # running the demo + src_blocks = [] + auto_strip = lambda s: self.re_auto.sub('',s) + for i,b in enumerate(src_b): + if self._auto[i]: + src_blocks.append(auto_strip(b)) + else: + src_blocks.append(b) + # remove the auto_all marker + src_blocks[0] = self.re_auto_all.sub('',src_blocks[0]) + + self.nblocks = len(src_blocks) + self.src_blocks = src_blocks + + # also build syntax-highlighted source + self.src_blocks_colored = list(map(self.highlight,self.src_blocks)) + + # ensure clean namespace and seek offset + self.reset() + + def reset(self): + """Reset the namespace and seek pointer to restart the demo""" + self.user_ns = {} + self.finished = False + self.block_index = 0 + + def _validate_index(self,index): + if index<0 or index>=self.nblocks: + raise ValueError('invalid block index %s' % index) + + def _get_index(self,index): + """Get the current block index, validating and checking status. + + Returns None if the demo is finished""" + + if index is None: + if self.finished: + print('Demo finished. Use .reset() if you want to rerun it.') + return None + index = self.block_index + else: + self._validate_index(index) + return index + + def seek(self,index): + """Move the current seek pointer to the given block. + + You can use negative indices to seek from the end, with identical + semantics to those of Python lists.""" + if index<0: + index = self.nblocks + index + self._validate_index(index) + self.block_index = index + self.finished = False + + def back(self,num=1): + """Move the seek pointer back num blocks (default is 1).""" + self.seek(self.block_index-num) + + def jump(self,num=1): + """Jump a given number of blocks relative to the current one. + + The offset can be positive or negative, defaults to 1.""" + self.seek(self.block_index+num) + + def again(self): + """Move the seek pointer back one block and re-execute.""" + self.back(1) + self() + + def edit(self,index=None): + """Edit a block. + + If no number is given, use the last block executed. + + This edits the in-memory copy of the demo, it does NOT modify the + original source file. If you want to do that, simply open the file in + an editor and use reload() when you make changes to the file. This + method is meant to let you change a block during a demonstration for + explanatory purposes, without damaging your original script.""" + + index = self._get_index(index) + if index is None: + return + # decrease the index by one (unless we're at the very beginning), so + # that the default demo.edit() call opens up the sblock we've last run + if index>0: + index -= 1 + + filename = self.shell.mktempfile(self.src_blocks[index]) + self.shell.hooks.editor(filename, 1) + with open(Path(filename), "r", encoding="utf-8") as f: + new_block = f.read() + # update the source and colored block + self.src_blocks[index] = new_block + self.src_blocks_colored[index] = self.highlight(new_block) + self.block_index = index + # call to run with the newly edited index + self() + + def show(self,index=None): + """Show a single block on screen""" + + index = self._get_index(index) + if index is None: + return + + print(self.marquee('<%s> block # %s (%s remaining)' % + (self.title,index,self.nblocks-index-1))) + print(self.src_blocks_colored[index]) + sys.stdout.flush() + + def show_all(self): + """Show entire demo on screen, block by block""" + + fname = self.title + title = self.title + nblocks = self.nblocks + silent = self._silent + marquee = self.marquee + for index,block in enumerate(self.src_blocks_colored): + if silent[index]: + print(marquee('<%s> SILENT block # %s (%s remaining)' % + (title,index,nblocks-index-1))) + else: + print(marquee('<%s> block # %s (%s remaining)' % + (title,index,nblocks-index-1))) + print(block, end=' ') + sys.stdout.flush() + + def run_cell(self,source): + """Execute a string with one or more lines of code""" + + exec(source, self.user_ns) + + def __call__(self,index=None): + """run a block of the demo. + + If index is given, it should be an integer >=1 and <= nblocks. This + means that the calling convention is one off from typical Python + lists. The reason for the inconsistency is that the demo always + prints 'Block n/N, and N is the total, so it would be very odd to use + zero-indexing here.""" + + index = self._get_index(index) + if index is None: + return + try: + marquee = self.marquee + next_block = self.src_blocks[index] + self.block_index += 1 + if self._silent[index]: + print(marquee('Executing silent block # %s (%s remaining)' % + (index,self.nblocks-index-1))) + else: + self.pre_cmd() + self.show(index) + if self.auto_all or self._auto[index]: + print(marquee('output:')) + else: + print(marquee('Press to quit, to execute...'), end=' ') + ans = py3compat.input().strip() + if ans: + print(marquee('Block NOT executed')) + return + try: + save_argv = sys.argv + sys.argv = self.sys_argv + self.run_cell(next_block) + self.post_cmd() + finally: + sys.argv = save_argv + + except: + if self.inside_ipython: + self.ip_showtb(filename=self.fname) + else: + if self.inside_ipython: + self.ip_ns.update(self.user_ns) + + if self.block_index == self.nblocks: + mq1 = self.marquee('END OF DEMO') + if mq1: + # avoid spurious print if empty marquees are used + print() + print(mq1) + print(self.marquee('Use .reset() if you want to rerun it.')) + self.finished = True + + # These methods are meant to be overridden by subclasses who may wish to + # customize the behavior of of their demos. + def marquee(self,txt='',width=78,mark='*'): + """Return the input string centered in a 'marquee'.""" + return marquee(txt,width,mark) + + def pre_cmd(self): + """Method called before executing each block.""" + pass + + def post_cmd(self): + """Method called after executing each block.""" + pass + + def highlight(self, block): + """Method called on each block to highlight it content""" + tokens = pygments.lex(block, self.python_lexer) + if self.format_rst: + from pygments.token import Token + toks = [] + for token in tokens: + if token[0] == Token.String.Doc and len(token[1]) > 6: + toks += pygments.lex(token[1][:3], self.python_lexer) + # parse doc string content by rst lexer + toks += pygments.lex(token[1][3:-3], self.rst_lexer) + toks += pygments.lex(token[1][-3:], self.python_lexer) + elif token[0] == Token.Comment.Single: + toks.append((Token.Comment.Single, token[1][0])) + # parse comment content by rst lexer + # remove the extra newline added by rst lexer + toks += list(pygments.lex(token[1][1:], self.rst_lexer))[:-1] + else: + toks.append(token) + tokens = toks + return pygments.format(tokens, self.formatter) + + +class IPythonDemo(Demo): + """Class for interactive demos with IPython's input processing applied. + + This subclasses Demo, but instead of executing each block by the Python + interpreter (via exec), it actually calls IPython on it, so that any input + filters which may be in place are applied to the input block. + + If you have an interactive environment which exposes special input + processing, you can use this class instead to write demo scripts which + operate exactly as if you had typed them interactively. The default Demo + class requires the input to be valid, pure Python code. + """ + + def run_cell(self,source): + """Execute a string with one or more lines of code""" + + self.shell.run_cell(source) + +class LineDemo(Demo): + """Demo where each line is executed as a separate block. + + The input script should be valid Python code. + + This class doesn't require any markup at all, and it's meant for simple + scripts (with no nesting or any kind of indentation) which consist of + multiple lines of input to be executed, one at a time, as if they had been + typed in the interactive prompt. + + Note: the input can not have *any* indentation, which means that only + single-lines of input are accepted, not even function definitions are + valid.""" + + def reload(self): + """Reload source from disk and initialize state.""" + # read data and parse into blocks + self.fload() + lines = self.fobj.readlines() + src_b = [l for l in lines if l.strip()] + nblocks = len(src_b) + self.src = ''.join(lines) + self._silent = [False]*nblocks + self._auto = [True]*nblocks + self.auto_all = True + self.nblocks = nblocks + self.src_blocks = src_b + + # also build syntax-highlighted source + self.src_blocks_colored = list(map(self.highlight,self.src_blocks)) + + # ensure clean namespace and seek offset + self.reset() + + +class IPythonLineDemo(IPythonDemo,LineDemo): + """Variant of the LineDemo class whose input is processed by IPython.""" + pass + + +class ClearMixin(object): + """Use this mixin to make Demo classes with less visual clutter. + + Demos using this mixin will clear the screen before every block and use + blank marquees. + + Note that in order for the methods defined here to actually override those + of the classes it's mixed with, it must go /first/ in the inheritance + tree. For example: + + class ClearIPDemo(ClearMixin,IPythonDemo): pass + + will provide an IPythonDemo class with the mixin's features. + """ + + def marquee(self,txt='',width=78,mark='*'): + """Blank marquee that returns '' no matter what the input.""" + return '' + + def pre_cmd(self): + """Method called before executing each block. + + This one simply clears the screen.""" + from IPython.utils.terminal import _term_clear + _term_clear() + +class ClearDemo(ClearMixin,Demo): + pass + + +class ClearIPDemo(ClearMixin,IPythonDemo): + pass + + +def slide(file_path, noclear=False, format_rst=True, formatter="terminal", + style="native", auto_all=False, delimiter='...'): + if noclear: + demo_class = Demo + else: + demo_class = ClearDemo + demo = demo_class(file_path, format_rst=format_rst, formatter=formatter, + style=style, auto_all=auto_all) + while not demo.finished: + demo() + try: + py3compat.input('\n' + delimiter) + except KeyboardInterrupt: + exit(1) + +if __name__ == '__main__': + import argparse + parser = argparse.ArgumentParser(description='Run python demos') + parser.add_argument('--noclear', '-C', action='store_true', + help='Do not clear terminal on each slide') + parser.add_argument('--rst', '-r', action='store_true', + help='Highlight comments and dostrings as rst') + parser.add_argument('--formatter', '-f', default='terminal', + help='pygments formatter name could be: terminal, ' + 'terminal256, terminal16m') + parser.add_argument('--style', '-s', default='default', + help='pygments style name') + parser.add_argument('--auto', '-a', action='store_true', + help='Run all blocks automatically without' + 'confirmation') + parser.add_argument('--delimiter', '-d', default='...', + help='slides delimiter added after each slide run') + parser.add_argument('file', nargs=1, + help='python demo file') + args = parser.parse_args() + slide(args.file[0], noclear=args.noclear, format_rst=args.rst, + formatter=args.formatter, style=args.style, auto_all=args.auto, + delimiter=args.delimiter) diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/lib/display.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/lib/display.py new file mode 100644 index 0000000000000000000000000000000000000000..f39f389f98b208ee990f898a70d827a9319c6c92 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/lib/display.py @@ -0,0 +1,677 @@ +"""Various display related classes. + +Authors : MinRK, gregcaporaso, dannystaple +""" +from html import escape as html_escape +from os.path import exists, isfile, splitext, abspath, join, isdir +from os import walk, sep, fsdecode + +from IPython.core.display import DisplayObject, TextDisplayObject + +from typing import Tuple, Iterable, Optional + +__all__ = ['Audio', 'IFrame', 'YouTubeVideo', 'VimeoVideo', 'ScribdDocument', + 'FileLink', 'FileLinks', 'Code'] + + +class Audio(DisplayObject): + """Create an audio object. + + When this object is returned by an input cell or passed to the + display function, it will result in Audio controls being displayed + in the frontend (only works in the notebook). + + Parameters + ---------- + data : numpy array, list, unicode, str or bytes + Can be one of + + * Numpy 1d array containing the desired waveform (mono) + * Numpy 2d array containing waveforms for each channel. + Shape=(NCHAN, NSAMPLES). For the standard channel order, see + http://msdn.microsoft.com/en-us/library/windows/hardware/dn653308(v=vs.85).aspx + * List of float or integer representing the waveform (mono) + * String containing the filename + * Bytestring containing raw PCM data or + * URL pointing to a file on the web. + + If the array option is used, the waveform will be normalized. + + If a filename or url is used, the format support will be browser + dependent. + url : unicode + A URL to download the data from. + filename : unicode + Path to a local file to load the data from. + embed : boolean + Should the audio data be embedded using a data URI (True) or should + the original source be referenced. Set this to True if you want the + audio to playable later with no internet connection in the notebook. + + Default is `True`, unless the keyword argument `url` is set, then + default value is `False`. + rate : integer + The sampling rate of the raw data. + Only required when data parameter is being used as an array + autoplay : bool + Set to True if the audio should immediately start playing. + Default is `False`. + normalize : bool + Whether audio should be normalized (rescaled) to the maximum possible + range. Default is `True`. When set to `False`, `data` must be between + -1 and 1 (inclusive), otherwise an error is raised. + Applies only when `data` is a list or array of samples; other types of + audio are never normalized. + + Examples + -------- + + >>> import pytest + >>> np = pytest.importorskip("numpy") + + Generate a sound + + >>> import numpy as np + >>> framerate = 44100 + >>> t = np.linspace(0,5,framerate*5) + >>> data = np.sin(2*np.pi*220*t) + np.sin(2*np.pi*224*t) + >>> Audio(data, rate=framerate) + + + Can also do stereo or more channels + + >>> dataleft = np.sin(2*np.pi*220*t) + >>> dataright = np.sin(2*np.pi*224*t) + >>> Audio([dataleft, dataright], rate=framerate) + + + From URL: + + >>> Audio("http://www.nch.com.au/acm/8k16bitpcm.wav") # doctest: +SKIP + >>> Audio(url="http://www.w3schools.com/html/horse.ogg") # doctest: +SKIP + + From a File: + + >>> Audio('IPython/lib/tests/test.wav') # doctest: +SKIP + >>> Audio(filename='IPython/lib/tests/test.wav') # doctest: +SKIP + + From Bytes: + + >>> Audio(b'RAW_WAV_DATA..') # doctest: +SKIP + >>> Audio(data=b'RAW_WAV_DATA..') # doctest: +SKIP + + See Also + -------- + ipywidgets.Audio + + Audio widget with more more flexibility and options. + + """ + _read_flags = 'rb' + + def __init__(self, data=None, filename=None, url=None, embed=None, rate=None, autoplay=False, normalize=True, *, + element_id=None): + if filename is None and url is None and data is None: + raise ValueError("No audio data found. Expecting filename, url, or data.") + if embed is False and url is None: + raise ValueError("No url found. Expecting url when embed=False") + + if url is not None and embed is not True: + self.embed = False + else: + self.embed = True + self.autoplay = autoplay + self.element_id = element_id + super(Audio, self).__init__(data=data, url=url, filename=filename) + + if self.data is not None and not isinstance(self.data, bytes): + if rate is None: + raise ValueError("rate must be specified when data is a numpy array or list of audio samples.") + self.data = Audio._make_wav(data, rate, normalize) + + def reload(self): + """Reload the raw data from file or URL.""" + import mimetypes + if self.embed: + super(Audio, self).reload() + + if self.filename is not None: + self.mimetype = mimetypes.guess_type(self.filename)[0] + elif self.url is not None: + self.mimetype = mimetypes.guess_type(self.url)[0] + else: + self.mimetype = "audio/wav" + + @staticmethod + def _make_wav(data, rate, normalize): + """ Transform a numpy array to a PCM bytestring """ + from io import BytesIO + import wave + + try: + scaled, nchan = Audio._validate_and_normalize_with_numpy(data, normalize) + except ImportError: + scaled, nchan = Audio._validate_and_normalize_without_numpy(data, normalize) + + fp = BytesIO() + waveobj = wave.open(fp,mode='wb') + waveobj.setnchannels(nchan) + waveobj.setframerate(rate) + waveobj.setsampwidth(2) + waveobj.setcomptype('NONE','NONE') + waveobj.writeframes(scaled) + val = fp.getvalue() + waveobj.close() + + return val + + @staticmethod + def _validate_and_normalize_with_numpy(data, normalize) -> Tuple[bytes, int]: + import numpy as np + + data = np.array(data, dtype=float) + if len(data.shape) == 1: + nchan = 1 + elif len(data.shape) == 2: + # In wave files,channels are interleaved. E.g., + # "L1R1L2R2..." for stereo. See + # http://msdn.microsoft.com/en-us/library/windows/hardware/dn653308(v=vs.85).aspx + # for channel ordering + nchan = data.shape[0] + data = data.T.ravel() + else: + raise ValueError('Array audio input must be a 1D or 2D array') + + max_abs_value = np.max(np.abs(data)) + normalization_factor = Audio._get_normalization_factor(max_abs_value, normalize) + scaled = data / normalization_factor * 32767 + return scaled.astype(" 1: + raise ValueError('Audio data must be between -1 and 1 when normalize=False.') + return max_abs_value if normalize else 1 + + def _data_and_metadata(self): + """shortcut for returning metadata with url information, if defined""" + md = {} + if self.url: + md['url'] = self.url + if md: + return self.data, md + else: + return self.data + + def _repr_html_(self): + src = """ + + """ + return src.format(src=self.src_attr(), type=self.mimetype, autoplay=self.autoplay_attr(), + element_id=self.element_id_attr()) + + def src_attr(self): + import base64 + if self.embed and (self.data is not None): + data = base64=base64.b64encode(self.data).decode('ascii') + return """data:{type};base64,{base64}""".format(type=self.mimetype, + base64=data) + elif self.url is not None: + return self.url + else: + return "" + + def autoplay_attr(self): + if(self.autoplay): + return 'autoplay="autoplay"' + else: + return '' + + def element_id_attr(self): + if (self.element_id): + return 'id="{element_id}"'.format(element_id=self.element_id) + else: + return '' + +class IFrame(object): + """ + Generic class to embed an iframe in an IPython notebook + """ + + iframe = """ + + """ + + def __init__( + self, src, width, height, extras: Optional[Iterable[str]] = None, **kwargs + ): + if extras is None: + extras = [] + + self.src = src + self.width = width + self.height = height + self.extras = extras + self.params = kwargs + + def _repr_html_(self): + """return the embed iframe""" + if self.params: + from urllib.parse import urlencode + params = "?" + urlencode(self.params) + else: + params = "" + return self.iframe.format( + src=self.src, + width=self.width, + height=self.height, + params=params, + extras=" ".join(self.extras), + ) + + +class YouTubeVideo(IFrame): + """Class for embedding a YouTube Video in an IPython session, based on its video id. + + e.g. to embed the video from https://www.youtube.com/watch?v=foo , you would + do:: + + vid = YouTubeVideo("foo") + display(vid) + + To start from 30 seconds:: + + vid = YouTubeVideo("abc", start=30) + display(vid) + + To calculate seconds from time as hours, minutes, seconds use + :class:`datetime.timedelta`:: + + start=int(timedelta(hours=1, minutes=46, seconds=40).total_seconds()) + + Other parameters can be provided as documented at + https://developers.google.com/youtube/player_parameters#Parameters + + When converting the notebook using nbconvert, a jpeg representation of the video + will be inserted in the document. + """ + + def __init__(self, id, width=400, height=300, allow_autoplay=False, **kwargs): + self.id=id + src = "https://www.youtube.com/embed/{0}".format(id) + if allow_autoplay: + extras = list(kwargs.get("extras", [])) + ['allow="autoplay"'] + kwargs.update(autoplay=1, extras=extras) + super(YouTubeVideo, self).__init__(src, width, height, **kwargs) + + def _repr_jpeg_(self): + # Deferred import + from urllib.request import urlopen + + try: + return urlopen("https://img.youtube.com/vi/{id}/hqdefault.jpg".format(id=self.id)).read() + except IOError: + return None + +class VimeoVideo(IFrame): + """ + Class for embedding a Vimeo video in an IPython session, based on its video id. + """ + + def __init__(self, id, width=400, height=300, **kwargs): + src="https://player.vimeo.com/video/{0}".format(id) + super(VimeoVideo, self).__init__(src, width, height, **kwargs) + +class ScribdDocument(IFrame): + """ + Class for embedding a Scribd document in an IPython session + + Use the start_page params to specify a starting point in the document + Use the view_mode params to specify display type one off scroll | slideshow | book + + e.g to Display Wes' foundational paper about PANDAS in book mode from page 3 + + ScribdDocument(71048089, width=800, height=400, start_page=3, view_mode="book") + """ + + def __init__(self, id, width=400, height=300, **kwargs): + src="https://www.scribd.com/embeds/{0}/content".format(id) + super(ScribdDocument, self).__init__(src, width, height, **kwargs) + +class FileLink(object): + """Class for embedding a local file link in an IPython session, based on path + + e.g. to embed a link that was generated in the IPython notebook as my/data.txt + + you would do:: + + local_file = FileLink("my/data.txt") + display(local_file) + + or in the HTML notebook, just:: + + FileLink("my/data.txt") + """ + + html_link_str = "%s" + + def __init__(self, + path, + url_prefix='', + result_html_prefix='', + result_html_suffix='
'): + """ + Parameters + ---------- + path : str + path to the file or directory that should be formatted + url_prefix : str + prefix to be prepended to all files to form a working link [default: + ''] + result_html_prefix : str + text to append to beginning to link [default: ''] + result_html_suffix : str + text to append at the end of link [default: '
'] + """ + if isdir(path): + raise ValueError("Cannot display a directory using FileLink. " + "Use FileLinks to display '%s'." % path) + self.path = fsdecode(path) + self.url_prefix = url_prefix + self.result_html_prefix = result_html_prefix + self.result_html_suffix = result_html_suffix + + def _format_path(self): + fp = ''.join([self.url_prefix, html_escape(self.path)]) + return ''.join([self.result_html_prefix, + self.html_link_str % \ + (fp, html_escape(self.path, quote=False)), + self.result_html_suffix]) + + def _repr_html_(self): + """return html link to file + """ + if not exists(self.path): + return ("Path (%s) doesn't exist. " + "It may still be in the process of " + "being generated, or you may have the " + "incorrect path." % self.path) + + return self._format_path() + + def __repr__(self): + """return absolute path to file + """ + return abspath(self.path) + +class FileLinks(FileLink): + """Class for embedding local file links in an IPython session, based on path + + e.g. to embed links to files that were generated in the IPython notebook + under ``my/data``, you would do:: + + local_files = FileLinks("my/data") + display(local_files) + + or in the HTML notebook, just:: + + FileLinks("my/data") + """ + def __init__(self, + path, + url_prefix='', + included_suffixes=None, + result_html_prefix='', + result_html_suffix='
', + notebook_display_formatter=None, + terminal_display_formatter=None, + recursive=True): + """ + See :class:`FileLink` for the ``path``, ``url_prefix``, + ``result_html_prefix`` and ``result_html_suffix`` parameters. + + included_suffixes : list + Filename suffixes to include when formatting output [default: include + all files] + + notebook_display_formatter : function + Used to format links for display in the notebook. See discussion of + formatter functions below. + + terminal_display_formatter : function + Used to format links for display in the terminal. See discussion of + formatter functions below. + + Formatter functions must be of the form:: + + f(dirname, fnames, included_suffixes) + + dirname : str + The name of a directory + fnames : list + The files in that directory + included_suffixes : list + The file suffixes that should be included in the output (passing None + meansto include all suffixes in the output in the built-in formatters) + recursive : boolean + Whether to recurse into subdirectories. Default is True. + + The function should return a list of lines that will be printed in the + notebook (if passing notebook_display_formatter) or the terminal (if + passing terminal_display_formatter). This function is iterated over for + each directory in self.path. Default formatters are in place, can be + passed here to support alternative formatting. + + """ + if isfile(path): + raise ValueError("Cannot display a file using FileLinks. " + "Use FileLink to display '%s'." % path) + self.included_suffixes = included_suffixes + # remove trailing slashes for more consistent output formatting + path = path.rstrip('/') + + self.path = path + self.url_prefix = url_prefix + self.result_html_prefix = result_html_prefix + self.result_html_suffix = result_html_suffix + + self.notebook_display_formatter = \ + notebook_display_formatter or self._get_notebook_display_formatter() + self.terminal_display_formatter = \ + terminal_display_formatter or self._get_terminal_display_formatter() + + self.recursive = recursive + + def _get_display_formatter( + self, dirname_output_format, fname_output_format, fp_format, fp_cleaner=None + ): + """generate built-in formatter function + + this is used to define both the notebook and terminal built-in + formatters as they only differ by some wrapper text for each entry + + dirname_output_format: string to use for formatting directory + names, dirname will be substituted for a single "%s" which + must appear in this string + fname_output_format: string to use for formatting file names, + if a single "%s" appears in the string, fname will be substituted + if two "%s" appear in the string, the path to fname will be + substituted for the first and fname will be substituted for the + second + fp_format: string to use for formatting filepaths, must contain + exactly two "%s" and the dirname will be substituted for the first + and fname will be substituted for the second + """ + def f(dirname, fnames, included_suffixes=None): + result = [] + # begin by figuring out which filenames, if any, + # are going to be displayed + display_fnames = [] + for fname in fnames: + if (isfile(join(dirname,fname)) and + (included_suffixes is None or + splitext(fname)[1] in included_suffixes)): + display_fnames.append(fname) + + if len(display_fnames) == 0: + # if there are no filenames to display, don't print anything + # (not even the directory name) + pass + else: + # otherwise print the formatted directory name followed by + # the formatted filenames + dirname_output_line = dirname_output_format % dirname + result.append(dirname_output_line) + for fname in display_fnames: + fp = fp_format % (dirname,fname) + if fp_cleaner is not None: + fp = fp_cleaner(fp) + try: + # output can include both a filepath and a filename... + fname_output_line = fname_output_format % (fp, fname) + except TypeError: + # ... or just a single filepath + fname_output_line = fname_output_format % fname + result.append(fname_output_line) + return result + return f + + def _get_notebook_display_formatter(self, + spacer="  "): + """ generate function to use for notebook formatting + """ + dirname_output_format = \ + self.result_html_prefix + "%s/" + self.result_html_suffix + fname_output_format = \ + self.result_html_prefix + spacer + self.html_link_str + self.result_html_suffix + fp_format = self.url_prefix + '%s/%s' + if sep == "\\": + # Working on a platform where the path separator is "\", so + # must convert these to "/" for generating a URI + def fp_cleaner(fp): + # Replace all occurrences of backslash ("\") with a forward + # slash ("/") - this is necessary on windows when a path is + # provided as input, but we must link to a URI + return fp.replace('\\','/') + else: + fp_cleaner = None + + return self._get_display_formatter(dirname_output_format, + fname_output_format, + fp_format, + fp_cleaner) + + def _get_terminal_display_formatter(self, + spacer=" "): + """ generate function to use for terminal formatting + """ + dirname_output_format = "%s/" + fname_output_format = spacer + "%s" + fp_format = '%s/%s' + + return self._get_display_formatter(dirname_output_format, + fname_output_format, + fp_format) + + def _format_path(self): + result_lines = [] + if self.recursive: + walked_dir = list(walk(self.path)) + else: + walked_dir = [next(walk(self.path))] + walked_dir.sort() + for dirname, subdirs, fnames in walked_dir: + result_lines += self.notebook_display_formatter(dirname, fnames, self.included_suffixes) + return '\n'.join(result_lines) + + def __repr__(self): + """return newline-separated absolute paths + """ + result_lines = [] + if self.recursive: + walked_dir = list(walk(self.path)) + else: + walked_dir = [next(walk(self.path))] + walked_dir.sort() + for dirname, subdirs, fnames in walked_dir: + result_lines += self.terminal_display_formatter(dirname, fnames, self.included_suffixes) + return '\n'.join(result_lines) + + +class Code(TextDisplayObject): + """Display syntax-highlighted source code. + + This uses Pygments to highlight the code for HTML and Latex output. + + Parameters + ---------- + data : str + The code as a string + url : str + A URL to fetch the code from + filename : str + A local filename to load the code from + language : str + The short name of a Pygments lexer to use for highlighting. + If not specified, it will guess the lexer based on the filename + or the code. Available lexers: http://pygments.org/docs/lexers/ + """ + def __init__(self, data=None, url=None, filename=None, language=None): + self.language = language + super().__init__(data=data, url=url, filename=filename) + + def _get_lexer(self): + if self.language: + from pygments.lexers import get_lexer_by_name + return get_lexer_by_name(self.language) + elif self.filename: + from pygments.lexers import get_lexer_for_filename + return get_lexer_for_filename(self.filename) + else: + from pygments.lexers import guess_lexer + return guess_lexer(self.data) + + def __repr__(self): + return self.data + + def _repr_html_(self): + from pygments import highlight + from pygments.formatters import HtmlFormatter + fmt = HtmlFormatter() + style = ''.format(fmt.get_style_defs('.output_html')) + return style + highlight(self.data, self._get_lexer(), fmt) + + def _repr_latex_(self): + from pygments import highlight + from pygments.formatters import LatexFormatter + return highlight(self.data, self._get_lexer(), LatexFormatter()) diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/lib/pretty.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/lib/pretty.py new file mode 100644 index 0000000000000000000000000000000000000000..a232e4edf6ff64f4fc51eecdeaa757cf37e34f2f --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/lib/pretty.py @@ -0,0 +1,961 @@ +""" +Python advanced pretty printer. This pretty printer is intended to +replace the old `pprint` python module which does not allow developers +to provide their own pretty print callbacks. + +This module is based on ruby's `prettyprint.rb` library by `Tanaka Akira`. + + +Example Usage +------------- + +To directly print the representation of an object use `pprint`:: + + from pretty import pprint + pprint(complex_object) + +To get a string of the output use `pretty`:: + + from pretty import pretty + string = pretty(complex_object) + + +Extending +--------- + +The pretty library allows developers to add pretty printing rules for their +own objects. This process is straightforward. All you have to do is to +add a `_repr_pretty_` method to your object and call the methods on the +pretty printer passed:: + + class MyObject(object): + + def _repr_pretty_(self, p, cycle): + ... + +Here's an example for a class with a simple constructor:: + + class MySimpleObject: + + def __init__(self, a, b, *, c=None): + self.a = a + self.b = b + self.c = c + + def _repr_pretty_(self, p, cycle): + ctor = CallExpression.factory(self.__class__.__name__) + if self.c is None: + p.pretty(ctor(a, b)) + else: + p.pretty(ctor(a, b, c=c)) + +Here is an example implementation of a `_repr_pretty_` method for a list +subclass:: + + class MyList(list): + + def _repr_pretty_(self, p, cycle): + if cycle: + p.text('MyList(...)') + else: + with p.group(8, 'MyList([', '])'): + for idx, item in enumerate(self): + if idx: + p.text(',') + p.breakable() + p.pretty(item) + +The `cycle` parameter is `True` if pretty detected a cycle. You *have* to +react to that or the result is an infinite loop. `p.text()` just adds +non breaking text to the output, `p.breakable()` either adds a whitespace +or breaks here. If you pass it an argument it's used instead of the +default space. `p.pretty` prettyprints another object using the pretty print +method. + +The first parameter to the `group` function specifies the extra indentation +of the next line. In this example the next item will either be on the same +line (if the items are short enough) or aligned with the right edge of the +opening bracket of `MyList`. + +If you just want to indent something you can use the group function +without open / close parameters. You can also use this code:: + + with p.indent(2): + ... + +Inheritance diagram: + +.. inheritance-diagram:: IPython.lib.pretty + :parts: 3 + +:copyright: 2007 by Armin Ronacher. + Portions (c) 2009 by Robert Kern. +:license: BSD License. +""" + +from contextlib import contextmanager +import datetime +import os +import re +import sys +import types +from collections import deque +from inspect import signature +from io import StringIO +from warnings import warn + +from IPython.utils.decorators import undoc +from IPython.utils.py3compat import PYPY + +from typing import Dict + +__all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter', + 'for_type', 'for_type_by_name', 'RawText', 'RawStringLiteral', 'CallExpression'] + + +MAX_SEQ_LENGTH = 1000 +_re_pattern_type = type(re.compile('')) + +def _safe_getattr(obj, attr, default=None): + """Safe version of getattr. + + Same as getattr, but will return ``default`` on any Exception, + rather than raising. + """ + try: + return getattr(obj, attr, default) + except Exception: + return default + +@undoc +class CUnicodeIO(StringIO): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + warn(("CUnicodeIO is deprecated since IPython 6.0. " + "Please use io.StringIO instead."), + DeprecationWarning, stacklevel=2) + +def _sorted_for_pprint(items): + """ + Sort the given items for pretty printing. Since some predictable + sorting is better than no sorting at all, we sort on the string + representation if normal sorting fails. + """ + items = list(items) + try: + return sorted(items) + except Exception: + try: + return sorted(items, key=str) + except Exception: + return items + +def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH): + """ + Pretty print the object's representation. + """ + stream = StringIO() + printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length) + printer.pretty(obj) + printer.flush() + return stream.getvalue() + + +def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH): + """ + Like `pretty` but print to stdout. + """ + printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length) + printer.pretty(obj) + printer.flush() + sys.stdout.write(newline) + sys.stdout.flush() + +class _PrettyPrinterBase(object): + + @contextmanager + def indent(self, indent): + """with statement support for indenting/dedenting.""" + self.indentation += indent + try: + yield + finally: + self.indentation -= indent + + @contextmanager + def group(self, indent=0, open='', close=''): + """like begin_group / end_group but for the with statement.""" + self.begin_group(indent, open) + try: + yield + finally: + self.end_group(indent, close) + +class PrettyPrinter(_PrettyPrinterBase): + """ + Baseclass for the `RepresentationPrinter` prettyprinter that is used to + generate pretty reprs of objects. Contrary to the `RepresentationPrinter` + this printer knows nothing about the default pprinters or the `_repr_pretty_` + callback method. + """ + + def __init__(self, output, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH): + self.output = output + self.max_width = max_width + self.newline = newline + self.max_seq_length = max_seq_length + self.output_width = 0 + self.buffer_width = 0 + self.buffer = deque() + + root_group = Group(0) + self.group_stack = [root_group] + self.group_queue = GroupQueue(root_group) + self.indentation = 0 + + def _break_one_group(self, group): + while group.breakables: + x = self.buffer.popleft() + self.output_width = x.output(self.output, self.output_width) + self.buffer_width -= x.width + while self.buffer and isinstance(self.buffer[0], Text): + x = self.buffer.popleft() + self.output_width = x.output(self.output, self.output_width) + self.buffer_width -= x.width + + def _break_outer_groups(self): + while self.max_width < self.output_width + self.buffer_width: + group = self.group_queue.deq() + if not group: + return + self._break_one_group(group) + + def text(self, obj): + """Add literal text to the output.""" + width = len(obj) + if self.buffer: + text = self.buffer[-1] + if not isinstance(text, Text): + text = Text() + self.buffer.append(text) + text.add(obj, width) + self.buffer_width += width + self._break_outer_groups() + else: + self.output.write(obj) + self.output_width += width + + def breakable(self, sep=' '): + """ + Add a breakable separator to the output. This does not mean that it + will automatically break here. If no breaking on this position takes + place the `sep` is inserted which default to one space. + """ + width = len(sep) + group = self.group_stack[-1] + if group.want_break: + self.flush() + self.output.write(self.newline) + self.output.write(' ' * self.indentation) + self.output_width = self.indentation + self.buffer_width = 0 + else: + self.buffer.append(Breakable(sep, width, self)) + self.buffer_width += width + self._break_outer_groups() + + def break_(self): + """ + Explicitly insert a newline into the output, maintaining correct indentation. + """ + group = self.group_queue.deq() + if group: + self._break_one_group(group) + self.flush() + self.output.write(self.newline) + self.output.write(' ' * self.indentation) + self.output_width = self.indentation + self.buffer_width = 0 + + + def begin_group(self, indent=0, open=''): + """ + Begin a group. + The first parameter specifies the indentation for the next line (usually + the width of the opening text), the second the opening text. All + parameters are optional. + """ + if open: + self.text(open) + group = Group(self.group_stack[-1].depth + 1) + self.group_stack.append(group) + self.group_queue.enq(group) + self.indentation += indent + + def _enumerate(self, seq): + """like enumerate, but with an upper limit on the number of items""" + for idx, x in enumerate(seq): + if self.max_seq_length and idx >= self.max_seq_length: + self.text(',') + self.breakable() + self.text('...') + return + yield idx, x + + def end_group(self, dedent=0, close=''): + """End a group. See `begin_group` for more details.""" + self.indentation -= dedent + group = self.group_stack.pop() + if not group.breakables: + self.group_queue.remove(group) + if close: + self.text(close) + + def flush(self): + """Flush data that is left in the buffer.""" + for data in self.buffer: + self.output_width += data.output(self.output, self.output_width) + self.buffer.clear() + self.buffer_width = 0 + + +def _get_mro(obj_class): + """ Get a reasonable method resolution order of a class and its superclasses + for both old-style and new-style classes. + """ + if not hasattr(obj_class, '__mro__'): + # Old-style class. Mix in object to make a fake new-style class. + try: + obj_class = type(obj_class.__name__, (obj_class, object), {}) + except TypeError: + # Old-style extension type that does not descend from object. + # FIXME: try to construct a more thorough MRO. + mro = [obj_class] + else: + mro = obj_class.__mro__[1:-1] + else: + mro = obj_class.__mro__ + return mro + + +class RepresentationPrinter(PrettyPrinter): + """ + Special pretty printer that has a `pretty` method that calls the pretty + printer for a python object. + + This class stores processing data on `self` so you must *never* use + this class in a threaded environment. Always lock it or reinstanciate + it. + + Instances also have a verbose flag callbacks can access to control their + output. For example the default instance repr prints all attributes and + methods that are not prefixed by an underscore if the printer is in + verbose mode. + """ + + def __init__(self, output, verbose=False, max_width=79, newline='\n', + singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None, + max_seq_length=MAX_SEQ_LENGTH): + + PrettyPrinter.__init__(self, output, max_width, newline, max_seq_length=max_seq_length) + self.verbose = verbose + self.stack = [] + if singleton_pprinters is None: + singleton_pprinters = _singleton_pprinters.copy() + self.singleton_pprinters = singleton_pprinters + if type_pprinters is None: + type_pprinters = _type_pprinters.copy() + self.type_pprinters = type_pprinters + if deferred_pprinters is None: + deferred_pprinters = _deferred_type_pprinters.copy() + self.deferred_pprinters = deferred_pprinters + + def pretty(self, obj): + """Pretty print the given object.""" + obj_id = id(obj) + cycle = obj_id in self.stack + self.stack.append(obj_id) + self.begin_group() + try: + obj_class = _safe_getattr(obj, '__class__', None) or type(obj) + # First try to find registered singleton printers for the type. + try: + printer = self.singleton_pprinters[obj_id] + except (TypeError, KeyError): + pass + else: + return printer(obj, self, cycle) + # Next walk the mro and check for either: + # 1) a registered printer + # 2) a _repr_pretty_ method + for cls in _get_mro(obj_class): + if cls in self.type_pprinters: + # printer registered in self.type_pprinters + return self.type_pprinters[cls](obj, self, cycle) + else: + # deferred printer + printer = self._in_deferred_types(cls) + if printer is not None: + return printer(obj, self, cycle) + else: + # Finally look for special method names. + # Some objects automatically create any requested + # attribute. Try to ignore most of them by checking for + # callability. + if '_repr_pretty_' in cls.__dict__: + meth = cls._repr_pretty_ + if callable(meth): + return meth(obj, self, cycle) + if ( + cls is not object + # check if cls defines __repr__ + and "__repr__" in cls.__dict__ + # check if __repr__ is callable. + # Note: we need to test getattr(cls, '__repr__') + # instead of cls.__dict__['__repr__'] + # in order to work with descriptors like partialmethod, + and callable(_safe_getattr(cls, "__repr__", None)) + ): + return _repr_pprint(obj, self, cycle) + + return _default_pprint(obj, self, cycle) + finally: + self.end_group() + self.stack.pop() + + def _in_deferred_types(self, cls): + """ + Check if the given class is specified in the deferred type registry. + + Returns the printer from the registry if it exists, and None if the + class is not in the registry. Successful matches will be moved to the + regular type registry for future use. + """ + mod = _safe_getattr(cls, '__module__', None) + name = _safe_getattr(cls, '__name__', None) + key = (mod, name) + printer = None + if key in self.deferred_pprinters: + # Move the printer over to the regular registry. + printer = self.deferred_pprinters.pop(key) + self.type_pprinters[cls] = printer + return printer + + +class Printable(object): + + def output(self, stream, output_width): + return output_width + + +class Text(Printable): + + def __init__(self): + self.objs = [] + self.width = 0 + + def output(self, stream, output_width): + for obj in self.objs: + stream.write(obj) + return output_width + self.width + + def add(self, obj, width): + self.objs.append(obj) + self.width += width + + +class Breakable(Printable): + + def __init__(self, seq, width, pretty): + self.obj = seq + self.width = width + self.pretty = pretty + self.indentation = pretty.indentation + self.group = pretty.group_stack[-1] + self.group.breakables.append(self) + + def output(self, stream, output_width): + self.group.breakables.popleft() + if self.group.want_break: + stream.write(self.pretty.newline) + stream.write(' ' * self.indentation) + return self.indentation + if not self.group.breakables: + self.pretty.group_queue.remove(self.group) + stream.write(self.obj) + return output_width + self.width + + +class Group(Printable): + + def __init__(self, depth): + self.depth = depth + self.breakables = deque() + self.want_break = False + + +class GroupQueue(object): + + def __init__(self, *groups): + self.queue = [] + for group in groups: + self.enq(group) + + def enq(self, group): + depth = group.depth + while depth > len(self.queue) - 1: + self.queue.append([]) + self.queue[depth].append(group) + + def deq(self): + for stack in self.queue: + for idx, group in enumerate(reversed(stack)): + if group.breakables: + del stack[idx] + group.want_break = True + return group + for group in stack: + group.want_break = True + del stack[:] + + def remove(self, group): + try: + self.queue[group.depth].remove(group) + except ValueError: + pass + + +class RawText: + """ Object such that ``p.pretty(RawText(value))`` is the same as ``p.text(value)``. + + An example usage of this would be to show a list as binary numbers, using + ``p.pretty([RawText(bin(i)) for i in integers])``. + """ + def __init__(self, value): + self.value = value + + def _repr_pretty_(self, p, cycle): + p.text(self.value) + + +class CallExpression: + """ Object which emits a line-wrapped call expression in the form `__name(*args, **kwargs)` """ + def __init__(__self, __name, *args, **kwargs): + # dunders are to avoid clashes with kwargs, as python's name managing + # will kick in. + self = __self + self.name = __name + self.args = args + self.kwargs = kwargs + + @classmethod + def factory(cls, name): + def inner(*args, **kwargs): + return cls(name, *args, **kwargs) + return inner + + def _repr_pretty_(self, p, cycle): + # dunders are to avoid clashes with kwargs, as python's name managing + # will kick in. + + started = False + def new_item(): + nonlocal started + if started: + p.text(",") + p.breakable() + started = True + + prefix = self.name + "(" + with p.group(len(prefix), prefix, ")"): + for arg in self.args: + new_item() + p.pretty(arg) + for arg_name, arg in self.kwargs.items(): + new_item() + arg_prefix = arg_name + "=" + with p.group(len(arg_prefix), arg_prefix): + p.pretty(arg) + + +class RawStringLiteral: + """ Wrapper that shows a string with a `r` prefix """ + def __init__(self, value): + self.value = value + + def _repr_pretty_(self, p, cycle): + base_repr = repr(self.value) + if base_repr[:1] in 'uU': + base_repr = base_repr[1:] + prefix = 'ur' + else: + prefix = 'r' + base_repr = prefix + base_repr.replace('\\\\', '\\') + p.text(base_repr) + + +def _default_pprint(obj, p, cycle): + """ + The default print function. Used if an object does not provide one and + it's none of the builtin objects. + """ + klass = _safe_getattr(obj, '__class__', None) or type(obj) + if _safe_getattr(klass, '__repr__', None) is not object.__repr__: + # A user-provided repr. Find newlines and replace them with p.break_() + _repr_pprint(obj, p, cycle) + return + p.begin_group(1, '<') + p.pretty(klass) + p.text(' at 0x%x' % id(obj)) + if cycle: + p.text(' ...') + elif p.verbose: + first = True + for key in dir(obj): + if not key.startswith('_'): + try: + value = getattr(obj, key) + except AttributeError: + continue + if isinstance(value, types.MethodType): + continue + if not first: + p.text(',') + p.breakable() + p.text(key) + p.text('=') + step = len(key) + 1 + p.indentation += step + p.pretty(value) + p.indentation -= step + first = False + p.end_group(1, '>') + + +def _seq_pprinter_factory(start, end): + """ + Factory that returns a pprint function useful for sequences. Used by + the default pprint for tuples and lists. + """ + def inner(obj, p, cycle): + if cycle: + return p.text(start + '...' + end) + step = len(start) + p.begin_group(step, start) + for idx, x in p._enumerate(obj): + if idx: + p.text(',') + p.breakable() + p.pretty(x) + if len(obj) == 1 and isinstance(obj, tuple): + # Special case for 1-item tuples. + p.text(',') + p.end_group(step, end) + return inner + + +def _set_pprinter_factory(start, end): + """ + Factory that returns a pprint function useful for sets and frozensets. + """ + def inner(obj, p, cycle): + if cycle: + return p.text(start + '...' + end) + if len(obj) == 0: + # Special case. + p.text(type(obj).__name__ + '()') + else: + step = len(start) + p.begin_group(step, start) + # Like dictionary keys, we will try to sort the items if there aren't too many + if not (p.max_seq_length and len(obj) >= p.max_seq_length): + items = _sorted_for_pprint(obj) + else: + items = obj + for idx, x in p._enumerate(items): + if idx: + p.text(',') + p.breakable() + p.pretty(x) + p.end_group(step, end) + return inner + + +def _dict_pprinter_factory(start, end): + """ + Factory that returns a pprint function used by the default pprint of + dicts and dict proxies. + """ + def inner(obj, p, cycle): + if cycle: + return p.text('{...}') + step = len(start) + p.begin_group(step, start) + keys = obj.keys() + for idx, key in p._enumerate(keys): + if idx: + p.text(',') + p.breakable() + p.pretty(key) + p.text(': ') + p.pretty(obj[key]) + p.end_group(step, end) + return inner + + +def _super_pprint(obj, p, cycle): + """The pprint for the super type.""" + p.begin_group(8, '') + + + +class _ReFlags: + def __init__(self, value): + self.value = value + + def _repr_pretty_(self, p, cycle): + done_one = False + for flag in ( + "IGNORECASE", + "LOCALE", + "MULTILINE", + "DOTALL", + "UNICODE", + "VERBOSE", + "DEBUG", + ): + if self.value & getattr(re, flag): + if done_one: + p.text('|') + p.text('re.' + flag) + done_one = True + + +def _re_pattern_pprint(obj, p, cycle): + """The pprint function for regular expression patterns.""" + re_compile = CallExpression.factory('re.compile') + if obj.flags: + p.pretty(re_compile(RawStringLiteral(obj.pattern), _ReFlags(obj.flags))) + else: + p.pretty(re_compile(RawStringLiteral(obj.pattern))) + + +def _types_simplenamespace_pprint(obj, p, cycle): + """The pprint function for types.SimpleNamespace.""" + namespace = CallExpression.factory('namespace') + if cycle: + p.pretty(namespace(RawText("..."))) + else: + p.pretty(namespace(**obj.__dict__)) + + +def _type_pprint(obj, p, cycle): + """The pprint for classes and types.""" + # Heap allocated types might not have the module attribute, + # and others may set it to None. + + # Checks for a __repr__ override in the metaclass. Can't compare the + # type(obj).__repr__ directly because in PyPy the representation function + # inherited from type isn't the same type.__repr__ + if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]: + _repr_pprint(obj, p, cycle) + return + + mod = _safe_getattr(obj, '__module__', None) + try: + name = obj.__qualname__ + if not isinstance(name, str): + # This can happen if the type implements __qualname__ as a property + # or other descriptor in Python 2. + raise Exception("Try __name__") + except Exception: + name = obj.__name__ + if not isinstance(name, str): + name = '' + + if mod in (None, '__builtin__', 'builtins', 'exceptions'): + p.text(name) + else: + p.text(mod + '.' + name) + + +def _repr_pprint(obj, p, cycle): + """A pprint that just redirects to the normal repr function.""" + # Find newlines and replace them with p.break_() + output = repr(obj) + lines = output.splitlines() + with p.group(): + for idx, output_line in enumerate(lines): + if idx: + p.break_() + p.text(output_line) + + +def _function_pprint(obj, p, cycle): + """Base pprint for all functions and builtin functions.""" + name = _safe_getattr(obj, '__qualname__', obj.__name__) + mod = obj.__module__ + if mod and mod not in ('__builtin__', 'builtins', 'exceptions'): + name = mod + '.' + name + try: + func_def = name + str(signature(obj)) + except ValueError: + func_def = name + p.text('' % func_def) + + +def _exception_pprint(obj, p, cycle): + """Base pprint for all exceptions.""" + name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__) + if obj.__class__.__module__ not in ('exceptions', 'builtins'): + name = '%s.%s' % (obj.__class__.__module__, name) + + p.pretty(CallExpression(name, *getattr(obj, 'args', ()))) + + +#: the exception base +_exception_base: type +try: + _exception_base = BaseException +except NameError: + _exception_base = Exception + + +#: printers for builtin types +_type_pprinters = { + int: _repr_pprint, + float: _repr_pprint, + str: _repr_pprint, + tuple: _seq_pprinter_factory('(', ')'), + list: _seq_pprinter_factory('[', ']'), + dict: _dict_pprinter_factory('{', '}'), + set: _set_pprinter_factory('{', '}'), + frozenset: _set_pprinter_factory('frozenset({', '})'), + super: _super_pprint, + _re_pattern_type: _re_pattern_pprint, + type: _type_pprint, + types.FunctionType: _function_pprint, + types.BuiltinFunctionType: _function_pprint, + types.MethodType: _repr_pprint, + types.SimpleNamespace: _types_simplenamespace_pprint, + datetime.datetime: _repr_pprint, + datetime.timedelta: _repr_pprint, + _exception_base: _exception_pprint +} + +# render os.environ like a dict +_env_type = type(os.environ) +# future-proof in case os.environ becomes a plain dict? +if _env_type is not dict: + _type_pprinters[_env_type] = _dict_pprinter_factory('environ{', '}') + +_type_pprinters[types.MappingProxyType] = _dict_pprinter_factory("mappingproxy({", "})") +_type_pprinters[slice] = _repr_pprint + +_type_pprinters[range] = _repr_pprint +_type_pprinters[bytes] = _repr_pprint + +#: printers for types specified by name +_deferred_type_pprinters: Dict = {} + + +def for_type(typ, func): + """ + Add a pretty printer for a given type. + """ + oldfunc = _type_pprinters.get(typ, None) + if func is not None: + # To support easy restoration of old pprinters, we need to ignore Nones. + _type_pprinters[typ] = func + return oldfunc + +def for_type_by_name(type_module, type_name, func): + """ + Add a pretty printer for a type specified by the module and name of a type + rather than the type object itself. + """ + key = (type_module, type_name) + oldfunc = _deferred_type_pprinters.get(key, None) + if func is not None: + # To support easy restoration of old pprinters, we need to ignore Nones. + _deferred_type_pprinters[key] = func + return oldfunc + + +#: printers for the default singletons +_singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis, + NotImplemented]), _repr_pprint) + + +def _defaultdict_pprint(obj, p, cycle): + cls_ctor = CallExpression.factory(obj.__class__.__name__) + if cycle: + p.pretty(cls_ctor(RawText("..."))) + else: + p.pretty(cls_ctor(obj.default_factory, dict(obj))) + +def _ordereddict_pprint(obj, p, cycle): + cls_ctor = CallExpression.factory(obj.__class__.__name__) + if cycle: + p.pretty(cls_ctor(RawText("..."))) + elif len(obj): + p.pretty(cls_ctor(list(obj.items()))) + else: + p.pretty(cls_ctor()) + +def _deque_pprint(obj, p, cycle): + cls_ctor = CallExpression.factory(obj.__class__.__name__) + if cycle: + p.pretty(cls_ctor(RawText("..."))) + elif obj.maxlen is not None: + p.pretty(cls_ctor(list(obj), maxlen=obj.maxlen)) + else: + p.pretty(cls_ctor(list(obj))) + +def _counter_pprint(obj, p, cycle): + cls_ctor = CallExpression.factory(obj.__class__.__name__) + if cycle: + p.pretty(cls_ctor(RawText("..."))) + elif len(obj): + p.pretty(cls_ctor(dict(obj.most_common()))) + else: + p.pretty(cls_ctor()) + + +def _userlist_pprint(obj, p, cycle): + cls_ctor = CallExpression.factory(obj.__class__.__name__) + if cycle: + p.pretty(cls_ctor(RawText("..."))) + else: + p.pretty(cls_ctor(obj.data)) + + +for_type_by_name('collections', 'defaultdict', _defaultdict_pprint) +for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint) +for_type_by_name('collections', 'deque', _deque_pprint) +for_type_by_name('collections', 'Counter', _counter_pprint) +for_type_by_name("collections", "UserList", _userlist_pprint) + +if __name__ == '__main__': + from random import randrange + class Foo(object): + def __init__(self): + self.foo = 1 + self.bar = re.compile(r'\s+') + self.blub = dict.fromkeys(range(30), randrange(1, 40)) + self.hehe = 23424.234234 + self.list = ["blub", "blah", self] + + def get_foo(self): + print("foo") + + pprint(Foo(), verbose=True) diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/__init__.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/console.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/console.py new file mode 100644 index 0000000000000000000000000000000000000000..65571a7572df6b372e8971d95367392801149151 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/console.py @@ -0,0 +1,19 @@ +""" +Shim to maintain backwards compatibility with old IPython.terminal.console imports. +""" +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. + +import sys +from warnings import warn + +from IPython.utils.shimmodule import ShimModule, ShimWarning + +warn("The `IPython.terminal.console` package has been deprecated since IPython 4.0. " + "You should import from jupyter_console instead.", ShimWarning) + +# Unconditionally insert the shim into sys.modules so that further import calls +# trigger the custom attribute access above + +sys.modules['IPython.terminal.console'] = ShimModule( + src='IPython.terminal.console', mirror='jupyter_console') diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/debugger.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/debugger.py new file mode 100644 index 0000000000000000000000000000000000000000..19ed3c7f6048489d28bb68e5850def65c81729d5 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/debugger.py @@ -0,0 +1,187 @@ +import asyncio +import os +import sys + +from IPython.core.debugger import Pdb +from IPython.core.completer import IPCompleter +from .ptutils import IPythonPTCompleter +from .shortcuts import create_ipython_shortcuts +from . import embed + +from pathlib import Path +from pygments.token import Token +from prompt_toolkit.application import create_app_session +from prompt_toolkit.shortcuts.prompt import PromptSession +from prompt_toolkit.enums import EditingMode +from prompt_toolkit.formatted_text import PygmentsTokens +from prompt_toolkit.history import InMemoryHistory, FileHistory +from concurrent.futures import ThreadPoolExecutor + +from prompt_toolkit import __version__ as ptk_version +PTK3 = ptk_version.startswith('3.') + + +# we want to avoid ptk as much as possible when using subprocesses +# as it uses cursor positioning requests, deletes color .... +_use_simple_prompt = "IPY_TEST_SIMPLE_PROMPT" in os.environ + + +class TerminalPdb(Pdb): + """Standalone IPython debugger.""" + + def __init__(self, *args, pt_session_options=None, **kwargs): + Pdb.__init__(self, *args, **kwargs) + self._ptcomp = None + self.pt_init(pt_session_options) + self.thread_executor = ThreadPoolExecutor(1) + + def pt_init(self, pt_session_options=None): + """Initialize the prompt session and the prompt loop + and store them in self.pt_app and self.pt_loop. + + Additional keyword arguments for the PromptSession class + can be specified in pt_session_options. + """ + if pt_session_options is None: + pt_session_options = {} + + def get_prompt_tokens(): + return [(Token.Prompt, self.prompt)] + + if self._ptcomp is None: + compl = IPCompleter( + shell=self.shell, namespace={}, global_namespace={}, parent=self.shell + ) + # add a completer for all the do_ methods + methods_names = [m[3:] for m in dir(self) if m.startswith("do_")] + + def gen_comp(self, text): + return [m for m in methods_names if m.startswith(text)] + import types + newcomp = types.MethodType(gen_comp, compl) + compl.custom_matchers.insert(0, newcomp) + # end add completer. + + self._ptcomp = IPythonPTCompleter(compl) + + # setup history only when we start pdb + if self.shell.debugger_history is None: + if self.shell.debugger_history_file is not None: + p = Path(self.shell.debugger_history_file).expanduser() + if not p.exists(): + p.touch() + self.debugger_history = FileHistory(os.path.expanduser(str(p))) + else: + self.debugger_history = InMemoryHistory() + else: + self.debugger_history = self.shell.debugger_history + + options = dict( + message=(lambda: PygmentsTokens(get_prompt_tokens())), + editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()), + key_bindings=create_ipython_shortcuts(self.shell), + history=self.debugger_history, + completer=self._ptcomp, + enable_history_search=True, + mouse_support=self.shell.mouse_support, + complete_style=self.shell.pt_complete_style, + style=getattr(self.shell, "style", None), + color_depth=self.shell.color_depth, + ) + + if not PTK3: + options['inputhook'] = self.shell.inputhook + options.update(pt_session_options) + if not _use_simple_prompt: + self.pt_loop = asyncio.new_event_loop() + self.pt_app = PromptSession(**options) + + def _prompt(self): + """ + In case other prompt_toolkit apps have to run in parallel to this one (e.g. in madbg), + create_app_session must be used to prevent mixing up between them. According to the prompt_toolkit docs: + + > If you need multiple applications running at the same time, you have to create a separate + > `AppSession` using a `with create_app_session():` block. + """ + with create_app_session(): + return self.pt_app.prompt() + + def cmdloop(self, intro=None): + """Repeatedly issue a prompt, accept input, parse an initial prefix + off the received input, and dispatch to action methods, passing them + the remainder of the line as argument. + + override the same methods from cmd.Cmd to provide prompt toolkit replacement. + """ + if not self.use_rawinput: + raise ValueError('Sorry ipdb does not support use_rawinput=False') + + # In order to make sure that prompt, which uses asyncio doesn't + # interfere with applications in which it's used, we always run the + # prompt itself in a different thread (we can't start an event loop + # within an event loop). This new thread won't have any event loop + # running, and here we run our prompt-loop. + self.preloop() + + try: + if intro is not None: + self.intro = intro + if self.intro: + print(self.intro, file=self.stdout) + stop = None + while not stop: + if self.cmdqueue: + line = self.cmdqueue.pop(0) + else: + self._ptcomp.ipy_completer.namespace = self.curframe_locals + self._ptcomp.ipy_completer.global_namespace = self.curframe.f_globals + + # Run the prompt in a different thread. + if not _use_simple_prompt: + try: + line = self.thread_executor.submit(self._prompt).result() + except EOFError: + line = "EOF" + else: + line = input("ipdb> ") + + line = self.precmd(line) + stop = self.onecmd(line) + stop = self.postcmd(stop, line) + self.postloop() + except Exception: + raise + + def do_interact(self, arg): + ipshell = embed.InteractiveShellEmbed( + config=self.shell.config, + banner1="*interactive*", + exit_msg="*exiting interactive console...*", + ) + global_ns = self.curframe.f_globals + ipshell( + module=sys.modules.get(global_ns["__name__"], None), + local_ns=self.curframe_locals, + ) + + +def set_trace(frame=None): + """ + Start debugging from `frame`. + + If frame is not specified, debugging starts from caller's frame. + """ + TerminalPdb().set_trace(frame or sys._getframe().f_back) + + +if __name__ == '__main__': + import pdb + # IPython.core.debugger.Pdb.trace_dispatch shall not catch + # bdb.BdbQuit. When started through __main__ and an exception + # happened after hitting "c", this is needed in order to + # be able to quit the debugging session (see #9950). + old_trace_dispatch = pdb.Pdb.trace_dispatch + pdb.Pdb = TerminalPdb # type: ignore + pdb.Pdb.trace_dispatch = old_trace_dispatch # type: ignore + pdb.main() diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/embed.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/embed.py new file mode 100644 index 0000000000000000000000000000000000000000..d46fa7441f270e9ed3331f58cdcdd3d8380e4346 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/embed.py @@ -0,0 +1,426 @@ +# encoding: utf-8 +""" +An embedded IPython shell. +""" +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. + + +import sys +import warnings + +from IPython.core import ultratb, compilerop +from IPython.core import magic_arguments +from IPython.core.magic import Magics, magics_class, line_magic +from IPython.core.interactiveshell import DummyMod, InteractiveShell +from IPython.terminal.interactiveshell import TerminalInteractiveShell +from IPython.terminal.ipapp import load_default_config + +from traitlets import Bool, CBool, Unicode +from IPython.utils.io import ask_yes_no + +from typing import Set + +class KillEmbedded(Exception):pass + +# kept for backward compatibility as IPython 6 was released with +# the typo. See https://github.com/ipython/ipython/pull/10706 +KillEmbeded = KillEmbedded + +# This is an additional magic that is exposed in embedded shells. +@magics_class +class EmbeddedMagics(Magics): + + @line_magic + @magic_arguments.magic_arguments() + @magic_arguments.argument('-i', '--instance', action='store_true', + help='Kill instance instead of call location') + @magic_arguments.argument('-x', '--exit', action='store_true', + help='Also exit the current session') + @magic_arguments.argument('-y', '--yes', action='store_true', + help='Do not ask confirmation') + def kill_embedded(self, parameter_s=''): + """%kill_embedded : deactivate for good the current embedded IPython + + This function (after asking for confirmation) sets an internal flag so + that an embedded IPython will never activate again for the given call + location. This is useful to permanently disable a shell that is being + called inside a loop: once you've figured out what you needed from it, + you may then kill it and the program will then continue to run without + the interactive shell interfering again. + + Kill Instance Option: + + If for some reasons you need to kill the location where the instance + is created and not called, for example if you create a single + instance in one place and debug in many locations, you can use the + ``--instance`` option to kill this specific instance. Like for the + ``call location`` killing an "instance" should work even if it is + recreated within a loop. + + .. note:: + + This was the default behavior before IPython 5.2 + + """ + + args = magic_arguments.parse_argstring(self.kill_embedded, parameter_s) + print(args) + if args.instance: + # let no ask + if not args.yes: + kill = ask_yes_no( + "Are you sure you want to kill this embedded instance? [y/N] ", 'n') + else: + kill = True + if kill: + self.shell._disable_init_location() + print("This embedded IPython instance will not reactivate anymore " + "once you exit.") + else: + if not args.yes: + kill = ask_yes_no( + "Are you sure you want to kill this embedded call_location? [y/N] ", 'n') + else: + kill = True + if kill: + self.shell.embedded_active = False + print("This embedded IPython call location will not reactivate anymore " + "once you exit.") + + if args.exit: + # Ask-exit does not really ask, it just set internals flags to exit + # on next loop. + self.shell.ask_exit() + + + @line_magic + def exit_raise(self, parameter_s=''): + """%exit_raise Make the current embedded kernel exit and raise and exception. + + This function sets an internal flag so that an embedded IPython will + raise a `IPython.terminal.embed.KillEmbedded` Exception on exit, and then exit the current I. This is + useful to permanently exit a loop that create IPython embed instance. + """ + + self.shell.should_raise = True + self.shell.ask_exit() + + +class _Sentinel: + def __init__(self, repr): + assert isinstance(repr, str) + self.repr = repr + + def __repr__(self): + return repr + + +class InteractiveShellEmbed(TerminalInteractiveShell): + + dummy_mode = Bool(False) + exit_msg = Unicode('') + embedded = CBool(True) + should_raise = CBool(False) + # Like the base class display_banner is not configurable, but here it + # is True by default. + display_banner = CBool(True) + exit_msg = Unicode() + + # When embedding, by default we don't change the terminal title + term_title = Bool(False, + help="Automatically set the terminal title" + ).tag(config=True) + + _inactive_locations: Set[str] = set() + + def _disable_init_location(self): + """Disable the current Instance creation location""" + InteractiveShellEmbed._inactive_locations.add(self._init_location_id) + + @property + def embedded_active(self): + return (self._call_location_id not in InteractiveShellEmbed._inactive_locations)\ + and (self._init_location_id not in InteractiveShellEmbed._inactive_locations) + + @embedded_active.setter + def embedded_active(self, value): + if value: + InteractiveShellEmbed._inactive_locations.discard( + self._call_location_id) + InteractiveShellEmbed._inactive_locations.discard( + self._init_location_id) + else: + InteractiveShellEmbed._inactive_locations.add( + self._call_location_id) + + def __init__(self, **kw): + assert ( + "user_global_ns" not in kw + ), "Key word argument `user_global_ns` has been replaced by `user_module` since IPython 4.0." + # temporary fix for https://github.com/ipython/ipython/issues/14164 + cls = type(self) + if cls._instance is None: + for subclass in cls._walk_mro(): + subclass._instance = self + cls._instance = self + + clid = kw.pop('_init_location_id', None) + if not clid: + frame = sys._getframe(1) + clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno) + self._init_location_id = clid + + super(InteractiveShellEmbed,self).__init__(**kw) + + # don't use the ipython crash handler so that user exceptions aren't + # trapped + sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors, + mode=self.xmode, + call_pdb=self.pdb) + + def init_sys_modules(self): + """ + Explicitly overwrite :mod:`IPython.core.interactiveshell` to do nothing. + """ + pass + + def init_magics(self): + super(InteractiveShellEmbed, self).init_magics() + self.register_magics(EmbeddedMagics) + + def __call__( + self, + header="", + local_ns=None, + module=None, + dummy=None, + stack_depth=1, + compile_flags=None, + **kw, + ): + """Activate the interactive interpreter. + + __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start + the interpreter shell with the given local and global namespaces, and + optionally print a header string at startup. + + The shell can be globally activated/deactivated using the + dummy_mode attribute. This allows you to turn off a shell used + for debugging globally. + + However, *each* time you call the shell you can override the current + state of dummy_mode with the optional keyword parameter 'dummy'. For + example, if you set dummy mode on with IPShell.dummy_mode = True, you + can still have a specific call work by making it as IPShell(dummy=False). + """ + + # we are called, set the underlying interactiveshell not to exit. + self.keep_running = True + + # If the user has turned it off, go away + clid = kw.pop('_call_location_id', None) + if not clid: + frame = sys._getframe(1) + clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno) + self._call_location_id = clid + + if not self.embedded_active: + return + + # Normal exits from interactive mode set this flag, so the shell can't + # re-enter (it checks this variable at the start of interactive mode). + self.exit_now = False + + # Allow the dummy parameter to override the global __dummy_mode + if dummy or (dummy != 0 and self.dummy_mode): + return + + # self.banner is auto computed + if header: + self.old_banner2 = self.banner2 + self.banner2 = self.banner2 + '\n' + header + '\n' + else: + self.old_banner2 = '' + + if self.display_banner: + self.show_banner() + + # Call the embedding code with a stack depth of 1 so it can skip over + # our call and get the original caller's namespaces. + self.mainloop( + local_ns, module, stack_depth=stack_depth, compile_flags=compile_flags + ) + + self.banner2 = self.old_banner2 + + if self.exit_msg is not None: + print(self.exit_msg) + + if self.should_raise: + raise KillEmbedded('Embedded IPython raising error, as user requested.') + + def mainloop( + self, + local_ns=None, + module=None, + stack_depth=0, + compile_flags=None, + ): + """Embeds IPython into a running python program. + + Parameters + ---------- + local_ns, module + Working local namespace (a dict) and module (a module or similar + object). If given as None, they are automatically taken from the scope + where the shell was called, so that program variables become visible. + stack_depth : int + How many levels in the stack to go to looking for namespaces (when + local_ns or module is None). This allows an intermediate caller to + make sure that this function gets the namespace from the intended + level in the stack. By default (0) it will get its locals and globals + from the immediate caller. + compile_flags + A bit field identifying the __future__ features + that are enabled, as passed to the builtin :func:`compile` function. + If given as None, they are automatically taken from the scope where + the shell was called. + + """ + + # Get locals and globals from caller + if ((local_ns is None or module is None or compile_flags is None) + and self.default_user_namespaces): + call_frame = sys._getframe(stack_depth).f_back + + if local_ns is None: + local_ns = call_frame.f_locals + if module is None: + global_ns = call_frame.f_globals + try: + module = sys.modules[global_ns['__name__']] + except KeyError: + warnings.warn("Failed to get module %s" % \ + global_ns.get('__name__', 'unknown module') + ) + module = DummyMod() + module.__dict__ = global_ns + if compile_flags is None: + compile_flags = (call_frame.f_code.co_flags & + compilerop.PyCF_MASK) + + # Save original namespace and module so we can restore them after + # embedding; otherwise the shell doesn't shut down correctly. + orig_user_module = self.user_module + orig_user_ns = self.user_ns + orig_compile_flags = self.compile.flags + + # Update namespaces and fire up interpreter + + # The global one is easy, we can just throw it in + if module is not None: + self.user_module = module + + # But the user/local one is tricky: ipython needs it to store internal + # data, but we also need the locals. We'll throw our hidden variables + # like _ih and get_ipython() into the local namespace, but delete them + # later. + if local_ns is not None: + reentrant_local_ns = {k: v for (k, v) in local_ns.items() if k not in self.user_ns_hidden.keys()} + self.user_ns = reentrant_local_ns + self.init_user_ns() + + # Compiler flags + if compile_flags is not None: + self.compile.flags = compile_flags + + # make sure the tab-completer has the correct frame information, so it + # actually completes using the frame's locals/globals + self.set_completer_frame() + + with self.builtin_trap, self.display_trap: + self.interact() + + # now, purge out the local namespace of IPython's hidden variables. + if local_ns is not None: + local_ns.update({k: v for (k, v) in self.user_ns.items() if k not in self.user_ns_hidden.keys()}) + + + # Restore original namespace so shell can shut down when we exit. + self.user_module = orig_user_module + self.user_ns = orig_user_ns + self.compile.flags = orig_compile_flags + + +def embed(*, header="", compile_flags=None, **kwargs): + """Call this to embed IPython at the current point in your program. + + The first invocation of this will create a :class:`terminal.embed.InteractiveShellEmbed` + instance and then call it. Consecutive calls just call the already + created instance. + + If you don't want the kernel to initialize the namespace + from the scope of the surrounding function, + and/or you want to load full IPython configuration, + you probably want `IPython.start_ipython()` instead. + + Here is a simple example:: + + from IPython import embed + a = 10 + b = 20 + embed(header='First time') + c = 30 + d = 40 + embed() + + Parameters + ---------- + + header : str + Optional header string to print at startup. + compile_flags + Passed to the `compile_flags` parameter of :py:meth:`terminal.embed.InteractiveShellEmbed.mainloop()`, + which is called when the :class:`terminal.embed.InteractiveShellEmbed` instance is called. + **kwargs : various, optional + Any other kwargs will be passed to the :class:`terminal.embed.InteractiveShellEmbed` constructor. + Full customization can be done by passing a traitlets :class:`Config` in as the + `config` argument (see :ref:`configure_start_ipython` and :ref:`terminal_options`). + """ + config = kwargs.get('config') + if config is None: + config = load_default_config() + config.InteractiveShellEmbed = config.TerminalInteractiveShell + kwargs['config'] = config + using = kwargs.get('using', 'sync') + if using : + kwargs['config'].update({'TerminalInteractiveShell':{'loop_runner':using, 'colors':'NoColor', 'autoawait': using!='sync'}}) + #save ps1/ps2 if defined + ps1 = None + ps2 = None + try: + ps1 = sys.ps1 + ps2 = sys.ps2 + except AttributeError: + pass + #save previous instance + saved_shell_instance = InteractiveShell._instance + if saved_shell_instance is not None: + cls = type(saved_shell_instance) + cls.clear_instance() + frame = sys._getframe(1) + shell = InteractiveShellEmbed.instance(_init_location_id='%s:%s' % ( + frame.f_code.co_filename, frame.f_lineno), **kwargs) + shell(header=header, stack_depth=2, compile_flags=compile_flags, + _call_location_id='%s:%s' % (frame.f_code.co_filename, frame.f_lineno)) + InteractiveShellEmbed.clear_instance() + #restore previous instance + if saved_shell_instance is not None: + cls = type(saved_shell_instance) + cls.clear_instance() + for subclass in cls._walk_mro(): + subclass._instance = saved_shell_instance + if ps1 is not None: + sys.ps1 = ps1 + sys.ps2 = ps2 diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/interactiveshell.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/interactiveshell.py new file mode 100644 index 0000000000000000000000000000000000000000..5c85e44e6260d4159ed4804e0ea9eb48efbb5ccf --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/interactiveshell.py @@ -0,0 +1,1146 @@ +"""IPython terminal interface using prompt_toolkit""" + +import os +import sys +import inspect +from warnings import warn +from typing import Union as UnionType, Optional + +from IPython.core.async_helpers import get_asyncio_loop +from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC +from IPython.utils.py3compat import input +from IPython.utils.terminal import toggle_set_term_title, set_term_title, restore_term_title +from IPython.utils.process import abbrev_cwd +from traitlets import ( + Bool, + Unicode, + Dict, + Integer, + List, + observe, + Instance, + Type, + default, + Enum, + Union, + Any, + validate, + Float, + DottedObjectName, +) +from traitlets.utils.importstring import import_item + + +from prompt_toolkit.auto_suggest import AutoSuggestFromHistory +from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode +from prompt_toolkit.filters import HasFocus, Condition, IsDone +from prompt_toolkit.formatted_text import PygmentsTokens +from prompt_toolkit.history import History +from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor +from prompt_toolkit.output import ColorDepth +from prompt_toolkit.patch_stdout import patch_stdout +from prompt_toolkit.shortcuts import PromptSession, CompleteStyle, print_formatted_text +from prompt_toolkit.styles import DynamicStyle, merge_styles +from prompt_toolkit.styles.pygments import style_from_pygments_cls, style_from_pygments_dict +from prompt_toolkit import __version__ as ptk_version + +from pygments.styles import get_style_by_name +from pygments.style import Style +from pygments.token import Token + +from .debugger import TerminalPdb, Pdb +from .magics import TerminalMagics +from .pt_inputhooks import get_inputhook_name_and_func +from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook +from .ptutils import IPythonPTCompleter, IPythonPTLexer +from .shortcuts import ( + KEY_BINDINGS, + UNASSIGNED_ALLOWED_COMMANDS, + create_ipython_shortcuts, + create_identifier, + RuntimeBinding, + add_binding, +) +from .shortcuts.filters import KEYBINDING_FILTERS, filter_from_string +from .shortcuts.auto_suggest import ( + NavigableAutoSuggestFromHistory, + AppendAutoSuggestionInAnyLine, +) + +PTK3 = ptk_version.startswith('3.') + + +class _NoStyle(Style): + pass + + +_style_overrides_light_bg = { + Token.Prompt: '#ansibrightblue', + Token.PromptNum: '#ansiblue bold', + Token.OutPrompt: '#ansibrightred', + Token.OutPromptNum: '#ansired bold', +} + +_style_overrides_linux = { + Token.Prompt: '#ansibrightgreen', + Token.PromptNum: '#ansigreen bold', + Token.OutPrompt: '#ansibrightred', + Token.OutPromptNum: '#ansired bold', +} + + +def _backward_compat_continuation_prompt_tokens(method, width: int, *, lineno: int): + """ + Sagemath use custom prompt and we broke them in 8.19. + """ + sig = inspect.signature(method) + if "lineno" in inspect.signature(method).parameters or any( + [p.kind == p.VAR_KEYWORD for p in sig.parameters.values()] + ): + return method(width, lineno=lineno) + else: + return method(width) + + +def get_default_editor(): + try: + return os.environ['EDITOR'] + except KeyError: + pass + except UnicodeError: + warn("$EDITOR environment variable is not pure ASCII. Using platform " + "default editor.") + + if os.name == 'posix': + return 'vi' # the only one guaranteed to be there! + else: + return "notepad" # same in Windows! + + +# conservatively check for tty +# overridden streams can result in things like: +# - sys.stdin = None +# - no isatty method +for _name in ('stdin', 'stdout', 'stderr'): + _stream = getattr(sys, _name) + try: + if not _stream or not hasattr(_stream, "isatty") or not _stream.isatty(): + _is_tty = False + break + except ValueError: + # stream is closed + _is_tty = False + break +else: + _is_tty = True + + +_use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty) + +def black_reformat_handler(text_before_cursor): + """ + We do not need to protect against error, + this is taken care at a higher level where any reformat error is ignored. + Indeed we may call reformatting on incomplete code. + """ + import black + + formatted_text = black.format_str(text_before_cursor, mode=black.FileMode()) + if not text_before_cursor.endswith("\n") and formatted_text.endswith("\n"): + formatted_text = formatted_text[:-1] + return formatted_text + + +def yapf_reformat_handler(text_before_cursor): + from yapf.yapflib import file_resources + from yapf.yapflib import yapf_api + + style_config = file_resources.GetDefaultStyleForDir(os.getcwd()) + formatted_text, was_formatted = yapf_api.FormatCode( + text_before_cursor, style_config=style_config + ) + if was_formatted: + if not text_before_cursor.endswith("\n") and formatted_text.endswith("\n"): + formatted_text = formatted_text[:-1] + return formatted_text + else: + return text_before_cursor + + +class PtkHistoryAdapter(History): + """ + Prompt toolkit has it's own way of handling history, Where it assumes it can + Push/pull from history. + + """ + + def __init__(self, shell): + super().__init__() + self.shell = shell + self._refresh() + + def append_string(self, string): + # we rely on sql for that. + self._loaded = False + self._refresh() + + def _refresh(self): + if not self._loaded: + self._loaded_strings = list(self.load_history_strings()) + + def load_history_strings(self): + last_cell = "" + res = [] + for __, ___, cell in self.shell.history_manager.get_tail( + self.shell.history_load_length, include_latest=True + ): + # Ignore blank lines and consecutive duplicates + cell = cell.rstrip() + if cell and (cell != last_cell): + res.append(cell) + last_cell = cell + yield from res[::-1] + + def store_string(self, string: str) -> None: + pass + +class TerminalInteractiveShell(InteractiveShell): + mime_renderers = Dict().tag(config=True) + + space_for_menu = Integer(6, help='Number of line at the bottom of the screen ' + 'to reserve for the tab completion menu, ' + 'search history, ...etc, the height of ' + 'these menus will at most this value. ' + 'Increase it is you prefer long and skinny ' + 'menus, decrease for short and wide.' + ).tag(config=True) + + pt_app: UnionType[PromptSession, None] = None + auto_suggest: UnionType[ + AutoSuggestFromHistory, + NavigableAutoSuggestFromHistory, + None, + ] = None + debugger_history = None + + debugger_history_file = Unicode( + "~/.pdbhistory", help="File in which to store and read history" + ).tag(config=True) + + simple_prompt = Bool(_use_simple_prompt, + help="""Use `raw_input` for the REPL, without completion and prompt colors. + + Useful when controlling IPython as a subprocess, and piping + STDIN/OUT/ERR. Known usage are: IPython's own testing machinery, + and emacs' inferior-python subprocess (assuming you have set + `python-shell-interpreter` to "ipython") available through the + built-in `M-x run-python` and third party packages such as elpy. + + This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT` + environment variable is set, or the current terminal is not a tty. + Thus the Default value reported in --help-all, or config will often + be incorrectly reported. + """, + ).tag(config=True) + + @property + def debugger_cls(self): + return Pdb if self.simple_prompt else TerminalPdb + + confirm_exit = Bool(True, + help=""" + Set to confirm when you try to exit IPython with an EOF (Control-D + in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit', + you can force a direct exit without any confirmation.""", + ).tag(config=True) + + editing_mode = Unicode('emacs', + help="Shortcut style to use at the prompt. 'vi' or 'emacs'.", + ).tag(config=True) + + emacs_bindings_in_vi_insert_mode = Bool( + True, + help="Add shortcuts from 'emacs' insert mode to 'vi' insert mode.", + ).tag(config=True) + + modal_cursor = Bool( + True, + help=""" + Cursor shape changes depending on vi mode: beam in vi insert mode, + block in nav mode, underscore in replace mode.""", + ).tag(config=True) + + ttimeoutlen = Float( + 0.01, + help="""The time in milliseconds that is waited for a key code + to complete.""", + ).tag(config=True) + + timeoutlen = Float( + 0.5, + help="""The time in milliseconds that is waited for a mapped key + sequence to complete.""", + ).tag(config=True) + + autoformatter = Unicode( + None, + help="Autoformatter to reformat Terminal code. Can be `'black'`, `'yapf'` or `None`", + allow_none=True + ).tag(config=True) + + auto_match = Bool( + False, + help=""" + Automatically add/delete closing bracket or quote when opening bracket or quote is entered/deleted. + Brackets: (), [], {} + Quotes: '', \"\" + """, + ).tag(config=True) + + mouse_support = Bool(False, + help="Enable mouse support in the prompt\n(Note: prevents selecting text with the mouse)" + ).tag(config=True) + + # We don't load the list of styles for the help string, because loading + # Pygments plugins takes time and can cause unexpected errors. + highlighting_style = Union([Unicode('legacy'), Type(klass=Style)], + help="""The name or class of a Pygments style to use for syntax + highlighting. To see available styles, run `pygmentize -L styles`.""" + ).tag(config=True) + + @validate('editing_mode') + def _validate_editing_mode(self, proposal): + if proposal['value'].lower() == 'vim': + proposal['value']= 'vi' + elif proposal['value'].lower() == 'default': + proposal['value']= 'emacs' + + if hasattr(EditingMode, proposal['value'].upper()): + return proposal['value'].lower() + + return self.editing_mode + + @observe('editing_mode') + def _editing_mode(self, change): + if self.pt_app: + self.pt_app.editing_mode = getattr(EditingMode, change.new.upper()) + + def _set_formatter(self, formatter): + if formatter is None: + self.reformat_handler = lambda x:x + elif formatter == 'black': + self.reformat_handler = black_reformat_handler + elif formatter == "yapf": + self.reformat_handler = yapf_reformat_handler + else: + raise ValueError + + @observe("autoformatter") + def _autoformatter_changed(self, change): + formatter = change.new + self._set_formatter(formatter) + + @observe('highlighting_style') + @observe('colors') + def _highlighting_style_changed(self, change): + self.refresh_style() + + def refresh_style(self): + self._style = self._make_style_from_name_or_cls(self.highlighting_style) + + highlighting_style_overrides = Dict( + help="Override highlighting format for specific tokens" + ).tag(config=True) + + true_color = Bool(False, + help="""Use 24bit colors instead of 256 colors in prompt highlighting. + If your terminal supports true color, the following command should + print ``TRUECOLOR`` in orange:: + + printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\" + """, + ).tag(config=True) + + editor = Unicode(get_default_editor(), + help="Set the editor used by IPython (default to $EDITOR/vi/notepad)." + ).tag(config=True) + + prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True) + + prompts = Instance(Prompts) + + @default('prompts') + def _prompts_default(self): + return self.prompts_class(self) + +# @observe('prompts') +# def _(self, change): +# self._update_layout() + + @default('displayhook_class') + def _displayhook_class_default(self): + return RichPromptDisplayHook + + term_title = Bool(True, + help="Automatically set the terminal title" + ).tag(config=True) + + term_title_format = Unicode("IPython: {cwd}", + help="Customize the terminal title format. This is a python format string. " + + "Available substitutions are: {cwd}." + ).tag(config=True) + + display_completions = Enum(('column', 'multicolumn','readlinelike'), + help= ( "Options for displaying tab completions, 'column', 'multicolumn', and " + "'readlinelike'. These options are for `prompt_toolkit`, see " + "`prompt_toolkit` documentation for more information." + ), + default_value='multicolumn').tag(config=True) + + highlight_matching_brackets = Bool(True, + help="Highlight matching brackets.", + ).tag(config=True) + + extra_open_editor_shortcuts = Bool(False, + help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. " + "This is in addition to the F2 binding, which is always enabled." + ).tag(config=True) + + handle_return = Any(None, + help="Provide an alternative handler to be called when the user presses " + "Return. This is an advanced option intended for debugging, which " + "may be changed or removed in later releases." + ).tag(config=True) + + enable_history_search = Bool(True, + help="Allows to enable/disable the prompt toolkit history search" + ).tag(config=True) + + autosuggestions_provider = Unicode( + "NavigableAutoSuggestFromHistory", + help="Specifies from which source automatic suggestions are provided. " + "Can be set to ``'NavigableAutoSuggestFromHistory'`` (:kbd:`up` and " + ":kbd:`down` swap suggestions), ``'AutoSuggestFromHistory'``, " + " or ``None`` to disable automatic suggestions. " + "Default is `'NavigableAutoSuggestFromHistory`'.", + allow_none=True, + ).tag(config=True) + _autosuggestions_provider: Any + + llm_constructor_kwargs = Dict( + {}, + help=""" + Extra arguments to pass to `llm_provider_class` constructor. + + This is used to – for example – set the `model_id`""", + ).tag(config=True) + + llm_prefix_from_history = DottedObjectName( + "input_history", + help="""\ + Fully Qualifed name of a function that takes an IPython history manager and + return a prefix to pass the llm provider in addition to the current buffer + text. + + You can use: + + - no_prefix + - input_history + + As default value. `input_history` (default), will use all the input history + of current IPython session + + """, + ).tag(config=True) + _llm_prefix_from_history: Any + + @observe("llm_prefix_from_history") + def _llm_prefix_from_history_changed(self, change): + name = change.new + self._llm_prefix_from_history = name + self._set_autosuggestions() + + llm_provider_class = DottedObjectName( + None, + allow_none=True, + help="""\ + Provisional: + This is a provisinal API in IPython 8.32, before stabilisation + in 9.0, it may change without warnings. + + class to use for the `NavigableAutoSuggestFromHistory` to request + completions from a LLM, this should inherit from + `jupyter_ai_magics:BaseProvider` and implement + `stream_inline_completions` + """, + ).tag(config=True) + _llm_provider_class: Any = None + + @observe("llm_provider_class") + def _llm_provider_class_changed(self, change): + provider_class = change.new + if provider_class is not None: + warn( + "TerminalInteractiveShell.llm_provider_class is a provisional" + " API as of IPython 8.32, and may change without warnings." + ) + self._llm_provider_class = provider_class + self._set_autosuggestions() + + def _set_autosuggestions(self, provider=None): + if provider is None: + provider = self.autosuggestions_provider + # disconnect old handler + if self.auto_suggest and isinstance( + self.auto_suggest, NavigableAutoSuggestFromHistory + ): + self.auto_suggest.disconnect() + if provider is None: + self.auto_suggest = None + elif provider == "AutoSuggestFromHistory": + self.auto_suggest = AutoSuggestFromHistory() + elif provider == "NavigableAutoSuggestFromHistory": + # LLM stuff are all Provisional in 8.32 + if self._llm_provider_class: + llm_provider_constructor = import_item(self._llm_provider_class) + llm_provider = llm_provider_constructor(**self.llm_constructor_kwargs) + else: + llm_provider = None + self.auto_suggest = NavigableAutoSuggestFromHistory() + # Provisinal in 8.32 + self.auto_suggest._llm_provider = llm_provider + + name = self.llm_prefix_from_history + + if name == "no_prefix": + + def no_prefix(history_manager): + return "" + + fun = no_prefix + + elif name == "input_history": + + def input_history(history_manager): + return "\n".join([s[2] for s in history_manager.get_range()]) + "\n" + + fun = input_history + + else: + fun = import_item(name) + self.auto_suggest._llm_prefixer = fun + else: + raise ValueError("No valid provider.") + if self.pt_app: + self.pt_app.auto_suggest = self.auto_suggest + + @observe("autosuggestions_provider") + def _autosuggestions_provider_changed(self, change): + provider = change.new + self._set_autosuggestions(provider) + + shortcuts = List( + trait=Dict( + key_trait=Enum( + [ + "command", + "match_keys", + "match_filter", + "new_keys", + "new_filter", + "create", + ] + ), + per_key_traits={ + "command": Unicode(), + "match_keys": List(Unicode()), + "match_filter": Unicode(), + "new_keys": List(Unicode()), + "new_filter": Unicode(), + "create": Bool(False), + }, + ), + help=""" + Add, disable or modifying shortcuts. + + Each entry on the list should be a dictionary with ``command`` key + identifying the target function executed by the shortcut and at least + one of the following: + + - ``match_keys``: list of keys used to match an existing shortcut, + - ``match_filter``: shortcut filter used to match an existing shortcut, + - ``new_keys``: list of keys to set, + - ``new_filter``: a new shortcut filter to set + + The filters have to be composed of pre-defined verbs and joined by one + of the following conjunctions: ``&`` (and), ``|`` (or), ``~`` (not). + The pre-defined verbs are: + + {filters} + + To disable a shortcut set ``new_keys`` to an empty list. + To add a shortcut add key ``create`` with value ``True``. + + When modifying/disabling shortcuts, ``match_keys``/``match_filter`` can + be omitted if the provided specification uniquely identifies a shortcut + to be modified/disabled. When modifying a shortcut ``new_filter`` or + ``new_keys`` can be omitted which will result in reuse of the existing + filter/keys. + + Only shortcuts defined in IPython (and not default prompt-toolkit + shortcuts) can be modified or disabled. The full list of shortcuts, + command identifiers and filters is available under + :ref:`terminal-shortcuts-list`. + + Here is an example: + + .. code:: + + c.TerminalInteractiveShell.shortcuts = [ + {{ + "new_keys": ["c-q"], + "command": "prompt_toolkit:named_commands.capitalize_word", + "create": True, + }}, + {{ + "new_keys": ["c-j"], + "command": "prompt_toolkit:named_commands.beginning_of_line", + "create": True, + }}, + ] + + + """.format( + filters="\n ".join([f" - ``{k}``" for k in KEYBINDING_FILTERS]) + ), + ).tag(config=True) + + @observe("shortcuts") + def _shortcuts_changed(self, change): + if self.pt_app: + self.pt_app.key_bindings = self._merge_shortcuts(user_shortcuts=change.new) + + def _merge_shortcuts(self, user_shortcuts): + # rebuild the bindings list from scratch + key_bindings = create_ipython_shortcuts(self) + + # for now we only allow adding shortcuts for a specific set of + # commands; this is a security precution. + allowed_commands = { + create_identifier(binding.command): binding.command + for binding in KEY_BINDINGS + } + allowed_commands.update( + { + create_identifier(command): command + for command in UNASSIGNED_ALLOWED_COMMANDS + } + ) + shortcuts_to_skip = [] + shortcuts_to_add = [] + + for shortcut in user_shortcuts: + command_id = shortcut["command"] + if command_id not in allowed_commands: + allowed_commands = "\n - ".join(allowed_commands) + raise ValueError( + f"{command_id} is not a known shortcut command." + f" Allowed commands are: \n - {allowed_commands}" + ) + old_keys = shortcut.get("match_keys", None) + old_filter = ( + filter_from_string(shortcut["match_filter"]) + if "match_filter" in shortcut + else None + ) + matching = [ + binding + for binding in KEY_BINDINGS + if ( + (old_filter is None or binding.filter == old_filter) + and (old_keys is None or [k for k in binding.keys] == old_keys) + and create_identifier(binding.command) == command_id + ) + ] + + new_keys = shortcut.get("new_keys", None) + new_filter = shortcut.get("new_filter", None) + + command = allowed_commands[command_id] + + creating_new = shortcut.get("create", False) + modifying_existing = not creating_new and ( + new_keys is not None or new_filter + ) + + if creating_new and new_keys == []: + raise ValueError("Cannot add a shortcut without keys") + + if modifying_existing: + specification = { + key: shortcut[key] + for key in ["command", "filter"] + if key in shortcut + } + if len(matching) == 0: + raise ValueError( + f"No shortcuts matching {specification} found in {KEY_BINDINGS}" + ) + elif len(matching) > 1: + raise ValueError( + f"Multiple shortcuts matching {specification} found," + f" please add keys/filter to select one of: {matching}" + ) + + matched = matching[0] + old_filter = matched.filter + old_keys = list(matched.keys) + shortcuts_to_skip.append( + RuntimeBinding( + command, + keys=old_keys, + filter=old_filter, + ) + ) + + if new_keys != []: + shortcuts_to_add.append( + RuntimeBinding( + command, + keys=new_keys or old_keys, + filter=( + filter_from_string(new_filter) + if new_filter is not None + else ( + old_filter + if old_filter is not None + else filter_from_string("always") + ) + ), + ) + ) + + # rebuild the bindings list from scratch + key_bindings = create_ipython_shortcuts(self, skip=shortcuts_to_skip) + for binding in shortcuts_to_add: + add_binding(key_bindings, binding) + + return key_bindings + + prompt_includes_vi_mode = Bool(True, + help="Display the current vi mode (when using vi editing mode)." + ).tag(config=True) + + prompt_line_number_format = Unicode( + "", + help="The format for line numbering, will be passed `line` (int, 1 based)" + " the current line number and `rel_line` the relative line number." + " for example to display both you can use the following template string :" + " c.TerminalInteractiveShell.prompt_line_number_format='{line: 4d}/{rel_line:+03d} | '" + " This will display the current line number, with leading space and a width of at least 4" + " character, as well as the relative line number 0 padded and always with a + or - sign." + " Note that when using Emacs mode the prompt of the first line may not update.", + ).tag(config=True) + + @observe('term_title') + def init_term_title(self, change=None): + # Enable or disable the terminal title. + if self.term_title and _is_tty: + toggle_set_term_title(True) + set_term_title(self.term_title_format.format(cwd=abbrev_cwd())) + else: + toggle_set_term_title(False) + + def restore_term_title(self): + if self.term_title and _is_tty: + restore_term_title() + + def init_display_formatter(self): + super(TerminalInteractiveShell, self).init_display_formatter() + # terminal only supports plain text + self.display_formatter.active_types = ["text/plain"] + + def init_prompt_toolkit_cli(self): + if self.simple_prompt: + # Fall back to plain non-interactive output for tests. + # This is very limited. + def prompt(): + prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens()) + lines = [input(prompt_text)] + prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens()) + while self.check_complete('\n'.join(lines))[0] == 'incomplete': + lines.append( input(prompt_continuation) ) + return '\n'.join(lines) + self.prompt_for_code = prompt + return + + # Set up keyboard shortcuts + key_bindings = self._merge_shortcuts(user_shortcuts=self.shortcuts) + + # Pre-populate history from IPython's history database + history = PtkHistoryAdapter(self) + + self._style = self._make_style_from_name_or_cls(self.highlighting_style) + self.style = DynamicStyle(lambda: self._style) + + editing_mode = getattr(EditingMode, self.editing_mode.upper()) + + self._use_asyncio_inputhook = False + self.pt_app = PromptSession( + auto_suggest=self.auto_suggest, + editing_mode=editing_mode, + key_bindings=key_bindings, + history=history, + completer=IPythonPTCompleter(shell=self), + enable_history_search=self.enable_history_search, + style=self.style, + include_default_pygments_style=False, + mouse_support=self.mouse_support, + enable_open_in_editor=self.extra_open_editor_shortcuts, + color_depth=self.color_depth, + tempfile_suffix=".py", + **self._extra_prompt_options(), + ) + if isinstance(self.auto_suggest, NavigableAutoSuggestFromHistory): + self.auto_suggest.connect(self.pt_app) + + def _make_style_from_name_or_cls(self, name_or_cls): + """ + Small wrapper that make an IPython compatible style from a style name + + We need that to add style for prompt ... etc. + """ + style_overrides = {} + if name_or_cls == 'legacy': + legacy = self.colors.lower() + if legacy == 'linux': + style_cls = get_style_by_name('monokai') + style_overrides = _style_overrides_linux + elif legacy == 'lightbg': + style_overrides = _style_overrides_light_bg + style_cls = get_style_by_name('pastie') + elif legacy == 'neutral': + # The default theme needs to be visible on both a dark background + # and a light background, because we can't tell what the terminal + # looks like. These tweaks to the default theme help with that. + style_cls = get_style_by_name('default') + style_overrides.update({ + Token.Number: '#ansigreen', + Token.Operator: 'noinherit', + Token.String: '#ansiyellow', + Token.Name.Function: '#ansiblue', + Token.Name.Class: 'bold #ansiblue', + Token.Name.Namespace: 'bold #ansiblue', + Token.Name.Variable.Magic: '#ansiblue', + Token.Prompt: '#ansigreen', + Token.PromptNum: '#ansibrightgreen bold', + Token.OutPrompt: '#ansired', + Token.OutPromptNum: '#ansibrightred bold', + }) + + # Hack: Due to limited color support on the Windows console + # the prompt colors will be wrong without this + if os.name == 'nt': + style_overrides.update({ + Token.Prompt: '#ansidarkgreen', + Token.PromptNum: '#ansigreen bold', + Token.OutPrompt: '#ansidarkred', + Token.OutPromptNum: '#ansired bold', + }) + elif legacy =='nocolor': + style_cls=_NoStyle + style_overrides = {} + else : + raise ValueError('Got unknown colors: ', legacy) + else : + if isinstance(name_or_cls, str): + style_cls = get_style_by_name(name_or_cls) + else: + style_cls = name_or_cls + style_overrides = { + Token.Prompt: '#ansigreen', + Token.PromptNum: '#ansibrightgreen bold', + Token.OutPrompt: '#ansired', + Token.OutPromptNum: '#ansibrightred bold', + } + style_overrides.update(self.highlighting_style_overrides) + style = merge_styles([ + style_from_pygments_cls(style_cls), + style_from_pygments_dict(style_overrides), + ]) + + return style + + @property + def pt_complete_style(self): + return { + 'multicolumn': CompleteStyle.MULTI_COLUMN, + 'column': CompleteStyle.COLUMN, + 'readlinelike': CompleteStyle.READLINE_LIKE, + }[self.display_completions] + + @property + def color_depth(self): + return (ColorDepth.TRUE_COLOR if self.true_color else None) + + def _extra_prompt_options(self): + """ + Return the current layout option for the current Terminal InteractiveShell + """ + def get_message(): + return PygmentsTokens(self.prompts.in_prompt_tokens()) + + if self.editing_mode == "emacs" and self.prompt_line_number_format == "": + # with emacs mode the prompt is (usually) static, so we call only + # the function once. With VI mode it can toggle between [ins] and + # [nor] so we can't precompute. + # here I'm going to favor the default keybinding which almost + # everybody uses to decrease CPU usage. + # if we have issues with users with custom Prompts we can see how to + # work around this. + get_message = get_message() + + options = { + "complete_in_thread": False, + "lexer": IPythonPTLexer(), + "reserve_space_for_menu": self.space_for_menu, + "message": get_message, + "prompt_continuation": ( + lambda width, lineno, is_soft_wrap: PygmentsTokens( + _backward_compat_continuation_prompt_tokens( + self.prompts.continuation_prompt_tokens, width, lineno=lineno + ) + ) + ), + "multiline": True, + "complete_style": self.pt_complete_style, + "input_processors": [ + # Highlight matching brackets, but only when this setting is + # enabled, and only when the DEFAULT_BUFFER has the focus. + ConditionalProcessor( + processor=HighlightMatchingBracketProcessor(chars="[](){}"), + filter=HasFocus(DEFAULT_BUFFER) + & ~IsDone() + & Condition(lambda: self.highlight_matching_brackets), + ), + # Show auto-suggestion in lines other than the last line. + ConditionalProcessor( + processor=AppendAutoSuggestionInAnyLine(), + filter=HasFocus(DEFAULT_BUFFER) + & ~IsDone() + & Condition( + lambda: isinstance( + self.auto_suggest, + NavigableAutoSuggestFromHistory, + ) + ), + ), + ], + } + if not PTK3: + options['inputhook'] = self.inputhook + + return options + + def prompt_for_code(self): + if self.rl_next_input: + default = self.rl_next_input + self.rl_next_input = None + else: + default = '' + + # In order to make sure that asyncio code written in the + # interactive shell doesn't interfere with the prompt, we run the + # prompt in a different event loop. + # If we don't do this, people could spawn coroutine with a + # while/true inside which will freeze the prompt. + + with patch_stdout(raw=True): + if self._use_asyncio_inputhook: + # When we integrate the asyncio event loop, run the UI in the + # same event loop as the rest of the code. don't use an actual + # input hook. (Asyncio is not made for nesting event loops.) + asyncio_loop = get_asyncio_loop() + text = asyncio_loop.run_until_complete( + self.pt_app.prompt_async( + default=default, **self._extra_prompt_options() + ) + ) + else: + text = self.pt_app.prompt( + default=default, + inputhook=self._inputhook, + **self._extra_prompt_options(), + ) + + return text + + def enable_win_unicode_console(self): + # Since IPython 7.10 doesn't support python < 3.6 and PEP 528, Python uses the unicode APIs for the Windows + # console by default, so WUC shouldn't be needed. + warn("`enable_win_unicode_console` is deprecated since IPython 7.10, does not do anything and will be removed in the future", + DeprecationWarning, + stacklevel=2) + + def init_io(self): + if sys.platform not in {'win32', 'cli'}: + return + + import colorama + colorama.init() + + def init_magics(self): + super(TerminalInteractiveShell, self).init_magics() + self.register_magics(TerminalMagics) + + def init_alias(self): + # The parent class defines aliases that can be safely used with any + # frontend. + super(TerminalInteractiveShell, self).init_alias() + + # Now define aliases that only make sense on the terminal, because they + # need direct access to the console in a way that we can't emulate in + # GUI or web frontend + if os.name == 'posix': + for cmd in ('clear', 'more', 'less', 'man'): + self.alias_manager.soft_define_alias(cmd, cmd) + + def __init__(self, *args, **kwargs) -> None: + super(TerminalInteractiveShell, self).__init__(*args, **kwargs) + self._set_autosuggestions(self.autosuggestions_provider) + self.init_prompt_toolkit_cli() + self.init_term_title() + self.keep_running = True + self._set_formatter(self.autoformatter) + + def ask_exit(self): + self.keep_running = False + + rl_next_input = None + + def interact(self): + self.keep_running = True + while self.keep_running: + print(self.separate_in, end='') + + try: + code = self.prompt_for_code() + except EOFError: + if (not self.confirm_exit) \ + or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'): + self.ask_exit() + + else: + if code: + self.run_cell(code, store_history=True) + + def mainloop(self): + # An extra layer of protection in case someone mashing Ctrl-C breaks + # out of our internal code. + while True: + try: + self.interact() + break + except KeyboardInterrupt as e: + print("\n%s escaped interact()\n" % type(e).__name__) + finally: + # An interrupt during the eventloop will mess up the + # internal state of the prompt_toolkit library. + # Stopping the eventloop fixes this, see + # https://github.com/ipython/ipython/pull/9867 + if hasattr(self, '_eventloop'): + self._eventloop.stop() + + self.restore_term_title() + + # try to call some at-exit operation optimistically as some things can't + # be done during interpreter shutdown. this is technically inaccurate as + # this make mainlool not re-callable, but that should be a rare if not + # in existent use case. + + self._atexit_once() + + _inputhook = None + def inputhook(self, context): + if self._inputhook is not None: + self._inputhook(context) + + active_eventloop: Optional[str] = None + + def enable_gui(self, gui: Optional[str] = None) -> None: + if gui: + from ..core.pylabtools import _convert_gui_from_matplotlib + + gui = _convert_gui_from_matplotlib(gui) + + if self.simple_prompt is True and gui is not None: + print( + f'Cannot install event loop hook for "{gui}" when running with `--simple-prompt`.' + ) + print( + "NOTE: Tk is supported natively; use Tk apps and Tk backends with `--simple-prompt`." + ) + return + + if self._inputhook is None and gui is None: + print("No event loop hook running.") + return + + if self._inputhook is not None and gui is not None: + newev, newinhook = get_inputhook_name_and_func(gui) + if self._inputhook == newinhook: + # same inputhook, do nothing + self.log.info( + f"Shell is already running the {self.active_eventloop} eventloop. Doing nothing" + ) + return + self.log.warning( + f"Shell is already running a different gui event loop for {self.active_eventloop}. " + "Call with no arguments to disable the current loop." + ) + return + if self._inputhook is not None and gui is None: + self.active_eventloop = self._inputhook = None + + if gui and (gui not in {None, "webagg"}): + # This hook runs with each cycle of the `prompt_toolkit`'s event loop. + self.active_eventloop, self._inputhook = get_inputhook_name_and_func(gui) + else: + self.active_eventloop = self._inputhook = None + + self._use_asyncio_inputhook = gui == "asyncio" + + # Run !system commands directly, not through pipes, so terminal programs + # work correctly. + system = InteractiveShell.system_raw + + def auto_rewrite_input(self, cmd): + """Overridden from the parent class to use fancy rewriting prompt""" + if not self.show_rewritten_input: + return + + tokens = self.prompts.rewrite_prompt_tokens() + if self.pt_app: + print_formatted_text(PygmentsTokens(tokens), end='', + style=self.pt_app.app.style) + print(cmd) + else: + prompt = ''.join(s for t, s in tokens) + print(prompt, cmd, sep='') + + _prompts_before = None + def switch_doctest_mode(self, mode): + """Switch prompts to classic for %doctest_mode""" + if mode: + self._prompts_before = self.prompts + self.prompts = ClassicPrompts(self) + elif self._prompts_before: + self.prompts = self._prompts_before + self._prompts_before = None +# self._update_layout() + + +InteractiveShellABC.register(TerminalInteractiveShell) + +if __name__ == '__main__': + TerminalInteractiveShell.instance().interact() diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/ipapp.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/ipapp.py new file mode 100644 index 0000000000000000000000000000000000000000..fff6bdf9d212597c7a9d07d19cf844c1bf2fe22f --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/ipapp.py @@ -0,0 +1,338 @@ +# encoding: utf-8 +""" +The :class:`~traitlets.config.application.Application` object for the command +line :command:`ipython` program. +""" + +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. + + +import logging +import os +import sys +import warnings + +from traitlets.config.loader import Config +from traitlets.config.application import boolean_flag, catch_config_error +from IPython.core import release +from IPython.core import usage +from IPython.core.completer import IPCompleter +from IPython.core.crashhandler import CrashHandler +from IPython.core.formatters import PlainTextFormatter +from IPython.core.history import HistoryManager +from IPython.core.application import ( + ProfileDir, BaseIPythonApplication, base_flags, base_aliases +) +from IPython.core.magic import MagicsManager +from IPython.core.magics import ( + ScriptMagics, LoggingMagics +) +from IPython.core.shellapp import ( + InteractiveShellApp, shell_flags, shell_aliases +) +from IPython.extensions.storemagic import StoreMagics +from .interactiveshell import TerminalInteractiveShell +from IPython.paths import get_ipython_dir +from traitlets import ( + Bool, List, default, observe, Type +) + +#----------------------------------------------------------------------------- +# Globals, utilities and helpers +#----------------------------------------------------------------------------- + +_examples = """ +ipython --matplotlib # enable matplotlib integration +ipython --matplotlib=qt # enable matplotlib integration with qt4 backend + +ipython --log-level=DEBUG # set logging to DEBUG +ipython --profile=foo # start with profile foo + +ipython profile create foo # create profile foo w/ default config files +ipython help profile # show the help for the profile subcmd + +ipython locate # print the path to the IPython directory +ipython locate profile foo # print the path to the directory for profile `foo` +""" + +#----------------------------------------------------------------------------- +# Crash handler for this application +#----------------------------------------------------------------------------- + +class IPAppCrashHandler(CrashHandler): + """sys.excepthook for IPython itself, leaves a detailed report on disk.""" + + def __init__(self, app): + contact_name = release.author + contact_email = release.author_email + bug_tracker = 'https://github.com/ipython/ipython/issues' + super(IPAppCrashHandler,self).__init__( + app, contact_name, contact_email, bug_tracker + ) + + def make_report(self,traceback): + """Return a string containing a crash report.""" + + sec_sep = self.section_sep + # Start with parent report + report = [super(IPAppCrashHandler, self).make_report(traceback)] + # Add interactive-specific info we may have + rpt_add = report.append + try: + rpt_add(sec_sep+"History of session input:") + for line in self.app.shell.user_ns['_ih']: + rpt_add(line) + rpt_add('\n*** Last line of input (may not be in above history):\n') + rpt_add(self.app.shell._last_input_line+'\n') + except: + pass + + return ''.join(report) + +#----------------------------------------------------------------------------- +# Aliases and Flags +#----------------------------------------------------------------------------- +flags = dict(base_flags) +flags.update(shell_flags) +frontend_flags = {} +addflag = lambda *args: frontend_flags.update(boolean_flag(*args)) +addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax', + 'Turn on auto editing of files with syntax errors.', + 'Turn off auto editing of files with syntax errors.' +) +addflag('simple-prompt', 'TerminalInteractiveShell.simple_prompt', + "Force simple minimal prompt using `raw_input`", + "Use a rich interactive prompt with prompt_toolkit", +) + +addflag('banner', 'TerminalIPythonApp.display_banner', + "Display a banner upon starting IPython.", + "Don't display a banner upon starting IPython." +) +addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit', + """Set to confirm when you try to exit IPython with an EOF (Control-D + in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit', + you can force a direct exit without any confirmation.""", + "Don't prompt the user when exiting." +) +addflag('term-title', 'TerminalInteractiveShell.term_title', + "Enable auto setting the terminal title.", + "Disable auto setting the terminal title." +) +classic_config = Config() +classic_config.InteractiveShell.cache_size = 0 +classic_config.PlainTextFormatter.pprint = False +classic_config.TerminalInteractiveShell.prompts_class='IPython.terminal.prompts.ClassicPrompts' +classic_config.InteractiveShell.separate_in = '' +classic_config.InteractiveShell.separate_out = '' +classic_config.InteractiveShell.separate_out2 = '' +classic_config.InteractiveShell.colors = 'NoColor' +classic_config.InteractiveShell.xmode = 'Plain' + +frontend_flags['classic']=( + classic_config, + "Gives IPython a similar feel to the classic Python prompt." +) +# # log doesn't make so much sense this way anymore +# paa('--log','-l', +# action='store_true', dest='InteractiveShell.logstart', +# help="Start logging to the default log file (./ipython_log.py).") +# +# # quick is harder to implement +frontend_flags['quick']=( + {'TerminalIPythonApp' : {'quick' : True}}, + "Enable quick startup with no config files." +) + +frontend_flags['i'] = ( + {'TerminalIPythonApp' : {'force_interact' : True}}, + """If running code from the command line, become interactive afterwards. + It is often useful to follow this with `--` to treat remaining flags as + script arguments. + """ +) +flags.update(frontend_flags) + +aliases = dict(base_aliases) +aliases.update(shell_aliases) # type: ignore[arg-type] + +#----------------------------------------------------------------------------- +# Main classes and functions +#----------------------------------------------------------------------------- + + +class LocateIPythonApp(BaseIPythonApplication): + description = """print the path to the IPython dir""" + subcommands = dict( + profile=('IPython.core.profileapp.ProfileLocate', + "print the path to an IPython profile directory", + ), + ) + def start(self): + if self.subapp is not None: + return self.subapp.start() + else: + print(self.ipython_dir) + + +class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp): + name = "ipython" + description = usage.cl_usage + crash_handler_class = IPAppCrashHandler # typing: ignore[assignment] + examples = _examples + + flags = flags + aliases = aliases + classes = List() + + interactive_shell_class = Type( + klass=object, # use default_value otherwise which only allow subclasses. + default_value=TerminalInteractiveShell, + help="Class to use to instantiate the TerminalInteractiveShell object. Useful for custom Frontends" + ).tag(config=True) + + @default('classes') + def _classes_default(self): + """This has to be in a method, for TerminalIPythonApp to be available.""" + return [ + InteractiveShellApp, # ShellApp comes before TerminalApp, because + self.__class__, # it will also affect subclasses (e.g. QtConsole) + TerminalInteractiveShell, + HistoryManager, + MagicsManager, + ProfileDir, + PlainTextFormatter, + IPCompleter, + ScriptMagics, + LoggingMagics, + StoreMagics, + ] + + subcommands = dict( + profile = ("IPython.core.profileapp.ProfileApp", + "Create and manage IPython profiles." + ), + kernel = ("ipykernel.kernelapp.IPKernelApp", + "Start a kernel without an attached frontend." + ), + locate=('IPython.terminal.ipapp.LocateIPythonApp', + LocateIPythonApp.description + ), + history=('IPython.core.historyapp.HistoryApp', + "Manage the IPython history database." + ), + ) + + # *do* autocreate requested profile, but don't create the config file. + auto_create = Bool(True).tag(config=True) + + # configurables + quick = Bool(False, + help="""Start IPython quickly by skipping the loading of config files.""" + ).tag(config=True) + @observe('quick') + def _quick_changed(self, change): + if change['new']: + self.load_config_file = lambda *a, **kw: None + + display_banner = Bool(True, + help="Whether to display a banner upon starting IPython." + ).tag(config=True) + + # if there is code of files to run from the cmd line, don't interact + # unless the --i flag (App.force_interact) is true. + force_interact = Bool(False, + help="""If a command or file is given via the command-line, + e.g. 'ipython foo.py', start an interactive shell after executing the + file or command.""" + ).tag(config=True) + @observe('force_interact') + def _force_interact_changed(self, change): + if change['new']: + self.interact = True + + @observe('file_to_run', 'code_to_run', 'module_to_run') + def _file_to_run_changed(self, change): + new = change['new'] + if new: + self.something_to_run = True + if new and not self.force_interact: + self.interact = False + + # internal, not-configurable + something_to_run=Bool(False) + + @catch_config_error + def initialize(self, argv=None): + """Do actions after construct, but before starting the app.""" + super(TerminalIPythonApp, self).initialize(argv) + if self.subapp is not None: + # don't bother initializing further, starting subapp + return + # print(self.extra_args) + if self.extra_args and not self.something_to_run: + self.file_to_run = self.extra_args[0] + self.init_path() + # create the shell + self.init_shell() + # and draw the banner + self.init_banner() + # Now a variety of things that happen after the banner is printed. + self.init_gui_pylab() + self.init_extensions() + self.init_code() + + def init_shell(self): + """initialize the InteractiveShell instance""" + # Create an InteractiveShell instance. + # shell.display_banner should always be False for the terminal + # based app, because we call shell.show_banner() by hand below + # so the banner shows *before* all extension loading stuff. + self.shell = self.interactive_shell_class.instance(parent=self, + profile_dir=self.profile_dir, + ipython_dir=self.ipython_dir, user_ns=self.user_ns) + self.shell.configurables.append(self) + + def init_banner(self): + """optionally display the banner""" + if self.display_banner and self.interact: + self.shell.show_banner() + # Make sure there is a space below the banner. + if self.log_level <= logging.INFO: print() + + def _pylab_changed(self, name, old, new): + """Replace --pylab='inline' with --pylab='auto'""" + if new == 'inline': + warnings.warn("'inline' not available as pylab backend, " + "using 'auto' instead.") + self.pylab = 'auto' + + def start(self): + if self.subapp is not None: + return self.subapp.start() + # perform any prexec steps: + if self.interact: + self.log.debug("Starting IPython's mainloop...") + self.shell.mainloop() + else: + self.log.debug("IPython not interactive...") + self.shell.restore_term_title() + if not self.shell.last_execution_succeeded: + sys.exit(1) + +def load_default_config(ipython_dir=None): + """Load the default config file from the default ipython_dir. + + This is useful for embedded shells. + """ + if ipython_dir is None: + ipython_dir = get_ipython_dir() + + profile_dir = os.path.join(ipython_dir, 'profile_default') + app = TerminalIPythonApp() + app.config_file_paths.append(profile_dir) + app.load_config_file() + return app.config + +launch_new_instance = TerminalIPythonApp.launch_instance diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/magics.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/magics.py new file mode 100644 index 0000000000000000000000000000000000000000..cea53e4a2484d0cea9a60ecf8108d12aa7207800 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/magics.py @@ -0,0 +1,214 @@ +"""Extra magics for terminal use.""" + +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. + + +from logging import error +import os +import sys + +from IPython.core.error import TryNext, UsageError +from IPython.core.magic import Magics, magics_class, line_magic +from IPython.lib.clipboard import ClipboardEmpty +from IPython.testing.skipdoctest import skip_doctest +from IPython.utils.text import SList, strip_email_quotes +from IPython.utils import py3compat + +def get_pasted_lines(sentinel, l_input=py3compat.input, quiet=False): + """ Yield pasted lines until the user enters the given sentinel value. + """ + if not quiet: + print("Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \ + % sentinel) + prompt = ":" + else: + prompt = "" + while True: + try: + l = l_input(prompt) + if l == sentinel: + return + else: + yield l + except EOFError: + print('') + return + + +@magics_class +class TerminalMagics(Magics): + def __init__(self, shell): + super(TerminalMagics, self).__init__(shell) + + def store_or_execute(self, block, name, store_history=False): + """ Execute a block, or store it in a variable, per the user's request. + """ + if name: + # If storing it for further editing + self.shell.user_ns[name] = SList(block.splitlines()) + print("Block assigned to '%s'" % name) + else: + b = self.preclean_input(block) + self.shell.user_ns['pasted_block'] = b + self.shell.using_paste_magics = True + try: + self.shell.run_cell(b, store_history) + finally: + self.shell.using_paste_magics = False + + def preclean_input(self, block): + lines = block.splitlines() + while lines and not lines[0].strip(): + lines = lines[1:] + return strip_email_quotes('\n'.join(lines)) + + def rerun_pasted(self, name='pasted_block'): + """ Rerun a previously pasted command. + """ + b = self.shell.user_ns.get(name) + + # Sanity checks + if b is None: + raise UsageError('No previous pasted block available') + if not isinstance(b, str): + raise UsageError( + "Variable 'pasted_block' is not a string, can't execute") + + print("Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))) + self.shell.run_cell(b) + + @line_magic + def autoindent(self, parameter_s = ''): + """Toggle autoindent on/off (deprecated)""" + self.shell.set_autoindent() + print("Automatic indentation is:",['OFF','ON'][self.shell.autoindent]) + + @skip_doctest + @line_magic + def cpaste(self, parameter_s=''): + """Paste & execute a pre-formatted code block from clipboard. + + You must terminate the block with '--' (two minus-signs) or Ctrl-D + alone on the line. You can also provide your own sentinel with '%paste + -s %%' ('%%' is the new sentinel for this operation). + + The block is dedented prior to execution to enable execution of method + definitions. '>' and '+' characters at the beginning of a line are + ignored, to allow pasting directly from e-mails, diff files and + doctests (the '...' continuation prompt is also stripped). The + executed block is also assigned to variable named 'pasted_block' for + later editing with '%edit pasted_block'. + + You can also pass a variable name as an argument, e.g. '%cpaste foo'. + This assigns the pasted block to variable 'foo' as string, without + dedenting or executing it (preceding >>> and + is still stripped) + + '%cpaste -r' re-executes the block previously entered by cpaste. + '%cpaste -q' suppresses any additional output messages. + + Do not be alarmed by garbled output on Windows (it's a readline bug). + Just press enter and type -- (and press enter again) and the block + will be what was just pasted. + + Shell escapes are not supported (yet). + + See Also + -------- + paste : automatically pull code from clipboard. + + Examples + -------- + :: + + In [8]: %cpaste + Pasting code; enter '--' alone on the line to stop. + :>>> a = ["world!", "Hello"] + :>>> print(" ".join(sorted(a))) + :-- + Hello world! + + :: + In [8]: %cpaste + Pasting code; enter '--' alone on the line to stop. + :>>> %alias_magic t timeit + :>>> %t -n1 pass + :-- + Created `%t` as an alias for `%timeit`. + Created `%%t` as an alias for `%%timeit`. + 354 ns ± 224 ns per loop (mean ± std. dev. of 7 runs, 1 loop each) + """ + opts, name = self.parse_options(parameter_s, 'rqs:', mode='string') + if 'r' in opts: + self.rerun_pasted() + return + + quiet = ('q' in opts) + + sentinel = opts.get('s', u'--') + block = '\n'.join(get_pasted_lines(sentinel, quiet=quiet)) + self.store_or_execute(block, name, store_history=True) + + @line_magic + def paste(self, parameter_s=''): + """Paste & execute a pre-formatted code block from clipboard. + + The text is pulled directly from the clipboard without user + intervention and printed back on the screen before execution (unless + the -q flag is given to force quiet mode). + + The block is dedented prior to execution to enable execution of method + definitions. '>' and '+' characters at the beginning of a line are + ignored, to allow pasting directly from e-mails, diff files and + doctests (the '...' continuation prompt is also stripped). The + executed block is also assigned to variable named 'pasted_block' for + later editing with '%edit pasted_block'. + + You can also pass a variable name as an argument, e.g. '%paste foo'. + This assigns the pasted block to variable 'foo' as string, without + executing it (preceding >>> and + is still stripped). + + Options: + + -r: re-executes the block previously entered by cpaste. + + -q: quiet mode: do not echo the pasted text back to the terminal. + + IPython statements (magics, shell escapes) are not supported (yet). + + See Also + -------- + cpaste : manually paste code into terminal until you mark its end. + """ + opts, name = self.parse_options(parameter_s, 'rq', mode='string') + if 'r' in opts: + self.rerun_pasted() + return + try: + block = self.shell.hooks.clipboard_get() + except TryNext as clipboard_exc: + message = getattr(clipboard_exc, 'args') + if message: + error(message[0]) + else: + error('Could not get text from the clipboard.') + return + except ClipboardEmpty as e: + raise UsageError("The clipboard appears to be empty") from e + + # By default, echo back to terminal unless quiet mode is requested + if 'q' not in opts: + sys.stdout.write(self.shell.pycolorize(block)) + if not block.endswith("\n"): + sys.stdout.write("\n") + sys.stdout.write("## -- End pasted text --\n") + + self.store_or_execute(block, name, store_history=True) + + # Class-level: add a '%cls' magic only on Windows + if sys.platform == 'win32': + @line_magic + def cls(self, s): + """Clear screen. + """ + os.system("cls") diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/prompts.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/prompts.py new file mode 100644 index 0000000000000000000000000000000000000000..40a10511d9ac121c4740d4e590321e367e70b99d --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/prompts.py @@ -0,0 +1,128 @@ +"""Terminal input and output prompts.""" + +from pygments.token import Token +import sys + +from IPython.core.displayhook import DisplayHook + +from prompt_toolkit.formatted_text import fragment_list_width, PygmentsTokens +from prompt_toolkit.shortcuts import print_formatted_text +from prompt_toolkit.enums import EditingMode + + +class Prompts(object): + def __init__(self, shell): + self.shell = shell + + def vi_mode(self): + if (getattr(self.shell.pt_app, 'editing_mode', None) == EditingMode.VI + and self.shell.prompt_includes_vi_mode): + mode = str(self.shell.pt_app.app.vi_state.input_mode) + if mode.startswith('InputMode.'): + mode = mode[10:13].lower() + elif mode.startswith('vi-'): + mode = mode[3:6] + return '['+mode+'] ' + return '' + + def current_line(self) -> int: + if self.shell.pt_app is not None: + return self.shell.pt_app.default_buffer.document.cursor_position_row or 0 + return 0 + + def in_prompt_tokens(self): + return [ + (Token.Prompt, self.vi_mode()), + ( + Token.Prompt, + self.shell.prompt_line_number_format.format( + line=1, rel_line=-self.current_line() + ), + ), + (Token.Prompt, "In ["), + (Token.PromptNum, str(self.shell.execution_count)), + (Token.Prompt, ']: '), + ] + + def _width(self): + return fragment_list_width(self.in_prompt_tokens()) + + def continuation_prompt_tokens(self, width=None, *, lineno=None): + if width is None: + width = self._width() + line = lineno + 1 if lineno is not None else 0 + prefix = " " * len( + self.vi_mode() + ) + self.shell.prompt_line_number_format.format( + line=line, rel_line=line - self.current_line() - 1 + ) + return [ + ( + Token.Prompt, + prefix + (" " * (width - len(prefix) - 5)) + "...: ", + ), + ] + + def rewrite_prompt_tokens(self): + width = self._width() + return [ + (Token.Prompt, ('-' * (width - 2)) + '> '), + ] + + def out_prompt_tokens(self): + return [ + (Token.OutPrompt, 'Out['), + (Token.OutPromptNum, str(self.shell.execution_count)), + (Token.OutPrompt, ']: '), + ] + +class ClassicPrompts(Prompts): + def in_prompt_tokens(self): + return [ + (Token.Prompt, '>>> '), + ] + + def continuation_prompt_tokens(self, width=None): + return [ + (Token.Prompt, '... ') + ] + + def rewrite_prompt_tokens(self): + return [] + + def out_prompt_tokens(self): + return [] + +class RichPromptDisplayHook(DisplayHook): + """Subclass of base display hook using coloured prompt""" + def write_output_prompt(self): + sys.stdout.write(self.shell.separate_out) + # If we're not displaying a prompt, it effectively ends with a newline, + # because the output will be left-aligned. + self.prompt_end_newline = True + + if self.do_full_cache: + tokens = self.shell.prompts.out_prompt_tokens() + prompt_txt = "".join(s for _, s in tokens) + if prompt_txt and not prompt_txt.endswith("\n"): + # Ask for a newline before multiline output + self.prompt_end_newline = False + + if self.shell.pt_app: + print_formatted_text(PygmentsTokens(tokens), + style=self.shell.pt_app.app.style, end='', + ) + else: + sys.stdout.write(prompt_txt) + + def write_format_data(self, format_dict, md_dict=None) -> None: + assert self.shell is not None + if self.shell.mime_renderers: + + for mime, handler in self.shell.mime_renderers.items(): + if mime in format_dict: + handler(format_dict[mime], None) + return + + super().write_format_data(format_dict, md_dict) + diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/ptutils.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/ptutils.py new file mode 100644 index 0000000000000000000000000000000000000000..39bc2e15af9af142c7931926de41bf27667f2692 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/ptutils.py @@ -0,0 +1,204 @@ +"""prompt-toolkit utilities + +Everything in this module is a private API, +not to be used outside IPython. +""" + +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. + +import unicodedata +from wcwidth import wcwidth + +from IPython.core.completer import ( + provisionalcompleter, cursor_to_position, + _deduplicate_completions) +from prompt_toolkit.completion import Completer, Completion +from prompt_toolkit.lexers import Lexer +from prompt_toolkit.lexers import PygmentsLexer +from prompt_toolkit.patch_stdout import patch_stdout + +import pygments.lexers as pygments_lexers +import os +import sys +import traceback + +_completion_sentinel = object() + +def _elide_point(string:str, *, min_elide=30)->str: + """ + If a string is long enough, and has at least 3 dots, + replace the middle part with ellipses. + + If a string naming a file is long enough, and has at least 3 slashes, + replace the middle part with ellipses. + + If three consecutive dots, or two consecutive dots are encountered these are + replaced by the equivalents HORIZONTAL ELLIPSIS or TWO DOT LEADER unicode + equivalents + """ + string = string.replace('...','\N{HORIZONTAL ELLIPSIS}') + string = string.replace('..','\N{TWO DOT LEADER}') + if len(string) < min_elide: + return string + + object_parts = string.split('.') + file_parts = string.split(os.sep) + if file_parts[-1] == '': + file_parts.pop() + + if len(object_parts) > 3: + return "{}.{}\N{HORIZONTAL ELLIPSIS}{}.{}".format( + object_parts[0], + object_parts[1][:1], + object_parts[-2][-1:], + object_parts[-1], + ) + + elif len(file_parts) > 3: + return ("{}" + os.sep + "{}\N{HORIZONTAL ELLIPSIS}{}" + os.sep + "{}").format( + file_parts[0], file_parts[1][:1], file_parts[-2][-1:], file_parts[-1] + ) + + return string + +def _elide_typed(string:str, typed:str, *, min_elide:int=30)->str: + """ + Elide the middle of a long string if the beginning has already been typed. + """ + + if len(string) < min_elide: + return string + cut_how_much = len(typed)-3 + if cut_how_much < 7: + return string + if string.startswith(typed) and len(string)> len(typed): + return f"{string[:3]}\N{HORIZONTAL ELLIPSIS}{string[cut_how_much:]}" + return string + +def _elide(string:str, typed:str, min_elide=30)->str: + return _elide_typed( + _elide_point(string, min_elide=min_elide), + typed, min_elide=min_elide) + + + +def _adjust_completion_text_based_on_context(text, body, offset): + if text.endswith('=') and len(body) > offset and body[offset] == '=': + return text[:-1] + else: + return text + + +class IPythonPTCompleter(Completer): + """Adaptor to provide IPython completions to prompt_toolkit""" + def __init__(self, ipy_completer=None, shell=None): + if shell is None and ipy_completer is None: + raise TypeError("Please pass shell=an InteractiveShell instance.") + self._ipy_completer = ipy_completer + self.shell = shell + + @property + def ipy_completer(self): + if self._ipy_completer: + return self._ipy_completer + else: + return self.shell.Completer + + def get_completions(self, document, complete_event): + if not document.current_line.strip(): + return + # Some bits of our completion system may print stuff (e.g. if a module + # is imported). This context manager ensures that doesn't interfere with + # the prompt. + + with patch_stdout(), provisionalcompleter(): + body = document.text + cursor_row = document.cursor_position_row + cursor_col = document.cursor_position_col + cursor_position = document.cursor_position + offset = cursor_to_position(body, cursor_row, cursor_col) + try: + yield from self._get_completions(body, offset, cursor_position, self.ipy_completer) + except Exception as e: + try: + exc_type, exc_value, exc_tb = sys.exc_info() + traceback.print_exception(exc_type, exc_value, exc_tb) + except AttributeError: + print('Unrecoverable Error in completions') + + @staticmethod + def _get_completions(body, offset, cursor_position, ipyc): + """ + Private equivalent of get_completions() use only for unit_testing. + """ + debug = getattr(ipyc, 'debug', False) + completions = _deduplicate_completions( + body, ipyc.completions(body, offset)) + for c in completions: + if not c.text: + # Guard against completion machinery giving us an empty string. + continue + text = unicodedata.normalize('NFC', c.text) + # When the first character of the completion has a zero length, + # then it's probably a decomposed unicode character. E.g. caused by + # the "\dot" completion. Try to compose again with the previous + # character. + if wcwidth(text[0]) == 0: + if cursor_position + c.start > 0: + char_before = body[c.start - 1] + fixed_text = unicodedata.normalize( + 'NFC', char_before + text) + + # Yield the modified completion instead, if this worked. + if wcwidth(text[0:1]) == 1: + yield Completion(fixed_text, start_position=c.start - offset - 1) + continue + + # TODO: Use Jedi to determine meta_text + # (Jedi currently has a bug that results in incorrect information.) + # meta_text = '' + # yield Completion(m, start_position=start_pos, + # display_meta=meta_text) + display_text = c.text + + adjusted_text = _adjust_completion_text_based_on_context(c.text, body, offset) + if c.type == 'function': + yield Completion(adjusted_text, start_position=c.start - offset, display=_elide(display_text+'()', body[c.start:c.end]), display_meta=c.type+c.signature) + else: + yield Completion(adjusted_text, start_position=c.start - offset, display=_elide(display_text, body[c.start:c.end]), display_meta=c.type) + +class IPythonPTLexer(Lexer): + """ + Wrapper around PythonLexer and BashLexer. + """ + def __init__(self): + l = pygments_lexers + self.python_lexer = PygmentsLexer(l.Python3Lexer) + self.shell_lexer = PygmentsLexer(l.BashLexer) + + self.magic_lexers = { + 'HTML': PygmentsLexer(l.HtmlLexer), + 'html': PygmentsLexer(l.HtmlLexer), + 'javascript': PygmentsLexer(l.JavascriptLexer), + 'js': PygmentsLexer(l.JavascriptLexer), + 'perl': PygmentsLexer(l.PerlLexer), + 'ruby': PygmentsLexer(l.RubyLexer), + 'latex': PygmentsLexer(l.TexLexer), + } + + def lex_document(self, document): + text = document.text.lstrip() + + lexer = self.python_lexer + + if text.startswith('!') or text.startswith('%%bash'): + lexer = self.shell_lexer + + elif text.startswith('%%'): + for magic, l in self.magic_lexers.items(): + if text.startswith('%%' + magic): + lexer = l + break + + return lexer.lex_document(document) diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/__init__.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/fake_llm.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/fake_llm.py new file mode 100644 index 0000000000000000000000000000000000000000..cac5882598cc0a4a578a0858af455aad113ec63c --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/fake_llm.py @@ -0,0 +1,89 @@ +import asyncio + +try: + from jupyter_ai_magics import BaseProvider + from langchain_community.llms import FakeListLLM +except ImportError: + + class BaseProvider: + pass + + class FakeListLLM: + pass + + +FIBONACCI = """\ +def fib(n): + if n < 2: return n + return fib(n - 1) + fib(n - 2) +""" + + +class FibonacciCompletionProvider(BaseProvider, FakeListLLM): # type: ignore[misc, valid-type] + + id = "my_provider" + name = "My Provider" + model_id_key = "model" + models = ["model_a"] + + def __init__(self, **kwargs): + kwargs["responses"] = ["This fake response will not be used for completion"] + kwargs["model_id"] = "model_a" + super().__init__(**kwargs) + + async def generate_inline_completions(self, request): + raise ValueError("IPython only supports streaming models.") + + async def stream_inline_completions(self, request): + from jupyter_ai.completions.models import ( + InlineCompletionList, + InlineCompletionReply, + ) + + assert request.number > 0 + token = f"t{request.number}s0" + last_line = request.prefix.rstrip("\n").splitlines()[-1] + + if not FIBONACCI.startswith(last_line): + return + + yield InlineCompletionReply( + list=InlineCompletionList( + items=[ + {"insertText": "", "isIncomplete": True, "token": token}, + ] + ), + reply_to=request.number, + ) + + async for reply in self._stream( + FIBONACCI[len(last_line) :], + request.number, + token, + ): + yield reply + + async def _stream(self, sentence, request_number, token, start_with=""): + from jupyter_ai.completions.models import InlineCompletionStreamChunk + + suggestion = start_with + + for fragment in sentence.split(" "): + await asyncio.sleep(0.05) + if suggestion: + suggestion += " " + suggestion += fragment + yield InlineCompletionStreamChunk( + type="stream", + response={"insertText": suggestion, "token": token}, + reply_to=request_number, + done=False, + ) + + # finally, send a message confirming that we are done + yield InlineCompletionStreamChunk( + type="stream", + response={"insertText": suggestion, "token": token}, + reply_to=request_number, + done=True, + ) diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_debug_magic.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_debug_magic.py new file mode 100644 index 0000000000000000000000000000000000000000..16ed53d31afc4c9e0039841dbd8e98dd12a4929e --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_debug_magic.py @@ -0,0 +1,82 @@ +"""Test embedding of IPython""" + +#----------------------------------------------------------------------------- +# Copyright (C) 2013 The IPython Development Team +# +# Distributed under the terms of the BSD License. The full license is in +# the file COPYING, distributed as part of this software. +#----------------------------------------------------------------------------- + +#----------------------------------------------------------------------------- +# Imports +#----------------------------------------------------------------------------- + +import os +import sys +from IPython.testing.decorators import skip_win32 +from IPython.testing import IPYTHON_TESTING_TIMEOUT_SCALE + +#----------------------------------------------------------------------------- +# Tests +#----------------------------------------------------------------------------- + +@skip_win32 +def test_debug_magic_passes_through_generators(): + """ + This test that we can correctly pass through frames of a generator post-mortem. + """ + import pexpect + import re + in_prompt = re.compile(br'In ?\[\d+\]:') + ipdb_prompt = 'ipdb>' + env = os.environ.copy() + child = pexpect.spawn(sys.executable, ['-m', 'IPython', '--colors=nocolor', '--simple-prompt'], + env=env) + child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE + + child.expect(in_prompt) + + child.timeout = 2 * IPYTHON_TESTING_TIMEOUT_SCALE + + child.sendline("def f(x):") + child.sendline(" raise Exception") + child.sendline("") + + child.expect(in_prompt) + child.sendline("gen = (f(x) for x in [0])") + child.sendline("") + + child.expect(in_prompt) + child.sendline("for x in gen:") + child.sendline(" pass") + child.sendline("") + + child.timeout = 10 * IPYTHON_TESTING_TIMEOUT_SCALE + + child.expect('Exception:') + + child.expect(in_prompt) + child.sendline(r'%debug') + child.expect('----> 2 raise Exception') + + child.expect(ipdb_prompt) + child.sendline('u') + child.expect_exact(r'----> 1 gen = (f(x) for x in [0])') + + child.expect(ipdb_prompt) + child.sendline('u') + child.expect_exact('----> 1 for x in gen:') + + child.expect(ipdb_prompt) + child.sendline("u") + child.expect_exact( + "*** all frames above hidden, use `skip_hidden False` to get get into those." + ) + + child.expect(ipdb_prompt) + child.sendline('exit') + + child.expect(in_prompt) + child.sendline('exit') + + child.close() diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_embed.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_embed.py new file mode 100644 index 0000000000000000000000000000000000000000..3f0885e73ccd6e3e1ab848ea503499ebf867f214 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_embed.py @@ -0,0 +1,138 @@ +"""Test embedding of IPython""" + +#----------------------------------------------------------------------------- +# Copyright (C) 2013 The IPython Development Team +# +# Distributed under the terms of the BSD License. The full license is in +# the file COPYING, distributed as part of this software. +#----------------------------------------------------------------------------- + +#----------------------------------------------------------------------------- +# Imports +#----------------------------------------------------------------------------- + +import os +import subprocess +import sys + +from IPython.utils.tempdir import NamedFileInTemporaryDirectory +from IPython.testing.decorators import skip_win32 +from IPython.testing import IPYTHON_TESTING_TIMEOUT_SCALE + +#----------------------------------------------------------------------------- +# Tests +#----------------------------------------------------------------------------- + + +_sample_embed = b""" +import IPython + +a = 3 +b = 14 +print(a, '.', b) + +IPython.embed() + +print('bye!') +""" + +_exit = b"exit\r" + +def test_ipython_embed(): + """test that `IPython.embed()` works""" + with NamedFileInTemporaryDirectory('file_with_embed.py') as f: + f.write(_sample_embed) + f.flush() + f.close() # otherwise msft won't be able to read the file + + # run `python file_with_embed.py` + cmd = [sys.executable, f.name] + env = os.environ.copy() + env['IPY_TEST_SIMPLE_PROMPT'] = '1' + + p = subprocess.Popen(cmd, env=env, stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + out, err = p.communicate(_exit) + std = out.decode('UTF-8') + + assert p.returncode == 0 + assert "3 . 14" in std + if os.name != "nt": + # TODO: Fix up our different stdout references, see issue gh-14 + assert "IPython" in std + assert "bye!" in std + + +@skip_win32 +def test_nest_embed(): + """test that `IPython.embed()` is nestable""" + import pexpect + ipy_prompt = r']:' #ansi color codes give problems matching beyond this + env = os.environ.copy() + env['IPY_TEST_SIMPLE_PROMPT'] = '1' + + + child = pexpect.spawn(sys.executable, ['-m', 'IPython', '--colors=nocolor'], + env=env) + child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE + child.expect(ipy_prompt) + child.timeout = 5 * IPYTHON_TESTING_TIMEOUT_SCALE + child.sendline("import IPython") + child.expect(ipy_prompt) + child.sendline("ip0 = get_ipython()") + #enter first nested embed + child.sendline("IPython.embed()") + #skip the banner until we get to a prompt + try: + prompted = -1 + while prompted != 0: + prompted = child.expect([ipy_prompt, '\r\n']) + except pexpect.TIMEOUT as e: + print(e) + #child.interact() + child.sendline("embed1 = get_ipython()") + child.expect(ipy_prompt) + child.sendline("print('true' if embed1 is not ip0 else 'false')") + assert(child.expect(['true\r\n', 'false\r\n']) == 0) + child.expect(ipy_prompt) + child.sendline("print('true' if IPython.get_ipython() is embed1 else 'false')") + assert(child.expect(['true\r\n', 'false\r\n']) == 0) + child.expect(ipy_prompt) + #enter second nested embed + child.sendline("IPython.embed()") + #skip the banner until we get to a prompt + try: + prompted = -1 + while prompted != 0: + prompted = child.expect([ipy_prompt, '\r\n']) + except pexpect.TIMEOUT as e: + print(e) + #child.interact() + child.sendline("embed2 = get_ipython()") + child.expect(ipy_prompt) + child.sendline("print('true' if embed2 is not embed1 else 'false')") + assert(child.expect(['true\r\n', 'false\r\n']) == 0) + child.expect(ipy_prompt) + child.sendline("print('true' if embed2 is IPython.get_ipython() else 'false')") + assert(child.expect(['true\r\n', 'false\r\n']) == 0) + child.expect(ipy_prompt) + child.sendline('exit') + #back at first embed + child.expect(ipy_prompt) + child.sendline("print('true' if get_ipython() is embed1 else 'false')") + assert(child.expect(['true\r\n', 'false\r\n']) == 0) + child.expect(ipy_prompt) + child.sendline("print('true' if IPython.get_ipython() is embed1 else 'false')") + assert(child.expect(['true\r\n', 'false\r\n']) == 0) + child.expect(ipy_prompt) + child.sendline('exit') + #back at launching scope + child.expect(ipy_prompt) + child.sendline("print('true' if get_ipython() is ip0 else 'false')") + assert(child.expect(['true\r\n', 'false\r\n']) == 0) + child.expect(ipy_prompt) + child.sendline("print('true' if IPython.get_ipython() is ip0 else 'false')") + assert(child.expect(['true\r\n', 'false\r\n']) == 0) + child.expect(ipy_prompt) + child.sendline('exit') + child.close() diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_help.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_help.py new file mode 100644 index 0000000000000000000000000000000000000000..038f560b2fb2addf7d95f45b358a7d4e0864e943 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_help.py @@ -0,0 +1,30 @@ +"""Test help output of various IPython entry points""" + +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. + +import pytest +import IPython.testing.tools as tt + + +def test_ipython_help(): + tt.help_all_output_test() + +def test_profile_help(): + tt.help_all_output_test("profile") + +def test_profile_list_help(): + tt.help_all_output_test("profile list") + +def test_profile_create_help(): + tt.help_all_output_test("profile create") + +def test_locate_help(): + tt.help_all_output_test("locate") + +def test_locate_profile_help(): + tt.help_all_output_test("locate profile") + +def test_trust_help(): + pytest.importorskip("nbformat") + tt.help_all_output_test("trust") diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_interactivshell.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_interactivshell.py new file mode 100644 index 0000000000000000000000000000000000000000..ae7da217f1dffde0133685ea50baeda1b7091c92 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_interactivshell.py @@ -0,0 +1,255 @@ +# -*- coding: utf-8 -*- +"""Tests for the TerminalInteractiveShell and related pieces.""" +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. + +import sys +import unittest +import os + +from prompt_toolkit.auto_suggest import AutoSuggestFromHistory + + +from IPython.testing import tools as tt + +from IPython.terminal.ptutils import _elide, _adjust_completion_text_based_on_context +from IPython.terminal.shortcuts.auto_suggest import NavigableAutoSuggestFromHistory + + +class TestAutoSuggest(unittest.TestCase): + def test_changing_provider(self): + ip = get_ipython() + ip.autosuggestions_provider = None + self.assertEqual(ip.auto_suggest, None) + ip.autosuggestions_provider = "AutoSuggestFromHistory" + self.assertIsInstance(ip.auto_suggest, AutoSuggestFromHistory) + ip.autosuggestions_provider = "NavigableAutoSuggestFromHistory" + self.assertIsInstance(ip.auto_suggest, NavigableAutoSuggestFromHistory) + + +class TestElide(unittest.TestCase): + def test_elide(self): + _elide("concatenate((a1, a2, ...), axis", "") # do not raise + _elide("concatenate((a1, a2, ..), . axis", "") # do not raise + self.assertEqual( + _elide("aaaa.bbbb.ccccc.dddddd.eeeee.fffff.gggggg.hhhhhh", ""), + "aaaa.b…g.hhhhhh", + ) + + test_string = os.sep.join(["", 10 * "a", 10 * "b", 10 * "c", ""]) + expect_string = ( + os.sep + "a" + "\N{HORIZONTAL ELLIPSIS}" + "b" + os.sep + 10 * "c" + ) + self.assertEqual(_elide(test_string, ""), expect_string) + + def test_elide_typed_normal(self): + self.assertEqual( + _elide( + "the quick brown fox jumped over the lazy dog", + "the quick brown fox", + min_elide=10, + ), + "the…fox jumped over the lazy dog", + ) + + def test_elide_typed_short_match(self): + """ + if the match is too short we don't elide. + avoid the "the...the" + """ + self.assertEqual( + _elide("the quick brown fox jumped over the lazy dog", "the", min_elide=10), + "the quick brown fox jumped over the lazy dog", + ) + + def test_elide_typed_no_match(self): + """ + if the match is too short we don't elide. + avoid the "the...the" + """ + # here we typed red instead of brown + self.assertEqual( + _elide( + "the quick brown fox jumped over the lazy dog", + "the quick red fox", + min_elide=10, + ), + "the quick brown fox jumped over the lazy dog", + ) + + +class TestContextAwareCompletion(unittest.TestCase): + def test_adjust_completion_text_based_on_context(self): + # Adjusted case + self.assertEqual( + _adjust_completion_text_based_on_context("arg1=", "func1(a=)", 7), "arg1" + ) + + # Untouched cases + self.assertEqual( + _adjust_completion_text_based_on_context("arg1=", "func1(a)", 7), "arg1=" + ) + self.assertEqual( + _adjust_completion_text_based_on_context("arg1=", "func1(a", 7), "arg1=" + ) + self.assertEqual( + _adjust_completion_text_based_on_context("%magic", "func1(a=)", 7), "%magic" + ) + self.assertEqual( + _adjust_completion_text_based_on_context("func2", "func1(a=)", 7), "func2" + ) + + +# Decorator for interaction loop tests ----------------------------------------- + + +class mock_input_helper(object): + """Machinery for tests of the main interact loop. + + Used by the mock_input decorator. + """ + def __init__(self, testgen): + self.testgen = testgen + self.exception = None + self.ip = get_ipython() + + def __enter__(self): + self.orig_prompt_for_code = self.ip.prompt_for_code + self.ip.prompt_for_code = self.fake_input + return self + + def __exit__(self, etype, value, tb): + self.ip.prompt_for_code = self.orig_prompt_for_code + + def fake_input(self): + try: + return next(self.testgen) + except StopIteration: + self.ip.keep_running = False + return u'' + except: + self.exception = sys.exc_info() + self.ip.keep_running = False + return u'' + +def mock_input(testfunc): + """Decorator for tests of the main interact loop. + + Write the test as a generator, yield-ing the input strings, which IPython + will see as if they were typed in at the prompt. + """ + def test_method(self): + testgen = testfunc(self) + with mock_input_helper(testgen) as mih: + mih.ip.interact() + + if mih.exception is not None: + # Re-raise captured exception + etype, value, tb = mih.exception + import traceback + traceback.print_tb(tb, file=sys.stdout) + del tb # Avoid reference loop + raise value + + return test_method + +# Test classes ----------------------------------------------------------------- + +class InteractiveShellTestCase(unittest.TestCase): + def rl_hist_entries(self, rl, n): + """Get last n readline history entries as a list""" + return [rl.get_history_item(rl.get_current_history_length() - x) + for x in range(n - 1, -1, -1)] + + @mock_input + def test_inputtransformer_syntaxerror(self): + ip = get_ipython() + ip.input_transformers_post.append(syntax_error_transformer) + + try: + #raise Exception + with tt.AssertPrints('4', suppress=False): + yield u'print(2*2)' + + with tt.AssertPrints('SyntaxError: input contains', suppress=False): + yield u'print(2345) # syntaxerror' + + with tt.AssertPrints('16', suppress=False): + yield u'print(4*4)' + + finally: + ip.input_transformers_post.remove(syntax_error_transformer) + + def test_repl_not_plain_text(self): + ip = get_ipython() + formatter = ip.display_formatter + assert formatter.active_types == ['text/plain'] + + # terminal may have arbitrary mimetype handler to open external viewer + # or inline images. + assert formatter.ipython_display_formatter.enabled + + class Test(object): + def __repr__(self): + return "" % id(self) + + def _repr_html_(self): + return '' + + # verify that HTML repr isn't computed + obj = Test() + data, _ = formatter.format(obj) + self.assertEqual(data, {'text/plain': repr(obj)}) + + class Test2(Test): + def _ipython_display_(self): + from IPython.display import display, HTML + + display(HTML("")) + + # verify that mimehandlers are called + called = False + + def handler(data, metadata): + print("Handler called") + nonlocal called + called = True + + ip.display_formatter.active_types.append("text/html") + ip.display_formatter.formatters["text/html"].enabled = True + ip.mime_renderers["text/html"] = handler + try: + obj = Test() + display(obj) + finally: + ip.display_formatter.formatters["text/html"].enabled = False + del ip.mime_renderers["text/html"] + + assert called == True + + +def syntax_error_transformer(lines): + """Transformer that throws SyntaxError if 'syntaxerror' is in the code.""" + for line in lines: + pos = line.find('syntaxerror') + if pos >= 0: + e = SyntaxError('input contains "syntaxerror"') + e.text = line + e.offset = pos + 1 + raise e + return lines + + +class TerminalMagicsTestCase(unittest.TestCase): + def test_paste_magics_blankline(self): + """Test that code with a blank line doesn't get split (gh-3246).""" + ip = get_ipython() + s = ('def pasted_func(a):\n' + ' b = a+1\n' + '\n' + ' return b') + + tm = ip.magics_manager.registry['TerminalMagics'] + tm.store_or_execute(s, name=None) + + self.assertEqual(ip.user_ns['pasted_func'](54), 55) diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_pt_inputhooks.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_pt_inputhooks.py new file mode 100644 index 0000000000000000000000000000000000000000..3f788c738cffdca794b72dcf2f5c488c17a1d0af --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_pt_inputhooks.py @@ -0,0 +1,50 @@ +import os +import importlib + +import pytest + +from IPython.terminal.pt_inputhooks import set_qt_api, get_inputhook_name_and_func + + +guis_avail = [] + + +def _get_qt_vers(): + """If any version of Qt is available, this will populate `guis_avail` with 'qt' and 'qtx'. Due + to the import mechanism, we can't import multiple versions of Qt in one session.""" + for gui in ["qt", "qt6", "qt5"]: + print(f"Trying {gui}") + try: + set_qt_api(gui) + importlib.import_module("IPython.terminal.pt_inputhooks.qt") + guis_avail.append(gui) + if "QT_API" in os.environ.keys(): + del os.environ["QT_API"] + except ImportError: + pass # that version of Qt isn't available. + except RuntimeError: + pass # the version of IPython doesn't know what to do with this Qt version. + + +_get_qt_vers() + + +@pytest.mark.skipif( + len(guis_avail) == 0, reason="No viable version of PyQt or PySide installed." +) +def test_inputhook_qt(): + # Choose the "best" Qt version. + gui_ret, _ = get_inputhook_name_and_func("qt") + + assert gui_ret != "qt" # you get back the specific version that was loaded. + assert gui_ret in guis_avail + + if len(guis_avail) > 2: + # ...and now we're stuck with this version of Qt for good; can't switch. + for not_gui in ["qt6", "qt5"]: + if not_gui != gui_ret: + break + # Try to import the other gui; it won't work. + gui_ret2, _ = get_inputhook_name_and_func(not_gui) + assert gui_ret2 == gui_ret + assert gui_ret2 != not_gui diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_shortcuts.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_shortcuts.py new file mode 100644 index 0000000000000000000000000000000000000000..d6007b6ad822f4942dbd0aaa672710f984d79c7c --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_shortcuts.py @@ -0,0 +1,509 @@ +import pytest +from IPython.terminal.shortcuts.auto_suggest import ( + accept, + accept_or_jump_to_end, + accept_token, + accept_character, + accept_word, + accept_and_keep_cursor, + discard, + llm_autosuggestion, + NavigableAutoSuggestFromHistory, + swap_autosuggestion_up, + swap_autosuggestion_down, +) +from IPython.terminal.shortcuts.auto_match import skip_over +from IPython.terminal.shortcuts import create_ipython_shortcuts, reset_search_buffer +from IPython.testing import decorators as dec + +from prompt_toolkit.history import InMemoryHistory +from prompt_toolkit.buffer import Buffer +from prompt_toolkit.document import Document +from prompt_toolkit.auto_suggest import AutoSuggestFromHistory +from prompt_toolkit.enums import DEFAULT_BUFFER + +from unittest.mock import patch, Mock + + +def test_deprected(): + import IPython.terminal.shortcuts.auto_suggest as iptsa + + with pytest.warns(DeprecationWarning, match=r"8\.12.+accept_or_jump_to_end"): + iptsa.accept_in_vi_insert_mode + + +def make_event(text, cursor, suggestion): + event = Mock() + event.current_buffer = Mock() + event.current_buffer.suggestion = Mock() + event.current_buffer.text = text + event.current_buffer.cursor_position = cursor + event.current_buffer.suggestion.text = suggestion + event.current_buffer.document = Document(text=text, cursor_position=cursor) + return event + + +try: + from .fake_llm import FIBONACCI +except ImportError: + FIBONACCI = None + + +@dec.skip_without("jupyter_ai") +@pytest.mark.asyncio +async def test_llm_autosuggestion(): + provider = NavigableAutoSuggestFromHistory() + ip = get_ipython() + ip.auto_suggest = provider + ip.llm_provider_class = "IPython.terminal.tests.fake_llm.FibonacciCompletionProvider" + text = "def fib" + event = make_event(text, len(text), "") + event.current_buffer.history.shell.history_manager.get_range = Mock(return_value=[]) + await llm_autosuggestion(event) + assert event.current_buffer.suggestion.text == FIBONACCI[len(text) :] + + +@pytest.mark.parametrize( + "text, suggestion, expected", + [ + ("", "def out(tag: str, n=50):", "def out(tag: str, n=50):"), + ("def ", "out(tag: str, n=50):", "out(tag: str, n=50):"), + ], +) +def test_accept(text, suggestion, expected): + event = make_event(text, len(text), suggestion) + buffer = event.current_buffer + buffer.insert_text = Mock() + accept(event) + assert buffer.insert_text.called + assert buffer.insert_text.call_args[0] == (expected,) + + +@pytest.mark.parametrize( + "text, suggestion", + [ + ("", "def out(tag: str, n=50):"), + ("def ", "out(tag: str, n=50):"), + ], +) +def test_discard(text, suggestion): + event = make_event(text, len(text), suggestion) + buffer = event.current_buffer + buffer.insert_text = Mock() + discard(event) + assert not buffer.insert_text.called + assert buffer.suggestion is None + + +@pytest.mark.parametrize( + "text, cursor, suggestion, called", + [ + ("123456", 6, "123456789", True), + ("123456", 3, "123456789", False), + ("123456 \n789", 6, "123456789", True), + ], +) +def test_autosuggest_at_EOL(text, cursor, suggestion, called): + """ + test that autosuggest is only applied at end of line. + """ + + event = make_event(text, cursor, suggestion) + event.current_buffer.insert_text = Mock() + accept_or_jump_to_end(event) + if called: + event.current_buffer.insert_text.assert_called() + else: + event.current_buffer.insert_text.assert_not_called() + # event.current_buffer.document.get_end_of_line_position.assert_called() + + +@pytest.mark.parametrize( + "text, suggestion, expected", + [ + ("", "def out(tag: str, n=50):", "def "), + ("d", "ef out(tag: str, n=50):", "ef "), + ("de ", "f out(tag: str, n=50):", "f "), + ("def", " out(tag: str, n=50):", " "), + ("def ", "out(tag: str, n=50):", "out("), + ("def o", "ut(tag: str, n=50):", "ut("), + ("def ou", "t(tag: str, n=50):", "t("), + ("def out", "(tag: str, n=50):", "("), + ("def out(", "tag: str, n=50):", "tag: "), + ("def out(t", "ag: str, n=50):", "ag: "), + ("def out(ta", "g: str, n=50):", "g: "), + ("def out(tag", ": str, n=50):", ": "), + ("def out(tag:", " str, n=50):", " "), + ("def out(tag: ", "str, n=50):", "str, "), + ("def out(tag: s", "tr, n=50):", "tr, "), + ("def out(tag: st", "r, n=50):", "r, "), + ("def out(tag: str", ", n=50):", ", n"), + ("def out(tag: str,", " n=50):", " n"), + ("def out(tag: str, ", "n=50):", "n="), + ("def out(tag: str, n", "=50):", "="), + ("def out(tag: str, n=", "50):", "50)"), + ("def out(tag: str, n=5", "0):", "0)"), + ("def out(tag: str, n=50", "):", "):"), + ("def out(tag: str, n=50)", ":", ":"), + ], +) +def test_autosuggest_token(text, suggestion, expected): + event = make_event(text, len(text), suggestion) + event.current_buffer.insert_text = Mock() + accept_token(event) + assert event.current_buffer.insert_text.called + assert event.current_buffer.insert_text.call_args[0] == (expected,) + + +@pytest.mark.parametrize( + "text, suggestion, expected", + [ + ("", "def out(tag: str, n=50):", "d"), + ("d", "ef out(tag: str, n=50):", "e"), + ("de ", "f out(tag: str, n=50):", "f"), + ("def", " out(tag: str, n=50):", " "), + ], +) +def test_accept_character(text, suggestion, expected): + event = make_event(text, len(text), suggestion) + event.current_buffer.insert_text = Mock() + accept_character(event) + assert event.current_buffer.insert_text.called + assert event.current_buffer.insert_text.call_args[0] == (expected,) + + +@pytest.mark.parametrize( + "text, suggestion, expected", + [ + ("", "def out(tag: str, n=50):", "def "), + ("d", "ef out(tag: str, n=50):", "ef "), + ("de", "f out(tag: str, n=50):", "f "), + ("def", " out(tag: str, n=50):", " "), + # (this is why we also have accept_token) + ("def ", "out(tag: str, n=50):", "out(tag: "), + ], +) +def test_accept_word(text, suggestion, expected): + event = make_event(text, len(text), suggestion) + event.current_buffer.insert_text = Mock() + accept_word(event) + assert event.current_buffer.insert_text.called + assert event.current_buffer.insert_text.call_args[0] == (expected,) + + +@pytest.mark.parametrize( + "text, suggestion, expected, cursor", + [ + ("", "def out(tag: str, n=50):", "def out(tag: str, n=50):", 0), + ("def ", "out(tag: str, n=50):", "out(tag: str, n=50):", 4), + ], +) +def test_accept_and_keep_cursor(text, suggestion, expected, cursor): + event = make_event(text, cursor, suggestion) + buffer = event.current_buffer + buffer.insert_text = Mock() + accept_and_keep_cursor(event) + assert buffer.insert_text.called + assert buffer.insert_text.call_args[0] == (expected,) + assert buffer.cursor_position == cursor + + +def test_autosuggest_token_empty(): + full = "def out(tag: str, n=50):" + event = make_event(full, len(full), "") + event.current_buffer.insert_text = Mock() + + with patch( + "prompt_toolkit.key_binding.bindings.named_commands.forward_word" + ) as forward_word: + accept_token(event) + assert not event.current_buffer.insert_text.called + assert forward_word.called + + +def test_reset_search_buffer(): + event_with_text = Mock() + event_with_text.current_buffer.document.text = "some text" + event_with_text.current_buffer.reset = Mock() + + event_empty = Mock() + event_empty.current_buffer.document.text = "" + event_empty.app.layout.focus = Mock() + + reset_search_buffer(event_with_text) + event_with_text.current_buffer.reset.assert_called_once() + + reset_search_buffer(event_empty) + event_empty.app.layout.focus.assert_called_once_with(DEFAULT_BUFFER) + + +def test_other_providers(): + """Ensure that swapping autosuggestions does not break with other providers""" + provider = AutoSuggestFromHistory() + ip = get_ipython() + ip.auto_suggest = provider + event = Mock() + event.current_buffer = Buffer() + assert swap_autosuggestion_up(event) is None + assert swap_autosuggestion_down(event) is None + + +@pytest.mark.asyncio +async def test_navigable_provider(): + provider = NavigableAutoSuggestFromHistory() + history = InMemoryHistory(history_strings=["very_a", "very", "very_b", "very_c"]) + buffer = Buffer(history=history) + ip = get_ipython() + ip.auto_suggest = provider + + async for _ in history.load(): + pass + + buffer.cursor_position = 5 + buffer.text = "very" + + up = swap_autosuggestion_up + down = swap_autosuggestion_down + + event = Mock() + event.current_buffer = buffer + + def get_suggestion(): + suggestion = provider.get_suggestion(buffer, buffer.document) + buffer.suggestion = suggestion + return suggestion + + assert get_suggestion().text == "_c" + + # should go up + up(event) + assert get_suggestion().text == "_b" + + # should skip over 'very' which is identical to buffer content + up(event) + assert get_suggestion().text == "_a" + + # should cycle back to beginning + up(event) + assert get_suggestion().text == "_c" + + # should cycle back through end boundary + down(event) + assert get_suggestion().text == "_a" + + down(event) + assert get_suggestion().text == "_b" + + down(event) + assert get_suggestion().text == "_c" + + down(event) + assert get_suggestion().text == "_a" + + +@pytest.mark.asyncio +async def test_navigable_provider_multiline_entries(): + provider = NavigableAutoSuggestFromHistory() + history = InMemoryHistory(history_strings=["very_a\nvery_b", "very_c"]) + buffer = Buffer(history=history) + ip = get_ipython() + ip.auto_suggest = provider + + async for _ in history.load(): + pass + + buffer.cursor_position = 5 + buffer.text = "very" + up = swap_autosuggestion_up + down = swap_autosuggestion_down + + event = Mock() + event.current_buffer = buffer + + def get_suggestion(): + suggestion = provider.get_suggestion(buffer, buffer.document) + buffer.suggestion = suggestion + return suggestion + + assert get_suggestion().text == "_c" + + up(event) + assert get_suggestion().text == "_b" + + up(event) + assert get_suggestion().text == "_a" + + down(event) + assert get_suggestion().text == "_b" + + down(event) + assert get_suggestion().text == "_c" + + +def create_session_mock(): + session = Mock() + session.default_buffer = Buffer() + return session + + +def test_navigable_provider_connection(): + provider = NavigableAutoSuggestFromHistory() + provider.skip_lines = 1 + + session_1 = create_session_mock() + provider.connect(session_1) + + assert provider.skip_lines == 1 + session_1.default_buffer.on_text_insert.fire() + assert provider.skip_lines == 0 + + session_2 = create_session_mock() + provider.connect(session_2) + provider.skip_lines = 2 + + assert provider.skip_lines == 2 + session_2.default_buffer.on_text_insert.fire() + assert provider.skip_lines == 0 + + provider.skip_lines = 3 + provider.disconnect() + session_1.default_buffer.on_text_insert.fire() + session_2.default_buffer.on_text_insert.fire() + assert provider.skip_lines == 3 + + +@pytest.fixture +def ipython_with_prompt(): + ip = get_ipython() + ip.pt_app = Mock() + ip.pt_app.key_bindings = create_ipython_shortcuts(ip) + try: + yield ip + finally: + ip.pt_app = None + + +def find_bindings_by_command(command): + ip = get_ipython() + return [ + binding + for binding in ip.pt_app.key_bindings.bindings + if binding.handler == command + ] + + +def test_modify_unique_shortcut(ipython_with_prompt): + original = find_bindings_by_command(accept_token) + assert len(original) == 1 + + ipython_with_prompt.shortcuts = [ + {"command": "IPython:auto_suggest.accept_token", "new_keys": ["a", "b", "c"]} + ] + matched = find_bindings_by_command(accept_token) + assert len(matched) == 1 + assert list(matched[0].keys) == ["a", "b", "c"] + assert list(matched[0].keys) != list(original[0].keys) + assert matched[0].filter == original[0].filter + + ipython_with_prompt.shortcuts = [ + {"command": "IPython:auto_suggest.accept_token", "new_filter": "always"} + ] + matched = find_bindings_by_command(accept_token) + assert len(matched) == 1 + assert list(matched[0].keys) != ["a", "b", "c"] + assert list(matched[0].keys) == list(original[0].keys) + assert matched[0].filter != original[0].filter + + +def test_disable_shortcut(ipython_with_prompt): + matched = find_bindings_by_command(accept_token) + assert len(matched) == 1 + + ipython_with_prompt.shortcuts = [ + {"command": "IPython:auto_suggest.accept_token", "new_keys": []} + ] + matched = find_bindings_by_command(accept_token) + assert len(matched) == 0 + + ipython_with_prompt.shortcuts = [] + matched = find_bindings_by_command(accept_token) + assert len(matched) == 1 + + +def test_modify_shortcut_with_filters(ipython_with_prompt): + matched = find_bindings_by_command(skip_over) + matched_keys = {m.keys[0] for m in matched} + assert matched_keys == {")", "]", "}", "'", '"'} + + with pytest.raises(ValueError, match="Multiple shortcuts matching"): + ipython_with_prompt.shortcuts = [ + {"command": "IPython:auto_match.skip_over", "new_keys": ["x"]} + ] + + ipython_with_prompt.shortcuts = [ + { + "command": "IPython:auto_match.skip_over", + "new_keys": ["x"], + "match_filter": "focused_insert & auto_match & followed_by_single_quote", + } + ] + matched = find_bindings_by_command(skip_over) + matched_keys = {m.keys[0] for m in matched} + assert matched_keys == {")", "]", "}", "x", '"'} + + +def example_command(): + pass + + +def test_add_shortcut_for_new_command(ipython_with_prompt): + matched = find_bindings_by_command(example_command) + assert len(matched) == 0 + + with pytest.raises(ValueError, match="example_command is not a known"): + ipython_with_prompt.shortcuts = [ + {"command": "example_command", "new_keys": ["x"]} + ] + matched = find_bindings_by_command(example_command) + assert len(matched) == 0 + + +def test_modify_shortcut_failure(ipython_with_prompt): + with pytest.raises(ValueError, match="No shortcuts matching"): + ipython_with_prompt.shortcuts = [ + { + "command": "IPython:auto_match.skip_over", + "match_keys": ["x"], + "new_keys": ["y"], + } + ] + + +def test_add_shortcut_for_existing_command(ipython_with_prompt): + matched = find_bindings_by_command(skip_over) + assert len(matched) == 5 + + with pytest.raises(ValueError, match="Cannot add a shortcut without keys"): + ipython_with_prompt.shortcuts = [ + {"command": "IPython:auto_match.skip_over", "new_keys": [], "create": True} + ] + + ipython_with_prompt.shortcuts = [ + {"command": "IPython:auto_match.skip_over", "new_keys": ["x"], "create": True} + ] + matched = find_bindings_by_command(skip_over) + assert len(matched) == 6 + + ipython_with_prompt.shortcuts = [] + matched = find_bindings_by_command(skip_over) + assert len(matched) == 5 + + +def test_setting_shortcuts_before_pt_app_init(): + ipython = get_ipython() + assert ipython.pt_app is None + shortcuts = [ + {"command": "IPython:auto_match.skip_over", "new_keys": ["x"], "create": True} + ] + ipython.shortcuts = shortcuts + assert ipython.shortcuts == shortcuts diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/__init__.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a47bbdd6aca8b99c1e8f79b07522c39c28f749a6 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/__init__.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/decorators.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/decorators.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5787a8763faadcfbb33a8cf87471056ce2de7e9f Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/decorators.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/globalipapp.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/globalipapp.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed638971f1339614a4ba333dce1406705b9de81e Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/globalipapp.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/ipunittest.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/ipunittest.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c32a160a95cc5955e6ec4a2bdbb0dd75852a50a Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/ipunittest.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/skipdoctest.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/skipdoctest.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38f1787ce9c4840ad6c7358340e16786cc05e5a5 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/skipdoctest.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/tools.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/tools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b460adf6353c6b81ccb20082d92921a8d9f8b5a8 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/tools.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/README.txt b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..a85e5a12a1061d6fa69a99e48f4b738654711815 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/README.txt @@ -0,0 +1,34 @@ +======================================================= + Nose plugin with IPython and extension module support +======================================================= + +This directory provides the key functionality for test support that IPython +needs as a nose plugin, which can be installed for use in projects other than +IPython. + +The presence of a Makefile here is mostly for development and debugging +purposes as it only provides a few shorthand commands. You can manually +install the plugin by using standard Python procedures (``setup.py install`` +with appropriate arguments). + +To install the plugin using the Makefile, edit its first line to reflect where +you'd like the installation. + +Once you've set the prefix, simply build/install the plugin with:: + + make + +and run the tests with:: + + make test + +You should see output similar to:: + + maqroll[plugin]> make test + nosetests -s --with-ipdoctest --doctest-tests dtexample.py + .. + ---------------------------------------------------------------------- + Ran 2 tests in 0.016s + + OK + diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__init__.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/__init__.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c76281809815dd895e351bbc8fa8c43c56ed8eb Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/__init__.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/dtexample.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/dtexample.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9825431032dd2b0df8284e550ac2c061d419de7 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/dtexample.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/ipdoctest.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/ipdoctest.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c3f49cbea3ea998b1312a8acbe27999101419d2 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/ipdoctest.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/pytest_ipdoctest.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/pytest_ipdoctest.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de2f4c42760ca0f3970e57445220cf8ce4de802f Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/pytest_ipdoctest.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/setup.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/setup.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae496d4f2c78132a0057a3fc3640f2fde0655d94 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/setup.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/simple.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/simple.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2057459243fc6cdef33a26ac8058c9170763a072 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/simple.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/simplevars.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/simplevars.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb4add4badfa98ecf37bc558df3eb54b62388872 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/simplevars.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/test_ipdoctest.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/test_ipdoctest.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e05bf835a6d93278c16ab17684214029c2176c4 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/test_ipdoctest.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/test_refs.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/test_refs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11314f953f7ed6f0c7c50d0188d9746876235af3 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/test_refs.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/dtexample.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/dtexample.py new file mode 100644 index 0000000000000000000000000000000000000000..68f7016e34dc57b9ae7aadfd028c36889fe36088 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/dtexample.py @@ -0,0 +1,167 @@ +"""Simple example using doctests. + +This file just contains doctests both using plain python and IPython prompts. +All tests should be loaded by nose. +""" + +import os + + +def pyfunc(): + """Some pure python tests... + + >>> pyfunc() + 'pyfunc' + + >>> import os + + >>> 2+3 + 5 + + >>> for i in range(3): + ... print(i, end=' ') + ... print(i+1, end=' ') + ... + 0 1 1 2 2 3 + """ + return 'pyfunc' + +def ipfunc(): + """Some ipython tests... + + In [1]: import os + + In [3]: 2+3 + Out[3]: 5 + + In [26]: for i in range(3): + ....: print(i, end=' ') + ....: print(i+1, end=' ') + ....: + 0 1 1 2 2 3 + + + It's OK to use '_' for the last result, but do NOT try to use IPython's + numbered history of _NN outputs, since those won't exist under the + doctest environment: + + In [7]: 'hi' + Out[7]: 'hi' + + In [8]: print(repr(_)) + 'hi' + + In [7]: 3+4 + Out[7]: 7 + + In [8]: _+3 + Out[8]: 10 + + In [9]: ipfunc() + Out[9]: 'ipfunc' + """ + return "ipfunc" + + +def ipos(): + """Examples that access the operating system work: + + In [1]: !echo hello + hello + + In [2]: !echo hello > /tmp/foo_iptest + + In [3]: !cat /tmp/foo_iptest + hello + + In [4]: rm -f /tmp/foo_iptest + """ + pass + + +ipos.__skip_doctest__ = os.name == "nt" + + +def ranfunc(): + """A function with some random output. + + Normal examples are verified as usual: + >>> 1+3 + 4 + + But if you put '# random' in the output, it is ignored: + >>> 1+3 + junk goes here... # random + + >>> 1+2 + again, anything goes #random + if multiline, the random mark is only needed once. + + >>> 1+2 + You can also put the random marker at the end: + # random + + >>> 1+2 + # random + .. or at the beginning. + + More correct input is properly verified: + >>> ranfunc() + 'ranfunc' + """ + return 'ranfunc' + + +def random_all(): + """A function where we ignore the output of ALL examples. + + Examples: + + # all-random + + This mark tells the testing machinery that all subsequent examples should + be treated as random (ignoring their output). They are still executed, + so if a they raise an error, it will be detected as such, but their + output is completely ignored. + + >>> 1+3 + junk goes here... + + >>> 1+3 + klasdfj; + + >>> 1+2 + again, anything goes + blah... + """ + pass + +def iprand(): + """Some ipython tests with random output. + + In [7]: 3+4 + Out[7]: 7 + + In [8]: print('hello') + world # random + + In [9]: iprand() + Out[9]: 'iprand' + """ + return 'iprand' + +def iprand_all(): + """Some ipython tests with fully random output. + + # all-random + + In [7]: 1 + Out[7]: 99 + + In [8]: print('hello') + world + + In [9]: iprand_all() + Out[9]: 'junk' + """ + return 'iprand_all' diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/ipdoctest.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/ipdoctest.py new file mode 100644 index 0000000000000000000000000000000000000000..0e6a7efa968d9c217087da0e2c6daca4c891aa95 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/ipdoctest.py @@ -0,0 +1,299 @@ +"""Nose Plugin that supports IPython doctests. + +Limitations: + +- When generating examples for use as doctests, make sure that you have + pretty-printing OFF. This can be done either by setting the + ``PlainTextFormatter.pprint`` option in your configuration file to False, or + by interactively disabling it with %Pprint. This is required so that IPython + output matches that of normal Python, which is used by doctest for internal + execution. + +- Do not rely on specific prompt numbers for results (such as using + '_34==True', for example). For IPython tests run via an external process the + prompt numbers may be different, and IPython tests run as normal python code + won't even have these special _NN variables set at all. +""" + +#----------------------------------------------------------------------------- +# Module imports + +# From the standard library +import doctest +import logging +import re + +from testpath import modified_env + +#----------------------------------------------------------------------------- +# Module globals and other constants +#----------------------------------------------------------------------------- + +log = logging.getLogger(__name__) + + +#----------------------------------------------------------------------------- +# Classes and functions +#----------------------------------------------------------------------------- + + +class DocTestFinder(doctest.DocTestFinder): + def _get_test(self, obj, name, module, globs, source_lines): + test = super()._get_test(obj, name, module, globs, source_lines) + + if bool(getattr(obj, "__skip_doctest__", False)) and test is not None: + for example in test.examples: + example.options[doctest.SKIP] = True + + return test + + +class IPDoctestOutputChecker(doctest.OutputChecker): + """Second-chance checker with support for random tests. + + If the default comparison doesn't pass, this checker looks in the expected + output string for flags that tell us to ignore the output. + """ + + random_re = re.compile(r'#\s*random\s+') + + def check_output(self, want, got, optionflags): + """Check output, accepting special markers embedded in the output. + + If the output didn't pass the default validation but the special string + '#random' is included, we accept it.""" + + # Let the original tester verify first, in case people have valid tests + # that happen to have a comment saying '#random' embedded in. + ret = doctest.OutputChecker.check_output(self, want, got, + optionflags) + if not ret and self.random_re.search(want): + # print('RANDOM OK:',want, file=sys.stderr) # dbg + return True + + return ret + + +# A simple subclassing of the original with a different class name, so we can +# distinguish and treat differently IPython examples from pure python ones. +class IPExample(doctest.Example): pass + + +class IPDocTestParser(doctest.DocTestParser): + """ + A class used to parse strings containing doctest examples. + + Note: This is a version modified to properly recognize IPython input and + convert any IPython examples into valid Python ones. + """ + # This regular expression is used to find doctest examples in a + # string. It defines three groups: `source` is the source code + # (including leading indentation and prompts); `indent` is the + # indentation of the first (PS1) line of the source code; and + # `want` is the expected output (including leading indentation). + + # Classic Python prompts or default IPython ones + _PS1_PY = r'>>>' + _PS2_PY = r'\.\.\.' + + _PS1_IP = r'In\ \[\d+\]:' + _PS2_IP = r'\ \ \ \.\.\.+:' + + _RE_TPL = r''' + # Source consists of a PS1 line followed by zero or more PS2 lines. + (?P + (?:^(?P [ ]*) (?P %s) .*) # PS1 line + (?:\n [ ]* (?P %s) .*)*) # PS2 lines + \n? # a newline + # Want consists of any non-blank lines that do not start with PS1. + (?P (?:(?![ ]*$) # Not a blank line + (?![ ]*%s) # Not a line starting with PS1 + (?![ ]*%s) # Not a line starting with PS2 + .*$\n? # But any other line + )*) + ''' + + _EXAMPLE_RE_PY = re.compile( _RE_TPL % (_PS1_PY,_PS2_PY,_PS1_PY,_PS2_PY), + re.MULTILINE | re.VERBOSE) + + _EXAMPLE_RE_IP = re.compile( _RE_TPL % (_PS1_IP,_PS2_IP,_PS1_IP,_PS2_IP), + re.MULTILINE | re.VERBOSE) + + # Mark a test as being fully random. In this case, we simply append the + # random marker ('#random') to each individual example's output. This way + # we don't need to modify any other code. + _RANDOM_TEST = re.compile(r'#\s*all-random\s+') + + def ip2py(self,source): + """Convert input IPython source into valid Python.""" + block = _ip.input_transformer_manager.transform_cell(source) + if len(block.splitlines()) == 1: + return _ip.prefilter(block) + else: + return block + + def parse(self, string, name=''): + """ + Divide the given string into examples and intervening text, + and return them as a list of alternating Examples and strings. + Line numbers for the Examples are 0-based. The optional + argument `name` is a name identifying this string, and is only + used for error messages. + """ + + # print('Parse string:\n',string) # dbg + + string = string.expandtabs() + # If all lines begin with the same indentation, then strip it. + min_indent = self._min_indent(string) + if min_indent > 0: + string = '\n'.join([l[min_indent:] for l in string.split('\n')]) + + output = [] + charno, lineno = 0, 0 + + # We make 'all random' tests by adding the '# random' mark to every + # block of output in the test. + if self._RANDOM_TEST.search(string): + random_marker = '\n# random' + else: + random_marker = '' + + # Whether to convert the input from ipython to python syntax + ip2py = False + # Find all doctest examples in the string. First, try them as Python + # examples, then as IPython ones + terms = list(self._EXAMPLE_RE_PY.finditer(string)) + if terms: + # Normal Python example + Example = doctest.Example + else: + # It's an ipython example. + terms = list(self._EXAMPLE_RE_IP.finditer(string)) + Example = IPExample + ip2py = True + + for m in terms: + # Add the pre-example text to `output`. + output.append(string[charno:m.start()]) + # Update lineno (lines before this example) + lineno += string.count('\n', charno, m.start()) + # Extract info from the regexp match. + (source, options, want, exc_msg) = \ + self._parse_example(m, name, lineno,ip2py) + + # Append the random-output marker (it defaults to empty in most + # cases, it's only non-empty for 'all-random' tests): + want += random_marker + + # Create an Example, and add it to the list. + if not self._IS_BLANK_OR_COMMENT(source): + output.append(Example(source, want, exc_msg, + lineno=lineno, + indent=min_indent+len(m.group('indent')), + options=options)) + # Update lineno (lines inside this example) + lineno += string.count('\n', m.start(), m.end()) + # Update charno. + charno = m.end() + # Add any remaining post-example text to `output`. + output.append(string[charno:]) + return output + + def _parse_example(self, m, name, lineno,ip2py=False): + """ + Given a regular expression match from `_EXAMPLE_RE` (`m`), + return a pair `(source, want)`, where `source` is the matched + example's source code (with prompts and indentation stripped); + and `want` is the example's expected output (with indentation + stripped). + + `name` is the string's name, and `lineno` is the line number + where the example starts; both are used for error messages. + + Optional: + `ip2py`: if true, filter the input via IPython to convert the syntax + into valid python. + """ + + # Get the example's indentation level. + indent = len(m.group('indent')) + + # Divide source into lines; check that they're properly + # indented; and then strip their indentation & prompts. + source_lines = m.group('source').split('\n') + + # We're using variable-length input prompts + ps1 = m.group('ps1') + ps2 = m.group('ps2') + ps1_len = len(ps1) + + self._check_prompt_blank(source_lines, indent, name, lineno,ps1_len) + if ps2: + self._check_prefix(source_lines[1:], ' '*indent + ps2, name, lineno) + + source = '\n'.join([sl[indent+ps1_len+1:] for sl in source_lines]) + + if ip2py: + # Convert source input from IPython into valid Python syntax + source = self.ip2py(source) + + # Divide want into lines; check that it's properly indented; and + # then strip the indentation. Spaces before the last newline should + # be preserved, so plain rstrip() isn't good enough. + want = m.group('want') + want_lines = want.split('\n') + if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]): + del want_lines[-1] # forget final newline & spaces after it + self._check_prefix(want_lines, ' '*indent, name, + lineno + len(source_lines)) + + # Remove ipython output prompt that might be present in the first line + want_lines[0] = re.sub(r'Out\[\d+\]: \s*?\n?','',want_lines[0]) + + want = '\n'.join([wl[indent:] for wl in want_lines]) + + # If `want` contains a traceback message, then extract it. + m = self._EXCEPTION_RE.match(want) + if m: + exc_msg = m.group('msg') + else: + exc_msg = None + + # Extract options from the source. + options = self._find_options(source, name, lineno) + + return source, options, want, exc_msg + + def _check_prompt_blank(self, lines, indent, name, lineno, ps1_len): + """ + Given the lines of a source string (including prompts and + leading indentation), check to make sure that every prompt is + followed by a space character. If any line is not followed by + a space character, then raise ValueError. + + Note: IPython-modified version which takes the input prompt length as a + parameter, so that prompts of variable length can be dealt with. + """ + space_idx = indent+ps1_len + min_len = space_idx+1 + for i, line in enumerate(lines): + if len(line) >= min_len and line[space_idx] != ' ': + raise ValueError('line %r of the docstring for %s ' + 'lacks blank after %s: %r' % + (lineno+i+1, name, + line[indent:space_idx], line)) + + +SKIP = doctest.register_optionflag('SKIP') + + +class IPDocTestRunner(doctest.DocTestRunner,object): + """Test runner that synchronizes the IPython namespace with test globals. + """ + + def run(self, test, compileflags=None, out=None, clear_globs=True): + # Override terminal size to standardise traceback format + with modified_env({'COLUMNS': '80', 'LINES': '24'}): + return super(IPDocTestRunner,self).run(test, + compileflags,out,clear_globs) diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/pytest_ipdoctest.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/pytest_ipdoctest.py new file mode 100644 index 0000000000000000000000000000000000000000..40a3ae92b404f8d80d0f6bd268c0bd7435e17625 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/pytest_ipdoctest.py @@ -0,0 +1,879 @@ +# Based on Pytest doctest.py +# Original license: +# The MIT License (MIT) +# +# Copyright (c) 2004-2021 Holger Krekel and others +"""Discover and run ipdoctests in modules and test files.""" +import bdb +import builtins +import inspect +import os +import platform +import sys +import traceback +import types +import warnings +from contextlib import contextmanager +from pathlib import Path +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Generator, + Iterable, + List, + Optional, + Pattern, + Sequence, + Tuple, + Type, + Union, +) + +import pytest +from _pytest import outcomes +from _pytest._code.code import ExceptionInfo, ReprFileLocation, TerminalRepr +from _pytest._io import TerminalWriter +from _pytest.compat import safe_getattr +from _pytest.config import Config +from _pytest.config.argparsing import Parser + +try: + from _pytest.fixtures import TopRequest as FixtureRequest +except ImportError: + from _pytest.fixtures import FixtureRequest +from _pytest.nodes import Collector +from _pytest.outcomes import OutcomeException +from _pytest.pathlib import fnmatch_ex, import_path +from _pytest.python_api import approx +from _pytest.warning_types import PytestWarning + +if TYPE_CHECKING: + import doctest + + from .ipdoctest import IPDoctestOutputChecker + +DOCTEST_REPORT_CHOICE_NONE = "none" +DOCTEST_REPORT_CHOICE_CDIFF = "cdiff" +DOCTEST_REPORT_CHOICE_NDIFF = "ndiff" +DOCTEST_REPORT_CHOICE_UDIFF = "udiff" +DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE = "only_first_failure" + +DOCTEST_REPORT_CHOICES = ( + DOCTEST_REPORT_CHOICE_NONE, + DOCTEST_REPORT_CHOICE_CDIFF, + DOCTEST_REPORT_CHOICE_NDIFF, + DOCTEST_REPORT_CHOICE_UDIFF, + DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE, +) + +# Lazy definition of runner class +RUNNER_CLASS = None +# Lazy definition of output checker class +CHECKER_CLASS: Optional[Type["IPDoctestOutputChecker"]] = None + +pytest_version = tuple([int(part) for part in pytest.__version__.split(".")]) + + +def pytest_addoption(parser: Parser) -> None: + parser.addini( + "ipdoctest_optionflags", + "option flags for ipdoctests", + type="args", + default=["ELLIPSIS"], + ) + parser.addini( + "ipdoctest_encoding", "encoding used for ipdoctest files", default="utf-8" + ) + group = parser.getgroup("collect") + group.addoption( + "--ipdoctest-modules", + action="store_true", + default=False, + help="run ipdoctests in all .py modules", + dest="ipdoctestmodules", + ) + group.addoption( + "--ipdoctest-report", + type=str.lower, + default="udiff", + help="choose another output format for diffs on ipdoctest failure", + choices=DOCTEST_REPORT_CHOICES, + dest="ipdoctestreport", + ) + group.addoption( + "--ipdoctest-glob", + action="append", + default=[], + metavar="pat", + help="ipdoctests file matching pattern, default: test*.txt", + dest="ipdoctestglob", + ) + group.addoption( + "--ipdoctest-ignore-import-errors", + action="store_true", + default=False, + help="ignore ipdoctest ImportErrors", + dest="ipdoctest_ignore_import_errors", + ) + group.addoption( + "--ipdoctest-continue-on-failure", + action="store_true", + default=False, + help="for a given ipdoctest, continue to run after the first failure", + dest="ipdoctest_continue_on_failure", + ) + + +def pytest_unconfigure() -> None: + global RUNNER_CLASS + + RUNNER_CLASS = None + + +def pytest_collect_file( + file_path: Path, + parent: Collector, +) -> Optional[Union["IPDoctestModule", "IPDoctestTextfile"]]: + config = parent.config + if file_path.suffix == ".py": + if config.option.ipdoctestmodules and not any( + (_is_setup_py(file_path), _is_main_py(file_path)) + ): + mod: IPDoctestModule = IPDoctestModule.from_parent(parent, path=file_path) + return mod + elif _is_ipdoctest(config, file_path, parent): + txt: IPDoctestTextfile = IPDoctestTextfile.from_parent(parent, path=file_path) + return txt + return None + + +if pytest_version[0] < 7: + _collect_file = pytest_collect_file + + def pytest_collect_file( + path, + parent: Collector, + ) -> Optional[Union["IPDoctestModule", "IPDoctestTextfile"]]: + return _collect_file(Path(path), parent) + + _import_path = import_path + + def import_path(path, root): + import py.path + + return _import_path(py.path.local(path)) + + +def _is_setup_py(path: Path) -> bool: + if path.name != "setup.py": + return False + contents = path.read_bytes() + return b"setuptools" in contents or b"distutils" in contents + + +def _is_ipdoctest(config: Config, path: Path, parent: Collector) -> bool: + if path.suffix in (".txt", ".rst") and parent.session.isinitpath(path): + return True + globs = config.getoption("ipdoctestglob") or ["test*.txt"] + return any(fnmatch_ex(glob, path) for glob in globs) + + +def _is_main_py(path: Path) -> bool: + return path.name == "__main__.py" + + +class ReprFailDoctest(TerminalRepr): + def __init__( + self, reprlocation_lines: Sequence[Tuple[ReprFileLocation, Sequence[str]]] + ) -> None: + self.reprlocation_lines = reprlocation_lines + + def toterminal(self, tw: TerminalWriter) -> None: + for reprlocation, lines in self.reprlocation_lines: + for line in lines: + tw.line(line) + reprlocation.toterminal(tw) + + +class MultipleDoctestFailures(Exception): + def __init__(self, failures: Sequence["doctest.DocTestFailure"]) -> None: + super().__init__() + self.failures = failures + + +def _init_runner_class() -> Type["IPDocTestRunner"]: + import doctest + from .ipdoctest import IPDocTestRunner + + class PytestDoctestRunner(IPDocTestRunner): + """Runner to collect failures. + + Note that the out variable in this case is a list instead of a + stdout-like object. + """ + + def __init__( + self, + checker: Optional["IPDoctestOutputChecker"] = None, + verbose: Optional[bool] = None, + optionflags: int = 0, + continue_on_failure: bool = True, + ) -> None: + super().__init__(checker=checker, verbose=verbose, optionflags=optionflags) + self.continue_on_failure = continue_on_failure + + def report_failure( + self, + out, + test: "doctest.DocTest", + example: "doctest.Example", + got: str, + ) -> None: + failure = doctest.DocTestFailure(test, example, got) + if self.continue_on_failure: + out.append(failure) + else: + raise failure + + def report_unexpected_exception( + self, + out, + test: "doctest.DocTest", + example: "doctest.Example", + exc_info: Tuple[Type[BaseException], BaseException, types.TracebackType], + ) -> None: + if isinstance(exc_info[1], OutcomeException): + raise exc_info[1] + if isinstance(exc_info[1], bdb.BdbQuit): + outcomes.exit("Quitting debugger") + failure = doctest.UnexpectedException(test, example, exc_info) + if self.continue_on_failure: + out.append(failure) + else: + raise failure + + return PytestDoctestRunner + + +def _get_runner( + checker: Optional["IPDoctestOutputChecker"] = None, + verbose: Optional[bool] = None, + optionflags: int = 0, + continue_on_failure: bool = True, +) -> "IPDocTestRunner": + # We need this in order to do a lazy import on doctest + global RUNNER_CLASS + if RUNNER_CLASS is None: + RUNNER_CLASS = _init_runner_class() + # Type ignored because the continue_on_failure argument is only defined on + # PytestDoctestRunner, which is lazily defined so can't be used as a type. + return RUNNER_CLASS( # type: ignore + checker=checker, + verbose=verbose, + optionflags=optionflags, + continue_on_failure=continue_on_failure, + ) + + +class IPDoctestItem(pytest.Item): + _user_ns_orig: Dict[str, Any] + + def __init__( + self, + name: str, + parent: "Union[IPDoctestTextfile, IPDoctestModule]", + runner: Optional["IPDocTestRunner"] = None, + dtest: Optional["doctest.DocTest"] = None, + ) -> None: + super().__init__(name, parent) + self.runner = runner + self.dtest = dtest + self.obj = None + self.fixture_request: Optional[FixtureRequest] = None + self._user_ns_orig = {} + + @classmethod + def from_parent( # type: ignore + cls, + parent: "Union[IPDoctestTextfile, IPDoctestModule]", + *, + name: str, + runner: "IPDocTestRunner", + dtest: "doctest.DocTest", + ): + # incompatible signature due to imposed limits on subclass + """The public named constructor.""" + return super().from_parent(name=name, parent=parent, runner=runner, dtest=dtest) + + def setup(self) -> None: + if self.dtest is not None: + self.fixture_request = _setup_fixtures(self) + globs = dict(getfixture=self.fixture_request.getfixturevalue) + for name, value in self.fixture_request.getfixturevalue( + "ipdoctest_namespace" + ).items(): + globs[name] = value + self.dtest.globs.update(globs) + + from .ipdoctest import IPExample + + if isinstance(self.dtest.examples[0], IPExample): + # for IPython examples *only*, we swap the globals with the ipython + # namespace, after updating it with the globals (which doctest + # fills with the necessary info from the module being tested). + self._user_ns_orig = {} + self._user_ns_orig.update(_ip.user_ns) + _ip.user_ns.update(self.dtest.globs) + # We must remove the _ key in the namespace, so that Python's + # doctest code sets it naturally + _ip.user_ns.pop("_", None) + _ip.user_ns["__builtins__"] = builtins + self.dtest.globs = _ip.user_ns + + def teardown(self) -> None: + from .ipdoctest import IPExample + + # Undo the test.globs reassignment we made + if isinstance(self.dtest.examples[0], IPExample): + self.dtest.globs = {} + _ip.user_ns.clear() + _ip.user_ns.update(self._user_ns_orig) + del self._user_ns_orig + + self.dtest.globs.clear() + + def runtest(self) -> None: + assert self.dtest is not None + assert self.runner is not None + _check_all_skipped(self.dtest) + self._disable_output_capturing_for_darwin() + failures: List["doctest.DocTestFailure"] = [] + + # exec(compile(..., "single", ...), ...) puts result in builtins._ + had_underscore_value = hasattr(builtins, "_") + underscore_original_value = getattr(builtins, "_", None) + + # Save our current directory and switch out to the one where the + # test was originally created, in case another doctest did a + # directory change. We'll restore this in the finally clause. + curdir = os.getcwd() + os.chdir(self.fspath.dirname) + try: + # Type ignored because we change the type of `out` from what + # ipdoctest expects. + self.runner.run(self.dtest, out=failures, clear_globs=False) # type: ignore[arg-type] + finally: + os.chdir(curdir) + if had_underscore_value: + setattr(builtins, "_", underscore_original_value) + elif hasattr(builtins, "_"): + delattr(builtins, "_") + + if failures: + raise MultipleDoctestFailures(failures) + + def _disable_output_capturing_for_darwin(self) -> None: + """Disable output capturing. Otherwise, stdout is lost to ipdoctest (pytest#985).""" + if platform.system() != "Darwin": + return + capman = self.config.pluginmanager.getplugin("capturemanager") + if capman: + capman.suspend_global_capture(in_=True) + out, err = capman.read_global_capture() + sys.stdout.write(out) + sys.stderr.write(err) + + # TODO: Type ignored -- breaks Liskov Substitution. + def repr_failure( # type: ignore[override] + self, + excinfo: ExceptionInfo[BaseException], + ) -> Union[str, TerminalRepr]: + import doctest + + failures: Optional[ + Sequence[Union[doctest.DocTestFailure, doctest.UnexpectedException]] + ] = None + if isinstance( + excinfo.value, (doctest.DocTestFailure, doctest.UnexpectedException) + ): + failures = [excinfo.value] + elif isinstance(excinfo.value, MultipleDoctestFailures): + failures = excinfo.value.failures + + if failures is None: + return super().repr_failure(excinfo) + + reprlocation_lines = [] + for failure in failures: + example = failure.example + test = failure.test + filename = test.filename + if test.lineno is None: + lineno = None + else: + lineno = test.lineno + example.lineno + 1 + message = type(failure).__name__ + # TODO: ReprFileLocation doesn't expect a None lineno. + reprlocation = ReprFileLocation(filename, lineno, message) # type: ignore[arg-type] + checker = _get_checker() + report_choice = _get_report_choice(self.config.getoption("ipdoctestreport")) + if lineno is not None: + assert failure.test.docstring is not None + lines = failure.test.docstring.splitlines(False) + # add line numbers to the left of the error message + assert test.lineno is not None + lines = [ + "%03d %s" % (i + test.lineno + 1, x) for (i, x) in enumerate(lines) + ] + # trim docstring error lines to 10 + lines = lines[max(example.lineno - 9, 0) : example.lineno + 1] + else: + lines = [ + "EXAMPLE LOCATION UNKNOWN, not showing all tests of that example" + ] + indent = ">>>" + for line in example.source.splitlines(): + lines.append(f"??? {indent} {line}") + indent = "..." + if isinstance(failure, doctest.DocTestFailure): + lines += checker.output_difference( + example, failure.got, report_choice + ).split("\n") + else: + inner_excinfo = ExceptionInfo.from_exc_info(failure.exc_info) + lines += ["UNEXPECTED EXCEPTION: %s" % repr(inner_excinfo.value)] + lines += [ + x.strip("\n") for x in traceback.format_exception(*failure.exc_info) + ] + reprlocation_lines.append((reprlocation, lines)) + return ReprFailDoctest(reprlocation_lines) + + def reportinfo(self) -> Tuple[Union["os.PathLike[str]", str], Optional[int], str]: + assert self.dtest is not None + return self.path, self.dtest.lineno, "[ipdoctest] %s" % self.name + + if pytest_version[0] < 7: + + @property + def path(self) -> Path: + return Path(self.fspath) + + +def _get_flag_lookup() -> Dict[str, int]: + import doctest + + return dict( + DONT_ACCEPT_TRUE_FOR_1=doctest.DONT_ACCEPT_TRUE_FOR_1, + DONT_ACCEPT_BLANKLINE=doctest.DONT_ACCEPT_BLANKLINE, + NORMALIZE_WHITESPACE=doctest.NORMALIZE_WHITESPACE, + ELLIPSIS=doctest.ELLIPSIS, + IGNORE_EXCEPTION_DETAIL=doctest.IGNORE_EXCEPTION_DETAIL, + COMPARISON_FLAGS=doctest.COMPARISON_FLAGS, + ALLOW_UNICODE=_get_allow_unicode_flag(), + ALLOW_BYTES=_get_allow_bytes_flag(), + NUMBER=_get_number_flag(), + ) + + +def get_optionflags(parent): + optionflags_str = parent.config.getini("ipdoctest_optionflags") + flag_lookup_table = _get_flag_lookup() + flag_acc = 0 + for flag in optionflags_str: + flag_acc |= flag_lookup_table[flag] + return flag_acc + + +def _get_continue_on_failure(config): + continue_on_failure = config.getvalue("ipdoctest_continue_on_failure") + if continue_on_failure: + # We need to turn off this if we use pdb since we should stop at + # the first failure. + if config.getvalue("usepdb"): + continue_on_failure = False + return continue_on_failure + + +class IPDoctestTextfile(pytest.Module): + obj = None + + def collect(self) -> Iterable[IPDoctestItem]: + import doctest + from .ipdoctest import IPDocTestParser + + # Inspired by doctest.testfile; ideally we would use it directly, + # but it doesn't support passing a custom checker. + encoding = self.config.getini("ipdoctest_encoding") + text = self.path.read_text(encoding) + filename = str(self.path) + name = self.path.name + globs = {"__name__": "__main__"} + + optionflags = get_optionflags(self) + + runner = _get_runner( + verbose=False, + optionflags=optionflags, + checker=_get_checker(), + continue_on_failure=_get_continue_on_failure(self.config), + ) + + parser = IPDocTestParser() + test = parser.get_doctest(text, globs, name, filename, 0) + if test.examples: + yield IPDoctestItem.from_parent( + self, name=test.name, runner=runner, dtest=test + ) + + if pytest_version[0] < 7: + + @property + def path(self) -> Path: + return Path(self.fspath) + + @classmethod + def from_parent( + cls, + parent, + *, + fspath=None, + path: Optional[Path] = None, + **kw, + ): + if path is not None: + import py.path + + fspath = py.path.local(path) + return super().from_parent(parent=parent, fspath=fspath, **kw) + + +def _check_all_skipped(test: "doctest.DocTest") -> None: + """Raise pytest.skip() if all examples in the given DocTest have the SKIP + option set.""" + import doctest + + all_skipped = all(x.options.get(doctest.SKIP, False) for x in test.examples) + if all_skipped: + pytest.skip("all docstests skipped by +SKIP option") + + +def _is_mocked(obj: object) -> bool: + """Return if an object is possibly a mock object by checking the + existence of a highly improbable attribute.""" + return ( + safe_getattr(obj, "pytest_mock_example_attribute_that_shouldnt_exist", None) + is not None + ) + + +@contextmanager +def _patch_unwrap_mock_aware() -> Generator[None, None, None]: + """Context manager which replaces ``inspect.unwrap`` with a version + that's aware of mock objects and doesn't recurse into them.""" + real_unwrap = inspect.unwrap + + def _mock_aware_unwrap( + func: Callable[..., Any], *, stop: Optional[Callable[[Any], Any]] = None + ) -> Any: + try: + if stop is None or stop is _is_mocked: + return real_unwrap(func, stop=_is_mocked) + _stop = stop + return real_unwrap(func, stop=lambda obj: _is_mocked(obj) or _stop(func)) + except Exception as e: + warnings.warn( + "Got %r when unwrapping %r. This is usually caused " + "by a violation of Python's object protocol; see e.g. " + "https://github.com/pytest-dev/pytest/issues/5080" % (e, func), + PytestWarning, + ) + raise + + inspect.unwrap = _mock_aware_unwrap + try: + yield + finally: + inspect.unwrap = real_unwrap + + +class IPDoctestModule(pytest.Module): + def collect(self) -> Iterable[IPDoctestItem]: + import doctest + from .ipdoctest import DocTestFinder, IPDocTestParser + + class MockAwareDocTestFinder(DocTestFinder): + """A hackish ipdoctest finder that overrides stdlib internals to fix a stdlib bug. + + https://github.com/pytest-dev/pytest/issues/3456 + https://bugs.python.org/issue25532 + """ + + def _find_lineno(self, obj, source_lines): + """Doctest code does not take into account `@property`, this + is a hackish way to fix it. https://bugs.python.org/issue17446 + + Wrapped Doctests will need to be unwrapped so the correct + line number is returned. This will be reported upstream. #8796 + """ + if isinstance(obj, property): + obj = getattr(obj, "fget", obj) + + if hasattr(obj, "__wrapped__"): + # Get the main obj in case of it being wrapped + obj = inspect.unwrap(obj) + + # Type ignored because this is a private function. + return super()._find_lineno( # type:ignore[misc] + obj, + source_lines, + ) + + def _find( + self, tests, obj, name, module, source_lines, globs, seen + ) -> None: + if _is_mocked(obj): + return + with _patch_unwrap_mock_aware(): + # Type ignored because this is a private function. + super()._find( # type:ignore[misc] + tests, obj, name, module, source_lines, globs, seen + ) + + if self.path.name == "conftest.py": + if pytest_version[0] < 7: + module = self.config.pluginmanager._importconftest( + self.path, + self.config.getoption("importmode"), + ) + else: + kwargs = {"rootpath": self.config.rootpath} + if pytest_version >= (8, 1): + kwargs["consider_namespace_packages"] = False + module = self.config.pluginmanager._importconftest( + self.path, + self.config.getoption("importmode"), + **kwargs, + ) + else: + try: + kwargs = {"root": self.config.rootpath} + if pytest_version >= (8, 1): + kwargs["consider_namespace_packages"] = False + module = import_path(self.path, **kwargs) + except ImportError: + if self.config.getvalue("ipdoctest_ignore_import_errors"): + pytest.skip("unable to import module %r" % self.path) + else: + raise + # Uses internal doctest module parsing mechanism. + finder = MockAwareDocTestFinder(parser=IPDocTestParser()) + optionflags = get_optionflags(self) + runner = _get_runner( + verbose=False, + optionflags=optionflags, + checker=_get_checker(), + continue_on_failure=_get_continue_on_failure(self.config), + ) + + for test in finder.find(module, module.__name__): + if test.examples: # skip empty ipdoctests + yield IPDoctestItem.from_parent( + self, name=test.name, runner=runner, dtest=test + ) + + if pytest_version[0] < 7: + + @property + def path(self) -> Path: + return Path(self.fspath) + + @classmethod + def from_parent( + cls, + parent, + *, + fspath=None, + path: Optional[Path] = None, + **kw, + ): + if path is not None: + import py.path + + fspath = py.path.local(path) + return super().from_parent(parent=parent, fspath=fspath, **kw) + + +def _setup_fixtures(doctest_item: IPDoctestItem) -> FixtureRequest: + """Used by IPDoctestTextfile and IPDoctestItem to setup fixture information.""" + + def func() -> None: + pass + + doctest_item.funcargs = {} # type: ignore[attr-defined] + fm = doctest_item.session._fixturemanager + kwargs = {"node": doctest_item, "func": func, "cls": None} + if pytest_version <= (8, 0): + kwargs["funcargs"] = False + doctest_item._fixtureinfo = fm.getfixtureinfo( # type: ignore[attr-defined] + **kwargs + ) + fixture_request = FixtureRequest(doctest_item, _ispytest=True) + if pytest_version <= (8, 0): + fixture_request._fillfixtures() + return fixture_request + + +def _init_checker_class() -> Type["IPDoctestOutputChecker"]: + import doctest + import re + from .ipdoctest import IPDoctestOutputChecker + + class LiteralsOutputChecker(IPDoctestOutputChecker): + # Based on doctest_nose_plugin.py from the nltk project + # (https://github.com/nltk/nltk) and on the "numtest" doctest extension + # by Sebastien Boisgerault (https://github.com/boisgera/numtest). + + _unicode_literal_re = re.compile(r"(\W|^)[uU]([rR]?[\'\"])", re.UNICODE) + _bytes_literal_re = re.compile(r"(\W|^)[bB]([rR]?[\'\"])", re.UNICODE) + _number_re = re.compile( + r""" + (?P + (?P + (?P [+-]?\d*)\.(?P\d+) + | + (?P [+-]?\d+)\. + ) + (?: + [Ee] + (?P [+-]?\d+) + )? + | + (?P [+-]?\d+) + (?: + [Ee] + (?P [+-]?\d+) + ) + ) + """, + re.VERBOSE, + ) + + def check_output(self, want: str, got: str, optionflags: int) -> bool: + if super().check_output(want, got, optionflags): + return True + + allow_unicode = optionflags & _get_allow_unicode_flag() + allow_bytes = optionflags & _get_allow_bytes_flag() + allow_number = optionflags & _get_number_flag() + + if not allow_unicode and not allow_bytes and not allow_number: + return False + + def remove_prefixes(regex: Pattern[str], txt: str) -> str: + return re.sub(regex, r"\1\2", txt) + + if allow_unicode: + want = remove_prefixes(self._unicode_literal_re, want) + got = remove_prefixes(self._unicode_literal_re, got) + + if allow_bytes: + want = remove_prefixes(self._bytes_literal_re, want) + got = remove_prefixes(self._bytes_literal_re, got) + + if allow_number: + got = self._remove_unwanted_precision(want, got) + + return super().check_output(want, got, optionflags) + + def _remove_unwanted_precision(self, want: str, got: str) -> str: + wants = list(self._number_re.finditer(want)) + gots = list(self._number_re.finditer(got)) + if len(wants) != len(gots): + return got + offset = 0 + for w, g in zip(wants, gots): + fraction: Optional[str] = w.group("fraction") + exponent: Optional[str] = w.group("exponent1") + if exponent is None: + exponent = w.group("exponent2") + precision = 0 if fraction is None else len(fraction) + if exponent is not None: + precision -= int(exponent) + if float(w.group()) == approx(float(g.group()), abs=10**-precision): + # They're close enough. Replace the text we actually + # got with the text we want, so that it will match when we + # check the string literally. + got = ( + got[: g.start() + offset] + w.group() + got[g.end() + offset :] + ) + offset += w.end() - w.start() - (g.end() - g.start()) + return got + + return LiteralsOutputChecker + + +def _get_checker() -> "IPDoctestOutputChecker": + """Return a IPDoctestOutputChecker subclass that supports some + additional options: + + * ALLOW_UNICODE and ALLOW_BYTES options to ignore u'' and b'' + prefixes (respectively) in string literals. Useful when the same + ipdoctest should run in Python 2 and Python 3. + + * NUMBER to ignore floating-point differences smaller than the + precision of the literal number in the ipdoctest. + + An inner class is used to avoid importing "ipdoctest" at the module + level. + """ + global CHECKER_CLASS + if CHECKER_CLASS is None: + CHECKER_CLASS = _init_checker_class() + return CHECKER_CLASS() + + +def _get_allow_unicode_flag() -> int: + """Register and return the ALLOW_UNICODE flag.""" + import doctest + + return doctest.register_optionflag("ALLOW_UNICODE") + + +def _get_allow_bytes_flag() -> int: + """Register and return the ALLOW_BYTES flag.""" + import doctest + + return doctest.register_optionflag("ALLOW_BYTES") + + +def _get_number_flag() -> int: + """Register and return the NUMBER flag.""" + import doctest + + return doctest.register_optionflag("NUMBER") + + +def _get_report_choice(key: str) -> int: + """Return the actual `ipdoctest` module flag value. + + We want to do it as late as possible to avoid importing `ipdoctest` and all + its dependencies when parsing options, as it adds overhead and breaks tests. + """ + import doctest + + return { + DOCTEST_REPORT_CHOICE_UDIFF: doctest.REPORT_UDIFF, + DOCTEST_REPORT_CHOICE_CDIFF: doctest.REPORT_CDIFF, + DOCTEST_REPORT_CHOICE_NDIFF: doctest.REPORT_NDIFF, + DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE: doctest.REPORT_ONLY_FIRST_FAILURE, + DOCTEST_REPORT_CHOICE_NONE: 0, + }[key] + + +@pytest.fixture(scope="session") +def ipdoctest_namespace() -> Dict[str, Any]: + """Fixture that returns a :py:class:`dict` that will be injected into the + namespace of ipdoctests.""" + return dict() diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/setup.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..a3281d30c8da509f46859b56ee66658e66156e84 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/setup.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +"""A Nose plugin to support IPython doctests. +""" + +from setuptools import setup + +setup(name='IPython doctest plugin', + version='0.1', + author='The IPython Team', + description = 'Nose plugin to load IPython-extended doctests', + license = 'LGPL', + py_modules = ['ipdoctest'], + entry_points = { + 'nose.plugins.0.10': ['ipdoctest = ipdoctest:IPythonDoctest', + 'extdoctest = ipdoctest:ExtensionDoctest', + ], + }, + ) diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/simple.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/simple.py new file mode 100644 index 0000000000000000000000000000000000000000..35fbfd2fbdced20195bd18a37218fb909cc9b83c --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/simple.py @@ -0,0 +1,44 @@ +"""Simple example using doctests. + +This file just contains doctests both using plain python and IPython prompts. +All tests should be loaded by Pytest. +""" + +def pyfunc(): + """Some pure python tests... + + >>> pyfunc() + 'pyfunc' + + >>> import os + + >>> 2+3 + 5 + + >>> for i in range(3): + ... print(i, end=' ') + ... print(i+1, end=' ') + ... + 0 1 1 2 2 3 + """ + return 'pyfunc' + + +def ipyfunc(): + """Some IPython tests... + + In [1]: ipyfunc() + Out[1]: 'ipyfunc' + + In [2]: import os + + In [3]: 2+3 + Out[3]: 5 + + In [4]: for i in range(3): + ...: print(i, end=' ') + ...: print(i+1, end=' ') + ...: + Out[4]: 0 1 1 2 2 3 + """ + return "ipyfunc" diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/simplevars.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/simplevars.py new file mode 100644 index 0000000000000000000000000000000000000000..82a5edb028dada24662962811ff975d74d1c3a10 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/simplevars.py @@ -0,0 +1,2 @@ +x = 1 +print("x is:", x) diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/test_combo.txt b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/test_combo.txt new file mode 100644 index 0000000000000000000000000000000000000000..6c8759f3e72ae3f1aea989826f58ca6863337435 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/test_combo.txt @@ -0,0 +1,36 @@ +======================= + Combo testing example +======================= + +This is a simple example that mixes ipython doctests:: + + In [1]: import code + + In [2]: 2**12 + Out[2]: 4096 + +with command-line example information that does *not* get executed:: + + $ mpirun -n 4 ipengine --controller-port=10000 --controller-ip=host0 + +and with literal examples of Python source code:: + + controller = dict(host='myhost', + engine_port=None, # default is 10105 + control_port=None, + ) + + # keys are hostnames, values are the number of engine on that host + engines = dict(node1=2, + node2=2, + node3=2, + node3=2, + ) + + # Force failure to detect that this test is being run. + 1/0 + +These source code examples are executed but no output is compared at all. An +error or failure is reported only if an exception is raised. + +NOTE: the execution of pure python blocks is not yet working! diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/test_example.txt b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/test_example.txt new file mode 100644 index 0000000000000000000000000000000000000000..f8b681eb4ff4410bc9d66a66ba77ee2c6dea6d12 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/test_example.txt @@ -0,0 +1,24 @@ +===================================== + Tests in example form - pure python +===================================== + +This file contains doctest examples embedded as code blocks, using normal +Python prompts. See the accompanying file for similar examples using IPython +prompts (you can't mix both types within one file). The following will be run +as a test:: + + >>> 1+1 + 2 + >>> print ("hello") + hello + +More than one example works:: + + >>> s="Hello World" + + >>> s.upper() + 'HELLO WORLD' + +but you should note that the *entire* test file is considered to be a single +test. Individual code blocks that fail are printed separately as ``example +failures``, but the whole file is still counted and reported as one test. diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/test_exampleip.txt b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/test_exampleip.txt new file mode 100644 index 0000000000000000000000000000000000000000..96b1eae19f09fb62702f5ee58851f4cad87aa9d5 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/test_exampleip.txt @@ -0,0 +1,30 @@ +================================= + Tests in example form - IPython +================================= + +You can write text files with examples that use IPython prompts (as long as you +use the nose ipython doctest plugin), but you can not mix and match prompt +styles in a single file. That is, you either use all ``>>>`` prompts or all +IPython-style prompts. Your test suite *can* have both types, you just need to +put each type of example in a separate. Using IPython prompts, you can paste +directly from your session:: + + In [5]: s="Hello World" + + In [6]: s.upper() + Out[6]: 'HELLO WORLD' + +Another example:: + + In [8]: 1+3 + Out[8]: 4 + +Just like in IPython docstrings, you can use all IPython syntax and features:: + + In [9]: !echo hello + hello + + In [10]: a='hi' + + In [11]: !echo $a + hi diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/test_ipdoctest.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/test_ipdoctest.py new file mode 100644 index 0000000000000000000000000000000000000000..2686172bb29e50c9fe824ef9f31b1d3badb1c7b4 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/test_ipdoctest.py @@ -0,0 +1,92 @@ +"""Tests for the ipdoctest machinery itself. + +Note: in a file named test_X, functions whose only test is their docstring (as +a doctest) and which have no test functionality of their own, should be called +'doctest_foo' instead of 'test_foo', otherwise they get double-counted (the +empty function call is counted as a test, which just inflates tests numbers +artificially). +""" + +def doctest_simple(): + """ipdoctest must handle simple inputs + + In [1]: 1 + Out[1]: 1 + + In [2]: print(1) + 1 + """ + +def doctest_multiline1(): + """The ipdoctest machinery must handle multiline examples gracefully. + + In [2]: for i in range(4): + ...: print(i) + ...: + 0 + 1 + 2 + 3 + """ + +def doctest_multiline2(): + """Multiline examples that define functions and print output. + + In [7]: def f(x): + ...: return x+1 + ...: + + In [8]: f(1) + Out[8]: 2 + + In [9]: def g(x): + ...: print('x is:',x) + ...: + + In [10]: g(1) + x is: 1 + + In [11]: g('hello') + x is: hello + """ + + +def doctest_multiline3(): + """Multiline examples with blank lines. + + In [12]: def h(x): + ....: if x>1: + ....: return x**2 + ....: # To leave a blank line in the input, you must mark it + ....: # with a comment character: + ....: # + ....: # otherwise the doctest parser gets confused. + ....: else: + ....: return -1 + ....: + + In [13]: h(5) + Out[13]: 25 + + In [14]: h(1) + Out[14]: -1 + + In [15]: h(0) + Out[15]: -1 + """ + + +def doctest_builtin_underscore(): + """Defining builtins._ should not break anything outside the doctest + while also should be working as expected inside the doctest. + + In [1]: import builtins + + In [2]: builtins._ = 42 + + In [3]: builtins._ + Out[3]: 42 + + In [4]: _ + Out[4]: 42 + """ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/test_refs.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/test_refs.py new file mode 100644 index 0000000000000000000000000000000000000000..b92448be074180e8311fa9820b52bc6fa70d696e --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/test_refs.py @@ -0,0 +1,39 @@ +"""Some simple tests for the plugin while running scripts. +""" +# Module imports +# Std lib +import inspect + +# Our own + +#----------------------------------------------------------------------------- +# Testing functions + +def test_trivial(): + """A trivial passing test.""" + pass + +def doctest_run(): + """Test running a trivial script. + + In [13]: run simplevars.py + x is: 1 + """ + +def doctest_runvars(): + """Test that variables defined in scripts get loaded correctly via %run. + + In [13]: run simplevars.py + x is: 1 + + In [14]: x + Out[14]: 1 + """ + +def doctest_ivars(): + """Test that variables defined interactively are picked up. + In [5]: zz=1 + + In [6]: zz + Out[6]: 1 + """ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/tests/__init__.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..042eb921f58ffe461e9ab00430f045de94633fa2 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/tests/__init__.py @@ -0,0 +1,10 @@ +# encoding: utf-8 +__docformat__ = "restructuredtext en" +# ------------------------------------------------------------------------------- +# Copyright (C) 2005 Fernando Perez +# Brian E Granger +# Benjamin Ragan-Kelley +# +# Distributed under the terms of the BSD License. The full license is in +# the file COPYING, distributed as part of this software. +# ------------------------------------------------------------------------------- diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/tests/__pycache__/__init__.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8600cb93853d0f33fc87fa4a6c90b149068ca5de Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/tests/__pycache__/test_decorators.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/tests/__pycache__/test_decorators.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b6f4a3037787b5abe743a0a1eab5174a11a79a7 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/tests/__pycache__/test_decorators.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/tests/__pycache__/test_ipunittest.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/tests/__pycache__/test_ipunittest.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de009754d4bb834859906d5206159c9078114c35 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/tests/__pycache__/test_ipunittest.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/tests/__pycache__/test_tools.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/tests/__pycache__/test_tools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5285ecef8beba6c8ca77039d5f9c5c673f254a6d Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/tests/__pycache__/test_tools.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/tests/test_decorators.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..9eef690021dddfd7f5fdbc17e57bb6864b9ccd26 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/tests/test_decorators.py @@ -0,0 +1,168 @@ +"""Tests for the decorators we've created for IPython. +""" + +# Module imports +# Std lib +import inspect +import sys + +# Our own +from IPython.testing import decorators as dec +from IPython.testing.skipdoctest import skip_doctest +from IPython.utils.text import dedent + +#----------------------------------------------------------------------------- +# Utilities + +# Note: copied from OInspect, kept here so the testing stuff doesn't create +# circular dependencies and is easier to reuse. +def getargspec(obj): + """Get the names and default values of a function's arguments. + + A tuple of four things is returned: (args, varargs, varkw, defaults). + 'args' is a list of the argument names (it may contain nested lists). + 'varargs' and 'varkw' are the names of the * and ** arguments or None. + 'defaults' is an n-tuple of the default values of the last n arguments. + + Modified version of inspect.getargspec from the Python Standard + Library.""" + + if inspect.isfunction(obj): + func_obj = obj + elif inspect.ismethod(obj): + func_obj = obj.__func__ + else: + raise TypeError('arg is not a Python function') + args, varargs, varkw = inspect.getargs(func_obj.__code__) + return args, varargs, varkw, func_obj.__defaults__ + +#----------------------------------------------------------------------------- +# Testing functions + +@dec.as_unittest +def trivial(): + """A trivial test""" + pass + + +@dec.skip() +def test_deliberately_broken(): + """A deliberately broken test - we want to skip this one.""" + 1/0 + +@dec.skip('Testing the skip decorator') +def test_deliberately_broken2(): + """Another deliberately broken test - we want to skip this one.""" + 1/0 + + +# Verify that we can correctly skip the doctest for a function at will, but +# that the docstring itself is NOT destroyed by the decorator. +@skip_doctest +def doctest_bad(x,y=1,**k): + """A function whose doctest we need to skip. + + >>> 1+1 + 3 + """ + print('x:',x) + print('y:',y) + print('k:',k) + + +def call_doctest_bad(): + """Check that we can still call the decorated functions. + + >>> doctest_bad(3,y=4) + x: 3 + y: 4 + k: {} + """ + pass + + +def test_skip_dt_decorator(): + """Doctest-skipping decorator should preserve the docstring. + """ + # Careful: 'check' must be a *verbatim* copy of the doctest_bad docstring! + check = """A function whose doctest we need to skip. + + >>> 1+1 + 3 + """ + + # Fetch the docstring from doctest_bad after decoration. + val = doctest_bad.__doc__ + + assert dedent(check) == dedent(val), "doctest_bad docstrings don't match" + + +# Doctest skipping should work for class methods too +class FooClass(object): + """FooClass + + Example: + + >>> 1+1 + 2 + """ + + @skip_doctest + def __init__(self,x): + """Make a FooClass. + + Example: + + >>> f = FooClass(3) + junk + """ + print('Making a FooClass.') + self.x = x + + @skip_doctest + def bar(self,y): + """Example: + + >>> ff = FooClass(3) + >>> ff.bar(0) + boom! + >>> 1/0 + bam! + """ + return 1/y + + def baz(self,y): + """Example: + + >>> ff2 = FooClass(3) + Making a FooClass. + >>> ff2.baz(3) + True + """ + return self.x==y + + +def test_skip_dt_decorator2(): + """Doctest-skipping decorator should preserve function signature. + """ + # Hardcoded correct answer + dtargs = (['x', 'y'], None, 'k', (1,)) + # Introspect out the value + dtargsr = getargspec(doctest_bad) + assert dtargsr==dtargs, \ + "Incorrectly reconstructed args for doctest_bad: %s" % (dtargsr,) + + +@dec.skip_linux +def test_linux(): + assert sys.platform.startswith("linux") is False, "This test can't run under linux" + + +@dec.skip_win32 +def test_win32(): + assert sys.platform != "win32", "This test can't run under windows" + + +@dec.skip_osx +def test_osx(): + assert sys.platform != "darwin", "This test can't run under osx" diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/tests/test_ipunittest.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/tests/test_ipunittest.py new file mode 100644 index 0000000000000000000000000000000000000000..df436546e1ec290d0380e6fc356b83e7a33df637 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/tests/test_ipunittest.py @@ -0,0 +1,131 @@ +"""Tests for IPython's test support utilities. + +These are decorators that allow standalone functions and docstrings to be seen +as tests by unittest, replicating some of nose's functionality. Additionally, +IPython-syntax docstrings can be auto-converted to '>>>' so that ipython +sessions can be copy-pasted as tests. + +This file can be run as a script, and it will call unittest.main(). We must +check that it works with unittest as well as with nose... + + +Notes: + +- Using nosetests --with-doctest --doctest-tests testfile.py + will find docstrings as tests wherever they are, even in methods. But + if we use ipython syntax in the docstrings, they must be decorated with + @ipdocstring. This is OK for test-only code, but not for user-facing + docstrings where we want to keep the ipython syntax. + +- Using nosetests --with-doctest file.py + also finds doctests if the file name doesn't have 'test' in it, because it is + treated like a normal module. But if nose treats the file like a test file, + then for normal classes to be doctested the extra --doctest-tests is + necessary. + +- running this script with python (it has a __main__ section at the end) misses + one docstring test, the one embedded in the Foo object method. Since our + approach relies on using decorators that create standalone TestCase + instances, it can only be used for functions, not for methods of objects. +Authors +------- + +- Fernando Perez +""" + +#----------------------------------------------------------------------------- +# Copyright (C) 2009-2011 The IPython Development Team +# +# Distributed under the terms of the BSD License. The full license is in +# the file COPYING, distributed as part of this software. +#----------------------------------------------------------------------------- + + +#----------------------------------------------------------------------------- +# Imports +#----------------------------------------------------------------------------- + +from IPython.testing.ipunittest import ipdoctest, ipdocstring + +#----------------------------------------------------------------------------- +# Test classes and functions +#----------------------------------------------------------------------------- +@ipdoctest +def simple_dt(): + """ + >>> print(1+1) + 2 + """ + + +@ipdoctest +def ipdt_flush(): + """ +In [20]: print(1) +1 + +In [26]: for i in range(4): + ....: print(i) + ....: + ....: +0 +1 +2 +3 + +In [27]: 3+4 +Out[27]: 7 +""" + + +@ipdoctest +def ipdt_indented_test(): + """ + In [20]: print(1) + 1 + + In [26]: for i in range(4): + ....: print(i) + ....: + ....: + 0 + 1 + 2 + 3 + + In [27]: 3+4 + Out[27]: 7 + """ + + +class Foo(object): + """For methods, the normal decorator doesn't work. + + But rewriting the docstring with ip2py does, *but only if using nose + --with-doctest*. Do we want to have that as a dependency? + """ + + @ipdocstring + def ipdt_method(self): + """ + In [20]: print(1) + 1 + + In [26]: for i in range(4): + ....: print(i) + ....: + ....: + 0 + 1 + 2 + 3 + + In [27]: 3+4 + Out[27]: 7 + """ + + def normaldt_method(self): + """ + >>> print(1+1) + 2 + """ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/tests/test_tools.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/tests/test_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..e6d5bc2d1c4847d87f87ff68ba5f2f3f0f070229 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/tests/test_tools.py @@ -0,0 +1,133 @@ +# encoding: utf-8 +""" +Tests for testing.tools +""" + +#----------------------------------------------------------------------------- +# Copyright (C) 2008-2011 The IPython Development Team +# +# Distributed under the terms of the BSD License. The full license is in +# the file COPYING, distributed as part of this software. +#----------------------------------------------------------------------------- + +#----------------------------------------------------------------------------- +# Imports +#----------------------------------------------------------------------------- + +import os +import unittest + +from IPython.testing import decorators as dec +from IPython.testing import tools as tt + +#----------------------------------------------------------------------------- +# Tests +#----------------------------------------------------------------------------- + +@dec.skip_win32 +def test_full_path_posix(): + spath = "/foo/bar.py" + result = tt.full_path(spath, ["a.txt", "b.txt"]) + assert result, ["/foo/a.txt" == "/foo/b.txt"] + spath = "/foo" + result = tt.full_path(spath, ["a.txt", "b.txt"]) + assert result, ["/a.txt" == "/b.txt"] + result = tt.full_path(spath, ["a.txt"]) + assert result == ["/a.txt"] + + +@dec.skip_if_not_win32 +def test_full_path_win32(): + spath = "c:\\foo\\bar.py" + result = tt.full_path(spath, ["a.txt", "b.txt"]) + assert result, ["c:\\foo\\a.txt" == "c:\\foo\\b.txt"] + spath = "c:\\foo" + result = tt.full_path(spath, ["a.txt", "b.txt"]) + assert result, ["c:\\a.txt" == "c:\\b.txt"] + result = tt.full_path(spath, ["a.txt"]) + assert result == ["c:\\a.txt"] + + +def test_parser(): + err = ("FAILED (errors=1)", 1, 0) + fail = ("FAILED (failures=1)", 0, 1) + both = ("FAILED (errors=1, failures=1)", 1, 1) + for txt, nerr, nfail in [err, fail, both]: + nerr1, nfail1 = tt.parse_test_output(txt) + assert nerr == nerr1 + assert nfail == nfail1 + + +def test_temp_pyfile(): + src = 'pass\n' + fname = tt.temp_pyfile(src) + assert os.path.isfile(fname) + with open(fname, encoding="utf-8") as fh2: + src2 = fh2.read() + assert src2 == src + +class TestAssertPrints(unittest.TestCase): + def test_passing(self): + with tt.AssertPrints("abc"): + print("abcd") + print("def") + print(b"ghi") + + def test_failing(self): + def func(): + with tt.AssertPrints("abc"): + print("acd") + print("def") + print(b"ghi") + + self.assertRaises(AssertionError, func) + + +class Test_ipexec_validate(tt.TempFileMixin): + def test_main_path(self): + """Test with only stdout results. + """ + self.mktmp("print('A')\n" + "print('B')\n" + ) + out = "A\nB" + tt.ipexec_validate(self.fname, out) + + def test_main_path2(self): + """Test with only stdout results, expecting windows line endings. + """ + self.mktmp("print('A')\n" + "print('B')\n" + ) + out = "A\r\nB" + tt.ipexec_validate(self.fname, out) + + def test_exception_path(self): + """Test exception path in exception_validate. + """ + self.mktmp("import sys\n" + "print('A')\n" + "print('B')\n" + "print('C', file=sys.stderr)\n" + "print('D', file=sys.stderr)\n" + ) + out = "A\nB" + tt.ipexec_validate(self.fname, expected_out=out, expected_err="C\nD") + + def test_exception_path2(self): + """Test exception path in exception_validate, expecting windows line endings. + """ + self.mktmp("import sys\n" + "print('A')\n" + "print('B')\n" + "print('C', file=sys.stderr)\n" + "print('D', file=sys.stderr)\n" + ) + out = "A\r\nB" + tt.ipexec_validate(self.fname, expected_out=out, expected_err="C\r\nD") + + + def tearDown(self): + # tear down correctly the mixin, + # unittest.TestCase.tearDown does nothing + tt.TempFileMixin.tearDown(self) diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/utils/__pycache__/_process_emscripten.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/utils/__pycache__/_process_emscripten.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1bc404afadeb67b319417adcdd7034d079b73d3f Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/utils/__pycache__/_process_emscripten.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/utils/__pycache__/dir2.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/utils/__pycache__/dir2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb01f4030c04407b969b3ed4f737547c0a6042c5 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/utils/__pycache__/dir2.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/utils/__pycache__/generics.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/utils/__pycache__/generics.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c592967afbfce133fc4aade56e75706ae3df2ba4 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/utils/__pycache__/generics.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/utils/__pycache__/jsonutil.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/utils/__pycache__/jsonutil.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7775551203a4280869f8e657640fdcdd7782f0f1 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/utils/__pycache__/jsonutil.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/utils/__pycache__/log.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/utils/__pycache__/log.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bbc6a1cf5daec7109188206231271cc08add3ab Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/utils/__pycache__/log.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/utils/__pycache__/openpy.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/utils/__pycache__/openpy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2106897f3deb6efa7e8ee1d9b543ef1f7923705 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/utils/__pycache__/openpy.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/utils/__pycache__/shimmodule.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/utils/__pycache__/shimmodule.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3b5b1199209c5044d3ef35360497a7519a34309 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/utils/__pycache__/shimmodule.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/filters/__pycache__/alphabeticalattributes.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/filters/__pycache__/alphabeticalattributes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8608d53b2ea01a2891fb37ab8b177de8fa9040a Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/filters/__pycache__/alphabeticalattributes.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/filters/__pycache__/base.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/filters/__pycache__/base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0359f829537726a009b30d957aa6233998952476 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/filters/__pycache__/base.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/filters/__pycache__/optionaltags.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/filters/__pycache__/optionaltags.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64b1d499abb36ede24275b8f46b31a0f01c8ca68 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/filters/__pycache__/optionaltags.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/filters/__pycache__/sanitizer.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/filters/__pycache__/sanitizer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..007abe0c4a9e865d64b4a0787425ea1fb0551d79 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/filters/__pycache__/sanitizer.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/treeadapters/__init__.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/treeadapters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7ef59590c76ee75733d78b061d4108d49f209ee5 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/treeadapters/__init__.py @@ -0,0 +1,30 @@ +"""Tree adapters let you convert from one tree structure to another + +Example: + +.. code-block:: python + + from pip._vendor import html5lib + from pip._vendor.html5lib.treeadapters import genshi + + doc = 'Hi!' + treebuilder = html5lib.getTreeBuilder('etree') + parser = html5lib.HTMLParser(tree=treebuilder) + tree = parser.parse(doc) + TreeWalker = html5lib.getTreeWalker('etree') + + genshi_tree = genshi.to_genshi(TreeWalker(tree)) + +""" +from __future__ import absolute_import, division, unicode_literals + +from . import sax + +__all__ = ["sax"] + +try: + from . import genshi # noqa +except ImportError: + pass +else: + __all__.append("genshi") diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/treeadapters/__pycache__/__init__.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/treeadapters/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4bda6b99c6d7c6ed75f294d7a312c78cc865ca7 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/treeadapters/__pycache__/__init__.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/treeadapters/__pycache__/genshi.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/treeadapters/__pycache__/genshi.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..825ffea37a2feace04b3458dd809cc83503b0105 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/treeadapters/__pycache__/genshi.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/treeadapters/__pycache__/sax.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/treeadapters/__pycache__/sax.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af5378e2e89be81a907982d437ad6c178ef8f2dc Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/treeadapters/__pycache__/sax.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/treeadapters/genshi.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/treeadapters/genshi.py new file mode 100644 index 0000000000000000000000000000000000000000..61d5fb6ac42ca4152f056d996af0cb0b0d2ddc35 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/treeadapters/genshi.py @@ -0,0 +1,54 @@ +from __future__ import absolute_import, division, unicode_literals + +from genshi.core import QName, Attrs +from genshi.core import START, END, TEXT, COMMENT, DOCTYPE + + +def to_genshi(walker): + """Convert a tree to a genshi tree + + :arg walker: the treewalker to use to walk the tree to convert it + + :returns: generator of genshi nodes + + """ + text = [] + for token in walker: + type = token["type"] + if type in ("Characters", "SpaceCharacters"): + text.append(token["data"]) + elif text: + yield TEXT, "".join(text), (None, -1, -1) + text = [] + + if type in ("StartTag", "EmptyTag"): + if token["namespace"]: + name = "{%s}%s" % (token["namespace"], token["name"]) + else: + name = token["name"] + attrs = Attrs([(QName("{%s}%s" % attr if attr[0] is not None else attr[1]), value) + for attr, value in token["data"].items()]) + yield (START, (QName(name), attrs), (None, -1, -1)) + if type == "EmptyTag": + type = "EndTag" + + if type == "EndTag": + if token["namespace"]: + name = "{%s}%s" % (token["namespace"], token["name"]) + else: + name = token["name"] + + yield END, QName(name), (None, -1, -1) + + elif type == "Comment": + yield COMMENT, token["data"], (None, -1, -1) + + elif type == "Doctype": + yield DOCTYPE, (token["name"], token["publicId"], + token["systemId"]), (None, -1, -1) + + else: + pass # FIXME: What to do? + + if text: + yield TEXT, "".join(text), (None, -1, -1) diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/treeadapters/sax.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/treeadapters/sax.py new file mode 100644 index 0000000000000000000000000000000000000000..f4ccea5a25653dd9e4c1bcf1047f407184562a1b --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/html5lib/treeadapters/sax.py @@ -0,0 +1,50 @@ +from __future__ import absolute_import, division, unicode_literals + +from xml.sax.xmlreader import AttributesNSImpl + +from ..constants import adjustForeignAttributes, unadjustForeignAttributes + +prefix_mapping = {} +for prefix, localName, namespace in adjustForeignAttributes.values(): + if prefix is not None: + prefix_mapping[prefix] = namespace + + +def to_sax(walker, handler): + """Call SAX-like content handler based on treewalker walker + + :arg walker: the treewalker to use to walk the tree to convert it + + :arg handler: SAX handler to use + + """ + handler.startDocument() + for prefix, namespace in prefix_mapping.items(): + handler.startPrefixMapping(prefix, namespace) + + for token in walker: + type = token["type"] + if type == "Doctype": + continue + elif type in ("StartTag", "EmptyTag"): + attrs = AttributesNSImpl(token["data"], + unadjustForeignAttributes) + handler.startElementNS((token["namespace"], token["name"]), + token["name"], + attrs) + if type == "EmptyTag": + handler.endElementNS((token["namespace"], token["name"]), + token["name"]) + elif type == "EndTag": + handler.endElementNS((token["namespace"], token["name"]), + token["name"]) + elif type in ("Characters", "SpaceCharacters"): + handler.characters(token["data"]) + elif type == "Comment": + pass + else: + assert False, "Unknown token type" + + for prefix, namespace in prefix_mapping.items(): + handler.endPrefixMapping(prefix) + handler.endDocument() diff --git a/material/dataset/xpsdeeplearning/tests/data/sim/ref_sim_spectrum.npz b/material/dataset/xpsdeeplearning/tests/data/sim/ref_sim_spectrum.npz new file mode 100644 index 0000000000000000000000000000000000000000..0a71090fbe2488444dc71112f55d758d9f910e0e --- /dev/null +++ b/material/dataset/xpsdeeplearning/tests/data/sim/ref_sim_spectrum.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:20964b78885ea2a94f0e8853e582861091beea83bcccd73c9486e2efb39f5e21 +size 5100