id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
176,871 | import sys
import time
import signal
import OpenGL.GLUT as glut
import OpenGL.platform as platform
from timeit import default_timer as clock
def glut_display():
# Dummy display function
pass | null |
176,872 | import sys
import time
import signal
import OpenGL.GLUT as glut
import OpenGL.platform as platform
from timeit import default_timer as clock
def glut_idle():
# Dummy idle function
pass | null |
176,873 | import sys
import time
import signal
import OpenGL.GLUT as glut
import OpenGL.platform as platform
from timeit import default_timer as clock
glutMainLoopEvent = None
glut.glutInit( sys.argv )
glut.glutInitDisplayMode( glut_display_mode )
glut.glutCreateWindow( b'ipython' )
glut.glutReshapeWindow( 1, 1 )
glut.glutHideWi... | null |
176,874 | import sys
import time
import signal
import OpenGL.GLUT as glut
import OpenGL.platform as platform
from timeit import default_timer as clock
glutMainLoopEvent = None
def glut_int_handler(signum, frame):
# Catch sigint and print the defaultipyt message
signal.signal(signal.SIGINT, signal.default_int_handler)
... | Run the pyglet event loop by processing pending events only. This keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance. |
176,875 | import gtk, gobject
gtk.gdk.threads_init()
import gtk, gobject
gtk.gdk.threads_init()
The provided code snippet includes necessary dependencies for implementing the `inputhook` function. Write a Python function `def inputhook(context)` to solve the following problem:
When the eventloop of prompt-toolkit is idle, cal... | When the eventloop of prompt-toolkit is idle, call this inputhook. This will run the GTK main loop until the file descriptor `context.fileno()` becomes ready. :param context: An `InputHookContext` instance. |
176,876 | import ctypes
import ctypes.util
from threading import Event
objc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("objc"))
void_p = ctypes.c_void_p
objc.objc_getClass.restype = void_p
objc.sel_registerName.restype = void_p
objc.objc_msgSend.restype = void_p
objc.objc_msgSend.argtypes = [void_p, void_p]
msg = objc.o... | Callback to fire when there's input to be read |
176,877 | import ctypes
import ctypes.util
from threading import Event
objc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("objc"))
void_p = ctypes.c_void_p
objc.objc_getClass.restype = void_p
objc.sel_registerName.restype = void_p
objc.objc_msgSend.restype = void_p
objc.objc_msgSend.argtypes = [void_p, void_p]
msg = objc.o... | Inputhook for Cocoa (NSApp) |
176,878 | from gi.repository import Gtk, GLib
def _main_quit(*args, **kwargs):
Gtk.main_quit()
return False
def inputhook(context):
GLib.io_add_watch(context.fileno(), GLib.PRIORITY_DEFAULT, GLib.IO_IN, _main_quit)
Gtk.main() | null |
176,879 | import sys
import warnings
from IPython.core import ultratb, compilerop
from IPython.core import magic_arguments
from IPython.core.magic import Magics, magics_class, line_magic
from IPython.core.interactiveshell import DummyMod, InteractiveShell
from IPython.terminal.interactiveshell import TerminalInteractiveShell
fro... | Call this to embed IPython at the current point in your program. The first invocation of this will create a :class:`terminal.embed.InteractiveShellEmbed` instance and then call it. Consecutive calls just call the already created instance. If you don't want the kernel to initialize the namespace from the scope of the su... |
176,880 | from logging import error
import os
import sys
from IPython.core.error import TryNext, UsageError
from IPython.core.magic import Magics, magics_class, line_magic
from IPython.lib.clipboard import ClipboardEmpty
from IPython.testing.skipdoctest import skip_doctest
from IPython.utils.text import SList, strip_email_quotes... | Yield pasted lines until the user enters the given sentinel value. |
176,881 | import importlib.abc
import sys
import os
import types
from functools import partial, lru_cache
import operator
QT_API_PYQT6 = "pyqt6"
QT_API_PYSIDE6 = "pyside6"
QT_API_PYQT5 = 'pyqt5'
QT_API_PYSIDE2 = 'pyside2'
QT_API_PYQT = "pyqt"
QT_API_PYQTv1 = "pyqtv1"
QT_API_PYSIDE = "pyside"
QT_API_PYQT_DEFAULT = "pyqtdefault"... | Attempt to import Qt, given a preference list of permissible bindings It is safe to call this function multiple times. Parameters ---------- api_options : List of strings The order of APIs to try. Valid items are 'pyside', 'pyside2', 'pyqt', 'pyqt5', 'pyqtv1' and 'pyqtdefault' Returns ------- A tuple of QtCore, QtGui, ... |
176,882 | import importlib.abc
import sys
import os
import types
from functools import partial, lru_cache
import operator
QT_API_PYQT6 = "pyqt6"
sys.meta_path.insert(0, ID)
The provided code snippet includes necessary dependencies for implementing the `enum_factory` function. Write a Python function `def enum_factory(QT_API, Qt... | Construct an enum helper to account for PyQt5 <-> PyQt6 changes. |
176,883 | import os
import sys
from IPython.external.qt_loaders import (
load_qt,
loaded_api,
enum_factory,
# QT6
QT_API_PYQT6,
QT_API_PYSIDE6,
# QT5
QT_API_PYQT5,
QT_API_PYSIDE2,
# QT4
QT_API_PYQT,
QT_API_PYSIDE,
# default
QT_API_PYQT_DEFAULT,
)
_qt_apis = (
# QT6
... | Return a list of acceptable QT APIs, in decreasing order of preference. |
176,884 | import inspect, os, sys, textwrap
from IPython.core.error import UsageError
from IPython.core.magic import Magics, magics_class, line_magic
from IPython.testing.skipdoctest import skip_doctest
from traitlets import Bool
def restore_aliases(ip, alias=None):
def refresh_variables(ip):
def restore_dhist(ip):
def restore_... | null |
176,885 | import inspect, os, sys, textwrap
from IPython.core.error import UsageError
from IPython.core.magic import Magics, magics_class, line_magic
from IPython.testing.skipdoctest import skip_doctest
from traitlets import Bool
class StoreMagics(Magics):
"""Lightweight persistence for python variables.
Provides the %st... | Load the extension in IPython. |
176,886 | from IPython.core import magic_arguments
from IPython.core.magic import Magics, magics_class, line_magic
import os
import sys
import traceback
import types
import weakref
import gc
import logging
from importlib import import_module, reload
from importlib.util import source_from_cache
func_attrs = [
"__code__",
... | Upgrade the code object of a function |
176,887 | from IPython.core import magic_arguments
from IPython.core.magic import Magics, magics_class, line_magic
import os
import sys
import traceback
import types
import weakref
import gc
import logging
from importlib import import_module, reload
from importlib.util import source_from_cache
def update_instances(old, new):
... | Replace stuff in the __dict__ of a class, and upgrade method code objects, and add new methods, if any |
176,888 | from IPython.core import magic_arguments
from IPython.core.magic import Magics, magics_class, line_magic
import os
import sys
import traceback
import types
import weakref
import gc
import logging
from importlib import import_module, reload
from importlib.util import source_from_cache
def update_generic(a, b):
for t... | Replace get/set/del functions of a property |
176,889 | from IPython.core import magic_arguments
from IPython.core.magic import Magics, magics_class, line_magic
import os
import sys
import traceback
import types
import weakref
import gc
import logging
from importlib import import_module, reload
from importlib.util import source_from_cache
def load_ipython_extension(ip):
de... | null |
176,890 | from IPython.core import magic_arguments
from IPython.core.magic import Magics, magics_class, line_magic
import os
import sys
import traceback
import types
import weakref
import gc
import logging
from importlib import import_module, reload
from importlib.util import source_from_cache
def update_generic(a, b):
for t... | Enhanced version of the builtin reload function. superreload remembers objects previously in the module, and - upgrades the class dictionary of every old class in the module - upgrades the code object of every old function and method - clears the module's namespace before reloading |
176,891 | from IPython.core import magic_arguments
from IPython.core.magic import Magics, magics_class, line_magic
__skip_doctest__ = True
import os
import sys
import traceback
import types
import weakref
import gc
import logging
from importlib import import_module, reload
from importlib.util import source_from_cache
func_attrs ... | Load the extension in IPython. |
176,892 | from sphinx import highlighting
from IPython.lib.lexers import IPyLexer
The provided code snippet includes necessary dependencies for implementing the `setup` function. Write a Python function `def setup(app)` to solve the following problem:
Setup as a sphinx extension.
Here is the function:
def setup(app):
"""S... | Setup as a sphinx extension. |
176,893 | import atexit
import errno
import os
import pathlib
import re
import sys
import tempfile
import ast
import warnings
import shutil
from io import StringIO
from docutils.parsers.rst import directives
from docutils.parsers.rst import Directive
from sphinx.util import logging
from traitlets.config import Config
from IPytho... | part is a string of ipython text, comprised of at most one input, one output, comments, and blank lines. The block parser parses the text into a list of:: blocks = [ (TOKEN0, data0), (TOKEN1, data1), ...] where TOKEN is one of [COMMENT | INPUT | OUTPUT ] and data is, depending on the type of token:: COMMENT : the comme... |
176,894 | import atexit
import errno
import os
import pathlib
import re
import sys
import tempfile
import ast
import warnings
import shutil
from io import StringIO
from docutils.parsers.rst import directives
from docutils.parsers.rst import Directive
from sphinx.util import logging
from traitlets.config import Config
from IPytho... | null |
176,895 | from warnings import warn
warn(
"The `IPython.utils.version` module has been deprecated since IPython 8.0.",
DeprecationWarning,
)
The provided code snippet includes necessary dependencies for implementing the `check_version` function. Write a Python function `def check_version(v, check)` to solve the followin... | check version string v >= check If dev/prerelease tags result in TypeError for string-number comparison, it is assumed that the dependency is satisfied. Users on dev branches are responsible for keeping their own packages up to date. |
176,896 | import os
from IPython.utils.ipstruct import Struct
color_templates = (
# Dark colors
("Black" , "0;30"),
("Red" , "0;31"),
("Green" , "0;32"),
("Brown" , "0;33"),
("Blue" , "0;34"),
("Purple" , "0;35"),
("Cyan" ... | Build a set of color attributes in a class. Helper function for building the :class:`TermColors` and :class`InputTermColors`. |
176,897 | import os, sys, threading
import ctypes, msvcrt
from ctypes import POINTER
from ctypes.wintypes import HANDLE, HLOCAL, LPVOID, WORD, DWORD, BOOL, \
ULONG, LPCWSTR
class AvoidUNCPath(object):
"""A context manager to protect command execution from UNC paths.
In the Win32 API, commands can't be invoked wit... | Win32 version of os.system() that works with network shares. Note that this implementation returns None, as meant for use in IPython. Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- None : we explicitly do NOT return the subprocess status code, as this utility is meant to b... |
176,898 | import sys
import sys
if sys.platform[:5] == 'linux':
def jiffies(_proc_pid_stat=f'/proc/{os.getpid()}/stat', _load_time=[]):
"""
Return number of jiffies elapsed.
Return number of jiffies (1/100ths of a second) that this
process has been scheduled in user m... | Extract a set of variables by name from another frame. Parameters ---------- *names : str One or more variable names which will be extracted from the caller's frame. **kw : integer, optional How many frames in the stack to walk when looking for your variables. The default is 0, which will use the frame where the call w... |
176,899 | import sys
import sys
if sys.platform[:5] == 'linux':
def jiffies(_proc_pid_stat=f'/proc/{os.getpid()}/stat', _load_time=[]):
"""
Return number of jiffies elapsed.
Return number of jiffies (1/100ths of a second) that this
process has been scheduled in user m... | Extract a set of variables by name from another frame. Similar to extractVars(), but with a specified depth of 1, so that names are extracted exactly from above the caller. This is simply a convenience function so that the very common case (for us) of skipping exactly 1 frame doesn't have to construct a special dict fo... |
176,900 | import sys
import sys
if sys.platform[:5] == 'linux':
def jiffies(_proc_pid_stat=f'/proc/{os.getpid()}/stat', _load_time=[]):
"""
Return number of jiffies elapsed.
Return number of jiffies (1/100ths of a second) that this
process has been scheduled in user m... | Print the value of an expression from the caller's frame. Takes an expression, evaluates it in the caller's frame and prints both the given expression and the resulting value (as well as a debug mark indicating the name of the calling function. The input must be of a form suitable for eval(). An optional message can be... |
176,901 | import time
try:
import resource
except ImportError:
resource = None
if resource is not None and hasattr(resource, "getrusage"):
else:
# There is no distinction of user/system time under windows, so we just use
# time.process_time() for everything...
clocku = clocks = clock = time.process_time
The ... | clocku() -> floating point number Return the *USER* CPU time in seconds since the start of the process. This is done via a call to resource.getrusage, so it avoids the wraparound problems in time.clock(). |
176,902 | import time
try:
import resource
except ImportError:
resource = None
if resource is not None and hasattr(resource, "getrusage"):
else:
# There is no distinction of user/system time under windows, so we just use
# time.process_time() for everything...
clocku = clocks = clock = time.process_time
The ... | clocks() -> floating point number Return the *SYSTEM* CPU time in seconds since the start of the process. This is done via a call to resource.getrusage, so it avoids the wraparound problems in time.clock(). |
176,903 | import time
try:
import resource
except ImportError:
resource = None
if resource is not None and hasattr(resource, "getrusage"):
else:
# There is no distinction of user/system time under windows, so we just use
# time.process_time() for everything...
clocku = clocks = clock = time.process_time
The ... | clock2() -> (t_user,t_system) Similar to clock(), but return a tuple of user/system times. |
176,904 | import time
The provided code snippet includes necessary dependencies for implementing the `clock2` function. Write a Python function `def clock2()` to solve the following problem:
Under windows, system CPU time can't be measured. This just returns process_time() and zero.
Here is the function:
def clock2():
... | Under windows, system CPU time can't be measured. This just returns process_time() and zero. |
176,905 | import time
def timings_out(reps,func,*args,**kw):
"""timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
Execute a function reps times, return a tuple with the elapsed total
CPU time in seconds, the time per call and the function's output.
Under Unix, the return value is the sum of user+sy... | timings(reps,func,*args,**kw) -> (t_total,t_per_call) Execute a function reps times, return a tuple with the elapsed total CPU time in seconds and the time per call. These are just the first two values in timings_out(). |
176,906 | import time
def timings_out(reps,func,*args,**kw):
"""timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
Execute a function reps times, return a tuple with the elapsed total
CPU time in seconds, the time per call and the function's output.
Under Unix, the return value is the sum of user+sy... | timing(func,*args,**kw) -> t_total Execute a function once, return the elapsed total CPU time in seconds. This is just the first value in timings_out(). |
176,907 | import subprocess
import shlex
import sys
import os
from IPython.utils import py3compat
def process_handler(cmd, callback, stderr=subprocess.PIPE):
"""Open a command in a shell subprocess and execute a callback.
This function provides common scaffolding for creating subprocess.Popen()
calls. It creates a P... | Run a command and return its stdout/stderr as a string. Parameters ---------- cmd : str or list A command to be executed in the system shell. Returns ------- output : str A string containing the combination of stdout and stderr from the subprocess, in whatever order the subprocess originally wrote to its file descripto... |
176,908 | import subprocess
import shlex
import sys
import os
from IPython.utils import py3compat
def get_output_error_code(cmd):
"""Return (standard output, standard error, return code) of executing cmd
in a shell.
Accepts the same arguments as os.system().
Parameters
----------
cmd : str or list
... | Return (standard output, standard error) of executing cmd in a shell. Accepts the same arguments as os.system(). Parameters ---------- cmd : str or list A command to be executed in the system shell. Returns ------- stdout : str stderr : str |
176,909 | import functools
import linecache
from warnings import warn
The provided code snippet includes necessary dependencies for implementing the `getlines` function. Write a Python function `def getlines(filename, module_globals=None)` to solve the following problem:
Deprecated since IPython 6.0
Here is the function:
def ... | Deprecated since IPython 6.0 |
176,910 | from collections import namedtuple
from io import StringIO
from keyword import iskeyword
import tokenize
The provided code snippet includes necessary dependencies for implementing the `line_at_cursor` function. Write a Python function `def line_at_cursor(cell, cursor_pos=0)` to solve the following problem:
Return the ... | Return the line in a cell at a given cursor position Used for calling line-based APIs that don't support multi-line input, yet. Parameters ---------- cell : str multiline block of text cursor_pos : integer the cursor position Returns ------- (line, offset): (string, integer) The line with the current cursor, and the ch... |
176,911 | from collections import namedtuple
from io import StringIO
from keyword import iskeyword
import tokenize
Token = namedtuple('Token', ['token', 'text', 'start', 'end', 'line'])
def generate_tokens(readline):
"""wrap generate_tokens to catch EOF errors"""
try:
for token in tokenize.generate_tokens(readlin... | Get the token at a given cursor Used for introspection. Function calls are prioritized, so the token for the callable will be returned if the cursor is anywhere inside the call. Parameters ---------- cell : unicode A block of Python code cursor_pos : int The location of the cursor in the block where the token should be... |
176,912 | import inspect
import types
The provided code snippet includes necessary dependencies for implementing the `get_real_method` function. Write a Python function `def get_real_method(obj, name)` to solve the following problem:
Like getattr, but with a few extra sanity checks: - If obj is a class, ignore everything except... | Like getattr, but with a few extra sanity checks: - If obj is a class, ignore everything except class methods - Check if obj is a proxy that claims to have all attributes - Catch attribute access failing with any exception - Check that the attribute is a callable object Returns the method or None. |
176,913 | import errno
import os
import subprocess as sp
import sys
import pexpect
from ._process_common import getoutput, arg_split
from IPython.utils.encoding import DEFAULT_ENCODING
import os
if os.name == 'nt':
# Code "stolen" from enthought/debug/memusage.py
def GetPerformanceAttributes(object... | null |
176,914 | import os
import platform
import pprint
import sys
import subprocess
from IPython.core import release
from IPython.utils import _sysinfo, encoding
def get_sys_info():
"""Return useful information about IPython and the system, as a dict."""
p = os.path
path = p.realpath(p.dirname(p.abspath(p.join(__file__, '... | Return useful information about IPython and the system, as a string. Examples -------- :: In [2]: print(sys_info()) {'commit_hash': '144fdae', # random 'commit_source': 'repository', 'ipython_path': '/home/fperez/usr/lib/python2.6/site-packages/IPython', 'ipython_version': '0.11.dev', 'os_name': 'posix', 'platform': 'L... |
176,915 | import os
import platform
import pprint
import sys
import subprocess
from IPython.core import release
from IPython.utils import _sysinfo, encoding
import os
if os.name == 'nt':
# Code "stolen" from enthought/debug/memusage.py
def GetPerformanceAttributes(object, counter, instance=None,
... | DEPRECATED Return the effective number of CPUs in the system as an integer. This cross-platform function makes an attempt at finding the total number of available CPUs in the system, as returned by various underlying system and python calls. If it can't find a sensible answer, it returns 1 (though an error *may* make i... |
176,916 | import sys
import locale
import warnings
def get_stream_enc(stream, default=None):
"""Return the given stream's encoding or a default.
There are cases where ``sys.std*`` might not actually be a stream, so
check for the encoding attribute prior to returning it, and return
a default if it doesn't exist or... | Return IPython's guess for the default encoding for bytes as text. If prefer_stream is True (default), asks for stdin.encoding first, to match the calling Terminal, but that is often None for subprocesses. Then fall back on locale.getpreferredencoding(), which should be a sensible platform default (that respects LANG e... |
176,917 | from IPython.core.error import TryNext
from functools import singledispatch
class TryNext(IPythonCoreError):
"""Try next hook exception.
Raise this in your hook function to indicate that the next hook handler
should be used to handle the operation.
"""
The provided code snippet includes necessary dep... | Called when you do obj? |
176,918 | from IPython.core.error import TryNext
from functools import singledispatch
class TryNext(IPythonCoreError):
"""Try next hook exception.
Raise this in your hook function to indicate that the next hook handler
should be used to handle the operation.
"""
The provided code snippet includes necessary dep... | Custom completer dispatching for python objects. Parameters ---------- obj : object The object to complete. prev_completions : list List of attributes discovered so far. This should return the list of attributes in obj. If you only wish to add to the attributes already discovered normally, return own_attrs + prev_compl... |
176,919 | import os
import sys
import errno
import shutil
import random
import glob
from IPython.utils.process import system
if sys.platform == 'win32':
def _get_long_path_name(path):
"""Get a long path name (expand ~) on Windows using ctypes.
Examples
--------
>>> get_long_path_name('c:\\\\do... | Expand a path into its long form. On Windows this expands any ~ in the paths. On other platforms, it is a null operation. |
176,920 | import os
import sys
import errno
import shutil
import random
import glob
from IPython.utils.process import system
import os
if os.name == 'nt':
# Code "stolen" from enthought/debug/memusage.py
def GetPerformanceAttributes(object, counter, instance=None,
i... | Return a valid python filename in the current directory. If the given name is not a file, it adds '.py' and searches again. Raises IOError with an informative message if the file isn't found. |
176,921 | import os
import sys
import errno
import shutil
import random
import glob
from IPython.utils.process import system
def expand_path(s):
"""Expand $VARS and ~names in a string, like a shell
:Examples:
In [2]: os.environ['FOO']='test'
In [3]: expand_path('variable FOO is $FOO')
Out[3]: 'variab... | Find a file by looking through a sequence of paths. This iterates through a sequence of paths looking for a file and returns the full, absolute path of the first occurrence of the file. If no set of path dirs is given, the filename is tested as is, after running through :func:`expandvars` and :func:`expanduser`. Thus a... |
176,922 | import os
import sys
import errno
import shutil
import random
import glob
from IPython.utils.process import system
if sys.platform == 'win32':
else:
def unescape_glob(string):
"""Unescape glob pattern in `string`."""
def unescape(s):
for pattern in '*[]!?':
s = s.replace(r'\{0}'.format(patte... | Do glob expansion for each element in `args` and return a flattened list. Unmatched glob pattern will remain as-is in the returned list. |
176,923 | import os
import sys
import errno
import shutil
import random
import glob
from IPython.utils.process import system
def target_outdated(target,deps):
"""Determine whether a target is out of date.
target_outdated(target,deps) -> 1/0
deps: list of filenames which MUST exist.
target: single filename which m... | Update a target with a given command given a list of dependencies. target_update(target,deps,cmd) -> runs cmd if target is outdated. This is just a wrapper around target_outdated() which calls the given command if target is outdated. |
176,924 | import os
import sys
import errno
import shutil
import random
import glob
from IPython.utils.process import system
def link(src, dst):
"""Hard links ``src`` to ``dst``, returning 0 or errno.
Note that the special errno ``ENOLINK`` will be returned if ``os.link`` isn't
supported by the operating system.
... | Attempts to hardlink ``src`` to ``dst``, copying if the link fails. Attempts to maintain the semantics of ``shutil.copy``. Because ``os.link`` does not overwrite files, a unique temporary file will be used if the target already exists, then that file will be moved into place. |
176,925 | import importlib
import sys
import sys
if sys.platform[:5] == 'linux':
def jiffies(_proc_pid_stat=f'/proc/{os.getpid()}/stat', _load_time=[]):
"""
Return number of jiffies elapsed.
Return number of jiffies (1/100ths of a second) that this
process has been sc... | Find module `module_name` on sys.path, and return the path to module `module_name`. - If `module_name` refers to a module directory, then return path to __init__ file. - If `module_name` is a directory without an __init__file, return None. - If module is missing or does not have a `.py` or `.pyw` extension, return None... |
176,926 | import os
import sys
import warnings
from shutil import get_terminal_size as _get_terminal_size
if os.name == 'posix':
elif sys.platform == 'win32':
else:
if os.name == 'posix':
TERM = os.environ.get('TERM','')
if TERM.startswith('xterm'):
_set_term_title = _set_term_title_xterm
_restore_term_ti... | null |
176,927 | import os
import sys
import warnings
from shutil import get_terminal_size as _get_terminal_size
if os.name == 'posix':
elif sys.platform == 'win32':
else:
if os.name == 'posix':
TERM = os.environ.get('TERM','')
if TERM.startswith('xterm'):
_set_term_title = _set_term_title_xterm
_restore_term_ti... | null |
176,928 | import os
import sys
import warnings
from shutil import get_terminal_size as _get_terminal_size
def _term_clear():
pass | null |
176,929 | import os
import sys
import warnings
from shutil import get_terminal_size as _get_terminal_size
ignore_termtitle = True
The provided code snippet includes necessary dependencies for implementing the `toggle_set_term_title` function. Write a Python function `def toggle_set_term_title(val)` to solve the following proble... | Control whether set_term_title is active or not. set_term_title() allows writing to the console titlebar. In embedded widgets this can cause problems, so this call can be used to toggle it on or off as needed. The default state of the module is for the function to be disabled. Parameters ---------- val : bool If True, ... |
176,930 | import os
import sys
import warnings
from shutil import get_terminal_size as _get_terminal_size
_xterm_term_title_saved = False
import sys
if sys.platform[:5] == 'linux':
def jiffies(_proc_pid_stat=f'/proc/{os.getpid()}/stat', _load_time=[]):
"""
Return number of jiffies ela... | Change virtual terminal title in xterm-workalikes |
176,931 | import os
import sys
import warnings
from shutil import get_terminal_size as _get_terminal_size
_xterm_term_title_saved = False
import sys
if sys.platform[:5] == 'linux':
def jiffies(_proc_pid_stat=f'/proc/{os.getpid()}/stat', _load_time=[]):
"""
Return number of jiffies ela... | null |
176,932 | import os
import sys
import warnings
from shutil import get_terminal_size as _get_terminal_size
ignore_termtitle = True
def _set_term_title(*args,**kw):
"""Dummy no-op."""
pass
if os.name == 'posix':
TERM = os.environ.get('TERM','')
if TERM.startswith('xterm'):
_set_term_title = _set_term_title_... | Set terminal title using the necessary platform-dependent calls. |
176,933 | import os
import sys
import warnings
from shutil import get_terminal_size as _get_terminal_size
ignore_termtitle = True
def _restore_term_title():
pass
The provided code snippet includes necessary dependencies for implementing the `restore_term_title` function. Write a Python function `def restore_term_title()` to... | Restore, if possible, terminal title to the original state |
176,934 | import os
import sys
import warnings
from shutil import get_terminal_size as _get_terminal_size
ignore_termtitle = True
import warnings
warnings.warn("Importing from numpy.testing.utils is deprecated "
"since 1.15.0, import from numpy.testing instead.",
DeprecationWarning, stacklevel=2)
d... | null |
176,935 | import os
import sys
import ctypes
import time
from ctypes import c_int, POINTER
from ctypes.wintypes import LPCWSTR, HLOCAL
from subprocess import STDOUT, TimeoutExpired
from threading import Thread
from ._process_common import read_no_interrupt, process_handler, arg_split as py_arg_split
from . import py3compat
from ... | Win32 version of os.system() that works with network shares. Note that this implementation returns None, as meant for use in IPython. Parameters ---------- cmd : str or list A command to be executed in the system shell. Returns ------- int : child process' exit code. |
176,936 | import os
import sys
import ctypes
import time
from ctypes import c_int, POINTER
from ctypes.wintypes import LPCWSTR, HLOCAL
from subprocess import STDOUT, TimeoutExpired
from threading import Thread
from ._process_common import read_no_interrupt, process_handler, arg_split as py_arg_split
from . import py3compat
from ... | Return standard output of executing cmd in a shell. Accepts the same arguments as os.system(). Parameters ---------- cmd : str or list A command to be executed in the system shell. Returns ------- stdout : str |
176,937 | import os
import sys
import ctypes
import time
from ctypes import c_int, POINTER
from ctypes.wintypes import LPCWSTR, HLOCAL
from subprocess import STDOUT, TimeoutExpired
from threading import Thread
from ._process_common import read_no_interrupt, process_handler, arg_split as py_arg_split
from . import py3compat
from ... | Split a command line's arguments in a shell-like manner. This is a special version for windows that use a ctypes call to CommandLineToArgvW to do the argv splitting. The posix parameter is ignored. If strict=False, process_common.arg_split(...strict=False) is used instead. |
176,938 | import os
import sys
import ctypes
import time
from ctypes import c_int, POINTER
from ctypes.wintypes import LPCWSTR, HLOCAL
from subprocess import STDOUT, TimeoutExpired
from threading import Thread
from ._process_common import read_no_interrupt, process_handler, arg_split as py_arg_split
from . import py3compat
from ... | null |
176,939 |
The provided code snippet includes necessary dependencies for implementing the `uniq_stable` function. Write a Python function `def uniq_stable(elems)` to solve the following problem:
uniq_stable(elems) -> list Return from an iterable, a list of all the unique elements in the input, but maintaining the order in which... | uniq_stable(elems) -> list Return from an iterable, a list of all the unique elements in the input, but maintaining the order in which they first appear. Note: All elements in the input must be hashable for this routine to work, as it internally uses a set for efficiency reasons. |
176,940 | from typing import Sequence
from IPython.utils.docs import GENERATING_DOCUMENTATION
The provided code snippet includes necessary dependencies for implementing the `undoc` function. Write a Python function `def undoc(func)` to solve the following problem:
Mark a function or class as undocumented. This is found by inspe... | Mark a function or class as undocumented. This is found by inspecting the AST, so for now it must be used directly as @undoc, not as e.g. @decorators.undoc |
176,941 | from typing import Sequence
from IPython.utils.docs import GENERATING_DOCUMENTATION
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, star... | Set sphinx options |
176,942 | import re
import types
from IPython.utils.dir2 import dir2
typestr2type, type2typestr = create_typestr2type_dicts()
The provided code snippet includes necessary dependencies for implementing the `create_typestr2type_dicts` function. Write a Python function `def create_typestr2type_dicts(dont_include_in_type2typestr=["... | Return dictionaries mapping lower case typename (e.g. 'tuple') to type objects from the types package, and vice versa. |
176,943 | import re
import types
from IPython.utils.dir2 import dir2
def dict_dir(obj):
"""Produce a dictionary of an object's attributes. Builds on dir2 by
checking that a getattr() call actually succeeds."""
ns = {}
for key in dir2(obj):
# This seemingly unnecessary try/except is actually needed
#... | Return dictionary of all objects in a namespace dictionary that match type_pattern and filter. |
176,944 | import os
import re
import string
import sys
import textwrap
from string import Formatter
from pathlib import Path
The provided code snippet includes necessary dependencies for implementing the `list_strings` function. Write a Python function `def list_strings(arg)` to solve the following problem:
Always return a list... | Always return a list of strings, given a string or list of strings as input. Examples -------- :: In [7]: list_strings('A single string') Out[7]: ['A single string'] In [8]: list_strings(['A single string in a list']) Out[8]: ['A single string in a list'] In [9]: list_strings(['A','list','of','strings']) Out[9]: ['A', ... |
176,945 | import os
import re
import string
import sys
import textwrap
from string import Formatter
from pathlib import Path
The provided code snippet includes necessary dependencies for implementing the `marquee` function. Write a Python function `def marquee(txt='',width=78,mark='*')` to solve the following problem:
Return th... | Return the input string centered in a 'marquee'. Examples -------- :: In [16]: marquee('A test',40) Out[16]: '**************** A test ****************' In [17]: marquee('A test',40,'-') Out[17]: '---------------- A test ----------------' In [18]: marquee('A test',40,' ') Out[18]: ' A test ' |
176,946 | import os
import re
import string
import sys
import textwrap
from string import Formatter
from pathlib import Path
ini_spaces_re = re.compile(r'^(\s+)')
The provided code snippet includes necessary dependencies for implementing the `num_ini_spaces` function. Write a Python function `def num_ini_spaces(strng)` to solve... | Return the number of initial spaces in a string |
176,947 | import os
import re
import string
import sys
import textwrap
from string import Formatter
from pathlib import Path
The provided code snippet includes necessary dependencies for implementing the `format_screen` function. Write a Python function `def format_screen(strng)` to solve the following problem:
Format a string ... | Format a string for screen printing. This removes some latex-type format codes. |
176,948 | import os
import re
import string
import sys
import textwrap
from string import Formatter
from pathlib import Path
def dedent(text):
"""Equivalent of textwrap.dedent that ignores unindented first line.
This means it will still dedent strings like:
'''foo
is a bar
'''
For use in wrap_paragraphs.
... | 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. |
176,949 | import os
import re
import string
import sys
import textwrap
from string import Formatter
from pathlib import Path
The provided code snippet includes necessary dependencies for implementing the `strip_email_quotes` function. Write a Python function `def strip_email_quotes(text)` to solve the following problem:
Strip l... | Strip leading email quotation characters ('>'). Removes any combination of leading '>' interspersed with whitespace that appears *identically* in all lines of the input text. Parameters ---------- text : str Examples -------- Simple uses:: In [2]: strip_email_quotes('> > text') Out[2]: 'text' In [3]: strip_email_quotes... |
176,950 | import os
import re
import string
import sys
import textwrap
from string import Formatter
from pathlib import Path
The provided code snippet includes necessary dependencies for implementing the `strip_ansi` function. Write a Python function `def strip_ansi(source)` to solve the following problem:
Remove ansi escape co... | Remove ansi escape codes from text. Parameters ---------- source : str Source to remove the ansi from |
176,951 | import os
import re
import string
import sys
import textwrap
from string import Formatter
from pathlib import Path
def compute_item_matrix(items, row_first=False, empty=None, *args, **kwargs) :
"""Returns a nested list, and info to columnize items
Parameters
----------
items
list of strings to c... | Transform a list of strings into a single string with columns. Parameters ---------- items : sequence of strings The strings to process. row_first : (default False) Whether to compute columns for a row-first matrix instead of column-first (default). separator : str, optional [default is two spaces] The string that sepa... |
176,952 | import os
import re
import string
import sys
import textwrap
from string import Formatter
from pathlib import Path
The provided code snippet includes necessary dependencies for implementing the `get_text_list` function. Write a Python function `def get_text_list(list_, last_sep=' and ', sep=", ", wrap_item_with="")` t... | Return a string with a natural enumeration of items >>> get_text_list(['a', 'b', 'c', 'd']) 'a, b, c and d' >>> get_text_list(['a', 'b', 'c'], ' or ') 'a, b or c' >>> get_text_list(['a', 'b', 'c'], ', ') 'a, b, c' >>> get_text_list(['a', 'b'], ' or ') 'a or b' >>> get_text_list(['a']) 'a' >>> get_text_list([]) '' >>> g... |
176,953 | import platform
import builtins as builtin_mod
from .encoding import DEFAULT_ENCODING
The provided code snippet includes necessary dependencies for implementing the `safe_unicode` function. Write a Python function `def safe_unicode(e)` to solve the following problem:
unicode(e) with various fallbacks. Used for excepti... | unicode(e) with various fallbacks. Used for exceptions, which may not be safe to call unicode() on. |
176,954 | import platform
import builtins as builtin_mod
from .encoding import DEFAULT_ENCODING
def execfile(fname, glob, loc=None, compiler=None):
loc = loc if (loc is not None) else glob
with open(fname, "rb") as f:
compiler = compiler or compile
exec(compiler(f.read(), fname, "exec"), glob, loc) | null |
176,955 | import platform
import builtins as builtin_mod
from .encoding import DEFAULT_ENCODING
def no_code(x, encoding=None):
return x | null |
176,957 | import io
from io import TextIOWrapper, BytesIO
from pathlib import Path
import re
from tokenize import open, detect_encoding
def strip_encoding_cookie(filelike):
"""Generator to pull lines from a text-mode file, skipping the encoding
cookie if it is found in the first two lines.
"""
it = iter(filelike)... | Read a Python file, using the encoding declared inside the file. Parameters ---------- filename : str The path to the file to read. skip_encoding_cookie : bool If True (the default), and the encoding declaration is found in the first two lines, that line will be excluded from the output. Returns ------- A unicode strin... |
176,958 | import io
from io import TextIOWrapper, BytesIO
from pathlib import Path
import re
from tokenize import open, detect_encoding
def source_to_unicode(txt, errors='replace', skip_encoding_cookie=True):
"""Converts a bytes string with python source code to unicode.
Unicode strings are passed through unchanged. Byte... | Read a Python file from a URL, using the encoding declared inside the file. Parameters ---------- url : str The URL from which to fetch the file. errors : str How to handle decoding errors in the file. Options are the same as for bytes.decode(), but here 'replace' is the default. skip_encoding_cookie : bool If True (th... |
176,959 | import os
import shutil
import sys
if sys.platform == 'win32':
from ._process_win32 import system, getoutput, arg_split, check_pid
elif sys.platform == 'cli':
from ._process_cli import system, getoutput, arg_split, check_pid
else:
from ._process_posix import system, getoutput, arg_split, check_pid
from ._pr... | Return abbreviated version of cwd, e.g. d:mydir |
176,960 | import atexit
import os
import sys
import tempfile
from pathlib import Path
from warnings import warn
from IPython.utils.decorators import undoc
from .capture import CapturedIO, capture_output
The provided code snippet includes necessary dependencies for implementing the `ask_yes_no` function. Write a Python function ... | Asks a question and returns a boolean (y/n) answer. If default is given (one of 'y','n'), it is used if the user input is empty. If interrupt is given (one of 'y','n'), it is used if the user presses Ctrl-C. Otherwise the question is repeated until an answer is given. An EOF is treated as the default answer. If there i... |
176,961 | import atexit
import os
import sys
import tempfile
from pathlib import Path
from warnings import warn
from IPython.utils.decorators import undoc
from .capture import CapturedIO, capture_output
class Path(PurePath):
def __new__(cls: Type[_P], *args: Union[str, _PathLike], **kwargs: Any) -> _P: ...
def __enter__... | Make a temporary python file, return filename and filehandle. Parameters ---------- src : string or list of strings (no need for ending newlines if list) Source code to be written to the file. ext : optional, string Extension for the generated file. Returns ------- (filename, open filehandle) It is the caller's respons... |
176,962 | import atexit
import os
import sys
import tempfile
from pathlib import Path
from warnings import warn
from IPython.utils.decorators import undoc
from .capture import CapturedIO, capture_output
import sys
if sys.platform[:5] == 'linux':
def jiffies(_proc_pid_stat=f'/proc/{os.getpid()}/stat',... | DEPRECATED: Raw print to sys.__stdout__, otherwise identical interface to print(). |
176,963 | import atexit
import os
import sys
import tempfile
from pathlib import Path
from warnings import warn
from IPython.utils.decorators import undoc
from .capture import CapturedIO, capture_output
import sys
if sys.platform[:5] == 'linux':
def jiffies(_proc_pid_stat=f'/proc/{os.getpid()}/stat',... | DEPRECATED: Raw print to sys.__stderr__, otherwise identical interface to print(). |
176,964 | import clr
import System
import os
from ._process_common import arg_split
The provided code snippet includes necessary dependencies for implementing the `system` function. Write a Python function `def system(cmd)` to solve the following problem:
system(cmd) should work in a cli environment on Mac OSX, Linux, and Windo... | system(cmd) should work in a cli environment on Mac OSX, Linux, and Windows |
176,965 | import clr
import System
import os
from ._process_common import arg_split
The provided code snippet includes necessary dependencies for implementing the `getoutput` function. Write a Python function `def getoutput(cmd)` to solve the following problem:
getoutput(cmd) should work in a cli environment on Mac OSX, Linux, ... | getoutput(cmd) should work in a cli environment on Mac OSX, Linux, and Windows |
176,966 | import clr
import System
import os
from ._process_common import arg_split
The provided code snippet includes necessary dependencies for implementing the `check_pid` function. Write a Python function `def check_pid(pid)` to solve the following problem:
Check if a process with the given PID (pid) exists
Here is the fun... | Check if a process with the given PID (pid) exists |
176,967 | import ast
import dis
from types import CodeType, FrameType
from typing import Any, Callable, Iterator, Optional, Sequence, Set, Tuple, Type, Union, cast
from .executing import EnhancedAST, NotOneValueFound, Source, only, function_node_types, assert_
from ._exceptions import KnownIssue, VerifierFailure
from functools i... | null |
176,968 | import ast
import dis
from types import CodeType, FrameType
from typing import Any, Callable, Iterator, Optional, Sequence, Set, Tuple, Type, Union, cast
from .executing import EnhancedAST, NotOneValueFound, Source, only, function_node_types, assert_
from ._exceptions import KnownIssue, VerifierFailure
from functools i... | Parameters: node: the node which should be mangled name: the name of the node Returns: The mangled name of `node` |
176,969 | import __future__
import ast
import dis
import functools
import inspect
import io
import linecache
import re
import sys
import types
from collections import defaultdict, namedtuple
from copy import deepcopy
from itertools import islice
from operator import attrgetter
from threading import RLock
from typing import TYPE_... | null |
176,970 | import __future__
import ast
import dis
import functools
import inspect
import io
import linecache
import re
import sys
import types
from collections import defaultdict, namedtuple
from copy import deepcopy
from itertools import islice
from operator import attrgetter
from threading import RLock
from typing import TYPE_... | null |
176,971 | import __future__
import ast
import dis
import functools
import inspect
import io
import linecache
import re
import sys
import types
from collections import defaultdict, namedtuple
from copy import deepcopy
from itertools import islice
from operator import attrgetter
from threading import RLock
from typing import TYPE_... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.