id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
186,372 | import os
import sys
import textwrap
from argparse import ArgumentParser
from contextlib import contextmanager
from pathlib import Path
import asdl
TABSIZE = 4
def reflow_c_string(s, depth):
return '"%s"' % s.replace('\n', '\\n"\n%s"' % (' ' * depth * TABSIZE)) | null |
186,373 | import os
import sys
import textwrap
from argparse import ArgumentParser
from contextlib import contextmanager
from pathlib import Path
import asdl
def is_simple(sum):
"""Return True if a sum is a simple.
A sum is simple if its types have no fields, e.g.
unaryop = Invert | Not | UAdd | USub
"""
for ... | null |
186,374 | import os
import sys
import textwrap
from argparse import ArgumentParser
from contextlib import contextmanager
from pathlib import Path
import asdl
def ast_func_name(name):
return f"_PyAST_{name}" | null |
186,375 | import os
import sys
import textwrap
from argparse import ArgumentParser
from contextlib import contextmanager
from pathlib import Path
import asdl
class TypeDefVisitor(EmitVisitor):
def visitModule(self, mod):
for dfn in mod.dfns:
self.visit(dfn)
def visitType(self, type, depth=0):
... | null |
186,376 | import os
import sys
import textwrap
from argparse import ArgumentParser
from contextlib import contextmanager
from pathlib import Path
import asdl
def write_internal_h_header(mod, f):
print(textwrap.dedent("""
#ifndef Py_INTERNAL_AST_STATE_H
#define Py_INTERNAL_AST_STATE_H
#ifdef __cpluspl... | null |
186,377 | import os
import sys
import textwrap
from argparse import ArgumentParser
from contextlib import contextmanager
from pathlib import Path
import asdl
def write_internal_h_footer(mod, f):
print(textwrap.dedent("""
#ifdef __cplusplus
}
#endif
#endif /* !Py_INTERNAL_AST_STATE_H */
"... | null |
186,378 | import os
import sys
import textwrap
from argparse import ArgumentParser
from contextlib import contextmanager
from pathlib import Path
import asdl
class FunctionVisitor(PrototypeVisitor):
"""Visitor to generate constructor functions for AST."""
def emit_function(self, name, ctype, args, attrs, union=True):
... | null |
186,380 | from collections import namedtuple
import re
class ASDLParser:
"""Parser for ASDL files.
Create, then call the parse method on a buffer containing ASDL.
This is a simple recursive descent parser that uses tokenize_asdl for the
lexing.
"""
def __init__(self):
self._tokenizer = None
... | Parse ASDL from the given file and return a Module node describing it. |
186,384 | import os
import stat
from itertools import filterfalse
from types import GenericAlias
class dircmp:
"""A class that manages the comparison of 2 directories.
dircmp(a, b, ignore=None, hide=None)
A and B are directories.
IGNORE is a list of names to ignore,
defaults to DEFAULT_IGNORES.
... | null |
186,388 | import _lsprof
import profile as _pyprofile
class Profile(_lsprof.Profiler):
def print_stats(self, sort=-1):
def dump_stats(self, file):
def create_stats(self):
def snapshot_stats(self):
def run(self, cmd):
def runctx(self, cmd, globals, locals):
def runcall(self, func, /, *args, **kw... | null |
186,390 | __block_openssl_constructor = {
'blake2b', 'blake2s',
}
def __get_builtin_constructor(name):
cache = __builtin_constructor_cache
constructor = cache.get(name)
if constructor is not None:
return constructor
try:
if name in {'SHA1', 'sha1'}:
import _sha1
cache['... | null |
186,392 | __block_openssl_constructor = {
'blake2b', 'blake2s',
}
def __get_builtin_constructor(name):
cache = __builtin_constructor_cache
constructor = cache.get(name)
if constructor is not None:
return constructor
try:
if name in {'SHA1', 'sha1'}:
import _sha1
cache['... | new(name, data=b'') - Return a new hashing object using the named algorithm; optionally initialized with data (which must be a bytes-like object). |
186,393 |
The provided code snippet includes necessary dependencies for implementing the `pbkdf2_hmac` function. Write a Python function `def pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None)` to solve the following problem:
Password based key derivation function 2 (PKCS #5 v2.0) This Python implementations based ... | Password based key derivation function 2 (PKCS #5 v2.0) This Python implementations based on the hmac module about as fast as OpenSSL's PKCS5_PBKDF2_HMAC for short passwords and much faster for long passwords. |
186,404 | import __future__
import warnings
def _is_syntax_error(err1, err2):
rep1 = repr(err1)
rep2 = repr(err2)
if "was never closed" in rep1 and "was never closed" in rep2:
return False
if rep1 == rep2:
return True
return False | null |
186,405 | import __future__
import warnings
def _maybe_compile(compiler, source, filename, symbol):
# Check for source consisting of only blank lines and comments.
for line in source.split("\n"):
line = line.strip()
if line and line[0] != '#':
break # Leave it alone.
else:
... | r"""Compile a command and determine whether it is incomplete. Arguments: source -- the source string; may contain \n characters filename -- optional filename from which source was read; default "<input>" symbol -- optional grammar start symbol; "single" (default), "exec" or "eval" Return value / exceptions raised: - Re... |
186,406 | hasname = []
def def_op(name, op):
opname[op] = name
opmap[name] = op
def_op('POP_TOP', 1)
def_op('ROT_TWO', 2)
def_op('ROT_THREE', 3)
def_op('DUP_TOP', 4)
def_op('DUP_TOP_TWO', 5)
def_op('ROT_FOUR', 6)
def_op('NOP', 9)
def_op('UNARY_POSITIVE', 10)
def_op('UNARY_NEGATIVE', 11)
def_op('UNARY_NOT', 12)
def_op('UN... | null |
186,407 | hasjrel = []
def def_op(name, op):
opname[op] = name
opmap[name] = op
def_op('POP_TOP', 1)
def_op('ROT_TWO', 2)
def_op('ROT_THREE', 3)
def_op('DUP_TOP', 4)
def_op('DUP_TOP_TWO', 5)
def_op('ROT_FOUR', 6)
def_op('NOP', 9)
def_op('UNARY_POSITIVE', 10)
def_op('UNARY_NEGATIVE', 11)
def_op('UNARY_NOT', 12)
def_op('UN... | null |
186,408 | hasjabs = []
def def_op(name, op):
opname[op] = name
opmap[name] = op
def_op('POP_TOP', 1)
def_op('ROT_TWO', 2)
def_op('ROT_THREE', 3)
def_op('DUP_TOP', 4)
def_op('DUP_TOP_TWO', 5)
def_op('ROT_FOUR', 6)
def_op('NOP', 9)
def_op('UNARY_POSITIVE', 10)
def_op('UNARY_NEGATIVE', 11)
def_op('UNARY_NOT', 12)
def_op('UN... | null |
186,409 | import sys
import sysconfig
def _aix_tag(vrtl, bd):
# type: (List[int], int) -> str
# Infer the ABI bitwidth from maxsize (assuming 64 bit as the default)
_sz = 32 if sys.maxsize == (2**31-1) else 64
# vrtl[version, release, technology_level]
return "aix-{:1x}{:1d}{:02d}-{:04d}-{}".format(vrtl[0], v... | Return the platform_tag of the system Python was built on. |
186,420 | from .. import fixer_base
from ..pygram import token
from ..fixer_util import syms, Node, Leaf
def fixup_simple_stmt(parent, i, stmt_node):
""" if there is a semi-colon all the parts count as part of the same
simple_stmt. We just want the __metaclass__ part so we move
everything after the semi-colo... | null |
186,437 | import string, re
from codecs import BOM_UTF8, lookup
from lib2to3.pgen2.token import *
from . import token
def group(*choices):
def maybe(*choices): return group(*choices) + '?' | null |
186,444 | from .pgen2 import token
from .pytree import Leaf, Node
from .pygram import python_symbols as syms
from . import patcomp
class Node(Base):
def __init__(self,type, children,
context=None,
prefix=None,
fixers_applied=None):
def __repr__(self):
... | null |
186,454 | from .pgen2 import token
from .pytree import Leaf, Node
from .pygram import python_symbols as syms
from . import patcomp
def LParen():
def RParen():
class Node(Base):
def __init__(self,type, children,
context=None,
prefix=None,
fixers_applied=None):
... | null |
186,467 | import collections
import os
import re
import sys
import subprocess
import functools
import itertools
def _sys_version(sys_version=None):
""" Returns a parsed version of Python's sys.version as tuple
(name, version, branch, revision, buildno, builddate, compiler)
referring to the Python implementati... | Returns a string identifying the Python implementation. Currently, the following implementations are identified: 'CPython' (C implementation of Python), 'IronPython' (.NET implementation of Python), 'Jython' (Java implementation of Python), 'PyPy' (Python implementation of Python). |
186,468 | import collections
import os
import re
import sys
import subprocess
import functools
import itertools
def _sys_version(sys_version=None):
""" Returns a parsed version of Python's sys.version as tuple
(name, version, branch, revision, buildno, builddate, compiler)
referring to the Python implementati... | Returns the Python version as tuple (major, minor, patchlevel) of strings. Note that unlike the Python sys.version, the returned value will always include the patchlevel (it defaults to 0). |
186,469 | import collections
import os
import re
import sys
import subprocess
import functools
import itertools
def _sys_version(sys_version=None):
""" Returns a parsed version of Python's sys.version as tuple
(name, version, branch, revision, buildno, builddate, compiler)
referring to the Python implementati... | Returns a string identifying the Python implementation branch. For CPython this is the SCM branch from which the Python binary was built. If not available, an empty string is returned. |
186,470 | import collections
import os
import re
import sys
import subprocess
import functools
import itertools
def _sys_version(sys_version=None):
""" Returns a parsed version of Python's sys.version as tuple
(name, version, branch, revision, buildno, builddate, compiler)
referring to the Python implementati... | Returns a string identifying the Python implementation revision. For CPython this is the SCM revision from which the Python binary was built. If not available, an empty string is returned. |
186,471 | import collections
import os
import re
import sys
import subprocess
import functools
import itertools
_os_release_candidates = ("/etc/os-release", "/usr/lib/os-release")
_os_release_cache = None
def _parse_os_release(lines):
# These fields are mandatory fields with well-known defaults
# in practice all Linux di... | Return operation system identification from freedesktop.org os-release |
186,472 | import _imp
import _io
import sys
import _warnings
import marshal
_CASE_INSENSITIVE_PLATFORMS_STR_KEY = 'win',
_CASE_INSENSITIVE_PLATFORMS = (_CASE_INSENSITIVE_PLATFORMS_BYTES_KEY
+ _CASE_INSENSITIVE_PLATFORMS_STR_KEY)
_relax_case = _make_relax_case()
def _make_relax_case():
if sys... | null |
186,477 | _bootstrap = None
import _imp
import _io
import sys
import _warnings
import marshal
The provided code snippet includes necessary dependencies for implementing the `_check_name` function. Write a Python function `def _check_name(method)` to solve the following problem:
Decorator to verify that the module being requeste... | Decorator to verify that the module being requested matches the one the loader can handle. The first argument (self) must define _name which the second argument is compared against. If the comparison fails then ImportError is raised. |
186,478 | import _imp
import _io
import sys
import _warnings
import marshal
The provided code snippet includes necessary dependencies for implementing the `_find_module_shim` function. Write a Python function `def _find_module_shim(self, fullname)` to solve the following problem:
Try to find a loader for the specified module by... | Try to find a loader for the specified module by delegating to self.find_loader(). This method is deprecated in favor of finder.find_spec(). |
186,479 | _bootstrap = None
import _imp
import _io
import sys
import _warnings
import marshal
def _unpack_uint32(data):
"""Convert 4 bytes in little-endian to an integer."""
assert len(data) == 4
return int.from_bytes(data, 'little')
The provided code snippet includes necessary dependencies for implementing the `_va... | Validate a pyc against the source last-modified time. *data* is the contents of the pyc file. (Only the first 16 bytes are required.) *source_mtime* is the last modified timestamp of the source file. *source_size* is None or the size of the source file in bytes. *name* is the name of the module being imported. It is us... |
186,481 | _bootstrap = None
import _imp
import _io
import sys
import _warnings
import marshal
_code_type = type(_write_atomic.__code__)
The provided code snippet includes necessary dependencies for implementing the `_compile_bytecode` function. Write a Python function `def _compile_bytecode(data, name=None, bytecode_path=None, ... | Compile bytecode as found in a pyc. |
186,483 | import _imp
import _io
import sys
import _warnings
import marshal
def spec_from_file_location(name, location=None, *, loader=None,
submodule_search_locations=_POPULATE):
"""Return a module spec based on a file location.
To indicate that the module is a package, set
submodule_sear... | null |
186,484 | import _imp
import _io
import sys
import _warnings
import marshal
class PathFinder:
"""Meta path finder for sys.path and package __path__ attributes."""
def invalidate_caches():
"""Call the invalidate_caches() method on all path entry finders
stored in sys.path_importer_caches (where implemented... | Install the path-based import components. |
186,485 | from . import _bootstrap_external
from . import machinery
try:
import _frozen_importlib
except ImportError as exc:
if exc.name != '_frozen_importlib':
raise
_frozen_importlib = None
try:
import _frozen_importlib_external
except ImportError:
_frozen_importlib_external = _bootstrap_external
fr... | null |
186,486 | from ._abc import Loader
from ._bootstrap import module_from_spec
from ._bootstrap import _resolve_name
from ._bootstrap import spec_from_loader
from ._bootstrap import _find_spec
from ._bootstrap_external import MAGIC_NUMBER
from ._bootstrap_external import _RAW_MAGIC_NUMBER
from ._bootstrap_external import cache_from... | Set __package__ on the returned module. This function is deprecated. |
186,487 | from ._abc import Loader
from ._bootstrap import module_from_spec
from ._bootstrap import _resolve_name
from ._bootstrap import spec_from_loader
from ._bootstrap import _find_spec
from ._bootstrap_external import MAGIC_NUMBER
from ._bootstrap_external import _RAW_MAGIC_NUMBER
from ._bootstrap_external import cache_from... | Set __loader__ on the returned module. This function is deprecated. |
186,488 | from ._abc import Loader
from ._bootstrap import module_from_spec
from ._bootstrap import _resolve_name
from ._bootstrap import spec_from_loader
from ._bootstrap import _find_spec
from ._bootstrap_external import MAGIC_NUMBER
from ._bootstrap_external import _RAW_MAGIC_NUMBER
from ._bootstrap_external import cache_from... | Decorator to handle selecting the proper module for loaders. The decorated function is passed the module to use instead of the module name. The module passed in to the function is either from sys.modules if it already exists or is a new module. If the module is new, then __name__ is set the first argument to the method... |
186,489 | from itertools import filterfalse
The provided code snippet includes necessary dependencies for implementing the `unique_everseen` function. Write a Python function `def unique_everseen(iterable, key=None)` to solve the following problem:
List unique elements, preserving order. Remember all elements ever seen.
Here i... | List unique elements, preserving order. Remember all elements ever seen. |
186,491 | import os
import pathlib
import tempfile
import functools
import contextlib
import types
import importlib
from typing import Union, Any, Optional
from .abc import ResourceReader, Traversable
from ._adapters import wrap_spec
The provided code snippet includes necessary dependencies for implementing the `_` function. Wr... | Degenerate behavior for pathlib.Path objects. |
186,492 | import os
import io
from . import _common
from ._common import as_file, files
from .abc import ResourceReader
from contextlib import suppress
from importlib.abc import ResourceLoader
from importlib.machinery import ModuleSpec
from io import BytesIO, TextIOWrapper
from pathlib import Path
from types import ModuleType
fr... | Return the binary contents of the resource. |
186,493 | import os
import io
from . import _common
from ._common import as_file, files
from .abc import ResourceReader
from contextlib import suppress
from importlib.abc import ResourceLoader
from importlib.machinery import ModuleSpec
from io import BytesIO, TextIOWrapper
from pathlib import Path
from types import ModuleType
fr... | Return the decoded string of the resource. The decoding-related arguments have the same semantics as those of bytes.decode(). |
186,494 | import os
import io
from . import _common
from ._common import as_file, files
from .abc import ResourceReader
from contextlib import suppress
from importlib.abc import ResourceLoader
from importlib.machinery import ModuleSpec
from io import BytesIO, TextIOWrapper
from pathlib import Path
from types import ModuleType
fr... | True if 'name' is a resource inside 'package'. Directories are *not* resources. |
186,495 | import os
import io
from . import _common
from ._common import as_file, files
from .abc import ResourceReader
from contextlib import suppress
from importlib.abc import ResourceLoader
from importlib.machinery import ModuleSpec
from io import BytesIO, TextIOWrapper
from pathlib import Path
from types import ModuleType
fr... | null |
186,496 |
The provided code snippet includes necessary dependencies for implementing the `_has_deadlocked` function. Write a Python function `def _has_deadlocked(target_id, *, seen_ids, candidate_ids, blocking_on)` to solve the following problem:
Check if 'target_id' is holding the same lock as another thread(s). The search wi... | Check if 'target_id' is holding the same lock as another thread(s). The search within 'blocking_on' starts with the threads listed in 'candidate_ids'. 'seen_ids' contains any threads that are considered already traversed in the search. Keyword arguments: target_id -- The thread id to try to reach. seen_ids -- A set of ... |
186,499 | _warnings = None
def spec_from_loader(name, loader, *, origin=None, is_package=None):
"""Return a module spec based on various loader methods."""
if hasattr(loader, 'get_filename'):
if _bootstrap_external is None:
raise NotImplementedError
spec_from_file_location = _bootstrap_externa... | Load the specified module into sys.modules and return it. This method is deprecated. Use loader.exec_module() instead. |
186,500 | def _module_repr_from_spec(spec):
"""Return the repr to use for the module."""
# We mostly replicate _module_repr() using the spec attributes.
name = '?' if spec.name is None else spec.name
if spec.origin is None:
if spec.loader is None:
return '<module {!r}>'.format(name)
el... | The implementation of ModuleType.__repr__(). |
186,501 | _bootstrap_external = None
def _install(sys_module, _imp_module):
"""Install importers for builtin and frozen modules"""
_setup(sys_module, _imp_module)
sys.meta_path.append(BuiltinImporter)
sys.meta_path.append(FrozenImporter)
try:
import _frozen_importlib_external as _bootstrap_external
except Im... | Install importers that require external filesystem access |
186,502 | import collections
import zipfile
import pathlib
from . import abc
def remove_duplicates(items):
return iter(collections.OrderedDict.fromkeys(items)) | null |
186,507 | import os
import sys
import stat
import genericpath
from genericpath import *
def join(a, *p):
"""Join two or more pathname components, inserting '/' as needed.
If any component is an absolute path, all previous path components
will be discarded. An empty last part will result in a path that
ends with ... | Test whether a path is a mount point |
186,508 | sep = '/'
import os
import sys
import stat
import genericpath
from genericpath import *
def _get_sep(path):
if isinstance(path, bytes):
return b'/'
else:
return '/'
from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep,
devnull)
The provided code snippet includes neces... | Expand ~ and ~user constructions. If user or $HOME is unknown, do nothing. |
186,512 | import re
class TextWrapper:
"""
Object for wrapping/filling text. The public interface consists of
the wrap() and fill() methods; the other methods are just there for
subclasses to override in order to tweak the default behaviour.
If you want to completely replace the main wrapping algorithm,
... | Wrap a single paragraph of text, returning a list of wrapped lines. Reformat the single paragraph in 'text' so it fits in lines of no more than 'width' columns, and return a list of wrapped lines. By default, tabs in 'text' are expanded with string.expandtabs(), and all other whitespace characters (including newline) a... |
186,513 | import re
class TextWrapper:
"""
Object for wrapping/filling text. The public interface consists of
the wrap() and fill() methods; the other methods are just there for
subclasses to override in order to tweak the default behaviour.
If you want to completely replace the main wrapping algorithm,
... | Collapse and truncate the given text to fit in the given width. The text first has its whitespace collapsed. If it then fits in the *width*, it is returned as is. Otherwise, as many words as possible are joined and then the placeholder is appended:: >>> textwrap.shorten("Hello world!", width=12) 'Hello world!' >>> text... |
186,517 | import struct, sys, time, os
import zlib
import builtins
import io
import _compression
_COMPRESS_LEVEL_BEST = 9
class GzipFile(_compression.BaseStream):
"""The GzipFile class simulates most of the methods of a file object with
the exception of the truncate() method.
This class only supports opening files in... | Compress data in one shot and return the compressed string. Optional argument is the compression level, in range of 0-9. |
186,518 | import struct, sys, time, os
import zlib
import builtins
import io
import _compression
class GzipFile(_compression.BaseStream):
"""The GzipFile class simulates most of the methods of a file object with
the exception of the truncate() method.
This class only supports opening files in binary mode. If you need... | Decompress a gzip compressed string in one shot. Return the decompressed string. |
186,522 | import struct
class ZoneInfoNotFoundError(KeyError):
def load_tzdata(key):
import importlib.resources
components = key.split("/")
package_name = ".".join(["tzdata.zoneinfo"] + components[:-1])
resource_name = components[-1]
try:
return importlib.resources.open_binary(package_name, resourc... | null |
186,523 | import struct
class _TZifHeader:
__slots__ = [
"version",
"isutcnt",
"isstdcnt",
"leapcnt",
"timecnt",
"typecnt",
"charcnt",
]
def __init__(self, *args):
for attr, val in zip(self.__slots__, args, strict=True):
setattr(self, attr, v... | null |
186,525 | import bisect
import calendar
import collections
import functools
import re
import weakref
from datetime import datetime, timedelta, tzinfo
from . import _common, _tzpath
def _load_timedelta(seconds):
return timedelta(seconds=seconds)
class _ttinfo:
__slots__ = ["utcoff", "dstoff", "tzname"]
def __init__(se... | null |
186,530 | from pickle import DEFAULT_PROTOCOL, Pickler, Unpickler
from io import BytesIO
import collections.abc
class DbfilenameShelf(Shelf):
"""Shelf implementation using the "dbm" generic dbm interface.
This is initialized with the filename for the dbm database.
See the module's __doc__ string for an overview of th... | Open a persistent dictionary for reading and writing. The filename parameter is the base filename for the underlying database. As a side-effect, an extension may be added to the filename and more than one file may be created. The optional flag parameter has the same interpretation as the flag parameter of dbm.open(). T... |
186,540 | from collections import namedtuple
def what(filename):
from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep,
devnull)
def glob(pathname, *, root_dir=None, dir_fd=None, recursive=False):
def testall(list, recursive, toplevel):
import sys
import os
for filename in list:
if... | null |
186,551 | import re
import struct
import binascii
_b32alphabet = b'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
def _b32encode(alphabet, s):
global _b32tab2
# Delay the initialization of the table to not waste memory
# if the function is never called
if alphabet not in _b32tab2:
b32tab = [bytes((i,)) for i in alphab... | null |
186,552 | import re
import struct
import binascii
_b32alphabet = b'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
def _b32decode(alphabet, s, casefold=False, map01=None):
global _b32rev
# Delay the initialization of the table to not waste memory
# if the function is never called
if alphabet not in _b32rev:
_b32rev[alp... | null |
186,553 | import re
import struct
import binascii
_b32hexalphabet = b'0123456789ABCDEFGHIJKLMNOPQRSTUV'
def _b32encode(alphabet, s):
global _b32tab2
# Delay the initialization of the table to not waste memory
# if the function is never called
if alphabet not in _b32tab2:
b32tab = [bytes((i,)) for i in alp... | null |
186,554 | import re
import struct
import binascii
_b32hexalphabet = b'0123456789ABCDEFGHIJKLMNOPQRSTUV'
def _b32decode(alphabet, s, casefold=False, map01=None):
def b32hexdecode(s, casefold=False):
# base32hex does not have the 01 mapping
return _b32decode(_b32hexalphabet, s, casefold) | null |
186,562 | import warnings as _warnings
try:
import _hashlib as _hashopenssl
except ImportError:
_hashopenssl = None
_functype = None
from _operator import _compare_digest as compare_digest
else:
compare_digest = _hashopenssl.compare_digest
_functype = type(_hashopenssl.openssl_sha256) # builtin type
impo... | Fast inline implementation of HMAC. key: bytes or buffer, The key for the keyed hash object. msg: bytes or buffer, Input message. digest: A hash name suitable for hashlib.new() for best performance. *OR* A hashlib constructor returning a new hash object. *OR* A module supporting PEP 247. |
186,569 | import os
import warnings
import tkinter
from tkinter import *
from tkinter import _cnfmerge
The provided code snippet includes necessary dependencies for implementing the `OptionName` function. Write a Python function `def OptionName(widget)` to solve the following problem:
Returns the qualified path name for the wid... | Returns the qualified path name for the widget. Normally used to set default options for subwidgets. See tixwidgets.py |
186,570 | import os
import warnings
import tkinter
from tkinter import *
from tkinter import _cnfmerge
def FileTypeList(dict):
s = ''
for type in dict.keys():
s = s + '{{' + type + '} {' + type + ' - ' + dict[type] + '}} '
return s | null |
186,571 | from tkinter import _cnfmerge, Widget, TclError, Button, Pack
DIALOG_ICON = 'questhead'
class Dialog(Widget):
def __init__(self, master=None, cnf={}, **kw):
def destroy(self):
def _test():
d = Dialog(None, {'title': 'File Modified',
'text':
'File "Python.h" has... | null |
186,572 | import tkinter
class DndHandler:
def __init__(self, source, event):
def __del__(self):
def on_motion(self, event):
def on_release(self, event):
def cancel(self, event=None):
def finish(self, event, commit=0):
def dnd_start(source, event):
h = DndHandler(source, event)
if h.root is... | null |
186,573 | from tkinter import *
from tkinter import _get_temp_root, _destroy_temp_root
from tkinter import messagebox
def _place_window(w, parent=None):
w.wm_withdraw() # Remain invisible while we figure out the geometry
w.update_idletasks() # Actualize geometry information
minwidth = w.winfo_reqwidth()
minheig... | null |
186,574 | from tkinter import *
from tkinter import _get_temp_root, _destroy_temp_root
from tkinter import messagebox
def _setup_dialog(w):
if w._windowingsystem == "aqua":
w.tk.call("::tk::unsupported::MacWindowStyle", "style",
w, "moveableModal", "")
elif w._windowingsystem == "x11":
... | null |
186,575 | from tkinter import *
from tkinter import _get_temp_root, _destroy_temp_root
from tkinter import messagebox
class _QueryInteger(_QueryDialog):
errormessage = "Not an integer."
def getresult(self):
return self.getint(self.entry.get())
The provided code snippet includes necessary dependencies for impleme... | get an integer from the user Arguments: title -- the dialog title prompt -- the label text **kw -- see SimpleDialog class Return value is an integer |
186,576 | from tkinter import *
from tkinter import _get_temp_root, _destroy_temp_root
from tkinter import messagebox
class _QueryFloat(_QueryDialog):
errormessage = "Not a floating point value."
def getresult(self):
return self.getdouble(self.entry.get())
The provided code snippet includes necessary dependencie... | get a float from the user Arguments: title -- the dialog title prompt -- the label text **kw -- see SimpleDialog class Return value is a float |
186,577 | from tkinter import *
from tkinter import _get_temp_root, _destroy_temp_root
from tkinter import messagebox
class _QueryString(_QueryDialog):
def __init__(self, *args, **kw):
if "show" in kw:
self.__show = kw["show"]
del kw["show"]
else:
self.__show = None
... | get a string from the user Arguments: title -- the dialog title prompt -- the label text **kw -- see SimpleDialog class Return value is a string |
186,579 | import itertools
import tkinter
class Font:
"""Represents a named font.
Constructor options are:
font -- font specifier (name, system font, or (family, size, style)-tuple)
name -- name to use for this font configuration (defaults to a unique name)
exists -- does a named font by this name already exi... | Given the name of a tk named font, returns a Font representation. |
186,580 | import itertools
import tkinter
The provided code snippet includes necessary dependencies for implementing the `families` function. Write a Python function `def families(root=None, displayof=None)` to solve the following problem:
Get font families (as a tuple)
Here is the function:
def families(root=None, displayof=... | Get font families (as a tuple) |
186,605 | import os
import sys
import posixpath
import urllib.parse
_db = None
def init(files=None):
global suffix_map, types_map, encodings_map, common_types
global inited, _db
inited = True # so that MimeTypes.__init__() doesn't call us again
if files is None or _db is None:
db = MimeTypes()
... | Guess the extensions for a file based on its MIME type. Return value is a list of strings giving the possible filename extensions, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). If no ... |
186,606 | import os
import sys
import posixpath
import urllib.parse
_db = None
def init(files=None):
global suffix_map, types_map, encodings_map, common_types
global inited, _db
inited = True # so that MimeTypes.__init__() doesn't call us again
if files is None or _db is None:
db = MimeTypes()
... | Add a mapping between a type and an extension. When the extension is already known, the new type will replace the old one. When the type is already known the extension will be added to the list of known extensions. If strict is true, information will be added to list of standard types, else to the list of non-standard ... |
186,607 | import os
import sys
import posixpath
import urllib.parse
class MimeTypes:
def __init__(self, filenames=(), strict=True):
def add_type(self, type, ext, strict=True):
def guess_type(self, url, strict=True):
def guess_all_extensions(self, type, strict=True):
def guess_extension(self, type, strict... | null |
186,608 | import os
import sys
import posixpath
import urllib.parse
def _default_mime_types():
global suffix_map, _suffix_map_default
global encodings_map, _encodings_map_default
global types_map, _types_map_default
global common_types, _common_types_default
suffix_map = _suffix_map_default = {
'.sv... | null |
186,625 | import base64
import bisect
import email
import hashlib
import http.client
import io
import os
import posixpath
import re
import socket
import string
import sys
import time
import tempfile
import contextlib
import warnings
from urllib.error import URLError, HTTPError, ContentTooShortError
from urllib.parse import (
... | Return a dictionary of scheme -> proxy server URL mappings. Returns settings gathered from the environment, if specified, or the registry. |
186,637 | import re
import sys
import types
import collections
import warnings
from collections import namedtuple
def _splitport(host):
def splitport(host):
warnings.warn("urllib.parse.splitport() is deprecated as of 3.8, "
"use urllib.parse.urlparse() instead",
DeprecationWarning, stackl... | null |
186,638 | import re
import sys
import types
import collections
import warnings
from collections import namedtuple
def _splitnport(host, defport=-1):
"""Split host and port, returning numeric port.
Return given default port if no ':' found; defaults to -1.
Return numerical port if a valid number are found after ':'.
... | null |
186,640 | import re
import sys
import types
import collections
import warnings
from collections import namedtuple
def _splittag(url):
def splittag(url):
warnings.warn("urllib.parse.splittag() is deprecated as of 3.8, "
"use urllib.parse.urlparse() instead",
DeprecationWarning, stacklevel=... | null |
186,643 | def bisect_right(a, x, lo=0, hi=None, *, key=None):
"""Return the index where to insert item x in list a, assuming a is sorted.
The return value i is such that all e in a[:i] have e <= x, and all e in
a[i:] have e > x. So if x already appears in the list, a.insert(i, x) will
insert just after the right... | Insert item x in list a, and keep it sorted assuming a is sorted. If x is already in a, insert it to the right of the rightmost x. Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched. |
186,644 | def bisect_left(a, x, lo=0, hi=None, *, key=None):
"""Return the index where to insert item x in list a, assuming a is sorted.
The return value i is such that all e in a[:i] have e < x, and all e in
a[i:] have e >= x. So if x already appears in the list, a.insert(i, x) will
insert just before the leftm... | Insert item x in list a, and keep it sorted assuming a is sorted. If x is already in a, insert it to the left of the leftmost x. Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched. |
186,647 | import base64
import sys
import time
from datetime import datetime
from decimal import Decimal
import http.client
import urllib.parse
from xml.parsers import expat
import errno
from io import BytesIO
if _try('%Y'): # Mac OS X
def _iso8601_format(value):
return value.strftime("%Y%m%dT%H:%M:%S")
elif _tr... | null |
186,653 | import sys
import types
import collections
import io
from opcode import *
from opcode import __all__ as _opcodes_all
def _get_code_object(x):
"""Helper to handle methods, compiled or raw code objects, and strings."""
# Extract functions from methods.
if hasattr(x, '__func__'):
x = x.__func__
# E... | Iterator for the opcodes in methods, functions or code Generates a series of Instruction named tuples giving the details of each operations in the supplied code. If *first_line* is not None, it indicates the line number that should be reported for the first source line in the disassembled code. Otherwise, the source li... |
186,655 | import collections as _collections
import dataclasses as _dataclasses
import re
import sys as _sys
import types as _types
from io import StringIO as _StringIO
def pprint(object, stream=None, indent=1, width=80, depth=None, *,
compact=False, sort_dicts=True, underscore_numbers=False):
"""Pretty-print a Py... | Pretty-print a Python object |
186,656 | import collections as _collections
import dataclasses as _dataclasses
import re
import sys as _sys
import types as _types
from io import StringIO as _StringIO
class PrettyPrinter:
def __init__(self, indent=1, width=80, depth=None, stream=None, *,
compact=False, sort_dicts=True, underscore_numbers=F... | Version of repr() which can handle recursive data structures. |
186,657 | import collections as _collections
import dataclasses as _dataclasses
import re
import sys as _sys
import types as _types
from io import StringIO as _StringIO
class PrettyPrinter:
def __init__(self, indent=1, width=80, depth=None, stream=None, *,
compact=False, sort_dicts=True, underscore_numbers=F... | Determine if saferepr(object) is readable by eval(). |
186,658 | import collections as _collections
import dataclasses as _dataclasses
import re
import sys as _sys
import types as _types
from io import StringIO as _StringIO
class PrettyPrinter:
def __init__(self, indent=1, width=80, depth=None, stream=None, *,
compact=False, sort_dicts=True, underscore_numbers=F... | Determine if object requires a recursive representation. |
186,659 | import collections as _collections
import dataclasses as _dataclasses
import re
import sys as _sys
import types as _types
from io import StringIO as _StringIO
class _safe_key:
"""Helper function for key functions when sorting unorderable objects.
The wrapped-object will fallback to a Py2.x style comparison for
... | Helper function for comparing 2-tuples |
186,660 | import collections as _collections
import dataclasses as _dataclasses
import re
import sys as _sys
import types as _types
from io import StringIO as _StringIO
def _recursion(object):
return ("<Recursion on %s with id=%s>"
% (type(object).__name__, id(object))) | null |
186,661 | import collections as _collections
import dataclasses as _dataclasses
import re
import sys as _sys
import types as _types
from io import StringIO as _StringIO
def pformat(object, indent=1, width=80, depth=None, *,
compact=False, sort_dicts=True, underscore_numbers=False):
"""Format a Python object into ... | null |
186,662 | import collections as _collections
import dataclasses as _dataclasses
import re
import sys as _sys
import types as _types
from io import StringIO as _StringIO
def _wrap_bytes_repr(object, width, allowance):
current = b''
last = len(object) // 4 * 4
for i in range(0, len(object), 4):
part = object[i... | null |
186,663 | from builtins import open as _builtin_open
import io
import os
import _compression
from _bz2 import BZ2Compressor, BZ2Decompressor
The provided code snippet includes necessary dependencies for implementing the `compress` function. Write a Python function `def compress(data, compresslevel=9)` to solve the following pro... | Compress a block of data. compresslevel, if given, must be a number between 1 and 9. For incremental compression, use a BZ2Compressor object instead. |
186,664 | from builtins import open as _builtin_open
import io
import os
import _compression
from _bz2 import BZ2Compressor, BZ2Decompressor
The provided code snippet includes necessary dependencies for implementing the `decompress` function. Write a Python function `def decompress(data)` to solve the following problem:
Decompr... | Decompress a block of data. For incremental decompression, use a BZ2Decompressor object instead. |
186,667 |
def rgb_to_hls(r, g, b):
maxc = max(r, g, b)
minc = min(r, g, b)
sumc = (maxc+minc)
rangec = (maxc-minc)
l = sumc/2.0
if minc == maxc:
return 0.0, l, 0.0
if l <= 0.5:
s = rangec / sumc
else:
s = rangec / (2.0-sumc)
rc = (maxc-r) / rangec
gc = (maxc-g) / ... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.