id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
173,921 | from __future__ import division
import os
import sys
import warnings
from .table_wide import WIDE_EASTASIAN
from .table_zero import ZERO_WIDTH
from .unicode_versions import list_versions
def wcwidth(wc, unicode_version='auto'):
r"""
Given one Unicode character, return its printable length on a terminal.
:pa... | Given a unicode string, return its printable length on a terminal. :param str pwcs: Measure width of given unicode string. :param int n: When ``n`` is None (default), return the length of the entire string, otherwise width the first ``n`` characters specified. :param str unicode_version: An explicit definition of the u... |
173,922 | from traitlets.config.configurable import SingletonConfigurable
from traitlets import (
Dict, Instance, Set, Bool, TraitError, Unicode
)
class Image:
"""
This class represents an image object. To create
:py:class:`~PIL.Image.Image` objects, use the appropriate factory
functions. There's hardly ev... | Test if PIL/Pillow is available |
173,923 | import matplotlib
from matplotlib import colors
from matplotlib.backends import backend_agg
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib._pylab_helpers import Gcf
from matplotlib.figure import Figure
from IPython.core.interactiveshell import InteractiveShell
from IPython.core.getipython i... | Return a new figure manager for a new figure instance. This function is part of the API expected by Matplotlib backends. |
173,924 | import matplotlib
from matplotlib import colors
from matplotlib.backends import backend_agg
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib._pylab_helpers import Gcf
from matplotlib.figure import Figure
from IPython.core.interactiveshell import InteractiveShell
from IPython.core.getipython i... | Enable extra IPython matplotlib integration when we are loaded as the matplotlib backend. |
173,925 | import matplotlib
from matplotlib import colors
from matplotlib.backends import backend_agg
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib._pylab_helpers import Gcf
from matplotlib.figure import Figure
from IPython.core.interactiveshell import InteractiveShell
from IPython.core.getipython i... | Select figure formats for the inline backend. Optionally pass quality for JPEG. For example, this enables PNG and JPEG output with a JPEG quality of 90%:: In [1]: set_matplotlib_formats('png', 'jpeg', quality=90) To set this in your config files use the following:: c.InlineBackend.figure_formats = {'png', 'jpeg'} c.Inl... |
173,926 | import matplotlib
from matplotlib import colors
from matplotlib.backends import backend_agg
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib._pylab_helpers import Gcf
from matplotlib.figure import Figure
from IPython.core.interactiveshell import InteractiveShell
from IPython.core.getipython i... | Set whether the inline backend closes all figures automatically or not. By default, the inline backend used in the IPython Notebook will close all matplotlib figures automatically after each cell is run. This means that plots in different cells won't interfere. Sometimes, you may want to make a plot in one cell and the... |
173,927 | import copy
import errno
import glob
import json
import os
from traitlets.config import LoggingConfigurable
from traitlets.traitlets import Bool, Unicode
The provided code snippet includes necessary dependencies for implementing the `recursive_update` function. Write a Python function `def recursive_update(target, new... | Recursively update one dictionary using another. None values will delete their keys. |
173,928 | import copy
import errno
import glob
import json
import os
from traitlets.config import LoggingConfigurable
from traitlets.traitlets import Bool, Unicode
The provided code snippet includes necessary dependencies for implementing the `remove_defaults` function. Write a Python function `def remove_defaults(data, default... | Recursively remove items from dict that are already in defaults |
173,929 | import errno
import importlib.util
import os
import socket
import sys
import warnings
from contextlib import contextmanager
from typing import NewType
from urllib.parse import (
SplitResult,
quote,
unquote,
urljoin, # noqa
urlparse,
urlsplit,
urlunsplit,
)
from urllib.request import pathnam... | Determine whether a given URL is absolute |
173,930 | import errno
import importlib.util
import os
import socket
import sys
import warnings
from contextlib import contextmanager
from typing import NewType
from urllib.parse import (
SplitResult,
quote,
unquote,
urljoin, # noqa
urlparse,
urlsplit,
urlunsplit,
)
from urllib.request import pathnam... | Convert a local file path to a URL |
173,931 | import errno
import importlib.util
import os
import socket
import sys
import warnings
from contextlib import contextmanager
from typing import NewType
from urllib.parse import (
SplitResult,
quote,
unquote,
urljoin, # noqa
urlparse,
urlsplit,
urlunsplit,
)
from urllib.request import pathnam... | Convert a URL to a local file path |
173,932 | import errno
import importlib.util
import os
import socket
import sys
import warnings
from contextlib import contextmanager
from typing import NewType
from urllib.parse import (
SplitResult,
quote,
unquote,
urljoin, # noqa
urlparse,
urlsplit,
urlunsplit,
)
from urllib.request import pathnam... | Escape special characters in a URL path Turns '/foo bar/' into '/foo%20bar/' |
173,933 | import errno
import importlib.util
import os
import socket
import sys
import warnings
from contextlib import contextmanager
from typing import NewType
from urllib.parse import (
SplitResult,
quote,
unquote,
urljoin, # noqa
urlparse,
urlsplit,
urlunsplit,
)
from urllib.request import pathnam... | Unescape special characters in a URL path Turns '/foo%20bar/' into '/foo bar/' |
173,934 | import errno
import importlib.util
import os
import socket
import sys
import warnings
from contextlib import contextmanager
from typing import NewType
from urllib.parse import (
SplitResult,
quote,
unquote,
urljoin, # noqa
urlparse,
urlsplit,
urlunsplit,
)
from urllib.request import pathnam... | 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.sa... |
173,935 | import errno
import importlib.util
import os
import socket
import sys
import warnings
from contextlib import contextmanager
from typing import NewType
from urllib.parse import (
SplitResult,
quote,
unquote,
urljoin, # noqa
urlparse,
urlsplit,
urlunsplit,
)
from urllib.request import pathnam... | Convert an API path to a filesystem path If given, root will be prepended to the path. root must be a filesystem path already. |
173,936 | import errno
import importlib.util
import os
import socket
import sys
import warnings
from contextlib import contextmanager
from typing import NewType
from urllib.parse import (
SplitResult,
quote,
unquote,
urljoin, # noqa
urlparse,
urlsplit,
urlunsplit,
)
from urllib.request import pathnam... | Convert a filesystem path to an API path If given, root will be removed from the path. root must be a filesystem path already. |
173,937 | import errno
import importlib.util
import os
import socket
import sys
import warnings
from contextlib import contextmanager
from typing import NewType
from urllib.parse import (
SplitResult,
quote,
unquote,
urljoin, # noqa
urlparse,
urlsplit,
urlunsplit,
)
from urllib.request import pathnam... | 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. |
173,938 | import errno
import importlib.util
import os
import socket
import sys
import warnings
from contextlib import contextmanager
from typing import NewType
from urllib.parse import (
SplitResult,
quote,
unquote,
urljoin, # noqa
urlparse,
urlsplit,
urlunsplit,
)
from urllib.request import pathnam... | null |
173,939 | import errno
import importlib.util
import os
import socket
import sys
import warnings
from contextlib import contextmanager
from typing import NewType
from urllib.parse import (
SplitResult,
quote,
unquote,
urljoin, # noqa
urlparse,
urlsplit,
urlunsplit,
)
from urllib.request import pathnam... | Copy of IPython.utils.process.check_pid |
173,940 | import errno
import importlib.util
import os
import socket
import sys
import warnings
from contextlib import contextmanager
from typing import NewType
from urllib.parse import (
SplitResult,
quote,
unquote,
urljoin, # noqa
urlparse,
urlsplit,
urlunsplit,
)
from urllib.request import pathnam... | **DEPRECATED**: Use ``ensure_async`` from jupyter_core instead. |
173,941 | import errno
import importlib.util
import os
import socket
import sys
import warnings
from contextlib import contextmanager
from typing import NewType
from urllib.parse import (
SplitResult,
quote,
unquote,
urljoin, # noqa
urlparse,
urlsplit,
urlunsplit,
)
from urllib.request import pathnam... | Encodes a UNIX socket URL from a socket path for the `http+unix` URI form. |
173,942 | import errno
import importlib.util
import os
import socket
import sys
import warnings
from contextlib import contextmanager
from typing import NewType
from urllib.parse import (
SplitResult,
quote,
unquote,
urljoin, # noqa
urlparse,
urlsplit,
urlunsplit,
)
from urllib.request import pathnam... | Checks whether a UNIX socket path on disk is in use by attempting to connect to it. |
173,943 | import errno
import importlib.util
import os
import socket
import sys
import warnings
from contextlib import contextmanager
from typing import NewType
from urllib.parse import (
SplitResult,
quote,
unquote,
urljoin, # noqa
urlparse,
urlsplit,
urlunsplit,
)
from urllib.request import pathnam... | Send an asynchronous HTTP, HTTPS, or HTTP+UNIX request to a Tornado Web Server. Returns a tornado HTTPResponse. |
173,944 | import errno
import importlib.util
import os
import socket
import sys
import warnings
from contextlib import contextmanager
from typing import NewType
from urllib.parse import (
SplitResult,
quote,
unquote,
urljoin, # noqa
urlparse,
urlsplit,
urlunsplit,
)
from urllib.request import pathnam... | Is the provided namespace a Python Namespace Package (PEP420). https://www.python.org/dev/peps/pep-0420/#specification Returns `None` if module is not importable. |
173,945 | import errno
import importlib.util
import os
import socket
import sys
import warnings
from contextlib import contextmanager
from typing import NewType
from urllib.parse import (
SplitResult,
quote,
unquote,
urljoin, # noqa
urlparse,
urlsplit,
urlunsplit,
)
from urllib.request import pathnam... | Find a file by looking through a sequence of paths. This iterates through a sequence of paths looking for a file and returns the full, absolute path of the first occurence of the file. If no set of path dirs is given, the filename is tested as is, after running through :func:`expandvars` and :func:`expanduser`. Thus a ... |
173,946 | import errno
import importlib.util
import os
import socket
import sys
import warnings
from contextlib import contextmanager
from typing import NewType
from urllib.parse import (
SplitResult,
quote,
unquote,
urljoin, # noqa
urlparse,
urlsplit,
urlunsplit,
)
from urllib.request import pathnam... | 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 : str The fully qualified name of the module/package being imported. Returns ------- mod : module object The module that... |
173,947 | import importlib
import time
import warnings
class ExtensionLoadingError(Exception):
"""An extension loading error."""
pass
The provided code snippet includes necessary dependencies for implementing the `get_loader` function. Write a Python function `def get_loader(obj, logger=None)` to solve the following pro... | Looks for _load_jupyter_server_extension as an attribute of the object or module. Adds backwards compatibility for old function name missing the underscore prefix. |
173,948 | import importlib
import time
import warnings
The provided code snippet includes necessary dependencies for implementing the `get_metadata` function. Write a Python function `def get_metadata(package_name, logger=None)` to solve the following problem:
Find the extension metadata from an extension package. This looks fo... | Find the extension metadata from an extension package. This looks for a `_jupyter_server_extension_points` function that returns metadata about all extension points within a Jupyter Server Extension pacakge. If it doesn't exist, return a basic metadata packet given the module name. |
173,949 | import importlib
import time
import warnings
class ExtensionPackage(LoggingConfigurable):
"""An API for interfacing with a Jupyter Server extension package.
Usage:
ext_name = "my_extensions"
extpkg = ExtensionPackage(name=ext_name)
"""
name = Unicode(help="Name of the an importable Python pa... | Raises an exception is the extension is missing a needed hook or metadata field. An extension is valid if: 1) name is an importable Python package. 1) the package has a _jupyter_server_extension_paths function 2) each extension path has a _load_jupyter_server_extension function If this works, nothing should happen. |
173,950 | import logging
import os
import sys
from jupyter_core.application import JupyterApp
from jupyter_core.paths import ENV_CONFIG_PATH, SYSTEM_CONFIG_PATH, jupyter_config_dir
from tornado.log import LogFormatter
from traitlets import Bool
from jupyter_server._version import __version__
from jupyter_server.extension.config ... | Get an extension manager pointing at the current context Returns the path to the current context and an ExtensionManager object. Parameters ---------- write_dir : str [default: 'jupyter_server_config.d'] Name of config directory to write extension config. user : bool [default: False] Get the user's .jupyter config dire... |
173,951 | import logging
import os
import sys
from jupyter_core.application import JupyterApp
from jupyter_core.paths import ENV_CONFIG_PATH, SYSTEM_CONFIG_PATH, jupyter_config_dir
from tornado.log import LogFormatter
from traitlets import Bool
from jupyter_server._version import __version__
from jupyter_server.extension.config ... | Toggle the boolean setting for a given server extension in a Jupyter config file. |
173,952 | import logging
import re
import sys
import typing as t
from jinja2 import Environment, FileSystemLoader
from jupyter_core.application import JupyterApp, NoStart
from tornado.log import LogFormatter
from tornado.web import RedirectHandler
from traitlets import Any, Bool, Dict, HasTraits, List, Unicode, default
from trai... | Preparse command line to look for subcommands. |
173,953 | import logging
import re
import sys
import typing as t
from jinja2 import Environment, FileSystemLoader
from jupyter_core.application import JupyterApp, NoStart
from tornado.log import LogFormatter
from tornado.web import RedirectHandler
from traitlets import Any, Bool, Dict, HasTraits, List, Unicode, default
from trai... | Looks for 'help', 'version', and 'generate-config; commands in command line. If found, raises the help and version of current Application. This is useful for traitlets applications that have to parse the command line multiple times, but want to control when when 'help' and 'version' is raised. |
173,954 | import gettext
import os
import warnings
trans = gettext.translation(
"notebook", localedir=os.path.join(base_dir, "notebook/i18n"), fallback=True
)
The provided code snippet includes necessary dependencies for implementing the `_trans_gettext_deprecation_helper` function. Write a Python function `def _trans_gette... | The trans gettext deprecation helper. |
173,955 | import io
import os
import sys
import zipfile
from anyio.to_thread import run_sync
from jupyter_core.utils import ensure_async
from nbformat import from_dict
from tornado import web
from tornado.log import app_log
from jupyter_server.auth import authorized
from ..base.handlers import FilesRedirectHandler, JupyterHandle... | Find the resource files in a directory. |
173,956 | import io
import os
import sys
import zipfile
from anyio.to_thread import run_sync
from jupyter_core.utils import ensure_async
from nbformat import from_dict
from tornado import web
from tornado.log import app_log
from jupyter_server.auth import authorized
from ..base.handlers import FilesRedirectHandler, JupyterHandle... | 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. |
173,957 | import io
import os
import sys
import zipfile
from anyio.to_thread import run_sync
from jupyter_core.utils import ensure_async
from nbformat import from_dict
from tornado import web
from tornado.log import app_log
from jupyter_server.auth import authorized
from ..base.handlers import FilesRedirectHandler, JupyterHandle... | get an exporter, raising appropriate errors |
173,958 | import asyncio
import json
import logging
import os
import typing as ty
from abc import ABC, ABCMeta, abstractmethod
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from http.cookies import SimpleCookie
from socket import gaierror
from tornado import web
from tornado.httpclient imp... | Make an async request to kernel gateway endpoint, returns a response |
173,959 | from __future__ import annotations
import binascii
import datetime
import json
import os
import re
import sys
import uuid
from dataclasses import asdict, dataclass
from http.cookies import Morsel
from typing import TYPE_CHECKING, Any, Awaitable
from tornado import escape, httputil, web
from traitlets import Bool, Dict,... | Backward-compatibility for LoginHandler.get_user Prior to 2.0, LoginHandler.get_user could return anything truthy. Typically, this was either a simple string username, or a simple dict. Make some effort to allow common patterns to keep working. |
173,960 | import importlib
import random
import re
import warnings
The provided code snippet includes necessary dependencies for implementing the `warn_disabled_authorization` function. Write a Python function `def warn_disabled_authorization()` to solve the following problem:
DEPRECATED, does nothing
Here is the function:
de... | DEPRECATED, does nothing |
173,961 | import importlib
import random
import re
import warnings
def get_regex_to_resource_map():
"""Returns a dictionary with all of Jupyter Server's
request handler URL regex patterns mapped to
their resource name.
e.g.
{ "/api/contents/<regex_pattern>": "contents", ...}
"""
from jupyter_server.se... | Finds the JupyterHandler regex pattern that would match the given URL and returns the resource name (str) of that handler. e.g. /api/contents/... returns "contents" |
173,962 | import importlib
import random
import re
import warnings
moons_of_jupyter = [
"Metis",
"Adrastea",
"Amalthea",
"Thebe",
"Io",
"Europa",
"Ganymede",
"Callisto",
"Themisto",
"Leda",
"Ersa",
"Pandia",
"Himalia",
"Lysithea",
"Elara",
"Dia",
"Carpo",
"V... | Get a random user-name based on the moons of Jupyter. This function returns names like "Anonymous Io" or "Anonymous Metis". |
173,963 | from functools import wraps
from typing import Callable, Optional, Union
from tornado.log import app_log
from tornado.web import HTTPError
from .utils import HTTP_METHOD_TO_AUTH_ACTION
def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> Callable[[_T], _T]: ...
class Callab... | A decorator for tornado.web.RequestHandler methods that verifies whether the current user is authorized to make the following request. Helpful for adding an 'authorization' layer to a REST API. .. versionadded:: 2.0 Parameters ---------- action : str the type of permission or action to check. resource: str or None the ... |
173,964 | import argparse
import sys
import warnings
from getpass import getpass
from jupyter_core.paths import jupyter_config_dir
from traitlets.log import get_logger
from jupyter_server.auth import passwd
from jupyter_server.config_manager import BaseJSONConfigManager
def getpass(prompt: str = ..., stream: Optional[TextIO] = ... | Set a password. |
173,965 | import getpass
import hashlib
import json
import os
import random
import traceback
import warnings
from contextlib import contextmanager
from jupyter_core.paths import jupyter_config_dir
from traitlets.config import Config, ConfigFileNotFound, JSONFileConfigLoader
The provided code snippet includes necessary dependenc... | 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 -------- >>> myhash = passwd('mypassword')... |
173,966 | import getpass
import hashlib
import json
import os
import random
import traceback
import warnings
from contextlib import contextmanager
from jupyter_core.paths import jupyter_config_dir
from traitlets.config import Config, ConfigFileNotFound, JSONFileConfigLoader
def passwd(passphrase=None, algorithm="argon2"):
""... | Ask user for password, store it in JSON configuration file |
173,967 | from datetime import datetime, timedelta, tzinfo
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: dat... | decorator for adding UTC tzinfo to datetime's utcfoo methods |
173,968 | from datetime import datetime, timedelta, tzinfo
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 ... | Return iso-formatted timestamp Like .isoformat(), but uses Z for UTC instead of +00:00 |
173,969 | from __future__ import annotations
import functools
import inspect
import ipaddress
import json
import mimetypes
import os
import re
import traceback
import types
import warnings
from http.client import responses
from typing import TYPE_CHECKING, Awaitable
from urllib.parse import urlparse
import prometheus_client
from... | Get sys info as json. |
173,970 | from __future__ import annotations
import functools
import inspect
import ipaddress
import json
import mimetypes
import os
import re
import traceback
import types
import warnings
from http.client import responses
from typing import TYPE_CHECKING, Awaitable
from urllib.parse import urlparse
import prometheus_client
from... | 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 messag... |
173,971 | import asyncio
import json
import time
import weakref
from concurrent.futures import Future
from textwrap import dedent
from typing import Dict as Dict_t
from typing import MutableSet
from jupyter_client import protocol_version as client_protocol_version
from tornado import gen, web
from tornado.ioloop import IOLoop
fr... | Wrap a concurrent future as an asyncio future if there is a running loop. |
173,972 | import json
import struct
from jupyter_client.session import Session
from tornado.websocket import WebSocketHandler
from traitlets import Float, Instance, default
from traitlets.config import LoggingConfigurable
from jupyter_client.jsonutil import extract_dates
from .abc import KernelWebsocketConnectionABC
def json_de... | 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. |
173,973 | import json
import struct
from jupyter_client.session import Session
from tornado.websocket import WebSocketHandler
from traitlets import Float, Instance, default
from traitlets.config import LoggingConfigurable
from jupyter_client.jsonutil import extract_dates
from .abc import KernelWebsocketConnectionABC
def extract... | 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 |
173,974 | import json
import struct
from jupyter_client.session import Session
from tornado.websocket import WebSocketHandler
from traitlets import Float, Instance, default
from traitlets.config import LoggingConfigurable
from jupyter_client.jsonutil import extract_dates
from .abc import KernelWebsocketConnectionABC
The provide... | Serialize a message using the v1 protocol. |
173,975 | import json
import struct
from jupyter_client.session import Session
from tornado.websocket import WebSocketHandler
from traitlets import Float, Instance, default
from traitlets.config import LoggingConfigurable
from jupyter_client.jsonutil import extract_dates
from .abc import KernelWebsocketConnectionABC
The provide... | Deserialize a message using the v1 protocol. |
173,976 | import errno
import os
import shutil
from base64 import decodebytes, encodebytes
from contextlib import contextmanager
from functools import partial
import nbformat
from anyio.to_thread import run_sync
from tornado.web import HTTPError
from traitlets import Bool
from traitlets.config import Configurable
from jupyter_se... | replace dst with src asynchronously |
173,977 | import errno
import os
import shutil
from base64 import decodebytes, encodebytes
from contextlib import contextmanager
from functools import partial
import nbformat
from anyio.to_thread import run_sync
from tornado.web import HTTPError
from traitlets import Bool
from traitlets.config import Configurable
from jupyter_se... | copy src to dst asynchronously like shutil.copy2, but log errors in copystat instead of raising |
173,978 | import errno
import os
import shutil
from base64 import decodebytes, encodebytes
from contextlib import contextmanager
from functools import partial
import nbformat
from anyio.to_thread import run_sync
from tornado.web import HTTPError
from traitlets import Bool
from traitlets.config import Configurable
from jupyter_se... | Name of invalid file after a failed atomic write and subsequent read. |
173,979 | import errno
import os
import shutil
from base64 import decodebytes, encodebytes
from contextlib import contextmanager
from functools import partial
import nbformat
from anyio.to_thread import run_sync
from tornado.web import HTTPError
from traitlets import Bool
from traitlets.config import Configurable
from jupyter_se... | 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 tempor... |
173,980 | import errno
import os
import shutil
from base64 import decodebytes, encodebytes
from contextlib import contextmanager
from functools import partial
import nbformat
from anyio.to_thread import run_sync
from tornado.web import HTTPError
from traitlets import Bool
from traitlets.config import Configurable
from jupyter_se... | 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 ... |
173,981 | import json
from jupyter_core.utils import ensure_async
from tornado import web
from jupyter_server.auth import authorized
from jupyter_server.base.handlers import APIHandler, JupyterHandler, path_regex
from jupyter_server.utils import url_escape, url_path_join
The provided code snippet includes necessary dependencies... | Validate a model returned by a ContentsManager method. If expect_content is True, then we expect non-null entries for 'content' and 'format'. |
173,982 | import glob
import json
import os
pjoin = os.path.join
from jupyter_core.utils import ensure_async
from tornado import web
from jupyter_server.auth import authorized
from ...base.handlers import APIHandler
from ...utils import url_path_join, url_unescape
def url_path_join(*pieces):
"""Join components of url into a... | Load a KernelSpec by name and return the REST API model |
173,983 | import glob
import json
import os
from jupyter_core.utils import ensure_async
from tornado import web
from jupyter_server.auth import authorized
from ...base.handlers import APIHandler
from ...utils import url_path_join, url_unescape
The provided code snippet includes necessary dependencies for implementing the `is_ke... | Returns True if spec_dict is already in proper form. This will occur when using a gateway. |
173,984 | import json
from datetime import datetime
from typing import Any, Dict, Optional
from jupyter_events import EventLogger
from tornado import web, websocket
from jupyter_server.auth import authorized
from jupyter_server.base.handlers import JupyterHandler
from ...base.handlers import APIHandler
Any = object()
... | Validates for required fields in the JSON request body |
173,985 | import json
from datetime import datetime
from typing import Any, Dict, Optional
from jupyter_events import EventLogger
from tornado import web, websocket
from jupyter_server.auth import authorized
from jupyter_server.base.handlers import JupyterHandler
from ...base.handlers import APIHandler
class datetime(date):
... | Parses timestamp from the JSON request body |
173,986 | import json
from urllib.parse import urlparse, urlunparse
from tornado.log import access_log
from .auth import User
from .prometheus.log_functions import prometheus_log_method
def _scrub_uri(uri: str) -> str:
"""scrub auth info from uri"""
parsed = urlparse(uri)
if parsed.query:
# check for potentia... | 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 |
173,987 | import datetime
import errno
import gettext
import hashlib
import hmac
import ipaddress
import json
import logging
import mimetypes
import os
import pathlib
import random
import re
import select
import signal
import socket
import stat
import sys
import threading
import time
import urllib
import warnings
from base64 imp... | 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]. |
173,988 | import datetime
import errno
import gettext
import hashlib
import hmac
import ipaddress
import json
import logging
import mimetypes
import os
import pathlib
import random
import re
import select
import signal
import socket
import stat
import sys
import threading
import time
import urllib
import warnings
from base64 imp... | Load the (URL pattern, handler) tuples for each component. |
173,989 | import datetime
import errno
import gettext
import hashlib
import hmac
import ipaddress
import json
import logging
import mimetypes
import os
import pathlib
import random
import re
import select
import signal
import socket
import stat
import sys
import threading
import time
import urllib
import warnings
from base64 imp... | Shutdown a Jupyter 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. Ret... |
173,990 | import datetime
import errno
import gettext
import hashlib
import hmac
import ipaddress
import json
import logging
import mimetypes
import os
import pathlib
import random
import re
import select
import signal
import socket
import stat
import sys
import threading
import time
import urllib
import warnings
from base64 imp... | Iterate over the server info files of running Jupyter servers. Given a runtime directory, find jpserver-* files in the security directory, and yield dicts of their information, each one pertaining to a currently running Jupyter server instance. |
173,992 | from . import Image, ImageFile
from ._binary import o8
from ._binary import o16be as o16b
_Palm8BitColormapValues = (
(255, 255, 255), (255, 204, 255), (255, 153, 255), (255, 102, 255),
(255, 51, 255), (255, 0, 255), (255, 255, 204), (255, 204, 204),
(255, 153, 204), (255, 102, 204), (255, 51, 204), (25... | null |
173,993 | from . import Image, ImageFile
from ._binary import o8
from ._binary import o16be as o16b
_FLAGS = {"custom-colormap": 0x4000, "is-compressed": 0x8000, "has-transparent": 0x2000}
_COMPRESSION_TYPES = {"none": 0xFF, "rle": 0x01, "scanline": 0x00}
class ImageFile(Image.Image):
"""Base class for image file format han... | null |
173,994 | from . import Image, ImageFile
from ._binary import i16le as word
from ._binary import si16le as short
from ._binary import si32le as _long
_handler = None
The provided code snippet includes necessary dependencies for implementing the `register_handler` function. Write a Python function `def register_handler(handler)`... | Install application-specific WMF image handler. :param handler: Handler object. |
173,995 | from . import Image, ImageFile
from ._binary import i16le as word
from ._binary import si16le as short
from ._binary import si32le as _long
def _accept(prefix):
return (
prefix[:6] == b"\xd7\xcd\xc6\x9a\x00\x00" or prefix[:4] == b"\x01\x00\x00\x00"
) | null |
173,996 | from . import Image, ImageFile
from ._binary import i16le as word
from ._binary import si16le as short
from ._binary import si32le as _long
_handler = None
if hasattr(Image.core, "drawwmf"):
# install default handler (windows only)
register_handler(WmfHandler())
def _save(im, fp, filename):
if _handler is ... | null |
173,997 | import struct
from enum import IntEnum
from io import BytesIO
from . import Image, ImageFile
from ._deprecate import deprecate
class Format(IntEnum):
DXT1 = 0
UNCOMPRESSED = 1
def deprecate(
deprecated: str,
when: int | None,
replacement: str | None = None,
*,
action: str | None = None,
... | null |
173,998 | import struct
from enum import IntEnum
from io import BytesIO
from . import Image, ImageFile
from ._deprecate import deprecate
MAGIC = b"FTEX"
def _accept(prefix):
return prefix[:4] == MAGIC | null |
174,002 | import calendar
import codecs
import collections
import mmap
import os
import re
import time
import zlib
def encode_text(s):
return codecs.BOM_UTF16_BE + s.encode("utf_16_be")
class PdfName:
def __init__(self, name):
if isinstance(name, PdfName):
self.name = name.name
elif isinstance... | null |
174,003 | import math
import numbers
import warnings
from . import Image, ImageColor
from ._deprecate import deprecate
def _color_diff(color1, color2):
"""
Uses 1-norm distance to calculate difference between two values.
"""
if isinstance(color2, tuple):
return sum(abs(color1[i] - color2[i]) for i in rang... | (experimental) Fills a bounded region with a given color. :param image: Target image. :param xy: Seed position (a 2-item coordinate tuple). See :ref:`coordinate-system`. :param value: Fill color. :param border: Optional border value. If given, the region consists of pixels with a color different from the border color. ... |
174,004 | import math
import numbers
import warnings
from . import Image, ImageColor
from ._deprecate import deprecate
The provided code snippet includes necessary dependencies for implementing the `_compute_regular_polygon_vertices` function. Write a Python function `def _compute_regular_polygon_vertices(bounding_circle, n_sid... | Generate a list of vertices for a 2D regular polygon. :param bounding_circle: The bounding circle is a tuple defined by a point and radius. The polygon is inscribed in this circle. (e.g. ``bounding_circle=(x, y, r)`` or ``((x, y), r)``) :param n_sides: Number of sides (e.g. ``n_sides=3`` for a triangle, ``6`` for a hex... |
174,005 | import tkinter
from io import BytesIO
from . import Image
from ._deprecate import deprecate
_pilbitmap_ok = None
class BitmapImage:
"""
A Tkinter-compatible bitmap image. This can be used everywhere Tkinter
expects an image object.
The given image must have mode "1". Pixels having value 0 are treated ... | null |
174,006 | import tkinter
from io import BytesIO
from . import Image
from ._deprecate import deprecate
class BytesIO(BufferedIOBase, BinaryIO):
def __init__(self, initial_bytes: bytes = ...) -> None: ...
# BytesIO does not contain a "name" field. This workaround is necessary
# to allow BytesIO sub-classes to add this... | null |
174,007 | import tkinter
from io import BytesIO
from . import Image
from ._deprecate import deprecate
def _pyimagingtkcall(command, photo, id):
tk = photo.tk
try:
tk.call(command, photo, id)
except tkinter.TclError:
# activate Tkinter hook
# may raise an error if it cannot attach to Tkinter
... | Copies the contents of a PhotoImage to a PIL image memory. |
174,008 | import tkinter
from io import BytesIO
from . import Image
from ._deprecate import deprecate
class PhotoImage:
"""
A Tkinter-compatible photo image. This can be used
everywhere Tkinter expects an image object. If the image is an RGBA
image, pixels having alpha 0 are treated as transparent.
The cons... | Helper for the Image.show method. |
174,009 | class Iterator:
"""
This class implements an iterator object that can be used to loop
over an image sequence.
You can use the ``[]`` operator to access elements by index. This operator
will raise an :py:exc:`IndexError` if you try to access a nonexistent
frame.
:param im: An image object.
... | Applies a given function to all frames in an image or a list of images. The frames are returned as a list of separate images. :param im: An image, or a list of images. :param func: The function to apply to all of the image frames. :returns: A list of images. |
174,010 | import os
import struct
import sys
from PIL import Image, ImageFile
def isSpiderImage(filename):
with open(filename, "rb") as fp:
f = fp.read(92) # read 23 * 4 bytes
t = struct.unpack(">23f", f) # try big-endian first
hdrlen = isSpiderHeader(t)
if hdrlen == 0:
t = struct.unpack("<23f",... | create a list of :py:class:`~PIL.Image.Image` objects for use in a montage |
174,011 | import os
import struct
import sys
from PIL import Image, ImageFile
class SpiderImageFile(ImageFile.ImageFile):
format = "SPIDER"
format_description = "Spider 2D image"
_close_exclusive_fp_after_loading = False
def _open(self):
# check header
n = 27 * 4 # read 27 float values
f ... | null |
174,013 | import os
import tempfile
from . import Image, ImageFile
from ._binary import i8
from ._binary import i16be as i16
from ._binary import i32be as i32
from ._binary import o8
class IptcImageFile(ImageFile.ImageFile):
format = "IPTC"
format_description = "IPTC/NAA"
def getint(self, key):
return i(self.... | Get IPTC information from TIFF, JPEG, or IPTC file. :param im: An image containing IPTC data. :returns: A dictionary containing IPTC information, or None if no IPTC information block was found. |
174,015 | from io import BytesIO
from . import Image, ImageFile
try:
from . import _webp
SUPPORTED = True
except ImportError:
SUPPORTED = False
_VALID_WEBP_MODES = {"RGBX": True, "RGBA": True, "RGB": True}
def _save(im, fp, filename):
lossless = im.encoderinfo.get("lossless", False)
quality = im.encoderinfo.g... | null |
174,017 | import io
import logging
from . import Image, ImageFile, ImagePalette
from ._binary import i16le as i16
from ._binary import o8
from ._binary import o16le as o16
logger = logging.getLogger(__name__)
SAVE = {
# mode: (version, bits, planes, raw mode)
"1": (2, 1, 1, "1"),
"L": (5, 8, 1, "L"),
"P": (5, 8, ... | null |
174,018 | import io
import itertools
import struct
import sys
from . import Image
from ._util import is_path
ERRORS = {
-1: "image buffer overrun error",
-2: "decoding error",
-3: "unknown error",
-8: "bad configuration",
-9: "out of memory error",
}
class Image:
"""
This class represents an image ob... | null |
174,020 | import io
import struct
from . import Image, ImageFile
from ._binary import i16le as i16
from ._binary import o16le as o16
class ImageFile(Image.Image):
"""Base class for image file format handlers."""
def __init__(self, fp=None, filename=None):
super().__init__()
self._min_frame = 0
... | null |
174,022 | import io
import math
import os
import time
from . import Image, ImageFile, ImageSequence, PdfParser, __version__, features
def _save(im, fp, filename, save_all=False):
is_appending = im.encoderinfo.get("append", False)
if is_appending:
existing_pdf = PdfParser.PdfParser(f=fp, filename=filename, mode="r... | null |
174,024 | import io
import os
import struct
import sys
from PIL import Image, ImageFile, PngImagePlugin, features
def read_32(fobj, start_length, size):
def read_32t(fobj, start_length, size):
# The 128x128 icon seems to have an extra header for some reason.
(start, length) = start_length
fobj.seek(start)
sig = ... | null |
174,025 | import io
import os
import struct
import sys
from PIL import Image, ImageFile, PngImagePlugin, features
Image.register_open(IcnsImageFile.format, IcnsImageFile, _accept)
Image.register_extension(IcnsImageFile.format, ".icns")
Image.register_save(IcnsImageFile.format, _save)
Image.register_mime(IcnsImageFile.format, "im... | null |
174,026 | import io
import os
import struct
import sys
from PIL import Image, ImageFile, PngImagePlugin, features
enable_jpeg2k = features.check_codec("jpg_2000")
if enable_jpeg2k:
from PIL import Jpeg2KImagePlugin
Image.register_open(IcnsImageFile.format, IcnsImageFile, _accept)
Image.register_extension(IcnsImageFile.format... | null |
174,029 | from . import Image, ImageFile
from ._binary import i16be as i16
from ._binary import o8
from ._binary import o32le as o32
def _accept(prefix):
return prefix[0:1] == b"P" and prefix[1] in b"0123456y" | null |
174,030 | from . import Image, ImageFile
from ._binary import i16be as i16
from ._binary import o8
from ._binary import o32le as o32
class ImageFile(Image.Image):
"""Base class for image file format handlers."""
def __init__(self, fp=None, filename=None):
super().__init__()
self._min_frame = 0
... | null |
174,031 | from struct import pack, unpack_from
def unpack_from(__format: _FmtType, buffer: _BufferType, offset: int = ...) -> Tuple[Any, ...]: ...
The provided code snippet includes necessary dependencies for implementing the `i16le` function. Write a Python function `def i16le(c, o=0)` to solve the following problem:
Converts... | Converts a 2-bytes (16 bits) string to an unsigned integer. :param c: string containing bytes to convert :param o: offset of bytes to convert in string |
174,032 | from struct import pack, unpack_from
def unpack_from(__format: _FmtType, buffer: _BufferType, offset: int = ...) -> Tuple[Any, ...]: ...
The provided code snippet includes necessary dependencies for implementing the `si16le` function. Write a Python function `def si16le(c, o=0)` to solve the following problem:
Conver... | Converts a 2-bytes (16 bits) string to a signed integer. :param c: string containing bytes to convert :param o: offset of bytes to convert in string |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.