id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
170,410
from qtpy import QtCore, QtGui, QtSvg, QtWidgets The provided code snippet includes necessary dependencies for implementing the `save_svg` function. Write a Python function `def save_svg(string, parent=None)` to solve the following problem: Prompts the user to save an SVG document to disk. Parameters ---------- string : basestring A Python string containing a SVG document. parent : QWidget, optional The parent to use for the file dialog. Returns ------- The name of the file to which the document was saved, or None if the save was cancelled. Here is the function: def save_svg(string, parent=None): """ Prompts the user to save an SVG document to disk. Parameters ---------- string : basestring A Python string containing a SVG document. parent : QWidget, optional The parent to use for the file dialog. Returns ------- The name of the file to which the document was saved, or None if the save was cancelled. """ if isinstance(string, str): string = string.encode('utf-8') dialog = QtWidgets.QFileDialog(parent, 'Save SVG Document') dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptSave) dialog.setDefaultSuffix('svg') dialog.setNameFilter('SVG document (*.svg)') if dialog.exec_(): filename = dialog.selectedFiles()[0] f = open(filename, 'wb') try: f.write(string) finally: f.close() return filename return None
Prompts the user to save an SVG document to disk. Parameters ---------- string : basestring A Python string containing a SVG document. parent : QWidget, optional The parent to use for the file dialog. Returns ------- The name of the file to which the document was saved, or None if the save was cancelled.
170,411
from qtpy import QtCore, QtGui, QtSvg, QtWidgets The provided code snippet includes necessary dependencies for implementing the `svg_to_clipboard` function. Write a Python function `def svg_to_clipboard(string)` to solve the following problem: Copy a SVG document to the clipboard. Parameters ---------- string : basestring A Python string containing a SVG document. Here is the function: def svg_to_clipboard(string): """ Copy a SVG document to the clipboard. Parameters ---------- string : basestring A Python string containing a SVG document. """ if isinstance(string, str): string = string.encode('utf-8') mime_data = QtCore.QMimeData() mime_data.setData('image/svg+xml', string) QtWidgets.QApplication.clipboard().setMimeData(mime_data)
Copy a SVG document to the clipboard. Parameters ---------- string : basestring A Python string containing a SVG document.
170,412
from qtpy import QtCore, QtGui, QtSvg, QtWidgets The provided code snippet includes necessary dependencies for implementing the `svg_to_image` function. Write a Python function `def svg_to_image(string, size=None)` to solve the following problem: Convert a SVG document to a QImage. Parameters ---------- string : basestring A Python string containing a SVG document. size : QSize, optional The size of the image that is produced. If not specified, the SVG document's default size is used. Raises ------ ValueError If an invalid SVG string is provided. Returns ------- A QImage of format QImage.Format_ARGB32. Here is the function: def svg_to_image(string, size=None): """ Convert a SVG document to a QImage. Parameters ---------- string : basestring A Python string containing a SVG document. size : QSize, optional The size of the image that is produced. If not specified, the SVG document's default size is used. Raises ------ ValueError If an invalid SVG string is provided. Returns ------- A QImage of format QImage.Format_ARGB32. """ if isinstance(string, str): string = string.encode('utf-8') renderer = QtSvg.QSvgRenderer(QtCore.QByteArray(string)) if not renderer.isValid(): raise ValueError('Invalid SVG data.') if size is None: size = renderer.defaultSize() image = QtGui.QImage(size, QtGui.QImage.Format_ARGB32) image.fill(0) painter = QtGui.QPainter(image) renderer.render(painter) return image
Convert a SVG document to a QImage. Parameters ---------- string : basestring A Python string containing a SVG document. size : QSize, optional The size of the image that is produced. If not specified, the SVG document's default size is used. Raises ------ ValueError If an invalid SVG string is provided. Returns ------- A QImage of format QImage.Format_ARGB32.
170,413
import ipython_genutils.text as text from qtpy import QtCore, QtGui, QtWidgets The provided code snippet includes necessary dependencies for implementing the `html_tableify` function. Write a Python function `def html_tableify(item_matrix, select=None, header=None , footer=None) ` to solve the following problem: returnr a string for an html table Here is the function: def html_tableify(item_matrix, select=None, header=None , footer=None) : """ returnr a string for an html table""" if not item_matrix : return '' html_cols = [] tds = lambda text : '<td>'+text+' </td>' trs = lambda text : '<tr>'+text+'</tr>' tds_items = [list(map(tds, row)) for row in item_matrix] if select : row, col = select tds_items[row][col] = '<td class="inverted">'\ +item_matrix[row][col]\ +' </td>' #select the right item html_cols = map(trs, (''.join(row) for row in tds_items)) head = '' foot = '' if header : head = ('<tr>'\ +''.join(('<td>'+header+'</td>')*len(item_matrix[0]))\ +'</tr>') if footer : foot = ('<tr>'\ +''.join(('<td>'+footer+'</td>')*len(item_matrix[0]))\ +'</tr>') html = ('<table class="completion" style="white-space:pre"' 'cellspacing=0>' + head + (''.join(html_cols)) + foot + '</table>') return html
returnr a string for an html table
170,414
import io import os import re from qtpy import QtWidgets IMG_RE = re.compile(r'<img src="(?P<name>[\d]+)" />') def default_image_tag(match, path = None, format = "png"): """ Return (X)HTML mark-up for the image-tag given by match. This default implementation merely removes the image, and exists mostly for documentation purposes. More information than is present in the Qt HTML is required to supply the images. Parameters ---------- match : re.SRE_Match A match to an HTML image tag as exported by Qt, with match.group("Name") containing the matched image ID. path : string|None, optional [default None] If not None, specifies a path to which supporting files may be written (e.g., for linked images). If None, all images are to be included inline. format : "png"|"svg", optional [default "png"] Format for returned or referenced images. """ return '' def fix_html(html): """ Transforms a Qt-generated HTML string into a standards-compliant one. Parameters ---------- html : unicode, A Python unicode string containing the Qt HTML. """ # A UTF-8 declaration is needed for proper rendering of some characters # (e.g., indented commands) when viewing exported HTML on a local system # (i.e., without seeing an encoding declaration in an HTTP header). # C.f. http://www.w3.org/International/O-charset for details. offset = html.find('<head>') if offset > -1: html = (html[:offset+6]+ '\n<meta http-equiv="Content-Type" '+ 'content="text/html; charset=utf-8" />\n'+ html[offset+6:]) # Replace empty paragraphs tags with line breaks. html = re.sub(EMPTY_P_RE, '<br/>', html) return html The provided code snippet includes necessary dependencies for implementing the `export_html` function. Write a Python function `def export_html(html, filename, image_tag = None, inline = True)` to solve the following problem: Export the contents of the ConsoleWidget as HTML. Parameters ---------- html : unicode, A Python unicode string containing the Qt HTML to export. filename : str The file to be saved. image_tag : callable, optional (default None) Used to convert images. See ``default_image_tag()`` for information. inline : bool, optional [default True] If True, include images as inline PNGs. Otherwise, include them as links to external PNG files, mimicking web browsers' "Web Page, Complete" behavior. Here is the function: def export_html(html, filename, image_tag = None, inline = True): """ Export the contents of the ConsoleWidget as HTML. Parameters ---------- html : unicode, A Python unicode string containing the Qt HTML to export. filename : str The file to be saved. image_tag : callable, optional (default None) Used to convert images. See ``default_image_tag()`` for information. inline : bool, optional [default True] If True, include images as inline PNGs. Otherwise, include them as links to external PNG files, mimicking web browsers' "Web Page, Complete" behavior. """ if image_tag is None: image_tag = default_image_tag if inline: path = None else: root,ext = os.path.splitext(filename) path = root + "_files" if os.path.isfile(path): raise OSError("%s exists, but is not a directory." % path) with io.open(filename, 'w', encoding='utf-8') as f: html = fix_html(html) f.write(IMG_RE.sub(lambda x: image_tag(x, path = path, format = "png"), html))
Export the contents of the ConsoleWidget as HTML. Parameters ---------- html : unicode, A Python unicode string containing the Qt HTML to export. filename : str The file to be saved. image_tag : callable, optional (default None) Used to convert images. See ``default_image_tag()`` for information. inline : bool, optional [default True] If True, include images as inline PNGs. Otherwise, include them as links to external PNG files, mimicking web browsers' "Web Page, Complete" behavior.
170,415
import io import os import re from qtpy import QtWidgets IMG_RE = re.compile(r'<img src="(?P<name>[\d]+)" />') def default_image_tag(match, path = None, format = "png"): """ Return (X)HTML mark-up for the image-tag given by match. This default implementation merely removes the image, and exists mostly for documentation purposes. More information than is present in the Qt HTML is required to supply the images. Parameters ---------- match : re.SRE_Match A match to an HTML image tag as exported by Qt, with match.group("Name") containing the matched image ID. path : string|None, optional [default None] If not None, specifies a path to which supporting files may be written (e.g., for linked images). If None, all images are to be included inline. format : "png"|"svg", optional [default "png"] Format for returned or referenced images. """ return '' def fix_html(html): """ Transforms a Qt-generated HTML string into a standards-compliant one. Parameters ---------- html : unicode, A Python unicode string containing the Qt HTML. """ # A UTF-8 declaration is needed for proper rendering of some characters # (e.g., indented commands) when viewing exported HTML on a local system # (i.e., without seeing an encoding declaration in an HTTP header). # C.f. http://www.w3.org/International/O-charset for details. offset = html.find('<head>') if offset > -1: html = (html[:offset+6]+ '\n<meta http-equiv="Content-Type" '+ 'content="text/html; charset=utf-8" />\n'+ html[offset+6:]) # Replace empty paragraphs tags with line breaks. html = re.sub(EMPTY_P_RE, '<br/>', html) return html The provided code snippet includes necessary dependencies for implementing the `export_xhtml` function. Write a Python function `def export_xhtml(html, filename, image_tag=None)` to solve the following problem: Export the contents of the ConsoleWidget as XHTML with inline SVGs. Parameters ---------- html : unicode, A Python unicode string containing the Qt HTML to export. filename : str The file to be saved. image_tag : callable, optional (default None) Used to convert images. See ``default_image_tag()`` for information. Here is the function: def export_xhtml(html, filename, image_tag=None): """ Export the contents of the ConsoleWidget as XHTML with inline SVGs. Parameters ---------- html : unicode, A Python unicode string containing the Qt HTML to export. filename : str The file to be saved. image_tag : callable, optional (default None) Used to convert images. See ``default_image_tag()`` for information. """ if image_tag is None: image_tag = default_image_tag with io.open(filename, 'w', encoding='utf-8') as f: # Hack to make xhtml header -- note that we are not doing any check for # valid XML. offset = html.find("<html>") assert offset > -1, 'Invalid HTML string: no <html> tag.' html = ('<html xmlns="http://www.w3.org/1999/xhtml">\n'+ html[offset+6:]) html = fix_html(html) f.write(IMG_RE.sub(lambda x: image_tag(x, path = None, format = "svg"), html))
Export the contents of the ConsoleWidget as XHTML with inline SVGs. Parameters ---------- html : unicode, A Python unicode string containing the Qt HTML to export. filename : str The file to be saved. image_tag : callable, optional (default None) Used to convert images. See ``default_image_tag()`` for information.
170,416
from qtpy import QtGui from qtconsole.qstringhelpers import qstring_length from pygments.formatters.html import HtmlFormatter from pygments.lexer import RegexLexer, _TokenType, Text, Error from pygments.lexers import Python3Lexer from pygments.styles import get_style_by_name def get_tokens_unprocessed(self, text, stack=('root',)): """ Split ``text`` into (tokentype, text) pairs. Monkeypatched to store the final stack on the object itself. The `text` parameter this gets passed is only the current line, so to highlight things like multiline strings correctly, we need to retrieve the state from the previous line (this is done in PygmentsHighlighter, below), and use it to continue processing the current line. """ pos = 0 tokendefs = self._tokens if hasattr(self, '_saved_state_stack'): statestack = list(self._saved_state_stack) else: statestack = list(stack) statetokens = tokendefs[statestack[-1]] while 1: for rexmatch, action, new_state in statetokens: m = rexmatch(text, pos) if m: if action is not None: if type(action) is _TokenType: yield pos, action, m.group() else: for item in action(self, m): yield item pos = m.end() if new_state is not None: # state transition if isinstance(new_state, tuple): for state in new_state: if state == '#pop': statestack.pop() elif state == '#push': statestack.append(statestack[-1]) else: statestack.append(state) elif isinstance(new_state, int): # pop del statestack[new_state:] elif new_state == '#push': statestack.append(statestack[-1]) else: assert False, "wrong state def: %r" % new_state statetokens = tokendefs[statestack[-1]] break else: try: if text[pos] == '\n': # at EOL, reset state to "root" pos += 1 statestack = ['root'] statetokens = tokendefs['root'] yield pos, Text, '\n' continue yield pos, Error, text[pos] pos += 1 except IndexError: break self._saved_state_stack = list(statestack) from contextlib import contextmanager class RegexLexer(Lexer, metaclass=RegexLexerMeta): """ Base for simple stateful regular expression-based lexers. Simplifies the lexing process so that you need only provide a list of states and regular expressions. """ #: Flags for compiling the regular expressions. #: Defaults to MULTILINE. flags = re.MULTILINE #: At all time there is a stack of states. Initially, the stack contains #: a single state 'root'. The top of the stack is called "the current state". #: #: Dict of ``{'state': [(regex, tokentype, new_state), ...], ...}`` #: #: ``new_state`` can be omitted to signify no state transition. #: If ``new_state`` is a string, it is pushed on the stack. This ensure #: the new current state is ``new_state``. #: If ``new_state`` is a tuple of strings, all of those strings are pushed #: on the stack and the current state will be the last element of the list. #: ``new_state`` can also be ``combined('state1', 'state2', ...)`` #: to signify a new, anonymous state combined from the rules of two #: or more existing ones. #: Furthermore, it can be '#pop' to signify going back one step in #: the state stack, or '#push' to push the current state on the stack #: again. Note that if you push while in a combined state, the combined #: state itself is pushed, and not only the state in which the rule is #: defined. #: #: The tuple can also be replaced with ``include('state')``, in which #: case the rules from the state named by the string are included in the #: current one. tokens = {} def get_tokens_unprocessed(self, text, stack=('root',)): """ Split ``text`` into (tokentype, text) pairs. ``stack`` is the initial stack (default: ``['root']``) """ pos = 0 tokendefs = self._tokens statestack = list(stack) statetokens = tokendefs[statestack[-1]] while 1: for rexmatch, action, new_state in statetokens: m = rexmatch(text, pos) if m: if action is not None: if type(action) is _TokenType: yield pos, action, m.group() else: yield from action(self, m) pos = m.end() if new_state is not None: # state transition if isinstance(new_state, tuple): for state in new_state: if state == '#pop': if len(statestack) > 1: statestack.pop() elif state == '#push': statestack.append(statestack[-1]) else: statestack.append(state) elif isinstance(new_state, int): # pop, but keep at least one state on the stack # (random code leading to unexpected pops should # not allow exceptions) if abs(new_state) >= len(statestack): del statestack[1:] else: del statestack[new_state:] elif new_state == '#push': statestack.append(statestack[-1]) else: assert False, "wrong state def: %r" % new_state statetokens = tokendefs[statestack[-1]] break else: # We are here only if all state tokens have been considered # and there was not a match on any of them. try: if text[pos] == '\n': # at EOL, reset state to "root" statestack = ['root'] statetokens = tokendefs['root'] yield pos, Whitespace, '\n' pos += 1 continue yield pos, Error, text[pos] pos += 1 except IndexError: break def _lexpatch(): try: orig = RegexLexer.get_tokens_unprocessed RegexLexer.get_tokens_unprocessed = get_tokens_unprocessed yield finally: pass RegexLexer.get_tokens_unprocessed = orig
null
170,417
import os import signal import sys from warnings import warn from packaging.version import parse from qtpy import QtCore, QtGui, QtWidgets, QT_VERSION from traitlets.config.application import boolean_flag from traitlets.config.application import catch_config_error from qtconsole.jupyter_widget import JupyterWidget from qtconsole.rich_jupyter_widget import RichJupyterWidget from qtconsole import styles, __version__ from qtconsole.mainwindow import MainWindow from qtconsole.client import QtKernelClient from qtconsole.manager import QtKernelManager from traitlets import ( Dict, Unicode, CBool, Any ) from jupyter_core.application import JupyterApp, base_flags, base_aliases from jupyter_client.consoleapp import ( JupyterConsoleApp, app_aliases, app_flags, ) from jupyter_client.localinterfaces import is_local_ip def gui_excepthook(exctype, value, tb): try: import ctypes, traceback MB_ICONERROR = 0x00000010 title = 'Error starting QtConsole' msg = ''.join(traceback.format_exception(exctype, value, tb)) ctypes.windll.user32.MessageBoxW(0, msg, title, MB_ICONERROR) finally: # Also call the old exception hook to let it do # its thing too. old_excepthook(exctype, value, tb)
null
170,418
import sys import webbrowser from functools import partial from threading import Thread from jupyter_core.paths import jupyter_runtime_dir from pygments.styles import get_all_styles from qtpy import QtGui, QtCore, QtWidgets from qtconsole import styles from qtconsole.jupyter_widget import JupyterWidget from qtconsole.usage import gui_reference class Thread: name: str ident: Optional[int] daemon: bool if sys.version_info >= (3,): def __init__( self, group: None = ..., target: Optional[Callable[..., Any]] = ..., name: Optional[str] = ..., args: Iterable[Any] = ..., kwargs: Mapping[str, Any] = ..., *, daemon: Optional[bool] = ..., ) -> None: ... else: def __init__( self, group: None = ..., target: Optional[Callable[..., Any]] = ..., name: Optional[Text] = ..., args: Iterable[Any] = ..., kwargs: Mapping[Text, Any] = ..., ) -> None: ... def start(self) -> None: ... def run(self) -> None: ... def join(self, timeout: Optional[float] = ...) -> None: ... def getName(self) -> str: ... def setName(self, name: Text) -> None: ... if sys.version_info >= (3, 8): def native_id(self) -> Optional[int]: ... # only available on some platforms def is_alive(self) -> bool: ... if sys.version_info < (3, 9): def isAlive(self) -> bool: ... def isDaemon(self) -> bool: ... def setDaemon(self, daemonic: bool) -> None: ... The provided code snippet includes necessary dependencies for implementing the `background` function. Write a Python function `def background(f)` to solve the following problem: call a function in a simple thread, to prevent blocking Here is the function: def background(f): """call a function in a simple thread, to prevent blocking""" t = Thread(target=f) t.start() return t
call a function in a simple thread, to prevent blocking
170,419
import inspect from typing import Any, Callable, Optional from jupyter_core.utils import ensure_async, run_sync Any = object() Optional: _SpecialForm = ... 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 `run_hook` function. Write a Python function `async def run_hook(hook: Optional[Callable], **kwargs: Any) -> None` to solve the following problem: Run a hook callback. Here is the function: async def run_hook(hook: Optional[Callable], **kwargs: Any) -> None: """Run a hook callback.""" if hook is None: return res = hook(**kwargs) if inspect.isawaitable(res): await res
Run a hook callback.
170,420
import math import numbers import re import types from binascii import b2a_base64 from datetime import datetime from typing import Dict Dict = _Alias() The provided code snippet includes necessary dependencies for implementing the `encode_images` function. Write a Python function `def encode_images(format_dict: Dict) -> Dict[str, str]` to solve the following problem: b64-encodes images in a displaypub format dict Perhaps this should be handled in json_clean itself? Parameters ---------- format_dict : dict A dictionary of display data keyed by mime-type Returns ------- format_dict : dict A copy of the same dictionary, but binary image data ('image/png', 'image/jpeg' or 'application/pdf') is base64-encoded. Here is the function: def encode_images(format_dict: Dict) -> Dict[str, str]: """b64-encodes images in a displaypub format dict Perhaps this should be handled in json_clean itself? Parameters ---------- format_dict : dict A dictionary of display data keyed by mime-type Returns ------- format_dict : dict A copy of the same dictionary, but binary image data ('image/png', 'image/jpeg' or 'application/pdf') is base64-encoded. """ return format_dict
b64-encodes images in a displaypub format dict Perhaps this should be handled in json_clean itself? Parameters ---------- format_dict : dict A dictionary of display data keyed by mime-type Returns ------- format_dict : dict A copy of the same dictionary, but binary image data ('image/png', 'image/jpeg' or 'application/pdf') is base64-encoded.
170,421
import math import numbers import re import types from binascii import b2a_base64 from datetime import datetime from typing import Dict ISO8601 = "%Y-%m-%dT%H:%M:%S.%f" datetime.strptime("1", "%d") class datetime(date): min: ClassVar[datetime] max: ClassVar[datetime] resolution: ClassVar[timedelta] if sys.version_info >= (3, 6): def __new__( cls: Type[_S], year: int, month: int, day: int, hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., *, fold: int = ..., ) -> _S: ... else: def __new__( cls: Type[_S], year: int, month: int, day: int, hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., ) -> _S: ... def year(self) -> int: ... def month(self) -> int: ... def day(self) -> int: ... def hour(self) -> int: ... def minute(self) -> int: ... def second(self) -> int: ... def microsecond(self) -> int: ... def tzinfo(self) -> Optional[_tzinfo]: ... if sys.version_info >= (3, 6): def fold(self) -> int: ... def fromtimestamp(cls: Type[_S], t: float, tz: Optional[_tzinfo] = ...) -> _S: ... def utcfromtimestamp(cls: Type[_S], t: float) -> _S: ... def today(cls: Type[_S]) -> _S: ... def fromordinal(cls: Type[_S], n: int) -> _S: ... if sys.version_info >= (3, 8): def now(cls: Type[_S], tz: Optional[_tzinfo] = ...) -> _S: ... else: def now(cls: Type[_S], tz: None = ...) -> _S: ... def now(cls, tz: _tzinfo) -> datetime: ... def utcnow(cls: Type[_S]) -> _S: ... if sys.version_info >= (3, 6): def combine(cls, date: _date, time: _time, tzinfo: Optional[_tzinfo] = ...) -> datetime: ... else: def combine(cls, date: _date, time: _time) -> datetime: ... if sys.version_info >= (3, 7): def fromisoformat(cls: Type[_S], date_string: str) -> _S: ... def strftime(self, fmt: _Text) -> str: ... if sys.version_info >= (3,): def __format__(self, fmt: str) -> str: ... else: def __format__(self, fmt: AnyStr) -> AnyStr: ... def toordinal(self) -> int: ... def timetuple(self) -> struct_time: ... if sys.version_info >= (3, 3): def timestamp(self) -> float: ... def utctimetuple(self) -> struct_time: ... def date(self) -> _date: ... def time(self) -> _time: ... def timetz(self) -> _time: ... if sys.version_info >= (3, 6): def replace( self, year: int = ..., month: int = ..., day: int = ..., hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., *, fold: int = ..., ) -> datetime: ... else: def replace( self, year: int = ..., month: int = ..., day: int = ..., hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., ) -> datetime: ... if sys.version_info >= (3, 8): def astimezone(self: _S, tz: Optional[_tzinfo] = ...) -> _S: ... elif sys.version_info >= (3, 3): def astimezone(self, tz: Optional[_tzinfo] = ...) -> datetime: ... else: def astimezone(self, tz: _tzinfo) -> datetime: ... def ctime(self) -> str: ... if sys.version_info >= (3, 6): def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ... else: def isoformat(self, sep: str = ...) -> str: ... def strptime(cls, date_string: _Text, format: _Text) -> datetime: ... def utcoffset(self) -> Optional[timedelta]: ... def tzname(self) -> Optional[str]: ... def dst(self) -> Optional[timedelta]: ... def __le__(self, other: datetime) -> bool: ... # type: ignore def __lt__(self, other: datetime) -> bool: ... # type: ignore def __ge__(self, other: datetime) -> bool: ... # type: ignore def __gt__(self, other: datetime) -> bool: ... # type: ignore if sys.version_info >= (3, 8): def __add__(self: _S, other: timedelta) -> _S: ... def __radd__(self: _S, other: timedelta) -> _S: ... else: def __add__(self, other: timedelta) -> datetime: ... def __radd__(self, other: timedelta) -> datetime: ... def __sub__(self, other: datetime) -> timedelta: ... def __sub__(self, other: timedelta) -> datetime: ... def __hash__(self) -> int: ... def weekday(self) -> int: ... def isoweekday(self) -> int: ... def isocalendar(self) -> Tuple[int, int, int]: ... The provided code snippet includes necessary dependencies for implementing the `json_clean` function. Write a Python function `def json_clean(obj)` to solve the following problem: Clean an object to ensure it's safe to encode in JSON. Atomic, immutable objects are returned unmodified. Sets and tuples are converted to lists, lists are copied and dicts are also copied. Note: dicts whose keys could cause collisions upon encoding (such as a dict with both the number 1 and the string '1' as keys) will cause a ValueError to be raised. Parameters ---------- obj : any python object Returns ------- out : object A version of the input which will not cause an encoding error when encoded as JSON. Note that this function does not *encode* its inputs, it simply sanitizes it so that there will be no encoding errors later. Here is the function: def json_clean(obj): """Clean an object to ensure it's safe to encode in JSON. Atomic, immutable objects are returned unmodified. Sets and tuples are converted to lists, lists are copied and dicts are also copied. Note: dicts whose keys could cause collisions upon encoding (such as a dict with both the number 1 and the string '1' as keys) will cause a ValueError to be raised. Parameters ---------- obj : any python object Returns ------- out : object A version of the input which will not cause an encoding error when encoded as JSON. Note that this function does not *encode* its inputs, it simply sanitizes it so that there will be no encoding errors later. """ # types that are 'atomic' and ok in json as-is. atomic_ok = (str, type(None)) # containers that we need to convert into lists container_to_list = (tuple, set, types.GeneratorType) # Since bools are a subtype of Integrals, which are a subtype of Reals, # we have to check them in that order. if isinstance(obj, bool): return obj if isinstance(obj, numbers.Integral): # cast int to int, in case subclasses override __str__ (e.g. boost enum, #4598) return int(obj) if isinstance(obj, numbers.Real): # cast out-of-range floats to their reprs if math.isnan(obj) or math.isinf(obj): return repr(obj) return float(obj) if isinstance(obj, atomic_ok): return obj if isinstance(obj, bytes): return b2a_base64(obj).decode('ascii') if isinstance(obj, container_to_list) or ( hasattr(obj, '__iter__') and hasattr(obj, '__next__') ): obj = list(obj) if isinstance(obj, list): return [json_clean(x) for x in obj] if isinstance(obj, dict): # First, validate that the dict won't lose data in conversion due to # key collisions after stringification. This can happen with keys like # True and 'true' or 1 and '1', which collide in JSON. nkeys = len(obj) nkeys_collapsed = len(set(map(str, obj))) if nkeys != nkeys_collapsed: raise ValueError( 'dict cannot be safely converted to JSON: ' 'key collision would lead to dropped values' ) # If all OK, proceed by making the new dict that will be json-safe out = {} for k, v in iter(obj.items()): out[str(k)] = json_clean(v) return out if isinstance(obj, datetime): return obj.strftime(ISO8601) # we don't understand it, it's probably an unserializable object raise ValueError("Can't clean for JSON: %r" % obj)
Clean an object to ensure it's safe to encode in JSON. Atomic, immutable objects are returned unmodified. Sets and tuples are converted to lists, lists are copied and dicts are also copied. Note: dicts whose keys could cause collisions upon encoding (such as a dict with both the number 1 and the string '1' as keys) will cause a ValueError to be raised. Parameters ---------- obj : any python object Returns ------- out : object A version of the input which will not cause an encoding error when encoded as JSON. Note that this function does not *encode* its inputs, it simply sanitizes it so that there will be no encoding errors later.
170,422
import asyncio import atexit import base64 import collections import datetime import re import signal import typing as t from contextlib import asynccontextmanager, contextmanager from queue import Empty from textwrap import dedent from time import monotonic from jupyter_client import KernelManager from jupyter_client.client import KernelClient from nbformat import NotebookNode from nbformat.v4 import output_from_msg from traitlets import Any, Bool, Callable, Dict, Enum, Integer, List, Type, Unicode, default from traitlets.config.configurable import LoggingConfigurable from .exceptions import ( CellControlSignal, CellExecutionComplete, CellExecutionError, CellTimeoutError, DeadKernelError, ) from .output_widget import OutputWidget from .util import ensure_async, run_hook, run_sync The provided code snippet includes necessary dependencies for implementing the `timestamp` function. Write a Python function `def timestamp(msg: t.Optional[t.Dict] = None) -> str` to solve the following problem: Get the timestamp for a message. Here is the function: def timestamp(msg: t.Optional[t.Dict] = None) -> str: """Get the timestamp for a message.""" if msg and 'header' in msg: # The test mocks don't provide a header, so tolerate that msg_header = msg['header'] if 'date' in msg_header and isinstance(msg_header['date'], datetime.datetime): try: # reformat datetime into expected format formatted_time = datetime.datetime.strftime( msg_header['date'], '%Y-%m-%dT%H:%M:%S.%fZ' ) if ( formatted_time ): # docs indicate strftime may return empty string, so let's catch that too return formatted_time except Exception: # noqa pass # fallback to a local time return datetime.datetime.utcnow().isoformat() + 'Z'
Get the timestamp for a message.
170,423
import asyncio import atexit import base64 import collections import datetime import re import signal import typing as t from contextlib import asynccontextmanager, contextmanager from queue import Empty from textwrap import dedent from time import monotonic from jupyter_client import KernelManager from jupyter_client.client import KernelClient from nbformat import NotebookNode from nbformat.v4 import output_from_msg from traitlets import Any, Bool, Callable, Dict, Enum, Integer, List, Type, Unicode, default from traitlets.config.configurable import LoggingConfigurable from .exceptions import ( CellControlSignal, CellExecutionComplete, CellExecutionError, CellTimeoutError, DeadKernelError, ) from .output_widget import OutputWidget from .util import ensure_async, run_hook, run_sync class NotebookClient(LoggingConfigurable): """ Encompasses a Client for executing cells in a notebook """ timeout: int = Integer( None, allow_none=True, help=dedent( """ The time to wait (in seconds) for output from executions. If a cell execution takes longer, a TimeoutError is raised. ``None`` or ``-1`` will disable the timeout. If ``timeout_func`` is set, it overrides ``timeout``. """ ), ).tag(config=True) timeout_func: t.Callable[..., t.Optional[int]] = Any( default_value=None, allow_none=True, help=dedent( """ A callable which, when given the cell source as input, returns the time to wait (in seconds) for output from cell executions. If a cell execution takes longer, a TimeoutError is raised. Returning ``None`` or ``-1`` will disable the timeout for the cell. Not setting ``timeout_func`` will cause the client to default to using the ``timeout`` trait for all cells. The ``timeout_func`` trait overrides ``timeout`` if it is not ``None``. """ ), ).tag(config=True) interrupt_on_timeout: bool = Bool( False, help=dedent( """ If execution of a cell times out, interrupt the kernel and continue executing other cells rather than throwing an error and stopping. """ ), ).tag(config=True) error_on_timeout: t.Optional[t.Dict] = Dict( default_value=None, allow_none=True, help=dedent( """ If a cell execution was interrupted after a timeout, don't wait for the execute_reply from the kernel (e.g. KeyboardInterrupt error). Instead, return an execute_reply with the given error, which should be of the following form:: { 'ename': str, # Exception name, as a string 'evalue': str, # Exception value, as a string 'traceback': list(str), # traceback frames, as strings } """ ), ).tag(config=True) startup_timeout: int = Integer( 60, help=dedent( """ The time to wait (in seconds) for the kernel to start. If kernel startup takes longer, a RuntimeError is raised. """ ), ).tag(config=True) allow_errors: bool = Bool( False, help=dedent( """ If ``False`` (default), when a cell raises an error the execution is stopped and a ``CellExecutionError`` is raised, except if the error name is in ``allow_error_names``. If ``True``, execution errors are ignored and the execution is continued until the end of the notebook. Output from exceptions is included in the cell output in both cases. """ ), ).tag(config=True) allow_error_names: t.List[str] = List( Unicode(), help=dedent( """ List of error names which won't stop the execution. Use this if the ``allow_errors`` option it too general and you want to allow only specific kinds of errors. """ ), ).tag(config=True) force_raise_errors: bool = Bool( False, help=dedent( """ If False (default), errors from executing the notebook can be allowed with a ``raises-exception`` tag on a single cell, or the ``allow_errors`` or ``allow_error_names`` configurable options for all cells. An allowed error will be recorded in notebook output, and execution will continue. If an error occurs when it is not explicitly allowed, a ``CellExecutionError`` will be raised. If True, ``CellExecutionError`` will be raised for any error that occurs while executing the notebook. This overrides the ``allow_errors`` and ``allow_error_names`` options and the ``raises-exception`` cell tag. """ ), ).tag(config=True) skip_cells_with_tag: str = Unicode( 'skip-execution', help=dedent( """ Name of the cell tag to use to denote a cell that should be skipped. """ ), ).tag(config=True) extra_arguments: t.List = List(Unicode()).tag(config=True) kernel_name: str = Unicode( '', help=dedent( """ Name of kernel to use to execute the cells. If not set, use the kernel_spec embedded in the notebook. """ ), ).tag(config=True) raise_on_iopub_timeout: bool = Bool( False, help=dedent( """ If ``False`` (default), then the kernel will continue waiting for iopub messages until it receives a kernel idle message, or until a timeout occurs, at which point the currently executing cell will be skipped. If ``True``, then an error will be raised after the first timeout. This option generally does not need to be used, but may be useful in contexts where there is the possibility of executing notebooks with memory-consuming infinite loops. """ ), ).tag(config=True) store_widget_state: bool = Bool( True, help=dedent( """ If ``True`` (default), then the state of the Jupyter widgets created at the kernel will be stored in the metadata of the notebook. """ ), ).tag(config=True) record_timing: bool = Bool( True, help=dedent( """ If ``True`` (default), then the execution timings of each cell will be stored in the metadata of the notebook. """ ), ).tag(config=True) iopub_timeout: int = Integer( 4, allow_none=False, help=dedent( """ The time to wait (in seconds) for IOPub output. This generally doesn't need to be set, but on some slow networks (such as CI systems) the default timeout might not be long enough to get all messages. """ ), ).tag(config=True) shell_timeout_interval: int = Integer( 5, allow_none=False, help=dedent( """ The time to wait (in seconds) for Shell output before retrying. This generally doesn't need to be set, but if one needs to check for dead kernels at a faster rate this can help. """ ), ).tag(config=True) shutdown_kernel = Enum( ['graceful', 'immediate'], default_value='graceful', help=dedent( """ If ``graceful`` (default), then the kernel is given time to clean up after executing all cells, e.g., to execute its ``atexit`` hooks. If ``immediate``, then the kernel is signaled to immediately terminate. """ ), ).tag(config=True) ipython_hist_file: str = Unicode( default_value=':memory:', help="""Path to file to use for SQLite history database for an IPython kernel. The specific value ``:memory:`` (including the colon at both end but not the back ticks), avoids creating a history file. Otherwise, IPython will create a history file for each kernel. When running kernels simultaneously (e.g. via multiprocessing) saving history a single SQLite file can result in database errors, so using ``:memory:`` is recommended in non-interactive contexts. """, ).tag(config=True) kernel_manager_class = Type( config=True, klass=KernelManager, help='The kernel manager class to use.' ) on_notebook_start: t.Optional[t.Callable] = Callable( default_value=None, allow_none=True, help=dedent( """ A callable which executes after the kernel manager and kernel client are setup, and cells are about to execute. Called with kwargs ``notebook``. """ ), ).tag(config=True) on_notebook_complete: t.Optional[t.Callable] = Callable( default_value=None, allow_none=True, help=dedent( """ A callable which executes after the kernel is cleaned up. Called with kwargs ``notebook``. """ ), ).tag(config=True) on_notebook_error: t.Optional[t.Callable] = Callable( default_value=None, allow_none=True, help=dedent( """ A callable which executes when the notebook encounters an error. Called with kwargs ``notebook``. """ ), ).tag(config=True) on_cell_start: t.Optional[t.Callable] = Callable( default_value=None, allow_none=True, help=dedent( """ A callable which executes before a cell is executed and before non-executing cells are skipped. Called with kwargs ``cell`` and ``cell_index``. """ ), ).tag(config=True) on_cell_execute: t.Optional[t.Callable] = Callable( default_value=None, allow_none=True, help=dedent( """ A callable which executes just before a code cell is executed. Called with kwargs ``cell`` and ``cell_index``. """ ), ).tag(config=True) on_cell_complete: t.Optional[t.Callable] = Callable( default_value=None, allow_none=True, help=dedent( """ A callable which executes after a cell execution is complete. It is called even when a cell results in a failure. Called with kwargs ``cell`` and ``cell_index``. """ ), ).tag(config=True) on_cell_executed: t.Optional[t.Callable] = Callable( default_value=None, allow_none=True, help=dedent( """ A callable which executes just after a code cell is executed, whether or not it results in an error. Called with kwargs ``cell``, ``cell_index`` and ``execute_reply``. """ ), ).tag(config=True) on_cell_error: t.Optional[t.Callable] = Callable( default_value=None, allow_none=True, help=dedent( """ A callable which executes when a cell execution results in an error. This is executed even if errors are suppressed with ``cell_allows_errors``. Called with kwargs ``cell`, ``cell_index`` and ``execute_reply``. """ ), ).tag(config=True) def _kernel_manager_class_default(self) -> t.Type[KernelManager]: """Use a dynamic default to avoid importing jupyter_client at startup""" from jupyter_client import AsyncKernelManager return AsyncKernelManager _display_id_map = Dict( help=dedent( """ mapping of locations of outputs with a given display_id tracks cell index and output index within cell.outputs for each appearance of the display_id { 'display_id': { cell_idx: [output_idx,] } } """ ) ) display_data_priority: t.List = List( [ 'text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/markdown', 'text/plain', ], help=""" An ordered list of preferred output type, the first encountered will usually be used when converting discarding the others. """, ).tag(config=True) resources = Dict( help=dedent( """ Additional resources used in the conversion process. For example, passing ``{'metadata': {'path': run_path}}`` sets the execution path to ``run_path``. """ ) ) coalesce_streams = Bool( help=dedent( """ Merge all stream outputs with shared names into single streams. """ ) ) def __init__(self, nb: NotebookNode, km: t.Optional[KernelManager] = None, **kw: t.Any) -> None: """Initializes the execution manager. Parameters ---------- nb : NotebookNode Notebook being executed. km : KernelManager (optional) Optional kernel manager. If none is provided, a kernel manager will be created. """ super().__init__(**kw) self.nb: NotebookNode = nb self.km: t.Optional[KernelManager] = km self.owns_km: bool = km is None # whether the NotebookClient owns the kernel manager self.kc: t.Optional[KernelClient] = None self.reset_execution_trackers() self.widget_registry: t.Dict[str, t.Dict] = { '@jupyter-widgets/output': {'OutputModel': OutputWidget} } # comm_open_handlers should return an object with a .handle_msg(msg) method or None self.comm_open_handlers: t.Dict[str, t.Any] = { 'jupyter.widget': self.on_comm_open_jupyter_widget } def reset_execution_trackers(self) -> None: """Resets any per-execution trackers.""" self.task_poll_for_reply: t.Optional[asyncio.Future] = None self.code_cells_executed = 0 self._display_id_map = {} self.widget_state: t.Dict[str, t.Dict] = {} self.widget_buffers: t.Dict[str, t.Dict[t.Tuple[str, ...], t.Dict[str, str]]] = {} # maps to list of hooks, where the last is used, this is used # to support nested use of output widgets. self.output_hook_stack: t.Any = collections.defaultdict(list) # our front-end mimicking Output widgets self.comm_objects: t.Dict[str, t.Any] = {} def create_kernel_manager(self) -> KernelManager: """Creates a new kernel manager. Returns ------- km : KernelManager Kernel manager whose client class is asynchronous. """ if not self.kernel_name: kn = self.nb.metadata.get('kernelspec', {}).get('name') if kn is not None: self.kernel_name = kn if not self.kernel_name: self.km = self.kernel_manager_class(config=self.config) else: self.km = self.kernel_manager_class(kernel_name=self.kernel_name, config=self.config) assert self.km is not None return self.km async def _async_cleanup_kernel(self) -> None: assert self.km is not None now = self.shutdown_kernel == "immediate" try: # Queue the manager to kill the process, and recover gracefully if it's already dead. if await ensure_async(self.km.is_alive()): await ensure_async(self.km.shutdown_kernel(now=now)) except RuntimeError as e: # The error isn't specialized, so we have to check the message if 'No kernel is running!' not in str(e): raise finally: # Remove any state left over even if we failed to stop the kernel await ensure_async(self.km.cleanup_resources()) if getattr(self, "kc", None) and self.kc is not None: await ensure_async(self.kc.stop_channels()) # type:ignore[func-returns-value] self.kc = None self.km = None _cleanup_kernel = run_sync(_async_cleanup_kernel) async def async_start_new_kernel(self, **kwargs: t.Any) -> None: """Creates a new kernel. Parameters ---------- kwargs : Any options for ``self.kernel_manager_class.start_kernel()``. Because that defaults to AsyncKernelManager, this will likely include options accepted by ``AsyncKernelManager.start_kernel()``, which includes ``cwd``. """ assert self.km is not None resource_path = self.resources.get('metadata', {}).get('path') or None if resource_path and 'cwd' not in kwargs: kwargs["cwd"] = resource_path has_history_manager_arg = any( arg.startswith('--HistoryManager.hist_file') for arg in self.extra_arguments ) if ( hasattr(self.km, 'ipykernel') and self.km.ipykernel and self.ipython_hist_file and not has_history_manager_arg ): self.extra_arguments += [f'--HistoryManager.hist_file={self.ipython_hist_file}'] await ensure_async(self.km.start_kernel(extra_arguments=self.extra_arguments, **kwargs)) start_new_kernel = run_sync(async_start_new_kernel) async def async_start_new_kernel_client(self) -> KernelClient: """Creates a new kernel client. Returns ------- kc : KernelClient Kernel client as created by the kernel manager ``km``. """ assert self.km is not None try: self.kc = self.km.client() await ensure_async(self.kc.start_channels()) # type:ignore[func-returns-value] await ensure_async(self.kc.wait_for_ready(timeout=self.startup_timeout)) except Exception as e: self.log.error( "Error occurred while starting new kernel client for kernel {}: {}".format( getattr(self.km, 'kernel_id', None), str(e) ) ) await self._async_cleanup_kernel() raise self.kc.allow_stdin = False await run_hook(self.on_notebook_start, notebook=self.nb) return self.kc start_new_kernel_client = run_sync(async_start_new_kernel_client) def setup_kernel(self, **kwargs: t.Any) -> t.Generator: """ Context manager for setting up the kernel to execute a notebook. The assigns the Kernel Manager (``self.km``) if missing and Kernel Client(``self.kc``). When control returns from the yield it stops the client's zmq channels, and shuts down the kernel. """ # by default, cleanup the kernel client if we own the kernel manager # and keep it alive if we don't cleanup_kc = kwargs.pop('cleanup_kc', self.owns_km) # Can't use run_until_complete on an asynccontextmanager function :( if self.km is None: self.km = self.create_kernel_manager() if not self.km.has_kernel: self.start_new_kernel(**kwargs) if self.kc is None: self.start_new_kernel_client() try: yield finally: if cleanup_kc: self._cleanup_kernel() async def async_setup_kernel(self, **kwargs: t.Any) -> t.AsyncGenerator: """ Context manager for setting up the kernel to execute a notebook. This assigns the Kernel Manager (``self.km``) if missing and Kernel Client(``self.kc``). When control returns from the yield it stops the client's zmq channels, and shuts down the kernel. Handlers for SIGINT and SIGTERM are also added to cleanup in case of unexpected shutdown. """ # by default, cleanup the kernel client if we own the kernel manager # and keep it alive if we don't cleanup_kc = kwargs.pop('cleanup_kc', self.owns_km) if self.km is None: self.km = self.create_kernel_manager() # self._cleanup_kernel uses run_async, which ensures the ioloop is running again. # This is necessary as the ioloop has stopped once atexit fires. atexit.register(self._cleanup_kernel) def on_signal(): """Handle signals.""" self._async_cleanup_kernel_future = asyncio.ensure_future(self._async_cleanup_kernel()) atexit.unregister(self._cleanup_kernel) loop = asyncio.get_event_loop() try: loop.add_signal_handler(signal.SIGINT, on_signal) loop.add_signal_handler(signal.SIGTERM, on_signal) except RuntimeError: # NotImplementedError: Windows does not support signals. # RuntimeError: Raised when add_signal_handler is called outside the main thread pass if not self.km.has_kernel: await self.async_start_new_kernel(**kwargs) if self.kc is None: await self.async_start_new_kernel_client() try: yield except RuntimeError as e: await run_hook(self.on_notebook_error, notebook=self.nb) raise e finally: if cleanup_kc: await self._async_cleanup_kernel() await run_hook(self.on_notebook_complete, notebook=self.nb) atexit.unregister(self._cleanup_kernel) try: loop.remove_signal_handler(signal.SIGINT) loop.remove_signal_handler(signal.SIGTERM) except RuntimeError: pass async def async_execute(self, reset_kc: bool = False, **kwargs: t.Any) -> NotebookNode: """ Executes each code cell. Parameters ---------- kwargs : Any option for ``self.kernel_manager_class.start_kernel()``. Because that defaults to AsyncKernelManager, this will likely include options accepted by ``jupyter_client.AsyncKernelManager.start_kernel()``, which includes ``cwd``. ``reset_kc`` if True, the kernel client will be reset and a new one will be created (default: False). Returns ------- nb : NotebookNode The executed notebook. """ if reset_kc and self.owns_km: await self._async_cleanup_kernel() self.reset_execution_trackers() async with self.async_setup_kernel(**kwargs): assert self.kc is not None self.log.info("Executing notebook with kernel: %s" % self.kernel_name) msg_id = await ensure_async(self.kc.kernel_info()) info_msg = await self.async_wait_for_reply(msg_id) if info_msg is not None: if 'language_info' in info_msg['content']: self.nb.metadata['language_info'] = info_msg['content']['language_info'] else: raise RuntimeError( 'Kernel info received message content has no "language_info" key. ' 'Content is:\n' + str(info_msg['content']) ) for index, cell in enumerate(self.nb.cells): # Ignore `'execution_count' in content` as it's always 1 # when store_history is False await self.async_execute_cell( cell, index, execution_count=self.code_cells_executed + 1 ) self.set_widgets_metadata() return self.nb execute = run_sync(async_execute) def set_widgets_metadata(self) -> None: """Set with widget metadata.""" if self.widget_state: self.nb.metadata.widgets = { 'application/vnd.jupyter.widget-state+json': { 'state': { model_id: self._serialize_widget_state(state) for model_id, state in self.widget_state.items() if '_model_name' in state }, 'version_major': 2, 'version_minor': 0, } } for key, widget in self.nb.metadata.widgets[ 'application/vnd.jupyter.widget-state+json' ]['state'].items(): buffers = self.widget_buffers.get(key) if buffers: widget['buffers'] = list(buffers.values()) def _update_display_id(self, display_id: str, msg: t.Dict) -> None: """Update outputs with a given display_id""" if display_id not in self._display_id_map: self.log.debug("display id %r not in %s", display_id, self._display_id_map) return if msg['header']['msg_type'] == 'update_display_data': msg['header']['msg_type'] = 'display_data' try: out = output_from_msg(msg) except ValueError: self.log.error(f"unhandled iopub msg: {msg['msg_type']}") return for cell_idx, output_indices in self._display_id_map[display_id].items(): cell = self.nb['cells'][cell_idx] outputs = cell['outputs'] for output_idx in output_indices: outputs[output_idx]['data'] = out['data'] outputs[output_idx]['metadata'] = out['metadata'] async def _async_poll_for_reply( self, msg_id: str, cell: NotebookNode, timeout: t.Optional[int], task_poll_output_msg: asyncio.Future, task_poll_kernel_alive: asyncio.Future, ) -> t.Dict: msg: t.Dict assert self.kc is not None new_timeout: t.Optional[float] = None if timeout is not None: deadline = monotonic() + timeout new_timeout = float(timeout) error_on_timeout_execute_reply = None while True: try: if error_on_timeout_execute_reply: msg = error_on_timeout_execute_reply msg['parent_header'] = {'msg_id': msg_id} else: msg = await ensure_async(self.kc.shell_channel.get_msg(timeout=new_timeout)) if msg['parent_header'].get('msg_id') == msg_id: if self.record_timing: cell['metadata']['execution']['shell.execute_reply'] = timestamp(msg) try: await asyncio.wait_for(task_poll_output_msg, self.iopub_timeout) except (asyncio.TimeoutError, Empty): if self.raise_on_iopub_timeout: task_poll_kernel_alive.cancel() raise CellTimeoutError.error_from_timeout_and_cell( "Timeout waiting for IOPub output", self.iopub_timeout, cell ) from None else: self.log.warning("Timeout waiting for IOPub output") task_poll_kernel_alive.cancel() return msg else: if new_timeout is not None: new_timeout = max(0, deadline - monotonic()) except Empty: # received no message, check if kernel is still alive assert timeout is not None task_poll_kernel_alive.cancel() await self._async_check_alive() error_on_timeout_execute_reply = await self._async_handle_timeout(timeout, cell) async def _async_poll_output_msg( self, parent_msg_id: str, cell: NotebookNode, cell_index: int ) -> None: assert self.kc is not None while True: msg = await ensure_async(self.kc.iopub_channel.get_msg(timeout=None)) if msg['parent_header'].get('msg_id') == parent_msg_id: try: # Will raise CellExecutionComplete when completed self.process_message(msg, cell, cell_index) except CellExecutionComplete: return async def _async_poll_kernel_alive(self) -> None: while True: await asyncio.sleep(1) try: await self._async_check_alive() except DeadKernelError: assert self.task_poll_for_reply is not None self.task_poll_for_reply.cancel() return def _get_timeout(self, cell: t.Optional[NotebookNode]) -> t.Optional[int]: if self.timeout_func is not None and cell is not None: timeout = self.timeout_func(cell) else: timeout = self.timeout if not timeout or timeout < 0: timeout = None return timeout async def _async_handle_timeout( self, timeout: int, cell: t.Optional[NotebookNode] = None ) -> t.Union[None, t.Dict]: self.log.error("Timeout waiting for execute reply (%is)." % timeout) if self.interrupt_on_timeout: self.log.error("Interrupting kernel") assert self.km is not None await ensure_async(self.km.interrupt_kernel()) if self.error_on_timeout: execute_reply = {"content": {**self.error_on_timeout, "status": "error"}} return execute_reply return None else: assert cell is not None raise CellTimeoutError.error_from_timeout_and_cell( "Cell execution timed out", timeout, cell ) async def _async_check_alive(self) -> None: assert self.kc is not None if not await ensure_async(self.kc.is_alive()): # type:ignore[attr-defined] self.log.error("Kernel died while waiting for execute reply.") raise DeadKernelError("Kernel died") async def async_wait_for_reply( self, msg_id: str, cell: t.Optional[NotebookNode] = None ) -> t.Optional[t.Dict]: """Wait for a message reply.""" assert self.kc is not None # wait for finish, with timeout timeout = self._get_timeout(cell) cummulative_time = 0 while True: try: msg: t.Dict = await ensure_async( self.kc.shell_channel.get_msg(timeout=self.shell_timeout_interval) ) except Empty: await self._async_check_alive() cummulative_time += self.shell_timeout_interval if timeout and cummulative_time > timeout: await self._async_handle_timeout(timeout, cell) break else: if msg['parent_header'].get('msg_id') == msg_id: return msg return None wait_for_reply = run_sync(async_wait_for_reply) # Backwards compatibility naming for papermill _wait_for_reply = wait_for_reply def _passed_deadline(self, deadline: int) -> bool: if deadline is not None and deadline - monotonic() <= 0: return True return False async def _check_raise_for_error( self, cell: NotebookNode, cell_index: int, exec_reply: t.Optional[t.Dict] ) -> None: if exec_reply is None: return None exec_reply_content = exec_reply['content'] if exec_reply_content['status'] != 'error': return None cell_allows_errors = (not self.force_raise_errors) and ( self.allow_errors or exec_reply_content.get('ename') in self.allow_error_names or "raises-exception" in cell.metadata.get("tags", []) ) await run_hook( self.on_cell_error, cell=cell, cell_index=cell_index, execute_reply=exec_reply ) if not cell_allows_errors: raise CellExecutionError.from_cell_and_msg(cell, exec_reply_content) async def async_execute_cell( self, cell: NotebookNode, cell_index: int, execution_count: t.Optional[int] = None, store_history: bool = True, ) -> NotebookNode: """ Executes a single code cell. To execute all cells see :meth:`execute`. Parameters ---------- cell : nbformat.NotebookNode The cell which is currently being processed. cell_index : int The position of the cell within the notebook object. execution_count : int The execution count to be assigned to the cell (default: Use kernel response) store_history : bool Determines if history should be stored in the kernel (default: False). Specific to ipython kernels, which can store command histories. Returns ------- output : dict The execution output payload (or None for no output). Raises ------ CellExecutionError If execution failed and should raise an exception, this will be raised with defaults about the failure. Returns ------- cell : NotebookNode The cell which was just processed. """ assert self.kc is not None await run_hook(self.on_cell_start, cell=cell, cell_index=cell_index) if cell.cell_type != 'code' or not cell.source.strip(): self.log.debug("Skipping non-executing cell %s", cell_index) return cell if self.skip_cells_with_tag in cell.metadata.get("tags", []): self.log.debug("Skipping tagged cell %s", cell_index) return cell if self.record_timing: # clear execution metadata prior to execution cell['metadata']['execution'] = {} self.log.debug("Executing cell:\n%s", cell.source) cell_allows_errors = (not self.force_raise_errors) and ( self.allow_errors or "raises-exception" in cell.metadata.get("tags", []) ) await run_hook(self.on_cell_execute, cell=cell, cell_index=cell_index) parent_msg_id = await ensure_async( self.kc.execute( cell.source, store_history=store_history, stop_on_error=not cell_allows_errors ) ) await run_hook(self.on_cell_complete, cell=cell, cell_index=cell_index) # We launched a code cell to execute self.code_cells_executed += 1 exec_timeout = self._get_timeout(cell) cell.outputs = [] self.clear_before_next_output = False task_poll_kernel_alive = asyncio.ensure_future(self._async_poll_kernel_alive()) task_poll_output_msg = asyncio.ensure_future( self._async_poll_output_msg(parent_msg_id, cell, cell_index) ) self.task_poll_for_reply = asyncio.ensure_future( self._async_poll_for_reply( parent_msg_id, cell, exec_timeout, task_poll_output_msg, task_poll_kernel_alive ) ) try: exec_reply = await self.task_poll_for_reply except asyncio.CancelledError: # can only be cancelled by task_poll_kernel_alive when the kernel is dead task_poll_output_msg.cancel() raise DeadKernelError("Kernel died") from None except Exception as e: # Best effort to cancel request if it hasn't been resolved try: # Check if the task_poll_output is doing the raising for us if not isinstance(e, CellControlSignal): task_poll_output_msg.cancel() finally: raise if execution_count: cell['execution_count'] = execution_count await run_hook( self.on_cell_executed, cell=cell, cell_index=cell_index, execute_reply=exec_reply ) await self._check_raise_for_error(cell, cell_index, exec_reply) if self.coalesce_streams and cell.outputs: new_outputs = [] streams: dict[str, NotebookNode] = {} for output in cell.outputs: if output["output_type"] == "stream": if output["name"] in streams: streams[output["name"]]["text"] += output["text"] else: new_outputs.append(output) streams[output["name"]] = output else: new_outputs.append(output) # process \r and \b characters for output in streams.values(): old = output["text"] while len(output["text"]) < len(old): old = output["text"] # Cancel out anything-but-newline followed by backspace output["text"] = _RGX_BACKSPACE.sub("", output["text"]) # Replace all carriage returns not followed by newline output["text"] = _RGX_CARRIAGERETURN.sub("", output["text"]) # We also want to ensure stdout and stderr are always in the same consecutive order, # because they are asynchronous, so order isn't guaranteed. for i, output in enumerate(new_outputs): if output["output_type"] == "stream" and output["name"] == "stderr": if ( len(new_outputs) >= i + 2 and new_outputs[i + 1]["output_type"] == "stream" and new_outputs[i + 1]["name"] == "stdout" ): stdout = new_outputs.pop(i + 1) new_outputs.insert(i, stdout) cell.outputs = new_outputs self.nb['cells'][cell_index] = cell return cell execute_cell = run_sync(async_execute_cell) def process_message( self, msg: t.Dict, cell: NotebookNode, cell_index: int ) -> t.Optional[NotebookNode]: """ Processes a kernel message, updates cell state, and returns the resulting output object that was appended to cell.outputs. The input argument *cell* is modified in-place. Parameters ---------- msg : dict The kernel message being processed. cell : nbformat.NotebookNode The cell which is currently being processed. cell_index : int The position of the cell within the notebook object. Returns ------- output : NotebookNode The execution output payload (or None for no output). Raises ------ CellExecutionComplete Once a message arrives which indicates computation completeness. """ msg_type = msg['msg_type'] self.log.debug("msg_type: %s", msg_type) content = msg['content'] self.log.debug("content: %s", content) display_id = content.get('transient', {}).get('display_id', None) if display_id and msg_type in {'execute_result', 'display_data', 'update_display_data'}: self._update_display_id(display_id, msg) # set the prompt number for the input and the output if 'execution_count' in content: cell['execution_count'] = content['execution_count'] if self.record_timing: if msg_type == 'status': if content['execution_state'] == 'idle': cell['metadata']['execution']['iopub.status.idle'] = timestamp(msg) elif content['execution_state'] == 'busy': cell['metadata']['execution']['iopub.status.busy'] = timestamp(msg) elif msg_type == 'execute_input': cell['metadata']['execution']['iopub.execute_input'] = timestamp(msg) if msg_type == 'status': if content['execution_state'] == 'idle': raise CellExecutionComplete() elif msg_type == 'clear_output': self.clear_output(cell.outputs, msg, cell_index) elif msg_type.startswith('comm'): self.handle_comm_msg(cell.outputs, msg, cell_index) # Check for remaining messages we don't process elif msg_type not in ['execute_input', 'update_display_data']: # Assign output as our processed "result" return self.output(cell.outputs, msg, display_id, cell_index) return None def output( self, outs: t.List, msg: t.Dict, display_id: str, cell_index: int ) -> t.Optional[NotebookNode]: """Handle output.""" msg_type = msg['msg_type'] out: t.Optional[NotebookNode] = None parent_msg_id = msg['parent_header'].get('msg_id') if self.output_hook_stack[parent_msg_id]: # if we have a hook registered, it will override our # default output behaviour (e.g. OutputWidget) hook = self.output_hook_stack[parent_msg_id][-1] hook.output(outs, msg, display_id, cell_index) return None try: out = output_from_msg(msg) except ValueError: self.log.error(f"unhandled iopub msg: {msg_type}") return None if self.clear_before_next_output: self.log.debug('Executing delayed clear_output') outs[:] = [] self.clear_display_id_mapping(cell_index) self.clear_before_next_output = False if display_id: # record output index in: # _display_id_map[display_id][cell_idx] cell_map = self._display_id_map.setdefault(display_id, {}) output_idx_list = cell_map.setdefault(cell_index, []) output_idx_list.append(len(outs)) outs.append(out) return out def clear_output(self, outs: t.List, msg: t.Dict, cell_index: int) -> None: """Clear output.""" content = msg['content'] parent_msg_id = msg['parent_header'].get('msg_id') if self.output_hook_stack[parent_msg_id]: # if we have a hook registered, it will override our # default clear_output behaviour (e.g. OutputWidget) hook = self.output_hook_stack[parent_msg_id][-1] hook.clear_output(outs, msg, cell_index) return if content.get('wait'): self.log.debug('Wait to clear output') self.clear_before_next_output = True else: self.log.debug('Immediate clear output') outs[:] = [] self.clear_display_id_mapping(cell_index) def clear_display_id_mapping(self, cell_index: int) -> None: """Clear a display id mapping for a cell.""" for _, cell_map in self._display_id_map.items(): if cell_index in cell_map: cell_map[cell_index] = [] def handle_comm_msg(self, outs: t.List, msg: t.Dict, cell_index: int) -> None: """Handle a comm message.""" content = msg['content'] data = content['data'] if self.store_widget_state and 'state' in data: # ignore custom msg'es self.widget_state.setdefault(content['comm_id'], {}).update(data['state']) if 'buffer_paths' in data and data['buffer_paths']: comm_id = content['comm_id'] if comm_id not in self.widget_buffers: self.widget_buffers[comm_id] = {} # for each comm, the path uniquely identifies a buffer new_buffers: t.Dict[t.Tuple[str, ...], t.Dict[str, str]] = { tuple(k["path"]): k for k in self._get_buffer_data(msg) } self.widget_buffers[comm_id].update(new_buffers) # There are cases where we need to mimic a frontend, to get similar behaviour as # when using the Output widget from Jupyter lab/notebook if msg['msg_type'] == 'comm_open': target = msg['content'].get('target_name') handler = self.comm_open_handlers.get(target) if handler: comm_id = msg['content']['comm_id'] comm_object = handler(msg) if comm_object: self.comm_objects[comm_id] = comm_object else: self.log.warning(f'No handler found for comm target {target!r}') elif msg['msg_type'] == 'comm_msg': content = msg['content'] comm_id = msg['content']['comm_id'] if comm_id in self.comm_objects: self.comm_objects[comm_id].handle_msg(msg) def _serialize_widget_state(self, state: t.Dict) -> t.Dict[str, t.Any]: """Serialize a widget state, following format in @jupyter-widgets/schema.""" return { 'model_name': state.get('_model_name'), 'model_module': state.get('_model_module'), 'model_module_version': state.get('_model_module_version'), 'state': state, } def _get_buffer_data(self, msg: t.Dict) -> t.List[t.Dict[str, str]]: encoded_buffers = [] paths = msg['content']['data']['buffer_paths'] buffers = msg['buffers'] for path, buffer in zip(paths, buffers): encoded_buffers.append( { 'data': base64.b64encode(buffer).decode('utf-8'), 'encoding': 'base64', 'path': path, } ) return encoded_buffers def register_output_hook(self, msg_id: str, hook: OutputWidget) -> None: """Registers an override object that handles output/clear_output instead. Multiple hooks can be registered, where the last one will be used (stack based) """ # mimics # https://jupyterlab.github.io/jupyterlab/services/interfaces/kernel.ikernelconnection.html#registermessagehook self.output_hook_stack[msg_id].append(hook) def remove_output_hook(self, msg_id: str, hook: OutputWidget) -> None: """Unregisters an override object that handles output/clear_output instead""" # mimics # https://jupyterlab.github.io/jupyterlab/services/interfaces/kernel.ikernelconnection.html#removemessagehook removed_hook = self.output_hook_stack[msg_id].pop() assert removed_hook == hook def on_comm_open_jupyter_widget(self, msg: t.Dict) -> t.Optional[t.Any]: """Handle a jupyter widget comm open.""" content = msg['content'] data = content['data'] state = data['state'] comm_id = msg['content']['comm_id'] module = self.widget_registry.get(state['_model_module']) if module: widget_class = module.get(state['_model_name']) if widget_class: return widget_class(comm_id, state, self.kc, self) return None The provided code snippet includes necessary dependencies for implementing the `execute` function. Write a Python function `def execute( nb: NotebookNode, cwd: t.Optional[str] = None, km: t.Optional[KernelManager] = None, **kwargs: t.Any, ) -> NotebookNode` to solve the following problem: Execute a notebook's code, updating outputs within the notebook object. This is a convenient wrapper around NotebookClient. It returns the modified notebook object. Parameters ---------- nb : NotebookNode The notebook object to be executed cwd : str, optional If supplied, the kernel will run in this directory km : AsyncKernelManager, optional If supplied, the specified kernel manager will be used for code execution. kwargs : Any other options for NotebookClient, e.g. timeout, kernel_name Here is the function: def execute( nb: NotebookNode, cwd: t.Optional[str] = None, km: t.Optional[KernelManager] = None, **kwargs: t.Any, ) -> NotebookNode: """Execute a notebook's code, updating outputs within the notebook object. This is a convenient wrapper around NotebookClient. It returns the modified notebook object. Parameters ---------- nb : NotebookNode The notebook object to be executed cwd : str, optional If supplied, the kernel will run in this directory km : AsyncKernelManager, optional If supplied, the specified kernel manager will be used for code execution. kwargs : Any other options for NotebookClient, e.g. timeout, kernel_name """ resources = {} if cwd is not None: resources['metadata'] = {'path': cwd} return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()
Execute a notebook's code, updating outputs within the notebook object. This is a convenient wrapper around NotebookClient. It returns the modified notebook object. Parameters ---------- nb : NotebookNode The notebook object to be executed cwd : str, optional If supplied, the kernel will run in this directory km : AsyncKernelManager, optional If supplied, the specified kernel manager will be used for code execution. kwargs : Any other options for NotebookClient, e.g. timeout, kernel_name
170,424
from collections import namedtuple import os from tornado import ( gen, web, ) from ..base.handlers import ( IPythonHandler, FilesRedirectHandler, path_regex, ) from ..utils import ( maybe_future, url_escape, ) from ..transutils import _ def namedtuple( typename: Union[str, unicode], field_names: Union[str, unicode, Iterable[Union[str, unicode]]], verbose: bool = ..., rename: bool = ..., ) -> Type[Tuple[Any, ...]]: _ = trans.gettext def get_exporter(name, config=get_config()): def get_export_names(config=get_config()): def get_frontend_exporters(): from nbconvert.exporters.base import get_export_names, get_exporter # name=exporter_name, display=export_from_notebook+extension ExporterInfo = namedtuple('ExporterInfo', ['name', 'display']) default_exporters = [ ExporterInfo(name='html', display='HTML (.html)'), ExporterInfo(name='latex', display='LaTeX (.tex)'), ExporterInfo(name='markdown', display='Markdown (.md)'), ExporterInfo(name='notebook', display='Notebook (.ipynb)'), ExporterInfo(name='pdf', display='PDF via LaTeX (.pdf)'), ExporterInfo(name='rst', display='reST (.rst)'), ExporterInfo(name='script', display='Script (.txt)'), ExporterInfo(name='slides', display='Reveal.js slides (.slides.html)') ] frontend_exporters = [] for name in get_export_names(): exporter_class = get_exporter(name) exporter_instance = exporter_class() ux_name = getattr(exporter_instance, 'export_from_notebook', None) super_uxname = getattr(super(exporter_class, exporter_instance), 'export_from_notebook', None) # Ensure export_from_notebook is explicitly defined & not inherited if ux_name is not None and ux_name != super_uxname: display = _(f'{ux_name} ({exporter_instance.file_extension})') frontend_exporters.append(ExporterInfo(name, display)) # Ensure default_exporters are in frontend_exporters if not already # This protects against nbconvert versions lower than 5.5 names = {exporter.name.lower() for exporter in frontend_exporters} for exporter in default_exporters: if exporter.name not in names: frontend_exporters.append(exporter) # Protect against nbconvert 5.5.0 python_exporter = ExporterInfo(name='python', display='python (.py)') if python_exporter in frontend_exporters: frontend_exporters.remove(python_exporter) # Protect against nbconvert 5.4.x template_exporter = ExporterInfo(name='custom', display='custom (.txt)') if template_exporter in frontend_exporters: frontend_exporters.remove(template_exporter) return sorted(frontend_exporters)
null
170,425
import errno import glob import json import os import copy from traitlets.config import LoggingConfigurable from traitlets.traitlets import Unicode, Bool 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.
170,426
import errno import glob import json import os import copy from traitlets.config import LoggingConfigurable from traitlets.traitlets import Unicode, Bool The provided code snippet includes necessary dependencies for implementing the `remove_defaults` function. Write a Python function `def remove_defaults(data, defaults)` to solve the following problem: Recursively remove items from dict that are already in defaults Here is the function: def remove_defaults(data, defaults): """Recursively remove items from dict that are already in defaults""" # copy the iterator, since data will be modified for key, value in list(data.items()): if key in defaults: if isinstance(value, dict): remove_defaults(data[key], defaults[key]) if not data[key]: # prune empty subdicts del data[key] else: if value == defaults[key]: del data[key]
Recursively remove items from dict that are already in defaults
170,427
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as TornadoFuture from tornado import gen from ipython_genutils import py3compat The provided code snippet includes necessary dependencies for implementing the `url_is_absolute` function. Write a Python function `def url_is_absolute(url)` to solve the following problem: Determine whether a given URL is absolute Here is the function: def url_is_absolute(url): """Determine whether a given URL is absolute""" return urlparse(url).path.startswith("/")
Determine whether a given URL is absolute
170,428
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as TornadoFuture from tornado import gen from ipython_genutils import py3compat def url_path_join(*pieces): """Join components of url into a relative url Use to prevent double slash when joining subpath. This will leave the initial and final / in place """ initial = pieces[0].startswith('/') final = pieces[-1].endswith('/') stripped = [s.strip('/') for s in pieces] result = '/'.join(s for s in stripped if s) if initial: result = '/' + result if final: result = result + '/' if result == '//': result = '/' return result import os del os The provided code snippet includes necessary dependencies for implementing the `path2url` function. Write a Python function `def path2url(path)` to solve the following problem: Convert a local file path to a URL Here is the function: def path2url(path): """Convert a local file path to a URL""" pieces = [ quote(p) for p in path.split(os.sep) ] # preserve trailing / if pieces[-1] == '': pieces[-1] = '/' url = url_path_join(*pieces) return url
Convert a local file path to a URL
170,429
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as TornadoFuture from tornado import gen from ipython_genutils import py3compat import os del os The provided code snippet includes necessary dependencies for implementing the `url2path` function. Write a Python function `def url2path(url)` to solve the following problem: Convert a URL to a local file path Here is the function: def url2path(url): """Convert a URL to a local file path""" pieces = [ unquote(p) for p in url.split('/') ] path = os.path.join(*pieces) return path
Convert a URL to a local file path
170,430
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as TornadoFuture from tornado import gen from ipython_genutils import py3compat The provided code snippet includes necessary dependencies for implementing the `url_escape` function. Write a Python function `def url_escape(path)` to solve the following problem: Escape special characters in a URL path Turns '/foo bar/' into '/foo%20bar/' Here is the function: def url_escape(path): """Escape special characters in a URL path Turns '/foo bar/' into '/foo%20bar/' """ parts = py3compat.unicode_to_str(path, encoding='utf8').split('/') return '/'.join([quote(p) for p in parts])
Escape special characters in a URL path Turns '/foo bar/' into '/foo%20bar/'
170,431
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as TornadoFuture from tornado import gen from ipython_genutils import py3compat The provided code snippet includes necessary dependencies for implementing the `url_unescape` function. Write a Python function `def url_unescape(path)` to solve the following problem: Unescape special characters in a URL path Turns '/foo%20bar/' into '/foo bar/' Here is the function: def url_unescape(path): """Unescape special characters in a URL path Turns '/foo%20bar/' into '/foo bar/' """ return '/'.join([ py3compat.str_to_unicode(unquote(p), encoding='utf8') for p in py3compat.unicode_to_str(path, encoding='utf8').split('/') ])
Unescape special characters in a URL path Turns '/foo%20bar/' into '/foo bar/'
170,432
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as TornadoFuture from tornado import gen from ipython_genutils import py3compat import os del os The provided code snippet includes necessary dependencies for implementing the `is_file_hidden_win` function. Write a Python function `def is_file_hidden_win(abs_path, stat_res=None)` to solve the following problem: Is a file hidden? This only checks the file itself; it should be called in combination with checking the directory containing the file. Use is_hidden() instead to check the file and its parent directories. Parameters ---------- abs_path : unicode The absolute path to check. stat_res : os.stat_result, optional Ignored on Windows, exists for compatibility with POSIX version of the function. Here is the function: def is_file_hidden_win(abs_path, stat_res=None): """Is a file hidden? This only checks the file itself; it should be called in combination with checking the directory containing the file. Use is_hidden() instead to check the file and its parent directories. Parameters ---------- abs_path : unicode The absolute path to check. stat_res : os.stat_result, optional Ignored on Windows, exists for compatibility with POSIX version of the function. """ if os.path.basename(abs_path).startswith('.'): return True win32_FILE_ATTRIBUTE_HIDDEN = 0x02 try: attrs = ctypes.windll.kernel32.GetFileAttributesW( py3compat.cast_unicode(abs_path) ) except AttributeError: pass else: if attrs > 0 and attrs & win32_FILE_ATTRIBUTE_HIDDEN: return True return False
Is a file hidden? This only checks the file itself; it should be called in combination with checking the directory containing the file. Use is_hidden() instead to check the file and its parent directories. Parameters ---------- abs_path : unicode The absolute path to check. stat_res : os.stat_result, optional Ignored on Windows, exists for compatibility with POSIX version of the function.
170,433
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as TornadoFuture from tornado import gen from ipython_genutils import py3compat UF_HIDDEN = getattr(stat, 'UF_HIDDEN', 32768) import os del os The provided code snippet includes necessary dependencies for implementing the `is_file_hidden_posix` function. Write a Python function `def is_file_hidden_posix(abs_path, stat_res=None)` to solve the following problem: Is a file hidden? This only checks the file itself; it should be called in combination with checking the directory containing the file. Use is_hidden() instead to check the file and its parent directories. Parameters ---------- abs_path : unicode The absolute path to check. stat_res : os.stat_result, optional The result of calling stat() on abs_path. If not passed, this function will call stat() internally. Here is the function: def is_file_hidden_posix(abs_path, stat_res=None): """Is a file hidden? This only checks the file itself; it should be called in combination with checking the directory containing the file. Use is_hidden() instead to check the file and its parent directories. Parameters ---------- abs_path : unicode The absolute path to check. stat_res : os.stat_result, optional The result of calling stat() on abs_path. If not passed, this function will call stat() internally. """ if os.path.basename(abs_path).startswith('.'): return True if stat_res is None or stat.S_ISLNK(stat_res.st_mode): try: stat_res = os.stat(abs_path) except OSError as e: if e.errno == errno.ENOENT: return False raise # check that dirs can be listed if stat.S_ISDIR(stat_res.st_mode): # use x-access, not actual listing, in case of slow/large listings if not os.access(abs_path, os.X_OK | os.R_OK): return True # check UF_HIDDEN if getattr(stat_res, 'st_flags', 0) & UF_HIDDEN: return True return False
Is a file hidden? This only checks the file itself; it should be called in combination with checking the directory containing the file. Use is_hidden() instead to check the file and its parent directories. Parameters ---------- abs_path : unicode The absolute path to check. stat_res : os.stat_result, optional The result of calling stat() on abs_path. If not passed, this function will call stat() internally.
170,434
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as TornadoFuture from tornado import gen from ipython_genutils import py3compat UF_HIDDEN = getattr(stat, 'UF_HIDDEN', 32768) def exists(path): """Replacement for `os.path.exists` which works for host mapped volumes on Windows containers """ try: os.lstat(path) except OSError: return False return True import os del os The provided code snippet includes necessary dependencies for implementing the `is_hidden` function. Write a Python function `def is_hidden(abs_path, abs_root='')` to solve the following problem: Is a file hidden or contained in a hidden directory? This will start with the rightmost path element and work backwards to the given root to see if a path is hidden or in a hidden directory. Hidden is determined by either name starting with '.' or the UF_HIDDEN flag as reported by stat. If abs_path is the same directory as abs_root, it will be visible even if that is a hidden folder. This only checks the visibility of files and directories *within* abs_root. Parameters ---------- abs_path : unicode The absolute path to check for hidden directories. abs_root : unicode The absolute path of the root directory in which hidden directories should be checked for. Here is the function: def is_hidden(abs_path, abs_root=''): """Is a file hidden or contained in a hidden directory? This will start with the rightmost path element and work backwards to the given root to see if a path is hidden or in a hidden directory. Hidden is determined by either name starting with '.' or the UF_HIDDEN flag as reported by stat. If abs_path is the same directory as abs_root, it will be visible even if that is a hidden folder. This only checks the visibility of files and directories *within* abs_root. Parameters ---------- abs_path : unicode The absolute path to check for hidden directories. abs_root : unicode The absolute path of the root directory in which hidden directories should be checked for. """ if os.path.normpath(abs_path) == os.path.normpath(abs_root): return False if is_file_hidden(abs_path): return True if not abs_root: abs_root = abs_path.split(os.sep, 1)[0] + os.sep inside_root = abs_path[len(abs_root):] if any(part.startswith('.') for part in inside_root.split(os.sep)): return True # check UF_HIDDEN on any location up to root. # is_file_hidden() already checked the file, so start from its parent dir path = os.path.dirname(abs_path) while path and path.startswith(abs_root) and path != abs_root: if not exists(path): path = os.path.dirname(path) continue try: # may fail on Windows junctions st = os.lstat(path) except OSError: return True if getattr(st, 'st_flags', 0) & UF_HIDDEN: return True path = os.path.dirname(path) return False
Is a file hidden or contained in a hidden directory? This will start with the rightmost path element and work backwards to the given root to see if a path is hidden or in a hidden directory. Hidden is determined by either name starting with '.' or the UF_HIDDEN flag as reported by stat. If abs_path is the same directory as abs_root, it will be visible even if that is a hidden folder. This only checks the visibility of files and directories *within* abs_root. Parameters ---------- abs_path : unicode The absolute path to check for hidden directories. abs_root : unicode The absolute path of the root directory in which hidden directories should be checked for.
170,435
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as TornadoFuture from tornado import gen from ipython_genutils import py3compat import os del os The provided code snippet includes necessary dependencies for implementing the `samefile_simple` function. Write a Python function `def samefile_simple(path, other_path)` to solve the following problem: Fill in for os.path.samefile when it is unavailable (Windows+py2). Do a case-insensitive string comparison in this case plus comparing the full stat result (including times) because Windows + py2 doesn't support the stat fields needed for identifying if it's the same file (st_ino, st_dev). Only to be used if os.path.samefile is not available. Parameters ----------- path: String representing a path to a file other_path: String representing a path to another file Returns ----------- same: Boolean that is True if both path and other path are the same Here is the function: def samefile_simple(path, other_path): """ Fill in for os.path.samefile when it is unavailable (Windows+py2). Do a case-insensitive string comparison in this case plus comparing the full stat result (including times) because Windows + py2 doesn't support the stat fields needed for identifying if it's the same file (st_ino, st_dev). Only to be used if os.path.samefile is not available. Parameters ----------- path: String representing a path to a file other_path: String representing a path to another file Returns ----------- same: Boolean that is True if both path and other path are the same """ path_stat = os.stat(path) other_path_stat = os.stat(other_path) return (path.lower() == other_path.lower() and path_stat == other_path_stat)
Fill in for os.path.samefile when it is unavailable (Windows+py2). Do a case-insensitive string comparison in this case plus comparing the full stat result (including times) because Windows + py2 doesn't support the stat fields needed for identifying if it's the same file (st_ino, st_dev). Only to be used if os.path.samefile is not available. Parameters ----------- path: String representing a path to a file other_path: String representing a path to another file Returns ----------- same: Boolean that is True if both path and other path are the same
170,436
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as TornadoFuture from tornado import gen from ipython_genutils import py3compat import os del os The provided code snippet includes necessary dependencies for implementing the `to_os_path` function. Write a Python function `def to_os_path(path, root='')` to solve the following problem: Convert an API path to a filesystem path If given, root will be prepended to the path. root must be a filesystem path already. Here is the function: def to_os_path(path, root=''): """Convert an API path to a filesystem path If given, root will be prepended to the path. root must be a filesystem path already. """ parts = path.strip('/').split('/') parts = [p for p in parts if p != ''] # remove duplicate splits path = os.path.join(root, *parts) return os.path.normpath(path)
Convert an API path to a filesystem path If given, root will be prepended to the path. root must be a filesystem path already.
170,437
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as TornadoFuture from tornado import gen from ipython_genutils import py3compat 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 following problem: 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. Here is the function: def check_version(v, check): """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. """ try: return LooseVersion(v) >= LooseVersion(check) except TypeError: return True
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.
170,438
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as TornadoFuture from tornado import gen from ipython_genutils import py3compat def _check_pid_win32(pid): import ctypes # OpenProcess returns 0 if no such process (of ours) exists # positive int otherwise handle = ctypes.windll.kernel32.OpenProcess(1,0,pid) if handle: # the handle must be closed or the kernel process object won't be freed ctypes.windll.kernel32.CloseHandle( handle ) return bool(handle)
null
170,439
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as TornadoFuture from tornado import gen from ipython_genutils import py3compat import os del os The provided code snippet includes necessary dependencies for implementing the `_check_pid_posix` function. Write a Python function `def _check_pid_posix(pid)` to solve the following problem: Copy of IPython.utils.process.check_pid Here is the function: def _check_pid_posix(pid): """Copy of IPython.utils.process.check_pid""" try: os.kill(pid, 0) except OSError as err: if err.errno == errno.ESRCH: return False elif err.errno == errno.EPERM: # Don't have permission to signal the process - probably means it exists return True raise else: return True
Copy of IPython.utils.process.check_pid
170,440
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as TornadoFuture from tornado import gen from ipython_genutils import py3compat Future = asyncio.Future The provided code snippet includes necessary dependencies for implementing the `maybe_future` function. Write a Python function `def maybe_future(obj)` to solve the following problem: Like tornado's deprecated gen.maybe_future but more compatible with asyncio for recent versions of tornado Here is the function: def maybe_future(obj): """Like tornado's deprecated gen.maybe_future but more compatible with asyncio for recent versions of tornado """ if inspect.isawaitable(obj): return asyncio.ensure_future(obj) elif isinstance(obj, concurrent.futures.Future): return asyncio.wrap_future(obj) else: # not awaitable, wrap scalar in future f = asyncio.Future() f.set_result(obj) return f
Like tornado's deprecated gen.maybe_future but more compatible with asyncio for recent versions of tornado
170,441
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as TornadoFuture from tornado import gen from ipython_genutils import py3compat The provided code snippet includes necessary dependencies for implementing the `run_sync` function. Write a Python function `def run_sync(maybe_async)` to solve the following problem: If async, runs maybe_async and blocks until it has executed, possibly creating an event loop. If not async, just returns maybe_async as it is the result of something that has already executed. Parameters ---------- maybe_async : async or non-async object The object to be executed, if it is async. Returns ------- result : Whatever the async object returns, or the object itself. Here is the function: def run_sync(maybe_async): """If async, runs maybe_async and blocks until it has executed, possibly creating an event loop. If not async, just returns maybe_async as it is the result of something that has already executed. Parameters ---------- maybe_async : async or non-async object The object to be executed, if it is async. Returns ------- result : Whatever the async object returns, or the object itself. """ if not inspect.isawaitable(maybe_async): # that was not something async, just return it return maybe_async # it is async, we need to run it in an event loop def wrapped(): create_new_event_loop = False try: loop = asyncio.get_event_loop() except RuntimeError: create_new_event_loop = True else: if loop.is_closed(): create_new_event_loop = True if create_new_event_loop: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: result = loop.run_until_complete(maybe_async) except RuntimeError as e: if str(e) == 'This event loop is already running': # just return a Future, hoping that it will be awaited result = asyncio.ensure_future(maybe_async) return result return wrapped()
If async, runs maybe_async and blocks until it has executed, possibly creating an event loop. If not async, just returns maybe_async as it is the result of something that has already executed. Parameters ---------- maybe_async : async or non-async object The object to be executed, if it is async. Returns ------- result : Whatever the async object returns, or the object itself.
170,442
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as TornadoFuture from tornado import gen from ipython_genutils import py3compat def urlencode_unix_socket_path(socket_path): """Encodes a UNIX socket path string from a socket path for the `http+unix` URI form.""" return socket_path.replace('/', '%2F') The provided code snippet includes necessary dependencies for implementing the `urlencode_unix_socket` function. Write a Python function `def urlencode_unix_socket(socket_path)` to solve the following problem: Encodes a UNIX socket URL from a socket path for the `http+unix` URI form. Here is the function: def urlencode_unix_socket(socket_path): """Encodes a UNIX socket URL from a socket path for the `http+unix` URI form.""" return f'http+unix://{urlencode_unix_socket_path(socket_path)}'
Encodes a UNIX socket URL from a socket path for the `http+unix` URI form.
170,443
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as TornadoFuture from tornado import gen from ipython_genutils import py3compat def exists(path): """Replacement for `os.path.exists` which works for host mapped volumes on Windows containers """ try: os.lstat(path) except OSError: return False return True import os del os The provided code snippet includes necessary dependencies for implementing the `unix_socket_in_use` function. Write a Python function `def unix_socket_in_use(socket_path)` to solve the following problem: Checks whether a UNIX socket path on disk is in use by attempting to connect to it. Here is the function: def unix_socket_in_use(socket_path): """Checks whether a UNIX socket path on disk is in use by attempting to connect to it.""" if not os.path.exists(socket_path): return False try: sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.connect(socket_path) except OSError: return False else: return True finally: sock.close()
Checks whether a UNIX socket path on disk is in use by attempting to connect to it.
170,444
import importlib import sys from jupyter_core.paths import jupyter_config_path from ._version import __version__ from .config_manager import BaseJSONConfigManager from .extensions import ( BaseExtensionApp, _get_config_dir, GREEN_ENABLED, RED_DISABLED, GREEN_OK, RED_X ) from traitlets import Bool from traitlets.utils.importstring import import_item def validate_serverextension(import_name, logger=None): """Assess the health of an installed server extension Returns a list of validation warnings. Parameters ---------- import_name : str Importable Python module (dotted-notation) exposing the magic-named `load_jupyter_server_extension` function logger : Jupyter logger [optional] Logger instance to use """ warnings = [] infos = [] func = None if logger: logger.info(" - Validating...") try: mod = importlib.import_module(import_name) func = getattr(mod, 'load_jupyter_server_extension', None) version = getattr(mod, '__version__', '') except Exception: logger.warning("Error loading server extension %s", import_name) import_msg = " {} is {} importable?" if func is not None: infos.append(import_msg.format(GREEN_OK, import_name)) else: warnings.append(import_msg.format(RED_X, import_name)) post_mortem = " {} {} {}" if logger: if warnings: [logger.info(info) for info in infos] [logger.warn(warning) for warning in warnings] else: logger.info(post_mortem.format(import_name, version, GREEN_OK)) return warnings class BaseJSONConfigManager(LoggingConfigurable): """General JSON config manager Deals with persisting/storing config in a json file with optionally default values in a {section_name}.d directory. """ config_dir = Unicode('.') read_directory = Bool(True) def ensure_config_dir_exists(self): """Will try to create the config_dir directory.""" try: os.makedirs(self.config_dir, 0o755) except OSError as e: if e.errno != errno.EEXIST: raise def file_name(self, section_name): """Returns the json filename for the section_name: {config_dir}/{section_name}.json""" return os.path.join(self.config_dir, section_name+'.json') def directory(self, section_name): """Returns the directory name for the section name: {config_dir}/{section_name}.d""" return os.path.join(self.config_dir, section_name+'.d') def get(self, section_name, include_root=True): """Retrieve the config data for the specified section. Returns the data as a dictionary, or an empty dictionary if the file doesn't exist. When include_root is False, it will not read the root .json file, effectively returning the default values. """ paths = [self.file_name(section_name)] if include_root else [] if self.read_directory: pattern = os.path.join(self.directory(section_name), '*.json') # These json files should be processed first so that the # {section_name}.json take precedence. # The idea behind this is that installing a Python package may # put a json file somewhere in the a .d directory, while the # .json file is probably a user configuration. paths = sorted(glob.glob(pattern)) + paths self.log.debug('Paths used for configuration of %s: \n\t%s', section_name, '\n\t'.join(paths)) data = {} for path in paths: if os.path.isfile(path): with open(path, encoding='utf-8') as f: recursive_update(data, json.load(f)) return data def set(self, section_name, data): """Store the given config data. """ filename = self.file_name(section_name) self.ensure_config_dir_exists() if self.read_directory: # we will modify data in place, so make a copy data = copy.deepcopy(data) defaults = self.get(section_name, include_root=False) remove_defaults(data, defaults) # Generate the JSON up front, since it could raise an exception, # in order to avoid writing half-finished corrupted data to disk. json_content = json.dumps(data, indent=2) f = open(filename, 'w', encoding='utf-8') with f: f.write(json_content) def update(self, section_name, new_data): """Modify the config section by recursively updating it with new_data. Returns the modified config data as a dictionary. """ data = self.get(section_name) recursive_update(data, new_data) self.set(section_name, data) return data def _get_config_dir(user=False, sys_prefix=False): """Get the location of config files for the current context Returns the string to the environment Parameters ---------- user : bool [default: False] Get the user's .jupyter config directory sys_prefix : bool [default: False] Get sys.prefix, i.e. ~/.envs/my-env/etc/jupyter """ user = False if sys_prefix else user if user and sys_prefix: raise ArgumentConflict("Cannot specify more than one of user or sys_prefix") if user: nbext = jupyter_config_dir() elif sys_prefix: nbext = ENV_CONFIG_PATH[0] else: nbext = SYSTEM_CONFIG_PATH[0] return nbext The provided code snippet includes necessary dependencies for implementing the `toggle_serverextension_python` function. Write a Python function `def toggle_serverextension_python(import_name, enabled=None, parent=None, user=True, sys_prefix=False, logger=None)` to solve the following problem: Toggle a server extension. By default, toggles the extension in the system-wide Jupyter configuration location (e.g. /usr/local/etc/jupyter). Parameters ---------- import_name : str Importable Python module (dotted-notation) exposing the magic-named `load_jupyter_server_extension` function enabled : bool [default: None] Toggle state for the extension. Set to None to toggle, True to enable, and False to disable the extension. parent : Configurable [default: None] user : bool [default: True] Toggle in the user's configuration location (e.g. ~/.jupyter). sys_prefix : bool [default: False] Toggle in the current Python environment's configuration location (e.g. ~/.envs/my-env/etc/jupyter). Will override `user`. logger : Jupyter logger [optional] Logger instance to use Here is the function: def toggle_serverextension_python(import_name, enabled=None, parent=None, user=True, sys_prefix=False, logger=None): """Toggle a server extension. By default, toggles the extension in the system-wide Jupyter configuration location (e.g. /usr/local/etc/jupyter). Parameters ---------- import_name : str Importable Python module (dotted-notation) exposing the magic-named `load_jupyter_server_extension` function enabled : bool [default: None] Toggle state for the extension. Set to None to toggle, True to enable, and False to disable the extension. parent : Configurable [default: None] user : bool [default: True] Toggle in the user's configuration location (e.g. ~/.jupyter). sys_prefix : bool [default: False] Toggle in the current Python environment's configuration location (e.g. ~/.envs/my-env/etc/jupyter). Will override `user`. logger : Jupyter logger [optional] Logger instance to use """ user = False if sys_prefix else user config_dir = _get_config_dir(user=user, sys_prefix=sys_prefix) cm = BaseJSONConfigManager(parent=parent, config_dir=config_dir) cfg = cm.get("jupyter_notebook_config") server_extensions = ( cfg.setdefault("NotebookApp", {}) .setdefault("nbserver_extensions", {}) ) old_enabled = server_extensions.get(import_name, None) new_enabled = enabled if enabled is not None else not old_enabled if logger: if new_enabled: logger.info(f"Enabling: {import_name}") else: logger.info(f"Disabling: {import_name}") server_extensions[import_name] = new_enabled if logger: logger.info(f"- Writing config: {config_dir}") cm.update("jupyter_notebook_config", cfg) if new_enabled: validate_serverextension(import_name, logger)
Toggle a server extension. By default, toggles the extension in the system-wide Jupyter configuration location (e.g. /usr/local/etc/jupyter). Parameters ---------- import_name : str Importable Python module (dotted-notation) exposing the magic-named `load_jupyter_server_extension` function enabled : bool [default: None] Toggle state for the extension. Set to None to toggle, True to enable, and False to disable the extension. parent : Configurable [default: None] user : bool [default: True] Toggle in the user's configuration location (e.g. ~/.jupyter). sys_prefix : bool [default: False] Toggle in the current Python environment's configuration location (e.g. ~/.envs/my-env/etc/jupyter). Will override `user`. logger : Jupyter logger [optional] Logger instance to use
170,445
import importlib import sys from jupyter_core.paths import jupyter_config_path from ._version import __version__ from .config_manager import BaseJSONConfigManager from .extensions import ( BaseExtensionApp, _get_config_dir, GREEN_ENABLED, RED_DISABLED, GREEN_OK, RED_X ) from traitlets import Bool from traitlets.utils.importstring import import_item def import_item(name): """Import and return ``bar`` given the string ``foo.bar``. Calling ``bar = import_item("foo.bar")`` is the functional equivalent of executing the code ``from foo import bar``. Parameters ---------- name : string The fully qualified name of the module/package being imported. Returns ------- mod : module object The module that was imported. """ if not isinstance(name, str): raise TypeError("import_item accepts strings, not '%s'." % type(name)) parts = name.rsplit(".", 1) if len(parts) == 2: # called with 'foo.bar....' package, obj = parts module = __import__(package, fromlist=[obj]) try: pak = getattr(module, obj) except AttributeError as e: raise ImportError("No module named %s" % obj) from e return pak else: # called with un-dotted string return __import__(parts[0]) The provided code snippet includes necessary dependencies for implementing the `_get_server_extension_metadata` function. Write a Python function `def _get_server_extension_metadata(module)` to solve the following problem: Load server extension metadata from a module. Returns a tuple of ( the package as loaded a list of server extension specs: [ { "module": "mockextension" } ] ) Parameters ---------- module : str Importable Python module exposing the magic-named `_jupyter_server_extension_paths` function Here is the function: def _get_server_extension_metadata(module): """Load server extension metadata from a module. Returns a tuple of ( the package as loaded a list of server extension specs: [ { "module": "mockextension" } ] ) Parameters ---------- module : str Importable Python module exposing the magic-named `_jupyter_server_extension_paths` function """ m = import_item(module) if not hasattr(m, '_jupyter_server_extension_paths'): raise KeyError(f'The Python module {module} does not include any valid server extensions') return m, m._jupyter_server_extension_paths()
Load server extension metadata from a module. Returns a tuple of ( the package as loaded a list of server extension specs: [ { "module": "mockextension" } ] ) Parameters ---------- module : str Importable Python module exposing the magic-named `_jupyter_server_extension_paths` function
170,446
import io import os import zipfile from tornado import gen, web, escape from tornado.log import app_log from ..base.handlers import ( IPythonHandler, FilesRedirectHandler, path_regex, ) from ..utils import maybe_future from nbformat import from_dict from ipython_genutils.py3compat import cast_bytes from ipython_genutils import text def find_resource_files(output_files_dir): files = [] for dirpath, dirnames, filenames in os.walk(output_files_dir): files.extend([os.path.join(dirpath, f) for f in filenames]) return files
null
170,447
import io import os import zipfile from tornado import gen, web, escape from tornado.log import app_log from ..base.handlers import ( IPythonHandler, FilesRedirectHandler, path_regex, ) from ..utils import maybe_future from nbformat import from_dict from ipython_genutils.py3compat import cast_bytes from ipython_genutils import text def cast_bytes(s, encoding=None): if not isinstance(s, bytes): return encode(s, encoding) return s The provided code snippet includes necessary dependencies for implementing the `respond_zip` function. Write a Python function `def respond_zip(handler, name, output, resources)` to solve the following problem: Zip up the output and resource files and respond with the zip file. Returns True if it has served a zip file, False if there are no resource files, in which case we serve the plain output file. Here is the function: def respond_zip(handler, name, output, resources): """Zip up the output and resource files and respond with the zip file. Returns True if it has served a zip file, False if there are no resource files, in which case we serve the plain output file. """ # Check if we have resource files we need to zip output_files = resources.get('outputs', None) if not output_files: return False # Headers zip_filename = os.path.splitext(name)[0] + '.zip' handler.set_attachment_header(zip_filename) handler.set_header('Content-Type', 'application/zip') handler.set_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0') # Prepare the zip file buffer = io.BytesIO() zipf = zipfile.ZipFile(buffer, mode='w', compression=zipfile.ZIP_DEFLATED) output_filename = os.path.splitext(name)[0] + resources['output_extension'] zipf.writestr(output_filename, cast_bytes(output, 'utf-8')) for filename, data in output_files.items(): zipf.writestr(os.path.basename(filename), data) zipf.close() handler.finish(buffer.getvalue()) return True
Zip up the output and resource files and respond with the zip file. Returns True if it has served a zip file, False if there are no resource files, in which case we serve the plain output file.
170,448
import io import os import zipfile from tornado import gen, web, escape from tornado.log import app_log from ..base.handlers import ( IPythonHandler, FilesRedirectHandler, path_regex, ) from ..utils import maybe_future from nbformat import from_dict from ipython_genutils.py3compat import cast_bytes from ipython_genutils import text app_log = logging.getLogger("tornado.application") The provided code snippet includes necessary dependencies for implementing the `get_exporter` function. Write a Python function `def get_exporter(format, **kwargs)` to solve the following problem: get an exporter, raising appropriate errors Here is the function: def get_exporter(format, **kwargs): """get an exporter, raising appropriate errors""" # if this fails, will raise 500 try: from nbconvert.exporters.base import get_exporter except ImportError as e: raise web.HTTPError(500, f"Could not import nbconvert: {e}") from e try: Exporter = get_exporter(format) except KeyError as e: # should this be 400? raise web.HTTPError(404, f"No exporter for format: {format}") from e try: return Exporter(**kwargs) except Exception as e: app_log.exception("Could not construct Exporter: %s", Exporter) raise web.HTTPError(500, f"Could not construct Exporter: {e}") from e
get an exporter, raising appropriate errors
170,449
import os import json from socket import gaierror from tornado import web from tornado.escape import json_encode, json_decode, url_escape from tornado.httpclient import HTTPClient, AsyncHTTPClient, HTTPError from ..services.kernels.kernelmanager import AsyncMappingKernelManager from ..services.sessions.sessionmanager import SessionManager from jupyter_client.kernelspec import KernelSpecManager from ..utils import url_path_join from traitlets import Instance, Unicode, Int, Float, Bool, default, validate, TraitError from traitlets.config import SingletonConfigurable class GatewayClient(SingletonConfigurable): """This class manages the configuration. It's its own singleton class so that we can share these values across all objects. It also contains some helper methods to build request arguments out of the various config options. """ url = Unicode(default_value=None, allow_none=True, config=True, help="""The url of the Kernel or Enterprise Gateway server where kernel specifications are defined and kernel management takes place. If defined, this Notebook server acts as a proxy for all kernel management and kernel specification retrieval. (JUPYTER_GATEWAY_URL env var) """ ) url_env = 'JUPYTER_GATEWAY_URL' def _url_default(self): return os.environ.get(self.url_env) def _url_validate(self, proposal): value = proposal['value'] # Ensure value, if present, starts with 'http' if value is not None and len(value) > 0: if not str(value).lower().startswith('http'): raise TraitError(f"GatewayClient url must start with 'http': '{value!r}'") return value ws_url = Unicode(default_value=None, allow_none=True, config=True, help="""The websocket url of the Kernel or Enterprise Gateway server. If not provided, this value will correspond to the value of the Gateway url with 'ws' in place of 'http'. (JUPYTER_GATEWAY_WS_URL env var) """ ) ws_url_env = 'JUPYTER_GATEWAY_WS_URL' def _ws_url_default(self): default_value = os.environ.get(self.ws_url_env) if default_value is None: if self.gateway_enabled: default_value = self.url.lower().replace('http', 'ws') return default_value def _ws_url_validate(self, proposal): value = proposal['value'] # Ensure value, if present, starts with 'ws' if value is not None and len(value) > 0: if not str(value).lower().startswith('ws'): raise TraitError(f"GatewayClient ws_url must start with 'ws': '{value!r}'") return value kernels_endpoint_default_value = '/api/kernels' kernels_endpoint_env = 'JUPYTER_GATEWAY_KERNELS_ENDPOINT' kernels_endpoint = Unicode(default_value=kernels_endpoint_default_value, config=True, help="""The gateway API endpoint for accessing kernel resources (JUPYTER_GATEWAY_KERNELS_ENDPOINT env var)""") def _kernels_endpoint_default(self): return os.environ.get(self.kernels_endpoint_env, self.kernels_endpoint_default_value) kernelspecs_endpoint_default_value = '/api/kernelspecs' kernelspecs_endpoint_env = 'JUPYTER_GATEWAY_KERNELSPECS_ENDPOINT' kernelspecs_endpoint = Unicode(default_value=kernelspecs_endpoint_default_value, config=True, help="""The gateway API endpoint for accessing kernelspecs (JUPYTER_GATEWAY_KERNELSPECS_ENDPOINT env var)""") def _kernelspecs_endpoint_default(self): return os.environ.get(self.kernelspecs_endpoint_env, self.kernelspecs_endpoint_default_value) kernelspecs_resource_endpoint_default_value = '/kernelspecs' kernelspecs_resource_endpoint_env = 'JUPYTER_GATEWAY_KERNELSPECS_RESOURCE_ENDPOINT' kernelspecs_resource_endpoint = Unicode(default_value=kernelspecs_resource_endpoint_default_value, config=True, help="""The gateway endpoint for accessing kernelspecs resources (JUPYTER_GATEWAY_KERNELSPECS_RESOURCE_ENDPOINT env var)""") def _kernelspecs_resource_endpoint_default(self): return os.environ.get(self.kernelspecs_resource_endpoint_env, self.kernelspecs_resource_endpoint_default_value) connect_timeout_default_value = 40.0 connect_timeout_env = 'JUPYTER_GATEWAY_CONNECT_TIMEOUT' connect_timeout = Float(default_value=connect_timeout_default_value, config=True, help="""The time allowed for HTTP connection establishment with the Gateway server. (JUPYTER_GATEWAY_CONNECT_TIMEOUT env var)""") def connect_timeout_default(self): return float(os.environ.get('JUPYTER_GATEWAY_CONNECT_TIMEOUT', self.connect_timeout_default_value)) request_timeout_default_value = 40.0 request_timeout_env = 'JUPYTER_GATEWAY_REQUEST_TIMEOUT' request_timeout = Float(default_value=request_timeout_default_value, config=True, help="""The time allowed for HTTP request completion. (JUPYTER_GATEWAY_REQUEST_TIMEOUT env var)""") def request_timeout_default(self): return float(os.environ.get('JUPYTER_GATEWAY_REQUEST_TIMEOUT', self.request_timeout_default_value)) client_key = Unicode(default_value=None, allow_none=True, config=True, help="""The filename for client SSL key, if any. (JUPYTER_GATEWAY_CLIENT_KEY env var) """ ) client_key_env = 'JUPYTER_GATEWAY_CLIENT_KEY' def _client_key_default(self): return os.environ.get(self.client_key_env) client_cert = Unicode(default_value=None, allow_none=True, config=True, help="""The filename for client SSL certificate, if any. (JUPYTER_GATEWAY_CLIENT_CERT env var) """ ) client_cert_env = 'JUPYTER_GATEWAY_CLIENT_CERT' def _client_cert_default(self): return os.environ.get(self.client_cert_env) ca_certs = Unicode(default_value=None, allow_none=True, config=True, help="""The filename of CA certificates or None to use defaults. (JUPYTER_GATEWAY_CA_CERTS env var) """ ) ca_certs_env = 'JUPYTER_GATEWAY_CA_CERTS' def _ca_certs_default(self): return os.environ.get(self.ca_certs_env) http_user = Unicode(default_value=None, allow_none=True, config=True, help="""The username for HTTP authentication. (JUPYTER_GATEWAY_HTTP_USER env var) """ ) http_user_env = 'JUPYTER_GATEWAY_HTTP_USER' def _http_user_default(self): return os.environ.get(self.http_user_env) http_pwd = Unicode(default_value=None, allow_none=True, config=True, help="""The password for HTTP authentication. (JUPYTER_GATEWAY_HTTP_PWD env var) """ ) http_pwd_env = 'JUPYTER_GATEWAY_HTTP_PWD' def _http_pwd_default(self): return os.environ.get(self.http_pwd_env) headers_default_value = '{}' headers_env = 'JUPYTER_GATEWAY_HEADERS' headers = Unicode(default_value=headers_default_value, allow_none=True, config=True, help="""Additional HTTP headers to pass on the request. This value will be converted to a dict. (JUPYTER_GATEWAY_HEADERS env var) """ ) def _headers_default(self): return os.environ.get(self.headers_env, self.headers_default_value) auth_token = Unicode(default_value=None, allow_none=True, config=True, help="""The authorization token used in the HTTP headers. (JUPYTER_GATEWAY_AUTH_TOKEN env var) """ ) auth_token_env = 'JUPYTER_GATEWAY_AUTH_TOKEN' def _auth_token_default(self): return os.environ.get(self.auth_token_env, '') validate_cert_default_value = True validate_cert_env = 'JUPYTER_GATEWAY_VALIDATE_CERT' validate_cert = Bool(default_value=validate_cert_default_value, config=True, help="""For HTTPS requests, determines if server's certificate should be validated or not. (JUPYTER_GATEWAY_VALIDATE_CERT env var)""" ) def validate_cert_default(self): return bool(os.environ.get(self.validate_cert_env, str(self.validate_cert_default_value)) not in ['no', 'false']) def __init__(self, **kwargs): super().__init__(**kwargs) self._static_args = {} # initialized on first use env_whitelist_default_value = '' env_whitelist_env = 'JUPYTER_GATEWAY_ENV_WHITELIST' env_whitelist = Unicode(default_value=env_whitelist_default_value, config=True, help="""A comma-separated list of environment variable names that will be included, along with their values, in the kernel startup request. The corresponding `env_whitelist` configuration value must also be set on the Gateway server - since that configuration value indicates which environmental values to make available to the kernel. (JUPYTER_GATEWAY_ENV_WHITELIST env var)""") def _env_whitelist_default(self): return os.environ.get(self.env_whitelist_env, self.env_whitelist_default_value) gateway_retry_interval_default_value = 1.0 gateway_retry_interval_env = 'JUPYTER_GATEWAY_RETRY_INTERVAL' gateway_retry_interval = Float(default_value=gateway_retry_interval_default_value, config=True, help="""The time allowed for HTTP reconnection with the Gateway server for the first time. Next will be JUPYTER_GATEWAY_RETRY_INTERVAL multiplied by two in factor of numbers of retries but less than JUPYTER_GATEWAY_RETRY_INTERVAL_MAX. (JUPYTER_GATEWAY_RETRY_INTERVAL env var)""") def gateway_retry_interval_default(self): return float(os.environ.get('JUPYTER_GATEWAY_RETRY_INTERVAL', self.gateway_retry_interval_default_value)) gateway_retry_interval_max_default_value = 30.0 gateway_retry_interval_max_env = 'JUPYTER_GATEWAY_RETRY_INTERVAL_MAX' gateway_retry_interval_max = Float(default_value=gateway_retry_interval_max_default_value, config=True, help="""The maximum time allowed for HTTP reconnection retry with the Gateway server. (JUPYTER_GATEWAY_RETRY_INTERVAL_MAX env var)""") def gateway_retry_interval_max_default(self): return float(os.environ.get('JUPYTER_GATEWAY_RETRY_INTERVAL_MAX', self.gateway_retry_interval_max_default_value)) gateway_retry_max_default_value = 5 gateway_retry_max_env = 'JUPYTER_GATEWAY_RETRY_MAX' gateway_retry_max = Int(default_value=gateway_retry_max_default_value, config=True, help="""The maximum retries allowed for HTTP reconnection with the Gateway server. (JUPYTER_GATEWAY_RETRY_MAX env var)""") def gateway_retry_max_default(self): return int(os.environ.get('JUPYTER_GATEWAY_RETRY_MAX', self.gateway_retry_max_default_value)) def gateway_enabled(self): return bool(self.url is not None and len(self.url) > 0) # Ensure KERNEL_LAUNCH_TIMEOUT has a default value. KERNEL_LAUNCH_TIMEOUT = int(os.environ.get('KERNEL_LAUNCH_TIMEOUT', 40)) def init_static_args(self): """Initialize arguments used on every request. Since these are static values, we'll perform this operation once. """ # Ensure that request timeout and KERNEL_LAUNCH_TIMEOUT are the same, taking the # greater value of the two. if self.request_timeout < float(GatewayClient.KERNEL_LAUNCH_TIMEOUT): self.request_timeout = float(GatewayClient.KERNEL_LAUNCH_TIMEOUT) elif self.request_timeout > float(GatewayClient.KERNEL_LAUNCH_TIMEOUT): GatewayClient.KERNEL_LAUNCH_TIMEOUT = int(self.request_timeout) # Ensure any adjustments are reflected in env. os.environ['KERNEL_LAUNCH_TIMEOUT'] = str(GatewayClient.KERNEL_LAUNCH_TIMEOUT) self._static_args['headers'] = json.loads(self.headers) if 'Authorization' not in self._static_args['headers'].keys(): self._static_args['headers'].update({ 'Authorization': f'token {self.auth_token}' }) self._static_args['connect_timeout'] = self.connect_timeout self._static_args['request_timeout'] = self.request_timeout self._static_args['validate_cert'] = self.validate_cert if self.client_cert: self._static_args['client_cert'] = self.client_cert self._static_args['client_key'] = self.client_key if self.ca_certs: self._static_args['ca_certs'] = self.ca_certs if self.http_user: self._static_args['auth_username'] = self.http_user if self.http_pwd: self._static_args['auth_password'] = self.http_pwd def load_connection_args(self, **kwargs): """Merges the static args relative to the connection, with the given keyword arguments. If statics have yet to be initialized, we'll do that here. """ if len(self._static_args) == 0: self.init_static_args() for arg, static_value in self._static_args.items(): if arg == 'headers': given_value = kwargs.setdefault(arg, {}) if isinstance(given_value, dict): given_value.update(static_value) else: kwargs[arg] = static_value return kwargs class gaierror(error): def __init__(self, error: int = ..., string: str = ...) -> None: ... class AsyncHTTPClient(Configurable): """An non-blocking HTTP client. Example usage:: async def f(): http_client = AsyncHTTPClient() try: response = await http_client.fetch("http://www.google.com") except Exception as e: print("Error: %s" % e) else: print(response.body) The constructor for this class is magic in several respects: It actually creates an instance of an implementation-specific subclass, and instances are reused as a kind of pseudo-singleton (one per `.IOLoop`). The keyword argument ``force_instance=True`` can be used to suppress this singleton behavior. Unless ``force_instance=True`` is used, no arguments should be passed to the `AsyncHTTPClient` constructor. The implementation subclass as well as arguments to its constructor can be set with the static method `configure()` All `AsyncHTTPClient` implementations support a ``defaults`` keyword argument, which can be used to set default values for `HTTPRequest` attributes. For example:: AsyncHTTPClient.configure( None, defaults=dict(user_agent="MyUserAgent")) # or with force_instance: client = AsyncHTTPClient(force_instance=True, defaults=dict(user_agent="MyUserAgent")) .. versionchanged:: 5.0 The ``io_loop`` argument (deprecated since version 4.1) has been removed. """ _instance_cache = None # type: Dict[IOLoop, AsyncHTTPClient] def configurable_base(cls) -> Type[Configurable]: return AsyncHTTPClient def configurable_default(cls) -> Type[Configurable]: from tornado.simple_httpclient import SimpleAsyncHTTPClient return SimpleAsyncHTTPClient def _async_clients(cls) -> Dict[IOLoop, "AsyncHTTPClient"]: attr_name = "_async_client_dict_" + cls.__name__ if not hasattr(cls, attr_name): setattr(cls, attr_name, weakref.WeakKeyDictionary()) return getattr(cls, attr_name) def __new__(cls, force_instance: bool = False, **kwargs: Any) -> "AsyncHTTPClient": io_loop = IOLoop.current() if force_instance: instance_cache = None else: instance_cache = cls._async_clients() if instance_cache is not None and io_loop in instance_cache: return instance_cache[io_loop] instance = super(AsyncHTTPClient, cls).__new__(cls, **kwargs) # type: ignore # Make sure the instance knows which cache to remove itself from. # It can't simply call _async_clients() because we may be in # __new__(AsyncHTTPClient) but instance.__class__ may be # SimpleAsyncHTTPClient. instance._instance_cache = instance_cache if instance_cache is not None: instance_cache[instance.io_loop] = instance return instance def initialize(self, defaults: Optional[Dict[str, Any]] = None) -> None: self.io_loop = IOLoop.current() self.defaults = dict(HTTPRequest._DEFAULTS) if defaults is not None: self.defaults.update(defaults) self._closed = False def close(self) -> None: """Destroys this HTTP client, freeing any file descriptors used. This method is **not needed in normal use** due to the way that `AsyncHTTPClient` objects are transparently reused. ``close()`` is generally only necessary when either the `.IOLoop` is also being closed, or the ``force_instance=True`` argument was used when creating the `AsyncHTTPClient`. No other methods may be called on the `AsyncHTTPClient` after ``close()``. """ if self._closed: return self._closed = True if self._instance_cache is not None: cached_val = self._instance_cache.pop(self.io_loop, None) # If there's an object other than self in the instance # cache for our IOLoop, something has gotten mixed up. A # value of None appears to be possible when this is called # from a destructor (HTTPClient.__del__) as the weakref # gets cleared before the destructor runs. if cached_val is not None and cached_val is not self: raise RuntimeError("inconsistent AsyncHTTPClient cache") def fetch( self, request: Union[str, "HTTPRequest"], raise_error: bool = True, **kwargs: Any ) -> "Future[HTTPResponse]": """Executes a request, asynchronously returning an `HTTPResponse`. The request may be either a string URL or an `HTTPRequest` object. If it is a string, we construct an `HTTPRequest` using any additional kwargs: ``HTTPRequest(request, **kwargs)`` This method returns a `.Future` whose result is an `HTTPResponse`. By default, the ``Future`` will raise an `HTTPError` if the request returned a non-200 response code (other errors may also be raised if the server could not be contacted). Instead, if ``raise_error`` is set to False, the response will always be returned regardless of the response code. If a ``callback`` is given, it will be invoked with the `HTTPResponse`. In the callback interface, `HTTPError` is not automatically raised. Instead, you must check the response's ``error`` attribute or call its `~HTTPResponse.rethrow` method. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned `.Future` instead. The ``raise_error=False`` argument only affects the `HTTPError` raised when a non-200 response code is used, instead of suppressing all errors. """ if self._closed: raise RuntimeError("fetch() called on closed AsyncHTTPClient") if not isinstance(request, HTTPRequest): request = HTTPRequest(url=request, **kwargs) else: if kwargs: raise ValueError( "kwargs can't be used if request is an HTTPRequest object" ) # We may modify this (to add Host, Accept-Encoding, etc), # so make sure we don't modify the caller's object. This is also # where normal dicts get converted to HTTPHeaders objects. request.headers = httputil.HTTPHeaders(request.headers) request_proxy = _RequestProxy(request, self.defaults) future = Future() # type: Future[HTTPResponse] def handle_response(response: "HTTPResponse") -> None: if response.error: if raise_error or not response._error_is_response_code: future_set_exception_unless_cancelled(future, response.error) return future_set_result_unless_cancelled(future, response) self.fetch_impl(cast(HTTPRequest, request_proxy), handle_response) return future def fetch_impl( self, request: "HTTPRequest", callback: Callable[["HTTPResponse"], None] ) -> None: raise NotImplementedError() def configure( cls, impl: "Union[None, str, Type[Configurable]]", **kwargs: Any ) -> None: """Configures the `AsyncHTTPClient` subclass to use. ``AsyncHTTPClient()`` actually creates an instance of a subclass. This method may be called with either a class object or the fully-qualified name of such a class (or ``None`` to use the default, ``SimpleAsyncHTTPClient``) If additional keyword arguments are given, they will be passed to the constructor of each subclass instance created. The keyword argument ``max_clients`` determines the maximum number of simultaneous `~AsyncHTTPClient.fetch()` operations that can execute in parallel on each `.IOLoop`. Additional arguments may be supported depending on the implementation class in use. Example:: AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient") """ super(AsyncHTTPClient, cls).configure(impl, **kwargs) HTTPError = HTTPClientError The provided code snippet includes necessary dependencies for implementing the `gateway_request` function. Write a Python function `async def gateway_request(endpoint, **kwargs)` to solve the following problem: Make an async request to kernel gateway endpoint, returns a response Here is the function: async def gateway_request(endpoint, **kwargs): """Make an async request to kernel gateway endpoint, returns a response """ client = AsyncHTTPClient() kwargs = GatewayClient.instance().load_connection_args(**kwargs) try: response = await client.fetch(endpoint, **kwargs) # Trap a set of common exceptions so that we can inform the user that their Gateway url is incorrect # or the server is not running. # NOTE: We do this here since this handler is called during the Notebook's startup and subsequent refreshes # of the tree view. except ConnectionRefusedError as e: raise web.HTTPError( 503, f"Connection refused from Gateway server url '{GatewayClient.instance().url}'. " f"Check to be sure the Gateway instance is running." ) from e except HTTPError as e: # This can occur if the host is valid (e.g., foo.com) but there's nothing there. raise web.HTTPError( e.code, f"Error attempting to connect to Gateway server url '{GatewayClient.instance().url}'. " f"Ensure gateway url is valid and the Gateway instance is running." ) from e except gaierror as e: raise web.HTTPError( 404, f"The Gateway server specified in the gateway_url '{GatewayClient.instance().url}' " f"doesn't appear to be valid. " f"Ensure gateway url is valid and the Gateway instance is running." ) from e return response
Make an async request to kernel gateway endpoint, returns a response
170,450
import os import io import tarfile import nbformat The provided code snippet includes necessary dependencies for implementing the `_jupyter_bundlerextension_paths` function. Write a Python function `def _jupyter_bundlerextension_paths()` to solve the following problem: Metadata for notebook bundlerextension Here is the function: def _jupyter_bundlerextension_paths(): """Metadata for notebook bundlerextension""" return [{ # unique bundler name "name": "tarball_bundler", # module containing bundle function "module_name": "notebook.bundler.tarball_bundler", # human-readable menu item label "label" : "Notebook Tarball (tar.gz)", # group under 'deploy' or 'download' menu "group" : "download", }]
Metadata for notebook bundlerextension
170,451
import os import io import tarfile import nbformat The provided code snippet includes necessary dependencies for implementing the `bundle` function. Write a Python function `def bundle(handler, model)` to solve the following problem: Create a compressed tarball containing the notebook document. Parameters ---------- handler : tornado.web.RequestHandler Handler that serviced the bundle request model : dict Notebook model from the configured ContentManager Here is the function: def bundle(handler, model): """Create a compressed tarball containing the notebook document. Parameters ---------- handler : tornado.web.RequestHandler Handler that serviced the bundle request model : dict Notebook model from the configured ContentManager """ notebook_filename = model['name'] notebook_content = nbformat.writes(model['content']).encode('utf-8') notebook_name = os.path.splitext(notebook_filename)[0] tar_filename = f'{notebook_name}.tar.gz' info = tarfile.TarInfo(notebook_filename) info.size = len(notebook_content) with io.BytesIO() as tar_buffer: with tarfile.open(tar_filename, "w:gz", fileobj=tar_buffer) as tar: tar.addfile(info, io.BytesIO(notebook_content)) handler.set_attachment_header(tar_filename) handler.set_header('Content-Type', 'application/gzip') # Return the buffer value as the response handler.finish(tar_buffer.getvalue())
Create a compressed tarball containing the notebook document. Parameters ---------- handler : tornado.web.RequestHandler Handler that serviced the bundle request model : dict Notebook model from the configured ContentManager
170,452
import os import shutil import errno import nbformat import fnmatch import glob The provided code snippet includes necessary dependencies for implementing the `copy_filelist` function. Write a Python function `def copy_filelist(src, dst, src_relative_filenames)` to solve the following problem: Copies the given list of files, relative to src, into dst, creating directories along the way as needed and ignore existence errors. Skips any files that do not exist. Does not create empty directories from src in dst. Parameters ---------- src: str Root of the source directory dst: str Root of the destination directory src_relative_filenames: list Filenames relative to src Here is the function: def copy_filelist(src, dst, src_relative_filenames): """Copies the given list of files, relative to src, into dst, creating directories along the way as needed and ignore existence errors. Skips any files that do not exist. Does not create empty directories from src in dst. Parameters ---------- src: str Root of the source directory dst: str Root of the destination directory src_relative_filenames: list Filenames relative to src """ for filename in src_relative_filenames: # Only consider the file if it exists in src if os.path.isfile(os.path.join(src, filename)): parent_relative = os.path.dirname(filename) if parent_relative: # Make sure the parent directory exists parent_dst = os.path.join(dst, parent_relative) try: os.makedirs(parent_dst) except OSError as exc: if exc.errno == errno.EEXIST: pass else: raise exc shutil.copy2(os.path.join(src, filename), os.path.join(dst, filename))
Copies the given list of files, relative to src, into dst, creating directories along the way as needed and ignore existence errors. Skips any files that do not exist. Does not create empty directories from src in dst. Parameters ---------- src: str Root of the source directory dst: str Root of the destination directory src_relative_filenames: list Filenames relative to src
170,453
import os import io import zipfile import notebook.bundler.tools as tools The provided code snippet includes necessary dependencies for implementing the `_jupyter_bundlerextension_paths` function. Write a Python function `def _jupyter_bundlerextension_paths()` to solve the following problem: Metadata for notebook bundlerextension Here is the function: def _jupyter_bundlerextension_paths(): """Metadata for notebook bundlerextension""" return [{ 'name': 'notebook_zip_download', 'label': 'IPython Notebook bundle (.zip)', 'module_name': 'notebook.bundler.zip_bundler', 'group': 'download' }]
Metadata for notebook bundlerextension
170,454
import os import io import zipfile import notebook.bundler.tools as tools The provided code snippet includes necessary dependencies for implementing the `bundle` function. Write a Python function `def bundle(handler, model)` to solve the following problem: Create a zip file containing the original notebook and files referenced from it. Retain the referenced files in paths relative to the notebook. Return the zip as a file download. Assumes the notebook and other files are all on local disk. Parameters ---------- handler : tornado.web.RequestHandler Handler that serviced the bundle request model : dict Notebook model from the configured ContentManager Here is the function: def bundle(handler, model): """Create a zip file containing the original notebook and files referenced from it. Retain the referenced files in paths relative to the notebook. Return the zip as a file download. Assumes the notebook and other files are all on local disk. Parameters ---------- handler : tornado.web.RequestHandler Handler that serviced the bundle request model : dict Notebook model from the configured ContentManager """ abs_nb_path = os.path.join(handler.settings['contents_manager'].root_dir, model['path']) notebook_filename = model['name'] notebook_name = os.path.splitext(notebook_filename)[0] # Headers zip_filename = os.path.splitext(notebook_name)[0] + '.zip' handler.set_attachment_header(zip_filename) handler.set_header('Content-Type', 'application/zip') # Get associated files ref_filenames = tools.get_file_references(abs_nb_path, 4) # Prepare the zip file zip_buffer = io.BytesIO() zipf = zipfile.ZipFile(zip_buffer, mode='w', compression=zipfile.ZIP_DEFLATED) zipf.write(abs_nb_path, notebook_filename) notebook_dir = os.path.dirname(abs_nb_path) for nb_relative_filename in ref_filenames: # Build absolute path to file on disk abs_fn = os.path.join(notebook_dir, nb_relative_filename) # Store file under path relative to notebook zipf.write(abs_fn, nb_relative_filename) zipf.close() # Return the buffer value as the response handler.finish(zip_buffer.getvalue())
Create a zip file containing the original notebook and files referenced from it. Retain the referenced files in paths relative to the notebook. Return the zip as a file download. Assumes the notebook and other files are all on local disk. Parameters ---------- handler : tornado.web.RequestHandler Handler that serviced the bundle request model : dict Notebook model from the configured ContentManager
170,455
import sys import os from ..extensions import BaseExtensionApp, _get_config_dir, GREEN_ENABLED, RED_DISABLED from .._version import __version__ from notebook.config_manager import BaseJSONConfigManager from jupyter_core.paths import jupyter_config_path from traitlets.utils.importstring import import_item from traitlets import Bool def _set_bundler_state_python(state, module, user, sys_prefix, logger=None): """Enables or disables bundlers defined in a Python package. Returns a list of whether the state was achieved for each bundler. Parameters ---------- state : Bool Whether the extensions should be enabled module : str Importable Python module exposing the magic-named `_jupyter_bundlerextension_paths` function user : bool Whether to enable in the user's nbconfig directory. sys_prefix : bool Enable/disable in the sys.prefix, i.e. environment logger : Jupyter logger [optional] Logger instance to use """ m, bundlers = _get_bundler_metadata(module) return [_set_bundler_state(name=bundler["name"], label=bundler["label"], module_name=bundler["module_name"], group=bundler["group"], state=state, user=user, sys_prefix=sys_prefix, logger=logger) for bundler in bundlers] The provided code snippet includes necessary dependencies for implementing the `enable_bundler_python` function. Write a Python function `def enable_bundler_python(module, user=True, sys_prefix=False, logger=None)` to solve the following problem: Enables bundlers defined in a Python package. Returns whether each bundle defined in the packaged was enabled or not. Parameters ---------- module : str Importable Python module exposing the magic-named `_jupyter_bundlerextension_paths` function user : bool [default: True] Whether to enable in the user's nbconfig directory. sys_prefix : bool [default: False] Whether to enable in the sys.prefix, i.e. environment. Will override `user` logger : Jupyter logger [optional] Logger instance to use Here is the function: def enable_bundler_python(module, user=True, sys_prefix=False, logger=None): """Enables bundlers defined in a Python package. Returns whether each bundle defined in the packaged was enabled or not. Parameters ---------- module : str Importable Python module exposing the magic-named `_jupyter_bundlerextension_paths` function user : bool [default: True] Whether to enable in the user's nbconfig directory. sys_prefix : bool [default: False] Whether to enable in the sys.prefix, i.e. environment. Will override `user` logger : Jupyter logger [optional] Logger instance to use """ return _set_bundler_state_python(True, module, user, sys_prefix, logger=logger)
Enables bundlers defined in a Python package. Returns whether each bundle defined in the packaged was enabled or not. Parameters ---------- module : str Importable Python module exposing the magic-named `_jupyter_bundlerextension_paths` function user : bool [default: True] Whether to enable in the user's nbconfig directory. sys_prefix : bool [default: False] Whether to enable in the sys.prefix, i.e. environment. Will override `user` logger : Jupyter logger [optional] Logger instance to use
170,456
import sys import os from ..extensions import BaseExtensionApp, _get_config_dir, GREEN_ENABLED, RED_DISABLED from .._version import __version__ from notebook.config_manager import BaseJSONConfigManager from jupyter_core.paths import jupyter_config_path from traitlets.utils.importstring import import_item from traitlets import Bool def _set_bundler_state_python(state, module, user, sys_prefix, logger=None): """Enables or disables bundlers defined in a Python package. Returns a list of whether the state was achieved for each bundler. Parameters ---------- state : Bool Whether the extensions should be enabled module : str Importable Python module exposing the magic-named `_jupyter_bundlerextension_paths` function user : bool Whether to enable in the user's nbconfig directory. sys_prefix : bool Enable/disable in the sys.prefix, i.e. environment logger : Jupyter logger [optional] Logger instance to use """ m, bundlers = _get_bundler_metadata(module) return [_set_bundler_state(name=bundler["name"], label=bundler["label"], module_name=bundler["module_name"], group=bundler["group"], state=state, user=user, sys_prefix=sys_prefix, logger=logger) for bundler in bundlers] The provided code snippet includes necessary dependencies for implementing the `disable_bundler_python` function. Write a Python function `def disable_bundler_python(module, user=True, sys_prefix=False, logger=None)` to solve the following problem: Disables bundlers defined in a Python package. Returns whether each bundle defined in the packaged was enabled or not. Parameters ---------- module : str Importable Python module exposing the magic-named `_jupyter_bundlerextension_paths` function user : bool [default: True] Whether to enable in the user's nbconfig directory. sys_prefix : bool [default: False] Whether to enable in the sys.prefix, i.e. environment. Will override `user` logger : Jupyter logger [optional] Logger instance to use Here is the function: def disable_bundler_python(module, user=True, sys_prefix=False, logger=None): """Disables bundlers defined in a Python package. Returns whether each bundle defined in the packaged was enabled or not. Parameters ---------- module : str Importable Python module exposing the magic-named `_jupyter_bundlerextension_paths` function user : bool [default: True] Whether to enable in the user's nbconfig directory. sys_prefix : bool [default: False] Whether to enable in the sys.prefix, i.e. environment. Will override `user` logger : Jupyter logger [optional] Logger instance to use """ return _set_bundler_state_python(False, module, user, sys_prefix, logger=logger)
Disables bundlers defined in a Python package. Returns whether each bundle defined in the packaged was enabled or not. Parameters ---------- module : str Importable Python module exposing the magic-named `_jupyter_bundlerextension_paths` function user : bool [default: True] Whether to enable in the user's nbconfig directory. sys_prefix : bool [default: False] Whether to enable in the sys.prefix, i.e. environment. Will override `user` logger : Jupyter logger [optional] Logger instance to use
170,457
import notebook import asyncio import binascii import datetime import errno import functools import gettext import hashlib import hmac import importlib import inspect import ipaddress import json import logging import mimetypes import os import random import re import select import signal import socket import stat import sys import tempfile import threading import time import warnings import webbrowser from base64 import encodebytes from jinja2 import Environment, FileSystemLoader from notebook.transutils import trans, _ from tornado import httpserver from tornado import ioloop from tornado import web from tornado.httputil import url_concat from tornado.log import LogFormatter, app_log, access_log, gen_log from notebook import ( DEFAULT_NOTEBOOK_PORT, DEFAULT_TEMPLATE_PATH_LIST, __version__, ) import nbclassic from .base.handlers import Template404, RedirectWithParams from .log import log_request from .services.kernels.kernelmanager import MappingKernelManager, AsyncMappingKernelManager from .services.config import ConfigManager from .services.contents.manager import ContentsManager from .services.contents.filemanager import FileContentsManager from .services.contents.largefilemanager import LargeFileManager from .services.sessions.sessionmanager import SessionManager from .gateway.managers import GatewayKernelManager, GatewayKernelSpecManager, GatewaySessionManager, GatewayClient from .auth.login import LoginHandler from .auth.logout import LogoutHandler from .base.handlers import FileFindHandler from traitlets.config import Config from traitlets.config.application import catch_config_error, boolean_flag from jupyter_core.application import ( JupyterApp, base_flags, base_aliases, ) from jupyter_core.paths import jupyter_config_path from jupyter_client import KernelManager from jupyter_client.kernelspec import KernelSpecManager from jupyter_client.session import Session from nbformat.sign import NotebookNotary from traitlets import ( Any, Dict, Unicode, Integer, List, Bool, Bytes, Instance, TraitError, Type, Float, observe, default, validate ) from ipython_genutils import py3compat from jupyter_core.paths import jupyter_runtime_dir, jupyter_path from notebook._sysinfo import get_sys_info from ._tz import utcnow, utcfromtimestamp from .utils import ( check_pid, pathname2url, run_sync, unix_socket_in_use, url_escape, url_path_join, urldecode_unix_socket_path, urlencode_unix_socket, urljoin, ) from .traittypes import TypeFromClasses The provided code snippet includes necessary dependencies for implementing the `random_ports` function. Write a Python function `def random_ports(port, n)` to solve the following problem: Generate a list of n random ports near the given port. The first 5 ports will be sequential, and the remaining n-5 will be randomly selected in the range [port-2*n, port+2*n]. Here is the function: def random_ports(port, n): """Generate a list of n random ports near the given port. The first 5 ports will be sequential, and the remaining n-5 will be randomly selected in the range [port-2*n, port+2*n]. """ for i in range(min(5, n)): yield port + i for i in range(n-5): yield max(1, port + random.randint(-2*n, 2*n))
Generate a list of n random ports near the given port. The first 5 ports will be sequential, and the remaining n-5 will be randomly selected in the range [port-2*n, port+2*n].
170,458
import notebook import asyncio import binascii import datetime import errno import functools import gettext import hashlib import hmac import importlib import inspect import ipaddress import json import logging import mimetypes import os import random import re import select import signal import socket import stat import sys import tempfile import threading import time import warnings import webbrowser from base64 import encodebytes from jinja2 import Environment, FileSystemLoader from notebook.transutils import trans, _ from tornado import httpserver from tornado import ioloop from tornado import web from tornado.httputil import url_concat from tornado.log import LogFormatter, app_log, access_log, gen_log from notebook import ( DEFAULT_NOTEBOOK_PORT, DEFAULT_TEMPLATE_PATH_LIST, __version__, ) import nbclassic from .base.handlers import Template404, RedirectWithParams from .log import log_request from .services.kernels.kernelmanager import MappingKernelManager, AsyncMappingKernelManager from .services.config import ConfigManager from .services.contents.manager import ContentsManager from .services.contents.filemanager import FileContentsManager from .services.contents.largefilemanager import LargeFileManager from .services.sessions.sessionmanager import SessionManager from .gateway.managers import GatewayKernelManager, GatewayKernelSpecManager, GatewaySessionManager, GatewayClient from .auth.login import LoginHandler from .auth.logout import LogoutHandler from .base.handlers import FileFindHandler from traitlets.config import Config from traitlets.config.application import catch_config_error, boolean_flag from jupyter_core.application import ( JupyterApp, base_flags, base_aliases, ) from jupyter_core.paths import jupyter_config_path from jupyter_client import KernelManager from jupyter_client.kernelspec import KernelSpecManager from jupyter_client.session import Session from nbformat.sign import NotebookNotary from traitlets import ( Any, Dict, Unicode, Integer, List, Bool, Bytes, Instance, TraitError, Type, Float, observe, default, validate ) from ipython_genutils import py3compat from jupyter_core.paths import jupyter_runtime_dir, jupyter_path from notebook._sysinfo import get_sys_info from ._tz import utcnow, utcfromtimestamp from .utils import ( check_pid, pathname2url, run_sync, unix_socket_in_use, url_escape, url_path_join, urldecode_unix_socket_path, urlencode_unix_socket, urljoin, ) from .traittypes import TypeFromClasses The provided code snippet includes necessary dependencies for implementing the `load_handlers` function. Write a Python function `def load_handlers(name)` to solve the following problem: Load the (URL pattern, handler) tuples for each component. Here is the function: def load_handlers(name): """Load the (URL pattern, handler) tuples for each component.""" mod = __import__(name, fromlist=['default_handlers']) return mod.default_handlers
Load the (URL pattern, handler) tuples for each component.
170,459
import notebook import asyncio import binascii import datetime import errno import functools import gettext import hashlib import hmac import importlib import inspect import ipaddress import json import logging import mimetypes import os import random import re import select import signal import socket import stat import sys import tempfile import threading import time import warnings import webbrowser from base64 import encodebytes from jinja2 import Environment, FileSystemLoader from notebook.transutils import trans, _ try: import tornado except ImportError as e: raise ImportError(_("The Jupyter Notebook requires tornado >= 5.0")) from e from tornado import httpserver from tornado import ioloop from tornado import web from tornado.httputil import url_concat from tornado.log import LogFormatter, app_log, access_log, gen_log if not sys.platform.startswith('win'): from tornado.netutil import bind_unix_socket from notebook import ( DEFAULT_NOTEBOOK_PORT, DEFAULT_TEMPLATE_PATH_LIST, __version__, ) import nbclassic from .base.handlers import Template404, RedirectWithParams from .log import log_request from .services.kernels.kernelmanager import MappingKernelManager, AsyncMappingKernelManager from .services.config import ConfigManager from .services.contents.manager import ContentsManager from .services.contents.filemanager import FileContentsManager from .services.contents.largefilemanager import LargeFileManager from .services.sessions.sessionmanager import SessionManager from .gateway.managers import GatewayKernelManager, GatewayKernelSpecManager, GatewaySessionManager, GatewayClient from .auth.login import LoginHandler from .auth.logout import LogoutHandler from .base.handlers import FileFindHandler from traitlets.config import Config from traitlets.config.application import catch_config_error, boolean_flag from jupyter_core.application import ( JupyterApp, base_flags, base_aliases, ) from jupyter_core.paths import jupyter_config_path from jupyter_client import KernelManager from jupyter_client.kernelspec import KernelSpecManager from jupyter_client.session import Session from nbformat.sign import NotebookNotary from traitlets import ( Any, Dict, Unicode, Integer, List, Bool, Bytes, Instance, TraitError, Type, Float, observe, default, validate ) from ipython_genutils import py3compat from jupyter_core.paths import jupyter_runtime_dir, jupyter_path from notebook._sysinfo import get_sys_info from ._tz import utcnow, utcfromtimestamp from .utils import ( check_pid, pathname2url, run_sync, unix_socket_in_use, url_escape, url_path_join, urldecode_unix_socket_path, urlencode_unix_socket, urljoin, ) from .traittypes import TypeFromClasses import os del os _ = trans.gettext def urldecode_unix_socket_path(socket_path): """Decodes a UNIX sock path string from an encoded sock path for the `http+unix` URI form.""" return socket_path.replace('%2F', '/') class HTTPClient(object): """A blocking HTTP client. This interface is provided to make it easier to share code between synchronous and asynchronous applications. Applications that are running an `.IOLoop` must use `AsyncHTTPClient` instead. Typical usage looks like this:: http_client = httpclient.HTTPClient() try: response = http_client.fetch("http://www.google.com/") print(response.body) except httpclient.HTTPError as e: # HTTPError is raised for non-200 responses; the response # can be found in e.response. print("Error: " + str(e)) except Exception as e: # Other errors are possible, such as IOError. print("Error: " + str(e)) http_client.close() .. versionchanged:: 5.0 Due to limitations in `asyncio`, it is no longer possible to use the synchronous ``HTTPClient`` while an `.IOLoop` is running. Use `AsyncHTTPClient` instead. """ def __init__( self, async_client_class: "Optional[Type[AsyncHTTPClient]]" = None, **kwargs: Any ) -> None: # Initialize self._closed at the beginning of the constructor # so that an exception raised here doesn't lead to confusing # failures in __del__. self._closed = True self._io_loop = IOLoop(make_current=False) if async_client_class is None: async_client_class = AsyncHTTPClient # Create the client while our IOLoop is "current", without # clobbering the thread's real current IOLoop (if any). async def make_client() -> "AsyncHTTPClient": await gen.sleep(0) assert async_client_class is not None return async_client_class(**kwargs) self._async_client = self._io_loop.run_sync(make_client) self._closed = False def __del__(self) -> None: self.close() def close(self) -> None: """Closes the HTTPClient, freeing any resources used.""" if not self._closed: self._async_client.close() self._io_loop.close() self._closed = True def fetch( self, request: Union["HTTPRequest", str], **kwargs: Any ) -> "HTTPResponse": """Executes a request, returning an `HTTPResponse`. The request may be either a string URL or an `HTTPRequest` object. If it is a string, we construct an `HTTPRequest` using any additional kwargs: ``HTTPRequest(request, **kwargs)`` If an error occurs during the fetch, we raise an `HTTPError` unless the ``raise_error`` keyword argument is set to False. """ response = self._io_loop.run_sync( functools.partial(self._async_client.fetch, request, **kwargs) ) return response class AsyncHTTPClient(Configurable): """An non-blocking HTTP client. Example usage:: async def f(): http_client = AsyncHTTPClient() try: response = await http_client.fetch("http://www.google.com") except Exception as e: print("Error: %s" % e) else: print(response.body) The constructor for this class is magic in several respects: It actually creates an instance of an implementation-specific subclass, and instances are reused as a kind of pseudo-singleton (one per `.IOLoop`). The keyword argument ``force_instance=True`` can be used to suppress this singleton behavior. Unless ``force_instance=True`` is used, no arguments should be passed to the `AsyncHTTPClient` constructor. The implementation subclass as well as arguments to its constructor can be set with the static method `configure()` All `AsyncHTTPClient` implementations support a ``defaults`` keyword argument, which can be used to set default values for `HTTPRequest` attributes. For example:: AsyncHTTPClient.configure( None, defaults=dict(user_agent="MyUserAgent")) # or with force_instance: client = AsyncHTTPClient(force_instance=True, defaults=dict(user_agent="MyUserAgent")) .. versionchanged:: 5.0 The ``io_loop`` argument (deprecated since version 4.1) has been removed. """ _instance_cache = None # type: Dict[IOLoop, AsyncHTTPClient] def configurable_base(cls) -> Type[Configurable]: return AsyncHTTPClient def configurable_default(cls) -> Type[Configurable]: from tornado.simple_httpclient import SimpleAsyncHTTPClient return SimpleAsyncHTTPClient def _async_clients(cls) -> Dict[IOLoop, "AsyncHTTPClient"]: attr_name = "_async_client_dict_" + cls.__name__ if not hasattr(cls, attr_name): setattr(cls, attr_name, weakref.WeakKeyDictionary()) return getattr(cls, attr_name) def __new__(cls, force_instance: bool = False, **kwargs: Any) -> "AsyncHTTPClient": io_loop = IOLoop.current() if force_instance: instance_cache = None else: instance_cache = cls._async_clients() if instance_cache is not None and io_loop in instance_cache: return instance_cache[io_loop] instance = super(AsyncHTTPClient, cls).__new__(cls, **kwargs) # type: ignore # Make sure the instance knows which cache to remove itself from. # It can't simply call _async_clients() because we may be in # __new__(AsyncHTTPClient) but instance.__class__ may be # SimpleAsyncHTTPClient. instance._instance_cache = instance_cache if instance_cache is not None: instance_cache[instance.io_loop] = instance return instance def initialize(self, defaults: Optional[Dict[str, Any]] = None) -> None: self.io_loop = IOLoop.current() self.defaults = dict(HTTPRequest._DEFAULTS) if defaults is not None: self.defaults.update(defaults) self._closed = False def close(self) -> None: """Destroys this HTTP client, freeing any file descriptors used. This method is **not needed in normal use** due to the way that `AsyncHTTPClient` objects are transparently reused. ``close()`` is generally only necessary when either the `.IOLoop` is also being closed, or the ``force_instance=True`` argument was used when creating the `AsyncHTTPClient`. No other methods may be called on the `AsyncHTTPClient` after ``close()``. """ if self._closed: return self._closed = True if self._instance_cache is not None: cached_val = self._instance_cache.pop(self.io_loop, None) # If there's an object other than self in the instance # cache for our IOLoop, something has gotten mixed up. A # value of None appears to be possible when this is called # from a destructor (HTTPClient.__del__) as the weakref # gets cleared before the destructor runs. if cached_val is not None and cached_val is not self: raise RuntimeError("inconsistent AsyncHTTPClient cache") def fetch( self, request: Union[str, "HTTPRequest"], raise_error: bool = True, **kwargs: Any ) -> "Future[HTTPResponse]": """Executes a request, asynchronously returning an `HTTPResponse`. The request may be either a string URL or an `HTTPRequest` object. If it is a string, we construct an `HTTPRequest` using any additional kwargs: ``HTTPRequest(request, **kwargs)`` This method returns a `.Future` whose result is an `HTTPResponse`. By default, the ``Future`` will raise an `HTTPError` if the request returned a non-200 response code (other errors may also be raised if the server could not be contacted). Instead, if ``raise_error`` is set to False, the response will always be returned regardless of the response code. If a ``callback`` is given, it will be invoked with the `HTTPResponse`. In the callback interface, `HTTPError` is not automatically raised. Instead, you must check the response's ``error`` attribute or call its `~HTTPResponse.rethrow` method. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned `.Future` instead. The ``raise_error=False`` argument only affects the `HTTPError` raised when a non-200 response code is used, instead of suppressing all errors. """ if self._closed: raise RuntimeError("fetch() called on closed AsyncHTTPClient") if not isinstance(request, HTTPRequest): request = HTTPRequest(url=request, **kwargs) else: if kwargs: raise ValueError( "kwargs can't be used if request is an HTTPRequest object" ) # We may modify this (to add Host, Accept-Encoding, etc), # so make sure we don't modify the caller's object. This is also # where normal dicts get converted to HTTPHeaders objects. request.headers = httputil.HTTPHeaders(request.headers) request_proxy = _RequestProxy(request, self.defaults) future = Future() # type: Future[HTTPResponse] def handle_response(response: "HTTPResponse") -> None: if response.error: if raise_error or not response._error_is_response_code: future_set_exception_unless_cancelled(future, response.error) return future_set_result_unless_cancelled(future, response) self.fetch_impl(cast(HTTPRequest, request_proxy), handle_response) return future def fetch_impl( self, request: "HTTPRequest", callback: Callable[["HTTPResponse"], None] ) -> None: raise NotImplementedError() def configure( cls, impl: "Union[None, str, Type[Configurable]]", **kwargs: Any ) -> None: """Configures the `AsyncHTTPClient` subclass to use. ``AsyncHTTPClient()`` actually creates an instance of a subclass. This method may be called with either a class object or the fully-qualified name of such a class (or ``None`` to use the default, ``SimpleAsyncHTTPClient``) If additional keyword arguments are given, they will be passed to the constructor of each subclass instance created. The keyword argument ``max_clients`` determines the maximum number of simultaneous `~AsyncHTTPClient.fetch()` operations that can execute in parallel on each `.IOLoop`. Additional arguments may be supported depending on the implementation class in use. Example:: AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient") """ super(AsyncHTTPClient, cls).configure(impl, **kwargs) class HTTPRequest(object): """HTTP client request object.""" _headers = None # type: Union[Dict[str, str], httputil.HTTPHeaders] # Default values for HTTPRequest parameters. # Merged with the values on the request object by AsyncHTTPClient # implementations. _DEFAULTS = dict( connect_timeout=20.0, request_timeout=20.0, follow_redirects=True, max_redirects=5, decompress_response=True, proxy_password="", allow_nonstandard_methods=False, validate_cert=True, ) def __init__( self, url: str, method: str = "GET", headers: Optional[Union[Dict[str, str], httputil.HTTPHeaders]] = None, body: Optional[Union[bytes, str]] = None, auth_username: Optional[str] = None, auth_password: Optional[str] = None, auth_mode: Optional[str] = None, connect_timeout: Optional[float] = None, request_timeout: Optional[float] = None, if_modified_since: Optional[Union[float, datetime.datetime]] = None, follow_redirects: Optional[bool] = None, max_redirects: Optional[int] = None, user_agent: Optional[str] = None, use_gzip: Optional[bool] = None, network_interface: Optional[str] = None, streaming_callback: Optional[Callable[[bytes], None]] = None, header_callback: Optional[Callable[[str], None]] = None, prepare_curl_callback: Optional[Callable[[Any], None]] = None, proxy_host: Optional[str] = None, proxy_port: Optional[int] = None, proxy_username: Optional[str] = None, proxy_password: Optional[str] = None, proxy_auth_mode: Optional[str] = None, allow_nonstandard_methods: Optional[bool] = None, validate_cert: Optional[bool] = None, ca_certs: Optional[str] = None, allow_ipv6: Optional[bool] = None, client_key: Optional[str] = None, client_cert: Optional[str] = None, body_producer: Optional[ Callable[[Callable[[bytes], None]], "Future[None]"] ] = None, expect_100_continue: bool = False, decompress_response: Optional[bool] = None, ssl_options: Optional[Union[Dict[str, Any], ssl.SSLContext]] = None, ) -> None: r"""All parameters except ``url`` are optional. :arg str url: URL to fetch :arg str method: HTTP method, e.g. "GET" or "POST" :arg headers: Additional HTTP headers to pass on the request :type headers: `~tornado.httputil.HTTPHeaders` or `dict` :arg body: HTTP request body as a string (byte or unicode; if unicode the utf-8 encoding will be used) :type body: `str` or `bytes` :arg collections.abc.Callable body_producer: Callable used for lazy/asynchronous request bodies. It is called with one argument, a ``write`` function, and should return a `.Future`. It should call the write function with new data as it becomes available. The write function returns a `.Future` which can be used for flow control. Only one of ``body`` and ``body_producer`` may be specified. ``body_producer`` is not supported on ``curl_httpclient``. When using ``body_producer`` it is recommended to pass a ``Content-Length`` in the headers as otherwise chunked encoding will be used, and many servers do not support chunked encoding on requests. New in Tornado 4.0 :arg str auth_username: Username for HTTP authentication :arg str auth_password: Password for HTTP authentication :arg str auth_mode: Authentication mode; default is "basic". Allowed values are implementation-defined; ``curl_httpclient`` supports "basic" and "digest"; ``simple_httpclient`` only supports "basic" :arg float connect_timeout: Timeout for initial connection in seconds, default 20 seconds (0 means no timeout) :arg float request_timeout: Timeout for entire request in seconds, default 20 seconds (0 means no timeout) :arg if_modified_since: Timestamp for ``If-Modified-Since`` header :type if_modified_since: `datetime` or `float` :arg bool follow_redirects: Should redirects be followed automatically or return the 3xx response? Default True. :arg int max_redirects: Limit for ``follow_redirects``, default 5. :arg str user_agent: String to send as ``User-Agent`` header :arg bool decompress_response: Request a compressed response from the server and decompress it after downloading. Default is True. New in Tornado 4.0. :arg bool use_gzip: Deprecated alias for ``decompress_response`` since Tornado 4.0. :arg str network_interface: Network interface or source IP to use for request. See ``curl_httpclient`` note below. :arg collections.abc.Callable streaming_callback: If set, ``streaming_callback`` will be run with each chunk of data as it is received, and ``HTTPResponse.body`` and ``HTTPResponse.buffer`` will be empty in the final response. :arg collections.abc.Callable header_callback: If set, ``header_callback`` will be run with each header line as it is received (including the first line, e.g. ``HTTP/1.0 200 OK\r\n``, and a final line containing only ``\r\n``. All lines include the trailing newline characters). ``HTTPResponse.headers`` will be empty in the final response. This is most useful in conjunction with ``streaming_callback``, because it's the only way to get access to header data while the request is in progress. :arg collections.abc.Callable prepare_curl_callback: If set, will be called with a ``pycurl.Curl`` object to allow the application to make additional ``setopt`` calls. :arg str proxy_host: HTTP proxy hostname. To use proxies, ``proxy_host`` and ``proxy_port`` must be set; ``proxy_username``, ``proxy_pass`` and ``proxy_auth_mode`` are optional. Proxies are currently only supported with ``curl_httpclient``. :arg int proxy_port: HTTP proxy port :arg str proxy_username: HTTP proxy username :arg str proxy_password: HTTP proxy password :arg str proxy_auth_mode: HTTP proxy Authentication mode; default is "basic". supports "basic" and "digest" :arg bool allow_nonstandard_methods: Allow unknown values for ``method`` argument? Default is False. :arg bool validate_cert: For HTTPS requests, validate the server's certificate? Default is True. :arg str ca_certs: filename of CA certificates in PEM format, or None to use defaults. See note below when used with ``curl_httpclient``. :arg str client_key: Filename for client SSL key, if any. See note below when used with ``curl_httpclient``. :arg str client_cert: Filename for client SSL certificate, if any. See note below when used with ``curl_httpclient``. :arg ssl.SSLContext ssl_options: `ssl.SSLContext` object for use in ``simple_httpclient`` (unsupported by ``curl_httpclient``). Overrides ``validate_cert``, ``ca_certs``, ``client_key``, and ``client_cert``. :arg bool allow_ipv6: Use IPv6 when available? Default is True. :arg bool expect_100_continue: If true, send the ``Expect: 100-continue`` header and wait for a continue response before sending the request body. Only supported with ``simple_httpclient``. .. note:: When using ``curl_httpclient`` certain options may be inherited by subsequent fetches because ``pycurl`` does not allow them to be cleanly reset. This applies to the ``ca_certs``, ``client_key``, ``client_cert``, and ``network_interface`` arguments. If you use these options, you should pass them on every request (you don't have to always use the same values, but it's not possible to mix requests that specify these options with ones that use the defaults). .. versionadded:: 3.1 The ``auth_mode`` argument. .. versionadded:: 4.0 The ``body_producer`` and ``expect_100_continue`` arguments. .. versionadded:: 4.2 The ``ssl_options`` argument. .. versionadded:: 4.5 The ``proxy_auth_mode`` argument. """ # Note that some of these attributes go through property setters # defined below. self.headers = headers # type: ignore if if_modified_since: self.headers["If-Modified-Since"] = httputil.format_timestamp( if_modified_since ) self.proxy_host = proxy_host self.proxy_port = proxy_port self.proxy_username = proxy_username self.proxy_password = proxy_password self.proxy_auth_mode = proxy_auth_mode self.url = url self.method = method self.body = body # type: ignore self.body_producer = body_producer self.auth_username = auth_username self.auth_password = auth_password self.auth_mode = auth_mode self.connect_timeout = connect_timeout self.request_timeout = request_timeout self.follow_redirects = follow_redirects self.max_redirects = max_redirects self.user_agent = user_agent if decompress_response is not None: self.decompress_response = decompress_response # type: Optional[bool] else: self.decompress_response = use_gzip self.network_interface = network_interface self.streaming_callback = streaming_callback self.header_callback = header_callback self.prepare_curl_callback = prepare_curl_callback self.allow_nonstandard_methods = allow_nonstandard_methods self.validate_cert = validate_cert self.ca_certs = ca_certs self.allow_ipv6 = allow_ipv6 self.client_key = client_key self.client_cert = client_cert self.ssl_options = ssl_options self.expect_100_continue = expect_100_continue self.start_time = time.time() def headers(self) -> httputil.HTTPHeaders: # TODO: headers may actually be a plain dict until fairly late in # the process (AsyncHTTPClient.fetch), but practically speaking, # whenever the property is used they're already HTTPHeaders. return self._headers # type: ignore def headers(self, value: Union[Dict[str, str], httputil.HTTPHeaders]) -> None: if value is None: self._headers = httputil.HTTPHeaders() else: self._headers = value # type: ignore def body(self) -> bytes: return self._body def body(self, value: Union[bytes, str]) -> None: self._body = utf8(value) class Resolver(Configurable): """Configurable asynchronous DNS resolver interface. By default, a blocking implementation is used (which simply calls `socket.getaddrinfo`). An alternative implementation can be chosen with the `Resolver.configure <.Configurable.configure>` class method:: Resolver.configure('tornado.netutil.ThreadedResolver') The implementations of this interface included with Tornado are * `tornado.netutil.DefaultLoopResolver` * `tornado.netutil.DefaultExecutorResolver` (deprecated) * `tornado.netutil.BlockingResolver` (deprecated) * `tornado.netutil.ThreadedResolver` (deprecated) * `tornado.netutil.OverrideResolver` * `tornado.platform.twisted.TwistedResolver` (deprecated) * `tornado.platform.caresresolver.CaresResolver` (deprecated) .. versionchanged:: 5.0 The default implementation has changed from `BlockingResolver` to `DefaultExecutorResolver`. .. versionchanged:: 6.2 The default implementation has changed from `DefaultExecutorResolver` to `DefaultLoopResolver`. """ def configurable_base(cls) -> Type["Resolver"]: return Resolver def configurable_default(cls) -> Type["Resolver"]: return DefaultLoopResolver def resolve( self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC ) -> Awaitable[List[Tuple[int, Any]]]: """Resolves an address. The ``host`` argument is a string which may be a hostname or a literal IP address. Returns a `.Future` whose result is a list of (family, address) pairs, where address is a tuple suitable to pass to `socket.connect <socket.socket.connect>` (i.e. a ``(host, port)`` pair for IPv4; additional fields may be present for IPv6). If a ``callback`` is passed, it will be run with the result as an argument when it is complete. :raises IOError: if the address cannot be resolved. .. versionchanged:: 4.4 Standardized all implementations to raise `IOError`. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead. """ raise NotImplementedError() def close(self) -> None: """Closes the `Resolver`, freeing any resources used. .. versionadded:: 3.1 """ pass def initialize(nb_app): if os.name == 'nt': default_shell = 'powershell.exe' else: default_shell = which('sh') shell_override = nb_app.terminado_settings.get('shell_command') shell = ( [os.environ.get('SHELL') or default_shell] if shell_override is None else shell_override ) # When the notebook server is not running in a terminal (e.g. when # it's launched by a JupyterHub spawner), it's likely that the user # environment hasn't been fully set up. In that case, run a login # shell to automatically source /etc/profile and the like, unless # the user has specifically set a preferred shell command. if os.name != 'nt' and shell_override is None and not sys.stdout.isatty(): shell.append('-l') terminal_manager = nb_app.web_app.settings['terminal_manager'] = TerminalManager( shell_command=shell, extra_env={'JUPYTER_SERVER_ROOT': nb_app.notebook_dir, 'JUPYTER_SERVER_URL': nb_app.connection_url, }, parent=nb_app, ) terminal_manager.log = nb_app.log base_url = nb_app.web_app.settings['base_url'] handlers = [ (ujoin(base_url, r"/terminals/new"), NamedTerminalHandler), (ujoin(base_url, r"/terminals/new/(\w+)"), NewTerminalHandler), (ujoin(base_url, r"/terminals/(\w+)"), TerminalHandler), (ujoin(base_url, r"/terminals/websocket/(\w+)"), TermSocket, {'term_manager': terminal_manager}), (ujoin(base_url, r"/api/terminals"), api_handlers.TerminalRootHandler), (ujoin(base_url, r"/api/terminals/(\w+)"), api_handlers.TerminalHandler), ] nb_app.web_app.add_handlers(".*$", handlers) The provided code snippet includes necessary dependencies for implementing the `shutdown_server` function. Write a Python function `def shutdown_server(server_info, timeout=5, log=None)` to solve the following problem: Shutdown a notebook server in a separate process. *server_info* should be a dictionary as produced by list_running_servers(). Will first try to request shutdown using /api/shutdown . On Unix, if the server is still running after *timeout* seconds, it will send SIGTERM. After another timeout, it escalates to SIGKILL. Returns True if the server was stopped by any means, False if stopping it failed (on Windows). Here is the function: def shutdown_server(server_info, timeout=5, log=None): """Shutdown a notebook server in a separate process. *server_info* should be a dictionary as produced by list_running_servers(). Will first try to request shutdown using /api/shutdown . On Unix, if the server is still running after *timeout* seconds, it will send SIGTERM. After another timeout, it escalates to SIGKILL. Returns True if the server was stopped by any means, False if stopping it failed (on Windows). """ from tornado import gen from tornado.httpclient import AsyncHTTPClient, HTTPClient, HTTPRequest from tornado.netutil import Resolver url = server_info['url'] pid = server_info['pid'] resolver = None # UNIX Socket handling. if url.startswith('http+unix://'): # This library doesn't understand our URI form, but it's just HTTP. url = url.replace('http+unix://', 'http://') class UnixSocketResolver(Resolver): def initialize(self, resolver): self.resolver = resolver def close(self): self.resolver.close() @gen.coroutine def resolve(self, host, port, *args, **kwargs): raise gen.Return([ (socket.AF_UNIX, urldecode_unix_socket_path(host)) ]) resolver = UnixSocketResolver(resolver=Resolver()) req = HTTPRequest(url + 'api/shutdown', method='POST', body=b'', headers={ 'Authorization': 'token ' + server_info['token'] }) if log: log.debug("POST request to %sapi/shutdown", url) AsyncHTTPClient.configure(None, resolver=resolver) HTTPClient(AsyncHTTPClient).fetch(req) # Poll to see if it shut down. for _ in range(timeout*10): if not check_pid(pid): if log: log.debug("Server PID %s is gone", pid) return True time.sleep(0.1) if sys.platform.startswith('win'): return False if log: log.debug("SIGTERM to PID %s", pid) os.kill(pid, signal.SIGTERM) # Poll to see if it shut down. for _ in range(timeout * 10): if not check_pid(pid): if log: log.debug("Server PID %s is gone", pid) return True time.sleep(0.1) if log: log.debug("SIGKILL to PID %s", pid) os.kill(pid, signal.SIGKILL) return True # SIGKILL cannot be caught
Shutdown a notebook server in a separate process. *server_info* should be a dictionary as produced by list_running_servers(). Will first try to request shutdown using /api/shutdown . On Unix, if the server is still running after *timeout* seconds, it will send SIGTERM. After another timeout, it escalates to SIGKILL. Returns True if the server was stopped by any means, False if stopping it failed (on Windows).
170,460
import notebook import asyncio import binascii import datetime import errno import functools import gettext import hashlib import hmac import importlib import inspect import ipaddress import json import logging import mimetypes import os import random import re import select import signal import socket import stat import sys import tempfile import threading import time import warnings import webbrowser from base64 import encodebytes from jinja2 import Environment, FileSystemLoader from notebook.transutils import trans, _ from tornado import httpserver from tornado import ioloop from tornado import web from tornado.httputil import url_concat from tornado.log import LogFormatter, app_log, access_log, gen_log from notebook import ( DEFAULT_NOTEBOOK_PORT, DEFAULT_TEMPLATE_PATH_LIST, __version__, ) import nbclassic from .base.handlers import Template404, RedirectWithParams from .log import log_request from .services.kernels.kernelmanager import MappingKernelManager, AsyncMappingKernelManager from .services.config import ConfigManager from .services.contents.manager import ContentsManager from .services.contents.filemanager import FileContentsManager from .services.contents.largefilemanager import LargeFileManager from .services.sessions.sessionmanager import SessionManager from .gateway.managers import GatewayKernelManager, GatewayKernelSpecManager, GatewaySessionManager, GatewayClient from .auth.login import LoginHandler from .auth.logout import LogoutHandler from .base.handlers import FileFindHandler from traitlets.config import Config from traitlets.config.application import catch_config_error, boolean_flag from jupyter_core.application import ( JupyterApp, base_flags, base_aliases, ) from jupyter_core.paths import jupyter_config_path from jupyter_client import KernelManager from jupyter_client.kernelspec import KernelSpecManager from jupyter_client.session import Session from nbformat.sign import NotebookNotary from traitlets import ( Any, Dict, Unicode, Integer, List, Bool, Bytes, Instance, TraitError, Type, Float, observe, default, validate ) from ipython_genutils import py3compat from jupyter_core.paths import jupyter_runtime_dir, jupyter_path from notebook._sysinfo import get_sys_info from ._tz import utcnow, utcfromtimestamp from .utils import ( check_pid, pathname2url, run_sync, unix_socket_in_use, url_escape, url_path_join, urldecode_unix_socket_path, urlencode_unix_socket, urljoin, ) from .traittypes import TypeFromClasses import os del os def jupyter_runtime_dir() -> str: """Return the runtime dir for transient jupyter files. Returns JUPYTER_RUNTIME_DIR if defined. The default is now (data_dir)/runtime on all platforms; we no longer use XDG_RUNTIME_DIR after various problems. """ env = os.environ if env.get("JUPYTER_RUNTIME_DIR"): return env["JUPYTER_RUNTIME_DIR"] return pjoin(jupyter_data_dir(), "runtime") The provided code snippet includes necessary dependencies for implementing the `list_running_servers` function. Write a Python function `def list_running_servers(runtime_dir=None)` to solve the following problem: Iterate over the server info files of running notebook servers. Given a runtime directory, find nbserver-* files in the security directory, and yield dicts of their information, each one pertaining to a currently running notebook server instance. Here is the function: def list_running_servers(runtime_dir=None): """Iterate over the server info files of running notebook servers. Given a runtime directory, find nbserver-* files in the security directory, and yield dicts of their information, each one pertaining to a currently running notebook server instance. """ if runtime_dir is None: runtime_dir = jupyter_runtime_dir() # The runtime dir might not exist if not os.path.isdir(runtime_dir): return for file_name in os.listdir(runtime_dir): if re.match('nbserver-(.+).json', file_name): with open(os.path.join(runtime_dir, file_name), encoding='utf-8') as f: info = json.load(f) # Simple check whether that process is really still running # Also remove leftover files from IPython 2.x without a pid field if ('pid' in info) and check_pid(info['pid']): yield info else: # If the process has died, try to delete its info file try: os.unlink(os.path.join(runtime_dir, file_name)) except OSError: pass # TODO: This should warn or log or something
Iterate over the server info files of running notebook servers. Given a runtime directory, find nbserver-* files in the security directory, and yield dicts of their information, each one pertaining to a currently running notebook server instance.
170,461
from notebook.auth import passwd from getpass import getpass from notebook.config_manager import BaseJSONConfigManager from jupyter_core.paths import jupyter_config_dir import argparse import sys def getpass(prompt: str = ..., stream: Optional[TextIO] = ...) -> str: ... class BaseJSONConfigManager(LoggingConfigurable): """General JSON config manager Deals with persisting/storing config in a json file with optionally default values in a {section_name}.d directory. """ config_dir = Unicode('.') read_directory = Bool(True) def ensure_config_dir_exists(self): """Will try to create the config_dir directory.""" try: os.makedirs(self.config_dir, 0o755) except OSError as e: if e.errno != errno.EEXIST: raise def file_name(self, section_name): """Returns the json filename for the section_name: {config_dir}/{section_name}.json""" return os.path.join(self.config_dir, section_name+'.json') def directory(self, section_name): """Returns the directory name for the section name: {config_dir}/{section_name}.d""" return os.path.join(self.config_dir, section_name+'.d') def get(self, section_name, include_root=True): """Retrieve the config data for the specified section. Returns the data as a dictionary, or an empty dictionary if the file doesn't exist. When include_root is False, it will not read the root .json file, effectively returning the default values. """ paths = [self.file_name(section_name)] if include_root else [] if self.read_directory: pattern = os.path.join(self.directory(section_name), '*.json') # These json files should be processed first so that the # {section_name}.json take precedence. # The idea behind this is that installing a Python package may # put a json file somewhere in the a .d directory, while the # .json file is probably a user configuration. paths = sorted(glob.glob(pattern)) + paths self.log.debug('Paths used for configuration of %s: \n\t%s', section_name, '\n\t'.join(paths)) data = {} for path in paths: if os.path.isfile(path): with open(path, encoding='utf-8') as f: recursive_update(data, json.load(f)) return data def set(self, section_name, data): """Store the given config data. """ filename = self.file_name(section_name) self.ensure_config_dir_exists() if self.read_directory: # we will modify data in place, so make a copy data = copy.deepcopy(data) defaults = self.get(section_name, include_root=False) remove_defaults(data, defaults) # Generate the JSON up front, since it could raise an exception, # in order to avoid writing half-finished corrupted data to disk. json_content = json.dumps(data, indent=2) f = open(filename, 'w', encoding='utf-8') with f: f.write(json_content) def update(self, section_name, new_data): """Modify the config section by recursively updating it with new_data. Returns the modified config data as a dictionary. """ data = self.get(section_name) recursive_update(data, new_data) self.set(section_name, data) return data def jupyter_config_dir() -> str: """Get the Jupyter config directory for this platform and user. Returns JUPYTER_CONFIG_DIR if defined, otherwise the appropriate directory for the platform. """ env = os.environ if env.get("JUPYTER_NO_CONFIG"): return _mkdtemp_once("jupyter-clean-cfg") if env.get("JUPYTER_CONFIG_DIR"): return env["JUPYTER_CONFIG_DIR"] if use_platform_dirs(): return platformdirs.user_config_dir(APPNAME, appauthor=False) home_dir = get_home_dir() return pjoin(home_dir, ".jupyter") def set_password(args): password = args.password while not password : password1 = getpass("" if args.quiet else "Provide password: ") password_repeat = getpass("" if args.quiet else "Repeat password: ") if password1 != password_repeat: print("Passwords do not match, try again") elif len(password1) < 4: print("Please provide at least 4 characters") else: password = password1 password_hash = passwd(password) cfg = BaseJSONConfigManager(config_dir=jupyter_config_dir()) cfg.update('jupyter_notebook_config', { 'NotebookApp': { 'password': password_hash, } }) if not args.quiet: print(f"password stored in config dir: {jupyter_config_dir()}")
null
170,462
from contextlib import contextmanager import getpass import hashlib import json import os import random import traceback import warnings from ipython_genutils.py3compat import cast_bytes, str_to_bytes, cast_unicode from traitlets.config import Config, ConfigFileNotFound, JSONFileConfigLoader from jupyter_core.paths import jupyter_config_dir def cast_bytes(s, encoding=None): if not isinstance(s, bytes): return encode(s, encoding) return s The provided code snippet includes necessary dependencies for implementing the `passwd_check` function. Write a Python function `def passwd_check(hashed_passphrase, passphrase)` to solve the following problem: Verify that a given passphrase matches its hashed version. Parameters ---------- hashed_passphrase : str Hashed password, in the format returned by `passwd`. passphrase : str Passphrase to validate. Returns ------- valid : bool True if the passphrase matches the hash. Examples -------- >>> from notebook.auth.security import passwd_check >>> passwd_check('argon2:...', 'mypassword') True >>> passwd_check('argon2:...', 'otherpassword') False >>> passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a', ... 'mypassword') True Here is the function: def passwd_check(hashed_passphrase, passphrase): """Verify that a given passphrase matches its hashed version. Parameters ---------- hashed_passphrase : str Hashed password, in the format returned by `passwd`. passphrase : str Passphrase to validate. Returns ------- valid : bool True if the passphrase matches the hash. Examples -------- >>> from notebook.auth.security import passwd_check >>> passwd_check('argon2:...', 'mypassword') True >>> passwd_check('argon2:...', 'otherpassword') False >>> passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a', ... 'mypassword') True """ if hashed_passphrase.startswith('argon2:'): import argon2 import argon2.exceptions ph = argon2.PasswordHasher() try: return ph.verify(hashed_passphrase[7:], passphrase) except argon2.exceptions.VerificationError: return False else: try: algorithm, salt, pw_digest = hashed_passphrase.split(':', 2) except (ValueError, TypeError): return False try: h = hashlib.new(algorithm) except ValueError: return False if len(pw_digest) == 0: return False h.update(cast_bytes(passphrase, 'utf-8') + cast_bytes(salt, 'ascii')) return h.hexdigest() == pw_digest
Verify that a given passphrase matches its hashed version. Parameters ---------- hashed_passphrase : str Hashed password, in the format returned by `passwd`. passphrase : str Passphrase to validate. Returns ------- valid : bool True if the passphrase matches the hash. Examples -------- >>> from notebook.auth.security import passwd_check >>> passwd_check('argon2:...', 'mypassword') True >>> passwd_check('argon2:...', 'otherpassword') False >>> passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a', ... 'mypassword') True
170,463
from contextlib import contextmanager import getpass import hashlib import json import os import random import traceback import warnings from ipython_genutils.py3compat import cast_bytes, str_to_bytes, cast_unicode from traitlets.config import Config, ConfigFileNotFound, JSONFileConfigLoader from jupyter_core.paths import jupyter_config_dir def passwd(passphrase=None, algorithm='argon2'): """Generate hashed password and salt for use in notebook configuration. In the notebook configuration, set `c.NotebookApp.password` to the generated string. Parameters ---------- passphrase : str Password to hash. If unspecified, the user is asked to input and verify a password. algorithm : str Hashing algorithm to use (e.g, 'sha1' or any argument supported by :func:`hashlib.new`, or 'argon2'). Returns ------- hashed_passphrase : str Hashed password, in the format 'hash_algorithm:salt:passphrase_hash'. Examples -------- >>> passwd('mypassword', algorithm='sha1') 'sha1:7cf3:b7d6da294ea9592a9480c8f52e63cd42cfb9dd12' """ if passphrase is None: for i in range(3): p0 = getpass.getpass('Enter password: ') p1 = getpass.getpass('Verify password: ') if p0 == p1: passphrase = p0 break else: print('Passwords do not match.') else: raise ValueError('No matching passwords found. Giving up.') if algorithm == 'argon2': from argon2 import PasswordHasher ph = PasswordHasher( memory_cost=10240, time_cost=10, parallelism=8, ) h = ph.hash(passphrase) return ':'.join((algorithm, cast_unicode(h, 'ascii'))) else: h = hashlib.new(algorithm) salt = f"{random.getrandbits(4 * salt_len):0{salt_len}x}" h.update(cast_bytes(passphrase, 'utf-8') + str_to_bytes(salt, 'ascii')) return ':'.join((algorithm, salt, h.hexdigest())) def persist_config(config_file=None, mode=0o600): """Context manager that can be used to modify a config object On exit of the context manager, the config will be written back to disk, by default with user-only (600) permissions. """ if config_file is None: config_file = os.path.join(jupyter_config_dir(), 'jupyter_notebook_config.json') os.makedirs(os.path.dirname(config_file), exist_ok=True) loader = JSONFileConfigLoader(os.path.basename(config_file), os.path.dirname(config_file)) try: config = loader.load_config() except ConfigFileNotFound: config = Config() yield config with open(config_file, 'w', encoding='utf8') as f: f.write(cast_unicode(json.dumps(config, indent=2))) try: os.chmod(config_file, mode) except Exception as e: tb = traceback.format_exc() warnings.warn(f"Failed to set permissions on {config_file}:\n{tb}", RuntimeWarning) The provided code snippet includes necessary dependencies for implementing the `set_password` function. Write a Python function `def set_password(password=None, config_file=None)` to solve the following problem: Ask user for password, store it in notebook json configuration file Here is the function: def set_password(password=None, config_file=None): """Ask user for password, store it in notebook json configuration file""" hashed_password = passwd(password) with persist_config(config_file) as config: config.NotebookApp.password = hashed_password
Ask user for password, store it in notebook json configuration file
170,464
import inspect from traitlets import ClassBasedTraitType, Undefined, warn try: from traitlets.utils.descriptions import describe except ImportError: import inspect import re import types def add_article(name, definite=False, capital=False): """Returns the string with a prepended article. The input does not need to begin with a charater. Parameters ---------- definite : bool (default: False) Whether the article is definite or not. Indefinite articles being 'a' and 'an', while 'the' is definite. capital : bool (default: False) Whether the added article should have its first letter capitalized or not. """ if definite: result = "the " + name else: first_letters = re.compile(r'[\W_]+').sub('', name) if first_letters[:1].lower() in 'aeiou': result = 'an ' + name else: result = 'a ' + name if capital: return result[0].upper() + result[1:] else: return result The provided code snippet includes necessary dependencies for implementing the `describe` function. Write a Python function `def describe(article, value, name=None, verbose=False, capital=False)` to solve the following problem: Return string that describes a value Parameters ---------- article : str or None A definite or indefinite article. If the article is indefinite (i.e. "a" or "an") the appropriate one will be infered. Thus, the arguments of ``describe`` can themselves represent what the resulting string will actually look like. If None, then no article will be prepended to the result. For non-articled description, values that are instances are treated definitely, while classes are handled indefinitely. value : any The value which will be named. name : str or None (default: None) Only applies when ``article`` is "the" - this ``name`` is a definite reference to the value. By default one will be infered from the value's type and repr methods. verbose : bool (default: False) Whether the name should be concise or verbose. When possible, verbose names include the module, and/or class name where an object was defined. capital : bool (default: False) Whether the first letter of the article should be capitalized or not. By default it is not. Examples -------- Indefinite description: >>> describe("a", object()) 'an object' >>> describe("a", object) 'an object' >>> describe("a", type(object)) 'a type' Definite description: >>> describe("the", object()) "the object at '0x10741f1b0'" >>> describe("the", object) "the type 'object'" >>> describe("the", type(object)) "the type 'type'" Definitely named description: >>> describe("the", object(), "I made") 'the object I made' >>> describe("the", object, "I will use") 'the object I will use' Here is the function: def describe(article, value, name=None, verbose=False, capital=False): """Return string that describes a value Parameters ---------- article : str or None A definite or indefinite article. If the article is indefinite (i.e. "a" or "an") the appropriate one will be infered. Thus, the arguments of ``describe`` can themselves represent what the resulting string will actually look like. If None, then no article will be prepended to the result. For non-articled description, values that are instances are treated definitely, while classes are handled indefinitely. value : any The value which will be named. name : str or None (default: None) Only applies when ``article`` is "the" - this ``name`` is a definite reference to the value. By default one will be infered from the value's type and repr methods. verbose : bool (default: False) Whether the name should be concise or verbose. When possible, verbose names include the module, and/or class name where an object was defined. capital : bool (default: False) Whether the first letter of the article should be capitalized or not. By default it is not. Examples -------- Indefinite description: >>> describe("a", object()) 'an object' >>> describe("a", object) 'an object' >>> describe("a", type(object)) 'a type' Definite description: >>> describe("the", object()) "the object at '0x10741f1b0'" >>> describe("the", object) "the type 'object'" >>> describe("the", type(object)) "the type 'type'" Definitely named description: >>> describe("the", object(), "I made") 'the object I made' >>> describe("the", object, "I will use") 'the object I will use' """ if isinstance(article, str): article = article.lower() if not inspect.isclass(value): typename = type(value).__name__ else: typename = value.__name__ if verbose: typename = _prefix(value) + typename if article == "the" or (article is None and not inspect.isclass(value)): if name is not None: result = f"{typename} {name}" if article is not None: return add_article(result, True, capital) else: return result else: tick_wrap = False if inspect.isclass(value): name = value.__name__ elif isinstance(value, types.FunctionType): name = value.__name__ tick_wrap = True elif isinstance(value, types.MethodType): name = value.__func__.__name__ tick_wrap = True elif type(value).__repr__ in (object.__repr__, type.__repr__): name = f"at '{id(value):x}'" verbose = False else: name = repr(value) verbose = False if verbose: name = _prefix(value) + name if tick_wrap: name = name.join("''") return describe(article, value, name=name, verbose=verbose, capital=capital) elif article in ("a", "an") or article is None: if article is None: return typename return add_article(typename, False, capital) else: raise ValueError( f"The 'article' argument should be 'the', 'a', 'an', or None not {article!r}" )
Return string that describes a value Parameters ---------- article : str or None A definite or indefinite article. If the article is indefinite (i.e. "a" or "an") the appropriate one will be infered. Thus, the arguments of ``describe`` can themselves represent what the resulting string will actually look like. If None, then no article will be prepended to the result. For non-articled description, values that are instances are treated definitely, while classes are handled indefinitely. value : any The value which will be named. name : str or None (default: None) Only applies when ``article`` is "the" - this ``name`` is a definite reference to the value. By default one will be infered from the value's type and repr methods. verbose : bool (default: False) Whether the name should be concise or verbose. When possible, verbose names include the module, and/or class name where an object was defined. capital : bool (default: False) Whether the first letter of the article should be capitalized or not. By default it is not. Examples -------- Indefinite description: >>> describe("a", object()) 'an object' >>> describe("a", object) 'an object' >>> describe("a", type(object)) 'a type' Definite description: >>> describe("the", object()) "the object at '0x10741f1b0'" >>> describe("the", object) "the type 'object'" >>> describe("the", type(object)) "the type 'type'" Definitely named description: >>> describe("the", object(), "I made") 'the object I made' >>> describe("the", object, "I will use") 'the object I will use'
170,465
from datetime import tzinfo, timedelta, datetime UTC = tzUTC() class tzinfo: def tzname(self, dt: Optional[datetime]) -> Optional[str]: ... def utcoffset(self, dt: Optional[datetime]) -> Optional[timedelta]: ... def dst(self, dt: Optional[datetime]) -> Optional[timedelta]: ... def fromutc(self, dt: datetime) -> datetime: ... The provided code snippet includes necessary dependencies for implementing the `utc_aware` function. Write a Python function `def utc_aware(unaware)` to solve the following problem: decorator for adding UTC tzinfo to datetime's utcfoo methods Here is the function: def utc_aware(unaware): """decorator for adding UTC tzinfo to datetime's utcfoo methods""" def utc_method(*args, **kwargs): dt = unaware(*args, **kwargs) return dt.replace(tzinfo=UTC) return utc_method
decorator for adding UTC tzinfo to datetime's utcfoo methods
170,466
from datetime import tzinfo, timedelta, datetime The provided code snippet includes necessary dependencies for implementing the `isoformat` function. Write a Python function `def isoformat(dt)` to solve the following problem: Return iso-formatted timestamp Like .isoformat(), but uses Z for UTC instead of +00:00 Here is the function: def isoformat(dt): """Return iso-formatted timestamp Like .isoformat(), but uses Z for UTC instead of +00:00 """ return dt.isoformat().replace('+00:00', 'Z')
Return iso-formatted timestamp Like .isoformat(), but uses Z for UTC instead of +00:00
170,467
import json import struct import sys from urllib.parse import urlparse import tornado from tornado import gen, ioloop, web from tornado.iostream import StreamClosedError from tornado.websocket import WebSocketHandler, WebSocketClosedError from jupyter_client.session import Session from ipython_genutils.py3compat import cast_unicode from notebook.utils import maybe_future from .handlers import IPythonHandler def json_default(obj): """default function for packing objects in JSON.""" if isinstance(obj, datetime): obj = _ensure_tzinfo(obj) return obj.isoformat().replace('+00:00', 'Z') if isinstance(obj, bytes): return b2a_base64(obj, newline=False).decode('ascii') if isinstance(obj, Iterable): return list(obj) if isinstance(obj, numbers.Integral): return int(obj) if isinstance(obj, numbers.Real): return float(obj) raise TypeError("%r is not JSON serializable" % obj) The provided code snippet includes necessary dependencies for implementing the `serialize_binary_message` function. Write a Python function `def serialize_binary_message(msg)` to solve the following problem: serialize a message as a binary blob Header: 4 bytes: number of msg parts (nbufs) as 32b int 4 * nbufs bytes: offset for each buffer as integer as 32b int Offsets are from the start of the buffer, including the header. Returns ------- The message serialized to bytes. Here is the function: def serialize_binary_message(msg): """serialize a message as a binary blob Header: 4 bytes: number of msg parts (nbufs) as 32b int 4 * nbufs bytes: offset for each buffer as integer as 32b int Offsets are from the start of the buffer, including the header. Returns ------- The message serialized to bytes. """ # don't modify msg or buffer list in-place msg = msg.copy() buffers = list(msg.pop('buffers')) bmsg = json.dumps(msg, default=json_default).encode('utf8') buffers.insert(0, bmsg) nbufs = len(buffers) offsets = [4 * (nbufs + 1)] for buf in buffers[:-1]: offsets.append(offsets[-1] + len(buf)) offsets_buf = struct.pack('!' + 'I' * (nbufs + 1), nbufs, *offsets) buffers.insert(0, offsets_buf) return b''.join(buffers)
serialize a message as a binary blob Header: 4 bytes: number of msg parts (nbufs) as 32b int 4 * nbufs bytes: offset for each buffer as integer as 32b int Offsets are from the start of the buffer, including the header. Returns ------- The message serialized to bytes.
170,468
import json import struct import sys from urllib.parse import urlparse import tornado from tornado import gen, ioloop, web from tornado.iostream import StreamClosedError from tornado.websocket import WebSocketHandler, WebSocketClosedError from jupyter_client.session import Session from ipython_genutils.py3compat import cast_unicode from notebook.utils import maybe_future from .handlers import IPythonHandler def extract_dates(obj): """extract ISO8601 dates from unpacked JSON""" if isinstance(obj, dict): new_obj = {} # don't clobber for k, v in obj.items(): new_obj[k] = extract_dates(v) obj = new_obj elif isinstance(obj, (list, tuple)): obj = [extract_dates(o) for o in obj] elif isinstance(obj, str): obj = parse_date(obj) return obj The provided code snippet includes necessary dependencies for implementing the `deserialize_binary_message` function. Write a Python function `def deserialize_binary_message(bmsg)` to solve the following problem: deserialize a message from a binary blog Header: 4 bytes: number of msg parts (nbufs) as 32b int 4 * nbufs bytes: offset for each buffer as integer as 32b int Offsets are from the start of the buffer, including the header. Returns ------- message dictionary Here is the function: def deserialize_binary_message(bmsg): """deserialize a message from a binary blog Header: 4 bytes: number of msg parts (nbufs) as 32b int 4 * nbufs bytes: offset for each buffer as integer as 32b int Offsets are from the start of the buffer, including the header. Returns ------- message dictionary """ nbufs = struct.unpack('!i', bmsg[:4])[0] offsets = list(struct.unpack('!' + 'I' * nbufs, bmsg[4:4*(nbufs+1)])) offsets.append(None) bufs = [] for start, stop in zip(offsets[:-1], offsets[1:]): bufs.append(bmsg[start:stop]) msg = json.loads(bufs[0].decode('utf8')) msg['header'] = extract_dates(msg['header']) msg['parent_header'] = extract_dates(msg['parent_header']) msg['buffers'] = bufs[1:] return msg
deserialize a message from a binary blog Header: 4 bytes: number of msg parts (nbufs) as 32b int 4 * nbufs bytes: offset for each buffer as integer as 32b int Offsets are from the start of the buffer, including the header. Returns ------- message dictionary
170,469
import datetime import functools import ipaddress import json import mimetypes import os import re import sys import traceback import types import warnings from http.client import responses from http.cookies import Morsel from urllib.parse import urlparse from jinja2 import TemplateNotFound from tornado import web, gen, escape, httputil from tornado.log import app_log import prometheus_client from notebook._sysinfo import get_sys_info from traitlets.config import Application from ipython_genutils.path import filefind from ipython_genutils.py3compat import string_types import notebook from notebook._tz import utcnow from notebook.i18n import combine_translations from notebook.utils import is_hidden, url_path_join, url_is_absolute, url_escape, urldecode_unix_socket_path from notebook.services.security import csp_report_uri _sys_info_cache = None def get_sys_info(): def json_sys_info(): global _sys_info_cache if _sys_info_cache is None: _sys_info_cache = json.dumps(get_sys_info()) return _sys_info_cache
null
170,470
import datetime import functools import ipaddress import json import mimetypes import os import re import sys import traceback import types import warnings from http.client import responses from http.cookies import Morsel from urllib.parse import urlparse from jinja2 import TemplateNotFound from tornado import web, gen, escape, httputil from tornado.log import app_log import prometheus_client from notebook._sysinfo import get_sys_info from traitlets.config import Application from ipython_genutils.path import filefind from ipython_genutils.py3compat import string_types import notebook from notebook._tz import utcnow from notebook.i18n import combine_translations from notebook.utils import is_hidden, url_path_join, url_is_absolute, url_escape, urldecode_unix_socket_path from notebook.services.security import csp_report_uri class APIHandler(IPythonHandler): """Base class for API handlers""" def prepare(self): if not self.check_origin(): raise web.HTTPError(404) return super().prepare() def write_error(self, status_code, **kwargs): """APIHandler errors are JSON, not human pages""" self.set_header('Content-Type', 'application/json') message = responses.get(status_code, 'Unknown HTTP Error') reply = { 'message': message, } exc_info = kwargs.get('exc_info') if exc_info: e = exc_info[1] if isinstance(e, HTTPError): reply['message'] = e.log_message or message reply['reason'] = e.reason else: reply['message'] = 'Unhandled error' reply['reason'] = None reply['traceback'] = ''.join(traceback.format_exception(*exc_info)) self.log.warning(reply['message']) self.finish(json.dumps(reply)) def get_current_user(self): """Raise 403 on API handlers instead of redirecting to human login page""" # preserve _user_cache so we don't raise more than once if hasattr(self, '_user_cache'): return self._user_cache self._user_cache = user = super().get_current_user() return user def get_login_url(self): # if get_login_url is invoked in an API handler, # that means @web.authenticated is trying to trigger a redirect. # instead of redirecting, raise 403 instead. if not self.current_user: raise web.HTTPError(403) return super().get_login_url() def content_security_policy(self): csp = '; '.join([ super().content_security_policy, "default-src 'none'", ]) return csp # set _track_activity = False on API handlers that shouldn't track activity _track_activity = True def update_api_activity(self): """Update last_activity of API requests""" # record activity of authenticated requests if ( self._track_activity and getattr(self, '_user_cache', None) and self.get_argument('no_track_activity', None) is None ): self.settings['api_last_activity'] = utcnow() def finish(self, *args, **kwargs): self.update_api_activity() self.set_header('Content-Type', 'application/json') return super().finish(*args, **kwargs) def options(self, *args, **kwargs): if 'Access-Control-Allow-Headers' in self.settings.get('headers', {}): self.set_header('Access-Control-Allow-Headers', self.settings['headers']['Access-Control-Allow-Headers']) else: self.set_header('Access-Control-Allow-Headers', 'accept, content-type, authorization, x-xsrftoken') self.set_header('Access-Control-Allow-Methods', 'GET, PUT, POST, PATCH, DELETE, OPTIONS') # if authorization header is requested, # that means the request is token-authenticated. # avoid browser-side rejection of the preflight request. # only allow this exception if allow_origin has not been specified # and notebook authentication is enabled. # If the token is not valid, the 'real' request will still be rejected. requested_headers = self.request.headers.get('Access-Control-Request-Headers', '').split(',') if requested_headers and any( h.strip().lower() == 'authorization' for h in requested_headers ) and ( # FIXME: it would be even better to check specifically for token-auth, # but there is currently no API for this. self.login_available ) and ( self.allow_origin or self.allow_origin_pat or 'Access-Control-Allow-Origin' in self.settings.get('headers', {}) ): self.set_header('Access-Control-Allow-Origin', self.request.headers.get('Origin', '')) The provided code snippet includes necessary dependencies for implementing the `json_errors` function. Write a Python function `def json_errors(method)` to solve the following problem: Decorate methods with this to return GitHub style JSON errors. This should be used on any JSON API on any handler method that can raise HTTPErrors. This will grab the latest HTTPError exception using sys.exc_info and then: 1. Set the HTTP status code based on the HTTPError 2. Create and return a JSON body with a message field describing the error in a human readable form. Here is the function: def json_errors(method): """Decorate methods with this to return GitHub style JSON errors. This should be used on any JSON API on any handler method that can raise HTTPErrors. This will grab the latest HTTPError exception using sys.exc_info and then: 1. Set the HTTP status code based on the HTTPError 2. Create and return a JSON body with a message field describing the error in a human readable form. """ warnings.warn('@json_errors is deprecated in notebook 5.2.0. Subclass APIHandler instead.', DeprecationWarning, stacklevel=2, ) @functools.wraps(method) def wrapper(self, *args, **kwargs): self.write_error = types.MethodType(APIHandler.write_error, self) return method(self, *args, **kwargs) return wrapper
Decorate methods with this to return GitHub style JSON errors. This should be used on any JSON API on any handler method that can raise HTTPErrors. This will grab the latest HTTPError exception using sys.exc_info and then: 1. Set the HTTP status code based on the HTTPError 2. Create and return a JSON body with a message field describing the error in a human readable form.
170,471
from datetime import datetime import errno import os import shutil import stat import sys import warnings import mimetypes import nbformat from send2trash import send2trash from send2trash.exceptions import TrashPermissionError from tornado import web from .filecheckpoints import FileCheckpoints from .fileio import FileManagerMixin from .manager import ContentsManager from ...utils import exists from ipython_genutils.importstring import import_item from traitlets import Any, Unicode, Bool, TraitError, observe, default, validate from ipython_genutils.py3compat import getcwd, string_types from notebook import _tz as tz from notebook.utils import ( is_hidden, is_file_hidden, to_api_path, ) from notebook.base.handlers import AuthenticatedFileHandler from notebook.transutils import _ from os.path import samefile _script_exporter = None def to_api_path(os_path, root=''): """Convert a filesystem path to an API path If given, root will be removed from the path. root must be a filesystem path already. """ if os_path.startswith(root): os_path = os_path[len(root):] parts = os_path.strip(os.path.sep).split(os.path.sep) parts = [p for p in parts if p != ''] # remove duplicate splits path = '/'.join(parts) return path class ScriptExporter(TemplateExporter): """A script exporter.""" # Caches of already looked-up and instantiated exporters for delegation: _exporters = Dict() _lang_exporters = Dict() export_from_notebook = "Script" def _template_file_default(self): return "script.j2" def _template_name_default(self): return "script" def _get_language_exporter(self, lang_name): """Find an exporter for the language name from notebook metadata. Uses the nbconvert.exporters.script group of entry points. Returns None if no exporter is found. """ if lang_name not in self._lang_exporters: try: exporters = entry_points(group="nbconvert.exporters.script") exporter = [e for e in exporters if e.name == lang_name][0].load() except (KeyError, IndexError): self._lang_exporters[lang_name] = None else: # TODO: passing config is wrong, but changing this revealed more complicated issues self._lang_exporters[lang_name] = exporter(config=self.config, parent=self) return self._lang_exporters[lang_name] def from_notebook_node(self, nb, resources=None, **kw): """Convert from notebook node.""" langinfo = nb.metadata.get("language_info", {}) # delegate to custom exporter, if specified exporter_name = langinfo.get("nbconvert_exporter") if exporter_name and exporter_name != "script": self.log.debug("Loading script exporter: %s", exporter_name) if exporter_name not in self._exporters: exporter = get_exporter(exporter_name) # TODO: passing config is wrong, but changing this revealed more complicated issues self._exporters[exporter_name] = exporter(config=self.config, parent=self) exporter = self._exporters[exporter_name] return exporter.from_notebook_node(nb, resources, **kw) # Look up a script exporter for this notebook's language lang_name = langinfo.get("name") if lang_name: self.log.debug("Using script exporter for language: %s", lang_name) exporter = self._get_language_exporter(lang_name) if exporter is not None: return exporter.from_notebook_node(nb, resources, **kw) # Fall back to plain script export self.file_extension = langinfo.get("file_extension", ".txt") self.output_mimetype = langinfo.get("mimetype", "text/plain") return super().from_notebook_node(nb, resources, **kw) The provided code snippet includes necessary dependencies for implementing the `_post_save_script` function. Write a Python function `def _post_save_script(model, os_path, contents_manager, **kwargs)` to solve the following problem: convert notebooks to Python script after save with nbconvert replaces `jupyter notebook --script` Here is the function: def _post_save_script(model, os_path, contents_manager, **kwargs): """convert notebooks to Python script after save with nbconvert replaces `jupyter notebook --script` """ from nbconvert.exporters.script import ScriptExporter warnings.warn("`_post_save_script` is deprecated and will be removed in Notebook 5.0", DeprecationWarning) if model['type'] != 'notebook': return global _script_exporter if _script_exporter is None: _script_exporter = ScriptExporter(parent=contents_manager) log = contents_manager.log base, ext = os.path.splitext(os_path) script, resources = _script_exporter.from_filename(os_path) script_fname = base + resources.get('output_extension', '.txt') log.info("Saving script /%s", to_api_path(script_fname, contents_manager.root_dir)) with open(script_fname, 'w', encoding='utf-8') as f: f.write(script)
convert notebooks to Python script after save with nbconvert replaces `jupyter notebook --script`
170,472
from contextlib import contextmanager import errno import os import shutil from tornado.web import HTTPError from notebook.utils import ( to_api_path, to_os_path, ) import nbformat from ipython_genutils.py3compat import str_to_unicode from traitlets.config import Configurable from traitlets import Bool from base64 import encodebytes, decodebytes The provided code snippet includes necessary dependencies for implementing the `path_to_invalid` function. Write a Python function `def path_to_invalid(path)` to solve the following problem: Name of invalid file after a failed atomic write and subsequent read. Here is the function: def path_to_invalid(path): '''Name of invalid file after a failed atomic write and subsequent read.''' dirname, basename = os.path.split(path) return os.path.join(dirname, basename+'.invalid')
Name of invalid file after a failed atomic write and subsequent read.
170,473
from contextlib import contextmanager import errno import os import shutil from tornado.web import HTTPError from notebook.utils import ( to_api_path, to_os_path, ) import nbformat from ipython_genutils.py3compat import str_to_unicode from traitlets.config import Configurable from traitlets import Bool from base64 import encodebytes, decodebytes def replace_file(src, dst): """ replace dst with src switches between os.replace or os.rename based on python 2.7 or python 3 """ if hasattr(os, 'replace'): # PY3 os.replace(src, dst) else: if os.name == 'nt' and os.path.exists(dst): # Rename over existing file doesn't work on Windows os.remove(dst) os.rename(src, dst) def copy2_safe(src, dst, log=None): """copy src to dst like shutil.copy2, but log errors in copystat instead of raising """ shutil.copyfile(src, dst) try: shutil.copystat(src, dst) except OSError: if log: log.debug("copystat on %s failed", dst, exc_info=True) def path_to_intermediate(path): '''Name of the intermediate file used in atomic writes. The .~ prefix will make Dropbox ignore the temporary file.''' dirname, basename = os.path.split(path) return os.path.join(dirname, '.~'+basename) The provided code snippet includes necessary dependencies for implementing the `atomic_writing` function. Write a Python function `def atomic_writing(path, text=True, encoding='utf-8', log=None, **kwargs)` to solve the following problem: Context manager to write to a file only if the entire write is successful. This works by copying the previous file contents to a temporary file in the same directory, and renaming that file back to the target if the context exits with an error. If the context is successful, the new data is synced to disk and the temporary file is removed. Parameters ---------- path : str The target file to write to. text : bool, optional Whether to open the file in text mode (i.e. to write unicode). Default is True. encoding : str, optional The encoding to use for files opened in text mode. Default is UTF-8. **kwargs Passed to :func:`io.open`. Here is the function: def atomic_writing(path, text=True, encoding='utf-8', log=None, **kwargs): """Context manager to write to a file only if the entire write is successful. This works by copying the previous file contents to a temporary file in the same directory, and renaming that file back to the target if the context exits with an error. If the context is successful, the new data is synced to disk and the temporary file is removed. Parameters ---------- path : str The target file to write to. text : bool, optional Whether to open the file in text mode (i.e. to write unicode). Default is True. encoding : str, optional The encoding to use for files opened in text mode. Default is UTF-8. **kwargs Passed to :func:`io.open`. """ # realpath doesn't work on Windows: https://bugs.python.org/issue9949 # Luckily, we only need to resolve the file itself being a symlink, not # any of its directories, so this will suffice: if os.path.islink(path): path = os.path.join(os.path.dirname(path), os.readlink(path)) tmp_path = path_to_intermediate(path) if os.path.isfile(path): copy2_safe(path, tmp_path, log=log) if text: # Make sure that text files have Unix linefeeds by default kwargs.setdefault('newline', '\n') fileobj = open(path, 'w', encoding=encoding, **kwargs) else: fileobj = open(path, 'wb', **kwargs) try: yield fileobj except: # Failed! Move the backup file back to the real path to avoid corruption fileobj.close() replace_file(tmp_path, path) raise # Flush to disk fileobj.flush() os.fsync(fileobj.fileno()) fileobj.close() # Written successfully, now remove the backup copy if os.path.isfile(tmp_path): os.remove(tmp_path)
Context manager to write to a file only if the entire write is successful. This works by copying the previous file contents to a temporary file in the same directory, and renaming that file back to the target if the context exits with an error. If the context is successful, the new data is synced to disk and the temporary file is removed. Parameters ---------- path : str The target file to write to. text : bool, optional Whether to open the file in text mode (i.e. to write unicode). Default is True. encoding : str, optional The encoding to use for files opened in text mode. Default is UTF-8. **kwargs Passed to :func:`io.open`.
170,474
from contextlib import contextmanager import errno import os import shutil from tornado.web import HTTPError from notebook.utils import ( to_api_path, to_os_path, ) import nbformat from ipython_genutils.py3compat import str_to_unicode from traitlets.config import Configurable from traitlets import Bool from base64 import encodebytes, decodebytes The provided code snippet includes necessary dependencies for implementing the `_simple_writing` function. Write a Python function `def _simple_writing(path, text=True, encoding='utf-8', log=None, **kwargs)` to solve the following problem: Context manager to write file without doing atomic writing ( for weird filesystem eg: nfs). Parameters ---------- path : str The target file to write to. text : bool, optional Whether to open the file in text mode (i.e. to write unicode). Default is True. encoding : str, optional The encoding to use for files opened in text mode. Default is UTF-8. **kwargs Passed to :func:`io.open`. Here is the function: def _simple_writing(path, text=True, encoding='utf-8', log=None, **kwargs): """Context manager to write file without doing atomic writing ( for weird filesystem eg: nfs). Parameters ---------- path : str The target file to write to. text : bool, optional Whether to open the file in text mode (i.e. to write unicode). Default is True. encoding : str, optional The encoding to use for files opened in text mode. Default is UTF-8. **kwargs Passed to :func:`io.open`. """ # realpath doesn't work on Windows: https://bugs.python.org/issue9949 # Luckily, we only need to resolve the file itself being a symlink, not # any of its directories, so this will suffice: if os.path.islink(path): path = os.path.join(os.path.dirname(path), os.readlink(path)) if text: # Make sure that text files have Unix linefeeds by default kwargs.setdefault('newline', '\n') fileobj = open(path, 'w', encoding=encoding, **kwargs) else: fileobj = open(path, 'wb', **kwargs) try: yield fileobj except: fileobj.close() raise fileobj.close()
Context manager to write file without doing atomic writing ( for weird filesystem eg: nfs). Parameters ---------- path : str The target file to write to. text : bool, optional Whether to open the file in text mode (i.e. to write unicode). Default is True. encoding : str, optional The encoding to use for files opened in text mode. Default is UTF-8. **kwargs Passed to :func:`io.open`.
170,475
import json from tornado import gen, web from notebook.utils import maybe_future, url_path_join, url_escape from notebook.base.handlers import ( IPythonHandler, APIHandler, path_regex, ) The provided code snippet includes necessary dependencies for implementing the `validate_model` function. Write a Python function `def validate_model(model, expect_content)` to solve the following problem: Validate a model returned by a ContentsManager method. If expect_content is True, then we expect non-null entries for 'content' and 'format'. Here is the function: def validate_model(model, expect_content): """ Validate a model returned by a ContentsManager method. If expect_content is True, then we expect non-null entries for 'content' and 'format'. """ required_keys = { "name", "path", "type", "writable", "created", "last_modified", "mimetype", "content", "format", } missing = required_keys - set(model.keys()) if missing: raise web.HTTPError( 500, f"Missing Model Keys: {missing}", ) maybe_none_keys = ['content', 'format'] if expect_content: errors = [key for key in maybe_none_keys if model[key] is None] if errors: raise web.HTTPError( 500, f"Keys unexpectedly None: {errors}", ) else: errors = { key: model[key] for key in maybe_none_keys if model[key] is not None } if errors: raise web.HTTPError( 500, f"Keys unexpectedly not None: {errors}", )
Validate a model returned by a ContentsManager method. If expect_content is True, then we expect non-null entries for 'content' and 'format'.
170,476
import glob import json import os pjoin = os.path.join from tornado import web, gen from ...base.handlers import APIHandler from ...utils import maybe_future, url_path_join, url_unescape def url_path_join(*pieces): """Join components of url into a relative url Use to prevent double slash when joining subpath. This will leave the initial and final / in place """ initial = pieces[0].startswith('/') final = pieces[-1].endswith('/') stripped = [s.strip('/') for s in pieces] result = '/'.join(s for s in stripped if s) if initial: result = '/' + result if final: result = result + '/' if result == '//': result = '/' return result The provided code snippet includes necessary dependencies for implementing the `kernelspec_model` function. Write a Python function `def kernelspec_model(handler, name, spec_dict, resource_dir)` to solve the following problem: Load a KernelSpec by name and return the REST API model Here is the function: def kernelspec_model(handler, name, spec_dict, resource_dir): """Load a KernelSpec by name and return the REST API model""" d = { 'name': name, 'spec': spec_dict, 'resources': {} } # Add resource files if they exist for resource in ['kernel.js', 'kernel.css']: if os.path.exists(pjoin(resource_dir, resource)): d['resources'][resource] = url_path_join( handler.base_url, 'kernelspecs', name, resource ) for logo_file in glob.glob(pjoin(resource_dir, 'logo-*')): fname = os.path.basename(logo_file) no_ext, _ = os.path.splitext(fname) d['resources'][no_ext] = url_path_join( handler.base_url, 'kernelspecs', name, fname ) return d
Load a KernelSpec by name and return the REST API model
170,477
import glob import json import os from tornado import web, gen from ...base.handlers import APIHandler from ...utils import maybe_future, url_path_join, url_unescape The provided code snippet includes necessary dependencies for implementing the `is_kernelspec_model` function. Write a Python function `def is_kernelspec_model(spec_dict)` to solve the following problem: Returns True if spec_dict is already in proper form. This will occur when using a gateway. Here is the function: def is_kernelspec_model(spec_dict): """Returns True if spec_dict is already in proper form. This will occur when using a gateway.""" return isinstance(spec_dict, dict) and 'name' in spec_dict and 'spec' in spec_dict and 'resources' in spec_dict
Returns True if spec_dict is already in proper form. This will occur when using a gateway.
170,478
import json from tornado.log import access_log from .prometheus.log_functions import prometheus_log_method access_log = logging.getLogger("tornado.access") def prometheus_log_method(handler): """ Tornado log handler for recording RED metrics. We record the following metrics: Rate - the number of requests, per second, your services are serving. Errors - the number of failed requests per second. Duration - The amount of time each request takes expressed as a time interval. We use a fully qualified name of the handler as a label, rather than every url path to reduce cardinality. This function should be either the value of or called from a function that is the 'log_function' tornado setting. This makes it get called at the end of every request, allowing us to record the metrics we need. """ HTTP_REQUEST_DURATION_SECONDS.labels( method=handler.request.method, handler=f'{handler.__class__.__module__}.{type(handler).__name__}', status_code=handler.get_status() ).observe(handler.request.request_time()) The provided code snippet includes necessary dependencies for implementing the `log_request` function. Write a Python function `def log_request(handler, log=access_log, log_json=False)` to solve the following problem: log a bit more information about each request than tornado's default - move static file get success to debug-level (reduces noise) - get proxied IP instead of proxy IP - log referer for redirect and failed requests - log user-agent for failed requests Here is the function: def log_request(handler, log=access_log, log_json=False): """log a bit more information about each request than tornado's default - move static file get success to debug-level (reduces noise) - get proxied IP instead of proxy IP - log referer for redirect and failed requests - log user-agent for failed requests """ status = handler.get_status() request = handler.request if status < 300 or status == 304: # Successes (or 304 FOUND) are debug-level log_method = log.debug elif status < 400: log_method = log.info elif status < 500: log_method = log.warning else: log_method = log.error request_time = 1000.0 * request.request_time() ns = dict( status=status, method=request.method, ip=request.remote_ip, uri=request.uri, request_time=float(f'{request_time:.2f}'), ) msg = "{status} {method} {uri} ({ip}) {request_time:f}ms" if status >= 400: # log bad referers ns['referer'] = request.headers.get('Referer', 'None') msg += ' referer={referer}' if status >= 500 and status != 502: # Log a subset of the headers if it caused an error. headers = {} for header in ['Host', 'Accept', 'Referer', 'User-Agent']: if header in request.headers: headers[header] = request.headers[header] if log_json: log_method("", extra=dict(props=headers)) else: log_method(json.dumps(dict(headers), indent=2)) if log_json: log_method("", extra=dict(props=ns)) else: log_method(msg.format(**ns)) prometheus_log_method(handler)
log a bit more information about each request than tornado's default - move static file get success to debug-level (reduces noise) - get proxied IP instead of proxy IP - log referer for redirect and failed requests - log user-agent for failed requests
170,479
import os import shutil import sys import tarfile import zipfile from os.path import basename, join as pjoin, normpath from urllib.parse import urlparse from urllib.request import urlretrieve from jupyter_core.paths import ( jupyter_data_dir, jupyter_config_path, jupyter_path, SYSTEM_JUPYTER_PATH, ENV_JUPYTER_PATH, ) from jupyter_core.utils import ensure_dir_exists from ipython_genutils.py3compat import string_types, cast_unicode_py2 from ipython_genutils.tempdir import TemporaryDirectory from ._version import __version__ from .config_manager import BaseJSONConfigManager from traitlets.utils.importstring import import_item from .extensions import ( BaseExtensionApp, _get_config_dir, GREEN_ENABLED, RED_DISABLED, GREEN_OK, RED_X, ArgumentConflict, _base_aliases, _base_flags, ) from traitlets import Bool, Unicode def _get_nbextension_dir(user=False, sys_prefix=False, prefix=None, nbextensions_dir=None): """Return the nbextension directory specified Parameters ---------- user : bool [default: False] Get the user's .jupyter/nbextensions directory sys_prefix : bool [default: False] Get sys.prefix, i.e. ~/.envs/my-env/share/jupyter/nbextensions prefix : str [optional] Get custom prefix nbextensions_dir : str [optional] Get what you put in """ conflicting = [ ('user', user), ('prefix', prefix), ('nbextensions_dir', nbextensions_dir), ('sys_prefix', sys_prefix), ] conflicting_set = [f'{n}={v!r}' for n, v in conflicting if v] if len(conflicting_set) > 1: raise ArgumentConflict( f"cannot specify more than one of user, sys_prefix, prefix, or nbextensions_dir, " f"but got: {', '.join(conflicting_set)}" ) if user: nbext = pjoin(jupyter_data_dir(), 'nbextensions') elif sys_prefix: nbext = pjoin(ENV_JUPYTER_PATH[0], 'nbextensions') elif prefix: nbext = pjoin(prefix, 'share', 'jupyter', 'nbextensions') elif nbextensions_dir: nbext = nbextensions_dir else: nbext = pjoin(SYSTEM_JUPYTER_PATH[0], 'nbextensions') return nbext import os del os The provided code snippet includes necessary dependencies for implementing the `check_nbextension` function. Write a Python function `def check_nbextension(files, user=False, prefix=None, nbextensions_dir=None, sys_prefix=False)` to solve the following problem: Check whether nbextension files have been installed Returns True if all files are found, False if any are missing. Parameters ---------- files : list(paths) a list of relative paths within nbextensions. user : bool [default: False] Whether to check the user's .jupyter/nbextensions directory. Otherwise check a system-wide install (e.g. /usr/local/share/jupyter/nbextensions). prefix : str [optional] Specify install prefix, if it should differ from default (e.g. /usr/local). Will check prefix/share/jupyter/nbextensions nbextensions_dir : str [optional] Specify absolute path of nbextensions directory explicitly. sys_prefix : bool [default: False] Install into the sys.prefix, i.e. environment Here is the function: def check_nbextension(files, user=False, prefix=None, nbextensions_dir=None, sys_prefix=False): """Check whether nbextension files have been installed Returns True if all files are found, False if any are missing. Parameters ---------- files : list(paths) a list of relative paths within nbextensions. user : bool [default: False] Whether to check the user's .jupyter/nbextensions directory. Otherwise check a system-wide install (e.g. /usr/local/share/jupyter/nbextensions). prefix : str [optional] Specify install prefix, if it should differ from default (e.g. /usr/local). Will check prefix/share/jupyter/nbextensions nbextensions_dir : str [optional] Specify absolute path of nbextensions directory explicitly. sys_prefix : bool [default: False] Install into the sys.prefix, i.e. environment """ nbext = _get_nbextension_dir(user=user, sys_prefix=sys_prefix, prefix=prefix, nbextensions_dir=nbextensions_dir) # make sure nbextensions dir exists if not os.path.exists(nbext): return False if isinstance(files, string_types): # one file given, turn it into a list files = [files] return all(os.path.exists(pjoin(nbext, f)) for f in files)
Check whether nbextension files have been installed Returns True if all files are found, False if any are missing. Parameters ---------- files : list(paths) a list of relative paths within nbextensions. user : bool [default: False] Whether to check the user's .jupyter/nbextensions directory. Otherwise check a system-wide install (e.g. /usr/local/share/jupyter/nbextensions). prefix : str [optional] Specify install prefix, if it should differ from default (e.g. /usr/local). Will check prefix/share/jupyter/nbextensions nbextensions_dir : str [optional] Specify absolute path of nbextensions directory explicitly. sys_prefix : bool [default: False] Install into the sys.prefix, i.e. environment
170,480
import os import shutil import sys import tarfile import zipfile from os.path import basename, join as pjoin, normpath from urllib.parse import urlparse from urllib.request import urlretrieve from jupyter_core.paths import ( jupyter_data_dir, jupyter_config_path, jupyter_path, SYSTEM_JUPYTER_PATH, ENV_JUPYTER_PATH, ) from jupyter_core.utils import ensure_dir_exists from ipython_genutils.py3compat import string_types, cast_unicode_py2 from ipython_genutils.tempdir import TemporaryDirectory from ._version import __version__ from .config_manager import BaseJSONConfigManager from traitlets.utils.importstring import import_item def install_nbextension(path, overwrite=False, symlink=False, user=False, prefix=None, nbextensions_dir=None, destination=None, verbose=DEPRECATED_ARGUMENT, logger=None, sys_prefix=False ): """Install a Javascript extension for the notebook Stages files and/or directories into the nbextensions directory. By default, this compares modification time, and only stages files that need updating. If `overwrite` is specified, matching files are purged before proceeding. Parameters ---------- path : path to file, directory, zip or tarball archive, or URL to install By default, the file will be installed with its base name, so '/path/to/foo' will install to 'nbextensions/foo'. See the destination argument below to change this. Archives (zip or tarballs) will be extracted into the nbextensions directory. overwrite : bool [default: False] If True, always install the files, regardless of what may already be installed. symlink : bool [default: False] If True, create a symlink in nbextensions, rather than copying files. Not allowed with URLs or archives. Windows support for symlinks requires Vista or above, Python 3, and a permission bit which only admin users have by default, so don't rely on it. user : bool [default: False] Whether to install to the user's nbextensions directory. Otherwise do a system-wide install (e.g. /usr/local/share/jupyter/nbextensions). prefix : str [optional] Specify install prefix, if it should differ from default (e.g. /usr/local). Will install to ``<prefix>/share/jupyter/nbextensions`` nbextensions_dir : str [optional] Specify absolute path of nbextensions directory explicitly. destination : str [optional] name the nbextension is installed to. For example, if destination is 'foo', then the source file will be installed to 'nbextensions/foo', regardless of the source name. This cannot be specified if an archive is given as the source. logger : Jupyter logger [optional] Logger instance to use """ if verbose != DEPRECATED_ARGUMENT: import warnings warnings.warn("`install_nbextension`'s `verbose` parameter is deprecated, it will have no effects and will be removed in Notebook 5.0", DeprecationWarning) # the actual path to which we eventually installed full_dest = None nbext = _get_nbextension_dir(user=user, sys_prefix=sys_prefix, prefix=prefix, nbextensions_dir=nbextensions_dir) # make sure nbextensions dir exists ensure_dir_exists(nbext) # forcing symlink parameter to False if os.symlink does not exist (e.g., on Windows machines running python 2) if not hasattr(os, 'symlink'): symlink = False if isinstance(path, (list, tuple)): raise TypeError("path must be a string pointing to a single extension to install; call this function multiple times to install multiple extensions") path = cast_unicode_py2(path) if path.startswith(('https://', 'http://')): if symlink: raise ValueError("Cannot symlink from URLs") # Given a URL, download it with TemporaryDirectory() as td: filename = urlparse(path).path.split('/')[-1] local_path = os.path.join(td, filename) if logger: logger.info(f"Downloading: {path} -> {local_path}") urlretrieve(path, local_path) # now install from the local copy full_dest = install_nbextension(local_path, overwrite=overwrite, symlink=symlink, nbextensions_dir=nbext, destination=destination, logger=logger) elif path.endswith('.zip') or _safe_is_tarfile(path): if symlink: raise ValueError("Cannot symlink from archives") if destination: raise ValueError("Cannot give destination for archives") if logger: logger.info(f"Extracting: {path} -> {nbext}") if path.endswith('.zip'): archive = zipfile.ZipFile(path) elif _safe_is_tarfile(path): archive = tarfile.open(path) archive.extractall(nbext) archive.close() # TODO: what to do here full_dest = None else: if not destination: destination = basename(normpath(path)) destination = cast_unicode_py2(destination) full_dest = normpath(pjoin(nbext, destination)) if overwrite and os.path.lexists(full_dest): if logger: logger.info(f"Removing: {full_dest}") if os.path.isdir(full_dest) and not os.path.islink(full_dest): shutil.rmtree(full_dest) else: os.remove(full_dest) if symlink: path = os.path.abspath(path) if not os.path.exists(full_dest): if logger: logger.info(f"Symlinking: {full_dest} -> {path}") os.symlink(path, full_dest) elif os.path.isdir(path): path = pjoin(os.path.abspath(path), '') # end in path separator for parent, dirs, files in os.walk(path): dest_dir = pjoin(full_dest, parent[len(path):]) if not os.path.exists(dest_dir): if logger: logger.info(f"Making directory: {dest_dir}") os.makedirs(dest_dir) for file_name in files: src = pjoin(parent, file_name) dest_file = pjoin(dest_dir, file_name) _maybe_copy(src, dest_file, logger=logger) else: src = path _maybe_copy(src, full_dest, logger=logger) return full_dest def validate_nbextension_python(spec, full_dest, logger=None): """Assess the health of an installed nbextension Returns a list of warnings. Parameters ---------- spec : dict A single entry of _jupyter_nbextension_paths(): [{ 'section': 'notebook', 'src': 'mockextension', 'dest': '_mockdestination', 'require': '_mockdestination/index' }] full_dest : str The on-disk location of the installed nbextension: this should end with `nbextensions/<dest>` logger : Jupyter logger [optional] Logger instance to use """ infos = [] warnings = [] section = spec.get("section", None) if section in NBCONFIG_SECTIONS: infos.append(f" {GREEN_OK} section: {section}") else: warnings.append(f" {RED_X} section: {section}") require = spec.get("require", None) if require is not None: require_path = os.path.join( full_dest[0:-len(spec["dest"])], f"{require}.js") if os.path.exists(require_path): infos.append(f" {GREEN_OK} require: {require_path}") else: warnings.append(f" {RED_X} require: {require_path}") if logger: if warnings: logger.warning("- Validating: problems found:") for msg in warnings: logger.warning(msg) for msg in infos: logger.info(msg) logger.warning(f"Full spec: {spec}") else: logger.info(f"- Validating: {GREEN_OK}") return warnings from .extensions import ( BaseExtensionApp, _get_config_dir, GREEN_ENABLED, RED_DISABLED, GREEN_OK, RED_X, ArgumentConflict, _base_aliases, _base_flags, ) from traitlets import Bool, Unicode def _get_nbextension_metadata(module): """Get the list of nbextension paths associated with a Python module. Returns a tuple of (the module, [{ 'section': 'notebook', 'src': 'mockextension', 'dest': '_mockdestination', 'require': '_mockdestination/index' }]) Parameters ---------- module : str Importable Python module exposing the magic-named `_jupyter_nbextension_paths` function """ m = import_item(module) if not hasattr(m, '_jupyter_nbextension_paths'): raise KeyError( f'The Python module {module} is not a valid nbextension, ' f'it is missing the `_jupyter_nbextension_paths()` method.' ) nbexts = m._jupyter_nbextension_paths() return m, nbexts import os del os The provided code snippet includes necessary dependencies for implementing the `install_nbextension_python` function. Write a Python function `def install_nbextension_python(module, overwrite=False, symlink=False, user=False, sys_prefix=False, prefix=None, nbextensions_dir=None, logger=None)` to solve the following problem: Install an nbextension bundled in a Python package. Returns a list of installed/updated directories. See install_nbextension for parameter information. Here is the function: def install_nbextension_python(module, overwrite=False, symlink=False, user=False, sys_prefix=False, prefix=None, nbextensions_dir=None, logger=None): """Install an nbextension bundled in a Python package. Returns a list of installed/updated directories. See install_nbextension for parameter information.""" m, nbexts = _get_nbextension_metadata(module) base_path = os.path.split(m.__file__)[0] full_dests = [] for nbext in nbexts: src = os.path.join(base_path, nbext['src']) dest = nbext['dest'] if logger: logger.info(f"Installing {src} -> {dest}") full_dest = install_nbextension( src, overwrite=overwrite, symlink=symlink, user=user, sys_prefix=sys_prefix, prefix=prefix, nbextensions_dir=nbextensions_dir, destination=dest, logger=logger ) validate_nbextension_python(nbext, full_dest, logger) full_dests.append(full_dest) return full_dests
Install an nbextension bundled in a Python package. Returns a list of installed/updated directories. See install_nbextension for parameter information.
170,481
import os import shutil import sys import tarfile import zipfile from os.path import basename, join as pjoin, normpath from urllib.parse import urlparse from urllib.request import urlretrieve from jupyter_core.paths import ( jupyter_data_dir, jupyter_config_path, jupyter_path, SYSTEM_JUPYTER_PATH, ENV_JUPYTER_PATH, ) from jupyter_core.utils import ensure_dir_exists from ipython_genutils.py3compat import string_types, cast_unicode_py2 from ipython_genutils.tempdir import TemporaryDirectory from ._version import __version__ from .config_manager import BaseJSONConfigManager from traitlets.utils.importstring import import_item from .extensions import ( BaseExtensionApp, _get_config_dir, GREEN_ENABLED, RED_DISABLED, GREEN_OK, RED_X, ArgumentConflict, _base_aliases, _base_flags, ) from traitlets import Bool, Unicode import os del os def jupyter_path(*subdirs: str) -> List[str]: """Return a list of directories to search for data files JUPYTER_PATH environment variable has highest priority. If the JUPYTER_PREFER_ENV_PATH environment variable is set, the environment-level directories will have priority over user-level directories. If the Python site.ENABLE_USER_SITE variable is True, we also add the appropriate Python user site subdirectory to the user-level directories. If ``*subdirs`` are given, that subdirectory will be added to each element. Examples: >>> jupyter_path() ['~/.local/jupyter', '/usr/local/share/jupyter'] >>> jupyter_path('kernels') ['~/.local/jupyter/kernels', '/usr/local/share/jupyter/kernels'] """ paths: List[str] = [] # highest priority is explicit environment variable if os.environ.get("JUPYTER_PATH"): paths.extend(p.rstrip(os.sep) for p in os.environ["JUPYTER_PATH"].split(os.pathsep)) # Next is environment or user, depending on the JUPYTER_PREFER_ENV_PATH flag user = [jupyter_data_dir()] if site.ENABLE_USER_SITE: # Check if site.getuserbase() exists to be compatible with virtualenv, # which often does not have this method. userbase: Optional[str] userbase = site.getuserbase() if hasattr(site, "getuserbase") else site.USER_BASE if userbase: userdir = os.path.join(userbase, "share", "jupyter") if userdir not in user: user.append(userdir) env = [p for p in ENV_JUPYTER_PATH if p not in SYSTEM_JUPYTER_PATH] if prefer_environment_over_user(): paths.extend(env) paths.extend(user) else: paths.extend(user) paths.extend(env) # finally, system paths.extend(SYSTEM_JUPYTER_PATH) # add subdir, if requested if subdirs: paths = [pjoin(p, *subdirs) for p in paths] return paths The provided code snippet includes necessary dependencies for implementing the `_find_uninstall_nbextension` function. Write a Python function `def _find_uninstall_nbextension(filename, logger=None)` to solve the following problem: Remove nbextension files from the first location they are found. Returns True if files were removed, False otherwise. Here is the function: def _find_uninstall_nbextension(filename, logger=None): """Remove nbextension files from the first location they are found. Returns True if files were removed, False otherwise. """ filename = cast_unicode_py2(filename) for nbext in jupyter_path('nbextensions'): path = pjoin(nbext, filename) if os.path.lexists(path): if logger: logger.info(f"Removing: {path}") if os.path.isdir(path) and not os.path.islink(path): shutil.rmtree(path) else: os.remove(path) return True return False
Remove nbextension files from the first location they are found. Returns True if files were removed, False otherwise.
170,482
import os import shutil import sys import tarfile import zipfile from os.path import basename, join as pjoin, normpath from urllib.parse import urlparse from urllib.request import urlretrieve from jupyter_core.paths import ( jupyter_data_dir, jupyter_config_path, jupyter_path, SYSTEM_JUPYTER_PATH, ENV_JUPYTER_PATH, ) from jupyter_core.utils import ensure_dir_exists from ipython_genutils.py3compat import string_types, cast_unicode_py2 from ipython_genutils.tempdir import TemporaryDirectory from ._version import __version__ from .config_manager import BaseJSONConfigManager from traitlets.utils.importstring import import_item def uninstall_nbextension(dest, require=None, user=False, sys_prefix=False, prefix=None, nbextensions_dir=None, logger=None): """Uninstall a Javascript extension of the notebook Removes staged files and/or directories in the nbextensions directory and removes the extension from the frontend config. Parameters ---------- dest : str path to file, directory, zip or tarball archive, or URL to install name the nbextension is installed to. For example, if destination is 'foo', then the source file will be installed to 'nbextensions/foo', regardless of the source name. This cannot be specified if an archive is given as the source. require : str [optional] require.js path used to load the extension. If specified, frontend config loading extension will be removed. user : bool [default: False] Whether to install to the user's nbextensions directory. Otherwise do a system-wide install (e.g. /usr/local/share/jupyter/nbextensions). prefix : str [optional] Specify install prefix, if it should differ from default (e.g. /usr/local). Will install to ``<prefix>/share/jupyter/nbextensions`` nbextensions_dir : str [optional] Specify absolute path of nbextensions directory explicitly. logger : Jupyter logger [optional] Logger instance to use """ nbext = _get_nbextension_dir(user=user, sys_prefix=sys_prefix, prefix=prefix, nbextensions_dir=nbextensions_dir) dest = cast_unicode_py2(dest) full_dest = pjoin(nbext, dest) if os.path.lexists(full_dest): if logger: logger.info(f"Removing: {full_dest}") if os.path.isdir(full_dest) and not os.path.islink(full_dest): shutil.rmtree(full_dest) else: os.remove(full_dest) # Look through all of the config sections making sure that the nbextension # doesn't exist. config_dir = os.path.join(_get_config_dir(user=user, sys_prefix=sys_prefix), 'nbconfig') cm = BaseJSONConfigManager(config_dir=config_dir) if require: for section in NBCONFIG_SECTIONS: cm.update(section, {"load_extensions": {require: None}}) from .extensions import ( BaseExtensionApp, _get_config_dir, GREEN_ENABLED, RED_DISABLED, GREEN_OK, RED_X, ArgumentConflict, _base_aliases, _base_flags, ) from traitlets import Bool, Unicode def _get_nbextension_metadata(module): """Get the list of nbextension paths associated with a Python module. Returns a tuple of (the module, [{ 'section': 'notebook', 'src': 'mockextension', 'dest': '_mockdestination', 'require': '_mockdestination/index' }]) Parameters ---------- module : str Importable Python module exposing the magic-named `_jupyter_nbextension_paths` function """ m = import_item(module) if not hasattr(m, '_jupyter_nbextension_paths'): raise KeyError( f'The Python module {module} is not a valid nbextension, ' f'it is missing the `_jupyter_nbextension_paths()` method.' ) nbexts = m._jupyter_nbextension_paths() return m, nbexts The provided code snippet includes necessary dependencies for implementing the `uninstall_nbextension_python` function. Write a Python function `def uninstall_nbextension_python(module, user=False, sys_prefix=False, prefix=None, nbextensions_dir=None, logger=None)` to solve the following problem: Uninstall an nbextension bundled in a Python package. See parameters of `install_nbextension_python` Here is the function: def uninstall_nbextension_python(module, user=False, sys_prefix=False, prefix=None, nbextensions_dir=None, logger=None): """Uninstall an nbextension bundled in a Python package. See parameters of `install_nbextension_python` """ m, nbexts = _get_nbextension_metadata(module) for nbext in nbexts: dest = nbext['dest'] require = nbext['require'] if logger: logger.info(f"Uninstalling {dest} {require}") uninstall_nbextension(dest, require, user=user, sys_prefix=sys_prefix, prefix=prefix, nbextensions_dir=nbextensions_dir, logger=logger)
Uninstall an nbextension bundled in a Python package. See parameters of `install_nbextension_python`
170,483
import os import shutil import sys import tarfile import zipfile from os.path import basename, join as pjoin, normpath from urllib.parse import urlparse from urllib.request import urlretrieve from jupyter_core.paths import ( jupyter_data_dir, jupyter_config_path, jupyter_path, SYSTEM_JUPYTER_PATH, ENV_JUPYTER_PATH, ) from jupyter_core.utils import ensure_dir_exists from ipython_genutils.py3compat import string_types, cast_unicode_py2 from ipython_genutils.tempdir import TemporaryDirectory from ._version import __version__ from .config_manager import BaseJSONConfigManager from traitlets.utils.importstring import import_item def _set_nbextension_state(section, require, state, user=True, sys_prefix=False, logger=None): """Set whether the section's frontend should require the named nbextension Returns True if the final state is the one requested. Parameters ---------- section : string The section of the server to change, one of NBCONFIG_SECTIONS require : string An importable AMD module inside the nbextensions static path state : bool The state in which to leave the extension user : bool [default: True] Whether to update the user's .jupyter/nbextensions directory sys_prefix : bool [default: False] Whether to update the sys.prefix, i.e. environment. Will override `user`. logger : Jupyter logger [optional] Logger instance to use """ user = False if sys_prefix else user config_dir = os.path.join( _get_config_dir(user=user, sys_prefix=sys_prefix), 'nbconfig') cm = BaseJSONConfigManager(config_dir=config_dir) if logger: logger.info(f"{'Enabling' if state else 'Disabling'} {section} extension {require}...") cm.update(section, {"load_extensions": {require: state}}) validate_nbextension(require, logger=logger) return cm.get(section).get(require) == state from .extensions import ( BaseExtensionApp, _get_config_dir, GREEN_ENABLED, RED_DISABLED, GREEN_OK, RED_X, ArgumentConflict, _base_aliases, _base_flags, ) from traitlets import Bool, Unicode The provided code snippet includes necessary dependencies for implementing the `enable_nbextension` function. Write a Python function `def enable_nbextension(section, require, user=True, sys_prefix=False, logger=None)` to solve the following problem: Enable a named nbextension Returns True if the final state is the one requested. Parameters ---------- section : string The section of the server to change, one of NBCONFIG_SECTIONS require : string An importable AMD module inside the nbextensions static path user : bool [default: True] Whether to enable in the user's nbextensions directory. sys_prefix : bool [default: False] Whether to enable in the sys.prefix, i.e. environment. Will override `user` logger : Jupyter logger [optional] Logger instance to use Here is the function: def enable_nbextension(section, require, user=True, sys_prefix=False, logger=None): """Enable a named nbextension Returns True if the final state is the one requested. Parameters ---------- section : string The section of the server to change, one of NBCONFIG_SECTIONS require : string An importable AMD module inside the nbextensions static path user : bool [default: True] Whether to enable in the user's nbextensions directory. sys_prefix : bool [default: False] Whether to enable in the sys.prefix, i.e. environment. Will override `user` logger : Jupyter logger [optional] Logger instance to use """ return _set_nbextension_state(section=section, require=require, state=True, user=user, sys_prefix=sys_prefix, logger=logger)
Enable a named nbextension Returns True if the final state is the one requested. Parameters ---------- section : string The section of the server to change, one of NBCONFIG_SECTIONS require : string An importable AMD module inside the nbextensions static path user : bool [default: True] Whether to enable in the user's nbextensions directory. sys_prefix : bool [default: False] Whether to enable in the sys.prefix, i.e. environment. Will override `user` logger : Jupyter logger [optional] Logger instance to use
170,484
import os import shutil import sys import tarfile import zipfile from os.path import basename, join as pjoin, normpath from urllib.parse import urlparse from urllib.request import urlretrieve from jupyter_core.paths import ( jupyter_data_dir, jupyter_config_path, jupyter_path, SYSTEM_JUPYTER_PATH, ENV_JUPYTER_PATH, ) from jupyter_core.utils import ensure_dir_exists from ipython_genutils.py3compat import string_types, cast_unicode_py2 from ipython_genutils.tempdir import TemporaryDirectory from ._version import __version__ from .config_manager import BaseJSONConfigManager from traitlets.utils.importstring import import_item def _set_nbextension_state(section, require, state, user=True, sys_prefix=False, logger=None): """Set whether the section's frontend should require the named nbextension Returns True if the final state is the one requested. Parameters ---------- section : string The section of the server to change, one of NBCONFIG_SECTIONS require : string An importable AMD module inside the nbextensions static path state : bool The state in which to leave the extension user : bool [default: True] Whether to update the user's .jupyter/nbextensions directory sys_prefix : bool [default: False] Whether to update the sys.prefix, i.e. environment. Will override `user`. logger : Jupyter logger [optional] Logger instance to use """ user = False if sys_prefix else user config_dir = os.path.join( _get_config_dir(user=user, sys_prefix=sys_prefix), 'nbconfig') cm = BaseJSONConfigManager(config_dir=config_dir) if logger: logger.info(f"{'Enabling' if state else 'Disabling'} {section} extension {require}...") cm.update(section, {"load_extensions": {require: state}}) validate_nbextension(require, logger=logger) return cm.get(section).get(require) == state from .extensions import ( BaseExtensionApp, _get_config_dir, GREEN_ENABLED, RED_DISABLED, GREEN_OK, RED_X, ArgumentConflict, _base_aliases, _base_flags, ) from traitlets import Bool, Unicode The provided code snippet includes necessary dependencies for implementing the `disable_nbextension` function. Write a Python function `def disable_nbextension(section, require, user=True, sys_prefix=False, logger=None)` to solve the following problem: Disable a named nbextension Returns True if the final state is the one requested. Parameters ---------- section : string The section of the server to change, one of NBCONFIG_SECTIONS require : string An importable AMD module inside the nbextensions static path user : bool [default: True] Whether to enable in the user's nbextensions directory. sys_prefix : bool [default: False] Whether to enable in the sys.prefix, i.e. environment. Will override `user`. logger : Jupyter logger [optional] Logger instance to use Here is the function: def disable_nbextension(section, require, user=True, sys_prefix=False, logger=None): """Disable a named nbextension Returns True if the final state is the one requested. Parameters ---------- section : string The section of the server to change, one of NBCONFIG_SECTIONS require : string An importable AMD module inside the nbextensions static path user : bool [default: True] Whether to enable in the user's nbextensions directory. sys_prefix : bool [default: False] Whether to enable in the sys.prefix, i.e. environment. Will override `user`. logger : Jupyter logger [optional] Logger instance to use """ return _set_nbextension_state(section=section, require=require, state=False, user=user, sys_prefix=sys_prefix, logger=logger)
Disable a named nbextension Returns True if the final state is the one requested. Parameters ---------- section : string The section of the server to change, one of NBCONFIG_SECTIONS require : string An importable AMD module inside the nbextensions static path user : bool [default: True] Whether to enable in the user's nbextensions directory. sys_prefix : bool [default: False] Whether to enable in the sys.prefix, i.e. environment. Will override `user`. logger : Jupyter logger [optional] Logger instance to use
170,485
import os import shutil import sys import tarfile import zipfile from os.path import basename, join as pjoin, normpath from urllib.parse import urlparse from urllib.request import urlretrieve from jupyter_core.paths import ( jupyter_data_dir, jupyter_config_path, jupyter_path, SYSTEM_JUPYTER_PATH, ENV_JUPYTER_PATH, ) from jupyter_core.utils import ensure_dir_exists from ipython_genutils.py3compat import string_types, cast_unicode_py2 from ipython_genutils.tempdir import TemporaryDirectory from ._version import __version__ from .config_manager import BaseJSONConfigManager from traitlets.utils.importstring import import_item from .extensions import ( BaseExtensionApp, _get_config_dir, GREEN_ENABLED, RED_DISABLED, GREEN_OK, RED_X, ArgumentConflict, _base_aliases, _base_flags, ) from traitlets import Bool, Unicode import os del os def jupyter_config_path() -> List[str]: """Return the search path for Jupyter config files as a list. If the JUPYTER_PREFER_ENV_PATH environment variable is set, the environment-level directories will have priority over user-level directories. If the Python site.ENABLE_USER_SITE variable is True, we also add the appropriate Python user site subdirectory to the user-level directories. """ if os.environ.get("JUPYTER_NO_CONFIG"): # jupyter_config_dir makes a blank config when JUPYTER_NO_CONFIG is set. return [jupyter_config_dir()] paths: List[str] = [] # highest priority is explicit environment variable if os.environ.get("JUPYTER_CONFIG_PATH"): paths.extend(p.rstrip(os.sep) for p in os.environ["JUPYTER_CONFIG_PATH"].split(os.pathsep)) # Next is environment or user, depending on the JUPYTER_PREFER_ENV_PATH flag user = [jupyter_config_dir()] if site.ENABLE_USER_SITE: userbase: Optional[str] # Check if site.getuserbase() exists to be compatible with virtualenv, # which often does not have this method. userbase = site.getuserbase() if hasattr(site, "getuserbase") else site.USER_BASE if userbase: userdir = os.path.join(userbase, "etc", "jupyter") if userdir not in user: user.append(userdir) env = [p for p in ENV_CONFIG_PATH if p not in SYSTEM_CONFIG_PATH] if prefer_environment_over_user(): paths.extend(env) paths.extend(user) else: paths.extend(user) paths.extend(env) # Finally, system path paths.extend(SYSTEM_CONFIG_PATH) return paths class BaseJSONConfigManager(LoggingConfigurable): """General JSON config manager Deals with persisting/storing config in a json file with optionally default values in a {section_name}.d directory. """ config_dir = Unicode('.') read_directory = Bool(True) def ensure_config_dir_exists(self): """Will try to create the config_dir directory.""" try: os.makedirs(self.config_dir, 0o755) except OSError as e: if e.errno != errno.EEXIST: raise def file_name(self, section_name): """Returns the json filename for the section_name: {config_dir}/{section_name}.json""" return os.path.join(self.config_dir, section_name+'.json') def directory(self, section_name): """Returns the directory name for the section name: {config_dir}/{section_name}.d""" return os.path.join(self.config_dir, section_name+'.d') def get(self, section_name, include_root=True): """Retrieve the config data for the specified section. Returns the data as a dictionary, or an empty dictionary if the file doesn't exist. When include_root is False, it will not read the root .json file, effectively returning the default values. """ paths = [self.file_name(section_name)] if include_root else [] if self.read_directory: pattern = os.path.join(self.directory(section_name), '*.json') # These json files should be processed first so that the # {section_name}.json take precedence. # The idea behind this is that installing a Python package may # put a json file somewhere in the a .d directory, while the # .json file is probably a user configuration. paths = sorted(glob.glob(pattern)) + paths self.log.debug('Paths used for configuration of %s: \n\t%s', section_name, '\n\t'.join(paths)) data = {} for path in paths: if os.path.isfile(path): with open(path, encoding='utf-8') as f: recursive_update(data, json.load(f)) return data def set(self, section_name, data): """Store the given config data. """ filename = self.file_name(section_name) self.ensure_config_dir_exists() if self.read_directory: # we will modify data in place, so make a copy data = copy.deepcopy(data) defaults = self.get(section_name, include_root=False) remove_defaults(data, defaults) # Generate the JSON up front, since it could raise an exception, # in order to avoid writing half-finished corrupted data to disk. json_content = json.dumps(data, indent=2) f = open(filename, 'w', encoding='utf-8') with f: f.write(json_content) def update(self, section_name, new_data): """Modify the config section by recursively updating it with new_data. Returns the modified config data as a dictionary. """ data = self.get(section_name) recursive_update(data, new_data) self.set(section_name, data) return data The provided code snippet includes necessary dependencies for implementing the `_find_disable_nbextension` function. Write a Python function `def _find_disable_nbextension(section, require, logger=None)` to solve the following problem: Disable an nbextension from the first config location where it is enabled. Returns True if it changed any config, False otherwise. Here is the function: def _find_disable_nbextension(section, require, logger=None): """Disable an nbextension from the first config location where it is enabled. Returns True if it changed any config, False otherwise. """ for config_dir in jupyter_config_path(): cm = BaseJSONConfigManager( config_dir=os.path.join(config_dir, 'nbconfig')) d = cm.get(section) if d.get('load_extensions', {}).get(require, None): if logger: logger.info("Disabling %s extension in %s", require, config_dir) cm.update(section, {'load_extensions': {require: None}}) return True return False
Disable an nbextension from the first config location where it is enabled. Returns True if it changed any config, False otherwise.
170,486
import os import shutil import sys import tarfile import zipfile from os.path import basename, join as pjoin, normpath from urllib.parse import urlparse from urllib.request import urlretrieve from jupyter_core.paths import ( jupyter_data_dir, jupyter_config_path, jupyter_path, SYSTEM_JUPYTER_PATH, ENV_JUPYTER_PATH, ) from jupyter_core.utils import ensure_dir_exists from ipython_genutils.py3compat import string_types, cast_unicode_py2 from ipython_genutils.tempdir import TemporaryDirectory from ._version import __version__ from .config_manager import BaseJSONConfigManager from traitlets.utils.importstring import import_item def _set_nbextension_state_python(state, module, user, sys_prefix, logger=None): """Enable or disable some nbextensions stored in a Python package Returns a list of whether the state was achieved (i.e. changed, or was already right) Parameters ---------- state : Bool Whether the extensions should be enabled module : str Importable Python module exposing the magic-named `_jupyter_nbextension_paths` function user : bool Whether to enable in the user's nbextensions directory. sys_prefix : bool Enable/disable in the sys.prefix, i.e. environment logger : Jupyter logger [optional] Logger instance to use """ m, nbexts = _get_nbextension_metadata(module) return [_set_nbextension_state(section=nbext["section"], require=nbext["require"], state=state, user=user, sys_prefix=sys_prefix, logger=logger) for nbext in nbexts] from .extensions import ( BaseExtensionApp, _get_config_dir, GREEN_ENABLED, RED_DISABLED, GREEN_OK, RED_X, ArgumentConflict, _base_aliases, _base_flags, ) from traitlets import Bool, Unicode The provided code snippet includes necessary dependencies for implementing the `enable_nbextension_python` function. Write a Python function `def enable_nbextension_python(module, user=True, sys_prefix=False, logger=None)` to solve the following problem: Enable some nbextensions associated with a Python module. Returns a list of whether the state was achieved (i.e. changed, or was already right) Parameters ---------- module : str Importable Python module exposing the magic-named `_jupyter_nbextension_paths` function user : bool [default: True] Whether to enable in the user's nbextensions directory. sys_prefix : bool [default: False] Whether to enable in the sys.prefix, i.e. environment. Will override `user` logger : Jupyter logger [optional] Logger instance to use Here is the function: def enable_nbextension_python(module, user=True, sys_prefix=False, logger=None): """Enable some nbextensions associated with a Python module. Returns a list of whether the state was achieved (i.e. changed, or was already right) Parameters ---------- module : str Importable Python module exposing the magic-named `_jupyter_nbextension_paths` function user : bool [default: True] Whether to enable in the user's nbextensions directory. sys_prefix : bool [default: False] Whether to enable in the sys.prefix, i.e. environment. Will override `user` logger : Jupyter logger [optional] Logger instance to use """ return _set_nbextension_state_python(True, module, user, sys_prefix, logger=logger)
Enable some nbextensions associated with a Python module. Returns a list of whether the state was achieved (i.e. changed, or was already right) Parameters ---------- module : str Importable Python module exposing the magic-named `_jupyter_nbextension_paths` function user : bool [default: True] Whether to enable in the user's nbextensions directory. sys_prefix : bool [default: False] Whether to enable in the sys.prefix, i.e. environment. Will override `user` logger : Jupyter logger [optional] Logger instance to use
170,487
import os import shutil import sys import tarfile import zipfile from os.path import basename, join as pjoin, normpath from urllib.parse import urlparse from urllib.request import urlretrieve from jupyter_core.paths import ( jupyter_data_dir, jupyter_config_path, jupyter_path, SYSTEM_JUPYTER_PATH, ENV_JUPYTER_PATH, ) from jupyter_core.utils import ensure_dir_exists from ipython_genutils.py3compat import string_types, cast_unicode_py2 from ipython_genutils.tempdir import TemporaryDirectory from ._version import __version__ from .config_manager import BaseJSONConfigManager from traitlets.utils.importstring import import_item def _set_nbextension_state_python(state, module, user, sys_prefix, logger=None): """Enable or disable some nbextensions stored in a Python package Returns a list of whether the state was achieved (i.e. changed, or was already right) Parameters ---------- state : Bool Whether the extensions should be enabled module : str Importable Python module exposing the magic-named `_jupyter_nbextension_paths` function user : bool Whether to enable in the user's nbextensions directory. sys_prefix : bool Enable/disable in the sys.prefix, i.e. environment logger : Jupyter logger [optional] Logger instance to use """ m, nbexts = _get_nbextension_metadata(module) return [_set_nbextension_state(section=nbext["section"], require=nbext["require"], state=state, user=user, sys_prefix=sys_prefix, logger=logger) for nbext in nbexts] from .extensions import ( BaseExtensionApp, _get_config_dir, GREEN_ENABLED, RED_DISABLED, GREEN_OK, RED_X, ArgumentConflict, _base_aliases, _base_flags, ) from traitlets import Bool, Unicode The provided code snippet includes necessary dependencies for implementing the `disable_nbextension_python` function. Write a Python function `def disable_nbextension_python(module, user=True, sys_prefix=False, logger=None)` to solve the following problem: Disable some nbextensions associated with a Python module. Returns True if the final state is the one requested. Parameters ---------- module : str Importable Python module exposing the magic-named `_jupyter_nbextension_paths` function user : bool [default: True] Whether to enable in the user's nbextensions directory. sys_prefix : bool [default: False] Whether to enable in the sys.prefix, i.e. environment logger : Jupyter logger [optional] Logger instance to use Here is the function: def disable_nbextension_python(module, user=True, sys_prefix=False, logger=None): """Disable some nbextensions associated with a Python module. Returns True if the final state is the one requested. Parameters ---------- module : str Importable Python module exposing the magic-named `_jupyter_nbextension_paths` function user : bool [default: True] Whether to enable in the user's nbextensions directory. sys_prefix : bool [default: False] Whether to enable in the sys.prefix, i.e. environment logger : Jupyter logger [optional] Logger instance to use """ return _set_nbextension_state_python(False, module, user, sys_prefix, logger=logger)
Disable some nbextensions associated with a Python module. Returns True if the final state is the one requested. Parameters ---------- module : str Importable Python module exposing the magic-named `_jupyter_nbextension_paths` function user : bool [default: True] Whether to enable in the user's nbextensions directory. sys_prefix : bool [default: False] Whether to enable in the sys.prefix, i.e. environment logger : Jupyter logger [optional] Logger instance to use
170,488
import sys if PY3: from functools import wraps else: from functools import wraps as _wraps def wraps(f): def dec(func): _wraps(f)(func) func.__wrapped__ = f return func return dec def signature(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: ... def signature(obj): '''Get a signature object for the passed callable.''' if not callable(obj): raise TypeError('{0!r} is not a callable object'.format(obj)) if isinstance(obj, types.MethodType): # In this case we skip the first parameter of the underlying # function (usually `self` or `cls`). sig = signature(obj.__func__) return sig.replace(parameters=tuple(sig.parameters.values())[1:]) try: sig = obj.__signature__ except AttributeError: pass else: if sig is not None: return sig try: # Was this function wrapped by a decorator? wrapped = obj.__wrapped__ except AttributeError: pass else: return signature(wrapped) if isinstance(obj, types.FunctionType): return Signature.from_function(obj) if isinstance(obj, functools.partial): sig = signature(obj.func) new_params = OrderedDict(sig.parameters.items()) partial_args = obj.args or () partial_keywords = obj.keywords or {} try: ba = sig.bind_partial(*partial_args, **partial_keywords) except TypeError as ex: msg = 'partial object {0!r} has incorrect arguments'.format(obj) raise ValueError(msg) for arg_name, arg_value in ba.arguments.items(): param = new_params[arg_name] if arg_name in partial_keywords: # We set a new default value, because the following code # is correct: # # >>> def foo(a): print(a) # >>> print(partial(partial(foo, a=10), a=20)()) # 20 # >>> print(partial(partial(foo, a=10), a=20)(a=30)) # 30 # # So, with 'partial' objects, passing a keyword argument is # like setting a new default value for the corresponding # parameter # # We also mark this parameter with '_partial_kwarg' # flag. Later, in '_bind', the 'default' value of this # parameter will be added to 'kwargs', to simulate # the 'functools.partial' real call. new_params[arg_name] = param.replace(default=arg_value, _partial_kwarg=True) elif (param.kind not in (_VAR_KEYWORD, _VAR_POSITIONAL) and not param._partial_kwarg): new_params.pop(arg_name) return sig.replace(parameters=new_params.values()) sig = None if isinstance(obj, type): # obj is a class or a metaclass # First, let's see if it has an overloaded __call__ defined # in its metaclass call = _get_user_defined_method(type(obj), '__call__') if call is not None: sig = signature(call) else: # Now we check if the 'obj' class has a '__new__' method new = _get_user_defined_method(obj, '__new__') if new is not None: sig = signature(new) else: # Finally, we should have at least __init__ implemented init = _get_user_defined_method(obj, '__init__') if init is not None: sig = signature(init) elif not isinstance(obj, _NonUserDefinedCallables): # An object with __call__ # We also check that the 'obj' is not an instance of # _WrapperDescriptor or _MethodWrapper to avoid # infinite recursion (and even potential segfault) call = _get_user_defined_method(type(obj), '__call__', 'im_func') if call is not None: sig = signature(call) if sig is not None: return sig if isinstance(obj, types.BuiltinFunctionType): # Raise a nicer error message for builtins msg = 'no signature found for builtin function {0!r}'.format(obj) raise ValueError(msg) raise ValueError('callable {0!r} is not supported by signature'.format(obj)) class Parameter(object): '''Represents a parameter in a function signature. Has the following public attributes: * name : str The name of the parameter as a string. * default : object The default value for the parameter if specified. If the parameter has no default value, this attribute is not set. * annotation The annotation for the parameter if specified. If the parameter has no annotation, this attribute is not set. * kind : str Describes how argument values are bound to the parameter. Possible values: `Parameter.POSITIONAL_ONLY`, `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`, `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`. ''' __slots__ = ('_name', '_kind', '_default', '_annotation', '_partial_kwarg') POSITIONAL_ONLY = _POSITIONAL_ONLY POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD VAR_POSITIONAL = _VAR_POSITIONAL KEYWORD_ONLY = _KEYWORD_ONLY VAR_KEYWORD = _VAR_KEYWORD empty = _empty def __init__(self, name, kind, default=_empty, annotation=_empty, _partial_kwarg=False): if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD, _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD): raise ValueError("invalid value for 'Parameter.kind' attribute") self._kind = kind if default is not _empty: if kind in (_VAR_POSITIONAL, _VAR_KEYWORD): msg = '{0} parameters cannot have default values'.format(kind) raise ValueError(msg) self._default = default self._annotation = annotation if name is None: if kind != _POSITIONAL_ONLY: raise ValueError("None is not a valid name for a " "non-positional-only parameter") self._name = name else: name = str(name) if kind != _POSITIONAL_ONLY and not re.match(r'[a-z_]\w*$', name, re.I): msg = '{0!r} is not a valid parameter name'.format(name) raise ValueError(msg) self._name = name self._partial_kwarg = _partial_kwarg def name(self): return self._name def default(self): return self._default def annotation(self): return self._annotation def kind(self): return self._kind def replace(self, name=_void, kind=_void, annotation=_void, default=_void, _partial_kwarg=_void): '''Creates a customized copy of the Parameter.''' if name is _void: name = self._name if kind is _void: kind = self._kind if annotation is _void: annotation = self._annotation if default is _void: default = self._default if _partial_kwarg is _void: _partial_kwarg = self._partial_kwarg return type(self)(name, kind, default=default, annotation=annotation, _partial_kwarg=_partial_kwarg) def __str__(self): kind = self.kind formatted = self._name if kind == _POSITIONAL_ONLY: if formatted is None: formatted = '' formatted = '<{0}>'.format(formatted) # Add annotation and default value if self._annotation is not _empty: formatted = '{0}:{1}'.format(formatted, formatannotation(self._annotation)) if self._default is not _empty: formatted = '{0}={1}'.format(formatted, repr(self._default)) if kind == _VAR_POSITIONAL: formatted = '*' + formatted elif kind == _VAR_KEYWORD: formatted = '**' + formatted return formatted def __repr__(self): return '<{0} at {1:#x} {2!r}>'.format(self.__class__.__name__, id(self), self.name) def __hash__(self): msg = "unhashable type: '{0}'".format(self.__class__.__name__) raise TypeError(msg) def __eq__(self, other): return (issubclass(other.__class__, Parameter) and self._name == other._name and self._kind == other._kind and self._default == other._default and self._annotation == other._annotation) def __ne__(self, other): return not self.__eq__(other) def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> Callable[[_T], _T]: ... The provided code snippet includes necessary dependencies for implementing the `callback_prototype` function. Write a Python function `def callback_prototype(prototype)` to solve the following problem: Decorator to process a callback prototype. A callback prototype is a function whose signature includes all the values that will be passed by the callback API in question. The original function will be returned, with a ``prototype.adapt`` attribute which can be used to prepare third party callbacks. Here is the function: def callback_prototype(prototype): """Decorator to process a callback prototype. A callback prototype is a function whose signature includes all the values that will be passed by the callback API in question. The original function will be returned, with a ``prototype.adapt`` attribute which can be used to prepare third party callbacks. """ protosig = signature(prototype) positional, keyword = [], [] for name, param in protosig.parameters.items(): if param.kind in (Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD): raise TypeError("*args/**kwargs not supported in prototypes") if (param.default is not Parameter.empty) \ or (param.kind == Parameter.KEYWORD_ONLY): keyword.append(name) else: positional.append(name) kwargs = dict.fromkeys(keyword) def adapt(callback): """Introspect and prepare a third party callback.""" sig = signature(callback) try: # XXX: callback can have extra optional parameters - OK? sig.bind(*positional, **kwargs) return callback except TypeError: pass # Match up arguments unmatched_pos = positional[:] unmatched_kw = kwargs.copy() unrecognised = [] # TODO: unrecognised parameters with default values - OK? for name, param in sig.parameters.items(): # print(name, param.kind) #DBG if param.kind == Parameter.POSITIONAL_ONLY: if len(unmatched_pos) > 0: unmatched_pos.pop(0) else: unrecognised.append(name) elif param.kind == Parameter.POSITIONAL_OR_KEYWORD: if (param.default is not Parameter.empty) and (name in unmatched_kw): unmatched_kw.pop(name) elif len(unmatched_pos) > 0: unmatched_pos.pop(0) else: unrecognised.append(name) elif param.kind == Parameter.VAR_POSITIONAL: unmatched_pos = [] elif param.kind == Parameter.KEYWORD_ONLY: if name in unmatched_kw: unmatched_kw.pop(name) else: unrecognised.append(name) else: # VAR_KEYWORD unmatched_kw = {} # print(unmatched_pos, unmatched_kw, unrecognised) #DBG if unrecognised: raise TypeError("Function {!r} had unmatched arguments: {}".format(callback, unrecognised)) n_positional = len(positional) - len(unmatched_pos) @wraps(callback) def adapted(*args, **kwargs): """Wrapper for third party callbacks that discards excess arguments""" # print(args, kwargs) args = args[:n_positional] for name in unmatched_kw: # XXX: Could name not be in kwargs? kwargs.pop(name) # print(args, kwargs, unmatched_pos, cut_positional, unmatched_kw) return callback(*args, **kwargs) return adapted prototype.adapt = adapt return prototype
Decorator to process a callback prototype. A callback prototype is a function whose signature includes all the values that will be passed by the callback API in question. The original function will be returned, with a ``prototype.adapt`` attribute which can be used to prepare third party callbacks.
170,489
from __future__ import absolute_import, division, print_function import itertools import functools import re import types from collections import OrderedDict def formatannotation(annotation, base_module=None): if isinstance(annotation, type): if annotation.__module__ in ('builtins', '__builtin__', base_module): return annotation.__name__ return annotation.__module__+'.'+annotation.__name__ return repr(annotation)
null
170,490
from contextvars import ContextVar from typing import Optional import sys import threading current_async_library_cvar = ContextVar( "current_async_library_cvar", default=None ) thread_local = _ThreadLocal() class AsyncLibraryNotFoundError(RuntimeError): pass The provided code snippet includes necessary dependencies for implementing the `current_async_library` function. Write a Python function `def current_async_library() -> str` to solve the following problem: Detect which async library is currently running. The following libraries are currently supported: ================ =========== ============================ Library Requires Magic string ================ =========== ============================ **Trio** Trio v0.6+ ``"trio"`` **Curio** - ``"curio"`` **asyncio** ``"asyncio"`` **Trio-asyncio** v0.8.2+ ``"trio"`` or ``"asyncio"``, depending on current mode ================ =========== ============================ Returns: A string like ``"trio"``. Raises: AsyncLibraryNotFoundError: if called from synchronous context, or if the current async library was not recognized. Examples: .. code-block:: python3 from sniffio import current_async_library async def generic_sleep(seconds): library = current_async_library() if library == "trio": import trio await trio.sleep(seconds) elif library == "asyncio": import asyncio await asyncio.sleep(seconds) # ... and so on ... else: raise RuntimeError(f"Unsupported library {library!r}") Here is the function: def current_async_library() -> str: """Detect which async library is currently running. The following libraries are currently supported: ================ =========== ============================ Library Requires Magic string ================ =========== ============================ **Trio** Trio v0.6+ ``"trio"`` **Curio** - ``"curio"`` **asyncio** ``"asyncio"`` **Trio-asyncio** v0.8.2+ ``"trio"`` or ``"asyncio"``, depending on current mode ================ =========== ============================ Returns: A string like ``"trio"``. Raises: AsyncLibraryNotFoundError: if called from synchronous context, or if the current async library was not recognized. Examples: .. code-block:: python3 from sniffio import current_async_library async def generic_sleep(seconds): library = current_async_library() if library == "trio": import trio await trio.sleep(seconds) elif library == "asyncio": import asyncio await asyncio.sleep(seconds) # ... and so on ... else: raise RuntimeError(f"Unsupported library {library!r}") """ value = thread_local.name if value is not None: return value value = current_async_library_cvar.get() if value is not None: return value # Need to sniff for asyncio if "asyncio" in sys.modules: import asyncio try: current_task = asyncio.current_task # type: ignore[attr-defined] except AttributeError: current_task = asyncio.Task.current_task # type: ignore[attr-defined] try: if current_task() is not None: return "asyncio" except RuntimeError: pass # Sniff for curio (for now) if 'curio' in sys.modules: from curio.meta import curio_running if curio_running(): return 'curio' raise AsyncLibraryNotFoundError( "unknown async library, or not in async context" )
Detect which async library is currently running. The following libraries are currently supported: ================ =========== ============================ Library Requires Magic string ================ =========== ============================ **Trio** Trio v0.6+ ``"trio"`` **Curio** - ``"curio"`` **asyncio** ``"asyncio"`` **Trio-asyncio** v0.8.2+ ``"trio"`` or ``"asyncio"``, depending on current mode ================ =========== ============================ Returns: A string like ``"trio"``. Raises: AsyncLibraryNotFoundError: if called from synchronous context, or if the current async library was not recognized. Examples: .. code-block:: python3 from sniffio import current_async_library async def generic_sleep(seconds): library = current_async_library() if library == "trio": import trio await trio.sleep(seconds) elif library == "asyncio": import asyncio await asyncio.sleep(seconds) # ... and so on ... else: raise RuntimeError(f"Unsupported library {library!r}")
170,491
import os import pprint from twython import Twython def credsfromfile(creds_file=None, subdir=None, verbose=False): """ Convenience function for authentication """ return Authenticate().load_creds( creds_file=creds_file, subdir=subdir, verbose=verbose ) The provided code snippet includes necessary dependencies for implementing the `add_access_token` function. Write a Python function `def add_access_token(creds_file=None)` to solve the following problem: For OAuth 2, retrieve an access token for an app and append it to a credentials file. Here is the function: def add_access_token(creds_file=None): """ For OAuth 2, retrieve an access token for an app and append it to a credentials file. """ if creds_file is None: path = os.path.dirname(__file__) creds_file = os.path.join(path, "credentials2.txt") oauth2 = credsfromfile(creds_file=creds_file) app_key = oauth2["app_key"] app_secret = oauth2["app_secret"] twitter = Twython(app_key, app_secret, oauth_version=2) access_token = twitter.obtain_access_token() tok = f"access_token={access_token}\n" with open(creds_file, "a") as infile: print(tok, file=infile)
For OAuth 2, retrieve an access token for an app and append it to a credentials file.
170,492
import os import pprint from twython import Twython The provided code snippet includes necessary dependencies for implementing the `guess_path` function. Write a Python function `def guess_path(pth)` to solve the following problem: If the path is not absolute, guess that it is a subdirectory of the user's home directory. :param str pth: The pathname of the directory where files of tweets should be written Here is the function: def guess_path(pth): """ If the path is not absolute, guess that it is a subdirectory of the user's home directory. :param str pth: The pathname of the directory where files of tweets should be written """ if os.path.isabs(pth): return pth else: return os.path.expanduser(os.path.join("~", pth))
If the path is not absolute, guess that it is a subdirectory of the user's home directory. :param str pth: The pathname of the directory where files of tweets should be written
170,493
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) SPACER = "###################################" def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> Callable[[_T], _T]: ... The provided code snippet includes necessary dependencies for implementing the `verbose` function. Write a Python function `def verbose(func)` to solve the following problem: Decorator for demo functions Here is the function: def verbose(func): """Decorator for demo functions""" @wraps(func) def with_formatting(*args, **kwargs): print() print(SPACER) print("Using %s" % (func.__name__)) print(SPACER) return func(*args, **kwargs) return with_formatting
Decorator for demo functions
170,494
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) The provided code snippet includes necessary dependencies for implementing the `setup` function. Write a Python function `def setup()` to solve the following problem: Initialize global variables for the demos. Here is the function: def setup(): """ Initialize global variables for the demos. """ global USERIDS, FIELDS USERIDS = ["759251", "612473", "15108702", "6017542", "2673523800"] # UserIDs corresponding to\ # @CNN, @BBCNews, @ReutersLive, @BreakingNews, @AJELive FIELDS = ["id_str"]
Initialize global variables for the demos.
170,495
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) SPACER = "###################################" The provided code snippet includes necessary dependencies for implementing the `twitterclass_demo` function. Write a Python function `def twitterclass_demo()` to solve the following problem: Use the simplified :class:`Twitter` class to write some tweets to a file. Here is the function: def twitterclass_demo(): """ Use the simplified :class:`Twitter` class to write some tweets to a file. """ tw = Twitter() print("Track from the public stream\n") tw.tweets(keywords="love, hate", limit=10) # public stream print(SPACER) print("Search past Tweets\n") tw = Twitter() tw.tweets(keywords="love, hate", stream=False, limit=10) # search past tweets print(SPACER) print( "Follow two accounts in the public stream" + " -- be prepared to wait a few minutes\n" ) tw = Twitter() tw.tweets(follow=["759251", "6017542"], stream=True, limit=5) # public stream
Use the simplified :class:`Twitter` class to write some tweets to a file.
170,496
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) The provided code snippet includes necessary dependencies for implementing the `sampletoscreen_demo` function. Write a Python function `def sampletoscreen_demo(limit=20)` to solve the following problem: Sample from the Streaming API and send output to terminal. Here is the function: def sampletoscreen_demo(limit=20): """ Sample from the Streaming API and send output to terminal. """ oauth = credsfromfile() client = Streamer(**oauth) client.register(TweetViewer(limit=limit)) client.sample()
Sample from the Streaming API and send output to terminal.
170,497
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) The provided code snippet includes necessary dependencies for implementing the `tracktoscreen_demo` function. Write a Python function `def tracktoscreen_demo(track="taylor swift", limit=10)` to solve the following problem: Track keywords from the public Streaming API and send output to terminal. Here is the function: def tracktoscreen_demo(track="taylor swift", limit=10): """ Track keywords from the public Streaming API and send output to terminal. """ oauth = credsfromfile() client = Streamer(**oauth) client.register(TweetViewer(limit=limit)) client.filter(track=track)
Track keywords from the public Streaming API and send output to terminal.
170,498
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) The provided code snippet includes necessary dependencies for implementing the `search_demo` function. Write a Python function `def search_demo(keywords="nltk")` to solve the following problem: Use the REST API to search for past tweets containing a given keyword. Here is the function: def search_demo(keywords="nltk"): """ Use the REST API to search for past tweets containing a given keyword. """ oauth = credsfromfile() client = Query(**oauth) for tweet in client.search_tweets(keywords=keywords, limit=10): print(tweet["text"])
Use the REST API to search for past tweets containing a given keyword.
170,499
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) The provided code snippet includes necessary dependencies for implementing the `tweets_by_user_demo` function. Write a Python function `def tweets_by_user_demo(user="NLTK_org", count=200)` to solve the following problem: Use the REST API to search for past tweets by a given user. Here is the function: def tweets_by_user_demo(user="NLTK_org", count=200): """ Use the REST API to search for past tweets by a given user. """ oauth = credsfromfile() client = Query(**oauth) client.register(TweetWriter()) client.user_tweets(user, count)
Use the REST API to search for past tweets by a given user.
170,500
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) The provided code snippet includes necessary dependencies for implementing the `lookup_by_userid_demo` function. Write a Python function `def lookup_by_userid_demo()` to solve the following problem: Use the REST API to convert a userID to a screen name. Here is the function: def lookup_by_userid_demo(): """ Use the REST API to convert a userID to a screen name. """ oauth = credsfromfile() client = Query(**oauth) user_info = client.user_info_from_id(USERIDS) for info in user_info: name = info["screen_name"] followers = info["followers_count"] following = info["friends_count"] print(f"{name}, followers: {followers}, following: {following}")
Use the REST API to convert a userID to a screen name.
170,501
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) The provided code snippet includes necessary dependencies for implementing the `followtoscreen_demo` function. Write a Python function `def followtoscreen_demo(limit=10)` to solve the following problem: Using the Streaming API, select just the tweets from a specified list of userIDs. This is will only give results in a reasonable time if the users in question produce a high volume of tweets, and may even so show some delay. Here is the function: def followtoscreen_demo(limit=10): """ Using the Streaming API, select just the tweets from a specified list of userIDs. This is will only give results in a reasonable time if the users in question produce a high volume of tweets, and may even so show some delay. """ oauth = credsfromfile() client = Streamer(**oauth) client.register(TweetViewer(limit=limit)) client.statuses.filter(follow=USERIDS)
Using the Streaming API, select just the tweets from a specified list of userIDs. This is will only give results in a reasonable time if the users in question produce a high volume of tweets, and may even so show some delay.
170,502
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) The provided code snippet includes necessary dependencies for implementing the `streamtofile_demo` function. Write a Python function `def streamtofile_demo(limit=20)` to solve the following problem: Write 20 tweets sampled from the public Streaming API to a file. Here is the function: def streamtofile_demo(limit=20): """ Write 20 tweets sampled from the public Streaming API to a file. """ oauth = credsfromfile() client = Streamer(**oauth) client.register(TweetWriter(limit=limit, repeat=False)) client.statuses.sample()
Write 20 tweets sampled from the public Streaming API to a file.
170,503
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) def yesterday(): """ Get yesterday's datetime as a 5-tuple. """ date = datetime.datetime.now() date -= datetime.timedelta(days=1) date_tuple = date.timetuple()[:6] return date_tuple The provided code snippet includes necessary dependencies for implementing the `limit_by_time_demo` function. Write a Python function `def limit_by_time_demo(keywords="nltk")` to solve the following problem: Query the REST API for Tweets about NLTK since yesterday and send the output to terminal. This example makes the assumption that there are sufficient Tweets since yesterday for the date to be an effective cut-off. Here is the function: def limit_by_time_demo(keywords="nltk"): """ Query the REST API for Tweets about NLTK since yesterday and send the output to terminal. This example makes the assumption that there are sufficient Tweets since yesterday for the date to be an effective cut-off. """ date = yesterday() dt_date = datetime.datetime(*date) oauth = credsfromfile() client = Query(**oauth) client.register(TweetViewer(limit=100, lower_date_limit=date)) print(f"Cutoff date: {dt_date}\n") for tweet in client.search_tweets(keywords=keywords): print("{} ".format(tweet["created_at"]), end="") client.handler.handle(tweet)
Query the REST API for Tweets about NLTK since yesterday and send the output to terminal. This example makes the assumption that there are sufficient Tweets since yesterday for the date to be an effective cut-off.
170,504
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) SPACER = "###################################" twitter_samples: TwitterCorpusReader = LazyCorpusLoader( "twitter_samples", TwitterCorpusReader, r".*\.json" ) The provided code snippet includes necessary dependencies for implementing the `corpusreader_demo` function. Write a Python function `def corpusreader_demo()` to solve the following problem: Use `TwitterCorpusReader` tp read a file of tweets, and print out * some full tweets in JSON format; * some raw strings from the tweets (i.e., the value of the `text` field); and * the result of tokenising the raw strings. Here is the function: def corpusreader_demo(): """ Use `TwitterCorpusReader` tp read a file of tweets, and print out * some full tweets in JSON format; * some raw strings from the tweets (i.e., the value of the `text` field); and * the result of tokenising the raw strings. """ from nltk.corpus import twitter_samples as tweets print() print("Complete tweet documents") print(SPACER) for tweet in tweets.docs("tweets.20150430-223406.json")[:1]: print(json.dumps(tweet, indent=1, sort_keys=True)) print() print("Raw tweet strings:") print(SPACER) for text in tweets.strings("tweets.20150430-223406.json")[:15]: print(text) print() print("Tokenized tweet strings:") print(SPACER) for toks in tweets.tokenized("tweets.20150430-223406.json")[:15]: print(toks)
Use `TwitterCorpusReader` tp read a file of tweets, and print out * some full tweets in JSON format; * some raw strings from the tweets (i.e., the value of the `text` field); and * the result of tokenising the raw strings.
170,505
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) class StringIO(TextIOWrapper): def __init__(self, initial_value: Optional[str] = ..., newline: Optional[str] = ...) -> None: ... # StringIO does not contain a "name" field. This workaround is necessary # to allow StringIO sub-classes to add this field, as it is defined # as a read-only property on IO[]. name: Any def getvalue(self) -> str: ... The provided code snippet includes necessary dependencies for implementing the `expand_tweetids_demo` function. Write a Python function `def expand_tweetids_demo()` to solve the following problem: Given a file object containing a list of Tweet IDs, fetch the corresponding full Tweets, if available. Here is the function: def expand_tweetids_demo(): """ Given a file object containing a list of Tweet IDs, fetch the corresponding full Tweets, if available. """ ids_f = StringIO( """\ 588665495492124672 588665495487909888 588665495508766721 588665495513006080 588665495517200384 588665495487811584 588665495525588992 588665495487844352 588665495492014081 588665495512948737""" ) oauth = credsfromfile() client = Query(**oauth) hydrated = client.expand_tweetids(ids_f) for tweet in hydrated: id_str = tweet["id_str"] print(f"id: {id_str}") text = tweet["text"] if text.startswith("@null"): text = "[Tweet not available]" print(text + "\n")
Given a file object containing a list of Tweet IDs, fetch the corresponding full Tweets, if available.
170,506
import csv import gzip import json from nltk.internals import deprecated def extract_fields(tweet, fields): """ Extract field values from a full tweet and return them as a list :param json tweet: The tweet in JSON format :param list fields: The fields to be extracted from the tweet :rtype: list(str) """ out = [] for field in fields: try: _add_field_to_out(tweet, field, out) except TypeError as e: raise RuntimeError( "Fatal error when extracting fields. Cannot find field ", field ) from e return out def _outf_writer(outfile, encoding, errors, gzip_compress=False): if gzip_compress: outf = gzip.open(outfile, "wt", newline="", encoding=encoding, errors=errors) else: outf = open(outfile, "w", newline="", encoding=encoding, errors=errors) writer = csv.writer(outf) return (writer, outf) The provided code snippet includes necessary dependencies for implementing the `json2csv` function. Write a Python function `def json2csv( fp, outfile, fields, encoding="utf8", errors="replace", gzip_compress=False )` to solve the following problem: Extract selected fields from a file of line-separated JSON tweets and write to a file in CSV format. This utility function allows a file of full tweets to be easily converted to a CSV file for easier processing. For example, just TweetIDs or just the text content of the Tweets can be extracted. Additionally, the function allows combinations of fields of other Twitter objects (mainly the users, see below). For Twitter entities (e.g. hashtags of a Tweet), and for geolocation, see `json2csv_entities` :param str infile: The name of the file containing full tweets :param str outfile: The name of the text file where results should be\ written :param list fields: The list of fields to be extracted. Useful examples\ are 'id_str' for the tweetID and 'text' for the text of the tweet. See\ <https://dev.twitter.com/overview/api/tweets> for a full list of fields.\ e. g.: ['id_str'], ['id', 'text', 'favorite_count', 'retweet_count']\ Additionally, it allows IDs from other Twitter objects, e. g.,\ ['id', 'text', 'user.id', 'user.followers_count', 'user.friends_count'] :param error: Behaviour for encoding errors, see\ https://docs.python.org/3/library/codecs.html#codec-base-classes :param gzip_compress: if `True`, output files are compressed with gzip Here is the function: def json2csv( fp, outfile, fields, encoding="utf8", errors="replace", gzip_compress=False ): """ Extract selected fields from a file of line-separated JSON tweets and write to a file in CSV format. This utility function allows a file of full tweets to be easily converted to a CSV file for easier processing. For example, just TweetIDs or just the text content of the Tweets can be extracted. Additionally, the function allows combinations of fields of other Twitter objects (mainly the users, see below). For Twitter entities (e.g. hashtags of a Tweet), and for geolocation, see `json2csv_entities` :param str infile: The name of the file containing full tweets :param str outfile: The name of the text file where results should be\ written :param list fields: The list of fields to be extracted. Useful examples\ are 'id_str' for the tweetID and 'text' for the text of the tweet. See\ <https://dev.twitter.com/overview/api/tweets> for a full list of fields.\ e. g.: ['id_str'], ['id', 'text', 'favorite_count', 'retweet_count']\ Additionally, it allows IDs from other Twitter objects, e. g.,\ ['id', 'text', 'user.id', 'user.followers_count', 'user.friends_count'] :param error: Behaviour for encoding errors, see\ https://docs.python.org/3/library/codecs.html#codec-base-classes :param gzip_compress: if `True`, output files are compressed with gzip """ (writer, outf) = _outf_writer(outfile, encoding, errors, gzip_compress) # write the list of fields as header writer.writerow(fields) # process the file for line in fp: tweet = json.loads(line) row = extract_fields(tweet, fields) writer.writerow(row) outf.close()
Extract selected fields from a file of line-separated JSON tweets and write to a file in CSV format. This utility function allows a file of full tweets to be easily converted to a CSV file for easier processing. For example, just TweetIDs or just the text content of the Tweets can be extracted. Additionally, the function allows combinations of fields of other Twitter objects (mainly the users, see below). For Twitter entities (e.g. hashtags of a Tweet), and for geolocation, see `json2csv_entities` :param str infile: The name of the file containing full tweets :param str outfile: The name of the text file where results should be\ written :param list fields: The list of fields to be extracted. Useful examples\ are 'id_str' for the tweetID and 'text' for the text of the tweet. See\ <https://dev.twitter.com/overview/api/tweets> for a full list of fields.\ e. g.: ['id_str'], ['id', 'text', 'favorite_count', 'retweet_count']\ Additionally, it allows IDs from other Twitter objects, e. g.,\ ['id', 'text', 'user.id', 'user.followers_count', 'user.friends_count'] :param error: Behaviour for encoding errors, see\ https://docs.python.org/3/library/codecs.html#codec-base-classes :param gzip_compress: if `True`, output files are compressed with gzip
170,507
import csv import gzip import json from nltk.internals import deprecated def _outf_writer(outfile, encoding, errors, gzip_compress=False): if gzip_compress: outf = gzip.open(outfile, "wt", newline="", encoding=encoding, errors=errors) else: outf = open(outfile, "w", newline="", encoding=encoding, errors=errors) writer = csv.writer(outf) return (writer, outf) The provided code snippet includes necessary dependencies for implementing the `outf_writer_compat` function. Write a Python function `def outf_writer_compat(outfile, encoding, errors, gzip_compress=False)` to solve the following problem: Get a CSV writer with optional compression. Here is the function: def outf_writer_compat(outfile, encoding, errors, gzip_compress=False): """Get a CSV writer with optional compression.""" return _outf_writer(outfile, encoding, errors, gzip_compress)
Get a CSV writer with optional compression.
170,508
import csv import gzip import json from nltk.internals import deprecated def extract_fields(tweet, fields): """ Extract field values from a full tweet and return them as a list :param json tweet: The tweet in JSON format :param list fields: The fields to be extracted from the tweet :rtype: list(str) """ out = [] for field in fields: try: _add_field_to_out(tweet, field, out) except TypeError as e: raise RuntimeError( "Fatal error when extracting fields. Cannot find field ", field ) from e return out def _is_composed_key(field): return HIER_SEPARATOR in field def _get_key_value_composed(field): out = field.split(HIER_SEPARATOR) # there could be up to 3 levels key = out[0] value = HIER_SEPARATOR.join(out[1:]) return key, value def _get_entity_recursive(json, entity): if not json: return None elif isinstance(json, dict): for key, value in json.items(): if key == entity: return value # 'entities' and 'extended_entities' are wrappers in Twitter json # structure that contain other Twitter objects. See: # https://dev.twitter.com/overview/api/entities-in-twitter-objects if key == "entities" or key == "extended_entities": candidate = _get_entity_recursive(value, entity) if candidate is not None: return candidate return None elif isinstance(json, list): for item in json: candidate = _get_entity_recursive(item, entity) if candidate is not None: return candidate return None else: return None def _outf_writer(outfile, encoding, errors, gzip_compress=False): if gzip_compress: outf = gzip.open(outfile, "wt", newline="", encoding=encoding, errors=errors) else: outf = open(outfile, "w", newline="", encoding=encoding, errors=errors) writer = csv.writer(outf) return (writer, outf) def get_header_field_list(main_fields, entity_type, entity_fields): if _is_composed_key(entity_type): key, value = _get_key_value_composed(entity_type) main_entity = key sub_entity = value else: main_entity = None sub_entity = entity_type if main_entity: output1 = [HIER_SEPARATOR.join([main_entity, x]) for x in main_fields] else: output1 = main_fields output2 = [HIER_SEPARATOR.join([sub_entity, x]) for x in entity_fields] return output1 + output2 def _write_to_file(object_fields, items, entity_fields, writer): if not items: # it could be that the entity is just not present for the tweet # e.g. tweet hashtag is always present, even as [], however # tweet media may not be present return if isinstance(items, dict): # this happens e.g. for "place" of a tweet row = object_fields # there might be composed keys in de list of required fields entity_field_values = [x for x in entity_fields if not _is_composed_key(x)] entity_field_composed = [x for x in entity_fields if _is_composed_key(x)] for field in entity_field_values: value = items[field] if isinstance(value, list): row += value else: row += [value] # now check required dictionaries for d in entity_field_composed: kd, vd = _get_key_value_composed(d) json_dict = items[kd] if not isinstance(json_dict, dict): raise RuntimeError( """Key {} does not contain a dictionary in the json file""".format( kd ) ) row += [json_dict[vd]] writer.writerow(row) return # in general it is a list for item in items: row = object_fields + extract_fields(item, entity_fields) writer.writerow(row) The provided code snippet includes necessary dependencies for implementing the `json2csv_entities` function. Write a Python function `def json2csv_entities( tweets_file, outfile, main_fields, entity_type, entity_fields, encoding="utf8", errors="replace", gzip_compress=False, )` to solve the following problem: Extract selected fields from a file of line-separated JSON tweets and write to a file in CSV format. This utility function allows a file of full Tweets to be easily converted to a CSV file for easier processing of Twitter entities. For example, the hashtags or media elements of a tweet can be extracted. It returns one line per entity of a Tweet, e.g. if a tweet has two hashtags there will be two lines in the output file, one per hashtag :param tweets_file: the file-like object containing full Tweets :param str outfile: The path of the text file where results should be\ written :param list main_fields: The list of fields to be extracted from the main\ object, usually the tweet. Useful examples: 'id_str' for the tweetID. See\ <https://dev.twitter.com/overview/api/tweets> for a full list of fields. e. g.: ['id_str'], ['id', 'text', 'favorite_count', 'retweet_count'] If `entity_type` is expressed with hierarchy, then it is the list of\ fields of the object that corresponds to the key of the entity_type,\ (e.g., for entity_type='user.urls', the fields in the main_fields list\ belong to the user object; for entity_type='place.bounding_box', the\ files in the main_field list belong to the place object of the tweet). :param list entity_type: The name of the entity: 'hashtags', 'media',\ 'urls' and 'user_mentions' for the tweet object. For a user object,\ this needs to be expressed with a hierarchy: `'user.urls'`. For the\ bounding box of the Tweet location, use `'place.bounding_box'`. :param list entity_fields: The list of fields to be extracted from the\ entity. E.g. `['text']` (of the Tweet) :param error: Behaviour for encoding errors, see\ https://docs.python.org/3/library/codecs.html#codec-base-classes :param gzip_compress: if `True`, output files are compressed with gzip Here is the function: def json2csv_entities( tweets_file, outfile, main_fields, entity_type, entity_fields, encoding="utf8", errors="replace", gzip_compress=False, ): """ Extract selected fields from a file of line-separated JSON tweets and write to a file in CSV format. This utility function allows a file of full Tweets to be easily converted to a CSV file for easier processing of Twitter entities. For example, the hashtags or media elements of a tweet can be extracted. It returns one line per entity of a Tweet, e.g. if a tweet has two hashtags there will be two lines in the output file, one per hashtag :param tweets_file: the file-like object containing full Tweets :param str outfile: The path of the text file where results should be\ written :param list main_fields: The list of fields to be extracted from the main\ object, usually the tweet. Useful examples: 'id_str' for the tweetID. See\ <https://dev.twitter.com/overview/api/tweets> for a full list of fields. e. g.: ['id_str'], ['id', 'text', 'favorite_count', 'retweet_count'] If `entity_type` is expressed with hierarchy, then it is the list of\ fields of the object that corresponds to the key of the entity_type,\ (e.g., for entity_type='user.urls', the fields in the main_fields list\ belong to the user object; for entity_type='place.bounding_box', the\ files in the main_field list belong to the place object of the tweet). :param list entity_type: The name of the entity: 'hashtags', 'media',\ 'urls' and 'user_mentions' for the tweet object. For a user object,\ this needs to be expressed with a hierarchy: `'user.urls'`. For the\ bounding box of the Tweet location, use `'place.bounding_box'`. :param list entity_fields: The list of fields to be extracted from the\ entity. E.g. `['text']` (of the Tweet) :param error: Behaviour for encoding errors, see\ https://docs.python.org/3/library/codecs.html#codec-base-classes :param gzip_compress: if `True`, output files are compressed with gzip """ (writer, outf) = _outf_writer(outfile, encoding, errors, gzip_compress) header = get_header_field_list(main_fields, entity_type, entity_fields) writer.writerow(header) for line in tweets_file: tweet = json.loads(line) if _is_composed_key(entity_type): key, value = _get_key_value_composed(entity_type) object_json = _get_entity_recursive(tweet, key) if not object_json: # this can happen in the case of "place" continue object_fields = extract_fields(object_json, main_fields) items = _get_entity_recursive(object_json, value) _write_to_file(object_fields, items, entity_fields, writer) else: tweet_fields = extract_fields(tweet, main_fields) items = _get_entity_recursive(tweet, entity_type) _write_to_file(tweet_fields, items, entity_fields, writer) outf.close()
Extract selected fields from a file of line-separated JSON tweets and write to a file in CSV format. This utility function allows a file of full Tweets to be easily converted to a CSV file for easier processing of Twitter entities. For example, the hashtags or media elements of a tweet can be extracted. It returns one line per entity of a Tweet, e.g. if a tweet has two hashtags there will be two lines in the output file, one per hashtag :param tweets_file: the file-like object containing full Tweets :param str outfile: The path of the text file where results should be\ written :param list main_fields: The list of fields to be extracted from the main\ object, usually the tweet. Useful examples: 'id_str' for the tweetID. See\ <https://dev.twitter.com/overview/api/tweets> for a full list of fields. e. g.: ['id_str'], ['id', 'text', 'favorite_count', 'retweet_count'] If `entity_type` is expressed with hierarchy, then it is the list of\ fields of the object that corresponds to the key of the entity_type,\ (e.g., for entity_type='user.urls', the fields in the main_fields list\ belong to the user object; for entity_type='place.bounding_box', the\ files in the main_field list belong to the place object of the tweet). :param list entity_type: The name of the entity: 'hashtags', 'media',\ 'urls' and 'user_mentions' for the tweet object. For a user object,\ this needs to be expressed with a hierarchy: `'user.urls'`. For the\ bounding box of the Tweet location, use `'place.bounding_box'`. :param list entity_fields: The list of fields to be extracted from the\ entity. E.g. `['text']` (of the Tweet) :param error: Behaviour for encoding errors, see\ https://docs.python.org/3/library/codecs.html#codec-base-classes :param gzip_compress: if `True`, output files are compressed with gzip
170,509
import random import warnings from abc import ABCMeta, abstractmethod from bisect import bisect from itertools import accumulate from nltk.lm.counter import NgramCounter from nltk.lm.util import log_base2 from nltk.lm.vocabulary import Vocabulary The provided code snippet includes necessary dependencies for implementing the `_mean` function. Write a Python function `def _mean(items)` to solve the following problem: Return average (aka mean) for sequence of items. Here is the function: def _mean(items): """Return average (aka mean) for sequence of items.""" return sum(items) / len(items)
Return average (aka mean) for sequence of items.