id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
171,967
import os import sys import traceback import regutil import win32api import win32con import win32ui from pywin.mfc import afxres, dialog, window from pywin.mfc.thread import WinApp from . import scriptutils def RectToCreateStructRect(rect): return (rect[3] - rect[1], rect[2] - rect[0], rect[1], rect[0])
null
171,968
import os import sys import traceback import regutil import win32api import win32con import win32ui from pywin.mfc import afxres, dialog, window from pywin.mfc.thread import WinApp from . import scriptutils def _GetRegistryValue(key, val, default=None): # val is registry value - None for default val. try: hkey = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, key) return win32api.RegQueryValueEx(hkey, val)[0] except win32api.error: try: hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, key) return win32api.RegQueryValueEx(hkey, val)[0] except win32api.error: return default
null
171,969
import os import sys import traceback import regutil import win32api import win32con import win32ui from pywin.mfc import afxres, dialog, window from pywin.mfc.thread import WinApp from . import scriptutils def Win32RawInput(prompt=None): "Provide raw_input() for gui apps" # flush stderr/out first. try: sys.stdout.flush() sys.stderr.flush() except: pass if prompt is None: prompt = "" ret = dialog.GetSimpleInput(prompt) if ret == None: raise KeyboardInterrupt("operation cancelled") return ret def Win32Input(prompt=None): "Provide input() for gui apps" return eval(input(prompt)) def HookInput(): try: raw_input # must be py2x... sys.modules["__builtin__"].raw_input = Win32RawInput sys.modules["__builtin__"].input = Win32Input except NameError: # must be py3k import code sys.modules["builtins"].input = Win32RawInput
null
171,970
import os import sys import traceback import regutil import win32api import win32con import win32ui from pywin.mfc import afxres, dialog, window from pywin.mfc.thread import WinApp from . import scriptutils def HaveGoodGUI(): """Returns true if we currently have a good gui available.""" return "pywin.framework.startup" in sys.modules def CreateDefaultGUI(appClass=None): """Creates a default GUI environment""" if appClass is None: from . import intpyapp # Bring in the default app - could be param'd later. appClass = intpyapp.InteractivePythonApp # Create and init the app. appClass().InitInstance() The provided code snippet includes necessary dependencies for implementing the `CheckCreateDefaultGUI` function. Write a Python function `def CheckCreateDefaultGUI()` to solve the following problem: Checks and creates if necessary a default GUI environment. Here is the function: def CheckCreateDefaultGUI(): """Checks and creates if necessary a default GUI environment.""" rc = HaveGoodGUI() if not rc: CreateDefaultGUI() return rc
Checks and creates if necessary a default GUI environment.
171,971
import glob import os import re import win32api import win32con import win32ui from pywin.mfc import dialog, docview, window from . import scriptutils def getsubdirs(d): dlist = [] flist = glob.glob(d + "\\*") for f in flist: if os.path.isdir(f): dlist.append(f) dlist = dlist + getsubdirs(f) return dlist
null
171,972
import sys The provided code snippet includes necessary dependencies for implementing the `fake_raw_input` function. Write a Python function `def fake_raw_input(prompt=None)` to solve the following problem: Replacement for raw_input() which pulls lines out of global test_input. For testing only! Here is the function: def fake_raw_input(prompt=None): """Replacement for raw_input() which pulls lines out of global test_input. For testing only! """ global test_input if "\n" not in test_input: end_of_line_pos = len(test_input) else: end_of_line_pos = test_input.find("\n") result = test_input[:end_of_line_pos] test_input = test_input[end_of_line_pos + 1 :] if len(result) == 0 or result[0] == "~": raise EOFError() return result
Replacement for raw_input() which pulls lines out of global test_input. For testing only!
171,973
import os import win32api import win32con import win32ui from pywin.mfc import docview, window from . import app bitmapTemplate = BitmapTemplate() bitmapTemplate.SetDocStrings( "\nBitmap\nBitmap\nBitmap (*.bmp)\n.bmp\nPythonBitmapFileType\nPython Bitmap File" ) def t(): bitmapTemplate.OpenDocumentFile("d:\\winnt\\arcade.bmp") # OpenBMPFile( 'd:\\winnt\\arcade.bmp')
null
171,974
import os import win32api import win32con import win32ui from pywin.mfc import docview, window from . import app bitmapTemplate = BitmapTemplate() bitmapTemplate.SetDocStrings( "\nBitmap\nBitmap\nBitmap (*.bmp)\n.bmp\nPythonBitmapFileType\nPython Bitmap File" ) def demo(): import glob winDir = win32api.GetWindowsDirectory() for fileName in glob.glob1(winDir, "*.bmp")[:2]: bitmapTemplate.OpenDocumentFile(os.path.join(winDir, fileName))
null
171,975
import os import sys import traceback import __main__ import commctrl import win32api import win32con import win32ui from pywin.mfc import afxres, dialog from . import app, dbgcommands from pywin.mfc import docview def _SetupSharedMenu_(self): sharedMenu = self.GetSharedMenu() from pywin.framework import toolmenu toolmenu.SetToolsMenu(sharedMenu) from pywin.framework import help help.SetHelpMenuOtherHelp(sharedMenu)
null
171,976
import os import regutil import win32api import win32con import win32ui htmlhelp_handle = None def FinalizeHelp(): global htmlhelp_handle if htmlhelp_handle is not None: import win32help try: # frame = win32ui.GetMainFrame().GetSafeHwnd() frame = 0 win32help.HtmlHelp(frame, None, win32help.HH_UNINITIALIZE, htmlhelp_handle) except win32help.error: print("Failed to finalize htmlhelp!") htmlhelp_handle = None
null
171,977
import os import regutil import win32api import win32con import win32ui def OpenHelpFile(fileName, helpCmd=None, helpArg=None): "Open a help file, given a full path" # default help arg. win32ui.DoWaitCursor(1) try: if helpCmd is None: helpCmd = win32con.HELP_CONTENTS ext = os.path.splitext(fileName)[1].lower() if ext == ".hlp": win32api.WinHelp( win32ui.GetMainFrame().GetSafeHwnd(), fileName, helpCmd, helpArg ) # XXX - using the htmlhelp API wreaks havoc with keyboard shortcuts # so we disable it, forcing ShellExecute, which works fine (but # doesn't close the help file when Pythonwin is closed. # Tom Heller also points out http://www.microsoft.com/mind/0499/faq/faq0499.asp, # which may or may not be related. elif 0 and ext == ".chm": import win32help global htmlhelp_handle helpCmd = html_help_command_translators.get(helpCmd, helpCmd) # frame = win32ui.GetMainFrame().GetSafeHwnd() frame = 0 # Dont want it overlapping ours! if htmlhelp_handle is None: htmlhelp_hwnd, htmlhelp_handle = win32help.HtmlHelp( frame, None, win32help.HH_INITIALIZE ) win32help.HtmlHelp(frame, fileName, helpCmd, helpArg) else: # Hope that the extension is registered, and we know what to do! win32api.ShellExecute(0, "open", fileName, None, "", win32con.SW_SHOW) return fileName finally: win32ui.DoWaitCursor(-1) def ListAllHelpFiles(): ret = [] ret = _ListAllHelpFilesInRoot(win32con.HKEY_LOCAL_MACHINE) # Ensure we don't get dups. for item in _ListAllHelpFilesInRoot(win32con.HKEY_CURRENT_USER): if item not in ret: ret.append(item) return ret def SelectAndRunHelpFile(): from pywin.dialogs import list helpFiles = ListAllHelpFiles() if len(helpFiles) == 1: # only 1 help file registered - probably ours - no point asking index = 0 else: index = list.SelectFromLists("Select Help file", helpFiles, ["Title"]) if index is not None: OpenHelpFile(helpFiles[index][1])
null
171,978
import bdb import linecache import os import sys import traceback import __main__ import win32api import win32con import win32ui from pywin.mfc import dialog from pywin.mfc.docview import TreeView from .cmdline import ParseArgs def GetActiveView(): """Gets the edit control (eg, EditView) with the focus, or None""" try: childFrame, bIsMaximised = win32ui.GetMainFrame().MDIGetActive() return childFrame.GetActiveView() except win32ui.error: return None class TreeView(CtrlView): def __init__(self, doc): View.__init__(self, win32ui.CreateTreeView(doc)) The provided code snippet includes necessary dependencies for implementing the `GetActiveEditorDocument` function. Write a Python function `def GetActiveEditorDocument()` to solve the following problem: Returns the active editor document and view, or (None,None) if no active document or its not an editor document. Here is the function: def GetActiveEditorDocument(): """Returns the active editor document and view, or (None,None) if no active document or its not an editor document. """ view = GetActiveView() if view is None or isinstance(view, TreeView): return (None, None) doc = view.GetDocument() if hasattr(doc, "MarkerAdd"): # Is it an Editor document? return doc, view return (None, None)
Returns the active editor document and view, or (None,None) if no active document or its not an editor document.
171,979
import bdb import linecache import os import sys import traceback import __main__ import win32api import win32con import win32ui from pywin.mfc import dialog from pywin.mfc.docview import TreeView from .cmdline import ParseArgs RS_DEBUGGER_NONE = 0 RS_DEBUGGER_STEP = 1 RS_DEBUGGER_GO = 2 RS_DEBUGGER_PM = 3 byte_cr = "\r".encode("ascii") byte_lf = "\n".encode("ascii") byte_crlf = "\r\n".encode("ascii") class DlgRunScript(dialog.Dialog): "A class for the 'run script' dialog" def __init__(self, bHaveDebugger): dialog.Dialog.__init__(self, win32ui.IDD_RUN_SCRIPT) self.AddDDX(win32ui.IDC_EDIT1, "script") self.AddDDX(win32ui.IDC_EDIT2, "args") self.AddDDX(win32ui.IDC_COMBO1, "debuggingType", "i") self.HookCommand(self.OnBrowse, win32ui.IDC_BUTTON2) self.bHaveDebugger = bHaveDebugger def OnInitDialog(self): rc = dialog.Dialog.OnInitDialog(self) cbo = self.GetDlgItem(win32ui.IDC_COMBO1) for o in debugging_options: cbo.AddString(o) cbo.SetCurSel(self["debuggingType"]) if not self.bHaveDebugger: cbo.EnableWindow(0) def OnBrowse(self, id, code): if code != 0: # BN_CLICKED return 1 openFlags = win32con.OFN_OVERWRITEPROMPT | win32con.OFN_FILEMUSTEXIST dlg = win32ui.CreateFileDialog( 1, None, None, openFlags, "Python Scripts (*.py)|*.py||", self ) dlg.SetOFNTitle("Run Script") if dlg.DoModal() != win32con.IDOK: return 0 self["script"] = dlg.GetPathName() self.UpdateData(0) return 0 def GetDebugger(): """Get the default Python debugger. Returns the debugger, or None. It is assumed the debugger has a standard "pdb" defined interface. Currently always returns the 'pywin.debugger' debugger, or None (pdb is _not_ returned as it is not effective in this GUI environment) """ try: import pywin.debugger return pywin.debugger except ImportError: return None def IsOnPythonPath(path): "Given a path only, see if it is on the Pythonpath. Assumes path is a full path spec." # must check that the command line arg's path is in sys.path for syspath in sys.path: try: # Python 1.5 and later allows an empty sys.path entry. if syspath and win32ui.FullPath(syspath) == path: return 1 except win32ui.error as details: print( "Warning: The sys.path entry '%s' is invalid\n%s" % (syspath, details) ) return 0 def GetActiveFileName(bAutoSave=1): """Gets the file name for the active frame, saving it if necessary. Returns None if it cant be found, or raises KeyboardInterrupt. """ pathName = None active = GetActiveView() if active is None: return None try: doc = active.GetDocument() pathName = doc.GetPathName() if bAutoSave and ( len(pathName) > 0 or doc.GetTitle()[:8] == "Untitled" or doc.GetTitle()[:6] == "Script" ): # if not a special purpose window if doc.IsModified(): try: doc.OnSaveDocument(pathName) pathName = doc.GetPathName() # clear the linecache buffer linecache.clearcache() except win32ui.error: raise KeyboardInterrupt except (win32ui.error, AttributeError): pass if not pathName: return None return pathName lastScript = "" lastArgs = "" lastDebuggingType = RS_DEBUGGER_NONE def _HandlePythonFailure(what, syntaxErrorPathName=None): typ, details, tb = sys.exc_info() if isinstance(details, SyntaxError): try: msg, (fileName, line, col, text) = details if (not fileName or fileName == "<string>") and syntaxErrorPathName: fileName = syntaxErrorPathName _JumpToPosition(fileName, line, col) except (TypeError, ValueError): msg = str(details) win32ui.SetStatusText("Failed to " + what + " - syntax error - %s" % msg) else: traceback.print_exc() win32ui.SetStatusText("Failed to " + what + " - " + str(details)) tb = None # Clean up a cycle. def LocatePythonFile(fileName, bBrowseIfDir=1): "Given a file name, return a fully qualified file name, or None" # first look for the exact file as specified if not os.path.isfile(fileName): # Go looking! baseName = fileName for path in sys.path: fileName = os.path.abspath(os.path.join(path, baseName)) if os.path.isdir(fileName): if bBrowseIfDir: d = win32ui.CreateFileDialog( 1, "*.py", None, 0, "Python Files (*.py)|*.py|All files|*.*" ) d.SetOFNInitialDir(fileName) rc = d.DoModal() if rc == win32con.IDOK: fileName = d.GetPathName() break else: return None else: fileName = fileName + ".py" if os.path.isfile(fileName): break # Found it! else: # for not broken out of return None return win32ui.FullPath(fileName) def ParseArgs(str): import string ret = [] pos = 0 length = len(str) while pos < length: try: while str[pos] in string.whitespace: pos = pos + 1 except IndexError: break if pos >= length: break if str[pos] == '"': pos = pos + 1 try: endPos = str.index('"', pos) - 1 nextPos = endPos + 2 except ValueError: endPos = length nextPos = endPos + 1 else: endPos = pos while endPos < length and not str[endPos] in string.whitespace: endPos = endPos + 1 nextPos = endPos + 1 ret.append(str[pos : endPos + 1].strip()) pos = nextPos return ret def RunScript(defName=None, defArgs=None, bShowDialog=1, debuggingType=None): global lastScript, lastArgs, lastDebuggingType _debugger_stop_frame_ = 1 # Magic variable so the debugger will hide me! # Get the debugger - may be None! debugger = GetDebugger() if defName is None: try: pathName = GetActiveFileName() except KeyboardInterrupt: return # User cancelled save. else: pathName = defName if not pathName: pathName = lastScript if defArgs is None: args = "" if pathName == lastScript: args = lastArgs else: args = defArgs if debuggingType is None: debuggingType = lastDebuggingType if not pathName or bShowDialog: dlg = DlgRunScript(debugger is not None) dlg["script"] = pathName dlg["args"] = args dlg["debuggingType"] = debuggingType if dlg.DoModal() != win32con.IDOK: return script = dlg["script"] args = dlg["args"] debuggingType = dlg["debuggingType"] if not script: return if debuggingType == RS_DEBUGGER_GO and debugger is not None: # This may surprise users - they select "Run under debugger", but # it appears not to! Only warn when they pick from the dialog! # First - ensure the debugger is activated to pickup any break-points # set in the editor. try: # Create the debugger, but _dont_ init the debugger GUI. rd = debugger._GetCurrentDebugger() except AttributeError: rd = None if rd is not None and len(rd.breaks) == 0: msg = "There are no active break-points.\r\n\r\nSelecting this debug option without any\r\nbreak-points is unlikely to have the desired effect\r\nas the debugger is unlikely to be invoked..\r\n\r\nWould you like to step-through in the debugger instead?" rc = win32ui.MessageBox( msg, win32ui.LoadString(win32ui.IDR_DEBUGGER), win32con.MB_YESNOCANCEL | win32con.MB_ICONINFORMATION, ) if rc == win32con.IDCANCEL: return if rc == win32con.IDYES: debuggingType = RS_DEBUGGER_STEP lastDebuggingType = debuggingType lastScript = script lastArgs = args else: script = pathName # try and open the script. if ( len(os.path.splitext(script)[1]) == 0 ): # check if no extension supplied, and give one. script = script + ".py" # If no path specified, try and locate the file path, fnameonly = os.path.split(script) if len(path) == 0: try: os.stat(fnameonly) # See if it is OK as is... script = fnameonly except os.error: fullScript = LocatePythonFile(script) if fullScript is None: win32ui.MessageBox("The file '%s' can not be located" % script) return script = fullScript else: path = win32ui.FullPath(path) if not IsOnPythonPath(path): sys.path.append(path) # py3k fun: If we use text mode to open the file, we get \r\n # translated so Python allows the syntax (good!), but we get back # text already decoded from the default encoding (bad!) and Python # ignores any encoding decls (bad!). If we use binary mode we get # the raw bytes and Python looks at the encoding (good!) but \r\n # chars stay in place so Python throws a syntax error (bad!). # So: so the binary thing and manually normalize \r\n. try: f = open(script, "rb") except IOError as exc: win32ui.MessageBox( "The file could not be opened - %s (%d)" % (exc.strerror, exc.errno) ) return # Get the source-code - as above, normalize \r\n code = f.read().replace(byte_crlf, byte_lf).replace(byte_cr, byte_lf) + byte_lf # Remember and hack sys.argv for the script. oldArgv = sys.argv sys.argv = ParseArgs(args) sys.argv.insert(0, script) # sys.path[0] is the path of the script oldPath0 = sys.path[0] newPath0 = os.path.split(script)[0] if not oldPath0: # if sys.path[0] is empty sys.path[0] = newPath0 insertedPath0 = 0 else: sys.path.insert(0, newPath0) insertedPath0 = 1 bWorked = 0 win32ui.DoWaitCursor(1) base = os.path.split(script)[1] # Allow windows to repaint before starting. win32ui.PumpWaitingMessages() win32ui.SetStatusText("Running script %s..." % base, 1) exitCode = 0 from pywin.framework import interact # Check the debugger flags if debugger is None and (debuggingType != RS_DEBUGGER_NONE): win32ui.MessageBox( "No debugger is installed. Debugging options have been ignored!" ) debuggingType = RS_DEBUGGER_NONE # Get a code object - ignore the debugger for this, as it is probably a syntax error # at this point try: codeObject = compile(code, script, "exec") except: # Almost certainly a syntax error! _HandlePythonFailure("run script", script) # No code object which to run/debug. return __main__.__file__ = script try: if debuggingType == RS_DEBUGGER_STEP: debugger.run(codeObject, __main__.__dict__, start_stepping=1) elif debuggingType == RS_DEBUGGER_GO: debugger.run(codeObject, __main__.__dict__, start_stepping=0) else: # Post mortem or no debugging exec(codeObject, __main__.__dict__) bWorked = 1 except bdb.BdbQuit: # Dont print tracebacks when the debugger quit, but do print a message. print("Debugging session cancelled.") exitCode = 1 bWorked = 1 except SystemExit as code: exitCode = code bWorked = 1 except KeyboardInterrupt: # Consider this successful, as we dont want the debugger. # (but we do want a traceback!) if interact.edit and interact.edit.currentView: interact.edit.currentView.EnsureNoPrompt() traceback.print_exc() if interact.edit and interact.edit.currentView: interact.edit.currentView.AppendToPrompt([]) bWorked = 1 except: if interact.edit and interact.edit.currentView: interact.edit.currentView.EnsureNoPrompt() traceback.print_exc() if interact.edit and interact.edit.currentView: interact.edit.currentView.AppendToPrompt([]) if debuggingType == RS_DEBUGGER_PM: debugger.pm() del __main__.__file__ sys.argv = oldArgv if insertedPath0: del sys.path[0] else: sys.path[0] = oldPath0 f.close() if bWorked: win32ui.SetStatusText("Script '%s' returned exit code %s" % (script, exitCode)) else: win32ui.SetStatusText("Exception raised while running script %s" % base) try: sys.stdout.flush() except AttributeError: pass win32ui.DoWaitCursor(0)
null
171,980
import bdb import linecache import os import sys import traceback import __main__ import win32api import win32con import win32ui from pywin.mfc import dialog from pywin.mfc.docview import TreeView from .cmdline import ParseArgs def GetPackageModuleName(fileName): """Given a filename, return (module name, new path). eg - given "c:\a\b\c\my.py", return ("b.c.my",None) if "c:\a" is on sys.path. If no package found, will return ("my", "c:\a\b\c") """ path, fname = os.path.split(fileName) path = origPath = win32ui.FullPath(path) fname = os.path.splitext(fname)[0] modBits = [] newPathReturn = None if not IsOnPythonPath(path): # Module not directly on the search path - see if under a package. while len(path) > 3: # ie 'C:\' path, modBit = os.path.split(path) modBits.append(modBit) # If on path, _and_ existing package of that name loaded. if ( IsOnPythonPath(path) and modBit in sys.modules and ( os.path.exists(os.path.join(path, modBit, "__init__.py")) or os.path.exists(os.path.join(path, modBit, "__init__.pyc")) or os.path.exists(os.path.join(path, modBit, "__init__.pyo")) ) ): modBits.reverse() return ".".join(modBits) + "." + fname, newPathReturn # Not found - look a level higher else: newPathReturn = origPath return fname, newPathReturn def GetActiveFileName(bAutoSave=1): """Gets the file name for the active frame, saving it if necessary. Returns None if it cant be found, or raises KeyboardInterrupt. """ pathName = None active = GetActiveView() if active is None: return None try: doc = active.GetDocument() pathName = doc.GetPathName() if bAutoSave and ( len(pathName) > 0 or doc.GetTitle()[:8] == "Untitled" or doc.GetTitle()[:6] == "Script" ): # if not a special purpose window if doc.IsModified(): try: doc.OnSaveDocument(pathName) pathName = doc.GetPathName() # clear the linecache buffer linecache.clearcache() except win32ui.error: raise KeyboardInterrupt except (win32ui.error, AttributeError): pass if not pathName: return None return pathName def _HandlePythonFailure(what, syntaxErrorPathName=None): typ, details, tb = sys.exc_info() if isinstance(details, SyntaxError): try: msg, (fileName, line, col, text) = details if (not fileName or fileName == "<string>") and syntaxErrorPathName: fileName = syntaxErrorPathName _JumpToPosition(fileName, line, col) except (TypeError, ValueError): msg = str(details) win32ui.SetStatusText("Failed to " + what + " - syntax error - %s" % msg) else: traceback.print_exc() win32ui.SetStatusText("Failed to " + what + " - " + str(details)) tb = None # Clean up a cycle. The provided code snippet includes necessary dependencies for implementing the `ImportFile` function. Write a Python function `def ImportFile()` to solve the following problem: This code looks for the current window, and determines if it can be imported. If not, it will prompt for a file name, and allow it to be imported. Here is the function: def ImportFile(): """This code looks for the current window, and determines if it can be imported. If not, it will prompt for a file name, and allow it to be imported.""" try: pathName = GetActiveFileName() except KeyboardInterrupt: pathName = None if pathName is not None: if os.path.splitext(pathName)[1].lower() not in (".py", ".pyw", ".pyx"): pathName = None if pathName is None: openFlags = win32con.OFN_OVERWRITEPROMPT | win32con.OFN_FILEMUSTEXIST dlg = win32ui.CreateFileDialog( 1, None, None, openFlags, "Python Scripts (*.py;*.pyw)|*.py;*.pyw;*.pyx||" ) dlg.SetOFNTitle("Import Script") if dlg.DoModal() != win32con.IDOK: return 0 pathName = dlg.GetPathName() # If already imported, dont look for package path, modName = os.path.split(pathName) modName, modExt = os.path.splitext(modName) newPath = None # note that some packages (*cough* email *cough*) use "lazy importers" # meaning sys.modules can change as a side-effect of looking at # module.__file__ - so we must take a copy (ie, items() in py2k, # list(items()) in py3k) for key, mod in list(sys.modules.items()): if getattr(mod, "__file__", None): fname = mod.__file__ base, ext = os.path.splitext(fname) if ext.lower() in (".pyo", ".pyc"): ext = ".py" fname = base + ext if win32ui.ComparePath(fname, pathName): modName = key break else: # for not broken modName, newPath = GetPackageModuleName(pathName) if newPath: sys.path.append(newPath) if modName in sys.modules: bNeedReload = 1 what = "reload" else: what = "import" bNeedReload = 0 win32ui.SetStatusText(what.capitalize() + "ing module...", 1) win32ui.DoWaitCursor(1) # win32ui.GetMainFrame().BeginWaitCursor() try: # always do an import, as it is cheap if it's already loaded. This ensures # it is in our name space. codeObj = compile("import " + modName, "<auto import>", "exec") except SyntaxError: win32ui.SetStatusText('Invalid filename for import: "' + modName + '"') return try: exec(codeObj, __main__.__dict__) mod = sys.modules.get(modName) if bNeedReload: from importlib import reload mod = reload(sys.modules[modName]) win32ui.SetStatusText( "Successfully " + what + "ed module '" + modName + "': %s" % getattr(mod, "__file__", "<unkown file>") ) except: _HandlePythonFailure(what) win32ui.DoWaitCursor(0)
This code looks for the current window, and determines if it can be imported. If not, it will prompt for a file name, and allow it to be imported.
171,981
import bdb import linecache import os import sys import traceback import __main__ import win32api import win32con import win32ui from pywin.mfc import dialog from pywin.mfc.docview import TreeView from .cmdline import ParseArgs def GetActiveFileName(bAutoSave=1): """Gets the file name for the active frame, saving it if necessary. Returns None if it cant be found, or raises KeyboardInterrupt. """ pathName = None active = GetActiveView() if active is None: return None try: doc = active.GetDocument() pathName = doc.GetPathName() if bAutoSave and ( len(pathName) > 0 or doc.GetTitle()[:8] == "Untitled" or doc.GetTitle()[:6] == "Script" ): # if not a special purpose window if doc.IsModified(): try: doc.OnSaveDocument(pathName) pathName = doc.GetPathName() # clear the linecache buffer linecache.clearcache() except win32ui.error: raise KeyboardInterrupt except (win32ui.error, AttributeError): pass if not pathName: return None return pathName def RunTabNanny(filename): import io as io tabnanny = FindTabNanny() if tabnanny is None: win32ui.MessageBox("The TabNanny is not around, so the children can run amok!") return # Capture the tab-nanny output newout = io.StringIO() old_out = sys.stderr, sys.stdout sys.stderr = sys.stdout = newout try: tabnanny.check(filename) finally: # Restore output sys.stderr, sys.stdout = old_out data = newout.getvalue() if data: try: lineno = data.split()[1] lineno = int(lineno) _JumpToPosition(filename, lineno) try: # Try and display whitespace GetActiveEditControl().SCISetViewWS(1) except: pass win32ui.SetStatusText("The TabNanny found trouble at line %d" % lineno) except (IndexError, TypeError, ValueError): print("The tab nanny complained, but I cant see where!") print(data) return 0 return 1 def _HandlePythonFailure(what, syntaxErrorPathName=None): typ, details, tb = sys.exc_info() if isinstance(details, SyntaxError): try: msg, (fileName, line, col, text) = details if (not fileName or fileName == "<string>") and syntaxErrorPathName: fileName = syntaxErrorPathName _JumpToPosition(fileName, line, col) except (TypeError, ValueError): msg = str(details) win32ui.SetStatusText("Failed to " + what + " - syntax error - %s" % msg) else: traceback.print_exc() win32ui.SetStatusText("Failed to " + what + " - " + str(details)) tb = None # Clean up a cycle. The provided code snippet includes necessary dependencies for implementing the `CheckFile` function. Write a Python function `def CheckFile()` to solve the following problem: This code looks for the current window, and gets Python to check it without actually executing any code (ie, by compiling only) Here is the function: def CheckFile(): """This code looks for the current window, and gets Python to check it without actually executing any code (ie, by compiling only) """ try: pathName = GetActiveFileName() except KeyboardInterrupt: return what = "check" win32ui.SetStatusText(what.capitalize() + "ing module...", 1) win32ui.DoWaitCursor(1) try: f = open(pathName) except IOError as details: print("Cant open file '%s' - %s" % (pathName, details)) return try: code = f.read() + "\n" finally: f.close() try: codeObj = compile(code, pathName, "exec") if RunTabNanny(pathName): win32ui.SetStatusText( "Python and the TabNanny successfully checked the file '" + os.path.basename(pathName) + "'" ) except SyntaxError: _HandlePythonFailure(what, pathName) except: traceback.print_exc() _HandlePythonFailure(what) win32ui.DoWaitCursor(0)
This code looks for the current window, and gets Python to check it without actually executing any code (ie, by compiling only)
171,982
import sys import win32api import win32con import win32ui from . import app defaultToolMenuItems = [ ("Browser", "win32ui.GetApp().OnViewBrowse(0,0)"), ( "Browse PythonPath", "from pywin.tools import browseProjects;browseProjects.Browse()", ), ("Edit Python Path", "from pywin.tools import regedit;regedit.EditRegistry()"), ("COM Makepy utility", "from win32com.client import makepy;makepy.main()"), ( "COM Browser", "from win32com.client import combrowse;combrowse.main(modal=False)", ), ( "Trace Collector Debugging tool", "from pywin.tools import TraceCollector;TraceCollector.MakeOutputWindow()", ), ] import commctrl from pywin.mfc import dialog if win32ui.UNICODE: LVN_ENDLABELEDIT = commctrl.LVN_ENDLABELEDITW else: LVN_ENDLABELEDIT = commctrl.LVN_ENDLABELEDITA def WriteToolMenuItems(items): # Items is a list of (menu, command) # Delete the entire registry tree. try: mainKey = win32ui.GetAppRegistryKey() toolKey = win32api.RegOpenKey(mainKey, "Tools Menu") except win32ui.error: toolKey = None if toolKey is not None: while 1: try: subkey = win32api.RegEnumKey(toolKey, 0) except win32api.error: break win32api.RegDeleteKey(toolKey, subkey) # Keys are now removed - write the new ones. # But first check if we have the defaults - and if so, dont write anything! if items == defaultToolMenuItems: return itemNo = 1 for menu, cmd in items: win32ui.WriteProfileVal("Tools Menu\\%s" % itemNo, "", menu) win32ui.WriteProfileVal("Tools Menu\\%s" % itemNo, "Command", cmd) itemNo = itemNo + 1
null
171,983
import queue import re import win32api import win32con import win32ui from pywin.framework import app, window from pywin.mfc import docview import pywin.scintilla.document from pywin import default_scintilla_encoding from pywin.scintilla import scintillacon class WindowOutputViewRTF(docview.RichEditView, WindowOutputViewImpl): def __init__(self, doc): docview.RichEditView.__init__(self, doc) WindowOutputViewImpl.__init__(self) def OnInitialUpdate(self): WindowOutputViewImpl.OnInitialUpdate(self) return docview.RichEditView.OnInitialUpdate(self) def OnDestroy(self, msg): WindowOutputViewImpl.OnDestroy(self, msg) docview.RichEditView.OnDestroy(self, msg) def HookHandlers(self): WindowOutputViewImpl.HookHandlers(self) # Hook for finding and locating error messages self.HookMessage(self.OnLDoubleClick, win32con.WM_LBUTTONDBLCLK) # docview.RichEditView.HookHandlers(self) def OnLDoubleClick(self, params): if self.HandleSpecialLine(): return 0 # dont pass on return 1 # pass it on by default. def RestoreKillBuffer(self): if len(self.template.killBuffer): self.StreamIn(win32con.SF_RTF, self._StreamRTFIn) self.template.killBuffer = [] def SaveKillBuffer(self): self.StreamOut(win32con.SF_RTFNOOBJS, self._StreamRTFOut) def _StreamRTFOut(self, data): self.template.killBuffer.append(data) return 1 # keep em coming! def _StreamRTFIn(self, bytes): try: item = self.template.killBuffer[0] self.template.killBuffer.remove(item) if bytes < len(item): print("Warning - output buffer not big enough!") return item except IndexError: return None def dowrite(self, str): self.SetSel(-2) self.ReplaceSel(str) import pywin.scintilla.view class WindowOutput(docview.DocTemplate): """Looks like a general Output Window - text can be written by the 'write' method. Will auto-create itself on first write, and also on next write after being closed""" softspace = 1 def __init__( self, title=None, defSize=None, queueing=flags.WQ_LINE, bAutoRestore=1, style=None, makeDoc=None, makeFrame=None, makeView=None, ): """init the output window - Params title=None -- What is the title of the window defSize=None -- What is the default size for the window - if this is a string, the size will be loaded from the ini file. queueing = flags.WQ_LINE -- When should output be written bAutoRestore=1 -- Should a minimized window be restored. style -- Style for Window, or None for default. makeDoc, makeFrame, makeView -- Classes for frame, view and window respectively. """ if makeDoc is None: makeDoc = WindowOutputDocument if makeFrame is None: makeFrame = WindowOutputFrame if makeView is None: makeView = WindowOutputViewScintilla docview.DocTemplate.__init__( self, win32ui.IDR_PYTHONTYPE, makeDoc, makeFrame, makeView ) self.SetDocStrings("\nOutput\n\nText Documents (*.txt)\n.txt\n\n\n") win32ui.GetApp().AddDocTemplate(self) self.writeQueueing = queueing self.errorCantRecreate = 0 self.killBuffer = [] self.style = style self.bAutoRestore = bAutoRestore self.title = title self.bCreating = 0 self.interruptCount = 0 if type(defSize) == type(""): # is a string - maintain size pos from ini file. self.iniSizeSection = defSize self.defSize = app.LoadWindowSize(defSize) self.loadedSize = self.defSize else: self.iniSizeSection = None self.defSize = defSize self.currentView = None self.outputQueue = queue.Queue(-1) self.mainThreadId = win32api.GetCurrentThreadId() self.idleHandlerSet = 0 self.SetIdleHandler() def __del__(self): self.Close() def Create(self, title=None, style=None): self.bCreating = 1 if title: self.title = title if style: self.style = style doc = self.OpenDocumentFile() if doc is None: return self.currentView = doc.GetFirstView() self.bCreating = 0 if self.title: doc.SetTitle(self.title) def Close(self): self.RemoveIdleHandler() try: parent = self.currentView.GetParent() except (AttributeError, win32ui.error): # Already closed return parent.DestroyWindow() def SetTitle(self, title): self.title = title if self.currentView: self.currentView.GetDocument().SetTitle(self.title) def OnViewDestroy(self, view): self.currentView.SaveKillBuffer() self.currentView = None def OnFrameDestroy(self, frame): if self.iniSizeSection: # use GetWindowPlacement(), as it works even when min'd or max'd newSize = frame.GetWindowPlacement()[4] if self.loadedSize != newSize: app.SaveWindowSize(self.iniSizeSection, newSize) def SetIdleHandler(self): if not self.idleHandlerSet: debug("Idle handler set\n") win32ui.GetApp().AddIdleHandler(self.QueueIdleHandler) self.idleHandlerSet = 1 def RemoveIdleHandler(self): if self.idleHandlerSet: debug("Idle handler reset\n") if win32ui.GetApp().DeleteIdleHandler(self.QueueIdleHandler) == 0: debug("Error deleting idle handler\n") self.idleHandlerSet = 0 def RecreateWindow(self): if self.errorCantRecreate: debug("Error = not trying again") return 0 try: # This will fail if app shutting down win32ui.GetMainFrame().GetSafeHwnd() self.Create() return 1 except (win32ui.error, AttributeError): self.errorCantRecreate = 1 debug("Winout can not recreate the Window!\n") return 0 # this handles the idle message, and does the printing. def QueueIdleHandler(self, handler, count): try: bEmpty = self.QueueFlush(20) # If the queue is empty, then we are back to idle and restart interrupt logic. if bEmpty: self.interruptCount = 0 except KeyboardInterrupt: # First interrupt since idle we just pass on. # later ones we dump the queue and give up. self.interruptCount = self.interruptCount + 1 if self.interruptCount > 1: # Drop the queue quickly as the user is already annoyed :-) self.outputQueue = queue.Queue(-1) print("Interrupted.") bEmpty = 1 else: raise # re-raise the error so the users exception filters up. return not bEmpty # More to do if not empty. # Returns true if the Window needs to be recreated. def NeedRecreateWindow(self): try: if self.currentView is not None and self.currentView.IsWindow(): return 0 except ( win32ui.error, AttributeError, ): # Attribute error if the win32ui object has died. pass return 1 # Returns true if the Window is OK (either cos it was, or because it was recreated def CheckRecreateWindow(self): if self.bCreating: return 1 if not self.NeedRecreateWindow(): return 1 if self.bAutoRestore: if self.RecreateWindow(): return 1 return 0 def QueueFlush(self, max=None): # Returns true if the queue is empty after the flush # debug("Queueflush - %d, %d\n" % (max, self.outputQueue.qsize())) if self.bCreating: return 1 items = [] rc = 0 while max is None or max > 0: try: item = self.outputQueue.get_nowait() items.append(item) except queue.Empty: rc = 1 break if max is not None: max = max - 1 if len(items) != 0: if not self.CheckRecreateWindow(): debug(":Recreate failed!\n") return 1 # In trouble - so say we have nothing to do. win32ui.PumpWaitingMessages() # Pump paint messages self.currentView.dowrite("".join(items)) return rc def HandleOutput(self, message): # debug("QueueOutput on thread %d, flags %d with '%s'...\n" % (win32api.GetCurrentThreadId(), self.writeQueueing, message )) self.outputQueue.put(message) if win32api.GetCurrentThreadId() != self.mainThreadId: pass # debug("not my thread - ignoring queue options!\n") elif self.writeQueueing == flags.WQ_LINE: pos = message.rfind("\n") if pos >= 0: # debug("Line queueing - forcing flush\n") self.QueueFlush() return elif self.writeQueueing == flags.WQ_NONE: # debug("WQ_NONE - flushing!\n") self.QueueFlush() return # Let our idle handler get it - wake it up try: win32ui.GetMainFrame().PostMessage( win32con.WM_USER ) # Kick main thread off. except win32ui.error: # This can happen as the app is shutting down, so we send it to the C++ debugger win32api.OutputDebugString(message) # delegate certain fns to my view. def writelines(self, lines): for line in lines: self.write(line) def write(self, message): self.HandleOutput(message) def flush(self): self.QueueFlush() def HandleSpecialLine(self): self.currentView.HandleSpecialLine() def RTFWindowOutput(*args, **kw): kw["makeView"] = WindowOutputViewRTF return WindowOutput(*args, **kw)
null
171,984
import queue import re import win32api import win32con import win32ui from pywin.framework import app, window from pywin.mfc import docview import pywin.scintilla.document from pywin import default_scintilla_encoding from pywin.scintilla import scintillacon import pywin.scintilla.view def thread_test(o): for i in range(5): o.write("Hi from thread %d\n" % (win32api.GetCurrentThreadId())) win32api.Sleep(100)
null
171,985
import sys import commctrl import win32api import win32con import win32ui from pywin.mfc import dialog, docview, object, window from win32api import RGB def GetItemText(item): if type(item) == type(()) or type(item) == type([]): use = item[0] else: use = item if type(use) == type(""): return use else: return repr(item)
null
171,986
import glob import os import pyclbr import afxres import commctrl import pywin.framework.scriptutils import regutil import win32api import win32con import win32ui from pywin.mfc import dialog from . import hierlist class HLIModuleItem(hierlist.HierListItem): def __init__(self, path): hierlist.HierListItem.__init__(self) self.path = path def GetText(self): return os.path.split(self.path)[1] + " (module)" def IsExpandable(self): return 1 def TakeDefaultAction(self): win32ui.GetApp().OpenDocumentFile(self.path) def GetBitmapColumn(self): col = 4 # Default try: if win32api.GetFileAttributes(self.path) & win32con.FILE_ATTRIBUTE_READONLY: col = 5 except win32api.error: pass return col def GetSubList(self): mod, path = pywin.framework.scriptutils.GetPackageModuleName(self.path) win32ui.SetStatusText("Building class list - please wait...", 1) win32ui.DoWaitCursor(1) try: try: reader = pyclbr.readmodule_ex # Post 1.5.2 interface. extra_msg = " or functions" except AttributeError: reader = pyclbr.readmodule extra_msg = "" data = reader(mod, [path]) if data: ret = [] for item in data.values(): if ( item.__class__ != pyclbr.Class ): # ie, it is a pyclbr Function instance (only introduced post 1.5.2) ret.append(HLICLBRFunction(item, " (function)")) else: ret.append(HLICLBRClass(item, " (class)")) ret.sort() return ret else: return [HLIErrorItem("No Python classes%s in module." % (extra_msg,))] finally: win32ui.DoWaitCursor(0) win32ui.SetStatusText(win32ui.LoadString(afxres.AFX_IDS_IDLEMESSAGE)) class HLIDirectoryItem(hierlist.HierListItem): def __init__(self, path, displayName=None, bSubDirs=0): hierlist.HierListItem.__init__(self) self.path = path self.bSubDirs = bSubDirs if displayName: self.displayName = displayName else: self.displayName = path def IsExpandable(self): return 1 def GetText(self): return self.displayName def GetSubList(self): ret = MakePathSubList(self.path) if ( os.path.split(self.path)[1] == "win32com" ): # Complete and utter hack for win32com. try: path = win32api.GetFullPathName( os.path.join(self.path, "..\\win32comext") ) ret = ret + MakePathSubList(path) except win32ui.error: pass return ret def MakePathSubList(path): ret = [] for filename in glob.glob(os.path.join(path, "*")): if os.path.isdir(filename) and os.path.isfile( os.path.join(filename, "__init__.py") ): ret.append(HLIDirectoryItem(filename, os.path.split(filename)[1])) else: if os.path.splitext(filename)[1].lower() in [".py", ".pyw"]: ret.append(HLIModuleItem(filename)) return ret
null
171,987
import glob import os import pyclbr import afxres import commctrl import pywin.framework.scriptutils import regutil import win32api import win32con import win32ui from pywin.mfc import dialog from . import hierlist class HLIRoot(hierlist.HierListItem): def __init__(self): hierlist.HierListItem.__init__(self) def IsExpandable(self): return 1 def GetSubList(self): keyStr = regutil.BuildDefaultPythonKey() + "\\PythonPath" hKey = win32api.RegOpenKey(regutil.GetRootKey(), keyStr) try: ret = [] ret.append(HLIProjectRoot("", "Standard Python Library")) # The core path. index = 0 while 1: try: ret.append(HLIProjectRoot(win32api.RegEnumKey(hKey, index))) index = index + 1 except win32api.error: break return ret finally: win32api.RegCloseKey(hKey) class dynamic_browser(dialog.Dialog): style = win32con.WS_OVERLAPPEDWINDOW | win32con.WS_VISIBLE cs = ( win32con.WS_CHILD | win32con.WS_VISIBLE | commctrl.TVS_HASLINES | commctrl.TVS_LINESATROOT | commctrl.TVS_HASBUTTONS ) dt = [ ["Python Projects", (0, 0, 200, 200), style, None, (8, "MS Sans Serif")], ["SysTreeView32", None, win32ui.IDC_LIST1, (0, 0, 200, 200), cs], ] def __init__(self, hli_root): dialog.Dialog.__init__(self, self.dt) self.hier_list = hierlist.HierListWithItems(hli_root, win32ui.IDB_BROWSER_HIER) self.HookMessage(self.on_size, win32con.WM_SIZE) def OnInitDialog(self): self.hier_list.HierInit(self) return dialog.Dialog.OnInitDialog(self) def on_size(self, params): lparam = params[3] w = win32api.LOWORD(lparam) h = win32api.HIWORD(lparam) self.GetDlgItem(win32ui.IDC_LIST1).MoveWindow((0, 0, w, h)) def BrowseDialog(): root = HLIRoot() if not root.IsExpandable(): raise TypeError( "Browse() argument must have __dict__ attribute, or be a Browser supported type" ) dlg = dynamic_browser(root) dlg.CreateWindow()
null
171,988
import glob import os import pyclbr import afxres import commctrl import pywin.framework.scriptutils import regutil import win32api import win32con import win32ui from pywin.mfc import dialog from . import hierlist def DockableBrowserCreator(parent): root = HLIRoot() hl = hierlist.HierListWithItems(root, win32ui.IDB_BROWSER_HIER) style = ( win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.WS_BORDER | commctrl.TVS_HASLINES | commctrl.TVS_LINESATROOT | commctrl.TVS_HASBUTTONS ) control = win32ui.CreateTreeCtrl() control.CreateWindow(style, (0, 0, 150, 300), parent, win32ui.IDC_LIST1) list = hl.HierInit(parent, control) return control def DockablePathBrowser(): import pywin.docking.DockingBar bar = pywin.docking.DockingBar.DockingBar() bar.CreateWindow( win32ui.GetMainFrame(), DockableBrowserCreator, "Path Browser", 0x8E0A ) bar.SetBarStyle( bar.GetBarStyle() | afxres.CBRS_TOOLTIPS | afxres.CBRS_FLYBY | afxres.CBRS_SIZE_DYNAMIC ) bar.EnableDocking(afxres.CBRS_ALIGN_ANY) win32ui.GetMainFrame().DockControlBar(bar)
null
171,989
import _thread import win32api import win32event import win32trace from pywin.framework import winout def CollectorThread(stopEvent, file): win32trace.InitRead() handle = win32trace.GetHandle() # Run this thread at a lower priority to the main message-loop (and printing output) # thread can keep up import win32process win32process.SetThreadPriority( win32api.GetCurrentThread(), win32process.THREAD_PRIORITY_BELOW_NORMAL ) try: while 1: rc = win32event.WaitForMultipleObjects( (handle, stopEvent), 0, win32event.INFINITE ) if rc == win32event.WAIT_OBJECT_0: # About the only char we can't live with is \0! file.write(win32trace.read().replace("\0", "<null>")) else: # Stop event break finally: win32trace.TermRead() print("Thread dieing")
null
171,990
import _thread import win32api import win32event import win32trace from pywin.framework import winout outputWindow = None class WindowOutput(winout.WindowOutput): def __init__(self, *args): winout.WindowOutput.__init__(*(self,) + args) self.hStopThread = win32event.CreateEvent(None, 0, 0, None) _thread.start_new(CollectorThread, (self.hStopThread, self)) def _StopThread(self): win32event.SetEvent(self.hStopThread) self.hStopThread = None def Close(self): self._StopThread() winout.WindowOutput.Close(self) # def OnViewDestroy(self, frame): # return winout.WindowOutput.OnViewDestroy(self, frame) # def Create(self, title=None, style = None): # rc = winout.WindowOutput.Create(self, title, style) return rc def MakeOutputWindow(): # Note that it will not show until the first string written or # you pass bShow = 1 global outputWindow if outputWindow is None: title = "Python Trace Collector" # queueingFlag doesnt matter, as all output will come from new thread outputWindow = WindowOutput(title, title) # Let people know what this does! msg = """\ # This window will display output from any programs that import win32traceutil # win32com servers registered with '--debug' are in this category. """ outputWindow.write(msg) # force existing window open outputWindow.write("") return outputWindow
null
171,991
import commctrl import regutil import win32api import win32con import win32ui from pywin.mfc import dialog, docview, window from . import hierlist def SafeApply(fn, args, err_desc=""): try: fn(*args) return 1 except win32api.error as exc: msg = "Error " + err_desc + "\r\n\r\n" + exc.strerror win32ui.MessageBox(msg) return 0
null
171,992
import commctrl import regutil import win32api import win32con import win32ui from pywin.mfc import dialog, docview, window from . import hierlist template = RegTemplate() def EditRegistry(root=None, key=None): doc = template.OpenRegistryKey(root, key)
null
171,993
import commctrl import dialog import win32con import win32ui class RegistryPage(RegEditPropertyPage): def __init__(self): def OnInitDialog(self): class RegistrySheet(dialog.PropertySheet): def __init__(self, title): def OnActivate(self, msg): def t(): ps = RegistrySheet("Registry Settings") ps.AddPage(RegistryPage()) ps.DoModal()
null
171,994
import sys import types import __main__ import win32ui from pywin.mfc import dialog from . import hierlist class DialogShowObject(dialog.Dialog): def __init__(self, object, title): self.object = object self.title = title dialog.Dialog.__init__(self, win32ui.IDD_LARGE_EDIT) def OnInitDialog(self): import re self.SetWindowText(self.title) self.edit = self.GetDlgItem(win32ui.IDC_EDIT1) try: strval = str(self.object) except: t, v, tb = sys.exc_info() strval = "Exception getting object value\n\n%s:%s" % (t, v) tb = None strval = re.sub("\n", "\r\n", strval) self.edit.ReplaceSel(strval) import commctrl import win32api import win32con from pywin.mfc import docview def ShowObject(object, title): dlg = DialogShowObject(object, title) dlg.DoModal()
null
171,995
import sys import types import __main__ import win32ui from pywin.mfc import dialog from . import hierlist def MakeHLI(ob, name=None): try: cls = TypeMap[type(ob)] except KeyError: # hrmph - this check gets more and more bogus as Python # improves. Its possible we should just *always* use # HLIInstance? if hasattr(ob, "__class__"): # 'new style' class cls = HLIInstance else: cls = HLIPythonObject return cls(ob, name) import commctrl import win32api import win32con class dynamic_browser(dialog.Dialog): style = win32con.WS_OVERLAPPEDWINDOW | win32con.WS_VISIBLE cs = ( win32con.WS_CHILD | win32con.WS_VISIBLE | commctrl.TVS_HASLINES | commctrl.TVS_LINESATROOT | commctrl.TVS_HASBUTTONS ) dt = [ ["Python Object Browser", (0, 0, 200, 200), style, None, (8, "MS Sans Serif")], ["SysTreeView32", None, win32ui.IDC_LIST1, (0, 0, 200, 200), cs], ] def __init__(self, hli_root): dialog.Dialog.__init__(self, self.dt) self.hier_list = hierlist.HierListWithItems(hli_root, win32ui.IDB_BROWSER_HIER) self.HookMessage(self.on_size, win32con.WM_SIZE) def OnInitDialog(self): self.hier_list.HierInit(self) return dialog.Dialog.OnInitDialog(self) def OnOK(self): self.hier_list.HierTerm() self.hier_list = None return self._obj_.OnOK() def OnCancel(self): self.hier_list.HierTerm() self.hier_list = None return self._obj_.OnCancel() def on_size(self, params): lparam = params[3] w = win32api.LOWORD(lparam) h = win32api.HIWORD(lparam) self.GetDlgItem(win32ui.IDC_LIST1).MoveWindow((0, 0, w, h)) from pywin.mfc import docview The provided code snippet includes necessary dependencies for implementing the `Browse` function. Write a Python function `def Browse(ob=__main__)` to solve the following problem: Browse the argument, or the main dictionary Here is the function: def Browse(ob=__main__): "Browse the argument, or the main dictionary" root = MakeHLI(ob, "root") if not root.IsExpandable(): raise TypeError( "Browse() argument must have __dict__ attribute, or be a Browser supported type" ) dlg = dynamic_browser(root) dlg.CreateWindow() return dlg
Browse the argument, or the main dictionary
171,996
import sys import types import __main__ import win32ui from pywin.mfc import dialog from . import hierlist def MakeHLI(ob, name=None): try: cls = TypeMap[type(ob)] except KeyError: # hrmph - this check gets more and more bogus as Python # improves. Its possible we should just *always* use # HLIInstance? if hasattr(ob, "__class__"): # 'new style' class cls = HLIInstance else: cls = HLIPythonObject return cls(ob, name) import commctrl import win32api import win32con from pywin.mfc import docview template = None def MakeTemplate(): global template if template is None: template = ( BrowserTemplate() ) # win32ui.IDR_PYTHONTYPE, BrowserDocument, None, BrowserView) The provided code snippet includes necessary dependencies for implementing the `BrowseMDI` function. Write a Python function `def BrowseMDI(ob=__main__)` to solve the following problem: Browse an object using an MDI window. Here is the function: def BrowseMDI(ob=__main__): """Browse an object using an MDI window.""" MakeTemplate() root = MakeHLI(ob, repr(ob)) if not root.IsExpandable(): raise TypeError( "Browse() argument must have __dict__ attribute, or be a Browser supported type" ) template.OpenObject(root)
Browse an object using an MDI window.
171,997
import contextlib import enum import inspect import os import re import sys import types import typing as t from ast import literal_eval from warnings import warn, warn_explicit from .utils.bunch import Bunch from .utils.descriptions import add_article, class_of, describe, repr_type from .utils.getargspec import getargspec from .utils.importstring import import_item from .utils.sentinel import Sentinel def isidentifier(s): return s.isidentifier()
null
171,998
import contextlib import enum import inspect import os import re import sys import types import typing as t from ast import literal_eval from warnings import warn, warn_explicit from .utils.bunch import Bunch from .utils.descriptions import add_article, class_of, describe, repr_type from .utils.getargspec import getargspec from .utils.importstring import import_item from .utils.sentinel import Sentinel def _should_warn(key): """Add our own checks for too many deprecation warnings. Limit to once per package. """ env_flag = os.environ.get("TRAITLETS_ALL_DEPRECATIONS") if env_flag and env_flag != "0": return True if key not in _deprecations_shown: _deprecations_shown.add(key) return True else: return False The provided code snippet includes necessary dependencies for implementing the `_deprecated_method` function. Write a Python function `def _deprecated_method(method, cls, method_name, msg)` to solve the following problem: Show deprecation warning about a magic method definition. Uses warn_explicit to bind warning to method definition instead of triggering code, which isn't relevant. Here is the function: def _deprecated_method(method, cls, method_name, msg): """Show deprecation warning about a magic method definition. Uses warn_explicit to bind warning to method definition instead of triggering code, which isn't relevant. """ warn_msg = "{classname}.{method_name} is deprecated in traitlets 4.1: {msg}".format( classname=cls.__name__, method_name=method_name, msg=msg ) for parent in inspect.getmro(cls): if method_name in parent.__dict__: cls = parent break # limit deprecation messages to once per package package_name = cls.__module__.split(".", 1)[0] key = (package_name, msg) if not _should_warn(key): return try: fname = inspect.getsourcefile(method) or "<unknown>" lineno = inspect.getsourcelines(method)[1] or 0 except (OSError, TypeError) as e: # Failed to inspect for some reason warn(warn_msg + ("\n(inspection failed) %s" % e), DeprecationWarning) else: warn_explicit(warn_msg, DeprecationWarning, fname, lineno)
Show deprecation warning about a magic method definition. Uses warn_explicit to bind warning to method definition instead of triggering code, which isn't relevant.
171,999
import contextlib import enum import inspect import os import re import sys import types import typing as t from ast import literal_eval from warnings import warn, warn_explicit from .utils.bunch import Bunch from .utils.descriptions import add_article, class_of, describe, repr_type from .utils.getargspec import getargspec from .utils.importstring import import_item from .utils.sentinel import Sentinel def literal_eval(node_or_string: Union[str, AST]) -> Any: ... The provided code snippet includes necessary dependencies for implementing the `_safe_literal_eval` function. Write a Python function `def _safe_literal_eval(s)` to solve the following problem: Safely evaluate an expression Returns original string if eval fails. Use only where types are ambiguous. Here is the function: def _safe_literal_eval(s): """Safely evaluate an expression Returns original string if eval fails. Use only where types are ambiguous. """ try: return literal_eval(s) except (NameError, SyntaxError, ValueError): return s
Safely evaluate an expression Returns original string if eval fails. Use only where types are ambiguous.
172,000
import contextlib import enum import inspect import os import re import sys import types import typing as t from ast import literal_eval from warnings import warn, warn_explicit from .utils.bunch import Bunch from .utils.descriptions import add_article, class_of, describe, repr_type from .utils.getargspec import getargspec from .utils.importstring import import_item from .utils.sentinel import Sentinel All = Sentinel( "All", "traitlets", """ Used in Traitlets to listen to all types of notification or to notifications from all trait attributes. """, ) The provided code snippet includes necessary dependencies for implementing the `parse_notifier_name` function. Write a Python function `def parse_notifier_name(names)` to solve the following problem: Convert the name argument to a list of names. Examples -------- >>> parse_notifier_name([]) [traitlets.All] >>> parse_notifier_name("a") ['a'] >>> parse_notifier_name(["a", "b"]) ['a', 'b'] >>> parse_notifier_name(All) [traitlets.All] Here is the function: def parse_notifier_name(names): """Convert the name argument to a list of names. Examples -------- >>> parse_notifier_name([]) [traitlets.All] >>> parse_notifier_name("a") ['a'] >>> parse_notifier_name(["a", "b"]) ['a', 'b'] >>> parse_notifier_name(All) [traitlets.All] """ if names is All or isinstance(names, str): return [names] else: if not names or All in names: return [All] for n in names: if not isinstance(n, str): raise TypeError("names must be strings, not %r" % n) return names
Convert the name argument to a list of names. Examples -------- >>> parse_notifier_name([]) [traitlets.All] >>> parse_notifier_name("a") ['a'] >>> parse_notifier_name(["a", "b"]) ['a', 'b'] >>> parse_notifier_name(All) [traitlets.All]
172,001
import contextlib import enum import inspect import os import re import sys import types import typing as t from ast import literal_eval from warnings import warn, warn_explicit from .utils.bunch import Bunch from .utils.descriptions import add_article, class_of, describe, repr_type from .utils.getargspec import getargspec from .utils.importstring import import_item from .utils.sentinel import Sentinel class HasTraits(HasDescriptors, metaclass=MetaHasTraits): _trait_values: t.Dict[str, t.Any] _static_immutable_initial_values: t.Dict[str, t.Any] _trait_notifiers: t.Dict[str, t.Any] _trait_validators: t.Dict[str, t.Any] _cross_validation_lock: bool _traits: t.Dict[str, t.Any] _all_trait_default_generators: t.Dict[str, t.Any] def setup_instance(*args, **kwargs): # Pass self as args[0] to allow "self" as keyword argument self = args[0] args = args[1:] # although we'd prefer to set only the initial values not present # in kwargs, we will overwrite them in `__init__`, and simply making # a copy of a dict is faster than checking for each key. self._trait_values = self._static_immutable_initial_values.copy() self._trait_notifiers = {} self._trait_validators = {} self._cross_validation_lock = False super(HasTraits, self).setup_instance(*args, **kwargs) def __init__(self, *args, **kwargs): # Allow trait values to be set using keyword arguments. # We need to use setattr for this to trigger validation and # notifications. super_args = args super_kwargs = {} if kwargs: # this is a simplified (and faster) version of # the hold_trait_notifications(self) context manager def ignore(*_ignore_args): pass self.notify_change = ignore # type:ignore[assignment] self._cross_validation_lock = True changes = {} for key, value in kwargs.items(): if self.has_trait(key): setattr(self, key, value) changes[key] = Bunch( name=key, old=None, new=value, owner=self, type="change", ) else: # passthrough args that don't set traits to super super_kwargs[key] = value # notify and cross validate all trait changes that were set in kwargs changed = set(kwargs) & set(self._traits) for key in changed: value = self._traits[key]._cross_validate(self, getattr(self, key)) self.set_trait(key, value) changes[key]['new'] = value self._cross_validation_lock = False # Restore method retrieval from class del self.notify_change for key in changed: self.notify_change(changes[key]) try: super().__init__(*super_args, **super_kwargs) except TypeError as e: arg_s_list = [repr(arg) for arg in super_args] for k, v in super_kwargs.items(): arg_s_list.append(f"{k}={v!r}") arg_s = ", ".join(arg_s_list) warn( "Passing unrecognized arguments to super({classname}).__init__({arg_s}).\n" "{error}\n" "This is deprecated in traitlets 4.2." "This error will be raised in a future release of traitlets.".format( arg_s=arg_s, classname=self.__class__.__name__, error=e, ), DeprecationWarning, stacklevel=2, ) def __getstate__(self): d = self.__dict__.copy() # event handlers stored on an instance are # expected to be reinstantiated during a # recall of instance_init during __setstate__ d["_trait_notifiers"] = {} d["_trait_validators"] = {} d["_trait_values"] = self._trait_values.copy() d["_cross_validation_lock"] = False # FIXME: raise if cloning locked! return d def __setstate__(self, state): self.__dict__ = state.copy() # event handlers are reassigned to self cls = self.__class__ for key in dir(cls): # Some descriptors raise AttributeError like zope.interface's # __provides__ attributes even though they exist. This causes # AttributeErrors even though they are listed in dir(cls). try: value = getattr(cls, key) except AttributeError: pass else: if isinstance(value, EventHandler): value.instance_init(self) def cross_validation_lock(self): """ A contextmanager for running a block with our cross validation lock set to True. At the end of the block, the lock's value is restored to its value prior to entering the block. """ if self._cross_validation_lock: yield return else: try: self._cross_validation_lock = True yield finally: self._cross_validation_lock = False def hold_trait_notifications(self): """Context manager for bundling trait change notifications and cross validation. Use this when doing multiple trait assignments (init, config), to avoid race conditions in trait notifiers requesting other trait values. All trait notifications will fire after all values have been assigned. """ if self._cross_validation_lock: yield return else: cache: t.Dict[str, t.Any] = {} def compress(past_changes, change): """Merges the provided change with the last if possible.""" if past_changes is None: return [change] else: if past_changes[-1]["type"] == "change" and change.type == "change": past_changes[-1]["new"] = change.new else: # In case of changes other than 'change', append the notification. past_changes.append(change) return past_changes def hold(change): name = change.name cache[name] = compress(cache.get(name), change) try: # Replace notify_change with `hold`, caching and compressing # notifications, disable cross validation and yield. self.notify_change = hold # type:ignore[assignment] self._cross_validation_lock = True yield # Cross validate final values when context is released. for name in list(cache.keys()): trait = getattr(self.__class__, name) value = trait._cross_validate(self, getattr(self, name)) self.set_trait(name, value) except TraitError as e: # Roll back in case of TraitError during final cross validation. self.notify_change = lambda x: None # type:ignore[assignment] for name, changes in cache.items(): for change in changes[::-1]: # TODO: Separate in a rollback function per notification type. if change.type == "change": if change.old is not Undefined: self.set_trait(name, change.old) else: self._trait_values.pop(name) cache = {} raise e finally: self._cross_validation_lock = False # Restore method retrieval from class del self.notify_change # trigger delayed notifications for changes in cache.values(): for change in changes: self.notify_change(change) def _notify_trait(self, name, old_value, new_value): self.notify_change( Bunch( name=name, old=old_value, new=new_value, owner=self, type="change", ) ) def notify_change(self, change): """Notify observers of a change event""" return self._notify_observers(change) def _notify_observers(self, event): """Notify observers of any event""" if not isinstance(event, Bunch): # cast to bunch if given a dict event = Bunch(event) name, type = event['name'], event['type'] callables = [] if name in self._trait_notifiers: callables.extend(self._trait_notifiers.get(name, {}).get(type, [])) callables.extend(self._trait_notifiers.get(name, {}).get(All, [])) if All in self._trait_notifiers: # type:ignore[comparison-overlap] callables.extend( self._trait_notifiers.get(All, {}).get(type, []) # type:ignore[call-overload] ) callables.extend( self._trait_notifiers.get(All, {}).get(All, []) # type:ignore[call-overload] ) # Now static ones magic_name = "_%s_changed" % name if event['type'] == "change" and hasattr(self, magic_name): class_value = getattr(self.__class__, magic_name) if not isinstance(class_value, ObserveHandler): _deprecated_method( class_value, self.__class__, magic_name, "use @observe and @unobserve instead.", ) cb = getattr(self, magic_name) # Only append the magic method if it was not manually registered if cb not in callables: callables.append(_callback_wrapper(cb)) # Call them all now # Traits catches and logs errors here. I allow them to raise for c in callables: # Bound methods have an additional 'self' argument. if isinstance(c, _CallbackWrapper): c = c.__call__ elif isinstance(c, EventHandler) and c.name is not None: c = getattr(self, c.name) c(event) def _add_notifiers(self, handler, name, type): if name not in self._trait_notifiers: nlist: t.List[t.Any] = [] self._trait_notifiers[name] = {type: nlist} else: if type not in self._trait_notifiers[name]: nlist = [] self._trait_notifiers[name][type] = nlist else: nlist = self._trait_notifiers[name][type] if handler not in nlist: nlist.append(handler) def _remove_notifiers(self, handler, name, type): try: if handler is None: del self._trait_notifiers[name][type] else: self._trait_notifiers[name][type].remove(handler) except KeyError: pass def on_trait_change(self, handler=None, name=None, remove=False): """DEPRECATED: Setup a handler to be called when a trait changes. This is used to setup dynamic notifications of trait changes. Static handlers can be created by creating methods on a HasTraits subclass with the naming convention '_[traitname]_changed'. Thus, to create static handler for the trait 'a', create the method _a_changed(self, name, old, new) (fewer arguments can be used, see below). If `remove` is True and `handler` is not specified, all change handlers for the specified name are uninstalled. Parameters ---------- handler : callable, None A callable that is called when a trait changes. Its signature can be handler(), handler(name), handler(name, new), handler(name, old, new), or handler(name, old, new, self). name : list, str, None If None, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name. remove : bool If False (the default), then install the handler. If True then unintall it. """ warn( "on_trait_change is deprecated in traitlets 4.1: use observe instead", DeprecationWarning, stacklevel=2, ) if name is None: name = All if remove: self.unobserve(_callback_wrapper(handler), names=name) else: self.observe(_callback_wrapper(handler), names=name) def observe(self, handler, names=All, type="change"): """Setup a handler to be called when a trait changes. This is used to setup dynamic notifications of trait changes. Parameters ---------- handler : callable A callable that is called when a trait changes. Its signature should be ``handler(change)``, where ``change`` is a dictionary. The change dictionary at least holds a 'type' key. * ``type``: the type of notification. Other keys may be passed depending on the value of 'type'. In the case where type is 'change', we also have the following keys: * ``owner`` : the HasTraits instance * ``old`` : the old value of the modified trait attribute * ``new`` : the new value of the modified trait attribute * ``name`` : the name of the modified trait attribute. names : list, str, All If names is All, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name. type : str, All (default: 'change') The type of notification to filter by. If equal to All, then all notifications are passed to the observe handler. """ names = parse_notifier_name(names) for n in names: self._add_notifiers(handler, n, type) def unobserve(self, handler, names=All, type="change"): """Remove a trait change handler. This is used to unregister handlers to trait change notifications. Parameters ---------- handler : callable The callable called when a trait attribute changes. names : list, str, All (default: All) The names of the traits for which the specified handler should be uninstalled. If names is All, the specified handler is uninstalled from the list of notifiers corresponding to all changes. type : str or All (default: 'change') The type of notification to filter by. If All, the specified handler is uninstalled from the list of notifiers corresponding to all types. """ names = parse_notifier_name(names) for n in names: self._remove_notifiers(handler, n, type) def unobserve_all(self, name=All): """Remove trait change handlers of any type for the specified name. If name is not specified, removes all trait notifiers.""" if name is All: self._trait_notifiers: t.Dict[str, t.Any] = {} else: try: del self._trait_notifiers[name] except KeyError: pass def _register_validator(self, handler, names): """Setup a handler to be called when a trait should be cross validated. This is used to setup dynamic notifications for cross-validation. If a validator is already registered for any of the provided names, a TraitError is raised and no new validator is registered. Parameters ---------- handler : callable A callable that is called when the given trait is cross-validated. Its signature is handler(proposal), where proposal is a Bunch (dictionary with attribute access) with the following attributes/keys: * ``owner`` : the HasTraits instance * ``value`` : the proposed value for the modified trait attribute * ``trait`` : the TraitType instance associated with the attribute names : List of strings The names of the traits that should be cross-validated """ for name in names: magic_name = "_%s_validate" % name if hasattr(self, magic_name): class_value = getattr(self.__class__, magic_name) if not isinstance(class_value, ValidateHandler): _deprecated_method( class_value, self.__class__, magic_name, "use @validate decorator instead.", ) for name in names: self._trait_validators[name] = handler def add_traits(self, **traits): """Dynamically add trait attributes to the HasTraits instance.""" cls = self.__class__ attrs = {"__module__": cls.__module__} if hasattr(cls, "__qualname__"): # __qualname__ introduced in Python 3.3 (see PEP 3155) attrs["__qualname__"] = cls.__qualname__ attrs.update(traits) self.__class__ = type(cls.__name__, (cls,), attrs) for trait in traits.values(): trait.instance_init(self) def set_trait(self, name, value): """Forcibly sets trait attribute, including read-only attributes.""" cls = self.__class__ if not self.has_trait(name): raise TraitError(f"Class {cls.__name__} does not have a trait named {name}") else: getattr(cls, name).set(self, value) def class_trait_names(cls, **metadata): """Get a list of all the names of this class' traits. This method is just like the :meth:`trait_names` method, but is unbound. """ return list(cls.class_traits(**metadata)) def class_traits(cls, **metadata): """Get a ``dict`` of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects. This method is just like the :meth:`traits` method, but is unbound. The TraitTypes returned don't know anything about the values that the various HasTrait's instances are holding. The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn't exist, None will be passed to the function. """ traits = cls._traits.copy() if len(metadata) == 0: return traits result = {} for name, trait in traits.items(): for meta_name, meta_eval in metadata.items(): if not callable(meta_eval): meta_eval = _SimpleTest(meta_eval) if not meta_eval(trait.metadata.get(meta_name, None)): break else: result[name] = trait return result def class_own_traits(cls, **metadata): """Get a dict of all the traitlets defined on this class, not a parent. Works like `class_traits`, except for excluding traits from parents. """ sup = super(cls, cls) return { n: t for (n, t) in cls.class_traits(**metadata).items() if getattr(sup, n, None) is not t } def has_trait(self, name): """Returns True if the object has a trait with the specified name.""" return name in self._traits def trait_has_value(self, name): """Returns True if the specified trait has a value. This will return false even if ``getattr`` would return a dynamically generated default value. These default values will be recognized as existing only after they have been generated. Example .. code-block:: python class MyClass(HasTraits): i = Int() mc = MyClass() assert not mc.trait_has_value("i") mc.i # generates a default value assert mc.trait_has_value("i") """ return name in self._trait_values def trait_values(self, **metadata): """A ``dict`` of trait names and their values. The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn't exist, None will be passed to the function. Returns ------- A ``dict`` of trait names and their values. Notes ----- Trait values are retrieved via ``getattr``, any exceptions raised by traits or the operations they may trigger will result in the absence of a trait value in the result ``dict``. """ return {name: getattr(self, name) for name in self.trait_names(**metadata)} def _get_trait_default_generator(self, name): """Return default generator for a given trait Walk the MRO to resolve the correct default generator according to inheritance. """ method_name = "_%s_default" % name if method_name in self.__dict__: return getattr(self, method_name) if method_name in self.__class__.__dict__: return getattr(self.__class__, method_name) return self._all_trait_default_generators[name] def trait_defaults(self, *names, **metadata): """Return a trait's default value or a dictionary of them Notes ----- Dynamically generated default values may depend on the current state of the object.""" for n in names: if not self.has_trait(n): raise TraitError(f"'{n}' is not a trait of '{type(self).__name__}' instances") if len(names) == 1 and len(metadata) == 0: return self._get_trait_default_generator(names[0])(self) trait_names = self.trait_names(**metadata) trait_names.extend(names) defaults = {} for n in trait_names: defaults[n] = self._get_trait_default_generator(n)(self) return defaults def trait_names(self, **metadata): """Get a list of all the names of this class' traits.""" return list(self.traits(**metadata)) def traits(self, **metadata): """Get a ``dict`` of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects. The TraitTypes returned don't know anything about the values that the various HasTrait's instances are holding. The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn't exist, None will be passed to the function. """ traits = self._traits.copy() if len(metadata) == 0: return traits result = {} for name, trait in traits.items(): for meta_name, meta_eval in metadata.items(): if not callable(meta_eval): meta_eval = _SimpleTest(meta_eval) if not meta_eval(trait.metadata.get(meta_name, None)): break else: result[name] = trait return result def trait_metadata(self, traitname, key, default=None): """Get metadata values for trait by key.""" try: trait = getattr(self.__class__, traitname) except AttributeError as e: raise TraitError( f"Class {self.__class__.__name__} does not have a trait named {traitname}" ) from e metadata_name = "_" + traitname + "_metadata" if hasattr(self, metadata_name) and key in getattr(self, metadata_name): return getattr(self, metadata_name).get(key, default) else: return trait.metadata.get(key, default) def class_own_trait_events(cls, name): """Get a dict of all event handlers defined on this class, not a parent. Works like ``event_handlers``, except for excluding traits from parents. """ sup = super(cls, cls) return { n: e for (n, e) in cls.events(name).items() # type:ignore[attr-defined] if getattr(sup, n, None) is not e } def trait_events(cls, name=None): """Get a ``dict`` of all the event handlers of this class. Parameters ---------- name : str (default: None) The name of a trait of this class. If name is ``None`` then all the event handlers of this class will be returned instead. Returns ------- The event handlers associated with a trait name, or all event handlers. """ events = {} for k, v in getmembers(cls): if isinstance(v, EventHandler): if name is None: events[k] = v elif name in v.trait_names: # type:ignore[attr-defined] events[k] = v elif hasattr(v, "tags"): if cls.trait_names(**v.tags): events[k] = v return events The provided code snippet includes necessary dependencies for implementing the `_validate_link` function. Write a Python function `def _validate_link(*tuples)` to solve the following problem: Validate arguments for traitlet link functions Here is the function: def _validate_link(*tuples): """Validate arguments for traitlet link functions""" for tup in tuples: if not len(tup) == 2: raise TypeError( "Each linked traitlet must be specified as (HasTraits, 'trait_name'), not %r" % t ) obj, trait_name = tup if not isinstance(obj, HasTraits): raise TypeError("Each object must be HasTraits, not %r" % type(obj)) if trait_name not in obj.traits(): raise TypeError(f"{obj!r} has no trait {trait_name!r}")
Validate arguments for traitlet link functions
172,002
import contextlib import enum import inspect import os import re import sys import types import typing as t from ast import literal_eval from warnings import warn, warn_explicit from .utils.bunch import Bunch from .utils.descriptions import add_article, class_of, describe, repr_type from .utils.getargspec import getargspec from .utils.importstring import import_item from .utils.sentinel import Sentinel class _CallbackWrapper: """An object adapting a on_trait_change callback into an observe callback. The comparison operator __eq__ is implemented to enable removal of wrapped callbacks. """ def __init__(self, cb): self.cb = cb # Bound methods have an additional 'self' argument. offset = -1 if isinstance(self.cb, types.MethodType) else 0 self.nargs = len(getargspec(cb)[0]) + offset if self.nargs > 4: raise TraitError("a trait changed callback must have 0-4 arguments.") def __eq__(self, other): # The wrapper is equal to the wrapped element if isinstance(other, _CallbackWrapper): return self.cb == other.cb else: return self.cb == other def __call__(self, change): # The wrapper is callable if self.nargs == 0: self.cb() elif self.nargs == 1: self.cb(change.name) elif self.nargs == 2: self.cb(change.name, change.new) elif self.nargs == 3: self.cb(change.name, change.old, change.new) elif self.nargs == 4: self.cb(change.name, change.old, change.new, change.owner) def _callback_wrapper(cb): if isinstance(cb, _CallbackWrapper): return cb else: return _CallbackWrapper(cb)
null
172,003
import contextlib import enum import inspect import os import re import sys import types import typing as t from ast import literal_eval from warnings import warn, warn_explicit from .utils.bunch import Bunch from .utils.descriptions import add_article, class_of, describe, repr_type from .utils.getargspec import getargspec from .utils.importstring import import_item from .utils.sentinel import Sentinel All = Sentinel( "All", "traitlets", """ Used in Traitlets to listen to all types of notification or to notifications from all trait attributes. """, ) class ObserveHandler(EventHandler): def __init__(self, names, type): self.trait_names = names self.type = type def instance_init(self, inst): inst.observe(self, self.trait_names, type=self.type) class Union(TraitType): """A trait type representing a Union type.""" def __init__(self, trait_types, **kwargs): """Construct a Union trait. This trait allows values that are allowed by at least one of the specified trait types. A Union traitlet cannot have metadata on its own, besides the metadata of the listed types. Parameters ---------- trait_types : sequence The list of trait types of length at least 1. **kwargs Extra kwargs passed to `TraitType` Notes ----- Union([Float(), Bool(), Int()]) attempts to validate the provided values with the validation function of Float, then Bool, and finally Int. Parsing from string is ambiguous for container types which accept other collection-like literals (e.g. List accepting both `[]` and `()` precludes Union from ever parsing ``Union([List(), Tuple()])`` as a tuple; you can modify behaviour of too permissive container traits by overriding ``_literal_from_string_pairs`` in subclasses. Similarly, parsing unions of numeric types is only unambiguous if types are provided in order of increasing permissiveness, e.g. ``Union([Int(), Float()])`` (since floats accept integer-looking values). """ self.trait_types = list(trait_types) self.info_text = " or ".join([tt.info() for tt in self.trait_types]) super().__init__(**kwargs) def default(self, obj=None): default = super().default(obj) for trait in self.trait_types: if default is Undefined: default = trait.default(obj) else: break return default def class_init(self, cls, name): for trait_type in reversed(self.trait_types): trait_type.class_init(cls, None) super().class_init(cls, name) def subclass_init(self, cls): for trait_type in reversed(self.trait_types): trait_type.subclass_init(cls) # explicitly not calling super().subclass_init(cls) # to opt out of instance_init def validate(self, obj, value): with obj.cross_validation_lock: for trait_type in self.trait_types: try: v = trait_type._validate(obj, value) # In the case of an element trait, the name is None if self.name is not None: setattr(obj, "_" + self.name + "_metadata", trait_type.metadata) return v except TraitError: continue self.error(obj, value) def __or__(self, other): if isinstance(other, Union): return Union(self.trait_types + other.trait_types) else: return Union(self.trait_types + [other]) def from_string(self, s): for trait_type in self.trait_types: try: v = trait_type.from_string(s) return trait_type.validate(None, v) except (TraitError, ValueError): continue return super().from_string(s) class Sentinel: def __init__(self, name, module, docstring=None): self.name = name self.module = module if docstring: self.__doc__ = docstring def __repr__(self): return str(self.module) + "." + self.name def __copy__(self): return self def __deepcopy__(self, memo): return self The provided code snippet includes necessary dependencies for implementing the `observe` function. Write a Python function `def observe(*names: t.Union[Sentinel, str], type: str = "change") -> "ObserveHandler"` to solve the following problem: A decorator which can be used to observe Traits on a class. The handler passed to the decorator will be called with one ``change`` dict argument. The change dictionary at least holds a 'type' key and a 'name' key, corresponding respectively to the type of notification and the name of the attribute that triggered the notification. Other keys may be passed depending on the value of 'type'. In the case where type is 'change', we also have the following keys: * ``owner`` : the HasTraits instance * ``old`` : the old value of the modified trait attribute * ``new`` : the new value of the modified trait attribute * ``name`` : the name of the modified trait attribute. Parameters ---------- *names The str names of the Traits to observe on the object. type : str, kwarg-only The type of event to observe (e.g. 'change') Here is the function: def observe(*names: t.Union[Sentinel, str], type: str = "change") -> "ObserveHandler": """A decorator which can be used to observe Traits on a class. The handler passed to the decorator will be called with one ``change`` dict argument. The change dictionary at least holds a 'type' key and a 'name' key, corresponding respectively to the type of notification and the name of the attribute that triggered the notification. Other keys may be passed depending on the value of 'type'. In the case where type is 'change', we also have the following keys: * ``owner`` : the HasTraits instance * ``old`` : the old value of the modified trait attribute * ``new`` : the new value of the modified trait attribute * ``name`` : the name of the modified trait attribute. Parameters ---------- *names The str names of the Traits to observe on the object. type : str, kwarg-only The type of event to observe (e.g. 'change') """ if not names: raise TypeError("Please specify at least one trait name to observe.") for name in names: if name is not All and not isinstance(name, str): raise TypeError("trait names to observe must be strings or All, not %r" % name) return ObserveHandler(names, type=type)
A decorator which can be used to observe Traits on a class. The handler passed to the decorator will be called with one ``change`` dict argument. The change dictionary at least holds a 'type' key and a 'name' key, corresponding respectively to the type of notification and the name of the attribute that triggered the notification. Other keys may be passed depending on the value of 'type'. In the case where type is 'change', we also have the following keys: * ``owner`` : the HasTraits instance * ``old`` : the old value of the modified trait attribute * ``new`` : the new value of the modified trait attribute * ``name`` : the name of the modified trait attribute. Parameters ---------- *names The str names of the Traits to observe on the object. type : str, kwarg-only The type of event to observe (e.g. 'change')
172,004
import contextlib import enum import inspect import os import re import sys import types import typing as t from ast import literal_eval from warnings import warn, warn_explicit from .utils.bunch import Bunch from .utils.descriptions import add_article, class_of, describe, repr_type from .utils.getargspec import getargspec from .utils.importstring import import_item from .utils.sentinel import Sentinel Undefined = Sentinel( "Undefined", "traitlets", """ Used in Traitlets to specify that no defaults are set in kwargs """, ) class Bunch(dict): # type:ignore[type-arg] """A dict with attribute-access""" def __getattr__(self, key): try: return self.__getitem__(key) except KeyError as e: raise AttributeError(key) from e def __setattr__(self, key, value): self.__setitem__(key, value) def __dir__(self): # py2-compat: can't use super because dict doesn't have __dir__ names = dir({}) names.extend(self.keys()) return names The provided code snippet includes necessary dependencies for implementing the `observe_compat` function. Write a Python function `def observe_compat(func)` to solve the following problem: Backward-compatibility shim decorator for observers Use with: @observe('name') @observe_compat def _foo_changed(self, change): ... With this, `super()._foo_changed(self, name, old, new)` in subclasses will still work. Allows adoption of new observer API without breaking subclasses that override and super. Here is the function: def observe_compat(func): """Backward-compatibility shim decorator for observers Use with: @observe('name') @observe_compat def _foo_changed(self, change): ... With this, `super()._foo_changed(self, name, old, new)` in subclasses will still work. Allows adoption of new observer API without breaking subclasses that override and super. """ def compatible_observer(self, change_or_name, old=Undefined, new=Undefined): if isinstance(change_or_name, dict): change = change_or_name else: clsname = self.__class__.__name__ warn( "A parent of %s._%s_changed has adopted the new (traitlets 4.1) @observe(change) API" % (clsname, change_or_name), DeprecationWarning, ) change = Bunch( type="change", old=old, new=new, name=change_or_name, owner=self, ) return func(self, change) return compatible_observer
Backward-compatibility shim decorator for observers Use with: @observe('name') @observe_compat def _foo_changed(self, change): ... With this, `super()._foo_changed(self, name, old, new)` in subclasses will still work. Allows adoption of new observer API without breaking subclasses that override and super.
172,005
import contextlib import enum import inspect import os import re import sys import types import typing as t from ast import literal_eval from warnings import warn, warn_explicit from .utils.bunch import Bunch from .utils.descriptions import add_article, class_of, describe, repr_type from .utils.getargspec import getargspec from .utils.importstring import import_item from .utils.sentinel import Sentinel All = Sentinel( "All", "traitlets", """ Used in Traitlets to listen to all types of notification or to notifications from all trait attributes. """, ) class ValidateHandler(EventHandler): def __init__(self, names): self.trait_names = names def instance_init(self, inst): inst._register_validator(self, self.trait_names) class Union(TraitType): """A trait type representing a Union type.""" def __init__(self, trait_types, **kwargs): """Construct a Union trait. This trait allows values that are allowed by at least one of the specified trait types. A Union traitlet cannot have metadata on its own, besides the metadata of the listed types. Parameters ---------- trait_types : sequence The list of trait types of length at least 1. **kwargs Extra kwargs passed to `TraitType` Notes ----- Union([Float(), Bool(), Int()]) attempts to validate the provided values with the validation function of Float, then Bool, and finally Int. Parsing from string is ambiguous for container types which accept other collection-like literals (e.g. List accepting both `[]` and `()` precludes Union from ever parsing ``Union([List(), Tuple()])`` as a tuple; you can modify behaviour of too permissive container traits by overriding ``_literal_from_string_pairs`` in subclasses. Similarly, parsing unions of numeric types is only unambiguous if types are provided in order of increasing permissiveness, e.g. ``Union([Int(), Float()])`` (since floats accept integer-looking values). """ self.trait_types = list(trait_types) self.info_text = " or ".join([tt.info() for tt in self.trait_types]) super().__init__(**kwargs) def default(self, obj=None): default = super().default(obj) for trait in self.trait_types: if default is Undefined: default = trait.default(obj) else: break return default def class_init(self, cls, name): for trait_type in reversed(self.trait_types): trait_type.class_init(cls, None) super().class_init(cls, name) def subclass_init(self, cls): for trait_type in reversed(self.trait_types): trait_type.subclass_init(cls) # explicitly not calling super().subclass_init(cls) # to opt out of instance_init def validate(self, obj, value): with obj.cross_validation_lock: for trait_type in self.trait_types: try: v = trait_type._validate(obj, value) # In the case of an element trait, the name is None if self.name is not None: setattr(obj, "_" + self.name + "_metadata", trait_type.metadata) return v except TraitError: continue self.error(obj, value) def __or__(self, other): if isinstance(other, Union): return Union(self.trait_types + other.trait_types) else: return Union(self.trait_types + [other]) def from_string(self, s): for trait_type in self.trait_types: try: v = trait_type.from_string(s) return trait_type.validate(None, v) except (TraitError, ValueError): continue return super().from_string(s) class Sentinel: def __init__(self, name, module, docstring=None): self.name = name self.module = module if docstring: self.__doc__ = docstring def __repr__(self): return str(self.module) + "." + self.name def __copy__(self): return self def __deepcopy__(self, memo): return self The provided code snippet includes necessary dependencies for implementing the `validate` function. Write a Python function `def validate(*names: t.Union[Sentinel, str]) -> "ValidateHandler"` to solve the following problem: A decorator to register cross validator of HasTraits object's state when a Trait is set. The handler passed to the decorator must have one ``proposal`` dict argument. The proposal dictionary must hold the following keys: * ``owner`` : the HasTraits instance * ``value`` : the proposed value for the modified trait attribute * ``trait`` : the TraitType instance associated with the attribute Parameters ---------- *names The str names of the Traits to validate. Notes ----- Since the owner has access to the ``HasTraits`` instance via the 'owner' key, the registered cross validator could potentially make changes to attributes of the ``HasTraits`` instance. However, we recommend not to do so. The reason is that the cross-validation of attributes may run in arbitrary order when exiting the ``hold_trait_notifications`` context, and such changes may not commute. Here is the function: def validate(*names: t.Union[Sentinel, str]) -> "ValidateHandler": """A decorator to register cross validator of HasTraits object's state when a Trait is set. The handler passed to the decorator must have one ``proposal`` dict argument. The proposal dictionary must hold the following keys: * ``owner`` : the HasTraits instance * ``value`` : the proposed value for the modified trait attribute * ``trait`` : the TraitType instance associated with the attribute Parameters ---------- *names The str names of the Traits to validate. Notes ----- Since the owner has access to the ``HasTraits`` instance via the 'owner' key, the registered cross validator could potentially make changes to attributes of the ``HasTraits`` instance. However, we recommend not to do so. The reason is that the cross-validation of attributes may run in arbitrary order when exiting the ``hold_trait_notifications`` context, and such changes may not commute. """ if not names: raise TypeError("Please specify at least one trait name to validate.") for name in names: if name is not All and not isinstance(name, str): raise TypeError("trait names to validate must be strings or All, not %r" % name) return ValidateHandler(names)
A decorator to register cross validator of HasTraits object's state when a Trait is set. The handler passed to the decorator must have one ``proposal`` dict argument. The proposal dictionary must hold the following keys: * ``owner`` : the HasTraits instance * ``value`` : the proposed value for the modified trait attribute * ``trait`` : the TraitType instance associated with the attribute Parameters ---------- *names The str names of the Traits to validate. Notes ----- Since the owner has access to the ``HasTraits`` instance via the 'owner' key, the registered cross validator could potentially make changes to attributes of the ``HasTraits`` instance. However, we recommend not to do so. The reason is that the cross-validation of attributes may run in arbitrary order when exiting the ``hold_trait_notifications`` context, and such changes may not commute.
172,006
import contextlib import enum import inspect import os import re import sys import types import typing as t from ast import literal_eval from warnings import warn, warn_explicit from .utils.bunch import Bunch from .utils.descriptions import add_article, class_of, describe, repr_type from .utils.getargspec import getargspec from .utils.importstring import import_item from .utils.sentinel import Sentinel class TraitError(Exception): pass def class_of(value): """Returns a string of the value's type with an indefinite article. For example 'an Image' or 'a PlotValue'. """ if inspect.isclass(value): return add_article(value.__name__) else: return class_of(type(value)) The provided code snippet includes necessary dependencies for implementing the `_validate_bounds` function. Write a Python function `def _validate_bounds(trait, obj, value)` to solve the following problem: Validate that a number to be applied to a trait is between bounds. If value is not between min_bound and max_bound, this raises a TraitError with an error message appropriate for this trait. Here is the function: def _validate_bounds(trait, obj, value): """ Validate that a number to be applied to a trait is between bounds. If value is not between min_bound and max_bound, this raises a TraitError with an error message appropriate for this trait. """ if trait.min is not None and value < trait.min: raise TraitError( "The value of the '{name}' trait of {klass} instance should " "not be less than {min_bound}, but a value of {value} was " "specified".format( name=trait.name, klass=class_of(obj), value=value, min_bound=trait.min ) ) if trait.max is not None and value > trait.max: raise TraitError( "The value of the '{name}' trait of {klass} instance should " "not be greater than {max_bound}, but a value of {value} was " "specified".format( name=trait.name, klass=class_of(obj), value=value, max_bound=trait.max ) ) return value
Validate that a number to be applied to a trait is between bounds. If value is not between min_bound and max_bound, this raises a TraitError with an error message appropriate for this trait.
172,007
import argparse import copy import functools import json import os import re import sys import typing as t import warnings from traitlets.traitlets import Any, Container, Dict, HasTraits, List, Undefined from ..utils import cast_unicode, filefind def execfile(fname, glob): with open(fname, "rb") as f: exec(compile(f.read(), fname, "exec"), glob, glob) # noqa
null
172,008
import argparse import copy import functools import json import os import re import sys import typing as t import warnings from traitlets.traitlets import Any, Container, Dict, HasTraits, List, Undefined from ..utils import cast_unicode, filefind The provided code snippet includes necessary dependencies for implementing the `_is_section_key` function. Write a Python function `def _is_section_key(key)` to solve the following problem: Is a Config key a section name (does it start with a capital)? Here is the function: def _is_section_key(key): """Is a Config key a section name (does it start with a capital)?""" if key and key[0].upper() == key[0] and not key.startswith("_"): return True else: return False
Is a Config key a section name (does it start with a capital)?
172,009
import argparse import copy import functools import json import os import re import sys import typing as t import warnings from traitlets.traitlets import Any, Container, Dict, HasTraits, List, Undefined from ..utils import cast_unicode, filefind class ConfigFileNotFound(ConfigError): # noqa pass class Config(dict): # type:ignore[type-arg] """An attribute-based dict that can do smart merges. Accessing a field on a config object for the first time populates the key with either a nested Config object for keys starting with capitals or :class:`.LazyConfigValue` for lowercase keys, allowing quick assignments such as:: c = Config() c.Class.int_trait = 5 c.Class.list_trait.append("x") """ def __init__(self, *args, **kwds): dict.__init__(self, *args, **kwds) self._ensure_subconfig() def _ensure_subconfig(self): """ensure that sub-dicts that should be Config objects are casts dicts that are under section keys to Config objects, which is necessary for constructing Config objects from dict literals. """ for key in self: obj = self[key] if _is_section_key(key) and isinstance(obj, dict) and not isinstance(obj, Config): setattr(self, key, Config(obj)) def _merge(self, other): """deprecated alias, use Config.merge()""" self.merge(other) def merge(self, other): """merge another config object into this one""" to_update = {} for k, v in other.items(): if k not in self: to_update[k] = v else: # I have this key if isinstance(v, Config) and isinstance(self[k], Config): # Recursively merge common sub Configs self[k].merge(v) elif isinstance(v, LazyConfigValue): self[k] = v.merge_into(self[k]) else: # Plain updates for non-Configs to_update[k] = v self.update(to_update) def collisions(self, other: "Config") -> t.Dict[str, t.Any]: """Check for collisions between two config objects. Returns a dict of the form {"Class": {"trait": "collision message"}}`, indicating which values have been ignored. An empty dict indicates no collisions. """ collisions: t.Dict[str, t.Any] = {} for section in self: if section not in other: continue mine = self[section] theirs = other[section] for key in mine: if key in theirs and mine[key] != theirs[key]: collisions.setdefault(section, {}) collisions[section][key] = f"{mine[key]!r} ignored, using {theirs[key]!r}" return collisions def __contains__(self, key): # allow nested contains of the form `"Section.key" in config` if "." in key: first, remainder = key.split(".", 1) if first not in self: return False return remainder in self[first] return super().__contains__(key) # .has_key is deprecated for dictionaries. has_key = __contains__ def _has_section(self, key): return _is_section_key(key) and key in self def copy(self): return type(self)(dict.copy(self)) def __copy__(self): return self.copy() def __deepcopy__(self, memo): new_config = type(self)() for key, value in self.items(): if isinstance(value, (Config, LazyConfigValue)): # deep copy config objects value = copy.deepcopy(value, memo) elif type(value) in {dict, list, set, tuple}: # shallow copy plain container traits value = copy.copy(value) new_config[key] = value return new_config def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: if _is_section_key(key): c = Config() dict.__setitem__(self, key, c) return c elif not key.startswith("_"): # undefined, create lazy value, used for container methods v = LazyConfigValue() dict.__setitem__(self, key, v) return v else: raise KeyError def __setitem__(self, key, value): if _is_section_key(key): if not isinstance(value, Config): raise ValueError( "values whose keys begin with an uppercase " "char must be Config instances: %r, %r" % (key, value) ) dict.__setitem__(self, key, value) def __getattr__(self, key): if key.startswith("__"): return dict.__getattr__(self, key) # type:ignore[attr-defined] try: return self.__getitem__(key) except KeyError as e: raise AttributeError(e) from e def __setattr__(self, key, value): if key.startswith("__"): return dict.__setattr__(self, key, value) try: self.__setitem__(key, value) except KeyError as e: raise AttributeError(e) from e def __delattr__(self, key): if key.startswith("__"): return dict.__delattr__(self, key) try: dict.__delitem__(self, key) except KeyError as e: raise AttributeError(e) from e class PyFileConfigLoader(FileConfigLoader): """A config loader for pure python files. This is responsible for locating a Python config file by filename and path, then executing it to construct a Config object. """ def load_config(self): """Load the config from a file and return it as a Config object.""" self.clear() try: self._find_file() except OSError as e: raise ConfigFileNotFound(str(e)) from e self._read_file_as_dict() return self.config def load_subconfig(self, fname, path=None): """Injected into config file namespace as load_subconfig""" if path is None: path = self.path loader = self.__class__(fname, path) try: sub_config = loader.load_config() except ConfigFileNotFound: # Pass silently if the sub config is not there, # treat it as an empty config file. pass else: self.config.merge(sub_config) def _read_file_as_dict(self): """Load the config file into self.config, with recursive loading.""" def get_config(): """Unnecessary now, but a deprecation warning is more trouble than it's worth.""" return self.config namespace = dict( c=self.config, load_subconfig=self.load_subconfig, get_config=get_config, __file__=self.full_filename, ) conf_filename = self.full_filename with open(conf_filename, "rb") as f: exec(compile(f.read(), conf_filename, "exec"), namespace, namespace) # noqa The provided code snippet includes necessary dependencies for implementing the `load_pyconfig_files` function. Write a Python function `def load_pyconfig_files(config_files, path)` to solve the following problem: Load multiple Python config files, merging each of them in turn. Parameters ---------- config_files : list of str List of config files names to load and merge into the config. path : unicode The full path to the location of the config files. Here is the function: def load_pyconfig_files(config_files, path): """Load multiple Python config files, merging each of them in turn. Parameters ---------- config_files : list of str List of config files names to load and merge into the config. path : unicode The full path to the location of the config files. """ config = Config() for cf in config_files: loader = PyFileConfigLoader(cf, path=path) try: next_config = loader.load_config() except ConfigFileNotFound: pass except Exception: raise else: config.merge(next_config) return config
Load multiple Python config files, merging each of them in turn. Parameters ---------- config_files : list of str List of config files names to load and merge into the config. path : unicode The full path to the location of the config files.
172,010
from collections import defaultdict from textwrap import dedent from traitlets import Undefined from traitlets.utils.text import indent The provided code snippet includes necessary dependencies for implementing the `setup` function. Write a Python function `def setup(app)` to solve the following problem: Registers the Sphinx extension. You shouldn't need to call this directly; configure Sphinx to use this module instead. Here is the function: def setup(app): """Registers the Sphinx extension. You shouldn't need to call this directly; configure Sphinx to use this module instead. """ app.add_object_type("configtrait", "configtrait", objname="Config option") metadata = {"parallel_read_safe": True, "parallel_write_safe": True} return metadata
Registers the Sphinx extension. You shouldn't need to call this directly; configure Sphinx to use this module instead.
172,011
from collections import defaultdict from textwrap import dedent from traitlets import Undefined from traitlets.utils.text import indent def class_config_rst_doc(cls, trait_aliases): """Generate rST documentation for this class' config options. Excludes traits defined on parent classes. """ lines = [] classname = cls.__name__ for _, trait in sorted(cls.class_traits(config=True).items()): ttype = trait.__class__.__name__ fullname = classname + "." + trait.name lines += [".. configtrait:: " + fullname, ""] help = trait.help.rstrip() or "No description" lines.append(indent(dedent(help)) + "\n") # Choices or type if "Enum" in ttype: # include Enum choices lines.append(indent(":options: " + ", ".join("``%r``" % x for x in trait.values))) else: lines.append(indent(":trait type: " + ttype)) # Default value # Ignore boring default values like None, [] or '' if interesting_default_value(trait.default_value): try: dvr = trait.default_value_repr() except Exception: dvr = None # ignore defaults we can't construct if dvr is not None: if len(dvr) > 64: dvr = dvr[:61] + "..." # Double up backslashes, so they get to the rendered docs dvr = dvr.replace("\\n", "\\\\n") lines.append(indent(":default: ``%s``" % dvr)) # Command line aliases if trait_aliases[fullname]: fmt_aliases = format_aliases(trait_aliases[fullname]) lines.append(indent(":CLI option: " + fmt_aliases)) # Blank line lines.append("") return "\n".join(lines) def reverse_aliases(app): """Produce a mapping of trait names to lists of command line aliases.""" res = defaultdict(list) for alias, trait in app.aliases.items(): res[trait].append(alias) # Flags also often act as aliases for a boolean trait. # Treat flags which set one trait to True as aliases. for flag, (cfg, _) in app.flags.items(): if len(cfg) == 1: classname = list(cfg)[0] cls_cfg = cfg[classname] if len(cls_cfg) == 1: traitname = list(cls_cfg)[0] if cls_cfg[traitname] is True: res[classname + "." + traitname].append(flag) return res The provided code snippet includes necessary dependencies for implementing the `write_doc` function. Write a Python function `def write_doc(path, title, app, preamble=None)` to solve the following problem: Write a rst file documenting config options for a traitlets application. Parameters ---------- path : str The file to be written title : str The human-readable title of the document app : traitlets.config.Application An instance of the application class to be documented preamble : str Extra text to add just after the title (optional) Here is the function: def write_doc(path, title, app, preamble=None): """Write a rst file documenting config options for a traitlets application. Parameters ---------- path : str The file to be written title : str The human-readable title of the document app : traitlets.config.Application An instance of the application class to be documented preamble : str Extra text to add just after the title (optional) """ trait_aliases = reverse_aliases(app) with open(path, "w") as f: f.write(title + "\n") f.write(("=" * len(title)) + "\n") f.write("\n") if preamble is not None: f.write(preamble + "\n\n") for c in app._classes_inc_parents(): f.write(class_config_rst_doc(c, trait_aliases)) f.write("\n")
Write a rst file documenting config options for a traitlets application. Parameters ---------- path : str The file to be written title : str The human-readable title of the document app : traitlets.config.Application An instance of the application class to be documented preamble : str Extra text to add just after the title (optional)
172,012
import errno import json import os from traitlets.config import LoggingConfigurable from traitlets.traitlets import Unicode The provided code snippet includes necessary dependencies for implementing the `recursive_update` function. Write a Python function `def recursive_update(target, new)` to solve the following problem: Recursively update one dictionary using another. None values will delete their keys. Here is the function: def recursive_update(target, new): """Recursively update one dictionary using another. None values will delete their keys. """ for k, v in new.items(): if isinstance(v, dict): if k not in target: target[k] = {} recursive_update(target[k], v) if not target[k]: # Prune empty subdicts del target[k] elif v is None: target.pop(k, None) else: target[k] = v
Recursively update one dictionary using another. None values will delete their keys.
172,013
import functools import json import logging import os import pprint import re import sys import typing as t from collections import OrderedDict, defaultdict from contextlib import suppress from copy import deepcopy from logging.config import dictConfig from textwrap import dedent from typing import Any, Callable, TypeVar, cast from traitlets.config.configurable import Configurable, SingletonConfigurable from traitlets.config.loader import ( ArgumentError, Config, ConfigFileNotFound, JSONFileConfigLoader, KVArgParseConfigLoader, PyFileConfigLoader, ) from traitlets.traitlets import ( Bool, Dict, Enum, Instance, List, TraitError, Unicode, default, observe, observe_compat, ) from traitlets.utils.nested_update import nested_update from traitlets.utils.text import indent, wrap_paragraphs from ..utils import cast_unicode from ..utils.importstring import import_item T = TypeVar("T", bound=Callable[..., Any]) def cast(typ: Type[_T], val: Any) -> _T: ... def cast(typ: str, val: Any) -> Any: ... def cast(typ: object, val: Any) -> Any: ... class ArgumentError(ConfigLoaderError): pass class TraitError(Exception): pass The provided code snippet includes necessary dependencies for implementing the `catch_config_error` function. Write a Python function `def catch_config_error(method: T) -> T` to solve the following problem: Method decorator for catching invalid config (Trait/ArgumentErrors) during init. On a TraitError (generally caused by bad config), this will print the trait's message, and exit the app. For use on init methods, to prevent invoking excepthook on invalid input. Here is the function: def catch_config_error(method: T) -> T: """Method decorator for catching invalid config (Trait/ArgumentErrors) during init. On a TraitError (generally caused by bad config), this will print the trait's message, and exit the app. For use on init methods, to prevent invoking excepthook on invalid input. """ @functools.wraps(method) def inner(app, *args, **kwargs): try: return method(app, *args, **kwargs) except (TraitError, ArgumentError) as e: app.log.fatal("Bad config encountered during initialization: %s", e) app.log.debug("Config at the time: %s", app.config) app.exit(1) return cast(T, inner)
Method decorator for catching invalid config (Trait/ArgumentErrors) during init. On a TraitError (generally caused by bad config), this will print the trait's message, and exit the app. For use on init methods, to prevent invoking excepthook on invalid input.
172,014
import functools import json import logging import os import pprint import re import sys import typing as t from collections import OrderedDict, defaultdict from contextlib import suppress from copy import deepcopy from logging.config import dictConfig from textwrap import dedent from typing import Any, Callable, TypeVar, cast from traitlets.config.configurable import Configurable, SingletonConfigurable from traitlets.config.loader import ( ArgumentError, Config, ConfigFileNotFound, JSONFileConfigLoader, KVArgParseConfigLoader, PyFileConfigLoader, ) from traitlets.traitlets import ( Bool, Dict, Enum, Instance, List, TraitError, Unicode, default, observe, observe_compat, ) from traitlets.utils.nested_update import nested_update from traitlets.utils.text import indent, wrap_paragraphs from ..utils import cast_unicode from ..utils.importstring import import_item The provided code snippet includes necessary dependencies for implementing the `boolean_flag` function. Write a Python function `def boolean_flag(name, configurable, set_help="", unset_help="")` to solve the following problem: Helper for building basic --trait, --no-trait flags. Parameters ---------- name : str The name of the flag. configurable : str The 'Class.trait' string of the trait to be set/unset with the flag set_help : unicode help string for --name flag unset_help : unicode help string for --no-name flag Returns ------- cfg : dict A dict with two keys: 'name', and 'no-name', for setting and unsetting the trait, respectively. Here is the function: def boolean_flag(name, configurable, set_help="", unset_help=""): """Helper for building basic --trait, --no-trait flags. Parameters ---------- name : str The name of the flag. configurable : str The 'Class.trait' string of the trait to be set/unset with the flag set_help : unicode help string for --name flag unset_help : unicode help string for --no-name flag Returns ------- cfg : dict A dict with two keys: 'name', and 'no-name', for setting and unsetting the trait, respectively. """ # default helpstrings set_help = set_help or "set %s=True" % configurable unset_help = unset_help or "set %s=False" % configurable cls, trait = configurable.split(".") setter = {cls: {trait: True}} unsetter = {cls: {trait: False}} return {name: (setter, set_help), "no-" + name: (unsetter, unset_help)}
Helper for building basic --trait, --no-trait flags. Parameters ---------- name : str The name of the flag. configurable : str The 'Class.trait' string of the trait to be set/unset with the flag set_help : unicode help string for --name flag unset_help : unicode help string for --no-name flag Returns ------- cfg : dict A dict with two keys: 'name', and 'no-name', for setting and unsetting the trait, respectively.
172,015
import functools import json import logging import os import pprint import re import sys import typing as t from collections import OrderedDict, defaultdict from contextlib import suppress from copy import deepcopy from logging.config import dictConfig from textwrap import dedent from typing import Any, Callable, TypeVar, cast from traitlets.config.configurable import Configurable, SingletonConfigurable from traitlets.config.loader import ( ArgumentError, Config, ConfigFileNotFound, JSONFileConfigLoader, KVArgParseConfigLoader, PyFileConfigLoader, ) from traitlets.traitlets import ( Bool, Dict, Enum, Instance, List, TraitError, Unicode, default, observe, observe_compat, ) from traitlets.utils.nested_update import nested_update from traitlets.utils.text import indent, wrap_paragraphs from ..utils import cast_unicode from ..utils.importstring import import_item class Application(SingletonConfigurable): """A singleton application with full configuration support.""" # The name of the application, will usually match the name of the command # line application name: t.Union[str, Unicode] = Unicode("application") # The description of the application that is printed at the beginning # of the help. description: t.Union[str, Unicode] = Unicode("This is an application.") # default section descriptions option_description: t.Union[str, Unicode] = Unicode(option_description) keyvalue_description: t.Union[str, Unicode] = Unicode(keyvalue_description) subcommand_description: t.Union[str, Unicode] = Unicode(subcommand_description) python_config_loader_class = PyFileConfigLoader json_config_loader_class = JSONFileConfigLoader # The usage and example string that goes at the end of the help string. examples: t.Union[str, Unicode] = Unicode() # A sequence of Configurable subclasses whose config=True attributes will # be exposed at the command line. classes: t.List[t.Type[t.Any]] = [] def _classes_inc_parents(self, classes=None): """Iterate through configurable classes, including configurable parents :param classes: The list of classes to iterate; if not set, uses :attr:`classes`. Children should always be after parents, and each class should only be yielded once. """ if classes is None: classes = self.classes seen = set() for c in classes: # We want to sort parents before children, so we reverse the MRO for parent in reversed(c.mro()): if issubclass(parent, Configurable) and (parent not in seen): seen.add(parent) yield parent # The version string of this application. version: t.Union[str, Unicode] = Unicode("0.0") # the argv used to initialize the application argv: t.Union[t.List[str], List] = List() # Whether failing to load config files should prevent startup raise_config_file_errors: t.Union[bool, Bool] = Bool( TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR ) # The log level for the application log_level: t.Union[str, int, Enum] = Enum( (0, 10, 20, 30, 40, 50, "DEBUG", "INFO", "WARN", "ERROR", "CRITICAL"), default_value=logging.WARN, help="Set the log level by value or name.", ).tag(config=True) _log_formatter_cls = LevelFormatter log_datefmt: t.Union[str, Unicode] = Unicode( "%Y-%m-%d %H:%M:%S", help="The date format used by logging formatters for %(asctime)s" ).tag(config=True) log_format: t.Union[str, Unicode] = Unicode( "[%(name)s]%(highlevel)s %(message)s", help="The Logging format template", ).tag(config=True) def get_default_logging_config(self): """Return the base logging configuration. The default is to log to stderr using a StreamHandler, if no default handler already exists. The log handler level starts at logging.WARN, but this can be adjusted by setting the ``log_level`` attribute. The ``logging_config`` trait is merged into this allowing for finer control of logging. """ config: t.Dict[str, t.Any] = { "version": 1, "handlers": { "console": { "class": "logging.StreamHandler", "formatter": "console", "level": logging.getLevelName(self.log_level), "stream": "ext://sys.stderr", }, }, "formatters": { "console": { "class": ( f"{self._log_formatter_cls.__module__}" f".{self._log_formatter_cls.__name__}" ), "format": self.log_format, "datefmt": self.log_datefmt, }, }, "loggers": { self.__class__.__name__: { "level": "DEBUG", "handlers": ["console"], } }, "disable_existing_loggers": False, } if IS_PYTHONW: # disable logging # (this should really go to a file, but file-logging is only # hooked up in parallel applications) del config["handlers"] del config["loggers"] return config def _observe_logging_change(self, change): # convert log level strings to ints log_level = self.log_level if isinstance(log_level, str): self.log_level = getattr(logging, log_level) self._configure_logging() def _observe_logging_default(self, change): self._configure_logging() def _configure_logging(self): config = self.get_default_logging_config() nested_update(config, self.logging_config or {}) dictConfig(config) # make a note that we have configured logging self._logging_configured = True def _log_default(self): """Start logging for this application.""" log = logging.getLogger(self.__class__.__name__) log.propagate = False _log = log # copied from Logger.hasHandlers() (new in Python 3.2) while _log: if _log.handlers: return log if not _log.propagate: break else: _log = _log.parent # type:ignore[assignment] return log logging_config = Dict( help=""" Configure additional log handlers. The default stderr logs handler is configured by the log_level, log_datefmt and log_format settings. This configuration can be used to configure additional handlers (e.g. to output the log to a file) or for finer control over the default handlers. If provided this should be a logging configuration dictionary, for more information see: https://docs.python.org/3/library/logging.config.html#logging-config-dictschema This dictionary is merged with the base logging configuration which defines the following: * A logging formatter intended for interactive use called ``console``. * A logging handler that writes to stderr called ``console`` which uses the formatter ``console``. * A logger with the name of this application set to ``DEBUG`` level. This example adds a new handler that writes to a file: .. code-block:: python c.Application.logging_config = { 'handlers': { 'file': { 'class': 'logging.FileHandler', 'level': 'DEBUG', 'filename': '<path/to/file>', } }, 'loggers': { '<application-name>': { 'level': 'DEBUG', # NOTE: if you don't list the default "console" # handler here then it will be disabled 'handlers': ['console', 'file'], }, } } """, ).tag(config=True) #: the alias map for configurables #: Keys might strings or tuples for additional options; single-letter alias accessed like `-v`. #: Values might be like "Class.trait" strings of two-tuples: (Class.trait, help-text), # or just the "Class.trait" string, in which case the help text is inferred from the # corresponding trait aliases: t.Dict[t.Union[str, t.Tuple[str, ...]], t.Union[str, t.Tuple[str, str]]] = { "log-level": "Application.log_level" } # flags for loading Configurables or store_const style flags # flags are loaded from this dict by '--key' flags # this must be a dict of two-tuples, the first element being the Config/dict # and the second being the help string for the flag flags: t.Dict[ t.Union[str, t.Tuple[str, ...]], t.Tuple[t.Union[t.Dict[str, t.Any], Config], str] ] = { "debug": ( { "Application": { "log_level": logging.DEBUG, }, }, "Set log-level to debug, for the most verbose logging.", ), "show-config": ( { "Application": { "show_config": True, }, }, "Show the application's configuration (human-readable format)", ), "show-config-json": ( { "Application": { "show_config_json": True, }, }, "Show the application's configuration (json format)", ), } # subcommands for launching other applications # if this is not empty, this will be a parent Application # this must be a dict of two-tuples, # the first element being the application class/import string # and the second being the help string for the subcommand subcommands: t.Union[t.Dict[str, t.Tuple[t.Any, str]], Dict] = Dict() # parse_command_line will initialize a subapp, if requested subapp = Instance("traitlets.config.application.Application", allow_none=True) # extra command-line arguments that don't set config values extra_args: t.Union[t.List[str], List] = List(Unicode()) cli_config = Instance( Config, (), {}, help="""The subset of our configuration that came from the command-line We re-load this configuration after loading config files, to ensure that it maintains highest priority. """, ) _loaded_config_files = List() show_config: t.Union[bool, Bool] = Bool( help="Instead of starting the Application, dump configuration to stdout" ).tag(config=True) show_config_json: t.Union[bool, Bool] = Bool( help="Instead of starting the Application, dump configuration to stdout (as JSON)" ).tag(config=True) def _show_config_json_changed(self, change): self.show_config = change.new def _show_config_changed(self, change): if change.new: self._save_start = self.start self.start = self.start_show_config # type:ignore[assignment] def __init__(self, **kwargs): SingletonConfigurable.__init__(self, **kwargs) # Ensure my class is in self.classes, so my attributes appear in command line # options and config files. cls = self.__class__ if cls not in self.classes: if self.classes is cls.classes: # class attr, assign instead of insert self.classes = [cls] + self.classes else: self.classes.insert(0, self.__class__) def _config_changed(self, change): super()._config_changed(change) self.log.debug("Config changed: %r", change.new) def initialize(self, argv=None): """Do the basic steps to configure me. Override in subclasses. """ self.parse_command_line(argv) def start(self): """Start the app mainloop. Override in subclasses. """ if self.subapp is not None: return self.subapp.start() def start_show_config(self): """start function used when show_config is True""" config = self.config.copy() # exclude show_config flags from displayed config for cls in self.__class__.mro(): if cls.__name__ in config: cls_config = config[cls.__name__] cls_config.pop("show_config", None) cls_config.pop("show_config_json", None) if self.show_config_json: json.dump(config, sys.stdout, indent=1, sort_keys=True, default=repr) # add trailing newline sys.stdout.write("\n") return if self._loaded_config_files: print("Loaded config files:") for f in self._loaded_config_files: print(" " + f) print() for classname in sorted(config): class_config = config[classname] if not class_config: continue print(classname) pformat_kwargs: t.Dict[str, t.Any] = dict(indent=4, compact=True) for traitname in sorted(class_config): value = class_config[traitname] print( " .{} = {}".format( traitname, pprint.pformat(value, **pformat_kwargs), ) ) def print_alias_help(self): """Print the alias parts of the help.""" print("\n".join(self.emit_alias_help())) def emit_alias_help(self): """Yield the lines for alias part of the help.""" if not self.aliases: return classdict = {} for cls in self.classes: # include all parents (up to, but excluding Configurable) in available names for c in cls.mro()[:-3]: classdict[c.__name__] = c fhelp: t.Optional[str] for alias, longname in self.aliases.items(): try: if isinstance(longname, tuple): longname, fhelp = longname else: fhelp = None classname, traitname = longname.split(".")[-2:] longname = classname + "." + traitname cls = classdict[classname] trait = cls.class_traits(config=True)[traitname] fhelp = cls.class_get_trait_help(trait, helptext=fhelp).splitlines() if not isinstance(alias, tuple): alias = (alias,) alias = sorted(alias, key=len) # type:ignore[assignment] alias = ", ".join(("--%s" if len(m) > 1 else "-%s") % m for m in alias) # reformat first line assert fhelp is not None fhelp[0] = fhelp[0].replace("--" + longname, alias) # type:ignore yield from fhelp yield indent("Equivalent to: [--%s]" % longname) except Exception as ex: self.log.error("Failed collecting help-message for alias %r, due to: %s", alias, ex) raise def print_flag_help(self): """Print the flag part of the help.""" print("\n".join(self.emit_flag_help())) def emit_flag_help(self): """Yield the lines for the flag part of the help.""" if not self.flags: return for flags, (cfg, fhelp) in self.flags.items(): try: if not isinstance(flags, tuple): flags = (flags,) flags = sorted(flags, key=len) # type:ignore[assignment] flags = ", ".join(("--%s" if len(m) > 1 else "-%s") % m for m in flags) yield flags yield indent(dedent(fhelp.strip())) cfg_list = " ".join( f"--{clname}.{prop}={val}" for clname, props_dict in cfg.items() for prop, val in props_dict.items() ) cfg_txt = "Equivalent to: [%s]" % cfg_list yield indent(dedent(cfg_txt)) except Exception as ex: self.log.error("Failed collecting help-message for flag %r, due to: %s", flags, ex) raise def print_options(self): """Print the options part of the help.""" print("\n".join(self.emit_options_help())) def emit_options_help(self): """Yield the lines for the options part of the help.""" if not self.flags and not self.aliases: return header = "Options" yield header yield "=" * len(header) for p in wrap_paragraphs(self.option_description): yield p yield "" yield from self.emit_flag_help() yield from self.emit_alias_help() yield "" def print_subcommands(self): """Print the subcommand part of the help.""" print("\n".join(self.emit_subcommands_help())) def emit_subcommands_help(self): """Yield the lines for the subcommand part of the help.""" if not self.subcommands: return header = "Subcommands" yield header yield "=" * len(header) for p in wrap_paragraphs(self.subcommand_description.format(app=self.name)): yield p yield "" for subc, (_, help) in self.subcommands.items(): yield subc if help: yield indent(dedent(help.strip())) yield "" def emit_help_epilogue(self, classes): """Yield the very bottom lines of the help message. If classes=False (the default), print `--help-all` msg. """ if not classes: yield "To see all available configurables, use `--help-all`." yield "" def print_help(self, classes=False): """Print the help for each Configurable class in self.classes. If classes=False (the default), only flags and aliases are printed. """ print("\n".join(self.emit_help(classes=classes))) def emit_help(self, classes=False): """Yield the help-lines for each Configurable class in self.classes. If classes=False (the default), only flags and aliases are printed. """ yield from self.emit_description() yield from self.emit_subcommands_help() yield from self.emit_options_help() if classes: help_classes = self._classes_with_config_traits() if help_classes: yield "Class options" yield "=============" for p in wrap_paragraphs(self.keyvalue_description): yield p yield "" for cls in help_classes: yield cls.class_get_help() yield "" yield from self.emit_examples() yield from self.emit_help_epilogue(classes) def document_config_options(self): """Generate rST format documentation for the config options this application Returns a multiline string. """ return "\n".join(c.class_config_rst_doc() for c in self._classes_inc_parents()) def print_description(self): """Print the application description.""" print("\n".join(self.emit_description())) def emit_description(self): """Yield lines with the application description.""" for p in wrap_paragraphs(self.description or self.__doc__ or ""): yield p yield "" def print_examples(self): """Print usage and examples (see `emit_examples()`).""" print("\n".join(self.emit_examples())) def emit_examples(self): """Yield lines with the usage and examples. This usage string goes at the end of the command line help string and should contain examples of the application's usage. """ if self.examples: yield "Examples" yield "--------" yield "" yield indent(dedent(self.examples.strip())) yield "" def print_version(self): """Print the version string.""" print(self.version) def initialize_subcommand(self, subc, argv=None): """Initialize a subcommand with argv.""" val = self.subcommands.get(subc) assert val is not None subapp, _ = val if isinstance(subapp, str): subapp = import_item(subapp) # Cannot issubclass() on a non-type (SOhttp://stackoverflow.com/questions/8692430) if isinstance(subapp, type) and issubclass(subapp, Application): # Clear existing instances before... self.__class__.clear_instance() # instantiating subapp... self.subapp = subapp.instance(parent=self) elif callable(subapp): # or ask factory to create it... self.subapp = subapp(self) # type:ignore[call-arg] else: raise AssertionError("Invalid mappings for subcommand '%s'!" % subc) # ... and finally initialize subapp. self.subapp.initialize(argv) def flatten_flags(self): """Flatten flags and aliases for loaders, so cl-args override as expected. This prevents issues such as an alias pointing to InteractiveShell, but a config file setting the same trait in TerminalInteraciveShell getting inappropriate priority over the command-line arg. Also, loaders expect ``(key: longname)`` and not ``key: (longname, help)`` items. Only aliases with exactly one descendent in the class list will be promoted. """ # build a tree of classes in our list that inherit from a particular # it will be a dict by parent classname of classes in our list # that are descendents mro_tree = defaultdict(list) for cls in self.classes: clsname = cls.__name__ for parent in cls.mro()[1:-3]: # exclude cls itself and Configurable,HasTraits,object mro_tree[parent.__name__].append(clsname) # flatten aliases, which have the form: # { 'alias' : 'Class.trait' } aliases: t.Dict[str, str] = {} for alias, longname in self.aliases.items(): if isinstance(longname, tuple): longname, _ = longname cls, trait = longname.split(".", 1) # type:ignore children = mro_tree[cls] # type:ignore[index] if len(children) == 1: # exactly one descendent, promote alias cls = children[0] # type:ignore[assignment] if not isinstance(aliases, tuple): alias = (alias,) # type:ignore[assignment] for al in alias: aliases[al] = ".".join([cls, trait]) # type:ignore[list-item] # flatten flags, which are of the form: # { 'key' : ({'Cls' : {'trait' : value}}, 'help')} flags = {} for key, (flagdict, help) in self.flags.items(): newflag: t.Dict[t.Any, t.Any] = {} for cls, subdict in flagdict.items(): # type:ignore children = mro_tree[cls] # type:ignore[index] # exactly one descendent, promote flag section if len(children) == 1: cls = children[0] # type:ignore[assignment] if cls in newflag: newflag[cls].update(subdict) else: newflag[cls] = subdict if not isinstance(key, tuple): key = (key,) for k in key: flags[k] = (newflag, help) return flags, aliases def _create_loader(self, argv, aliases, flags, classes): return KVArgParseConfigLoader( argv, aliases, flags, classes=classes, log=self.log, subcommands=self.subcommands ) def _get_sys_argv(cls, check_argcomplete: bool = False) -> t.List[str]: """Get `sys.argv` or equivalent from `argcomplete` `argcomplete`'s strategy is to call the python script with no arguments, so ``len(sys.argv) == 1``, and run until the `ArgumentParser` is constructed and determine what completions are available. On the other hand, `traitlet`'s subcommand-handling strategy is to check ``sys.argv[1]`` and see if it matches a subcommand, and if so then dynamically load the subcommand app and initialize it with ``sys.argv[1:]``. This helper method helps to take the current tokens for `argcomplete` and pass them through as `argv`. """ if check_argcomplete and "_ARGCOMPLETE" in os.environ: try: from traitlets.config.argcomplete_config import get_argcomplete_cwords cwords = get_argcomplete_cwords() assert cwords is not None return cwords except (ImportError, ModuleNotFoundError): pass return sys.argv def _handle_argcomplete_for_subcommand(cls): """Helper for `argcomplete` to recognize `traitlets` subcommands `argcomplete` does not know that `traitlets` has already consumed subcommands, as it only "sees" the final `argparse.ArgumentParser` that is constructed. (Indeed `KVArgParseConfigLoader` does not get passed subcommands at all currently.) We explicitly manipulate the environment variables used internally by `argcomplete` to get it to skip over the subcommand tokens. """ if "_ARGCOMPLETE" not in os.environ: return try: from traitlets.config.argcomplete_config import increment_argcomplete_index increment_argcomplete_index() except (ImportError, ModuleNotFoundError): pass def parse_command_line(self, argv=None): """Parse the command line arguments.""" assert not isinstance(argv, str) if argv is None: argv = self._get_sys_argv(check_argcomplete=bool(self.subcommands))[1:] self.argv = [cast_unicode(arg) for arg in argv] if argv and argv[0] == "help": # turn `ipython help notebook` into `ipython notebook -h` argv = argv[1:] + ["-h"] if self.subcommands and len(argv) > 0: # we have subcommands, and one may have been specified subc, subargv = argv[0], argv[1:] if re.match(r"^\w(\-?\w)*$", subc) and subc in self.subcommands: # it's a subcommand, and *not* a flag or class parameter self._handle_argcomplete_for_subcommand() return self.initialize_subcommand(subc, subargv) # Arguments after a '--' argument are for the script IPython may be # about to run, not IPython iteslf. For arguments parsed here (help and # version), we want to only search the arguments up to the first # occurrence of '--', which we're calling interpreted_argv. try: interpreted_argv = argv[: argv.index("--")] except ValueError: interpreted_argv = argv if any(x in interpreted_argv for x in ("-h", "--help-all", "--help")): self.print_help("--help-all" in interpreted_argv) self.exit(0) if "--version" in interpreted_argv or "-V" in interpreted_argv: self.print_version() self.exit(0) # flatten flags&aliases, so cl-args get appropriate priority: flags, aliases = self.flatten_flags() classes = tuple(self._classes_with_config_traits()) loader = self._create_loader(argv, aliases, flags, classes=classes) try: self.cli_config = deepcopy(loader.load_config()) except SystemExit: # traitlets 5: no longer print help output on error # help output is huge, and comes after the error raise self.update_config(self.cli_config) # store unparsed args in extra_args self.extra_args = loader.extra_args def _load_config_files(cls, basefilename, path=None, log=None, raise_config_file_errors=False): """Load config files (py,json) by filename and path. yield each config object in turn. """ if not isinstance(path, list): path = [path] for current in reversed(path): # path list is in descending priority order, so load files backwards: pyloader = cls.python_config_loader_class(basefilename + ".py", path=current, log=log) if log: log.debug("Looking for %s in %s", basefilename, current or os.getcwd()) jsonloader = cls.json_config_loader_class(basefilename + ".json", path=current, log=log) loaded: t.List[t.Any] = [] filenames: t.List[str] = [] for loader in [pyloader, jsonloader]: config = None try: config = loader.load_config() except ConfigFileNotFound: pass except Exception: # try to get the full filename, but it will be empty in the # unlikely event that the error raised before filefind finished filename = loader.full_filename or basefilename # problem while running the file if raise_config_file_errors: raise if log: log.error("Exception while loading config file %s", filename, exc_info=True) else: if log: log.debug("Loaded config file: %s", loader.full_filename) if config: for filename, earlier_config in zip(filenames, loaded): collisions = earlier_config.collisions(config) if collisions and log: log.warning( "Collisions detected in {0} and {1} config files." " {1} has higher priority: {2}".format( filename, loader.full_filename, json.dumps(collisions, indent=2), ) ) yield (config, loader.full_filename) loaded.append(config) filenames.append(loader.full_filename) def loaded_config_files(self): """Currently loaded configuration files""" return self._loaded_config_files[:] def load_config_file(self, filename, path=None): """Load config files by filename and path.""" filename, ext = os.path.splitext(filename) new_config = Config() for (config, fname) in self._load_config_files( filename, path=path, log=self.log, raise_config_file_errors=self.raise_config_file_errors, ): new_config.merge(config) if ( fname not in self._loaded_config_files ): # only add to list of loaded files if not previously loaded self._loaded_config_files.append(fname) # add self.cli_config to preserve CLI config priority new_config.merge(self.cli_config) self.update_config(new_config) def _classes_with_config_traits(self, classes=None): """ Yields only classes with configurable traits, and their subclasses. :param classes: The list of classes to iterate; if not set, uses :attr:`classes`. Thus, produced sample config-file will contain all classes on which a trait-value may be overridden: - either on the class owning the trait, - or on its subclasses, even if those subclasses do not define any traits themselves. """ if classes is None: classes = self.classes cls_to_config = OrderedDict( (cls, bool(cls.class_own_traits(config=True))) for cls in self._classes_inc_parents(classes) ) def is_any_parent_included(cls): return any(b in cls_to_config and cls_to_config[b] for b in cls.__bases__) # Mark "empty" classes for inclusion if their parents own-traits, # and loop until no more classes gets marked. # while True: to_incl_orig = cls_to_config.copy() cls_to_config = OrderedDict( (cls, inc_yes or is_any_parent_included(cls)) for cls, inc_yes in cls_to_config.items() ) if cls_to_config == to_incl_orig: break for cl, inc_yes in cls_to_config.items(): if inc_yes: yield cl def generate_config_file(self, classes=None): """generate default config file from Configurables""" lines = ["# Configuration file for %s." % self.name] lines.append("") lines.append("c = get_config() #" + "noqa") lines.append("") classes = self.classes if classes is None else classes config_classes = list(self._classes_with_config_traits(classes)) for cls in config_classes: lines.append(cls.class_config_section(config_classes)) return "\n".join(lines) def close_handlers(self): if getattr(self, "_logging_configured", False): # don't attempt to close handlers unless they have been opened # (note accessing self.log.handlers will create handlers if they # have not yet been initialised) for handler in self.log.handlers: with suppress(Exception): handler.close() self._logging_configured = False def exit(self, exit_status=0): self.log.debug("Exiting application: %s" % self.name) self.close_handlers() sys.exit(exit_status) def __del__(self): self.close_handlers() def launch_instance(cls, argv=None, **kwargs): """Launch a global instance of this Application If a global instance already exists, this reinitializes and starts it """ app = cls.instance(**kwargs) app.initialize(argv) app.start() class Config(dict): # type:ignore[type-arg] """An attribute-based dict that can do smart merges. Accessing a field on a config object for the first time populates the key with either a nested Config object for keys starting with capitals or :class:`.LazyConfigValue` for lowercase keys, allowing quick assignments such as:: c = Config() c.Class.int_trait = 5 c.Class.list_trait.append("x") """ def __init__(self, *args, **kwds): dict.__init__(self, *args, **kwds) self._ensure_subconfig() def _ensure_subconfig(self): """ensure that sub-dicts that should be Config objects are casts dicts that are under section keys to Config objects, which is necessary for constructing Config objects from dict literals. """ for key in self: obj = self[key] if _is_section_key(key) and isinstance(obj, dict) and not isinstance(obj, Config): setattr(self, key, Config(obj)) def _merge(self, other): """deprecated alias, use Config.merge()""" self.merge(other) def merge(self, other): """merge another config object into this one""" to_update = {} for k, v in other.items(): if k not in self: to_update[k] = v else: # I have this key if isinstance(v, Config) and isinstance(self[k], Config): # Recursively merge common sub Configs self[k].merge(v) elif isinstance(v, LazyConfigValue): self[k] = v.merge_into(self[k]) else: # Plain updates for non-Configs to_update[k] = v self.update(to_update) def collisions(self, other: "Config") -> t.Dict[str, t.Any]: """Check for collisions between two config objects. Returns a dict of the form {"Class": {"trait": "collision message"}}`, indicating which values have been ignored. An empty dict indicates no collisions. """ collisions: t.Dict[str, t.Any] = {} for section in self: if section not in other: continue mine = self[section] theirs = other[section] for key in mine: if key in theirs and mine[key] != theirs[key]: collisions.setdefault(section, {}) collisions[section][key] = f"{mine[key]!r} ignored, using {theirs[key]!r}" return collisions def __contains__(self, key): # allow nested contains of the form `"Section.key" in config` if "." in key: first, remainder = key.split(".", 1) if first not in self: return False return remainder in self[first] return super().__contains__(key) # .has_key is deprecated for dictionaries. has_key = __contains__ def _has_section(self, key): return _is_section_key(key) and key in self def copy(self): return type(self)(dict.copy(self)) def __copy__(self): return self.copy() def __deepcopy__(self, memo): new_config = type(self)() for key, value in self.items(): if isinstance(value, (Config, LazyConfigValue)): # deep copy config objects value = copy.deepcopy(value, memo) elif type(value) in {dict, list, set, tuple}: # shallow copy plain container traits value = copy.copy(value) new_config[key] = value return new_config def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: if _is_section_key(key): c = Config() dict.__setitem__(self, key, c) return c elif not key.startswith("_"): # undefined, create lazy value, used for container methods v = LazyConfigValue() dict.__setitem__(self, key, v) return v else: raise KeyError def __setitem__(self, key, value): if _is_section_key(key): if not isinstance(value, Config): raise ValueError( "values whose keys begin with an uppercase " "char must be Config instances: %r, %r" % (key, value) ) dict.__setitem__(self, key, value) def __getattr__(self, key): if key.startswith("__"): return dict.__getattr__(self, key) # type:ignore[attr-defined] try: return self.__getitem__(key) except KeyError as e: raise AttributeError(e) from e def __setattr__(self, key, value): if key.startswith("__"): return dict.__setattr__(self, key, value) try: self.__setitem__(key, value) except KeyError as e: raise AttributeError(e) from e def __delattr__(self, key): if key.startswith("__"): return dict.__delattr__(self, key) try: dict.__delitem__(self, key) except KeyError as e: raise AttributeError(e) from e The provided code snippet includes necessary dependencies for implementing the `get_config` function. Write a Python function `def get_config()` to solve the following problem: Get the config object for the global Application instance, if there is one otherwise return an empty config object Here is the function: def get_config(): """Get the config object for the global Application instance, if there is one otherwise return an empty config object """ if Application.initialized(): return Application.instance().config else: return Config()
Get the config object for the global Application instance, if there is one otherwise return an empty config object
172,016
import inspect import re import types The provided code snippet includes necessary dependencies for implementing the `repr_type` function. Write a Python function `def repr_type(obj)` to solve the following problem: Return a string representation of a value and its type for readable error messages. Here is the function: def repr_type(obj): """Return a string representation of a value and its type for readable error messages. """ the_type = type(obj) msg = f"{obj!r} {the_type!r}" return msg
Return a string representation of a value and its type for readable error messages.
172,017
The provided code snippet includes necessary dependencies for implementing the `nested_update` function. Write a Python function `def nested_update(this, that)` to solve the following problem: Merge two nested dictionaries. Effectively a recursive ``dict.update``. Examples -------- Merge two flat dictionaries: >>> nested_update( ... {'a': 1, 'b': 2}, ... {'b': 3, 'c': 4} ... ) {'a': 1, 'b': 3, 'c': 4} Merge two nested dictionaries: >>> nested_update( ... {'x': {'a': 1, 'b': 2}, 'y': 5, 'z': 6}, ... {'x': {'b': 3, 'c': 4}, 'z': 7, '0': 8}, ... ) {'x': {'a': 1, 'b': 3, 'c': 4}, 'y': 5, 'z': 7, '0': 8} Here is the function: def nested_update(this, that): """Merge two nested dictionaries. Effectively a recursive ``dict.update``. Examples -------- Merge two flat dictionaries: >>> nested_update( ... {'a': 1, 'b': 2}, ... {'b': 3, 'c': 4} ... ) {'a': 1, 'b': 3, 'c': 4} Merge two nested dictionaries: >>> nested_update( ... {'x': {'a': 1, 'b': 2}, 'y': 5, 'z': 6}, ... {'x': {'b': 3, 'c': 4}, 'z': 7, '0': 8}, ... ) {'x': {'a': 1, 'b': 3, 'c': 4}, 'y': 5, 'z': 7, '0': 8} """ for key, value in this.items(): if isinstance(value, dict): if key in that and isinstance(that[key], dict): nested_update(this[key], that[key]) elif key in that: this[key] = that[key] for key, value in that.items(): if key not in this: this[key] = value return this
Merge two nested dictionaries. Effectively a recursive ``dict.update``. Examples -------- Merge two flat dictionaries: >>> nested_update( ... {'a': 1, 'b': 2}, ... {'b': 3, 'c': 4} ... ) {'a': 1, 'b': 3, 'c': 4} Merge two nested dictionaries: >>> nested_update( ... {'x': {'a': 1, 'b': 2}, 'y': 5, 'z': 6}, ... {'x': {'b': 3, 'c': 4}, 'z': 7, '0': 8}, ... ) {'x': {'a': 1, 'b': 3, 'c': 4}, 'y': 5, 'z': 7, '0': 8}
172,018
import copy from inspect import Parameter, Signature, signature from typing import Type, TypeVar from ..traitlets import HasTraits, Undefined def _get_default(value): """Get default argument value, given the trait default value.""" return Parameter.empty if value == Undefined else value T = TypeVar("T", bound=HasTraits) def signature(obj: Callable[..., Any], *, follow_wrapped: bool = ...) -> Signature: ... class Signature: def __init__(self, parameters: Optional[Sequence[Parameter]] = ..., *, return_annotation: Any = ...) -> None: ... # TODO: can we be more specific here? empty: object = ... parameters: Mapping[str, Parameter] # TODO: can we be more specific here? return_annotation: Any def bind(self, *args: Any, **kwargs: Any) -> BoundArguments: ... def bind_partial(self, *args: Any, **kwargs: Any) -> BoundArguments: ... def replace(self, *, parameters: Optional[Sequence[Parameter]] = ..., return_annotation: Any = ...) -> Signature: ... def from_callable(cls, obj: Callable[..., Any], *, follow_wrapped: bool = ...) -> Signature: ... class Parameter: def __init__(self, name: str, kind: _ParameterKind, *, default: Any = ..., annotation: Any = ...) -> None: ... empty: Any = ... name: str default: Any annotation: Any kind: _ParameterKind POSITIONAL_ONLY: ClassVar[Literal[_ParameterKind.POSITIONAL_ONLY]] POSITIONAL_OR_KEYWORD: ClassVar[Literal[_ParameterKind.POSITIONAL_OR_KEYWORD]] VAR_POSITIONAL: ClassVar[Literal[_ParameterKind.VAR_POSITIONAL]] KEYWORD_ONLY: ClassVar[Literal[_ParameterKind.KEYWORD_ONLY]] VAR_KEYWORD: ClassVar[Literal[_ParameterKind.VAR_KEYWORD]] def replace( self, *, name: Optional[str] = ..., kind: Optional[_ParameterKind] = ..., default: Any = ..., annotation: Any = ... ) -> Parameter: ... Type: _SpecialForm = ... The provided code snippet includes necessary dependencies for implementing the `signature_has_traits` function. Write a Python function `def signature_has_traits(cls: Type[T]) -> Type[T]` to solve the following problem: Return a decorated class with a constructor signature that contain Trait names as kwargs. Here is the function: def signature_has_traits(cls: Type[T]) -> Type[T]: """Return a decorated class with a constructor signature that contain Trait names as kwargs.""" traits = [ (name, _get_default(value.default_value)) for name, value in cls.class_traits().items() if not name.startswith("_") ] # Taking the __init__ signature, as the cls signature is not initialized yet old_signature = signature(cls.__init__) old_parameter_names = list(old_signature.parameters) old_positional_parameters = [] old_var_positional_parameter = None # This won't be None if the old signature contains *args old_keyword_only_parameters = [] old_var_keyword_parameter = None # This won't be None if the old signature contains **kwargs for parameter_name in old_signature.parameters: # Copy the parameter parameter = copy.copy(old_signature.parameters[parameter_name]) if ( parameter.kind is Parameter.POSITIONAL_ONLY or parameter.kind is Parameter.POSITIONAL_OR_KEYWORD ): old_positional_parameters.append(parameter) elif parameter.kind is Parameter.VAR_POSITIONAL: old_var_positional_parameter = parameter elif parameter.kind is Parameter.KEYWORD_ONLY: old_keyword_only_parameters.append(parameter) elif parameter.kind is Parameter.VAR_KEYWORD: old_var_keyword_parameter = parameter # Unfortunately, if the old signature does not contain **kwargs, we can't do anything, # because it can't accept traits as keyword arguments if old_var_keyword_parameter is None: raise RuntimeError( "The {} constructor does not take **kwargs, which means that the signature can not be expanded with trait names".format( cls ) ) new_parameters = [] # Append the old positional parameters (except `self` which is the first parameter) new_parameters += old_positional_parameters[1:] # Append *args if the old signature had it if old_var_positional_parameter is not None: new_parameters.append(old_var_positional_parameter) # Append the old keyword only parameters new_parameters += old_keyword_only_parameters # Append trait names as keyword only parameters in the signature new_parameters += [ Parameter(name, kind=Parameter.KEYWORD_ONLY, default=default) for name, default in traits if name not in old_parameter_names ] # Append **kwargs new_parameters.append(old_var_keyword_parameter) cls.__signature__ = Signature(new_parameters) # type:ignore[attr-defined] return cls
Return a decorated class with a constructor signature that contain Trait names as kwargs.
172,019
import re import textwrap from textwrap import dedent from textwrap import indent as _indent from typing import List def dedent(text: str) -> str: ... List = _Alias() The provided code snippet includes necessary dependencies for implementing the `wrap_paragraphs` function. Write a Python function `def wrap_paragraphs(text: str, ncols: int = 80) -> List[str]` to solve the following problem: Wrap multiple paragraphs to fit a specified width. This is equivalent to textwrap.wrap, but with support for multiple paragraphs, as separated by empty lines. Returns ------- list of complete paragraphs, wrapped to fill `ncols` columns. Here is the function: def wrap_paragraphs(text: str, ncols: int = 80) -> List[str]: """Wrap multiple paragraphs to fit a specified width. This is equivalent to textwrap.wrap, but with support for multiple paragraphs, as separated by empty lines. Returns ------- list of complete paragraphs, wrapped to fill `ncols` columns. """ paragraph_re = re.compile(r"\n(\s*\n)+", re.MULTILINE) text = dedent(text).strip() paragraphs = paragraph_re.split(text)[::2] # every other entry is space out_ps = [] indent_re = re.compile(r"\n\s+", re.MULTILINE) for p in paragraphs: # presume indentation that survives dedent is meaningful formatting, # so don't fill unless text is flush. if indent_re.search(p) is None: # wrap paragraph p = textwrap.fill(p, ncols) out_ps.append(p) return out_ps
Wrap multiple paragraphs to fit a specified width. This is equivalent to textwrap.wrap, but with support for multiple paragraphs, as separated by empty lines. Returns ------- list of complete paragraphs, wrapped to fill `ncols` columns.
172,020
import inspect from functools import partial class partial(Generic[_T]): func: Callable[..., _T] args: Tuple[Any, ...] keywords: Dict[str, Any] def __init__(self, func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> _T: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... The provided code snippet includes necessary dependencies for implementing the `getargspec` function. Write a Python function `def getargspec(func)` to solve the following problem: Like inspect.getargspec but supports functools.partial as well. Here is the function: def getargspec(func): """Like inspect.getargspec but supports functools.partial as well.""" if inspect.ismethod(func): func = func.__func__ if type(func) is partial: orig_func = func.func argspec = getargspec(orig_func) args = list(argspec[0]) defaults = list(argspec[3] or ()) kwoargs = list(argspec[4]) kwodefs = dict(argspec[5] or {}) if func.args: args = args[len(func.args) :] for arg in func.keywords or (): try: i = args.index(arg) - len(args) del args[i] try: del defaults[i] except IndexError: pass except ValueError: # must be a kwonly arg i = kwoargs.index(arg) del kwoargs[i] del kwodefs[arg] return inspect.FullArgSpec( args, argspec[1], argspec[2], tuple(defaults), kwoargs, kwodefs, argspec[6] ) while hasattr(func, "__wrapped__"): func = func.__wrapped__ if not inspect.isfunction(func): raise TypeError("%r is not a Python function" % func) return inspect.getfullargspec(func)
Like inspect.getargspec but supports functools.partial as well.
172,021
import re import sys import inspect import operator import itertools from contextlib import _GeneratorContextManager from inspect import getfullargspec, iscoroutinefunction, isgeneratorfunction class FunctionMaker(object): """ An object with the ability to create functions with a given signature. It has attributes name, doc, module, signature, defaults, dict and methods update and make. """ # Atomic get-and-increment provided by the GIL _compile_count = itertools.count() # make pylint happy args = varargs = varkw = defaults = kwonlyargs = kwonlydefaults = () def __init__(self, func=None, name=None, signature=None, defaults=None, doc=None, module=None, funcdict=None): self.shortsignature = signature if func: # func can be a class or a callable, but not an instance method self.name = func.__name__ if self.name == '<lambda>': # small hack for lambda functions self.name = '_lambda_' self.doc = func.__doc__ self.module = func.__module__ if inspect.isroutine(func): argspec = getfullargspec(func) self.annotations = getattr(func, '__annotations__', {}) for a in ('args', 'varargs', 'varkw', 'defaults', 'kwonlyargs', 'kwonlydefaults'): setattr(self, a, getattr(argspec, a)) for i, arg in enumerate(self.args): setattr(self, 'arg%d' % i, arg) allargs = list(self.args) allshortargs = list(self.args) if self.varargs: allargs.append('*' + self.varargs) allshortargs.append('*' + self.varargs) elif self.kwonlyargs: allargs.append('*') # single star syntax for a in self.kwonlyargs: allargs.append('%s=None' % a) allshortargs.append('%s=%s' % (a, a)) if self.varkw: allargs.append('**' + self.varkw) allshortargs.append('**' + self.varkw) self.signature = ', '.join(allargs) self.shortsignature = ', '.join(allshortargs) self.dict = func.__dict__.copy() # func=None happens when decorating a caller if name: self.name = name if signature is not None: self.signature = signature if defaults: self.defaults = defaults if doc: self.doc = doc if module: self.module = module if funcdict: self.dict = funcdict # check existence required attributes assert hasattr(self, 'name') if not hasattr(self, 'signature'): raise TypeError('You are decorating a non function: %s' % func) def update(self, func, **kw): """ Update the signature of func with the data in self """ func.__name__ = self.name func.__doc__ = getattr(self, 'doc', None) func.__dict__ = getattr(self, 'dict', {}) func.__defaults__ = self.defaults func.__kwdefaults__ = self.kwonlydefaults or None func.__annotations__ = getattr(self, 'annotations', None) try: frame = sys._getframe(3) except AttributeError: # for IronPython and similar implementations callermodule = '?' else: callermodule = frame.f_globals.get('__name__', '?') func.__module__ = getattr(self, 'module', callermodule) func.__dict__.update(kw) def make(self, src_templ, evaldict=None, addsource=False, **attrs): """ Make a new function from a given template and update the signature """ src = src_templ % vars(self) # expand name and signature evaldict = evaldict or {} mo = DEF.search(src) if mo is None: raise SyntaxError('not a valid function template\n%s' % src) name = mo.group(1) # extract the function name names = set([name] + [arg.strip(' *') for arg in self.shortsignature.split(',')]) for n in names: if n in ('_func_', '_call_'): raise NameError('%s is overridden in\n%s' % (n, src)) if not src.endswith('\n'): # add a newline for old Pythons src += '\n' # Ensure each generated function has a unique filename for profilers # (such as cProfile) that depend on the tuple of (<filename>, # <definition line>, <function name>) being unique. filename = '<decorator-gen-%d>' % next(self._compile_count) try: code = compile(src, filename, 'single') exec(code, evaldict) except Exception: print('Error in generated code:', file=sys.stderr) print(src, file=sys.stderr) raise func = evaldict[name] if addsource: attrs['__source__'] = src self.update(func, **attrs) return func def create(cls, obj, body, evaldict, defaults=None, doc=None, module=None, addsource=True, **attrs): """ Create a function from the strings name, signature and body. evaldict is the evaluation dictionary. If addsource is true an attribute __source__ is added to the result. The attributes attrs are added, if any. """ if isinstance(obj, str): # "name(signature)" name, rest = obj.strip().split('(', 1) signature = rest[:-1] # strip a right parens func = None else: # a function name = None signature = None func = obj self = cls(func, name, signature, defaults, doc, module) ibody = '\n'.join(' ' + line for line in body.splitlines()) caller = evaldict.get('_call_') # when called from `decorate` if caller and iscoroutinefunction(caller): body = ('async def %(name)s(%(signature)s):\n' + ibody).replace( 'return', 'return await') else: body = 'def %(name)s(%(signature)s):\n' + ibody return self.make(body, evaldict, addsource, **attrs) The provided code snippet includes necessary dependencies for implementing the `decoratorx` function. Write a Python function `def decoratorx(caller)` to solve the following problem: A version of "decorator" implemented via "exec" and not via the Signature object. Use this if you are want to preserve the `.__code__` object properties (https://github.com/micheles/decorator/issues/129). Here is the function: def decoratorx(caller): """ A version of "decorator" implemented via "exec" and not via the Signature object. Use this if you are want to preserve the `.__code__` object properties (https://github.com/micheles/decorator/issues/129). """ def dec(func): return FunctionMaker.create( func, "return _call_(_func_, %(shortsignature)s)", dict(_call_=caller, _func_=func), __wrapped__=func, __qualname__=func.__qualname__) return dec
A version of "decorator" implemented via "exec" and not via the Signature object. Use this if you are want to preserve the `.__code__` object properties (https://github.com/micheles/decorator/issues/129).
172,022
import re import sys import inspect import operator import itertools from contextlib import _GeneratorContextManager from inspect import getfullargspec, iscoroutinefunction, isgeneratorfunction POS = inspect.Parameter.POSITIONAL_OR_KEYWORD EMPTY = inspect.Parameter.empty def decorate(func, caller, extras=(), kwsyntax=False): """ Decorates a function/generator/coroutine using a caller. If kwsyntax is True calling the decorated functions with keyword syntax will pass the named arguments inside the ``kw`` dictionary, even if such argument are positional, similarly to what functools.wraps does. By default kwsyntax is False and the the arguments are untouched. """ sig = inspect.signature(func) if iscoroutinefunction(caller): async def fun(*args, **kw): if not kwsyntax: args, kw = fix(args, kw, sig) return await caller(func, *(extras + args), **kw) elif isgeneratorfunction(caller): def fun(*args, **kw): if not kwsyntax: args, kw = fix(args, kw, sig) for res in caller(func, *(extras + args), **kw): yield res else: def fun(*args, **kw): if not kwsyntax: args, kw = fix(args, kw, sig) return caller(func, *(extras + args), **kw) fun.__name__ = func.__name__ fun.__doc__ = func.__doc__ fun.__wrapped__ = func fun.__signature__ = sig fun.__qualname__ = func.__qualname__ # builtin functions like defaultdict.__setitem__ lack many attributes try: fun.__defaults__ = func.__defaults__ except AttributeError: pass try: fun.__kwdefaults__ = func.__kwdefaults__ except AttributeError: pass try: fun.__annotations__ = func.__annotations__ except AttributeError: pass try: fun.__module__ = func.__module__ except AttributeError: pass try: fun.__dict__.update(func.__dict__) except AttributeError: pass return fun The provided code snippet includes necessary dependencies for implementing the `decorator` function. Write a Python function `def decorator(caller, _func=None, kwsyntax=False)` to solve the following problem: decorator(caller) converts a caller function into a decorator Here is the function: def decorator(caller, _func=None, kwsyntax=False): """ decorator(caller) converts a caller function into a decorator """ if _func is not None: # return a decorated function # this is obsolete behavior; you should use decorate instead return decorate(_func, caller, (), kwsyntax) # else return a decorator function sig = inspect.signature(caller) dec_params = [p for p in sig.parameters.values() if p.kind is POS] def dec(func=None, *args, **kw): na = len(args) + 1 extras = args + tuple(kw.get(p.name, p.default) for p in dec_params[na:] if p.default is not EMPTY) if func is None: return lambda func: decorate(func, caller, extras, kwsyntax) else: return decorate(func, caller, extras, kwsyntax) dec.__signature__ = sig.replace(parameters=dec_params) dec.__name__ = caller.__name__ dec.__doc__ = caller.__doc__ dec.__wrapped__ = caller dec.__qualname__ = caller.__qualname__ dec.__kwdefaults__ = getattr(caller, '__kwdefaults__', None) dec.__dict__.update(caller.__dict__) return dec
decorator(caller) converts a caller function into a decorator
172,023
import re import sys import inspect import operator import itertools from contextlib import _GeneratorContextManager from inspect import getfullargspec, iscoroutinefunction, isgeneratorfunction _contextmanager = decorator(ContextManager) def contextmanager(func): # Enable Pylint config: contextmanager-decorators=decorator.contextmanager return _contextmanager(func)
null
172,024
import re import sys import inspect import operator import itertools from contextlib import _GeneratorContextManager from inspect import getfullargspec, iscoroutinefunction, isgeneratorfunction class FunctionMaker(object): """ An object with the ability to create functions with a given signature. It has attributes name, doc, module, signature, defaults, dict and methods update and make. """ # Atomic get-and-increment provided by the GIL _compile_count = itertools.count() # make pylint happy args = varargs = varkw = defaults = kwonlyargs = kwonlydefaults = () def __init__(self, func=None, name=None, signature=None, defaults=None, doc=None, module=None, funcdict=None): self.shortsignature = signature if func: # func can be a class or a callable, but not an instance method self.name = func.__name__ if self.name == '<lambda>': # small hack for lambda functions self.name = '_lambda_' self.doc = func.__doc__ self.module = func.__module__ if inspect.isroutine(func): argspec = getfullargspec(func) self.annotations = getattr(func, '__annotations__', {}) for a in ('args', 'varargs', 'varkw', 'defaults', 'kwonlyargs', 'kwonlydefaults'): setattr(self, a, getattr(argspec, a)) for i, arg in enumerate(self.args): setattr(self, 'arg%d' % i, arg) allargs = list(self.args) allshortargs = list(self.args) if self.varargs: allargs.append('*' + self.varargs) allshortargs.append('*' + self.varargs) elif self.kwonlyargs: allargs.append('*') # single star syntax for a in self.kwonlyargs: allargs.append('%s=None' % a) allshortargs.append('%s=%s' % (a, a)) if self.varkw: allargs.append('**' + self.varkw) allshortargs.append('**' + self.varkw) self.signature = ', '.join(allargs) self.shortsignature = ', '.join(allshortargs) self.dict = func.__dict__.copy() # func=None happens when decorating a caller if name: self.name = name if signature is not None: self.signature = signature if defaults: self.defaults = defaults if doc: self.doc = doc if module: self.module = module if funcdict: self.dict = funcdict # check existence required attributes assert hasattr(self, 'name') if not hasattr(self, 'signature'): raise TypeError('You are decorating a non function: %s' % func) def update(self, func, **kw): """ Update the signature of func with the data in self """ func.__name__ = self.name func.__doc__ = getattr(self, 'doc', None) func.__dict__ = getattr(self, 'dict', {}) func.__defaults__ = self.defaults func.__kwdefaults__ = self.kwonlydefaults or None func.__annotations__ = getattr(self, 'annotations', None) try: frame = sys._getframe(3) except AttributeError: # for IronPython and similar implementations callermodule = '?' else: callermodule = frame.f_globals.get('__name__', '?') func.__module__ = getattr(self, 'module', callermodule) func.__dict__.update(kw) def make(self, src_templ, evaldict=None, addsource=False, **attrs): """ Make a new function from a given template and update the signature """ src = src_templ % vars(self) # expand name and signature evaldict = evaldict or {} mo = DEF.search(src) if mo is None: raise SyntaxError('not a valid function template\n%s' % src) name = mo.group(1) # extract the function name names = set([name] + [arg.strip(' *') for arg in self.shortsignature.split(',')]) for n in names: if n in ('_func_', '_call_'): raise NameError('%s is overridden in\n%s' % (n, src)) if not src.endswith('\n'): # add a newline for old Pythons src += '\n' # Ensure each generated function has a unique filename for profilers # (such as cProfile) that depend on the tuple of (<filename>, # <definition line>, <function name>) being unique. filename = '<decorator-gen-%d>' % next(self._compile_count) try: code = compile(src, filename, 'single') exec(code, evaldict) except Exception: print('Error in generated code:', file=sys.stderr) print(src, file=sys.stderr) raise func = evaldict[name] if addsource: attrs['__source__'] = src self.update(func, **attrs) return func def create(cls, obj, body, evaldict, defaults=None, doc=None, module=None, addsource=True, **attrs): """ Create a function from the strings name, signature and body. evaldict is the evaluation dictionary. If addsource is true an attribute __source__ is added to the result. The attributes attrs are added, if any. """ if isinstance(obj, str): # "name(signature)" name, rest = obj.strip().split('(', 1) signature = rest[:-1] # strip a right parens func = None else: # a function name = None signature = None func = obj self = cls(func, name, signature, defaults, doc, module) ibody = '\n'.join(' ' + line for line in body.splitlines()) caller = evaldict.get('_call_') # when called from `decorate` if caller and iscoroutinefunction(caller): body = ('async def %(name)s(%(signature)s):\n' + ibody).replace( 'return', 'return await') else: body = 'def %(name)s(%(signature)s):\n' + ibody return self.make(body, evaldict, addsource, **attrs) def append(a, vancestors): """ Append ``a`` to the list of the virtual ancestors, unless it is already included. """ add = True for j, va in enumerate(vancestors): if issubclass(va, a): add = False break if issubclass(a, va): vancestors[j] = a add = False if add: vancestors.append(a) def getfullargspec(func: object) -> FullArgSpec: ... The provided code snippet includes necessary dependencies for implementing the `dispatch_on` function. Write a Python function `def dispatch_on(*dispatch_args)` to solve the following problem: Factory of decorators turning a function into a generic function dispatching on the given arguments. Here is the function: def dispatch_on(*dispatch_args): """ Factory of decorators turning a function into a generic function dispatching on the given arguments. """ assert dispatch_args, 'No dispatch args passed' dispatch_str = '(%s,)' % ', '.join(dispatch_args) def check(arguments, wrong=operator.ne, msg=''): """Make sure one passes the expected number of arguments""" if wrong(len(arguments), len(dispatch_args)): raise TypeError('Expected %d arguments, got %d%s' % (len(dispatch_args), len(arguments), msg)) def gen_func_dec(func): """Decorator turning a function into a generic function""" # first check the dispatch arguments argset = set(getfullargspec(func).args) if not set(dispatch_args) <= argset: raise NameError('Unknown dispatch arguments %s' % dispatch_str) typemap = {} def vancestors(*types): """ Get a list of sets of virtual ancestors for the given types """ check(types) ras = [[] for _ in range(len(dispatch_args))] for types_ in typemap: for t, type_, ra in zip(types, types_, ras): if issubclass(t, type_) and type_ not in t.mro(): append(type_, ra) return [set(ra) for ra in ras] def ancestors(*types): """ Get a list of virtual MROs, one for each type """ check(types) lists = [] for t, vas in zip(types, vancestors(*types)): n_vas = len(vas) if n_vas > 1: raise RuntimeError( 'Ambiguous dispatch for %s: %s' % (t, vas)) elif n_vas == 1: va, = vas mro = type('t', (t, va), {}).mro()[1:] else: mro = t.mro() lists.append(mro[:-1]) # discard t and object return lists def register(*types): """ Decorator to register an implementation for the given types """ check(types) def dec(f): check(getfullargspec(f).args, operator.lt, ' in ' + f.__name__) typemap[types] = f return f return dec def dispatch_info(*types): """ An utility to introspect the dispatch algorithm """ check(types) lst = [] for anc in itertools.product(*ancestors(*types)): lst.append(tuple(a.__name__ for a in anc)) return lst def _dispatch(dispatch_args, *args, **kw): types = tuple(type(arg) for arg in dispatch_args) try: # fast path f = typemap[types] except KeyError: pass else: return f(*args, **kw) combinations = itertools.product(*ancestors(*types)) next(combinations) # the first one has been already tried for types_ in combinations: f = typemap.get(types_) if f is not None: return f(*args, **kw) # else call the default implementation return func(*args, **kw) return FunctionMaker.create( func, 'return _f_(%s, %%(shortsignature)s)' % dispatch_str, dict(_f_=_dispatch), register=register, default=func, typemap=typemap, vancestors=vancestors, ancestors=ancestors, dispatch_info=dispatch_info, __wrapped__=func) gen_func_dec.__name__ = 'dispatch_on' + dispatch_str return gen_func_dec
Factory of decorators turning a function into a generic function dispatching on the given arguments.
172,025
from __future__ import annotations import os import signal import sys import threading from collections import deque from typing import ( Callable, ContextManager, Deque, Dict, Generator, Generic, List, Optional, TypeVar, Union, ) from wcwidth import wcwidth The provided code snippet includes necessary dependencies for implementing the `suspend_to_background_supported` function. Write a Python function `def suspend_to_background_supported() -> bool` to solve the following problem: Returns `True` when the Python implementation supports suspend-to-background. This is typically `False' on Windows systems. Here is the function: def suspend_to_background_supported() -> bool: """ Returns `True` when the Python implementation supports suspend-to-background. This is typically `False' on Windows systems. """ return hasattr(signal, "SIGTSTP")
Returns `True` when the Python implementation supports suspend-to-background. This is typically `False' on Windows systems.
172,026
from __future__ import annotations import os import signal import sys import threading from collections import deque from typing import ( Callable, ContextManager, Deque, Dict, Generator, Generic, List, Optional, TypeVar, Union, ) from wcwidth import wcwidth The provided code snippet includes necessary dependencies for implementing the `is_windows` function. Write a Python function `def is_windows() -> bool` to solve the following problem: True when we are using Windows. Here is the function: def is_windows() -> bool: """ True when we are using Windows. """ return sys.platform == "win32" # Not 'darwin' or 'linux2'
True when we are using Windows.
172,027
from __future__ import annotations import os import signal import sys import threading from collections import deque from typing import ( Callable, ContextManager, Deque, Dict, Generator, Generic, List, Optional, TypeVar, Union, ) from wcwidth import wcwidth def is_win_vt100_enabled() -> bool: """ Returns True when we're running Windows and VT100 escape sequences are supported. """ if sys.platform != "win32": return False hconsole = HANDLE(windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)) # Get original console mode. original_mode = DWORD(0) windll.kernel32.GetConsoleMode(hconsole, byref(original_mode)) try: # Try to enable VT100 sequences. result: int = windll.kernel32.SetConsoleMode( hconsole, DWORD(ENABLE_PROCESSED_INPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING) ) return result == 1 finally: windll.kernel32.SetConsoleMode(hconsole, original_mode) The provided code snippet includes necessary dependencies for implementing the `is_windows_vt100_supported` function. Write a Python function `def is_windows_vt100_supported() -> bool` to solve the following problem: True when we are using Windows, but VT100 escape sequences are supported. Here is the function: def is_windows_vt100_supported() -> bool: """ True when we are using Windows, but VT100 escape sequences are supported. """ if sys.platform == "win32": # Import needs to be inline. Windows libraries are not always available. from prompt_toolkit.output.windows10 import is_win_vt100_enabled return is_win_vt100_enabled() return False
True when we are using Windows, but VT100 escape sequences are supported.
172,028
from __future__ import annotations import os import signal import sys import threading from collections import deque from typing import ( Callable, ContextManager, Deque, Dict, Generator, Generic, List, Optional, TypeVar, Union, ) from wcwidth import wcwidth _T = TypeVar("_T") class Generator(Iterator[_T_co], Generic[_T_co, _T_contra, _V_co]): def __next__(self) -> _T_co: ... def send(self, __value: _T_contra) -> _T_co: ... def throw( self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ... ) -> _T_co: ... def throw(self, __typ: BaseException, __val: None = ..., __tb: Optional[TracebackType] = ...) -> _T_co: ... def close(self) -> None: ... def __iter__(self) -> Generator[_T_co, _T_contra, _V_co]: ... def gi_code(self) -> CodeType: ... def gi_frame(self) -> FrameType: ... def gi_running(self) -> bool: ... def gi_yieldfrom(self) -> Optional[Generator[Any, Any, Any]]: ... The provided code snippet includes necessary dependencies for implementing the `take_using_weights` function. Write a Python function `def take_using_weights( items: list[_T], weights: list[int] ) -> Generator[_T, None, None]` to solve the following problem: Generator that keeps yielding items from the items list, in proportion to their weight. For instance:: # Getting the first 70 items from this generator should have yielded 10 # times A, 20 times B and 40 times C, all distributed equally.. take_using_weights(['A', 'B', 'C'], [5, 10, 20]) :param items: List of items to take from. :param weights: Integers representing the weight. (Numbers have to be integers, not floats.) Here is the function: def take_using_weights( items: list[_T], weights: list[int] ) -> Generator[_T, None, None]: """ Generator that keeps yielding items from the items list, in proportion to their weight. For instance:: # Getting the first 70 items from this generator should have yielded 10 # times A, 20 times B and 40 times C, all distributed equally.. take_using_weights(['A', 'B', 'C'], [5, 10, 20]) :param items: List of items to take from. :param weights: Integers representing the weight. (Numbers have to be integers, not floats.) """ assert len(items) == len(weights) assert len(items) > 0 # Remove items with zero-weight. items2 = [] weights2 = [] for item, w in zip(items, weights): if w > 0: items2.append(item) weights2.append(w) items = items2 weights = weights2 # Make sure that we have some items left. if not items: raise ValueError("Did't got any items with a positive weight.") # already_taken = [0 for i in items] item_count = len(items) max_weight = max(weights) i = 0 while True: # Each iteration of this loop, we fill up until by (total_weight/max_weight). adding = True while adding: adding = False for item_i, item, weight in zip(range(item_count), items, weights): if already_taken[item_i] < i * weight / float(max_weight): yield item already_taken[item_i] += 1 adding = True i += 1
Generator that keeps yielding items from the items list, in proportion to their weight. For instance:: # Getting the first 70 items from this generator should have yielded 10 # times A, 20 times B and 40 times C, all distributed equally.. take_using_weights(['A', 'B', 'C'], [5, 10, 20]) :param items: List of items to take from. :param weights: Integers representing the weight. (Numbers have to be integers, not floats.)
172,029
from __future__ import annotations import os import signal import sys import threading from collections import deque from typing import ( Callable, ContextManager, Deque, Dict, Generator, Generic, List, Optional, TypeVar, Union, ) from wcwidth import wcwidth class Callable(BaseTypingInstance): def py__call__(self, arguments): """ def x() -> Callable[[Callable[..., _T]], _T]: ... """ # The 0th index are the arguments. try: param_values = self._generics_manager[0] result_values = self._generics_manager[1] except IndexError: debug.warning('Callable[...] defined without two arguments') return NO_VALUES else: from jedi.inference.gradual.annotation import infer_return_for_callable return infer_return_for_callable(arguments, param_values, result_values) def py__get__(self, instance, class_value): return ValueSet([self]) The provided code snippet includes necessary dependencies for implementing the `to_str` function. Write a Python function `def to_str(value: Callable[[], str] | str) -> str` to solve the following problem: Turn callable or string into string. Here is the function: def to_str(value: Callable[[], str] | str) -> str: "Turn callable or string into string." if callable(value): return to_str(value()) else: return str(value)
Turn callable or string into string.
172,030
from __future__ import annotations import os import signal import sys import threading from collections import deque from typing import ( Callable, ContextManager, Deque, Dict, Generator, Generic, List, Optional, TypeVar, Union, ) from wcwidth import wcwidth class Callable(BaseTypingInstance): def py__call__(self, arguments): """ def x() -> Callable[[Callable[..., _T]], _T]: ... """ # The 0th index are the arguments. try: param_values = self._generics_manager[0] result_values = self._generics_manager[1] except IndexError: debug.warning('Callable[...] defined without two arguments') return NO_VALUES else: from jedi.inference.gradual.annotation import infer_return_for_callable return infer_return_for_callable(arguments, param_values, result_values) def py__get__(self, instance, class_value): return ValueSet([self]) The provided code snippet includes necessary dependencies for implementing the `to_int` function. Write a Python function `def to_int(value: Callable[[], int] | int) -> int` to solve the following problem: Turn callable or int into int. Here is the function: def to_int(value: Callable[[], int] | int) -> int: "Turn callable or int into int." if callable(value): return to_int(value()) else: return int(value)
Turn callable or int into int.
172,031
from __future__ import annotations import os import signal import sys import threading from collections import deque from typing import ( Callable, ContextManager, Deque, Dict, Generator, Generic, List, Optional, TypeVar, Union, ) from wcwidth import wcwidth AnyFloat = Union[Callable[[], float], float] The provided code snippet includes necessary dependencies for implementing the `to_float` function. Write a Python function `def to_float(value: AnyFloat) -> float` to solve the following problem: Turn callable or float into float. Here is the function: def to_float(value: AnyFloat) -> float: "Turn callable or float into float." if callable(value): return to_float(value()) else: return float(value)
Turn callable or float into float.
172,032
from __future__ import annotations import os import signal import sys import threading from collections import deque from typing import ( Callable, ContextManager, Deque, Dict, Generator, Generic, List, Optional, TypeVar, Union, ) from wcwidth import wcwidth The provided code snippet includes necessary dependencies for implementing the `is_dumb_terminal` function. Write a Python function `def is_dumb_terminal(term: str | None = None) -> bool` to solve the following problem: True if this terminal type is considered "dumb". If so, we should fall back to the simplest possible form of line editing, without cursor positioning and color support. Here is the function: def is_dumb_terminal(term: str | None = None) -> bool: """ True if this terminal type is considered "dumb". If so, we should fall back to the simplest possible form of line editing, without cursor positioning and color support. """ if term is None: return is_dumb_terminal(os.environ.get("TERM", "")) return term.lower() in ["dumb", "unknown"]
True if this terminal type is considered "dumb". If so, we should fall back to the simplest possible form of line editing, without cursor positioning and color support.
172,033
from __future__ import annotations import asyncio import contextvars import socket import sys from asyncio import get_running_loop from typing import Any, Awaitable, Callable, List, Optional, Set, TextIO, Tuple, cast from prompt_toolkit.application.current import create_app_session, get_app from prompt_toolkit.application.run_in_terminal import run_in_terminal from prompt_toolkit.data_structures import Size from prompt_toolkit.formatted_text import AnyFormattedText, to_formatted_text from prompt_toolkit.input import PipeInput, create_pipe_input from prompt_toolkit.output.vt100 import Vt100_Output from prompt_toolkit.renderer import print_formatted_text as print_formatted_text from prompt_toolkit.styles import BaseStyle, DummyStyle from .log import logger from .protocol import ( DO, ECHO, IAC, LINEMODE, MODE, NAWS, SB, SE, SEND, SUPPRESS_GO_AHEAD, TTYPE, WILL, TelnetProtocolParser, ) def int2byte(number: int) -> bytes: return bytes((number,)) logger = logging.getLogger(__package__) IAC = int2byte(255) DO = int2byte(253) LINEMODE = int2byte(34) SB = int2byte(250) WILL = int2byte(251) MODE = int2byte(1) SE = int2byte(240) ECHO = int2byte(1) NAWS = int2byte(31) LINEMODE = int2byte(34) SUPPRESS_GO_AHEAD = int2byte(3) TTYPE = int2byte(24) SEND = int2byte(1) def _initialize_telnet(connection: socket.socket) -> None: logger.info("Initializing telnet connection") # Iac Do Linemode connection.send(IAC + DO + LINEMODE) # Suppress Go Ahead. (This seems important for Putty to do correct echoing.) # This will allow bi-directional operation. connection.send(IAC + WILL + SUPPRESS_GO_AHEAD) # Iac sb connection.send(IAC + SB + LINEMODE + MODE + int2byte(0) + IAC + SE) # IAC Will Echo connection.send(IAC + WILL + ECHO) # Negotiate window size connection.send(IAC + DO + NAWS) # Negotiate terminal type # Assume the client will accept the negociation with `IAC + WILL + TTYPE` connection.send(IAC + DO + TTYPE) # We can then select the first terminal type supported by the client, # which is generally the best type the client supports # The client should reply with a `IAC + SB + TTYPE + IS + ttype + IAC + SE` connection.send(IAC + SB + TTYPE + SEND + IAC + SE)
null
172,034
from __future__ import annotations import asyncio import contextvars import socket import sys from asyncio import get_running_loop from typing import Any, Awaitable, Callable, List, Optional, Set, TextIO, Tuple, cast from prompt_toolkit.application.current import create_app_session, get_app from prompt_toolkit.application.run_in_terminal import run_in_terminal from prompt_toolkit.data_structures import Size from prompt_toolkit.formatted_text import AnyFormattedText, to_formatted_text from prompt_toolkit.input import PipeInput, create_pipe_input from prompt_toolkit.output.vt100 import Vt100_Output from prompt_toolkit.renderer import print_formatted_text as print_formatted_text from prompt_toolkit.styles import BaseStyle, DummyStyle from .log import logger from .protocol import ( DO, ECHO, IAC, LINEMODE, MODE, NAWS, SB, SE, SEND, SUPPRESS_GO_AHEAD, TTYPE, WILL, TelnetProtocolParser, ) class TelnetConnection: """ Class that represents one Telnet connection. """ def __init__( self, conn: socket.socket, addr: tuple[str, int], interact: Callable[[TelnetConnection], Awaitable[None]], server: TelnetServer, encoding: str, style: BaseStyle | None, vt100_input: PipeInput, enable_cpr: bool = True, ) -> None: self.conn = conn self.addr = addr self.interact = interact self.server = server self.encoding = encoding self.style = style self._closed = False self._ready = asyncio.Event() self.vt100_input = vt100_input self.enable_cpr = enable_cpr self.vt100_output: Vt100_Output | None = None # Create "Output" object. self.size = Size(rows=40, columns=79) # Initialize. _initialize_telnet(conn) # Create output. def get_size() -> Size: return self.size self.stdout = cast(TextIO, _ConnectionStdout(conn, encoding=encoding)) def data_received(data: bytes) -> None: """TelnetProtocolParser 'data_received' callback""" self.vt100_input.send_bytes(data) def size_received(rows: int, columns: int) -> None: """TelnetProtocolParser 'size_received' callback""" self.size = Size(rows=rows, columns=columns) if self.vt100_output is not None and self.context: self.context.run(lambda: get_app()._on_resize()) def ttype_received(ttype: str) -> None: """TelnetProtocolParser 'ttype_received' callback""" self.vt100_output = Vt100_Output( self.stdout, get_size, term=ttype, enable_cpr=enable_cpr ) self._ready.set() self.parser = TelnetProtocolParser(data_received, size_received, ttype_received) self.context: contextvars.Context | None = None async def run_application(self) -> None: """ Run application. """ def handle_incoming_data() -> None: data = self.conn.recv(1024) if data: self.feed(data) else: # Connection closed by client. logger.info("Connection closed by client. %r %r" % self.addr) self.close() # Add reader. loop = get_running_loop() loop.add_reader(self.conn, handle_incoming_data) try: # Wait for v100_output to be properly instantiated await self._ready.wait() with create_app_session(input=self.vt100_input, output=self.vt100_output): self.context = contextvars.copy_context() await self.interact(self) finally: self.close() def feed(self, data: bytes) -> None: """ Handler for incoming data. (Called by TelnetServer.) """ self.parser.feed(data) def close(self) -> None: """ Closed by client. """ if not self._closed: self._closed = True self.vt100_input.close() get_running_loop().remove_reader(self.conn) self.conn.close() self.stdout.close() def send(self, formatted_text: AnyFormattedText) -> None: """ Send text to the client. """ if self.vt100_output is None: return formatted_text = to_formatted_text(formatted_text) print_formatted_text( self.vt100_output, formatted_text, self.style or DummyStyle() ) def send_above_prompt(self, formatted_text: AnyFormattedText) -> None: """ Send text to the client. This is asynchronous, returns a `Future`. """ formatted_text = to_formatted_text(formatted_text) return self._run_in_terminal(lambda: self.send(formatted_text)) def _run_in_terminal(self, func: Callable[[], None]) -> None: # Make sure that when an application was active for this connection, # that we print the text above the application. if self.context: self.context.run(run_in_terminal, func) # type: ignore else: raise RuntimeError("Called _run_in_terminal outside `run_application`.") def erase_screen(self) -> None: """ Erase the screen and move the cursor to the top. """ if self.vt100_output is None: return self.vt100_output.erase_screen() self.vt100_output.cursor_goto(0, 0) self.vt100_output.flush() async def _dummy_interact(connection: TelnetConnection) -> None: pass
null
172,035
from __future__ import annotations import re from typing import Callable, Dict, Iterable, Iterator, List from typing import Match as RegexMatch from typing import Optional, Pattern, Tuple from .regex_parser import ( AnyNode, Lookahead, Node, NodeSequence, Regex, Repeat, Variable, parse_regex, tokenize_regex, ) EscapeFuncDict = Dict[str, Callable[[str], str]] class _CompiledGrammar: """ Compiles a grammar. This will take the parse tree of a regular expression and compile the grammar. :param root_node: :class~`.regex_parser.Node` instance. :param escape_funcs: `dict` mapping variable names to escape callables. :param unescape_funcs: `dict` mapping variable names to unescape callables. """ def __init__( self, root_node: Node, escape_funcs: EscapeFuncDict | None = None, unescape_funcs: EscapeFuncDict | None = None, ) -> None: self.root_node = root_node self.escape_funcs = escape_funcs or {} self.unescape_funcs = unescape_funcs or {} #: Dictionary that will map the regex names to Node instances. self._group_names_to_nodes: dict[ str, str ] = {} # Maps regex group names to varnames. counter = [0] def create_group_func(node: Variable) -> str: name = "n%s" % counter[0] self._group_names_to_nodes[name] = node.varname counter[0] += 1 return name # Compile regex strings. self._re_pattern = "^%s$" % self._transform(root_node, create_group_func) self._re_prefix_patterns = list( self._transform_prefix(root_node, create_group_func) ) # Compile the regex itself. flags = re.DOTALL # Note that we don't need re.MULTILINE! (^ and $ # still represent the start and end of input text.) self._re = re.compile(self._re_pattern, flags) self._re_prefix = [re.compile(t, flags) for t in self._re_prefix_patterns] # We compile one more set of regexes, similar to `_re_prefix`, but accept any trailing # input. This will ensure that we can still highlight the input correctly, even when the # input contains some additional characters at the end that don't match the grammar.) self._re_prefix_with_trailing_input = [ re.compile( r"(?:{})(?P<{}>.*?)$".format(t.rstrip("$"), _INVALID_TRAILING_INPUT), flags, ) for t in self._re_prefix_patterns ] def escape(self, varname: str, value: str) -> str: """ Escape `value` to fit in the place of this variable into the grammar. """ f = self.escape_funcs.get(varname) return f(value) if f else value def unescape(self, varname: str, value: str) -> str: """ Unescape `value`. """ f = self.unescape_funcs.get(varname) return f(value) if f else value def _transform( cls, root_node: Node, create_group_func: Callable[[Variable], str] ) -> str: """ Turn a :class:`Node` object into a regular expression. :param root_node: The :class:`Node` instance for which we generate the grammar. :param create_group_func: A callable which takes a `Node` and returns the next free name for this node. """ def transform(node: Node) -> str: # Turn `AnyNode` into an OR. if isinstance(node, AnyNode): return "(?:%s)" % "|".join(transform(c) for c in node.children) # Concatenate a `NodeSequence` elif isinstance(node, NodeSequence): return "".join(transform(c) for c in node.children) # For Regex and Lookahead nodes, just insert them literally. elif isinstance(node, Regex): return node.regex elif isinstance(node, Lookahead): before = "(?!" if node.negative else "(=" return before + transform(node.childnode) + ")" # A `Variable` wraps the children into a named group. elif isinstance(node, Variable): return "(?P<{}>{})".format( create_group_func(node), transform(node.childnode), ) # `Repeat`. elif isinstance(node, Repeat): if node.max_repeat is None: if node.min_repeat == 0: repeat_sign = "*" elif node.min_repeat == 1: repeat_sign = "+" else: repeat_sign = "{%i,%s}" % ( node.min_repeat, ("" if node.max_repeat is None else str(node.max_repeat)), ) return "(?:{}){}{}".format( transform(node.childnode), repeat_sign, ("" if node.greedy else "?"), ) else: raise TypeError(f"Got {node!r}") return transform(root_node) def _transform_prefix( cls, root_node: Node, create_group_func: Callable[[Variable], str] ) -> Iterable[str]: """ Yield all the regular expressions matching a prefix of the grammar defined by the `Node` instance. For each `Variable`, one regex pattern will be generated, with this named group at the end. This is required because a regex engine will terminate once a match is found. For autocompletion however, we need the matches for all possible paths, so that we can provide completions for each `Variable`. - So, in the case of an `Any` (`A|B|C)', we generate a pattern for each clause. This is one for `A`, one for `B` and one for `C`. Unless some groups don't contain a `Variable`, then these can be merged together. - In the case of a `NodeSequence` (`ABC`), we generate a pattern for each prefix that ends with a variable, and one pattern for the whole sequence. So, that's one for `A`, one for `AB` and one for `ABC`. :param root_node: The :class:`Node` instance for which we generate the grammar. :param create_group_func: A callable which takes a `Node` and returns the next free name for this node. """ def contains_variable(node: Node) -> bool: if isinstance(node, Regex): return False elif isinstance(node, Variable): return True elif isinstance(node, (Lookahead, Repeat)): return contains_variable(node.childnode) elif isinstance(node, (NodeSequence, AnyNode)): return any(contains_variable(child) for child in node.children) return False def transform(node: Node) -> Iterable[str]: # Generate separate pattern for all terms that contain variables # within this OR. Terms that don't contain a variable can be merged # together in one pattern. if isinstance(node, AnyNode): # If we have a definition like: # (?P<name> .*) | (?P<city> .*) # Then we want to be able to generate completions for both the # name as well as the city. We do this by yielding two # different regular expressions, because the engine won't # follow multiple paths, if multiple are possible. children_with_variable = [] children_without_variable = [] for c in node.children: if contains_variable(c): children_with_variable.append(c) else: children_without_variable.append(c) for c in children_with_variable: yield from transform(c) # Merge options without variable together. if children_without_variable: yield "|".join( r for c in children_without_variable for r in transform(c) ) # For a sequence, generate a pattern for each prefix that ends with # a variable + one pattern of the complete sequence. # (This is because, for autocompletion, we match the text before # the cursor, and completions are given for the variable that we # match right before the cursor.) elif isinstance(node, NodeSequence): # For all components in the sequence, compute prefix patterns, # as well as full patterns. complete = [cls._transform(c, create_group_func) for c in node.children] prefixes = [list(transform(c)) for c in node.children] variable_nodes = [contains_variable(c) for c in node.children] # If any child is contains a variable, we should yield a # pattern up to that point, so that we are sure this will be # matched. for i in range(len(node.children)): if variable_nodes[i]: for c_str in prefixes[i]: yield "".join(complete[:i]) + c_str # If there are non-variable nodes, merge all the prefixes into # one pattern. If the input is: "[part1] [part2] [part3]", then # this gets compiled into: # (complete1 + (complete2 + (complete3 | partial3) | partial2) | partial1 ) # For nodes that contain a variable, we skip the "|partial" # part here, because thees are matched with the previous # patterns. if not all(variable_nodes): result = [] # Start with complete patterns. for i in range(len(node.children)): result.append("(?:") result.append(complete[i]) # Add prefix patterns. for i in range(len(node.children) - 1, -1, -1): if variable_nodes[i]: # No need to yield a prefix for this one, we did # the variable prefixes earlier. result.append(")") else: result.append("|(?:") # If this yields multiple, we should yield all combinations. assert len(prefixes[i]) == 1 result.append(prefixes[i][0]) result.append("))") yield "".join(result) elif isinstance(node, Regex): yield "(?:%s)?" % node.regex elif isinstance(node, Lookahead): if node.negative: yield "(?!%s)" % cls._transform(node.childnode, create_group_func) else: # Not sure what the correct semantics are in this case. # (Probably it's not worth implementing this.) raise Exception("Positive lookahead not yet supported.") elif isinstance(node, Variable): # (Note that we should not append a '?' here. the 'transform' # method will already recursively do that.) for c_str in transform(node.childnode): yield f"(?P<{create_group_func(node)}>{c_str})" elif isinstance(node, Repeat): # If we have a repetition of 8 times. That would mean that the # current input could have for instance 7 times a complete # match, followed by a partial match. prefix = cls._transform(node.childnode, create_group_func) if node.max_repeat == 1: yield from transform(node.childnode) else: for c_str in transform(node.childnode): if node.max_repeat: repeat_sign = "{,%i}" % (node.max_repeat - 1) else: repeat_sign = "*" yield "(?:{}){}{}{}".format( prefix, repeat_sign, ("" if node.greedy else "?"), c_str, ) else: raise TypeError("Got %r" % node) for r in transform(root_node): yield "^(?:%s)$" % r def match(self, string: str) -> Match | None: """ Match the string with the grammar. Returns a :class:`Match` instance or `None` when the input doesn't match the grammar. :param string: The input string. """ m = self._re.match(string) if m: return Match( string, [(self._re, m)], self._group_names_to_nodes, self.unescape_funcs ) return None def match_prefix(self, string: str) -> Match | None: """ Do a partial match of the string with the grammar. The returned :class:`Match` instance can contain multiple representations of the match. This will never return `None`. If it doesn't match at all, the "trailing input" part will capture all of the input. :param string: The input string. """ # First try to match using `_re_prefix`. If nothing is found, use the patterns that # also accept trailing characters. for patterns in [self._re_prefix, self._re_prefix_with_trailing_input]: matches = [(r, r.match(string)) for r in patterns] matches2 = [(r, m) for r, m in matches if m] if matches2 != []: return Match( string, matches2, self._group_names_to_nodes, self.unescape_funcs ) return None def _compile_from_parse_tree( root_node: Node, escape_funcs: EscapeFuncDict | None = None, unescape_funcs: EscapeFuncDict | None = None, ) -> _CompiledGrammar: """ Compile grammar (given as parse tree), returning a `CompiledGrammar` instance. """ return _CompiledGrammar( root_node, escape_funcs=escape_funcs, unescape_funcs=unescape_funcs ) def tokenize_regex(input: str) -> list[str]: """ Takes a string, representing a regular expression as input, and tokenizes it. :param input: string, representing a regular expression. :returns: List of tokens. """ # Regular expression for tokenizing other regular expressions. p = re.compile( r"""^( \(\?P\<[a-zA-Z0-9_-]+\> | # Start of named group. \(\?#[^)]*\) | # Comment \(\?= | # Start of lookahead assertion \(\?! | # Start of negative lookahead assertion \(\?<= | # If preceded by. \(\?< | # If not preceded by. \(?: | # Start of group. (non capturing.) \( | # Start of group. \(?[iLmsux] | # Flags. \(?P=[a-zA-Z]+\) | # Back reference to named group \) | # End of group. \{[^{}]*\} | # Repetition \*\? | \+\? | \?\?\ | # Non greedy repetition. \* | \+ | \? | # Repetition \#.*\n | # Comment \\. | # Character group. \[ ( [^\]\\] | \\.)* \] | [^(){}] | . )""", re.VERBOSE, ) tokens = [] while input: m = p.match(input) if m: token, input = input[: m.end()], input[m.end() :] if not token.isspace(): tokens.append(token) else: raise Exception("Could not tokenize input regex.") return tokens def parse_regex(regex_tokens: list[str]) -> Node: """ Takes a list of tokens from the tokenizer, and returns a parse tree. """ # We add a closing brace because that represents the final pop of the stack. tokens: list[str] = [")"] + regex_tokens[::-1] def wrap(lst: list[Node]) -> Node: """Turn list into sequence when it contains several items.""" if len(lst) == 1: return lst[0] else: return NodeSequence(lst) def _parse() -> Node: or_list: list[list[Node]] = [] result: list[Node] = [] def wrapped_result() -> Node: if or_list == []: return wrap(result) else: or_list.append(result) return AnyNode([wrap(i) for i in or_list]) while tokens: t = tokens.pop() if t.startswith("(?P<"): variable = Variable(_parse(), varname=t[4:-1]) result.append(variable) elif t in ("*", "*?"): greedy = t == "*" result[-1] = Repeat(result[-1], greedy=greedy) elif t in ("+", "+?"): greedy = t == "+" result[-1] = Repeat(result[-1], min_repeat=1, greedy=greedy) elif t in ("?", "??"): if result == []: raise Exception("Nothing to repeat." + repr(tokens)) else: greedy = t == "?" result[-1] = Repeat( result[-1], min_repeat=0, max_repeat=1, greedy=greedy ) elif t == "|": or_list.append(result) result = [] elif t in ("(", "(?:"): result.append(_parse()) elif t == "(?!": result.append(Lookahead(_parse(), negative=True)) elif t == "(?=": result.append(Lookahead(_parse(), negative=False)) elif t == ")": return wrapped_result() elif t.startswith("#"): pass elif t.startswith("{"): # TODO: implement! raise Exception(f"{t}-style repetition not yet supported") elif t.startswith("(?"): raise Exception("%r not supported" % t) elif t.isspace(): pass else: result.append(Regex(t)) raise Exception("Expecting ')' token") result = _parse() if len(tokens) != 0: raise Exception("Unmatched parentheses.") else: return result The provided code snippet includes necessary dependencies for implementing the `compile` function. Write a Python function `def compile( expression: str, escape_funcs: EscapeFuncDict | None = None, unescape_funcs: EscapeFuncDict | None = None, ) -> _CompiledGrammar` to solve the following problem: Compile grammar (given as regex string), returning a `CompiledGrammar` instance. Here is the function: def compile( expression: str, escape_funcs: EscapeFuncDict | None = None, unescape_funcs: EscapeFuncDict | None = None, ) -> _CompiledGrammar: """ Compile grammar (given as regex string), returning a `CompiledGrammar` instance. """ return _compile_from_parse_tree( parse_regex(tokenize_regex(expression)), escape_funcs=escape_funcs, unescape_funcs=unescape_funcs, )
Compile grammar (given as regex string), returning a `CompiledGrammar` instance.
172,036
from __future__ import annotations from asyncio.events import AbstractEventLoop from typing import TYPE_CHECKING, Any, Optional, TextIO from prompt_toolkit.application import Application from prompt_toolkit.application.current import get_app_or_none, get_app_session from prompt_toolkit.application.run_in_terminal import run_in_terminal from prompt_toolkit.formatted_text import ( FormattedText, StyleAndTextTuples, to_formatted_text, ) from prompt_toolkit.input import DummyInput from prompt_toolkit.layout import Layout from prompt_toolkit.output import ColorDepth, Output from prompt_toolkit.output.defaults import create_output from prompt_toolkit.renderer import ( print_formatted_text as renderer_print_formatted_text, ) from prompt_toolkit.styles import ( BaseStyle, StyleTransformation, default_pygments_style, default_ui_style, merge_styles, ) def _create_merged_style( style: BaseStyle | None, include_default_pygments_style: bool ) -> BaseStyle: """ Merge user defined style with built-in style. """ styles = [default_ui_style()] if include_default_pygments_style: styles.append(default_pygments_style()) if style: styles.append(style) return merge_styles(styles) Any = object() class TextIO(IO[str]): # TODO use abstractproperty def buffer(self) -> BinaryIO: ... def encoding(self) -> str: ... def errors(self) -> Optional[str]: ... def line_buffering(self) -> int: ... # int on PyPy, bool on CPython def newlines(self) -> Any: ... # None, str or tuple def __enter__(self) -> TextIO: ... def get_app_session() -> AppSession: return _current_app_session.get() def get_app_or_none() -> Application[Any] | None: """ Get the current active (running) Application, or return `None` if no application is running. """ session = _current_app_session.get() return session.app def run_in_terminal( func: Callable[[], _T], render_cli_done: bool = False, in_executor: bool = False ) -> Awaitable[_T]: """ Run function on the terminal above the current application or prompt. What this does is first hiding the prompt, then running this callable (which can safely output to the terminal), and then again rendering the prompt which causes the output of this function to scroll above the prompt. ``func`` is supposed to be a synchronous function. If you need an asynchronous version of this function, use the ``in_terminal`` context manager directly. :param func: The callable to execute. :param render_cli_done: When True, render the interface in the 'Done' state first, then execute the function. If False, erase the interface first. :param in_executor: When True, run in executor. (Use this for long blocking functions, when you don't want to block the event loop.) :returns: A `Future`. """ async def run() -> _T: async with in_terminal(render_cli_done=render_cli_done): if in_executor: return await run_in_executor_with_context(func) else: return func() return ensure_future(run()) def create_output( stdout: TextIO | None = None, always_prefer_tty: bool = False ) -> Output: """ Return an :class:`~prompt_toolkit.output.Output` instance for the command line. :param stdout: The stdout object :param always_prefer_tty: When set, look for `sys.stderr` if `sys.stdout` is not a TTY. Useful if `sys.stdout` is redirected to a file, but we still want user input and output on the terminal. By default, this is `False`. If `sys.stdout` is not a terminal (maybe it's redirected to a file), then a `PlainTextOutput` will be returned. That way, tools like `print_formatted_text` will write plain text into that file. """ # Consider TERM, PROMPT_TOOLKIT_BELL, and PROMPT_TOOLKIT_COLOR_DEPTH # environment variables. Notice that PROMPT_TOOLKIT_COLOR_DEPTH value is # the default that's used if the Application doesn't override it. term_from_env = get_term_environment_variable() bell_from_env = get_bell_environment_variable() color_depth_from_env = ColorDepth.from_env() if stdout is None: # By default, render to stdout. If the output is piped somewhere else, # render to stderr. stdout = sys.stdout if always_prefer_tty: for io in [sys.stdout, sys.stderr]: if io is not None and io.isatty(): # (This is `None` when using `pythonw.exe` on Windows.) stdout = io break # If the output is still `None`, use a DummyOutput. # This happens for instance on Windows, when running the application under # `pythonw.exe`. In that case, there won't be a terminal Window, and # stdin/stdout/stderr are `None`. if stdout is None: return DummyOutput() # If the patch_stdout context manager has been used, then sys.stdout is # replaced by this proxy. For prompt_toolkit applications, we want to use # the real stdout. from prompt_toolkit.patch_stdout import StdoutProxy while isinstance(stdout, StdoutProxy): stdout = stdout.original_stdout if sys.platform == "win32": from .conemu import ConEmuOutput from .win32 import Win32Output from .windows10 import Windows10_Output, is_win_vt100_enabled if is_win_vt100_enabled(): return cast( Output, Windows10_Output(stdout, default_color_depth=color_depth_from_env), ) if is_conemu_ansi(): return cast( Output, ConEmuOutput(stdout, default_color_depth=color_depth_from_env) ) else: return Win32Output(stdout, default_color_depth=color_depth_from_env) else: from .vt100 import Vt100_Output # Stdout is not a TTY? Render as plain text. # This is mostly useful if stdout is redirected to a file, and # `print_formatted_text` is used. if not stdout.isatty(): return PlainTextOutput(stdout) return Vt100_Output.from_pty( stdout, term=term_from_env, default_color_depth=color_depth_from_env, enable_bell=bell_from_env, ) The provided code snippet includes necessary dependencies for implementing the `print_formatted_text` function. Write a Python function `def print_formatted_text( *values: Any, sep: str = " ", end: str = "\n", file: TextIO | None = None, flush: bool = False, style: BaseStyle | None = None, output: Output | None = None, color_depth: ColorDepth | None = None, style_transformation: StyleTransformation | None = None, include_default_pygments_style: bool = True, ) -> None` to solve the following problem: :: print_formatted_text(*values, sep=' ', end='\\n', file=None, flush=False, style=None, output=None) Print text to stdout. This is supposed to be compatible with Python's print function, but supports printing of formatted text. You can pass a :class:`~prompt_toolkit.formatted_text.FormattedText`, :class:`~prompt_toolkit.formatted_text.HTML` or :class:`~prompt_toolkit.formatted_text.ANSI` object to print formatted text. * Print HTML as follows:: print_formatted_text(HTML('<i>Some italic text</i> <ansired>This is red!</ansired>')) style = Style.from_dict({ 'hello': '#ff0066', 'world': '#884444 italic', }) print_formatted_text(HTML('<hello>Hello</hello> <world>world</world>!'), style=style) * Print a list of (style_str, text) tuples in the given style to the output. E.g.:: style = Style.from_dict({ 'hello': '#ff0066', 'world': '#884444 italic', }) fragments = FormattedText([ ('class:hello', 'Hello'), ('class:world', 'World'), ]) print_formatted_text(fragments, style=style) If you want to print a list of Pygments tokens, wrap it in :class:`~prompt_toolkit.formatted_text.PygmentsTokens` to do the conversion. If a prompt_toolkit `Application` is currently running, this will always print above the application or prompt (similar to `patch_stdout`). So, `print_formatted_text` will erase the current application, print the text, and render the application again. :param values: Any kind of printable object, or formatted string. :param sep: String inserted between values, default a space. :param end: String appended after the last value, default a newline. :param style: :class:`.Style` instance for the color scheme. :param include_default_pygments_style: `bool`. Include the default Pygments style when set to `True` (the default). Here is the function: def print_formatted_text( *values: Any, sep: str = " ", end: str = "\n", file: TextIO | None = None, flush: bool = False, style: BaseStyle | None = None, output: Output | None = None, color_depth: ColorDepth | None = None, style_transformation: StyleTransformation | None = None, include_default_pygments_style: bool = True, ) -> None: """ :: print_formatted_text(*values, sep=' ', end='\\n', file=None, flush=False, style=None, output=None) Print text to stdout. This is supposed to be compatible with Python's print function, but supports printing of formatted text. You can pass a :class:`~prompt_toolkit.formatted_text.FormattedText`, :class:`~prompt_toolkit.formatted_text.HTML` or :class:`~prompt_toolkit.formatted_text.ANSI` object to print formatted text. * Print HTML as follows:: print_formatted_text(HTML('<i>Some italic text</i> <ansired>This is red!</ansired>')) style = Style.from_dict({ 'hello': '#ff0066', 'world': '#884444 italic', }) print_formatted_text(HTML('<hello>Hello</hello> <world>world</world>!'), style=style) * Print a list of (style_str, text) tuples in the given style to the output. E.g.:: style = Style.from_dict({ 'hello': '#ff0066', 'world': '#884444 italic', }) fragments = FormattedText([ ('class:hello', 'Hello'), ('class:world', 'World'), ]) print_formatted_text(fragments, style=style) If you want to print a list of Pygments tokens, wrap it in :class:`~prompt_toolkit.formatted_text.PygmentsTokens` to do the conversion. If a prompt_toolkit `Application` is currently running, this will always print above the application or prompt (similar to `patch_stdout`). So, `print_formatted_text` will erase the current application, print the text, and render the application again. :param values: Any kind of printable object, or formatted string. :param sep: String inserted between values, default a space. :param end: String appended after the last value, default a newline. :param style: :class:`.Style` instance for the color scheme. :param include_default_pygments_style: `bool`. Include the default Pygments style when set to `True` (the default). """ assert not (output and file) # Create Output object. if output is None: if file: output = create_output(stdout=file) else: output = get_app_session().output assert isinstance(output, Output) # Get color depth. color_depth = color_depth or output.get_default_color_depth() # Merges values. def to_text(val: Any) -> StyleAndTextTuples: # Normal lists which are not instances of `FormattedText` are # considered plain text. if isinstance(val, list) and not isinstance(val, FormattedText): return to_formatted_text(f"{val}") return to_formatted_text(val, auto_convert=True) fragments = [] for i, value in enumerate(values): fragments.extend(to_text(value)) if sep and i != len(values) - 1: fragments.extend(to_text(sep)) fragments.extend(to_text(end)) # Print output. def render() -> None: assert isinstance(output, Output) renderer_print_formatted_text( output, fragments, _create_merged_style( style, include_default_pygments_style=include_default_pygments_style ), color_depth=color_depth, style_transformation=style_transformation, ) # Flush the output stream. if flush: output.flush() # If an application is running, print above the app. This does not require # `patch_stdout`. loop: AbstractEventLoop | None = None app = get_app_or_none() if app is not None: loop = app.loop if loop is not None: loop.call_soon_threadsafe(lambda: run_in_terminal(render)) else: render()
:: print_formatted_text(*values, sep=' ', end='\\n', file=None, flush=False, style=None, output=None) Print text to stdout. This is supposed to be compatible with Python's print function, but supports printing of formatted text. You can pass a :class:`~prompt_toolkit.formatted_text.FormattedText`, :class:`~prompt_toolkit.formatted_text.HTML` or :class:`~prompt_toolkit.formatted_text.ANSI` object to print formatted text. * Print HTML as follows:: print_formatted_text(HTML('<i>Some italic text</i> <ansired>This is red!</ansired>')) style = Style.from_dict({ 'hello': '#ff0066', 'world': '#884444 italic', }) print_formatted_text(HTML('<hello>Hello</hello> <world>world</world>!'), style=style) * Print a list of (style_str, text) tuples in the given style to the output. E.g.:: style = Style.from_dict({ 'hello': '#ff0066', 'world': '#884444 italic', }) fragments = FormattedText([ ('class:hello', 'Hello'), ('class:world', 'World'), ]) print_formatted_text(fragments, style=style) If you want to print a list of Pygments tokens, wrap it in :class:`~prompt_toolkit.formatted_text.PygmentsTokens` to do the conversion. If a prompt_toolkit `Application` is currently running, this will always print above the application or prompt (similar to `patch_stdout`). So, `print_formatted_text` will erase the current application, print the text, and render the application again. :param values: Any kind of printable object, or formatted string. :param sep: String inserted between values, default a space. :param end: String appended after the last value, default a newline. :param style: :class:`.Style` instance for the color scheme. :param include_default_pygments_style: `bool`. Include the default Pygments style when set to `True` (the default).
172,037
from __future__ import annotations from asyncio.events import AbstractEventLoop from typing import TYPE_CHECKING, Any, Optional, TextIO from prompt_toolkit.application import Application from prompt_toolkit.application.current import get_app_or_none, get_app_session from prompt_toolkit.application.run_in_terminal import run_in_terminal from prompt_toolkit.formatted_text import ( FormattedText, StyleAndTextTuples, to_formatted_text, ) from prompt_toolkit.input import DummyInput from prompt_toolkit.layout import Layout from prompt_toolkit.output import ColorDepth, Output from prompt_toolkit.output.defaults import create_output from prompt_toolkit.renderer import ( print_formatted_text as renderer_print_formatted_text, ) from prompt_toolkit.styles import ( BaseStyle, StyleTransformation, default_pygments_style, default_ui_style, merge_styles, ) def _create_merged_style( style: BaseStyle | None, include_default_pygments_style: bool ) -> BaseStyle: """ Merge user defined style with built-in style. """ styles = [default_ui_style()] if include_default_pygments_style: styles.append(default_pygments_style()) if style: styles.append(style) return merge_styles(styles) class TextIO(IO[str]): # TODO use abstractproperty def buffer(self) -> BinaryIO: ... def encoding(self) -> str: ... def errors(self) -> Optional[str]: ... def line_buffering(self) -> int: ... # int on PyPy, bool on CPython def newlines(self) -> Any: ... # None, str or tuple def __enter__(self) -> TextIO: ... def get_app_session() -> AppSession: return _current_app_session.get() def create_output( stdout: TextIO | None = None, always_prefer_tty: bool = False ) -> Output: """ Return an :class:`~prompt_toolkit.output.Output` instance for the command line. :param stdout: The stdout object :param always_prefer_tty: When set, look for `sys.stderr` if `sys.stdout` is not a TTY. Useful if `sys.stdout` is redirected to a file, but we still want user input and output on the terminal. By default, this is `False`. If `sys.stdout` is not a terminal (maybe it's redirected to a file), then a `PlainTextOutput` will be returned. That way, tools like `print_formatted_text` will write plain text into that file. """ # Consider TERM, PROMPT_TOOLKIT_BELL, and PROMPT_TOOLKIT_COLOR_DEPTH # environment variables. Notice that PROMPT_TOOLKIT_COLOR_DEPTH value is # the default that's used if the Application doesn't override it. term_from_env = get_term_environment_variable() bell_from_env = get_bell_environment_variable() color_depth_from_env = ColorDepth.from_env() if stdout is None: # By default, render to stdout. If the output is piped somewhere else, # render to stderr. stdout = sys.stdout if always_prefer_tty: for io in [sys.stdout, sys.stderr]: if io is not None and io.isatty(): # (This is `None` when using `pythonw.exe` on Windows.) stdout = io break # If the output is still `None`, use a DummyOutput. # This happens for instance on Windows, when running the application under # `pythonw.exe`. In that case, there won't be a terminal Window, and # stdin/stdout/stderr are `None`. if stdout is None: return DummyOutput() # If the patch_stdout context manager has been used, then sys.stdout is # replaced by this proxy. For prompt_toolkit applications, we want to use # the real stdout. from prompt_toolkit.patch_stdout import StdoutProxy while isinstance(stdout, StdoutProxy): stdout = stdout.original_stdout if sys.platform == "win32": from .conemu import ConEmuOutput from .win32 import Win32Output from .windows10 import Windows10_Output, is_win_vt100_enabled if is_win_vt100_enabled(): return cast( Output, Windows10_Output(stdout, default_color_depth=color_depth_from_env), ) if is_conemu_ansi(): return cast( Output, ConEmuOutput(stdout, default_color_depth=color_depth_from_env) ) else: return Win32Output(stdout, default_color_depth=color_depth_from_env) else: from .vt100 import Vt100_Output # Stdout is not a TTY? Render as plain text. # This is mostly useful if stdout is redirected to a file, and # `print_formatted_text` is used. if not stdout.isatty(): return PlainTextOutput(stdout) return Vt100_Output.from_pty( stdout, term=term_from_env, default_color_depth=color_depth_from_env, enable_bell=bell_from_env, ) AnyContainer = Union[Container, "MagicContainer"] The provided code snippet includes necessary dependencies for implementing the `print_container` function. Write a Python function `def print_container( container: AnyContainer, file: TextIO | None = None, style: BaseStyle | None = None, include_default_pygments_style: bool = True, ) -> None` to solve the following problem: Print any layout to the output in a non-interactive way. Example usage:: from prompt_toolkit.widgets import Frame, TextArea print_container( Frame(TextArea(text='Hello world!'))) Here is the function: def print_container( container: AnyContainer, file: TextIO | None = None, style: BaseStyle | None = None, include_default_pygments_style: bool = True, ) -> None: """ Print any layout to the output in a non-interactive way. Example usage:: from prompt_toolkit.widgets import Frame, TextArea print_container( Frame(TextArea(text='Hello world!'))) """ if file: output = create_output(stdout=file) else: output = get_app_session().output app: Application[None] = Application( layout=Layout(container=container), output=output, # `DummyInput` will cause the application to terminate immediately. input=DummyInput(), style=_create_merged_style( style, include_default_pygments_style=include_default_pygments_style ), ) try: app.run(in_thread=True) except EOFError: pass
Print any layout to the output in a non-interactive way. Example usage:: from prompt_toolkit.widgets import Frame, TextArea print_container( Frame(TextArea(text='Hello world!')))
172,038
from __future__ import annotations from asyncio.events import AbstractEventLoop from typing import TYPE_CHECKING, Any, Optional, TextIO from prompt_toolkit.application import Application from prompt_toolkit.application.current import get_app_or_none, get_app_session from prompt_toolkit.application.run_in_terminal import run_in_terminal from prompt_toolkit.formatted_text import ( FormattedText, StyleAndTextTuples, to_formatted_text, ) from prompt_toolkit.input import DummyInput from prompt_toolkit.layout import Layout from prompt_toolkit.output import ColorDepth, Output from prompt_toolkit.output.defaults import create_output from prompt_toolkit.renderer import ( print_formatted_text as renderer_print_formatted_text, ) from prompt_toolkit.styles import ( BaseStyle, StyleTransformation, default_pygments_style, default_ui_style, merge_styles, ) def get_app_session() -> AppSession: return _current_app_session.get() The provided code snippet includes necessary dependencies for implementing the `clear` function. Write a Python function `def clear() -> None` to solve the following problem: Clear the screen. Here is the function: def clear() -> None: """ Clear the screen. """ output = get_app_session().output output.erase_screen() output.cursor_goto(0, 0) output.flush()
Clear the screen.
172,039
from __future__ import annotations from asyncio.events import AbstractEventLoop from typing import TYPE_CHECKING, Any, Optional, TextIO from prompt_toolkit.application import Application from prompt_toolkit.application.current import get_app_or_none, get_app_session from prompt_toolkit.application.run_in_terminal import run_in_terminal from prompt_toolkit.formatted_text import ( FormattedText, StyleAndTextTuples, to_formatted_text, ) from prompt_toolkit.input import DummyInput from prompt_toolkit.layout import Layout from prompt_toolkit.output import ColorDepth, Output from prompt_toolkit.output.defaults import create_output from prompt_toolkit.renderer import ( print_formatted_text as renderer_print_formatted_text, ) from prompt_toolkit.styles import ( BaseStyle, StyleTransformation, default_pygments_style, default_ui_style, merge_styles, ) def set_title(text: str) -> None: """ Set the terminal title. """ output = get_app_session().output output.set_title(text) The provided code snippet includes necessary dependencies for implementing the `clear_title` function. Write a Python function `def clear_title() -> None` to solve the following problem: Erase the current title. Here is the function: def clear_title() -> None: """ Erase the current title. """ set_title("")
Erase the current title.
172,040
from __future__ import annotations import datetime import time from abc import ABCMeta, abstractmethod from typing import TYPE_CHECKING, List, Tuple from prompt_toolkit.formatted_text import ( HTML, AnyFormattedText, StyleAndTextTuples, to_formatted_text, ) from prompt_toolkit.formatted_text.utils import fragment_list_width from prompt_toolkit.layout.dimension import AnyDimension, D from prompt_toolkit.layout.utils import explode_text_fragments from prompt_toolkit.utils import get_cwidth The provided code snippet includes necessary dependencies for implementing the `_format_timedelta` function. Write a Python function `def _format_timedelta(timedelta: datetime.timedelta) -> str` to solve the following problem: Return hh:mm:ss, or mm:ss if the amount of hours is zero. Here is the function: def _format_timedelta(timedelta: datetime.timedelta) -> str: """ Return hh:mm:ss, or mm:ss if the amount of hours is zero. """ result = f"{timedelta}".split(".")[0] if result.startswith("0:"): result = result[2:] return result
Return hh:mm:ss, or mm:ss if the amount of hours is zero.
172,041
from __future__ import annotations import datetime import time from abc import ABCMeta, abstractmethod from typing import TYPE_CHECKING, List, Tuple from prompt_toolkit.formatted_text import ( HTML, AnyFormattedText, StyleAndTextTuples, to_formatted_text, ) from prompt_toolkit.formatted_text.utils import fragment_list_width from prompt_toolkit.layout.dimension import AnyDimension, D from prompt_toolkit.layout.utils import explode_text_fragments from prompt_toolkit.utils import get_cwidth The provided code snippet includes necessary dependencies for implementing the `_hue_to_rgb` function. Write a Python function `def _hue_to_rgb(hue: float) -> tuple[int, int, int]` to solve the following problem: Take hue between 0 and 1, return (r, g, b). Here is the function: def _hue_to_rgb(hue: float) -> tuple[int, int, int]: """ Take hue between 0 and 1, return (r, g, b). """ i = int(hue * 6.0) f = (hue * 6.0) - i q = int(255 * (1.0 - f)) t = int(255 * (1.0 - (1.0 - f))) i %= 6 return [ (255, t, 0), (q, 255, 0), (0, 255, t), (0, q, 255), (t, 0, 255), (255, 0, q), ][i]
Take hue between 0 and 1, return (r, g, b).
172,042
from __future__ import annotations import datetime import time from abc import ABCMeta, abstractmethod from typing import TYPE_CHECKING, List, Tuple from prompt_toolkit.formatted_text import ( HTML, AnyFormattedText, StyleAndTextTuples, to_formatted_text, ) from prompt_toolkit.formatted_text.utils import fragment_list_width from prompt_toolkit.layout.dimension import AnyDimension, D from prompt_toolkit.layout.utils import explode_text_fragments from prompt_toolkit.utils import get_cwidth class Formatter(metaclass=ABCMeta): """ Base class for any formatter. """ def format( self, progress_bar: ProgressBar, progress: ProgressBarCounter[object], width: int, ) -> AnyFormattedText: pass def get_width(self, progress_bar: ProgressBar) -> AnyDimension: return D() class Text(Formatter): """ Display plain text. """ def __init__(self, text: AnyFormattedText, style: str = "") -> None: self.text = to_formatted_text(text, style=style) def format( self, progress_bar: ProgressBar, progress: ProgressBarCounter[object], width: int, ) -> AnyFormattedText: return self.text def get_width(self, progress_bar: ProgressBar) -> AnyDimension: return fragment_list_width(self.text) class Label(Formatter): """ Display the name of the current task. :param width: If a `width` is given, use this width. Scroll the text if it doesn't fit in this width. :param suffix: String suffix to be added after the task name, e.g. ': '. If no task name was given, no suffix will be added. """ def __init__(self, width: AnyDimension = None, suffix: str = "") -> None: self.width = width self.suffix = suffix def _add_suffix(self, label: AnyFormattedText) -> StyleAndTextTuples: label = to_formatted_text(label, style="class:label") return label + [("", self.suffix)] def format( self, progress_bar: ProgressBar, progress: ProgressBarCounter[object], width: int, ) -> AnyFormattedText: label = self._add_suffix(progress.label) cwidth = fragment_list_width(label) if cwidth > width: # It doesn't fit -> scroll task name. label = explode_text_fragments(label) max_scroll = cwidth - width current_scroll = int(time.time() * 3 % max_scroll) label = label[current_scroll:] return label def get_width(self, progress_bar: ProgressBar) -> AnyDimension: if self.width: return self.width all_labels = [self._add_suffix(c.label) for c in progress_bar.counters] if all_labels: max_widths = max(fragment_list_width(l) for l in all_labels) return D(preferred=max_widths, max=max_widths) else: return D() class Percentage(Formatter): """ Display the progress as a percentage. """ template = "<percentage>{percentage:>5}%</percentage>" def format( self, progress_bar: ProgressBar, progress: ProgressBarCounter[object], width: int, ) -> AnyFormattedText: return HTML(self.template).format(percentage=round(progress.percentage, 1)) def get_width(self, progress_bar: ProgressBar) -> AnyDimension: return D.exact(6) class Bar(Formatter): """ Display the progress bar itself. """ template = "<bar>{start}<bar-a>{bar_a}</bar-a><bar-b>{bar_b}</bar-b><bar-c>{bar_c}</bar-c>{end}</bar>" def __init__( self, start: str = "[", end: str = "]", sym_a: str = "=", sym_b: str = ">", sym_c: str = " ", unknown: str = "#", ) -> None: assert len(sym_a) == 1 and get_cwidth(sym_a) == 1 assert len(sym_c) == 1 and get_cwidth(sym_c) == 1 self.start = start self.end = end self.sym_a = sym_a self.sym_b = sym_b self.sym_c = sym_c self.unknown = unknown def format( self, progress_bar: ProgressBar, progress: ProgressBarCounter[object], width: int, ) -> AnyFormattedText: if progress.done or progress.total or progress.stopped: sym_a, sym_b, sym_c = self.sym_a, self.sym_b, self.sym_c # Compute pb_a based on done, total, or stopped states. if progress.done: # 100% completed irrelevant of how much was actually marked as completed. percent = 1.0 else: # Show percentage completed. percent = progress.percentage / 100 else: # Total is unknown and bar is still running. sym_a, sym_b, sym_c = self.sym_c, self.unknown, self.sym_c # Compute percent based on the time. percent = time.time() * 20 % 100 / 100 # Subtract left, sym_b, and right. width -= get_cwidth(self.start + sym_b + self.end) # Scale percent by width pb_a = int(percent * width) bar_a = sym_a * pb_a bar_b = sym_b bar_c = sym_c * (width - pb_a) return HTML(self.template).format( start=self.start, end=self.end, bar_a=bar_a, bar_b=bar_b, bar_c=bar_c ) def get_width(self, progress_bar: ProgressBar) -> AnyDimension: return D(min=9) class Progress(Formatter): """ Display the progress as text. E.g. "8/20" """ template = "<current>{current:>3}</current>/<total>{total:>3}</total>" def format( self, progress_bar: ProgressBar, progress: ProgressBarCounter[object], width: int, ) -> AnyFormattedText: return HTML(self.template).format( current=progress.items_completed, total=progress.total or "?" ) def get_width(self, progress_bar: ProgressBar) -> AnyDimension: all_lengths = [ len("{:>3}".format(c.total or "?")) for c in progress_bar.counters ] all_lengths.append(1) return D.exact(max(all_lengths) * 2 + 1) class TimeLeft(Formatter): """ Display the time left. """ template = "<time-left>{time_left}</time-left>" unknown = "?:??:??" def format( self, progress_bar: ProgressBar, progress: ProgressBarCounter[object], width: int, ) -> AnyFormattedText: time_left = progress.time_left if time_left is not None: formatted_time_left = _format_timedelta(time_left) else: formatted_time_left = self.unknown return HTML(self.template).format(time_left=formatted_time_left.rjust(width)) def get_width(self, progress_bar: ProgressBar) -> AnyDimension: all_values = [ len(_format_timedelta(c.time_left)) if c.time_left is not None else 7 for c in progress_bar.counters ] if all_values: return max(all_values) return 0 The provided code snippet includes necessary dependencies for implementing the `create_default_formatters` function. Write a Python function `def create_default_formatters() -> list[Formatter]` to solve the following problem: Return the list of default formatters. Here is the function: def create_default_formatters() -> list[Formatter]: """ Return the list of default formatters. """ return [ Label(), Text(" "), Percentage(), Text(" "), Bar(), Text(" "), Progress(), Text(" "), Text("eta [", style="class:time-left"), TimeLeft(), Text("]", style="class:time-left"), Text(" "), ]
Return the list of default formatters.
172,043
from __future__ import annotations import contextvars import datetime import functools import os import signal import threading import traceback from typing import ( Callable, Generic, Iterable, Iterator, List, Optional, Sequence, Sized, TextIO, TypeVar, cast, ) from prompt_toolkit.application import Application from prompt_toolkit.application.current import get_app_session from prompt_toolkit.filters import Condition, is_done, renderer_height_is_known from prompt_toolkit.formatted_text import ( AnyFormattedText, StyleAndTextTuples, to_formatted_text, ) from prompt_toolkit.input import Input from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.key_binding.key_processor import KeyPressEvent from prompt_toolkit.layout import ( ConditionalContainer, FormattedTextControl, HSplit, Layout, VSplit, Window, ) from prompt_toolkit.layout.controls import UIContent, UIControl from prompt_toolkit.layout.dimension import AnyDimension, D from prompt_toolkit.output import ColorDepth, Output from prompt_toolkit.styles import BaseStyle from prompt_toolkit.utils import in_main_thread from .formatters import Formatter, create_default_formatters E = KeyPressEvent class Callable(BaseTypingInstance): def py__call__(self, arguments): """ def x() -> Callable[[Callable[..., _T]], _T]: ... """ # The 0th index are the arguments. try: param_values = self._generics_manager[0] result_values = self._generics_manager[1] except IndexError: debug.warning('Callable[...] defined without two arguments') return NO_VALUES else: from jedi.inference.gradual.annotation import infer_return_for_callable return infer_return_for_callable(arguments, param_values, result_values) def py__get__(self, instance, class_value): return ValueSet([self]) The provided code snippet includes necessary dependencies for implementing the `create_key_bindings` function. Write a Python function `def create_key_bindings(cancel_callback: Callable[[], None] | None) -> KeyBindings` to solve the following problem: Key bindings handled by the progress bar. (The main thread is not supposed to handle any key bindings.) Here is the function: def create_key_bindings(cancel_callback: Callable[[], None] | None) -> KeyBindings: """ Key bindings handled by the progress bar. (The main thread is not supposed to handle any key bindings.) """ kb = KeyBindings() @kb.add("c-l") def _clear(event: E) -> None: event.app.renderer.clear() if cancel_callback is not None: @kb.add("c-c") def _interrupt(event: E) -> None: "Kill the 'body' of the progress bar, but only if we run from the main thread." assert cancel_callback is not None cancel_callback() return kb
Key bindings handled by the progress bar. (The main thread is not supposed to handle any key bindings.)
172,044
from __future__ import annotations import functools from asyncio import get_running_loop from typing import Any, Callable, List, Optional, Sequence, Tuple, TypeVar from prompt_toolkit.application import Application from prompt_toolkit.application.current import get_app from prompt_toolkit.buffer import Buffer from prompt_toolkit.completion import Completer from prompt_toolkit.eventloop import run_in_executor_with_context from prompt_toolkit.filters import FilterOrBool from prompt_toolkit.formatted_text import AnyFormattedText from prompt_toolkit.key_binding.bindings.focus import focus_next, focus_previous from prompt_toolkit.key_binding.defaults import load_key_bindings from prompt_toolkit.key_binding.key_bindings import KeyBindings, merge_key_bindings from prompt_toolkit.layout import Layout from prompt_toolkit.layout.containers import AnyContainer, HSplit from prompt_toolkit.layout.dimension import Dimension as D from prompt_toolkit.styles import BaseStyle from prompt_toolkit.validation import Validator from prompt_toolkit.widgets import ( Box, Button, CheckboxList, Dialog, Label, ProgressBar, RadioList, TextArea, ValidationToolbar, ) def _create_app(dialog: AnyContainer, style: BaseStyle | None) -> Application[Any]: # Key bindings. bindings = KeyBindings() bindings.add("tab")(focus_next) bindings.add("s-tab")(focus_previous) return Application( layout=Layout(dialog), key_bindings=merge_key_bindings([load_key_bindings(), bindings]), mouse_support=True, style=style, full_screen=True, ) def get_app() -> Application[Any]: """ Get the current active (running) Application. An :class:`.Application` is active during the :meth:`.Application.run_async` call. We assume that there can only be one :class:`.Application` active at the same time. There is only one terminal window, with only one stdin and stdout. This makes the code significantly easier than passing around the :class:`.Application` everywhere. If no :class:`.Application` is running, then return by default a :class:`.DummyApplication`. For practical reasons, we prefer to not raise an exception. This way, we don't have to check all over the place whether an actual `Application` was returned. (For applications like pymux where we can have more than one `Application`, we'll use a work-around to handle that.) """ session = _current_app_session.get() if session.app is not None: return session.app from .dummy import DummyApplication return DummyApplication() The provided code snippet includes necessary dependencies for implementing the `yes_no_dialog` function. Write a Python function `def yes_no_dialog( title: AnyFormattedText = "", text: AnyFormattedText = "", yes_text: str = "Yes", no_text: str = "No", style: BaseStyle | None = None, ) -> Application[bool]` to solve the following problem: Display a Yes/No dialog. Return a boolean. Here is the function: def yes_no_dialog( title: AnyFormattedText = "", text: AnyFormattedText = "", yes_text: str = "Yes", no_text: str = "No", style: BaseStyle | None = None, ) -> Application[bool]: """ Display a Yes/No dialog. Return a boolean. """ def yes_handler() -> None: get_app().exit(result=True) def no_handler() -> None: get_app().exit(result=False) dialog = Dialog( title=title, body=Label(text=text, dont_extend_height=True), buttons=[ Button(text=yes_text, handler=yes_handler), Button(text=no_text, handler=no_handler), ], with_background=True, ) return _create_app(dialog, style)
Display a Yes/No dialog. Return a boolean.
172,045
from __future__ import annotations import functools from asyncio import get_running_loop from typing import Any, Callable, List, Optional, Sequence, Tuple, TypeVar from prompt_toolkit.application import Application from prompt_toolkit.application.current import get_app from prompt_toolkit.buffer import Buffer from prompt_toolkit.completion import Completer from prompt_toolkit.eventloop import run_in_executor_with_context from prompt_toolkit.filters import FilterOrBool from prompt_toolkit.formatted_text import AnyFormattedText from prompt_toolkit.key_binding.bindings.focus import focus_next, focus_previous from prompt_toolkit.key_binding.defaults import load_key_bindings from prompt_toolkit.key_binding.key_bindings import KeyBindings, merge_key_bindings from prompt_toolkit.layout import Layout from prompt_toolkit.layout.containers import AnyContainer, HSplit from prompt_toolkit.layout.dimension import Dimension as D from prompt_toolkit.styles import BaseStyle from prompt_toolkit.validation import Validator from prompt_toolkit.widgets import ( Box, Button, CheckboxList, Dialog, Label, ProgressBar, RadioList, TextArea, ValidationToolbar, ) _T = TypeVar("_T") def _create_app(dialog: AnyContainer, style: BaseStyle | None) -> Application[Any]: # Key bindings. bindings = KeyBindings() bindings.add("tab")(focus_next) bindings.add("s-tab")(focus_previous) return Application( layout=Layout(dialog), key_bindings=merge_key_bindings([load_key_bindings(), bindings]), mouse_support=True, style=style, full_screen=True, ) def get_app() -> Application[Any]: """ Get the current active (running) Application. An :class:`.Application` is active during the :meth:`.Application.run_async` call. We assume that there can only be one :class:`.Application` active at the same time. There is only one terminal window, with only one stdin and stdout. This makes the code significantly easier than passing around the :class:`.Application` everywhere. If no :class:`.Application` is running, then return by default a :class:`.DummyApplication`. For practical reasons, we prefer to not raise an exception. This way, we don't have to check all over the place whether an actual `Application` was returned. (For applications like pymux where we can have more than one `Application`, we'll use a work-around to handle that.) """ session = _current_app_session.get() if session.app is not None: return session.app from .dummy import DummyApplication return DummyApplication() The provided code snippet includes necessary dependencies for implementing the `button_dialog` function. Write a Python function `def button_dialog( title: AnyFormattedText = "", text: AnyFormattedText = "", buttons: list[tuple[str, _T]] = [], style: BaseStyle | None = None, ) -> Application[_T]` to solve the following problem: Display a dialog with button choices (given as a list of tuples). Return the value associated with button. Here is the function: def button_dialog( title: AnyFormattedText = "", text: AnyFormattedText = "", buttons: list[tuple[str, _T]] = [], style: BaseStyle | None = None, ) -> Application[_T]: """ Display a dialog with button choices (given as a list of tuples). Return the value associated with button. """ def button_handler(v: _T) -> None: get_app().exit(result=v) dialog = Dialog( title=title, body=Label(text=text, dont_extend_height=True), buttons=[ Button(text=t, handler=functools.partial(button_handler, v)) for t, v in buttons ], with_background=True, ) return _create_app(dialog, style)
Display a dialog with button choices (given as a list of tuples). Return the value associated with button.
172,046
from __future__ import annotations import functools from asyncio import get_running_loop from typing import Any, Callable, List, Optional, Sequence, Tuple, TypeVar from prompt_toolkit.application import Application from prompt_toolkit.application.current import get_app from prompt_toolkit.buffer import Buffer from prompt_toolkit.completion import Completer from prompt_toolkit.eventloop import run_in_executor_with_context from prompt_toolkit.filters import FilterOrBool from prompt_toolkit.formatted_text import AnyFormattedText from prompt_toolkit.key_binding.bindings.focus import focus_next, focus_previous from prompt_toolkit.key_binding.defaults import load_key_bindings from prompt_toolkit.key_binding.key_bindings import KeyBindings, merge_key_bindings from prompt_toolkit.layout import Layout from prompt_toolkit.layout.containers import AnyContainer, HSplit from prompt_toolkit.layout.dimension import Dimension as D from prompt_toolkit.styles import BaseStyle from prompt_toolkit.validation import Validator from prompt_toolkit.widgets import ( Box, Button, CheckboxList, Dialog, Label, ProgressBar, RadioList, TextArea, ValidationToolbar, ) def _create_app(dialog: AnyContainer, style: BaseStyle | None) -> Application[Any]: # Key bindings. bindings = KeyBindings() bindings.add("tab")(focus_next) bindings.add("s-tab")(focus_previous) return Application( layout=Layout(dialog), key_bindings=merge_key_bindings([load_key_bindings(), bindings]), mouse_support=True, style=style, full_screen=True, ) def _return_none() -> None: "Button handler that returns None." get_app().exit() def get_app() -> Application[Any]: """ Get the current active (running) Application. An :class:`.Application` is active during the :meth:`.Application.run_async` call. We assume that there can only be one :class:`.Application` active at the same time. There is only one terminal window, with only one stdin and stdout. This makes the code significantly easier than passing around the :class:`.Application` everywhere. If no :class:`.Application` is running, then return by default a :class:`.DummyApplication`. For practical reasons, we prefer to not raise an exception. This way, we don't have to check all over the place whether an actual `Application` was returned. (For applications like pymux where we can have more than one `Application`, we'll use a work-around to handle that.) """ session = _current_app_session.get() if session.app is not None: return session.app from .dummy import DummyApplication return DummyApplication() class Buffer: """ The core data structure that holds the text and cursor position of the current input line and implements all text manipulations on top of it. It also implements the history, undo stack and the completion state. :param completer: :class:`~prompt_toolkit.completion.Completer` instance. :param history: :class:`~prompt_toolkit.history.History` instance. :param tempfile_suffix: The tempfile suffix (extension) to be used for the "open in editor" function. For a Python REPL, this would be ".py", so that the editor knows the syntax highlighting to use. This can also be a callable that returns a string. :param tempfile: For more advanced tempfile situations where you need control over the subdirectories and filename. For a Git Commit Message, this would be ".git/COMMIT_EDITMSG", so that the editor knows the syntax highlighting to use. This can also be a callable that returns a string. :param name: Name for this buffer. E.g. DEFAULT_BUFFER. This is mostly useful for key bindings where we sometimes prefer to refer to a buffer by their name instead of by reference. :param accept_handler: Called when the buffer input is accepted. (Usually when the user presses `enter`.) The accept handler receives this `Buffer` as input and should return True when the buffer text should be kept instead of calling reset. In case of a `PromptSession` for instance, we want to keep the text, because we will exit the application, and only reset it during the next run. Events: :param on_text_changed: When the buffer text changes. (Callable or None.) :param on_text_insert: When new text is inserted. (Callable or None.) :param on_cursor_position_changed: When the cursor moves. (Callable or None.) :param on_completions_changed: When the completions were changed. (Callable or None.) :param on_suggestion_set: When an auto-suggestion text has been set. (Callable or None.) Filters: :param complete_while_typing: :class:`~prompt_toolkit.filters.Filter` or `bool`. Decide whether or not to do asynchronous autocompleting while typing. :param validate_while_typing: :class:`~prompt_toolkit.filters.Filter` or `bool`. Decide whether or not to do asynchronous validation while typing. :param enable_history_search: :class:`~prompt_toolkit.filters.Filter` or `bool` to indicate when up-arrow partial string matching is enabled. It is advised to not enable this at the same time as `complete_while_typing`, because when there is an autocompletion found, the up arrows usually browse through the completions, rather than through the history. :param read_only: :class:`~prompt_toolkit.filters.Filter`. When True, changes will not be allowed. :param multiline: :class:`~prompt_toolkit.filters.Filter` or `bool`. When not set, pressing `Enter` will call the `accept_handler`. Otherwise, pressing `Esc-Enter` is required. """ def __init__( self, completer: Completer | None = None, auto_suggest: AutoSuggest | None = None, history: History | None = None, validator: Validator | None = None, tempfile_suffix: str | Callable[[], str] = "", tempfile: str | Callable[[], str] = "", name: str = "", complete_while_typing: FilterOrBool = False, validate_while_typing: FilterOrBool = False, enable_history_search: FilterOrBool = False, document: Document | None = None, accept_handler: BufferAcceptHandler | None = None, read_only: FilterOrBool = False, multiline: FilterOrBool = True, on_text_changed: BufferEventHandler | None = None, on_text_insert: BufferEventHandler | None = None, on_cursor_position_changed: BufferEventHandler | None = None, on_completions_changed: BufferEventHandler | None = None, on_suggestion_set: BufferEventHandler | None = None, ): # Accept both filters and booleans as input. enable_history_search = to_filter(enable_history_search) complete_while_typing = to_filter(complete_while_typing) validate_while_typing = to_filter(validate_while_typing) read_only = to_filter(read_only) multiline = to_filter(multiline) self.completer = completer or DummyCompleter() self.auto_suggest = auto_suggest self.validator = validator self.tempfile_suffix = tempfile_suffix self.tempfile = tempfile self.name = name self.accept_handler = accept_handler # Filters. (Usually, used by the key bindings to drive the buffer.) self.complete_while_typing = complete_while_typing self.validate_while_typing = validate_while_typing self.enable_history_search = enable_history_search self.read_only = read_only self.multiline = multiline # Text width. (For wrapping, used by the Vi 'gq' operator.) self.text_width = 0 #: The command buffer history. # Note that we shouldn't use a lazy 'or' here. bool(history) could be # False when empty. self.history = InMemoryHistory() if history is None else history self.__cursor_position = 0 # Events self.on_text_changed: Event[Buffer] = Event(self, on_text_changed) self.on_text_insert: Event[Buffer] = Event(self, on_text_insert) self.on_cursor_position_changed: Event[Buffer] = Event( self, on_cursor_position_changed ) self.on_completions_changed: Event[Buffer] = Event(self, on_completions_changed) self.on_suggestion_set: Event[Buffer] = Event(self, on_suggestion_set) # Document cache. (Avoid creating new Document instances.) self._document_cache: FastDictCache[ tuple[str, int, SelectionState | None], Document ] = FastDictCache(Document, size=10) # Create completer / auto suggestion / validation coroutines. self._async_suggester = self._create_auto_suggest_coroutine() self._async_completer = self._create_completer_coroutine() self._async_validator = self._create_auto_validate_coroutine() # Asyncio task for populating the history. self._load_history_task: asyncio.Future[None] | None = None # Reset other attributes. self.reset(document=document) def __repr__(self) -> str: if len(self.text) < 15: text = self.text else: text = self.text[:12] + "..." return f"<Buffer(name={self.name!r}, text={text!r}) at {id(self)!r}>" def reset( self, document: Document | None = None, append_to_history: bool = False ) -> None: """ :param append_to_history: Append current input to history first. """ if append_to_history: self.append_to_history() document = document or Document() self.__cursor_position = document.cursor_position # `ValidationError` instance. (Will be set when the input is wrong.) self.validation_error: ValidationError | None = None self.validation_state: ValidationState | None = ValidationState.UNKNOWN # State of the selection. self.selection_state: SelectionState | None = None # Multiple cursor mode. (When we press 'I' or 'A' in visual-block mode, # we can insert text on multiple lines at once. This is implemented by # using multiple cursors.) self.multiple_cursor_positions: list[int] = [] # When doing consecutive up/down movements, prefer to stay at this column. self.preferred_column: int | None = None # State of complete browser # For interactive completion through Ctrl-N/Ctrl-P. self.complete_state: CompletionState | None = None # State of Emacs yank-nth-arg completion. self.yank_nth_arg_state: YankNthArgState | None = None # for yank-nth-arg. # Remember the document that we had *right before* the last paste # operation. This is used for rotating through the kill ring. self.document_before_paste: Document | None = None # Current suggestion. self.suggestion: Suggestion | None = None # The history search text. (Used for filtering the history when we # browse through it.) self.history_search_text: str | None = None # Undo/redo stacks (stack of `(text, cursor_position)`). self._undo_stack: list[tuple[str, int]] = [] self._redo_stack: list[tuple[str, int]] = [] # Cancel history loader. If history loading was still ongoing. # Cancel the `_load_history_task`, so that next repaint of the # `BufferControl` we will repopulate it. if self._load_history_task is not None: self._load_history_task.cancel() self._load_history_task = None #: The working lines. Similar to history, except that this can be #: modified. The user can press arrow_up and edit previous entries. #: Ctrl-C should reset this, and copy the whole history back in here. #: Enter should process the current command and append to the real #: history. self._working_lines: Deque[str] = deque([document.text]) self.__working_index = 0 def load_history_if_not_yet_loaded(self) -> None: """ Create task for populating the buffer history (if not yet done). Note:: This needs to be called from within the event loop of the application, because history loading is async, and we need to be sure the right event loop is active. Therefor, we call this method in the `BufferControl.create_content`. There are situations where prompt_toolkit applications are created in one thread, but will later run in a different thread (Ptpython is one example. The REPL runs in a separate thread, in order to prevent interfering with a potential different event loop in the main thread. The REPL UI however is still created in the main thread.) We could decide to not support creating prompt_toolkit objects in one thread and running the application in a different thread, but history loading is the only place where it matters, and this solves it. """ if self._load_history_task is None: async def load_history() -> None: async for item in self.history.load(): self._working_lines.appendleft(item) self.__working_index += 1 self._load_history_task = get_app().create_background_task(load_history()) def load_history_done(f: asyncio.Future[None]) -> None: """ Handle `load_history` result when either done, cancelled, or when an exception was raised. """ try: f.result() except asyncio.CancelledError: # Ignore cancellation. But handle it, so that we don't get # this traceback. pass except GeneratorExit: # Probably not needed, but we had situations where # `GeneratorExit` was raised in `load_history` during # cancellation. pass except BaseException: # Log error if something goes wrong. (We don't have a # caller to which we can propagate this exception.) logger.exception("Loading history failed") self._load_history_task.add_done_callback(load_history_done) # <getters/setters> def _set_text(self, value: str) -> bool: """set text at current working_index. Return whether it changed.""" working_index = self.working_index working_lines = self._working_lines original_value = working_lines[working_index] working_lines[working_index] = value # Return True when this text has been changed. if len(value) != len(original_value): # For Python 2, it seems that when two strings have a different # length and one is a prefix of the other, Python still scans # character by character to see whether the strings are different. # (Some benchmarking showed significant differences for big # documents. >100,000 of lines.) return True elif value != original_value: return True return False def _set_cursor_position(self, value: int) -> bool: """Set cursor position. Return whether it changed.""" original_position = self.__cursor_position self.__cursor_position = max(0, value) return self.__cursor_position != original_position def text(self) -> str: return self._working_lines[self.working_index] def text(self, value: str) -> None: """ Setting text. (When doing this, make sure that the cursor_position is valid for this text. text/cursor_position should be consistent at any time, otherwise set a Document instead.) """ # Ensure cursor position remains within the size of the text. if self.cursor_position > len(value): self.cursor_position = len(value) # Don't allow editing of read-only buffers. if self.read_only(): raise EditReadOnlyBuffer() changed = self._set_text(value) if changed: self._text_changed() # Reset history search text. # (Note that this doesn't need to happen when working_index # changes, which is when we traverse the history. That's why we # don't do this in `self._text_changed`.) self.history_search_text = None def cursor_position(self) -> int: return self.__cursor_position def cursor_position(self, value: int) -> None: """ Setting cursor position. """ assert isinstance(value, int) # Ensure cursor position is within the size of the text. if value > len(self.text): value = len(self.text) if value < 0: value = 0 changed = self._set_cursor_position(value) if changed: self._cursor_position_changed() def working_index(self) -> int: return self.__working_index def working_index(self, value: int) -> None: if self.__working_index != value: self.__working_index = value # Make sure to reset the cursor position, otherwise we end up in # situations where the cursor position is out of the bounds of the # text. self.cursor_position = 0 self._text_changed() def _text_changed(self) -> None: # Remove any validation errors and complete state. self.validation_error = None self.validation_state = ValidationState.UNKNOWN self.complete_state = None self.yank_nth_arg_state = None self.document_before_paste = None self.selection_state = None self.suggestion = None self.preferred_column = None # fire 'on_text_changed' event. self.on_text_changed.fire() # Input validation. # (This happens on all change events, unlike auto completion, also when # deleting text.) if self.validator and self.validate_while_typing(): get_app().create_background_task(self._async_validator()) def _cursor_position_changed(self) -> None: # Remove any complete state. # (Input validation should only be undone when the cursor position # changes.) self.complete_state = None self.yank_nth_arg_state = None self.document_before_paste = None # Unset preferred_column. (Will be set after the cursor movement, if # required.) self.preferred_column = None # Note that the cursor position can change if we have a selection the # new position of the cursor determines the end of the selection. # fire 'on_cursor_position_changed' event. self.on_cursor_position_changed.fire() def document(self) -> Document: """ Return :class:`~prompt_toolkit.document.Document` instance from the current text, cursor position and selection state. """ return self._document_cache[ self.text, self.cursor_position, self.selection_state ] def document(self, value: Document) -> None: """ Set :class:`~prompt_toolkit.document.Document` instance. This will set both the text and cursor position at the same time, but atomically. (Change events will be triggered only after both have been set.) """ self.set_document(value) def set_document(self, value: Document, bypass_readonly: bool = False) -> None: """ Set :class:`~prompt_toolkit.document.Document` instance. Like the ``document`` property, but accept an ``bypass_readonly`` argument. :param bypass_readonly: When True, don't raise an :class:`.EditReadOnlyBuffer` exception, even when the buffer is read-only. .. warning:: When this buffer is read-only and `bypass_readonly` was not passed, the `EditReadOnlyBuffer` exception will be caught by the `KeyProcessor` and is silently suppressed. This is important to keep in mind when writing key bindings, because it won't do what you expect, and there won't be a stack trace. Use try/finally around this function if you need some cleanup code. """ # Don't allow editing of read-only buffers. if not bypass_readonly and self.read_only(): raise EditReadOnlyBuffer() # Set text and cursor position first. text_changed = self._set_text(value.text) cursor_position_changed = self._set_cursor_position(value.cursor_position) # Now handle change events. (We do this when text/cursor position is # both set and consistent.) if text_changed: self._text_changed() self.history_search_text = None if cursor_position_changed: self._cursor_position_changed() def is_returnable(self) -> bool: """ True when there is something handling accept. """ return bool(self.accept_handler) # End of <getters/setters> def save_to_undo_stack(self, clear_redo_stack: bool = True) -> None: """ Safe current state (input text and cursor position), so that we can restore it by calling undo. """ # Safe if the text is different from the text at the top of the stack # is different. If the text is the same, just update the cursor position. if self._undo_stack and self._undo_stack[-1][0] == self.text: self._undo_stack[-1] = (self._undo_stack[-1][0], self.cursor_position) else: self._undo_stack.append((self.text, self.cursor_position)) # Saving anything to the undo stack, clears the redo stack. if clear_redo_stack: self._redo_stack = [] def transform_lines( self, line_index_iterator: Iterable[int], transform_callback: Callable[[str], str], ) -> str: """ Transforms the text on a range of lines. When the iterator yield an index not in the range of lines that the document contains, it skips them silently. To uppercase some lines:: new_text = transform_lines(range(5,10), lambda text: text.upper()) :param line_index_iterator: Iterator of line numbers (int) :param transform_callback: callable that takes the original text of a line, and return the new text for this line. :returns: The new text. """ # Split lines lines = self.text.split("\n") # Apply transformation for index in line_index_iterator: try: lines[index] = transform_callback(lines[index]) except IndexError: pass return "\n".join(lines) def transform_current_line(self, transform_callback: Callable[[str], str]) -> None: """ Apply the given transformation function to the current line. :param transform_callback: callable that takes a string and return a new string. """ document = self.document a = document.cursor_position + document.get_start_of_line_position() b = document.cursor_position + document.get_end_of_line_position() self.text = ( document.text[:a] + transform_callback(document.text[a:b]) + document.text[b:] ) def transform_region( self, from_: int, to: int, transform_callback: Callable[[str], str] ) -> None: """ Transform a part of the input string. :param from_: (int) start position. :param to: (int) end position. :param transform_callback: Callable which accepts a string and returns the transformed string. """ assert from_ < to self.text = "".join( [ self.text[:from_] + transform_callback(self.text[from_:to]) + self.text[to:] ] ) def cursor_left(self, count: int = 1) -> None: self.cursor_position += self.document.get_cursor_left_position(count=count) def cursor_right(self, count: int = 1) -> None: self.cursor_position += self.document.get_cursor_right_position(count=count) def cursor_up(self, count: int = 1) -> None: """(for multiline edit). Move cursor to the previous line.""" original_column = self.preferred_column or self.document.cursor_position_col self.cursor_position += self.document.get_cursor_up_position( count=count, preferred_column=original_column ) # Remember the original column for the next up/down movement. self.preferred_column = original_column def cursor_down(self, count: int = 1) -> None: """(for multiline edit). Move cursor to the next line.""" original_column = self.preferred_column or self.document.cursor_position_col self.cursor_position += self.document.get_cursor_down_position( count=count, preferred_column=original_column ) # Remember the original column for the next up/down movement. self.preferred_column = original_column def auto_up( self, count: int = 1, go_to_start_of_line_if_history_changes: bool = False ) -> None: """ If we're not on the first line (of a multiline input) go a line up, otherwise go back in history. (If nothing is selected.) """ if self.complete_state: self.complete_previous(count=count) elif self.document.cursor_position_row > 0: self.cursor_up(count=count) elif not self.selection_state: self.history_backward(count=count) # Go to the start of the line? if go_to_start_of_line_if_history_changes: self.cursor_position += self.document.get_start_of_line_position() def auto_down( self, count: int = 1, go_to_start_of_line_if_history_changes: bool = False ) -> None: """ If we're not on the last line (of a multiline input) go a line down, otherwise go forward in history. (If nothing is selected.) """ if self.complete_state: self.complete_next(count=count) elif self.document.cursor_position_row < self.document.line_count - 1: self.cursor_down(count=count) elif not self.selection_state: self.history_forward(count=count) # Go to the start of the line? if go_to_start_of_line_if_history_changes: self.cursor_position += self.document.get_start_of_line_position() def delete_before_cursor(self, count: int = 1) -> str: """ Delete specified number of characters before cursor and return the deleted text. """ assert count >= 0 deleted = "" if self.cursor_position > 0: deleted = self.text[self.cursor_position - count : self.cursor_position] new_text = ( self.text[: self.cursor_position - count] + self.text[self.cursor_position :] ) new_cursor_position = self.cursor_position - len(deleted) # Set new Document atomically. self.document = Document(new_text, new_cursor_position) return deleted def delete(self, count: int = 1) -> str: """ Delete specified number of characters and Return the deleted text. """ if self.cursor_position < len(self.text): deleted = self.document.text_after_cursor[:count] self.text = ( self.text[: self.cursor_position] + self.text[self.cursor_position + len(deleted) :] ) return deleted else: return "" def join_next_line(self, separator: str = " ") -> None: """ Join the next line to the current one by deleting the line ending after the current line. """ if not self.document.on_last_line: self.cursor_position += self.document.get_end_of_line_position() self.delete() # Remove spaces. self.text = ( self.document.text_before_cursor + separator + self.document.text_after_cursor.lstrip(" ") ) def join_selected_lines(self, separator: str = " ") -> None: """ Join the selected lines. """ assert self.selection_state # Get lines. from_, to = sorted( [self.cursor_position, self.selection_state.original_cursor_position] ) before = self.text[:from_] lines = self.text[from_:to].splitlines() after = self.text[to:] # Replace leading spaces with just one space. lines = [l.lstrip(" ") + separator for l in lines] # Set new document. self.document = Document( text=before + "".join(lines) + after, cursor_position=len(before + "".join(lines[:-1])) - 1, ) def swap_characters_before_cursor(self) -> None: """ Swap the last two characters before the cursor. """ pos = self.cursor_position if pos >= 2: a = self.text[pos - 2] b = self.text[pos - 1] self.text = self.text[: pos - 2] + b + a + self.text[pos:] def go_to_history(self, index: int) -> None: """ Go to this item in the history. """ if index < len(self._working_lines): self.working_index = index self.cursor_position = len(self.text) def complete_next(self, count: int = 1, disable_wrap_around: bool = False) -> None: """ Browse to the next completions. (Does nothing if there are no completion.) """ index: int | None if self.complete_state: completions_count = len(self.complete_state.completions) if self.complete_state.complete_index is None: index = 0 elif self.complete_state.complete_index == completions_count - 1: index = None if disable_wrap_around: return else: index = min( completions_count - 1, self.complete_state.complete_index + count ) self.go_to_completion(index) def complete_previous( self, count: int = 1, disable_wrap_around: bool = False ) -> None: """ Browse to the previous completions. (Does nothing if there are no completion.) """ index: int | None if self.complete_state: if self.complete_state.complete_index == 0: index = None if disable_wrap_around: return elif self.complete_state.complete_index is None: index = len(self.complete_state.completions) - 1 else: index = max(0, self.complete_state.complete_index - count) self.go_to_completion(index) def cancel_completion(self) -> None: """ Cancel completion, go back to the original text. """ if self.complete_state: self.go_to_completion(None) self.complete_state = None def _set_completions(self, completions: list[Completion]) -> CompletionState: """ Start completions. (Generate list of completions and initialize.) By default, no completion will be selected. """ self.complete_state = CompletionState( original_document=self.document, completions=completions ) # Trigger event. This should eventually invalidate the layout. self.on_completions_changed.fire() return self.complete_state def start_history_lines_completion(self) -> None: """ Start a completion based on all the other lines in the document and the history. """ found_completions: set[str] = set() completions = [] # For every line of the whole history, find matches with the current line. current_line = self.document.current_line_before_cursor.lstrip() for i, string in enumerate(self._working_lines): for j, l in enumerate(string.split("\n")): l = l.strip() if l and l.startswith(current_line): # When a new line has been found. if l not in found_completions: found_completions.add(l) # Create completion. if i == self.working_index: display_meta = "Current, line %s" % (j + 1) else: display_meta = f"History {i + 1}, line {j + 1}" completions.append( Completion( text=l, start_position=-len(current_line), display_meta=display_meta, ) ) self._set_completions(completions=completions[::-1]) self.go_to_completion(0) def go_to_completion(self, index: int | None) -> None: """ Select a completion from the list of current completions. """ assert self.complete_state # Set new completion state = self.complete_state state.go_to_index(index) # Set text/cursor position new_text, new_cursor_position = state.new_text_and_position() self.document = Document(new_text, new_cursor_position) # (changing text/cursor position will unset complete_state.) self.complete_state = state def apply_completion(self, completion: Completion) -> None: """ Insert a given completion. """ # If there was already a completion active, cancel that one. if self.complete_state: self.go_to_completion(None) self.complete_state = None # Insert text from the given completion. self.delete_before_cursor(-completion.start_position) self.insert_text(completion.text) def _set_history_search(self) -> None: """ Set `history_search_text`. (The text before the cursor will be used for filtering the history.) """ if self.enable_history_search(): if self.history_search_text is None: self.history_search_text = self.document.text_before_cursor else: self.history_search_text = None def _history_matches(self, i: int) -> bool: """ True when the current entry matches the history search. (when we don't have history search, it's also True.) """ return self.history_search_text is None or self._working_lines[i].startswith( self.history_search_text ) def history_forward(self, count: int = 1) -> None: """ Move forwards through the history. :param count: Amount of items to move forward. """ self._set_history_search() # Go forward in history. found_something = False for i in range(self.working_index + 1, len(self._working_lines)): if self._history_matches(i): self.working_index = i count -= 1 found_something = True if count == 0: break # If we found an entry, move cursor to the end of the first line. if found_something: self.cursor_position = 0 self.cursor_position += self.document.get_end_of_line_position() def history_backward(self, count: int = 1) -> None: """ Move backwards through history. """ self._set_history_search() # Go back in history. found_something = False for i in range(self.working_index - 1, -1, -1): if self._history_matches(i): self.working_index = i count -= 1 found_something = True if count == 0: break # If we move to another entry, move cursor to the end of the line. if found_something: self.cursor_position = len(self.text) def yank_nth_arg(self, n: int | None = None, _yank_last_arg: bool = False) -> None: """ Pick nth word from previous history entry (depending on current `yank_nth_arg_state`) and insert it at current position. Rotate through history if called repeatedly. If no `n` has been given, take the first argument. (The second word.) :param n: (None or int), The index of the word from the previous line to take. """ assert n is None or isinstance(n, int) history_strings = self.history.get_strings() if not len(history_strings): return # Make sure we have a `YankNthArgState`. if self.yank_nth_arg_state is None: state = YankNthArgState(n=-1 if _yank_last_arg else 1) else: state = self.yank_nth_arg_state if n is not None: state.n = n # Get new history position. new_pos = state.history_position - 1 if -new_pos > len(history_strings): new_pos = -1 # Take argument from line. line = history_strings[new_pos] words = [w.strip() for w in _QUOTED_WORDS_RE.split(line)] words = [w for w in words if w] try: word = words[state.n] except IndexError: word = "" # Insert new argument. if state.previous_inserted_word: self.delete_before_cursor(len(state.previous_inserted_word)) self.insert_text(word) # Save state again for next completion. (Note that the 'insert' # operation from above clears `self.yank_nth_arg_state`.) state.previous_inserted_word = word state.history_position = new_pos self.yank_nth_arg_state = state def yank_last_arg(self, n: int | None = None) -> None: """ Like `yank_nth_arg`, but if no argument has been given, yank the last word by default. """ self.yank_nth_arg(n=n, _yank_last_arg=True) def start_selection( self, selection_type: SelectionType = SelectionType.CHARACTERS ) -> None: """ Take the current cursor position as the start of this selection. """ self.selection_state = SelectionState(self.cursor_position, selection_type) def copy_selection(self, _cut: bool = False) -> ClipboardData: """ Copy selected text and return :class:`.ClipboardData` instance. Notice that this doesn't store the copied data on the clipboard yet. You can store it like this: .. code:: python data = buffer.copy_selection() get_app().clipboard.set_data(data) """ new_document, clipboard_data = self.document.cut_selection() if _cut: self.document = new_document self.selection_state = None return clipboard_data def cut_selection(self) -> ClipboardData: """ Delete selected text and return :class:`.ClipboardData` instance. """ return self.copy_selection(_cut=True) def paste_clipboard_data( self, data: ClipboardData, paste_mode: PasteMode = PasteMode.EMACS, count: int = 1, ) -> None: """ Insert the data from the clipboard. """ assert isinstance(data, ClipboardData) assert paste_mode in (PasteMode.VI_BEFORE, PasteMode.VI_AFTER, PasteMode.EMACS) original_document = self.document self.document = self.document.paste_clipboard_data( data, paste_mode=paste_mode, count=count ) # Remember original document. This assignment should come at the end, # because assigning to 'document' will erase it. self.document_before_paste = original_document def newline(self, copy_margin: bool = True) -> None: """ Insert a line ending at the current position. """ if copy_margin: self.insert_text("\n" + self.document.leading_whitespace_in_current_line) else: self.insert_text("\n") def insert_line_above(self, copy_margin: bool = True) -> None: """ Insert a new line above the current one. """ if copy_margin: insert = self.document.leading_whitespace_in_current_line + "\n" else: insert = "\n" self.cursor_position += self.document.get_start_of_line_position() self.insert_text(insert) self.cursor_position -= 1 def insert_line_below(self, copy_margin: bool = True) -> None: """ Insert a new line below the current one. """ if copy_margin: insert = "\n" + self.document.leading_whitespace_in_current_line else: insert = "\n" self.cursor_position += self.document.get_end_of_line_position() self.insert_text(insert) def insert_text( self, data: str, overwrite: bool = False, move_cursor: bool = True, fire_event: bool = True, ) -> None: """ Insert characters at cursor position. :param fire_event: Fire `on_text_insert` event. This is mainly used to trigger autocompletion while typing. """ # Original text & cursor position. otext = self.text ocpos = self.cursor_position # In insert/text mode. if overwrite: # Don't overwrite the newline itself. Just before the line ending, # it should act like insert mode. overwritten_text = otext[ocpos : ocpos + len(data)] if "\n" in overwritten_text: overwritten_text = overwritten_text[: overwritten_text.find("\n")] text = otext[:ocpos] + data + otext[ocpos + len(overwritten_text) :] else: text = otext[:ocpos] + data + otext[ocpos:] if move_cursor: cpos = self.cursor_position + len(data) else: cpos = self.cursor_position # Set new document. # (Set text and cursor position at the same time. Otherwise, setting # the text will fire a change event before the cursor position has been # set. It works better to have this atomic.) self.document = Document(text, cpos) # Fire 'on_text_insert' event. if fire_event: # XXX: rename to `start_complete`. self.on_text_insert.fire() # Only complete when "complete_while_typing" is enabled. if self.completer and self.complete_while_typing(): get_app().create_background_task(self._async_completer()) # Call auto_suggest. if self.auto_suggest: get_app().create_background_task(self._async_suggester()) def undo(self) -> None: # Pop from the undo-stack until we find a text that if different from # the current text. (The current logic of `save_to_undo_stack` will # cause that the top of the undo stack is usually the same as the # current text, so in that case we have to pop twice.) while self._undo_stack: text, pos = self._undo_stack.pop() if text != self.text: # Push current text to redo stack. self._redo_stack.append((self.text, self.cursor_position)) # Set new text/cursor_position. self.document = Document(text, cursor_position=pos) break def redo(self) -> None: if self._redo_stack: # Copy current state on undo stack. self.save_to_undo_stack(clear_redo_stack=False) # Pop state from redo stack. text, pos = self._redo_stack.pop() self.document = Document(text, cursor_position=pos) def validate(self, set_cursor: bool = False) -> bool: """ Returns `True` if valid. :param set_cursor: Set the cursor position, if an error was found. """ # Don't call the validator again, if it was already called for the # current input. if self.validation_state != ValidationState.UNKNOWN: return self.validation_state == ValidationState.VALID # Call validator. if self.validator: try: self.validator.validate(self.document) except ValidationError as e: # Set cursor position (don't allow invalid values.) if set_cursor: self.cursor_position = min( max(0, e.cursor_position), len(self.text) ) self.validation_state = ValidationState.INVALID self.validation_error = e return False # Handle validation result. self.validation_state = ValidationState.VALID self.validation_error = None return True async def _validate_async(self) -> None: """ Asynchronous version of `validate()`. This one doesn't set the cursor position. We have both variants, because a synchronous version is required. Handling the ENTER key needs to be completely synchronous, otherwise stuff like type-ahead is going to give very weird results. (People could type input while the ENTER key is still processed.) An asynchronous version is required if we have `validate_while_typing` enabled. """ while True: # Don't call the validator again, if it was already called for the # current input. if self.validation_state != ValidationState.UNKNOWN: return # Call validator. error = None document = self.document if self.validator: try: await self.validator.validate_async(self.document) except ValidationError as e: error = e # If the document changed during the validation, try again. if self.document != document: continue # Handle validation result. if error: self.validation_state = ValidationState.INVALID else: self.validation_state = ValidationState.VALID self.validation_error = error get_app().invalidate() # Trigger redraw (display error). def append_to_history(self) -> None: """ Append the current input to the history. """ # Save at the tail of the history. (But don't if the last entry the # history is already the same.) if self.text: history_strings = self.history.get_strings() if not len(history_strings) or history_strings[-1] != self.text: self.history.append_string(self.text) def _search( self, search_state: SearchState, include_current_position: bool = False, count: int = 1, ) -> tuple[int, int] | None: """ Execute search. Return (working_index, cursor_position) tuple when this search is applied. Returns `None` when this text cannot be found. """ assert count > 0 text = search_state.text direction = search_state.direction ignore_case = search_state.ignore_case() def search_once( working_index: int, document: Document ) -> tuple[int, Document] | None: """ Do search one time. Return (working_index, document) or `None` """ if direction == SearchDirection.FORWARD: # Try find at the current input. new_index = document.find( text, include_current_position=include_current_position, ignore_case=ignore_case, ) if new_index is not None: return ( working_index, Document(document.text, document.cursor_position + new_index), ) else: # No match, go forward in the history. (Include len+1 to wrap around.) # (Here we should always include all cursor positions, because # it's a different line.) for i in range(working_index + 1, len(self._working_lines) + 1): i %= len(self._working_lines) document = Document(self._working_lines[i], 0) new_index = document.find( text, include_current_position=True, ignore_case=ignore_case ) if new_index is not None: return (i, Document(document.text, new_index)) else: # Try find at the current input. new_index = document.find_backwards(text, ignore_case=ignore_case) if new_index is not None: return ( working_index, Document(document.text, document.cursor_position + new_index), ) else: # No match, go back in the history. (Include -1 to wrap around.) for i in range(working_index - 1, -2, -1): i %= len(self._working_lines) document = Document( self._working_lines[i], len(self._working_lines[i]) ) new_index = document.find_backwards( text, ignore_case=ignore_case ) if new_index is not None: return ( i, Document(document.text, len(document.text) + new_index), ) return None # Do 'count' search iterations. working_index = self.working_index document = self.document for _ in range(count): result = search_once(working_index, document) if result is None: return None # Nothing found. else: working_index, document = result return (working_index, document.cursor_position) def document_for_search(self, search_state: SearchState) -> Document: """ Return a :class:`~prompt_toolkit.document.Document` instance that has the text/cursor position for this search, if we would apply it. This will be used in the :class:`~prompt_toolkit.layout.BufferControl` to display feedback while searching. """ search_result = self._search(search_state, include_current_position=True) if search_result is None: return self.document else: working_index, cursor_position = search_result # Keep selection, when `working_index` was not changed. if working_index == self.working_index: selection = self.selection_state else: selection = None return Document( self._working_lines[working_index], cursor_position, selection=selection ) def get_search_position( self, search_state: SearchState, include_current_position: bool = True, count: int = 1, ) -> int: """ Get the cursor position for this search. (This operation won't change the `working_index`. It's won't go through the history. Vi text objects can't span multiple items.) """ search_result = self._search( search_state, include_current_position=include_current_position, count=count ) if search_result is None: return self.cursor_position else: working_index, cursor_position = search_result return cursor_position def apply_search( self, search_state: SearchState, include_current_position: bool = True, count: int = 1, ) -> None: """ Apply search. If something is found, set `working_index` and `cursor_position`. """ search_result = self._search( search_state, include_current_position=include_current_position, count=count ) if search_result is not None: working_index, cursor_position = search_result self.working_index = working_index self.cursor_position = cursor_position def exit_selection(self) -> None: self.selection_state = None def _editor_simple_tempfile(self) -> tuple[str, Callable[[], None]]: """ Simple (file) tempfile implementation. Return (tempfile, cleanup_func). """ suffix = to_str(self.tempfile_suffix) descriptor, filename = tempfile.mkstemp(suffix) os.write(descriptor, self.text.encode("utf-8")) os.close(descriptor) def cleanup() -> None: os.unlink(filename) return filename, cleanup def _editor_complex_tempfile(self) -> tuple[str, Callable[[], None]]: # Complex (directory) tempfile implementation. headtail = to_str(self.tempfile) if not headtail: # Revert to simple case. return self._editor_simple_tempfile() headtail = str(headtail) # Try to make according to tempfile logic. head, tail = os.path.split(headtail) if os.path.isabs(head): head = head[1:] dirpath = tempfile.mkdtemp() if head: dirpath = os.path.join(dirpath, head) # Assume there is no issue creating dirs in this temp dir. os.makedirs(dirpath) # Open the filename and write current text. filename = os.path.join(dirpath, tail) with open(filename, "w", encoding="utf-8") as fh: fh.write(self.text) def cleanup() -> None: shutil.rmtree(dirpath) return filename, cleanup def open_in_editor(self, validate_and_handle: bool = False) -> asyncio.Task[None]: """ Open code in editor. This returns a future, and runs in a thread executor. """ if self.read_only(): raise EditReadOnlyBuffer() # Write current text to temporary file if self.tempfile: filename, cleanup_func = self._editor_complex_tempfile() else: filename, cleanup_func = self._editor_simple_tempfile() async def run() -> None: try: # Open in editor # (We need to use `run_in_terminal`, because not all editors go to # the alternate screen buffer, and some could influence the cursor # position.) succes = await run_in_terminal( lambda: self._open_file_in_editor(filename), in_executor=True ) # Read content again. if succes: with open(filename, "rb") as f: text = f.read().decode("utf-8") # Drop trailing newline. (Editors are supposed to add it at the # end, but we don't need it.) if text.endswith("\n"): text = text[:-1] self.document = Document(text=text, cursor_position=len(text)) # Accept the input. if validate_and_handle: self.validate_and_handle() finally: # Clean up temp dir/file. cleanup_func() return get_app().create_background_task(run()) def _open_file_in_editor(self, filename: str) -> bool: """ Call editor executable. Return True when we received a zero return code. """ # If the 'VISUAL' or 'EDITOR' environment variable has been set, use that. # Otherwise, fall back to the first available editor that we can find. visual = os.environ.get("VISUAL") editor = os.environ.get("EDITOR") editors = [ visual, editor, # Order of preference. "/usr/bin/editor", "/usr/bin/nano", "/usr/bin/pico", "/usr/bin/vi", "/usr/bin/emacs", ] for e in editors: if e: try: # Use 'shlex.split()', because $VISUAL can contain spaces # and quotes. returncode = subprocess.call(shlex.split(e) + [filename]) return returncode == 0 except OSError: # Executable does not exist, try the next one. pass return False def start_completion( self, select_first: bool = False, select_last: bool = False, insert_common_part: bool = False, complete_event: CompleteEvent | None = None, ) -> None: """ Start asynchronous autocompletion of this buffer. (This will do nothing if a previous completion was still in progress.) """ # Only one of these options can be selected. assert select_first + select_last + insert_common_part <= 1 get_app().create_background_task( self._async_completer( select_first=select_first, select_last=select_last, insert_common_part=insert_common_part, complete_event=complete_event or CompleteEvent(completion_requested=True), ) ) def _create_completer_coroutine(self) -> Callable[..., Coroutine[Any, Any, None]]: """ Create function for asynchronous autocompletion. (This consumes the asynchronous completer generator, which possibly runs the completion algorithm in another thread.) """ def completion_does_nothing(document: Document, completion: Completion) -> bool: """ Return `True` if applying this completion doesn't have any effect. (When it doesn't insert any new text. """ text_before_cursor = document.text_before_cursor replaced_text = text_before_cursor[ len(text_before_cursor) + completion.start_position : ] return replaced_text == completion.text async def async_completer( select_first: bool = False, select_last: bool = False, insert_common_part: bool = False, complete_event: CompleteEvent | None = None, ) -> None: document = self.document complete_event = complete_event or CompleteEvent(text_inserted=True) # Don't complete when we already have completions. if self.complete_state or not self.completer: return # Create an empty CompletionState. complete_state = CompletionState(original_document=self.document) self.complete_state = complete_state def proceed() -> bool: """Keep retrieving completions. Input text has not yet changed while generating completions.""" return self.complete_state == complete_state refresh_needed = asyncio.Event() async def refresh_while_loading() -> None: """Background loop to refresh the UI at most 3 times a second while the completion are loading. Calling `on_completions_changed.fire()` for every completion that we receive is too expensive when there are many completions. (We could tune `Application.max_render_postpone_time` and `Application.min_redraw_interval`, but having this here is a better approach.) """ while True: self.on_completions_changed.fire() refresh_needed.clear() await asyncio.sleep(0.3) await refresh_needed.wait() refresh_task = asyncio.ensure_future(refresh_while_loading()) try: # Load. async with aclosing( self.completer.get_completions_async(document, complete_event) ) as async_generator: async for completion in async_generator: complete_state.completions.append(completion) refresh_needed.set() # If the input text changes, abort. if not proceed(): break finally: refresh_task.cancel() # Refresh one final time after we got everything. self.on_completions_changed.fire() completions = complete_state.completions # When there is only one completion, which has nothing to add, ignore it. if len(completions) == 1 and completion_does_nothing( document, completions[0] ): del completions[:] # Set completions if the text was not yet changed. if proceed(): # When no completions were found, or when the user selected # already a completion by using the arrow keys, don't do anything. if ( not self.complete_state or self.complete_state.complete_index is not None ): return # When there are no completions, reset completion state anyway. if not completions: self.complete_state = None # Render the ui if the completion menu was shown # it is needed especially if there is one completion and it was deleted. self.on_completions_changed.fire() return # Select first/last or insert common part, depending on the key # binding. (For this we have to wait until all completions are # loaded.) if select_first: self.go_to_completion(0) elif select_last: self.go_to_completion(len(completions) - 1) elif insert_common_part: common_part = get_common_complete_suffix(document, completions) if common_part: # Insert the common part, update completions. self.insert_text(common_part) if len(completions) > 1: # (Don't call `async_completer` again, but # recalculate completions. See: # https://github.com/ipython/ipython/issues/9658) completions[:] = [ c.new_completion_from_position(len(common_part)) for c in completions ] self._set_completions(completions=completions) else: self.complete_state = None else: # When we were asked to insert the "common" # prefix, but there was no common suffix but # still exactly one match, then select the # first. (It could be that we have a completion # which does * expansion, like '*.py', with # exactly one match.) if len(completions) == 1: self.go_to_completion(0) else: # If the last operation was an insert, (not a delete), restart # the completion coroutine. if self.document.text_before_cursor == document.text_before_cursor: return # Nothing changed. if self.document.text_before_cursor.startswith( document.text_before_cursor ): raise _Retry return async_completer def _create_auto_suggest_coroutine(self) -> Callable[[], Coroutine[Any, Any, None]]: """ Create function for asynchronous auto suggestion. (This can be in another thread.) """ async def async_suggestor() -> None: document = self.document # Don't suggest when we already have a suggestion. if self.suggestion or not self.auto_suggest: return suggestion = await self.auto_suggest.get_suggestion_async(self, document) # Set suggestion only if the text was not yet changed. if self.document == document: # Set suggestion and redraw interface. self.suggestion = suggestion self.on_suggestion_set.fire() else: # Otherwise, restart thread. raise _Retry return async_suggestor def _create_auto_validate_coroutine( self, ) -> Callable[[], Coroutine[Any, Any, None]]: """ Create a function for asynchronous validation while typing. (This can be in another thread.) """ async def async_validator() -> None: await self._validate_async() return async_validator def validate_and_handle(self) -> None: """ Validate buffer and handle the accept action. """ valid = self.validate(set_cursor=True) # When the validation succeeded, accept the input. if valid: if self.accept_handler: keep_text = self.accept_handler(self) else: keep_text = False self.append_to_history() if not keep_text: self.reset() class HSplit(_Split): """ Several layouts, one stacked above/under the other. :: +--------------------+ | | +--------------------+ | | +--------------------+ By default, this doesn't display a horizontal line between the children, but if this is something you need, then create a HSplit as follows:: HSplit(children=[ ... ], padding_char='-', padding=1, padding_style='#ffff00') :param children: List of child :class:`.Container` objects. :param window_too_small: A :class:`.Container` object that is displayed if there is not enough space for all the children. By default, this is a "Window too small" message. :param align: `VerticalAlign` value. :param width: When given, use this width instead of looking at the children. :param height: When given, use this height instead of looking at the children. :param z_index: (int or None) When specified, this can be used to bring element in front of floating elements. `None` means: inherit from parent. :param style: A style string. :param modal: ``True`` or ``False``. :param key_bindings: ``None`` or a :class:`.KeyBindings` object. :param padding: (`Dimension` or int), size to be used for the padding. :param padding_char: Character to be used for filling in the padding. :param padding_style: Style to applied to the padding. """ def __init__( self, children: Sequence[AnyContainer], window_too_small: Container | None = None, align: VerticalAlign = VerticalAlign.JUSTIFY, padding: AnyDimension = 0, padding_char: str | None = None, padding_style: str = "", width: AnyDimension = None, height: AnyDimension = None, z_index: int | None = None, modal: bool = False, key_bindings: KeyBindingsBase | None = None, style: str | Callable[[], str] = "", ) -> None: super().__init__( children=children, window_too_small=window_too_small, padding=padding, padding_char=padding_char, padding_style=padding_style, width=width, height=height, z_index=z_index, modal=modal, key_bindings=key_bindings, style=style, ) self.align = align self._children_cache: SimpleCache[ tuple[Container, ...], list[Container] ] = SimpleCache(maxsize=1) self._remaining_space_window = Window() # Dummy window. def preferred_width(self, max_available_width: int) -> Dimension: if self.width is not None: return to_dimension(self.width) if self.children: dimensions = [c.preferred_width(max_available_width) for c in self.children] return max_layout_dimensions(dimensions) else: return Dimension() def preferred_height(self, width: int, max_available_height: int) -> Dimension: if self.height is not None: return to_dimension(self.height) dimensions = [ c.preferred_height(width, max_available_height) for c in self._all_children ] return sum_layout_dimensions(dimensions) def reset(self) -> None: for c in self.children: c.reset() def _all_children(self) -> list[Container]: """ List of child objects, including padding. """ def get() -> list[Container]: result: list[Container] = [] # Padding Top. if self.align in (VerticalAlign.CENTER, VerticalAlign.BOTTOM): result.append(Window(width=Dimension(preferred=0))) # The children with padding. for child in self.children: result.append(child) result.append( Window( height=self.padding, char=self.padding_char, style=self.padding_style, ) ) if result: result.pop() # Padding right. if self.align in (VerticalAlign.CENTER, VerticalAlign.TOP): result.append(Window(width=Dimension(preferred=0))) return result return self._children_cache.get(tuple(self.children), get) def write_to_screen( self, screen: Screen, mouse_handlers: MouseHandlers, write_position: WritePosition, parent_style: str, erase_bg: bool, z_index: int | None, ) -> None: """ Render the prompt to a `Screen` instance. :param screen: The :class:`~prompt_toolkit.layout.screen.Screen` class to which the output has to be written. """ sizes = self._divide_heights(write_position) style = parent_style + " " + to_str(self.style) z_index = z_index if self.z_index is None else self.z_index if sizes is None: self.window_too_small.write_to_screen( screen, mouse_handlers, write_position, style, erase_bg, z_index ) else: # ypos = write_position.ypos xpos = write_position.xpos width = write_position.width # Draw child panes. for s, c in zip(sizes, self._all_children): c.write_to_screen( screen, mouse_handlers, WritePosition(xpos, ypos, width, s), style, erase_bg, z_index, ) ypos += s # Fill in the remaining space. This happens when a child control # refuses to take more space and we don't have any padding. Adding a # dummy child control for this (in `self._all_children`) is not # desired, because in some situations, it would take more space, even # when it's not required. This is required to apply the styling. remaining_height = write_position.ypos + write_position.height - ypos if remaining_height > 0: self._remaining_space_window.write_to_screen( screen, mouse_handlers, WritePosition(xpos, ypos, width, remaining_height), style, erase_bg, z_index, ) def _divide_heights(self, write_position: WritePosition) -> list[int] | None: """ Return the heights for all rows. Or None when there is not enough space. """ if not self.children: return [] width = write_position.width height = write_position.height # Calculate heights. dimensions = [c.preferred_height(width, height) for c in self._all_children] # Sum dimensions sum_dimensions = sum_layout_dimensions(dimensions) # If there is not enough space for both. # Don't do anything. if sum_dimensions.min > height: return None # Find optimal sizes. (Start with minimal size, increase until we cover # the whole height.) sizes = [d.min for d in dimensions] child_generator = take_using_weights( items=list(range(len(dimensions))), weights=[d.weight for d in dimensions] ) i = next(child_generator) # Increase until we meet at least the 'preferred' size. preferred_stop = min(height, sum_dimensions.preferred) preferred_dimensions = [d.preferred for d in dimensions] while sum(sizes) < preferred_stop: if sizes[i] < preferred_dimensions[i]: sizes[i] += 1 i = next(child_generator) # Increase until we use all the available space. (or until "max") if not get_app().is_done: max_stop = min(height, sum_dimensions.max) max_dimensions = [d.max for d in dimensions] while sum(sizes) < max_stop: if sizes[i] < max_dimensions[i]: sizes[i] += 1 i = next(child_generator) return sizes class Validator(metaclass=ABCMeta): """ Abstract base class for an input validator. A validator is typically created in one of the following two ways: - Either by overriding this class and implementing the `validate` method. - Or by passing a callable to `Validator.from_callable`. If the validation takes some time and needs to happen in a background thread, this can be wrapped in a :class:`.ThreadedValidator`. """ def validate(self, document: Document) -> None: """ Validate the input. If invalid, this should raise a :class:`.ValidationError`. :param document: :class:`~prompt_toolkit.document.Document` instance. """ pass async def validate_async(self, document: Document) -> None: """ Return a `Future` which is set when the validation is ready. This function can be overloaded in order to provide an asynchronous implementation. """ try: self.validate(document) except ValidationError: raise def from_callable( cls, validate_func: Callable[[str], bool], error_message: str = "Invalid input", move_cursor_to_end: bool = False, ) -> Validator: """ Create a validator from a simple validate callable. E.g.: .. code:: python def is_valid(text): return text in ['hello', 'world'] Validator.from_callable(is_valid, error_message='Invalid input') :param validate_func: Callable that takes the input string, and returns `True` if the input is valid input. :param error_message: Message to be displayed if the input is invalid. :param move_cursor_to_end: Move the cursor to the end of the input, if the input is invalid. """ return _ValidatorFromCallable(validate_func, error_message, move_cursor_to_end) The provided code snippet includes necessary dependencies for implementing the `input_dialog` function. Write a Python function `def input_dialog( title: AnyFormattedText = "", text: AnyFormattedText = "", ok_text: str = "OK", cancel_text: str = "Cancel", completer: Completer | None = None, validator: Validator | None = None, password: FilterOrBool = False, style: BaseStyle | None = None, default: str = "", ) -> Application[str]` to solve the following problem: Display a text input box. Return the given text, or None when cancelled. Here is the function: def input_dialog( title: AnyFormattedText = "", text: AnyFormattedText = "", ok_text: str = "OK", cancel_text: str = "Cancel", completer: Completer | None = None, validator: Validator | None = None, password: FilterOrBool = False, style: BaseStyle | None = None, default: str = "", ) -> Application[str]: """ Display a text input box. Return the given text, or None when cancelled. """ def accept(buf: Buffer) -> bool: get_app().layout.focus(ok_button) return True # Keep text. def ok_handler() -> None: get_app().exit(result=textfield.text) ok_button = Button(text=ok_text, handler=ok_handler) cancel_button = Button(text=cancel_text, handler=_return_none) textfield = TextArea( text=default, multiline=False, password=password, completer=completer, validator=validator, accept_handler=accept, ) dialog = Dialog( title=title, body=HSplit( [ Label(text=text, dont_extend_height=True), textfield, ValidationToolbar(), ], padding=D(preferred=1, max=1), ), buttons=[ok_button, cancel_button], with_background=True, ) return _create_app(dialog, style)
Display a text input box. Return the given text, or None when cancelled.
172,047
from __future__ import annotations import functools from asyncio import get_running_loop from typing import Any, Callable, List, Optional, Sequence, Tuple, TypeVar from prompt_toolkit.application import Application from prompt_toolkit.application.current import get_app from prompt_toolkit.buffer import Buffer from prompt_toolkit.completion import Completer from prompt_toolkit.eventloop import run_in_executor_with_context from prompt_toolkit.filters import FilterOrBool from prompt_toolkit.formatted_text import AnyFormattedText from prompt_toolkit.key_binding.bindings.focus import focus_next, focus_previous from prompt_toolkit.key_binding.defaults import load_key_bindings from prompt_toolkit.key_binding.key_bindings import KeyBindings, merge_key_bindings from prompt_toolkit.layout import Layout from prompt_toolkit.layout.containers import AnyContainer, HSplit from prompt_toolkit.layout.dimension import Dimension as D from prompt_toolkit.styles import BaseStyle from prompt_toolkit.validation import Validator from prompt_toolkit.widgets import ( Box, Button, CheckboxList, Dialog, Label, ProgressBar, RadioList, TextArea, ValidationToolbar, ) def _create_app(dialog: AnyContainer, style: BaseStyle | None) -> Application[Any]: # Key bindings. bindings = KeyBindings() bindings.add("tab")(focus_next) bindings.add("s-tab")(focus_previous) return Application( layout=Layout(dialog), key_bindings=merge_key_bindings([load_key_bindings(), bindings]), mouse_support=True, style=style, full_screen=True, ) def _return_none() -> None: "Button handler that returns None." get_app().exit() The provided code snippet includes necessary dependencies for implementing the `message_dialog` function. Write a Python function `def message_dialog( title: AnyFormattedText = "", text: AnyFormattedText = "", ok_text: str = "Ok", style: BaseStyle | None = None, ) -> Application[None]` to solve the following problem: Display a simple message box and wait until the user presses enter. Here is the function: def message_dialog( title: AnyFormattedText = "", text: AnyFormattedText = "", ok_text: str = "Ok", style: BaseStyle | None = None, ) -> Application[None]: """ Display a simple message box and wait until the user presses enter. """ dialog = Dialog( title=title, body=Label(text=text, dont_extend_height=True), buttons=[Button(text=ok_text, handler=_return_none)], with_background=True, ) return _create_app(dialog, style)
Display a simple message box and wait until the user presses enter.
172,048
from __future__ import annotations import functools from asyncio import get_running_loop from typing import Any, Callable, List, Optional, Sequence, Tuple, TypeVar from prompt_toolkit.application import Application from prompt_toolkit.application.current import get_app from prompt_toolkit.buffer import Buffer from prompt_toolkit.completion import Completer from prompt_toolkit.eventloop import run_in_executor_with_context from prompt_toolkit.filters import FilterOrBool from prompt_toolkit.formatted_text import AnyFormattedText from prompt_toolkit.key_binding.bindings.focus import focus_next, focus_previous from prompt_toolkit.key_binding.defaults import load_key_bindings from prompt_toolkit.key_binding.key_bindings import KeyBindings, merge_key_bindings from prompt_toolkit.layout import Layout from prompt_toolkit.layout.containers import AnyContainer, HSplit from prompt_toolkit.layout.dimension import Dimension as D from prompt_toolkit.styles import BaseStyle from prompt_toolkit.validation import Validator from prompt_toolkit.widgets import ( Box, Button, CheckboxList, Dialog, Label, ProgressBar, RadioList, TextArea, ValidationToolbar, ) _T = TypeVar("_T") def _create_app(dialog: AnyContainer, style: BaseStyle | None) -> Application[Any]: # Key bindings. bindings = KeyBindings() bindings.add("tab")(focus_next) bindings.add("s-tab")(focus_previous) return Application( layout=Layout(dialog), key_bindings=merge_key_bindings([load_key_bindings(), bindings]), mouse_support=True, style=style, full_screen=True, ) def _return_none() -> None: "Button handler that returns None." get_app().exit() class Sequence(_Collection[_T_co], Reversible[_T_co], Generic[_T_co]): def __getitem__(self, i: int) -> _T_co: ... def __getitem__(self, s: slice) -> Sequence[_T_co]: ... # Mixin methods def index(self, value: Any, start: int = ..., stop: int = ...) -> int: ... def count(self, value: Any) -> int: ... def __contains__(self, x: object) -> bool: ... def __iter__(self) -> Iterator[_T_co]: ... def __reversed__(self) -> Iterator[_T_co]: ... def get_app() -> Application[Any]: """ Get the current active (running) Application. An :class:`.Application` is active during the :meth:`.Application.run_async` call. We assume that there can only be one :class:`.Application` active at the same time. There is only one terminal window, with only one stdin and stdout. This makes the code significantly easier than passing around the :class:`.Application` everywhere. If no :class:`.Application` is running, then return by default a :class:`.DummyApplication`. For practical reasons, we prefer to not raise an exception. This way, we don't have to check all over the place whether an actual `Application` was returned. (For applications like pymux where we can have more than one `Application`, we'll use a work-around to handle that.) """ session = _current_app_session.get() if session.app is not None: return session.app from .dummy import DummyApplication return DummyApplication() class HSplit(_Split): """ Several layouts, one stacked above/under the other. :: +--------------------+ | | +--------------------+ | | +--------------------+ By default, this doesn't display a horizontal line between the children, but if this is something you need, then create a HSplit as follows:: HSplit(children=[ ... ], padding_char='-', padding=1, padding_style='#ffff00') :param children: List of child :class:`.Container` objects. :param window_too_small: A :class:`.Container` object that is displayed if there is not enough space for all the children. By default, this is a "Window too small" message. :param align: `VerticalAlign` value. :param width: When given, use this width instead of looking at the children. :param height: When given, use this height instead of looking at the children. :param z_index: (int or None) When specified, this can be used to bring element in front of floating elements. `None` means: inherit from parent. :param style: A style string. :param modal: ``True`` or ``False``. :param key_bindings: ``None`` or a :class:`.KeyBindings` object. :param padding: (`Dimension` or int), size to be used for the padding. :param padding_char: Character to be used for filling in the padding. :param padding_style: Style to applied to the padding. """ def __init__( self, children: Sequence[AnyContainer], window_too_small: Container | None = None, align: VerticalAlign = VerticalAlign.JUSTIFY, padding: AnyDimension = 0, padding_char: str | None = None, padding_style: str = "", width: AnyDimension = None, height: AnyDimension = None, z_index: int | None = None, modal: bool = False, key_bindings: KeyBindingsBase | None = None, style: str | Callable[[], str] = "", ) -> None: super().__init__( children=children, window_too_small=window_too_small, padding=padding, padding_char=padding_char, padding_style=padding_style, width=width, height=height, z_index=z_index, modal=modal, key_bindings=key_bindings, style=style, ) self.align = align self._children_cache: SimpleCache[ tuple[Container, ...], list[Container] ] = SimpleCache(maxsize=1) self._remaining_space_window = Window() # Dummy window. def preferred_width(self, max_available_width: int) -> Dimension: if self.width is not None: return to_dimension(self.width) if self.children: dimensions = [c.preferred_width(max_available_width) for c in self.children] return max_layout_dimensions(dimensions) else: return Dimension() def preferred_height(self, width: int, max_available_height: int) -> Dimension: if self.height is not None: return to_dimension(self.height) dimensions = [ c.preferred_height(width, max_available_height) for c in self._all_children ] return sum_layout_dimensions(dimensions) def reset(self) -> None: for c in self.children: c.reset() def _all_children(self) -> list[Container]: """ List of child objects, including padding. """ def get() -> list[Container]: result: list[Container] = [] # Padding Top. if self.align in (VerticalAlign.CENTER, VerticalAlign.BOTTOM): result.append(Window(width=Dimension(preferred=0))) # The children with padding. for child in self.children: result.append(child) result.append( Window( height=self.padding, char=self.padding_char, style=self.padding_style, ) ) if result: result.pop() # Padding right. if self.align in (VerticalAlign.CENTER, VerticalAlign.TOP): result.append(Window(width=Dimension(preferred=0))) return result return self._children_cache.get(tuple(self.children), get) def write_to_screen( self, screen: Screen, mouse_handlers: MouseHandlers, write_position: WritePosition, parent_style: str, erase_bg: bool, z_index: int | None, ) -> None: """ Render the prompt to a `Screen` instance. :param screen: The :class:`~prompt_toolkit.layout.screen.Screen` class to which the output has to be written. """ sizes = self._divide_heights(write_position) style = parent_style + " " + to_str(self.style) z_index = z_index if self.z_index is None else self.z_index if sizes is None: self.window_too_small.write_to_screen( screen, mouse_handlers, write_position, style, erase_bg, z_index ) else: # ypos = write_position.ypos xpos = write_position.xpos width = write_position.width # Draw child panes. for s, c in zip(sizes, self._all_children): c.write_to_screen( screen, mouse_handlers, WritePosition(xpos, ypos, width, s), style, erase_bg, z_index, ) ypos += s # Fill in the remaining space. This happens when a child control # refuses to take more space and we don't have any padding. Adding a # dummy child control for this (in `self._all_children`) is not # desired, because in some situations, it would take more space, even # when it's not required. This is required to apply the styling. remaining_height = write_position.ypos + write_position.height - ypos if remaining_height > 0: self._remaining_space_window.write_to_screen( screen, mouse_handlers, WritePosition(xpos, ypos, width, remaining_height), style, erase_bg, z_index, ) def _divide_heights(self, write_position: WritePosition) -> list[int] | None: """ Return the heights for all rows. Or None when there is not enough space. """ if not self.children: return [] width = write_position.width height = write_position.height # Calculate heights. dimensions = [c.preferred_height(width, height) for c in self._all_children] # Sum dimensions sum_dimensions = sum_layout_dimensions(dimensions) # If there is not enough space for both. # Don't do anything. if sum_dimensions.min > height: return None # Find optimal sizes. (Start with minimal size, increase until we cover # the whole height.) sizes = [d.min for d in dimensions] child_generator = take_using_weights( items=list(range(len(dimensions))), weights=[d.weight for d in dimensions] ) i = next(child_generator) # Increase until we meet at least the 'preferred' size. preferred_stop = min(height, sum_dimensions.preferred) preferred_dimensions = [d.preferred for d in dimensions] while sum(sizes) < preferred_stop: if sizes[i] < preferred_dimensions[i]: sizes[i] += 1 i = next(child_generator) # Increase until we use all the available space. (or until "max") if not get_app().is_done: max_stop = min(height, sum_dimensions.max) max_dimensions = [d.max for d in dimensions] while sum(sizes) < max_stop: if sizes[i] < max_dimensions[i]: sizes[i] += 1 i = next(child_generator) return sizes The provided code snippet includes necessary dependencies for implementing the `radiolist_dialog` function. Write a Python function `def radiolist_dialog( title: AnyFormattedText = "", text: AnyFormattedText = "", ok_text: str = "Ok", cancel_text: str = "Cancel", values: Sequence[tuple[_T, AnyFormattedText]] | None = None, default: _T | None = None, style: BaseStyle | None = None, ) -> Application[_T]` to solve the following problem: Display a simple list of element the user can choose amongst. Only one element can be selected at a time using Arrow keys and Enter. The focus can be moved between the list and the Ok/Cancel button with tab. Here is the function: def radiolist_dialog( title: AnyFormattedText = "", text: AnyFormattedText = "", ok_text: str = "Ok", cancel_text: str = "Cancel", values: Sequence[tuple[_T, AnyFormattedText]] | None = None, default: _T | None = None, style: BaseStyle | None = None, ) -> Application[_T]: """ Display a simple list of element the user can choose amongst. Only one element can be selected at a time using Arrow keys and Enter. The focus can be moved between the list and the Ok/Cancel button with tab. """ if values is None: values = [] def ok_handler() -> None: get_app().exit(result=radio_list.current_value) radio_list = RadioList(values=values, default=default) dialog = Dialog( title=title, body=HSplit( [Label(text=text, dont_extend_height=True), radio_list], padding=1, ), buttons=[ Button(text=ok_text, handler=ok_handler), Button(text=cancel_text, handler=_return_none), ], with_background=True, ) return _create_app(dialog, style)
Display a simple list of element the user can choose amongst. Only one element can be selected at a time using Arrow keys and Enter. The focus can be moved between the list and the Ok/Cancel button with tab.
172,049
from __future__ import annotations import functools from asyncio import get_running_loop from typing import Any, Callable, List, Optional, Sequence, Tuple, TypeVar from prompt_toolkit.application import Application from prompt_toolkit.application.current import get_app from prompt_toolkit.buffer import Buffer from prompt_toolkit.completion import Completer from prompt_toolkit.eventloop import run_in_executor_with_context from prompt_toolkit.filters import FilterOrBool from prompt_toolkit.formatted_text import AnyFormattedText from prompt_toolkit.key_binding.bindings.focus import focus_next, focus_previous from prompt_toolkit.key_binding.defaults import load_key_bindings from prompt_toolkit.key_binding.key_bindings import KeyBindings, merge_key_bindings from prompt_toolkit.layout import Layout from prompt_toolkit.layout.containers import AnyContainer, HSplit from prompt_toolkit.layout.dimension import Dimension as D from prompt_toolkit.styles import BaseStyle from prompt_toolkit.validation import Validator from prompt_toolkit.widgets import ( Box, Button, CheckboxList, Dialog, Label, ProgressBar, RadioList, TextArea, ValidationToolbar, ) _T = TypeVar("_T") def _create_app(dialog: AnyContainer, style: BaseStyle | None) -> Application[Any]: # Key bindings. bindings = KeyBindings() bindings.add("tab")(focus_next) bindings.add("s-tab")(focus_previous) return Application( layout=Layout(dialog), key_bindings=merge_key_bindings([load_key_bindings(), bindings]), mouse_support=True, style=style, full_screen=True, ) def _return_none() -> None: "Button handler that returns None." get_app().exit() class Sequence(_Collection[_T_co], Reversible[_T_co], Generic[_T_co]): def __getitem__(self, i: int) -> _T_co: ... def __getitem__(self, s: slice) -> Sequence[_T_co]: ... # Mixin methods def index(self, value: Any, start: int = ..., stop: int = ...) -> int: ... def count(self, value: Any) -> int: ... def __contains__(self, x: object) -> bool: ... def __iter__(self) -> Iterator[_T_co]: ... def __reversed__(self) -> Iterator[_T_co]: ... def get_app() -> Application[Any]: """ Get the current active (running) Application. An :class:`.Application` is active during the :meth:`.Application.run_async` call. We assume that there can only be one :class:`.Application` active at the same time. There is only one terminal window, with only one stdin and stdout. This makes the code significantly easier than passing around the :class:`.Application` everywhere. If no :class:`.Application` is running, then return by default a :class:`.DummyApplication`. For practical reasons, we prefer to not raise an exception. This way, we don't have to check all over the place whether an actual `Application` was returned. (For applications like pymux where we can have more than one `Application`, we'll use a work-around to handle that.) """ session = _current_app_session.get() if session.app is not None: return session.app from .dummy import DummyApplication return DummyApplication() class HSplit(_Split): """ Several layouts, one stacked above/under the other. :: +--------------------+ | | +--------------------+ | | +--------------------+ By default, this doesn't display a horizontal line between the children, but if this is something you need, then create a HSplit as follows:: HSplit(children=[ ... ], padding_char='-', padding=1, padding_style='#ffff00') :param children: List of child :class:`.Container` objects. :param window_too_small: A :class:`.Container` object that is displayed if there is not enough space for all the children. By default, this is a "Window too small" message. :param align: `VerticalAlign` value. :param width: When given, use this width instead of looking at the children. :param height: When given, use this height instead of looking at the children. :param z_index: (int or None) When specified, this can be used to bring element in front of floating elements. `None` means: inherit from parent. :param style: A style string. :param modal: ``True`` or ``False``. :param key_bindings: ``None`` or a :class:`.KeyBindings` object. :param padding: (`Dimension` or int), size to be used for the padding. :param padding_char: Character to be used for filling in the padding. :param padding_style: Style to applied to the padding. """ def __init__( self, children: Sequence[AnyContainer], window_too_small: Container | None = None, align: VerticalAlign = VerticalAlign.JUSTIFY, padding: AnyDimension = 0, padding_char: str | None = None, padding_style: str = "", width: AnyDimension = None, height: AnyDimension = None, z_index: int | None = None, modal: bool = False, key_bindings: KeyBindingsBase | None = None, style: str | Callable[[], str] = "", ) -> None: super().__init__( children=children, window_too_small=window_too_small, padding=padding, padding_char=padding_char, padding_style=padding_style, width=width, height=height, z_index=z_index, modal=modal, key_bindings=key_bindings, style=style, ) self.align = align self._children_cache: SimpleCache[ tuple[Container, ...], list[Container] ] = SimpleCache(maxsize=1) self._remaining_space_window = Window() # Dummy window. def preferred_width(self, max_available_width: int) -> Dimension: if self.width is not None: return to_dimension(self.width) if self.children: dimensions = [c.preferred_width(max_available_width) for c in self.children] return max_layout_dimensions(dimensions) else: return Dimension() def preferred_height(self, width: int, max_available_height: int) -> Dimension: if self.height is not None: return to_dimension(self.height) dimensions = [ c.preferred_height(width, max_available_height) for c in self._all_children ] return sum_layout_dimensions(dimensions) def reset(self) -> None: for c in self.children: c.reset() def _all_children(self) -> list[Container]: """ List of child objects, including padding. """ def get() -> list[Container]: result: list[Container] = [] # Padding Top. if self.align in (VerticalAlign.CENTER, VerticalAlign.BOTTOM): result.append(Window(width=Dimension(preferred=0))) # The children with padding. for child in self.children: result.append(child) result.append( Window( height=self.padding, char=self.padding_char, style=self.padding_style, ) ) if result: result.pop() # Padding right. if self.align in (VerticalAlign.CENTER, VerticalAlign.TOP): result.append(Window(width=Dimension(preferred=0))) return result return self._children_cache.get(tuple(self.children), get) def write_to_screen( self, screen: Screen, mouse_handlers: MouseHandlers, write_position: WritePosition, parent_style: str, erase_bg: bool, z_index: int | None, ) -> None: """ Render the prompt to a `Screen` instance. :param screen: The :class:`~prompt_toolkit.layout.screen.Screen` class to which the output has to be written. """ sizes = self._divide_heights(write_position) style = parent_style + " " + to_str(self.style) z_index = z_index if self.z_index is None else self.z_index if sizes is None: self.window_too_small.write_to_screen( screen, mouse_handlers, write_position, style, erase_bg, z_index ) else: # ypos = write_position.ypos xpos = write_position.xpos width = write_position.width # Draw child panes. for s, c in zip(sizes, self._all_children): c.write_to_screen( screen, mouse_handlers, WritePosition(xpos, ypos, width, s), style, erase_bg, z_index, ) ypos += s # Fill in the remaining space. This happens when a child control # refuses to take more space and we don't have any padding. Adding a # dummy child control for this (in `self._all_children`) is not # desired, because in some situations, it would take more space, even # when it's not required. This is required to apply the styling. remaining_height = write_position.ypos + write_position.height - ypos if remaining_height > 0: self._remaining_space_window.write_to_screen( screen, mouse_handlers, WritePosition(xpos, ypos, width, remaining_height), style, erase_bg, z_index, ) def _divide_heights(self, write_position: WritePosition) -> list[int] | None: """ Return the heights for all rows. Or None when there is not enough space. """ if not self.children: return [] width = write_position.width height = write_position.height # Calculate heights. dimensions = [c.preferred_height(width, height) for c in self._all_children] # Sum dimensions sum_dimensions = sum_layout_dimensions(dimensions) # If there is not enough space for both. # Don't do anything. if sum_dimensions.min > height: return None # Find optimal sizes. (Start with minimal size, increase until we cover # the whole height.) sizes = [d.min for d in dimensions] child_generator = take_using_weights( items=list(range(len(dimensions))), weights=[d.weight for d in dimensions] ) i = next(child_generator) # Increase until we meet at least the 'preferred' size. preferred_stop = min(height, sum_dimensions.preferred) preferred_dimensions = [d.preferred for d in dimensions] while sum(sizes) < preferred_stop: if sizes[i] < preferred_dimensions[i]: sizes[i] += 1 i = next(child_generator) # Increase until we use all the available space. (or until "max") if not get_app().is_done: max_stop = min(height, sum_dimensions.max) max_dimensions = [d.max for d in dimensions] while sum(sizes) < max_stop: if sizes[i] < max_dimensions[i]: sizes[i] += 1 i = next(child_generator) return sizes The provided code snippet includes necessary dependencies for implementing the `checkboxlist_dialog` function. Write a Python function `def checkboxlist_dialog( title: AnyFormattedText = "", text: AnyFormattedText = "", ok_text: str = "Ok", cancel_text: str = "Cancel", values: Sequence[tuple[_T, AnyFormattedText]] | None = None, default_values: Sequence[_T] | None = None, style: BaseStyle | None = None, ) -> Application[list[_T]]` to solve the following problem: Display a simple list of element the user can choose multiple values amongst. Several elements can be selected at a time using Arrow keys and Enter. The focus can be moved between the list and the Ok/Cancel button with tab. Here is the function: def checkboxlist_dialog( title: AnyFormattedText = "", text: AnyFormattedText = "", ok_text: str = "Ok", cancel_text: str = "Cancel", values: Sequence[tuple[_T, AnyFormattedText]] | None = None, default_values: Sequence[_T] | None = None, style: BaseStyle | None = None, ) -> Application[list[_T]]: """ Display a simple list of element the user can choose multiple values amongst. Several elements can be selected at a time using Arrow keys and Enter. The focus can be moved between the list and the Ok/Cancel button with tab. """ if values is None: values = [] def ok_handler() -> None: get_app().exit(result=cb_list.current_values) cb_list = CheckboxList(values=values, default_values=default_values) dialog = Dialog( title=title, body=HSplit( [Label(text=text, dont_extend_height=True), cb_list], padding=1, ), buttons=[ Button(text=ok_text, handler=ok_handler), Button(text=cancel_text, handler=_return_none), ], with_background=True, ) return _create_app(dialog, style)
Display a simple list of element the user can choose multiple values amongst. Several elements can be selected at a time using Arrow keys and Enter. The focus can be moved between the list and the Ok/Cancel button with tab.
172,050
from __future__ import annotations import functools from asyncio import get_running_loop from typing import Any, Callable, List, Optional, Sequence, Tuple, TypeVar from prompt_toolkit.application import Application from prompt_toolkit.application.current import get_app from prompt_toolkit.buffer import Buffer from prompt_toolkit.completion import Completer from prompt_toolkit.eventloop import run_in_executor_with_context from prompt_toolkit.filters import FilterOrBool from prompt_toolkit.formatted_text import AnyFormattedText from prompt_toolkit.key_binding.bindings.focus import focus_next, focus_previous from prompt_toolkit.key_binding.defaults import load_key_bindings from prompt_toolkit.key_binding.key_bindings import KeyBindings, merge_key_bindings from prompt_toolkit.layout import Layout from prompt_toolkit.layout.containers import AnyContainer, HSplit from prompt_toolkit.layout.dimension import Dimension as D from prompt_toolkit.styles import BaseStyle from prompt_toolkit.validation import Validator from prompt_toolkit.widgets import ( Box, Button, CheckboxList, Dialog, Label, ProgressBar, RadioList, TextArea, ValidationToolbar, ) def _create_app(dialog: AnyContainer, style: BaseStyle | None) -> Application[Any]: # Key bindings. bindings = KeyBindings() bindings.add("tab")(focus_next) bindings.add("s-tab")(focus_previous) return Application( layout=Layout(dialog), key_bindings=merge_key_bindings([load_key_bindings(), bindings]), mouse_support=True, style=style, full_screen=True, ) class Callable(BaseTypingInstance): def py__call__(self, arguments): """ def x() -> Callable[[Callable[..., _T]], _T]: ... """ # The 0th index are the arguments. try: param_values = self._generics_manager[0] result_values = self._generics_manager[1] except IndexError: debug.warning('Callable[...] defined without two arguments') return NO_VALUES else: from jedi.inference.gradual.annotation import infer_return_for_callable return infer_return_for_callable(arguments, param_values, result_values) def py__get__(self, instance, class_value): return ValueSet([self]) class HSplit(_Split): """ Several layouts, one stacked above/under the other. :: +--------------------+ | | +--------------------+ | | +--------------------+ By default, this doesn't display a horizontal line between the children, but if this is something you need, then create a HSplit as follows:: HSplit(children=[ ... ], padding_char='-', padding=1, padding_style='#ffff00') :param children: List of child :class:`.Container` objects. :param window_too_small: A :class:`.Container` object that is displayed if there is not enough space for all the children. By default, this is a "Window too small" message. :param align: `VerticalAlign` value. :param width: When given, use this width instead of looking at the children. :param height: When given, use this height instead of looking at the children. :param z_index: (int or None) When specified, this can be used to bring element in front of floating elements. `None` means: inherit from parent. :param style: A style string. :param modal: ``True`` or ``False``. :param key_bindings: ``None`` or a :class:`.KeyBindings` object. :param padding: (`Dimension` or int), size to be used for the padding. :param padding_char: Character to be used for filling in the padding. :param padding_style: Style to applied to the padding. """ def __init__( self, children: Sequence[AnyContainer], window_too_small: Container | None = None, align: VerticalAlign = VerticalAlign.JUSTIFY, padding: AnyDimension = 0, padding_char: str | None = None, padding_style: str = "", width: AnyDimension = None, height: AnyDimension = None, z_index: int | None = None, modal: bool = False, key_bindings: KeyBindingsBase | None = None, style: str | Callable[[], str] = "", ) -> None: super().__init__( children=children, window_too_small=window_too_small, padding=padding, padding_char=padding_char, padding_style=padding_style, width=width, height=height, z_index=z_index, modal=modal, key_bindings=key_bindings, style=style, ) self.align = align self._children_cache: SimpleCache[ tuple[Container, ...], list[Container] ] = SimpleCache(maxsize=1) self._remaining_space_window = Window() # Dummy window. def preferred_width(self, max_available_width: int) -> Dimension: if self.width is not None: return to_dimension(self.width) if self.children: dimensions = [c.preferred_width(max_available_width) for c in self.children] return max_layout_dimensions(dimensions) else: return Dimension() def preferred_height(self, width: int, max_available_height: int) -> Dimension: if self.height is not None: return to_dimension(self.height) dimensions = [ c.preferred_height(width, max_available_height) for c in self._all_children ] return sum_layout_dimensions(dimensions) def reset(self) -> None: for c in self.children: c.reset() def _all_children(self) -> list[Container]: """ List of child objects, including padding. """ def get() -> list[Container]: result: list[Container] = [] # Padding Top. if self.align in (VerticalAlign.CENTER, VerticalAlign.BOTTOM): result.append(Window(width=Dimension(preferred=0))) # The children with padding. for child in self.children: result.append(child) result.append( Window( height=self.padding, char=self.padding_char, style=self.padding_style, ) ) if result: result.pop() # Padding right. if self.align in (VerticalAlign.CENTER, VerticalAlign.TOP): result.append(Window(width=Dimension(preferred=0))) return result return self._children_cache.get(tuple(self.children), get) def write_to_screen( self, screen: Screen, mouse_handlers: MouseHandlers, write_position: WritePosition, parent_style: str, erase_bg: bool, z_index: int | None, ) -> None: """ Render the prompt to a `Screen` instance. :param screen: The :class:`~prompt_toolkit.layout.screen.Screen` class to which the output has to be written. """ sizes = self._divide_heights(write_position) style = parent_style + " " + to_str(self.style) z_index = z_index if self.z_index is None else self.z_index if sizes is None: self.window_too_small.write_to_screen( screen, mouse_handlers, write_position, style, erase_bg, z_index ) else: # ypos = write_position.ypos xpos = write_position.xpos width = write_position.width # Draw child panes. for s, c in zip(sizes, self._all_children): c.write_to_screen( screen, mouse_handlers, WritePosition(xpos, ypos, width, s), style, erase_bg, z_index, ) ypos += s # Fill in the remaining space. This happens when a child control # refuses to take more space and we don't have any padding. Adding a # dummy child control for this (in `self._all_children`) is not # desired, because in some situations, it would take more space, even # when it's not required. This is required to apply the styling. remaining_height = write_position.ypos + write_position.height - ypos if remaining_height > 0: self._remaining_space_window.write_to_screen( screen, mouse_handlers, WritePosition(xpos, ypos, width, remaining_height), style, erase_bg, z_index, ) def _divide_heights(self, write_position: WritePosition) -> list[int] | None: """ Return the heights for all rows. Or None when there is not enough space. """ if not self.children: return [] width = write_position.width height = write_position.height # Calculate heights. dimensions = [c.preferred_height(width, height) for c in self._all_children] # Sum dimensions sum_dimensions = sum_layout_dimensions(dimensions) # If there is not enough space for both. # Don't do anything. if sum_dimensions.min > height: return None # Find optimal sizes. (Start with minimal size, increase until we cover # the whole height.) sizes = [d.min for d in dimensions] child_generator = take_using_weights( items=list(range(len(dimensions))), weights=[d.weight for d in dimensions] ) i = next(child_generator) # Increase until we meet at least the 'preferred' size. preferred_stop = min(height, sum_dimensions.preferred) preferred_dimensions = [d.preferred for d in dimensions] while sum(sizes) < preferred_stop: if sizes[i] < preferred_dimensions[i]: sizes[i] += 1 i = next(child_generator) # Increase until we use all the available space. (or until "max") if not get_app().is_done: max_stop = min(height, sum_dimensions.max) max_dimensions = [d.max for d in dimensions] while sum(sizes) < max_stop: if sizes[i] < max_dimensions[i]: sizes[i] += 1 i = next(child_generator) return sizes The provided code snippet includes necessary dependencies for implementing the `progress_dialog` function. Write a Python function `def progress_dialog( title: AnyFormattedText = "", text: AnyFormattedText = "", run_callback: Callable[[Callable[[int], None], Callable[[str], None]], None] = ( lambda *a: None ), style: BaseStyle | None = None, ) -> Application[None]` to solve the following problem: :param run_callback: A function that receives as input a `set_percentage` function and it does the work. Here is the function: def progress_dialog( title: AnyFormattedText = "", text: AnyFormattedText = "", run_callback: Callable[[Callable[[int], None], Callable[[str], None]], None] = ( lambda *a: None ), style: BaseStyle | None = None, ) -> Application[None]: """ :param run_callback: A function that receives as input a `set_percentage` function and it does the work. """ loop = get_running_loop() progressbar = ProgressBar() text_area = TextArea( focusable=False, # Prefer this text area as big as possible, to avoid having a window # that keeps resizing when we add text to it. height=D(preferred=10**10), ) dialog = Dialog( body=HSplit( [ Box(Label(text=text)), Box(text_area, padding=D.exact(1)), progressbar, ] ), title=title, with_background=True, ) app = _create_app(dialog, style) def set_percentage(value: int) -> None: progressbar.percentage = int(value) app.invalidate() def log_text(text: str) -> None: loop.call_soon_threadsafe(text_area.buffer.insert_text, text) app.invalidate() # Run the callback in the executor. When done, set a return value for the # UI, so that it quits. def start() -> None: try: run_callback(set_percentage, log_text) finally: app.exit() def pre_run() -> None: run_in_executor_with_context(start) app.pre_run_callables.append(pre_run) return app
:param run_callback: A function that receives as input a `set_percentage` function and it does the work.
172,051
from __future__ import annotations from asyncio import get_running_loop from contextlib import contextmanager from enum import Enum from functools import partial from typing import ( TYPE_CHECKING, Callable, Generic, Iterator, List, Optional, Tuple, TypeVar, Union, cast, ) from prompt_toolkit.application import Application from prompt_toolkit.application.current import get_app from prompt_toolkit.auto_suggest import AutoSuggest, DynamicAutoSuggest from prompt_toolkit.buffer import Buffer from prompt_toolkit.clipboard import Clipboard, DynamicClipboard, InMemoryClipboard from prompt_toolkit.completion import Completer, DynamicCompleter, ThreadedCompleter from prompt_toolkit.cursor_shapes import ( AnyCursorShapeConfig, CursorShapeConfig, DynamicCursorShapeConfig, ) from prompt_toolkit.document import Document from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER, EditingMode from prompt_toolkit.filters import ( Condition, FilterOrBool, has_arg, has_focus, is_done, is_true, renderer_height_is_known, to_filter, ) from prompt_toolkit.formatted_text import ( AnyFormattedText, StyleAndTextTuples, fragment_list_to_text, merge_formatted_text, to_formatted_text, ) from prompt_toolkit.history import History, InMemoryHistory from prompt_toolkit.input.base import Input from prompt_toolkit.key_binding.bindings.auto_suggest import load_auto_suggest_bindings from prompt_toolkit.key_binding.bindings.completion import ( display_completions_like_readline, ) from prompt_toolkit.key_binding.bindings.open_in_editor import ( load_open_in_editor_bindings, ) from prompt_toolkit.key_binding.key_bindings import ( ConditionalKeyBindings, DynamicKeyBindings, KeyBindings, KeyBindingsBase, merge_key_bindings, ) from prompt_toolkit.key_binding.key_processor import KeyPressEvent from prompt_toolkit.keys import Keys from prompt_toolkit.layout import Float, FloatContainer, HSplit, Window from prompt_toolkit.layout.containers import ConditionalContainer, WindowAlign from prompt_toolkit.layout.controls import ( BufferControl, FormattedTextControl, SearchBufferControl, ) from prompt_toolkit.layout.dimension import Dimension from prompt_toolkit.layout.layout import Layout from prompt_toolkit.layout.menus import CompletionsMenu, MultiColumnCompletionsMenu from prompt_toolkit.layout.processors import ( AfterInput, AppendAutoSuggestion, ConditionalProcessor, DisplayMultipleCursors, DynamicProcessor, HighlightIncrementalSearchProcessor, HighlightSelectionProcessor, PasswordProcessor, Processor, ReverseSearchProcessor, merge_processors, ) from prompt_toolkit.layout.utils import explode_text_fragments from prompt_toolkit.lexers import DynamicLexer, Lexer from prompt_toolkit.output import ColorDepth, DummyOutput, Output from prompt_toolkit.styles import ( BaseStyle, ConditionalStyleTransformation, DynamicStyle, DynamicStyleTransformation, StyleTransformation, SwapLightAndDarkStyleTransformation, merge_style_transformations, ) from prompt_toolkit.utils import ( get_cwidth, is_dumb_terminal, suspend_to_background_supported, to_str, ) from prompt_toolkit.validation import DynamicValidator, Validator from prompt_toolkit.widgets.toolbars import ( SearchToolbar, SystemToolbar, ValidationToolbar, ) _StyleAndTextTuplesCallable = Callable[[], StyleAndTextTuples] class Callable(BaseTypingInstance): def py__call__(self, arguments): """ def x() -> Callable[[Callable[..., _T]], _T]: ... """ # The 0th index are the arguments. try: param_values = self._generics_manager[0] result_values = self._generics_manager[1] except IndexError: debug.warning('Callable[...] defined without two arguments') return NO_VALUES else: from jedi.inference.gradual.annotation import infer_return_for_callable return infer_return_for_callable(arguments, param_values, result_values) def py__get__(self, instance, class_value): return ValueSet([self]) def explode_text_fragments(fragments: Iterable[_T]) -> _ExplodedList[_T]: """ Turn a list of (style_str, text) tuples into another list where each string is exactly one character. It should be fine to call this function several times. Calling this on a list that is already exploded, is a null operation. :param fragments: List of (style, text) tuples. """ # When the fragments is already exploded, don't explode again. if isinstance(fragments, _ExplodedList): return fragments result: list[_T] = [] for style, string, *rest in fragments: for c in string: result.append((style, c, *rest)) # type: ignore return _ExplodedList(result) The provided code snippet includes necessary dependencies for implementing the `_split_multiline_prompt` function. Write a Python function `def _split_multiline_prompt( get_prompt_text: _StyleAndTextTuplesCallable, ) -> tuple[ Callable[[], bool], _StyleAndTextTuplesCallable, _StyleAndTextTuplesCallable ]` to solve the following problem: Take a `get_prompt_text` function and return three new functions instead. One that tells whether this prompt consists of multiple lines; one that returns the fragments to be shown on the lines above the input; and another one with the fragments to be shown at the first line of the input. Here is the function: def _split_multiline_prompt( get_prompt_text: _StyleAndTextTuplesCallable, ) -> tuple[ Callable[[], bool], _StyleAndTextTuplesCallable, _StyleAndTextTuplesCallable ]: """ Take a `get_prompt_text` function and return three new functions instead. One that tells whether this prompt consists of multiple lines; one that returns the fragments to be shown on the lines above the input; and another one with the fragments to be shown at the first line of the input. """ def has_before_fragments() -> bool: for fragment, char, *_ in get_prompt_text(): if "\n" in char: return True return False def before() -> StyleAndTextTuples: result: StyleAndTextTuples = [] found_nl = False for fragment, char, *_ in reversed(explode_text_fragments(get_prompt_text())): if found_nl: result.insert(0, (fragment, char)) elif char == "\n": found_nl = True return result def first_input_line() -> StyleAndTextTuples: result: StyleAndTextTuples = [] for fragment, char, *_ in reversed(explode_text_fragments(get_prompt_text())): if char == "\n": break else: result.insert(0, (fragment, char)) return result return has_before_fragments, before, first_input_line
Take a `get_prompt_text` function and return three new functions instead. One that tells whether this prompt consists of multiple lines; one that returns the fragments to be shown on the lines above the input; and another one with the fragments to be shown at the first line of the input.
172,052
from __future__ import annotations from asyncio import FIRST_COMPLETED, Future, ensure_future, sleep, wait from collections import deque from enum import Enum from typing import TYPE_CHECKING, Any, Callable, Deque, Dict, Hashable, Optional, Tuple from prompt_toolkit.application.current import get_app from prompt_toolkit.cursor_shapes import CursorShape from prompt_toolkit.data_structures import Point, Size from prompt_toolkit.filters import FilterOrBool, to_filter from prompt_toolkit.formatted_text import AnyFormattedText, to_formatted_text from prompt_toolkit.layout.mouse_handlers import MouseHandlers from prompt_toolkit.layout.screen import Char, Screen, WritePosition from prompt_toolkit.output import ColorDepth, Output from prompt_toolkit.styles import ( Attrs, BaseStyle, DummyStyleTransformation, StyleTransformation, ) class _StyleStringToAttrsCache(Dict[str, Attrs]): """ A cache structure that maps style strings to :class:`.Attr`. (This is an important speed up.) """ def __init__( self, get_attrs_for_style_str: Callable[[str], Attrs], style_transformation: StyleTransformation, ) -> None: self.get_attrs_for_style_str = get_attrs_for_style_str self.style_transformation = style_transformation def __missing__(self, style_str: str) -> Attrs: attrs = self.get_attrs_for_style_str(style_str) attrs = self.style_transformation.transform_attrs(attrs) self[style_str] = attrs return attrs class _StyleStringHasStyleCache(Dict[str, bool]): """ Cache for remember which style strings don't render the default output style (default fg/bg, no underline and no reverse and no blink). That way we know that we should render these cells, even when they're empty (when they contain a space). Note: we don't consider bold/italic/hidden because they don't change the output if there's no text in the cell. """ def __init__(self, style_string_to_attrs: dict[str, Attrs]) -> None: self.style_string_to_attrs = style_string_to_attrs def __missing__(self, style_str: str) -> bool: attrs = self.style_string_to_attrs[style_str] is_default = bool( attrs.color or attrs.bgcolor or attrs.underline or attrs.strike or attrs.blink or attrs.reverse ) self[style_str] = is_default return is_default Any = object() class Point(NamedTuple): x: int y: int class Size(NamedTuple): rows: int columns: int class Char: """ Represent a single character in a :class:`.Screen`. This should be considered immutable. :param char: A single character (can be a double-width character). :param style: A style string. (Can contain classnames.) """ __slots__ = ("char", "style", "width") # If we end up having one of these special control sequences in the input string, # we should display them as follows: # Usually this happens after a "quoted insert". display_mappings: dict[str, str] = { "\x00": "^@", # Control space "\x01": "^A", "\x02": "^B", "\x03": "^C", "\x04": "^D", "\x05": "^E", "\x06": "^F", "\x07": "^G", "\x08": "^H", "\x09": "^I", "\x0a": "^J", "\x0b": "^K", "\x0c": "^L", "\x0d": "^M", "\x0e": "^N", "\x0f": "^O", "\x10": "^P", "\x11": "^Q", "\x12": "^R", "\x13": "^S", "\x14": "^T", "\x15": "^U", "\x16": "^V", "\x17": "^W", "\x18": "^X", "\x19": "^Y", "\x1a": "^Z", "\x1b": "^[", # Escape "\x1c": "^\\", "\x1d": "^]", "\x1e": "^^", "\x1f": "^_", "\x7f": "^?", # ASCII Delete (backspace). # Special characters. All visualized like Vim does. "\x80": "<80>", "\x81": "<81>", "\x82": "<82>", "\x83": "<83>", "\x84": "<84>", "\x85": "<85>", "\x86": "<86>", "\x87": "<87>", "\x88": "<88>", "\x89": "<89>", "\x8a": "<8a>", "\x8b": "<8b>", "\x8c": "<8c>", "\x8d": "<8d>", "\x8e": "<8e>", "\x8f": "<8f>", "\x90": "<90>", "\x91": "<91>", "\x92": "<92>", "\x93": "<93>", "\x94": "<94>", "\x95": "<95>", "\x96": "<96>", "\x97": "<97>", "\x98": "<98>", "\x99": "<99>", "\x9a": "<9a>", "\x9b": "<9b>", "\x9c": "<9c>", "\x9d": "<9d>", "\x9e": "<9e>", "\x9f": "<9f>", # For the non-breaking space: visualize like Emacs does by default. # (Print a space, but attach the 'nbsp' class that applies the # underline style.) "\xa0": " ", } def __init__(self, char: str = " ", style: str = "") -> None: # If this character has to be displayed otherwise, take that one. if char in self.display_mappings: if char == "\xa0": style += " class:nbsp " # Will be underlined. else: style += " class:control-character " char = self.display_mappings[char] self.char = char self.style = style # Calculate width. (We always need this, so better to store it directly # as a member for performance.) self.width = get_cwidth(char) # In theory, `other` can be any type of object, but because of performance # we don't want to do an `isinstance` check every time. We assume "other" # is always a "Char". def _equal(self, other: Char) -> bool: return self.char == other.char and self.style == other.style def _not_equal(self, other: Char) -> bool: # Not equal: We don't do `not char.__eq__` here, because of the # performance of calling yet another function. return self.char != other.char or self.style != other.style if not TYPE_CHECKING: __eq__ = _equal __ne__ = _not_equal def __repr__(self) -> str: return f"{self.__class__.__name__}({self.char!r}, {self.style!r})" class Screen: """ Two dimensional buffer of :class:`.Char` instances. """ def __init__( self, default_char: Char | None = None, initial_width: int = 0, initial_height: int = 0, ) -> None: if default_char is None: default_char2 = _CHAR_CACHE[" ", Transparent] else: default_char2 = default_char self.data_buffer: DefaultDict[int, DefaultDict[int, Char]] = defaultdict( lambda: defaultdict(lambda: default_char2) ) #: Escape sequences to be injected. self.zero_width_escapes: DefaultDict[int, DefaultDict[int, str]] = defaultdict( lambda: defaultdict(lambda: "") ) #: Position of the cursor. self.cursor_positions: dict[ Window, Point ] = {} # Map `Window` objects to `Point` objects. #: Visibility of the cursor. self.show_cursor = True #: (Optional) Where to position the menu. E.g. at the start of a completion. #: (We can't use the cursor position, because we don't want the #: completion menu to change its position when we browse through all the #: completions.) self.menu_positions: dict[ Window, Point ] = {} # Map `Window` objects to `Point` objects. #: Currently used width/height of the screen. This will increase when #: data is written to the screen. self.width = initial_width or 0 self.height = initial_height or 0 # Windows that have been drawn. (Each `Window` class will add itself to # this list.) self.visible_windows_to_write_positions: dict[Window, WritePosition] = {} # List of (z_index, draw_func) self._draw_float_functions: list[tuple[int, Callable[[], None]]] = [] def visible_windows(self) -> list[Window]: return list(self.visible_windows_to_write_positions.keys()) def set_cursor_position(self, window: Window, position: Point) -> None: """ Set the cursor position for a given window. """ self.cursor_positions[window] = position def set_menu_position(self, window: Window, position: Point) -> None: """ Set the cursor position for a given window. """ self.menu_positions[window] = position def get_cursor_position(self, window: Window) -> Point: """ Get the cursor position for a given window. Returns a `Point`. """ try: return self.cursor_positions[window] except KeyError: return Point(x=0, y=0) def get_menu_position(self, window: Window) -> Point: """ Get the menu position for a given window. (This falls back to the cursor position if no menu position was set.) """ try: return self.menu_positions[window] except KeyError: try: return self.cursor_positions[window] except KeyError: return Point(x=0, y=0) def draw_with_z_index(self, z_index: int, draw_func: Callable[[], None]) -> None: """ Add a draw-function for a `Window` which has a >= 0 z_index. This will be postponed until `draw_all_floats` is called. """ self._draw_float_functions.append((z_index, draw_func)) def draw_all_floats(self) -> None: """ Draw all float functions in order of z-index. """ # We keep looping because some draw functions could add new functions # to this list. See `FloatContainer`. while self._draw_float_functions: # Sort the floats that we have so far by z_index. functions = sorted(self._draw_float_functions, key=lambda item: item[0]) # Draw only one at a time, then sort everything again. Now floats # might have been added. self._draw_float_functions = functions[1:] functions[0][1]() def append_style_to_content(self, style_str: str) -> None: """ For all the characters in the screen. Set the style string to the given `style_str`. """ b = self.data_buffer char_cache = _CHAR_CACHE append_style = " " + style_str for y, row in b.items(): for x, char in row.items(): row[x] = char_cache[char.char, char.style + append_style] def fill_area( self, write_position: WritePosition, style: str = "", after: bool = False ) -> None: """ Fill the content of this area, using the given `style`. The style is prepended before whatever was here before. """ if not style.strip(): return xmin = write_position.xpos xmax = write_position.xpos + write_position.width char_cache = _CHAR_CACHE data_buffer = self.data_buffer if after: append_style = " " + style prepend_style = "" else: append_style = "" prepend_style = style + " " for y in range( write_position.ypos, write_position.ypos + write_position.height ): row = data_buffer[y] for x in range(xmin, xmax): cell = row[x] row[x] = char_cache[ cell.char, prepend_style + cell.style + append_style ] The provided code snippet includes necessary dependencies for implementing the `_output_screen_diff` function. Write a Python function `def _output_screen_diff( app: Application[Any], output: Output, screen: Screen, current_pos: Point, color_depth: ColorDepth, previous_screen: Screen | None, last_style: str | None, is_done: bool, # XXX: drop is_done full_screen: bool, attrs_for_style_string: _StyleStringToAttrsCache, style_string_has_style: _StyleStringHasStyleCache, size: Size, previous_width: int, ) -> tuple[Point, str | None]` to solve the following problem: Render the diff between this screen and the previous screen. This takes two `Screen` instances. The one that represents the output like it was during the last rendering and one that represents the current output raster. Looking at these two `Screen` instances, this function will render the difference by calling the appropriate methods of the `Output` object that only paint the changes to the terminal. This is some performance-critical code which is heavily optimized. Don't change things without profiling first. :param current_pos: Current cursor position. :param last_style: The style string, used for drawing the last drawn character. (Color/attributes.) :param attrs_for_style_string: :class:`._StyleStringToAttrsCache` instance. :param width: The width of the terminal. :param previous_width: The width of the terminal during the last rendering. Here is the function: def _output_screen_diff( app: Application[Any], output: Output, screen: Screen, current_pos: Point, color_depth: ColorDepth, previous_screen: Screen | None, last_style: str | None, is_done: bool, # XXX: drop is_done full_screen: bool, attrs_for_style_string: _StyleStringToAttrsCache, style_string_has_style: _StyleStringHasStyleCache, size: Size, previous_width: int, ) -> tuple[Point, str | None]: """ Render the diff between this screen and the previous screen. This takes two `Screen` instances. The one that represents the output like it was during the last rendering and one that represents the current output raster. Looking at these two `Screen` instances, this function will render the difference by calling the appropriate methods of the `Output` object that only paint the changes to the terminal. This is some performance-critical code which is heavily optimized. Don't change things without profiling first. :param current_pos: Current cursor position. :param last_style: The style string, used for drawing the last drawn character. (Color/attributes.) :param attrs_for_style_string: :class:`._StyleStringToAttrsCache` instance. :param width: The width of the terminal. :param previous_width: The width of the terminal during the last rendering. """ width, height = size.columns, size.rows #: Variable for capturing the output. write = output.write write_raw = output.write_raw # Create locals for the most used output methods. # (Save expensive attribute lookups.) _output_set_attributes = output.set_attributes _output_reset_attributes = output.reset_attributes _output_cursor_forward = output.cursor_forward _output_cursor_up = output.cursor_up _output_cursor_backward = output.cursor_backward # Hide cursor before rendering. (Avoid flickering.) output.hide_cursor() def reset_attributes() -> None: "Wrapper around Output.reset_attributes." nonlocal last_style _output_reset_attributes() last_style = None # Forget last char after resetting attributes. def move_cursor(new: Point) -> Point: "Move cursor to this `new` point. Returns the given Point." current_x, current_y = current_pos.x, current_pos.y if new.y > current_y: # Use newlines instead of CURSOR_DOWN, because this might add new lines. # CURSOR_DOWN will never create new lines at the bottom. # Also reset attributes, otherwise the newline could draw a # background color. reset_attributes() write("\r\n" * (new.y - current_y)) current_x = 0 _output_cursor_forward(new.x) return new elif new.y < current_y: _output_cursor_up(current_y - new.y) if current_x >= width - 1: write("\r") _output_cursor_forward(new.x) elif new.x < current_x or current_x >= width - 1: _output_cursor_backward(current_x - new.x) elif new.x > current_x: _output_cursor_forward(new.x - current_x) return new def output_char(char: Char) -> None: """ Write the output of this character. """ nonlocal last_style # If the last printed character has the same style, don't output the # style again. if last_style == char.style: write(char.char) else: # Look up `Attr` for this style string. Only set attributes if different. # (Two style strings can still have the same formatting.) # Note that an empty style string can have formatting that needs to # be applied, because of style transformations. new_attrs = attrs_for_style_string[char.style] if not last_style or new_attrs != attrs_for_style_string[last_style]: _output_set_attributes(new_attrs, color_depth) write(char.char) last_style = char.style def get_max_column_index(row: dict[int, Char]) -> int: """ Return max used column index, ignoring whitespace (without style) at the end of the line. This is important for people that copy/paste terminal output. There are two reasons we are sometimes seeing whitespace at the end: - `BufferControl` adds a trailing space to each line, because it's a possible cursor position, so that the line wrapping won't change if the cursor position moves around. - The `Window` adds a style class to the current line for highlighting (cursor-line). """ numbers = ( index for index, cell in row.items() if cell.char != " " or style_string_has_style[cell.style] ) return max(numbers, default=0) # Render for the first time: reset styling. if not previous_screen: reset_attributes() # Disable autowrap. (When entering a the alternate screen, or anytime when # we have a prompt. - In the case of a REPL, like IPython, people can have # background threads, and it's hard for debugging if their output is not # wrapped.) if not previous_screen or not full_screen: output.disable_autowrap() # When the previous screen has a different size, redraw everything anyway. # Also when we are done. (We might take up less rows, so clearing is important.) if ( is_done or not previous_screen or previous_width != width ): # XXX: also consider height?? current_pos = move_cursor(Point(x=0, y=0)) reset_attributes() output.erase_down() previous_screen = Screen() # Get height of the screen. # (height changes as we loop over data_buffer, so remember the current value.) # (Also make sure to clip the height to the size of the output.) current_height = min(screen.height, height) # Loop over the rows. row_count = min(max(screen.height, previous_screen.height), height) for y in range(row_count): new_row = screen.data_buffer[y] previous_row = previous_screen.data_buffer[y] zero_width_escapes_row = screen.zero_width_escapes[y] new_max_line_len = min(width - 1, get_max_column_index(new_row)) previous_max_line_len = min(width - 1, get_max_column_index(previous_row)) # Loop over the columns. c = 0 # Column counter. while c <= new_max_line_len: new_char = new_row[c] old_char = previous_row[c] char_width = new_char.width or 1 # When the old and new character at this position are different, # draw the output. (Because of the performance, we don't call # `Char.__ne__`, but inline the same expression.) if new_char.char != old_char.char or new_char.style != old_char.style: current_pos = move_cursor(Point(x=c, y=y)) # Send injected escape sequences to output. if c in zero_width_escapes_row: write_raw(zero_width_escapes_row[c]) output_char(new_char) current_pos = Point(x=current_pos.x + char_width, y=current_pos.y) c += char_width # If the new line is shorter, trim it. if previous_screen and new_max_line_len < previous_max_line_len: current_pos = move_cursor(Point(x=new_max_line_len + 1, y=y)) reset_attributes() output.erase_end_of_line() # Correctly reserve vertical space as required by the layout. # When this is a new screen (drawn for the first time), or for some reason # higher than the previous one. Move the cursor once to the bottom of the # output. That way, we're sure that the terminal scrolls up, even when the # lower lines of the canvas just contain whitespace. # The most obvious reason that we actually want this behaviour is the avoid # the artifact of the input scrolling when the completion menu is shown. # (If the scrolling is actually wanted, the layout can still be build in a # way to behave that way by setting a dynamic height.) if current_height > previous_screen.height: current_pos = move_cursor(Point(x=0, y=current_height - 1)) # Move cursor: if is_done: current_pos = move_cursor(Point(x=0, y=current_height)) output.erase_down() else: current_pos = move_cursor(screen.get_cursor_position(app.layout.current_window)) if is_done or not full_screen: output.enable_autowrap() # Always reset the color attributes. This is important because a background # thread could print data to stdout and we want that to be displayed in the # default colors. (Also, if a background color has been set, many terminals # give weird artifacts on resize events.) reset_attributes() if screen.show_cursor or is_done: output.show_cursor() return current_pos, last_style
Render the diff between this screen and the previous screen. This takes two `Screen` instances. The one that represents the output like it was during the last rendering and one that represents the current output raster. Looking at these two `Screen` instances, this function will render the difference by calling the appropriate methods of the `Output` object that only paint the changes to the terminal. This is some performance-critical code which is heavily optimized. Don't change things without profiling first. :param current_pos: Current cursor position. :param last_style: The style string, used for drawing the last drawn character. (Color/attributes.) :param attrs_for_style_string: :class:`._StyleStringToAttrsCache` instance. :param width: The width of the terminal. :param previous_width: The width of the terminal during the last rendering.
172,053
from __future__ import annotations from asyncio import FIRST_COMPLETED, Future, ensure_future, sleep, wait from collections import deque from enum import Enum from typing import TYPE_CHECKING, Any, Callable, Deque, Dict, Hashable, Optional, Tuple from prompt_toolkit.application.current import get_app from prompt_toolkit.cursor_shapes import CursorShape from prompt_toolkit.data_structures import Point, Size from prompt_toolkit.filters import FilterOrBool, to_filter from prompt_toolkit.formatted_text import AnyFormattedText, to_formatted_text from prompt_toolkit.layout.mouse_handlers import MouseHandlers from prompt_toolkit.layout.screen import Char, Screen, WritePosition from prompt_toolkit.output import ColorDepth, Output from prompt_toolkit.styles import ( Attrs, BaseStyle, DummyStyleTransformation, StyleTransformation, ) class _StyleStringToAttrsCache(Dict[str, Attrs]): """ A cache structure that maps style strings to :class:`.Attr`. (This is an important speed up.) """ def __init__( self, get_attrs_for_style_str: Callable[[str], Attrs], style_transformation: StyleTransformation, ) -> None: self.get_attrs_for_style_str = get_attrs_for_style_str self.style_transformation = style_transformation def __missing__(self, style_str: str) -> Attrs: attrs = self.get_attrs_for_style_str(style_str) attrs = self.style_transformation.transform_attrs(attrs) self[style_str] = attrs return attrs The provided code snippet includes necessary dependencies for implementing the `print_formatted_text` function. Write a Python function `def print_formatted_text( output: Output, formatted_text: AnyFormattedText, style: BaseStyle, style_transformation: StyleTransformation | None = None, color_depth: ColorDepth | None = None, ) -> None` to solve the following problem: Print a list of (style_str, text) tuples in the given style to the output. Here is the function: def print_formatted_text( output: Output, formatted_text: AnyFormattedText, style: BaseStyle, style_transformation: StyleTransformation | None = None, color_depth: ColorDepth | None = None, ) -> None: """ Print a list of (style_str, text) tuples in the given style to the output. """ fragments = to_formatted_text(formatted_text) style_transformation = style_transformation or DummyStyleTransformation() color_depth = color_depth or output.get_default_color_depth() # Reset first. output.reset_attributes() output.enable_autowrap() last_attrs: Attrs | None = None # Print all (style_str, text) tuples. attrs_for_style_string = _StyleStringToAttrsCache( style.get_attrs_for_style_str, style_transformation ) for style_str, text, *_ in fragments: attrs = attrs_for_style_string[style_str] # Set style attributes if something changed. if attrs != last_attrs: if attrs: output.set_attributes(attrs, color_depth) else: output.reset_attributes() last_attrs = attrs # Print escape sequences as raw output if "[ZeroWidthEscape]" in style_str: output.write_raw(text) else: # Eliminate carriage returns text = text.replace("\r", "") # Insert a carriage return before every newline (important when the # front-end is a telnet client). text = text.replace("\n", "\r\n") output.write(text) # Reset again. output.reset_attributes() output.flush()
Print a list of (style_str, text) tuples in the given style to the output.
172,054
from __future__ import annotations import sys from ctypes import pointer from ..utils import SPHINX_AUTODOC_RUNNING from ctypes.wintypes import BOOL, DWORD, HANDLE from typing import List, Optional from prompt_toolkit.win32_types import SECURITY_ATTRIBUTES WAIT_TIMEOUT = 0x00000102 INFINITE = -1 The provided code snippet includes necessary dependencies for implementing the `wait_for_handles` function. Write a Python function `def wait_for_handles(handles: list[HANDLE], timeout: int = INFINITE) -> HANDLE | None` to solve the following problem: Waits for multiple handles. (Similar to 'select') Returns the handle which is ready. Returns `None` on timeout. http://msdn.microsoft.com/en-us/library/windows/desktop/ms687025(v=vs.85).aspx Note that handles should be a list of `HANDLE` objects, not integers. See this comment in the patch by @quark-zju for the reason why: ''' Make sure HANDLE on Windows has a correct size Previously, the type of various HANDLEs are native Python integer types. The ctypes library will treat them as 4-byte integer when used in function arguments. On 64-bit Windows, HANDLE is 8-byte and usually a small integer. Depending on whether the extra 4 bytes are zero-ed out or not, things can happen to work, or break. ''' This function returns either `None` or one of the given `HANDLE` objects. (The return value can be tested with the `is` operator.) Here is the function: def wait_for_handles(handles: list[HANDLE], timeout: int = INFINITE) -> HANDLE | None: """ Waits for multiple handles. (Similar to 'select') Returns the handle which is ready. Returns `None` on timeout. http://msdn.microsoft.com/en-us/library/windows/desktop/ms687025(v=vs.85).aspx Note that handles should be a list of `HANDLE` objects, not integers. See this comment in the patch by @quark-zju for the reason why: ''' Make sure HANDLE on Windows has a correct size Previously, the type of various HANDLEs are native Python integer types. The ctypes library will treat them as 4-byte integer when used in function arguments. On 64-bit Windows, HANDLE is 8-byte and usually a small integer. Depending on whether the extra 4 bytes are zero-ed out or not, things can happen to work, or break. ''' This function returns either `None` or one of the given `HANDLE` objects. (The return value can be tested with the `is` operator.) """ arrtype = HANDLE * len(handles) handle_array = arrtype(*handles) ret: int = windll.kernel32.WaitForMultipleObjects( len(handle_array), handle_array, BOOL(False), DWORD(timeout) ) if ret == WAIT_TIMEOUT: return None else: return handles[ret]
Waits for multiple handles. (Similar to 'select') Returns the handle which is ready. Returns `None` on timeout. http://msdn.microsoft.com/en-us/library/windows/desktop/ms687025(v=vs.85).aspx Note that handles should be a list of `HANDLE` objects, not integers. See this comment in the patch by @quark-zju for the reason why: ''' Make sure HANDLE on Windows has a correct size Previously, the type of various HANDLEs are native Python integer types. The ctypes library will treat them as 4-byte integer when used in function arguments. On 64-bit Windows, HANDLE is 8-byte and usually a small integer. Depending on whether the extra 4 bytes are zero-ed out or not, things can happen to work, or break. ''' This function returns either `None` or one of the given `HANDLE` objects. (The return value can be tested with the `is` operator.)
172,055
from __future__ import annotations import sys from ctypes import pointer from ..utils import SPHINX_AUTODOC_RUNNING from ctypes.wintypes import BOOL, DWORD, HANDLE from typing import List, Optional from prompt_toolkit.win32_types import SECURITY_ATTRIBUTES class SECURITY_ATTRIBUTES(Structure): """ http://msdn.microsoft.com/en-us/library/windows/desktop/aa379560(v=vs.85).aspx """ if TYPE_CHECKING: nLength: int lpSecurityDescriptor: int bInheritHandle: int # BOOL comes back as 'int'. _fields_ = [ ("nLength", DWORD), ("lpSecurityDescriptor", LPVOID), ("bInheritHandle", BOOL), ] The provided code snippet includes necessary dependencies for implementing the `create_win32_event` function. Write a Python function `def create_win32_event() -> HANDLE` to solve the following problem: Creates a Win32 unnamed Event . http://msdn.microsoft.com/en-us/library/windows/desktop/ms682396(v=vs.85).aspx Here is the function: def create_win32_event() -> HANDLE: """ Creates a Win32 unnamed Event . http://msdn.microsoft.com/en-us/library/windows/desktop/ms682396(v=vs.85).aspx """ return HANDLE( windll.kernel32.CreateEventA( pointer(SECURITY_ATTRIBUTES()), BOOL(True), # Manual reset event. BOOL(False), # Initial state. None, # Unnamed event object. ) )
Creates a Win32 unnamed Event . http://msdn.microsoft.com/en-us/library/windows/desktop/ms682396(v=vs.85).aspx
172,056
from __future__ import annotations import asyncio import contextvars import sys import time from asyncio import get_running_loop from types import TracebackType from typing import Any, Awaitable, Callable, Dict, Optional, TypeVar, cast class Callable(BaseTypingInstance): def py__call__(self, arguments): """ def x() -> Callable[[Callable[..., _T]], _T]: ... """ # The 0th index are the arguments. try: param_values = self._generics_manager[0] result_values = self._generics_manager[1] except IndexError: debug.warning('Callable[...] defined without two arguments') return NO_VALUES else: from jedi.inference.gradual.annotation import infer_return_for_callable return infer_return_for_callable(arguments, param_values, result_values) def py__get__(self, instance, class_value): return ValueSet([self]) The provided code snippet includes necessary dependencies for implementing the `call_soon_threadsafe` function. Write a Python function `def call_soon_threadsafe( func: Callable[[], None], max_postpone_time: float | None = None, loop: asyncio.AbstractEventLoop | None = None, ) -> None` to solve the following problem: Wrapper around asyncio's `call_soon_threadsafe`. This takes a `max_postpone_time` which can be used to tune the urgency of the method. Asyncio runs tasks in first-in-first-out. However, this is not what we want for the render function of the prompt_toolkit UI. Rendering is expensive, but since the UI is invalidated very often, in some situations we render the UI too often, so much that the rendering CPU usage slows down the rest of the processing of the application. (Pymux is an example where we have to balance the CPU time spend on rendering the UI, and parsing process output.) However, we want to set a deadline value, for when the rendering should happen. (The UI should stay responsive). Here is the function: def call_soon_threadsafe( func: Callable[[], None], max_postpone_time: float | None = None, loop: asyncio.AbstractEventLoop | None = None, ) -> None: """ Wrapper around asyncio's `call_soon_threadsafe`. This takes a `max_postpone_time` which can be used to tune the urgency of the method. Asyncio runs tasks in first-in-first-out. However, this is not what we want for the render function of the prompt_toolkit UI. Rendering is expensive, but since the UI is invalidated very often, in some situations we render the UI too often, so much that the rendering CPU usage slows down the rest of the processing of the application. (Pymux is an example where we have to balance the CPU time spend on rendering the UI, and parsing process output.) However, we want to set a deadline value, for when the rendering should happen. (The UI should stay responsive). """ loop2 = loop or get_running_loop() # If no `max_postpone_time` has been given, schedule right now. if max_postpone_time is None: loop2.call_soon_threadsafe(func) return max_postpone_until = time.time() + max_postpone_time def schedule() -> None: # When there are no other tasks scheduled in the event loop. Run it # now. # Notice: uvloop doesn't have this _ready attribute. In that case, # always call immediately. if not getattr(loop2, "_ready", []): func() return # If the timeout expired, run this now. if time.time() > max_postpone_until: func() return # Schedule again for later. loop2.call_soon_threadsafe(schedule) loop2.call_soon_threadsafe(schedule)
Wrapper around asyncio's `call_soon_threadsafe`. This takes a `max_postpone_time` which can be used to tune the urgency of the method. Asyncio runs tasks in first-in-first-out. However, this is not what we want for the render function of the prompt_toolkit UI. Rendering is expensive, but since the UI is invalidated very often, in some situations we render the UI too often, so much that the rendering CPU usage slows down the rest of the processing of the application. (Pymux is an example where we have to balance the CPU time spend on rendering the UI, and parsing process output.) However, we want to set a deadline value, for when the rendering should happen. (The UI should stay responsive).
172,057
from __future__ import annotations import asyncio import contextvars import sys import time from asyncio import get_running_loop from types import TracebackType from typing import Any, Awaitable, Callable, Dict, Optional, TypeVar, cast class TracebackType: if sys.version_info >= (3, 7): def __init__(self, tb_next: Optional[TracebackType], tb_frame: FrameType, tb_lasti: int, tb_lineno: int) -> None: ... tb_next: Optional[TracebackType] else: def tb_next(self) -> Optional[TracebackType]: ... # the rest are read-only even in 3.7 def tb_frame(self) -> FrameType: ... def tb_lasti(self) -> int: ... def tb_lineno(self) -> int: ... Any = object() def cast(typ: Type[_T], val: Any) -> _T: ... def cast(typ: str, val: Any) -> Any: ... def cast(typ: object, val: Any) -> Any: ... The provided code snippet includes necessary dependencies for implementing the `get_traceback_from_context` function. Write a Python function `def get_traceback_from_context(context: dict[str, Any]) -> TracebackType | None` to solve the following problem: Get the traceback object from the context. Here is the function: def get_traceback_from_context(context: dict[str, Any]) -> TracebackType | None: """ Get the traceback object from the context. """ exception = context.get("exception") if exception: if hasattr(exception, "__traceback__"): return cast(TracebackType, exception.__traceback__) else: # call_exception_handler() is usually called indirectly # from an except block. If it's not the case, the traceback # is undefined... return sys.exc_info()[2] return None
Get the traceback object from the context.
172,058
from __future__ import annotations from asyncio import get_running_loop from contextlib import asynccontextmanager from queue import Empty, Full, Queue from typing import Any, AsyncGenerator, Callable, Iterable, TypeVar, Union from .utils import run_in_executor_with_context _T_Generator = TypeVar("_T_Generator", bound=AsyncGenerator[Any, None]) class AsyncGenerator(AsyncIterator[_T_co], Generic[_T_co, _T_contra]): def __anext__(self) -> Awaitable[_T_co]: ... def asend(self, __value: _T_contra) -> Awaitable[_T_co]: ... def athrow( self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ... ) -> Awaitable[_T_co]: ... def athrow(self, __typ: BaseException, __val: None = ..., __tb: Optional[TracebackType] = ...) -> Awaitable[_T_co]: ... def aclose(self) -> Awaitable[None]: ... def __aiter__(self) -> AsyncGenerator[_T_co, _T_contra]: ... def ag_await(self) -> Any: ... def ag_code(self) -> CodeType: ... def ag_frame(self) -> FrameType: ... def ag_running(self) -> bool: ... The provided code snippet includes necessary dependencies for implementing the `aclosing` function. Write a Python function `async def aclosing( thing: _T_Generator, ) -> AsyncGenerator[_T_Generator, None]` to solve the following problem: Similar to `contextlib.aclosing`, in Python 3.10. Here is the function: async def aclosing( thing: _T_Generator, ) -> AsyncGenerator[_T_Generator, None]: "Similar to `contextlib.aclosing`, in Python 3.10." try: yield thing finally: await thing.aclose()
Similar to `contextlib.aclosing`, in Python 3.10.
172,059
from __future__ import annotations from asyncio import get_running_loop from contextlib import asynccontextmanager from queue import Empty, Full, Queue from typing import Any, AsyncGenerator, Callable, Iterable, TypeVar, Union from .utils import run_in_executor_with_context DEFAULT_BUFFER_SIZE: int = 1000 _T = TypeVar("_T") class _Done: pass class Empty(Exception): ... class Full(Exception): ... class Queue(Generic[_T]): maxsize: int mutex: Lock # undocumented not_empty: Condition # undocumented not_full: Condition # undocumented all_tasks_done: Condition # undocumented unfinished_tasks: int # undocumented queue: Any # undocumented def __init__(self, maxsize: int = ...) -> None: ... def _init(self, maxsize: int) -> None: ... def empty(self) -> bool: ... def full(self) -> bool: ... def get(self, block: bool = ..., timeout: Optional[float] = ...) -> _T: ... def get_nowait(self) -> _T: ... def _get(self) -> _T: ... def put(self, item: _T, block: bool = ..., timeout: Optional[float] = ...) -> None: ... def put_nowait(self, item: _T) -> None: ... def _put(self, item: _T) -> None: ... def join(self) -> None: ... def qsize(self) -> int: ... def _qsize(self) -> int: ... def task_done(self) -> None: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... class Iterable(Protocol[_T_co]): def __iter__(self) -> Iterator[_T_co]: ... class AsyncGenerator(AsyncIterator[_T_co], Generic[_T_co, _T_contra]): def __anext__(self) -> Awaitable[_T_co]: ... def asend(self, __value: _T_contra) -> Awaitable[_T_co]: ... def athrow( self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ... ) -> Awaitable[_T_co]: ... def athrow(self, __typ: BaseException, __val: None = ..., __tb: Optional[TracebackType] = ...) -> Awaitable[_T_co]: ... def aclose(self) -> Awaitable[None]: ... def __aiter__(self) -> AsyncGenerator[_T_co, _T_contra]: ... def ag_await(self) -> Any: ... def ag_code(self) -> CodeType: ... def ag_frame(self) -> FrameType: ... def ag_running(self) -> bool: ... class Callable(BaseTypingInstance): def py__call__(self, arguments): """ def x() -> Callable[[Callable[..., _T]], _T]: ... """ # The 0th index are the arguments. try: param_values = self._generics_manager[0] result_values = self._generics_manager[1] except IndexError: debug.warning('Callable[...] defined without two arguments') return NO_VALUES else: from jedi.inference.gradual.annotation import infer_return_for_callable return infer_return_for_callable(arguments, param_values, result_values) def py__get__(self, instance, class_value): return ValueSet([self]) def run_in_executor_with_context( func: Callable[..., _T], *args: Any, loop: asyncio.AbstractEventLoop | None = None, ) -> Awaitable[_T]: """ Run a function in an executor, but make sure it uses the same contextvars. This is required so that the function will see the right application. See also: https://bugs.python.org/issue34014 """ loop = loop or get_running_loop() ctx: contextvars.Context = contextvars.copy_context() return loop.run_in_executor(None, ctx.run, func, *args) The provided code snippet includes necessary dependencies for implementing the `generator_to_async_generator` function. Write a Python function `async def generator_to_async_generator( get_iterable: Callable[[], Iterable[_T]], buffer_size: int = DEFAULT_BUFFER_SIZE, ) -> AsyncGenerator[_T, None]` to solve the following problem: Turn a generator or iterable into an async generator. This works by running the generator in a background thread. :param get_iterable: Function that returns a generator or iterable when called. :param buffer_size: Size of the queue between the async consumer and the synchronous generator that produces items. Here is the function: async def generator_to_async_generator( get_iterable: Callable[[], Iterable[_T]], buffer_size: int = DEFAULT_BUFFER_SIZE, ) -> AsyncGenerator[_T, None]: """ Turn a generator or iterable into an async generator. This works by running the generator in a background thread. :param get_iterable: Function that returns a generator or iterable when called. :param buffer_size: Size of the queue between the async consumer and the synchronous generator that produces items. """ quitting = False # NOTE: We are limiting the queue size in order to have back-pressure. q: Queue[_T | _Done] = Queue(maxsize=buffer_size) loop = get_running_loop() def runner() -> None: """ Consume the generator in background thread. When items are received, they'll be pushed to the queue. """ try: for item in get_iterable(): # When this async generator was cancelled (closed), stop this # thread. if quitting: return while True: try: q.put(item, timeout=1) except Full: if quitting: return continue else: break finally: while True: try: q.put(_Done(), timeout=1) except Full: if quitting: return continue else: break # Start background thread. runner_f = run_in_executor_with_context(runner) try: while True: try: item = q.get_nowait() except Empty: item = await loop.run_in_executor(None, q.get) if isinstance(item, _Done): break else: yield item finally: # When this async generator is closed (GeneratorExit exception, stop # the background thread as well. - we don't need that anymore.) quitting = True # Wait for the background thread to finish. (should happen right after # the last item is yielded). await runner_f
Turn a generator or iterable into an async generator. This works by running the generator in a background thread. :param get_iterable: Function that returns a generator or iterable when called. :param buffer_size: Size of the queue between the async consumer and the synchronous generator that produces items.
172,060
from __future__ import annotations import asyncio import os import select import selectors import sys import threading from asyncio import AbstractEventLoop, get_running_loop from selectors import BaseSelector, SelectorKey from typing import TYPE_CHECKING, Any, Callable, List, Mapping, Optional, Tuple def new_eventloop_with_inputhook( inputhook: Callable[[InputHookContext], None] ) -> AbstractEventLoop: """ Create a new event loop with the given inputhook. """ selector = InputHookSelector(selectors.DefaultSelector(), inputhook) loop = asyncio.SelectorEventLoop(selector) return loop class InputHookContext: """ Given as a parameter to the inputhook. """ def __init__(self, fileno: int, input_is_ready: Callable[[], bool]) -> None: self._fileno = fileno self.input_is_ready = input_is_ready def fileno(self) -> int: return self._fileno class Callable(BaseTypingInstance): def py__call__(self, arguments): """ def x() -> Callable[[Callable[..., _T]], _T]: ... """ # The 0th index are the arguments. try: param_values = self._generics_manager[0] result_values = self._generics_manager[1] except IndexError: debug.warning('Callable[...] defined without two arguments') return NO_VALUES else: from jedi.inference.gradual.annotation import infer_return_for_callable return infer_return_for_callable(arguments, param_values, result_values) def py__get__(self, instance, class_value): return ValueSet([self]) The provided code snippet includes necessary dependencies for implementing the `set_eventloop_with_inputhook` function. Write a Python function `def set_eventloop_with_inputhook( inputhook: Callable[[InputHookContext], None] ) -> AbstractEventLoop` to solve the following problem: Create a new event loop with the given inputhook, and activate it. Here is the function: def set_eventloop_with_inputhook( inputhook: Callable[[InputHookContext], None] ) -> AbstractEventLoop: """ Create a new event loop with the given inputhook, and activate it. """ loop = new_eventloop_with_inputhook(inputhook) asyncio.set_event_loop(loop) return loop
Create a new event loop with the given inputhook, and activate it.
172,061
from __future__ import annotations from collections import deque from functools import wraps from typing import Any, Callable, Deque, Dict, Generic, Hashable, Tuple, TypeVar, cast class SimpleCache(Generic[_T, _U]): """ Very simple cache that discards the oldest item when the cache size is exceeded. :param maxsize: Maximum size of the cache. (Don't make it too big.) """ def __init__(self, maxsize: int = 8) -> None: assert maxsize > 0 self._data: dict[_T, _U] = {} self._keys: Deque[_T] = deque() self.maxsize: int = maxsize def get(self, key: _T, getter_func: Callable[[], _U]) -> _U: """ Get object from the cache. If not found, call `getter_func` to resolve it, and put that on the top of the cache instead. """ # Look in cache first. try: return self._data[key] except KeyError: # Not found? Get it. value = getter_func() self._data[key] = value self._keys.append(key) # Remove the oldest key when the size is exceeded. if len(self._data) > self.maxsize: key_to_remove = self._keys.popleft() if key_to_remove in self._data: del self._data[key_to_remove] return value def clear(self) -> None: "Clear cache." self._data = {} self._keys = deque() _F = TypeVar("_F", bound=Callable[..., object]) def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> Callable[[_T], _T]: ... Any = object() class Hashable(Protocol, metaclass=ABCMeta): # TODO: This is special, in that a subclass of a hashable class may not be hashable # (for example, list vs. object). It's not obvious how to represent this. This class # is currently mostly useless for static checking. def __hash__(self) -> int: ... def cast(typ: Type[_T], val: Any) -> _T: ... def cast(typ: str, val: Any) -> Any: ... def cast(typ: object, val: Any) -> Any: ... class Callable(BaseTypingInstance): def py__call__(self, arguments): """ def x() -> Callable[[Callable[..., _T]], _T]: ... """ # The 0th index are the arguments. try: param_values = self._generics_manager[0] result_values = self._generics_manager[1] except IndexError: debug.warning('Callable[...] defined without two arguments') return NO_VALUES else: from jedi.inference.gradual.annotation import infer_return_for_callable return infer_return_for_callable(arguments, param_values, result_values) def py__get__(self, instance, class_value): return ValueSet([self]) The provided code snippet includes necessary dependencies for implementing the `memoized` function. Write a Python function `def memoized(maxsize: int = 1024) -> Callable[[_F], _F]` to solve the following problem: Memoization decorator for immutable classes and pure functions. Here is the function: def memoized(maxsize: int = 1024) -> Callable[[_F], _F]: """ Memoization decorator for immutable classes and pure functions. """ def decorator(obj: _F) -> _F: cache: SimpleCache[Hashable, Any] = SimpleCache(maxsize=maxsize) @wraps(obj) def new_callable(*a: Any, **kw: Any) -> Any: def create_new() -> Any: return obj(*a, **kw) key = (a, tuple(sorted(kw.items()))) return cache.get(key, create_new) return cast(_F, new_callable) return decorator
Memoization decorator for immutable classes and pure functions.
172,062
from __future__ import annotations import errno import os import sys from contextlib import contextmanager from typing import IO, Iterator, TextIO def _blocking_io(io: IO[str]) -> Iterator[None]: """ Ensure that the FD for `io` is set to blocking in here. """ if sys.platform == "win32": # On Windows, the `os` module doesn't have a `get/set_blocking` # function. yield return try: fd = io.fileno() blocking = os.get_blocking(fd) except: # noqa # Failed somewhere. # `get_blocking` can raise `OSError`. # The io object can raise `AttributeError` when no `fileno()` method is # present if we're not a real file object. blocking = True # Assume we're good, and don't do anything. try: # Make blocking if we weren't blocking yet. if not blocking: os.set_blocking(fd, True) yield finally: # Restore original blocking mode. if not blocking: os.set_blocking(fd, blocking) class TextIO(IO[str]): # TODO use abstractproperty def buffer(self) -> BinaryIO: ... def encoding(self) -> str: ... def errors(self) -> Optional[str]: ... def line_buffering(self) -> int: ... # int on PyPy, bool on CPython def newlines(self) -> Any: ... # None, str or tuple def __enter__(self) -> TextIO: ... def flush_stdout(stdout: TextIO, data: str) -> None: # If the IO object has an `encoding` and `buffer` attribute, it means that # we can access the underlying BinaryIO object and write into it in binary # mode. This is preferred if possible. # NOTE: When used in a Jupyter notebook, don't write binary. # `ipykernel.iostream.OutStream` has an `encoding` attribute, but not # a `buffer` attribute, so we can't write binary in it. has_binary_io = hasattr(stdout, "encoding") and hasattr(stdout, "buffer") try: # Ensure that `stdout` is made blocking when writing into it. # Otherwise, when uvloop is activated (which makes stdout # non-blocking), and we write big amounts of text, then we get a # `BlockingIOError` here. with _blocking_io(stdout): # (We try to encode ourself, because that way we can replace # characters that don't exist in the character set, avoiding # UnicodeEncodeError crashes. E.g. u'\xb7' does not appear in 'ascii'.) # My Arch Linux installation of july 2015 reported 'ANSI_X3.4-1968' # for sys.stdout.encoding in xterm. if has_binary_io: stdout.buffer.write(data.encode(stdout.encoding or "utf-8", "replace")) else: stdout.write(data) stdout.flush() except OSError as e: if e.args and e.args[0] == errno.EINTR: # Interrupted system call. Can happen in case of a window # resize signal. (Just ignore. The resize handler will render # again anyway.) pass elif e.args and e.args[0] == 0: # This can happen when there is a lot of output and the user # sends a KeyboardInterrupt by pressing Control-C. E.g. in # a Python REPL when we execute "while True: print('test')". # (The `ptpython` REPL uses this `Output` class instead of # `stdout` directly -- in order to be network transparent.) # So, just ignore. pass else: raise
null
172,063
from __future__ import annotations import sys import os from ctypes import ArgumentError, byref, c_char, c_long, c_uint, c_ulong, pointer from ..utils import SPHINX_AUTODOC_RUNNING from ctypes.wintypes import DWORD, HANDLE from typing import Callable, Dict, List, Optional, TextIO, Tuple, Type, TypeVar, Union from prompt_toolkit.cursor_shapes import CursorShape from prompt_toolkit.data_structures import Size from prompt_toolkit.styles import ANSI_COLOR_NAMES, Attrs from prompt_toolkit.utils import get_cwidth from prompt_toolkit.win32_types import ( CONSOLE_SCREEN_BUFFER_INFO, COORD, SMALL_RECT, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, ) from .base import Output from .color_depth import ColorDepth class COORD(Structure): """ Struct in wincon.h http://msdn.microsoft.com/en-us/library/windows/desktop/ms682119(v=vs.85).aspx """ if TYPE_CHECKING: X: int Y: int _fields_ = [ ("X", c_short), # Short ("Y", c_short), # Short ] def __repr__(self) -> str: return "{}(X={!r}, Y={!r}, type_x={!r}, type_y={!r})".format( self.__class__.__name__, self.X, self.Y, type(self.X), type(self.Y), ) The provided code snippet includes necessary dependencies for implementing the `_coord_byval` function. Write a Python function `def _coord_byval(coord: COORD) -> c_long` to solve the following problem: Turns a COORD object into a c_long. This will cause it to be passed by value instead of by reference. (That is what I think at least.) When running ``ptipython`` is run (only with IPython), we often got the following error:: Error in 'SetConsoleCursorPosition'. ArgumentError("argument 2: <class 'TypeError'>: wrong type",) argument 2: <class 'TypeError'>: wrong type It was solved by turning ``COORD`` parameters into a ``c_long`` like this. More info: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686025(v=vs.85).aspx Here is the function: def _coord_byval(coord: COORD) -> c_long: """ Turns a COORD object into a c_long. This will cause it to be passed by value instead of by reference. (That is what I think at least.) When running ``ptipython`` is run (only with IPython), we often got the following error:: Error in 'SetConsoleCursorPosition'. ArgumentError("argument 2: <class 'TypeError'>: wrong type",) argument 2: <class 'TypeError'>: wrong type It was solved by turning ``COORD`` parameters into a ``c_long`` like this. More info: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686025(v=vs.85).aspx """ return c_long(coord.Y * 0x10000 | coord.X & 0xFFFF)
Turns a COORD object into a c_long. This will cause it to be passed by value instead of by reference. (That is what I think at least.) When running ``ptipython`` is run (only with IPython), we often got the following error:: Error in 'SetConsoleCursorPosition'. ArgumentError("argument 2: <class 'TypeError'>: wrong type",) argument 2: <class 'TypeError'>: wrong type It was solved by turning ``COORD`` parameters into a ``c_long`` like this. More info: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686025(v=vs.85).aspx
172,064
from __future__ import annotations import sys import os from ctypes import ArgumentError, byref, c_char, c_long, c_uint, c_ulong, pointer from ..utils import SPHINX_AUTODOC_RUNNING from ctypes.wintypes import DWORD, HANDLE from typing import Callable, Dict, List, Optional, TextIO, Tuple, Type, TypeVar, Union from prompt_toolkit.cursor_shapes import CursorShape from prompt_toolkit.data_structures import Size from prompt_toolkit.styles import ANSI_COLOR_NAMES, Attrs from prompt_toolkit.utils import get_cwidth from prompt_toolkit.win32_types import ( CONSOLE_SCREEN_BUFFER_INFO, COORD, SMALL_RECT, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, ) from .base import Output from .color_depth import ColorDepth class FOREGROUND_COLOR: BLACK = 0x0000 BLUE = 0x0001 GREEN = 0x0002 CYAN = 0x0003 RED = 0x0004 MAGENTA = 0x0005 YELLOW = 0x0006 GRAY = 0x0007 INTENSITY = 0x0008 # Foreground color is intensified. class BACKGROUND_COLOR: BLACK = 0x0000 BLUE = 0x0010 GREEN = 0x0020 CYAN = 0x0030 RED = 0x0040 MAGENTA = 0x0050 YELLOW = 0x0060 GRAY = 0x0070 INTENSITY = 0x0080 # Background color is intensified. The provided code snippet includes necessary dependencies for implementing the `_create_ansi_color_dict` function. Write a Python function `def _create_ansi_color_dict( color_cls: type[FOREGROUND_COLOR] | type[BACKGROUND_COLOR], ) -> dict[str, int]` to solve the following problem: Create a table that maps the 16 named ansi colors to their Windows code. Here is the function: def _create_ansi_color_dict( color_cls: type[FOREGROUND_COLOR] | type[BACKGROUND_COLOR], ) -> dict[str, int]: "Create a table that maps the 16 named ansi colors to their Windows code." return { "ansidefault": color_cls.BLACK, "ansiblack": color_cls.BLACK, "ansigray": color_cls.GRAY, "ansibrightblack": color_cls.BLACK | color_cls.INTENSITY, "ansiwhite": color_cls.GRAY | color_cls.INTENSITY, # Low intensity. "ansired": color_cls.RED, "ansigreen": color_cls.GREEN, "ansiyellow": color_cls.YELLOW, "ansiblue": color_cls.BLUE, "ansimagenta": color_cls.MAGENTA, "ansicyan": color_cls.CYAN, # High intensity. "ansibrightred": color_cls.RED | color_cls.INTENSITY, "ansibrightgreen": color_cls.GREEN | color_cls.INTENSITY, "ansibrightyellow": color_cls.YELLOW | color_cls.INTENSITY, "ansibrightblue": color_cls.BLUE | color_cls.INTENSITY, "ansibrightmagenta": color_cls.MAGENTA | color_cls.INTENSITY, "ansibrightcyan": color_cls.CYAN | color_cls.INTENSITY, }
Create a table that maps the 16 named ansi colors to their Windows code.
172,065
from __future__ import annotations import io import os import sys from typing import ( Callable, Dict, Hashable, Iterable, List, Optional, Sequence, Set, TextIO, Tuple, ) from prompt_toolkit.cursor_shapes import CursorShape from prompt_toolkit.data_structures import Size from prompt_toolkit.output import Output from prompt_toolkit.styles import ANSI_COLOR_NAMES, Attrs from prompt_toolkit.utils import is_dumb_terminal from .color_depth import ColorDepth from .flush_stdout import flush_stdout ANSI_COLORS_TO_RGB = { "ansidefault": ( 0x00, 0x00, 0x00, ), # Don't use, 'default' doesn't really have a value. "ansiblack": (0x00, 0x00, 0x00), "ansigray": (0xE5, 0xE5, 0xE5), "ansibrightblack": (0x7F, 0x7F, 0x7F), "ansiwhite": (0xFF, 0xFF, 0xFF), # Low intensity. "ansired": (0xCD, 0x00, 0x00), "ansigreen": (0x00, 0xCD, 0x00), "ansiyellow": (0xCD, 0xCD, 0x00), "ansiblue": (0x00, 0x00, 0xCD), "ansimagenta": (0xCD, 0x00, 0xCD), "ansicyan": (0x00, 0xCD, 0xCD), # High intensity. "ansibrightred": (0xFF, 0x00, 0x00), "ansibrightgreen": (0x00, 0xFF, 0x00), "ansibrightyellow": (0xFF, 0xFF, 0x00), "ansibrightblue": (0x00, 0x00, 0xFF), "ansibrightmagenta": (0xFF, 0x00, 0xFF), "ansibrightcyan": (0x00, 0xFF, 0xFF), } class Sequence(_Collection[_T_co], Reversible[_T_co], Generic[_T_co]): def __getitem__(self, i: int) -> _T_co: ... def __getitem__(self, s: slice) -> Sequence[_T_co]: ... # Mixin methods def index(self, value: Any, start: int = ..., stop: int = ...) -> int: ... def count(self, value: Any) -> int: ... def __contains__(self, x: object) -> bool: ... def __iter__(self) -> Iterator[_T_co]: ... def __reversed__(self) -> Iterator[_T_co]: ... The provided code snippet includes necessary dependencies for implementing the `_get_closest_ansi_color` function. Write a Python function `def _get_closest_ansi_color(r: int, g: int, b: int, exclude: Sequence[str] = ()) -> str` to solve the following problem: Find closest ANSI color. Return it by name. :param r: Red (Between 0 and 255.) :param g: Green (Between 0 and 255.) :param b: Blue (Between 0 and 255.) :param exclude: A tuple of color names to exclude. (E.g. ``('ansired', )``.) Here is the function: def _get_closest_ansi_color(r: int, g: int, b: int, exclude: Sequence[str] = ()) -> str: """ Find closest ANSI color. Return it by name. :param r: Red (Between 0 and 255.) :param g: Green (Between 0 and 255.) :param b: Blue (Between 0 and 255.) :param exclude: A tuple of color names to exclude. (E.g. ``('ansired', )``.) """ exclude = list(exclude) # When we have a bit of saturation, avoid the gray-like colors, otherwise, # too often the distance to the gray color is less. saturation = abs(r - g) + abs(g - b) + abs(b - r) # Between 0..510 if saturation > 30: exclude.extend(["ansilightgray", "ansidarkgray", "ansiwhite", "ansiblack"]) # Take the closest color. # (Thanks to Pygments for this part.) distance = 257 * 257 * 3 # "infinity" (>distance from #000000 to #ffffff) match = "ansidefault" for name, (r2, g2, b2) in ANSI_COLORS_TO_RGB.items(): if name != "ansidefault" and name not in exclude: d = (r - r2) ** 2 + (g - g2) ** 2 + (b - b2) ** 2 if d < distance: match = name distance = d return match
Find closest ANSI color. Return it by name. :param r: Red (Between 0 and 255.) :param g: Green (Between 0 and 255.) :param b: Blue (Between 0 and 255.) :param exclude: A tuple of color names to exclude. (E.g. ``('ansired', )``.)
172,066
from __future__ import annotations import io import os import sys from typing import ( Callable, Dict, Hashable, Iterable, List, Optional, Sequence, Set, TextIO, Tuple, ) from prompt_toolkit.cursor_shapes import CursorShape from prompt_toolkit.data_structures import Size from prompt_toolkit.output import Output from prompt_toolkit.styles import ANSI_COLOR_NAMES, Attrs from prompt_toolkit.utils import is_dumb_terminal from .color_depth import ColorDepth from .flush_stdout import flush_stdout The provided code snippet includes necessary dependencies for implementing the `_get_size` function. Write a Python function `def _get_size(fileno: int) -> tuple[int, int]` to solve the following problem: Get the size of this pseudo terminal. :param fileno: stdout.fileno() :returns: A (rows, cols) tuple. Here is the function: def _get_size(fileno: int) -> tuple[int, int]: """ Get the size of this pseudo terminal. :param fileno: stdout.fileno() :returns: A (rows, cols) tuple. """ size = os.get_terminal_size(fileno) return size.lines, size.columns
Get the size of this pseudo terminal. :param fileno: stdout.fileno() :returns: A (rows, cols) tuple.