id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
173,580
from __future__ import annotations import contextlib import inspect import os import re from typing import Generator import warnings class Generator(Iterator[_T_co], Generic[_T_co, _T_contra, _V_co]): def __next__(self) -> _T_co: ... def send(self, __value: _T_contra) -> _T_co: ... def throw( self,...
Rewrite the message of a warning. Parameters ---------- target_message : str Warning message to match. target_category : Warning Warning type to match. new_message : str New warning message to emit. new_category : Warning or None, default None New warning type to emit. When None, will be the same as target_category.
173,581
import copy from functools import reduce from itertools import product, cycle from operator import mul, add The provided code snippet includes necessary dependencies for implementing the `_process_keys` function. Write a Python function `def _process_keys(left, right)` to solve the following problem: Helper function t...
Helper function to compose cycler keys. Parameters ---------- left, right : iterable of dictionaries or None The cyclers to be composed. Returns ------- keys : set The keys in the composition of the two cyclers.
173,582
import copy from functools import reduce from itertools import product, cycle from operator import mul, add def _cycler(label, itr): """ Create a new `Cycler` object from a property name and iterable of values. Parameters ---------- label : hashable The property key. itr : iterable ...
r""" Concatenate `Cycler`\s, as if chained using `itertools.chain`. The keys must match exactly. Examples -------- >>> num = cycler('a', range(3)) >>> let = cycler('a', 'abc') >>> num.concat(let) cycler('a', [0, 1, 2, 'a', 'b', 'c']) Returns ------- `Cycler` The concatenated cycler.
173,583
import re def get_filetype_from_line(l): m = modeline_re.search(l) if m: return m.group(1) The provided code snippet includes necessary dependencies for implementing the `get_filetype_from_buffer` function. Write a Python function `def get_filetype_from_buffer(buf, max_lines=5)` to solve the following ...
Scan the buffer for modelines and return filetype if one is found.
173,584
import re from io import TextIOWrapper class OptionError(Exception): pass def get_choice_opt(options, optname, allowed, default=None, normcase=False): string = options.get(optname, default) if normcase: string = string.lower() if string not in allowed: raise OptionError('Value for optio...
null
173,585
import re from io import TextIOWrapper class OptionError(Exception): pass def get_bool_opt(options, optname, default=None): string = options.get(optname, default) if isinstance(string, bool): return string elif isinstance(string, int): return bool(string) elif not isinstance(string,...
null
173,586
import re from io import TextIOWrapper class OptionError(Exception): pass def get_int_opt(options, optname, default=None): string = options.get(optname, default) try: return int(string) except TypeError: raise OptionError('Invalid type %r for option %s; you ' '...
null
173,587
import re from io import TextIOWrapper class OptionError(Exception): pass def get_list_opt(options, optname, default=None): val = options.get(optname, default) if isinstance(val, str): return val.split() elif isinstance(val, (list, tuple)): return list(val) else: raise Optio...
null
173,588
import re from io import TextIOWrapper The provided code snippet includes necessary dependencies for implementing the `make_analysator` function. Write a Python function `def make_analysator(f)` to solve the following problem: Return a static text analyser function that returns float values. Here is the function: de...
Return a static text analyser function that returns float values.
173,589
import re from io import TextIOWrapper split_path_re = re.compile(r'[/\\ ]') The provided code snippet includes necessary dependencies for implementing the `shebang_matches` function. Write a Python function `def shebang_matches(text, regex)` to solve the following problem: r"""Check if the given regular expression ma...
r"""Check if the given regular expression matches the last part of the shebang if one exists. >>> from pygments.util import shebang_matches >>> shebang_matches('#!/usr/bin/env python', r'python(2\.\d)?') True >>> shebang_matches('#!/usr/bin/python2.4', r'python(2\.\d)?') True >>> shebang_matches('#!/usr/bin/python-ruby...
173,590
import re from io import TextIOWrapper def doctype_matches(text, regex): """Check if the doctype matches a regular expression (if present). Note that this method only checks the first part of a DOCTYPE. eg: 'html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"' """ m = doctype_lookup_re.search(text) i...
Check if the file looks like it has a html doctype.
173,591
import re from io import TextIOWrapper doctype_lookup_re = re.compile(r''' <!DOCTYPE\s+( [a-zA-Z_][a-zA-Z0-9]* (?: \s+ # optional in HTML5 [a-zA-Z_][a-zA-Z0-9]*\s+ "[^"]*")? ) [^>]*> ''', re.DOTALL | re.MULTILINE | re.VERBOSE) tag_re = re.compile(r'<(.+?)(\s.*?)?>.*?</.+?>', ...
Check if a doctype exists or if we have some tags.
173,592
import re from io import TextIOWrapper The provided code snippet includes necessary dependencies for implementing the `surrogatepair` function. Write a Python function `def surrogatepair(c)` to solve the following problem: Given a unicode character code with length greater than 16 bits, return the two 16 bit surrogate...
Given a unicode character code with length greater than 16 bits, return the two 16 bit surrogate pair.
173,593
import re from io import TextIOWrapper The provided code snippet includes necessary dependencies for implementing the `duplicates_removed` function. Write a Python function `def duplicates_removed(it, already_seen=())` to solve the following problem: Returns a list with duplicates removed from the iterable `it`. Order...
Returns a list with duplicates removed from the iterable `it`. Order is preserved.
173,594
import re import sys import time from pygments.filter import apply_filters, Filter from pygments.filters import get_filter_by_name from pygments.token import Error, Text, Other, Whitespace, _TokenType from pygments.util import get_bool_opt, get_int_opt, get_list_opt, \ make_analysator, Future, guess_decode from pyg...
Helper for lexers which must combine the results of several sublexers. ``insertions`` is a list of ``(index, itokens)`` pairs. Each ``itokens`` iterable should be inserted at position ``index`` into the token stream given by the ``tokens`` argument. The result is a combined token stream. TODO: clean up the code here.
173,595
codes = {} codes[""] = "" codes["reset"] = esc + "39;49;00m" codes["bold"] = esc + "01m" codes["faint"] = esc + "02m" codes["standout"] = esc + "03m" codes["underline"] = esc + "04m" codes["blink"] = esc + "05m" codes["overline"] = esc + "06m" codes["white"] = codes["bold"] def reset_color(): return codes["reset"]
null
173,596
codes = {} codes[""] = "" codes["reset"] = esc + "39;49;00m" codes["bold"] = esc + "01m" codes["faint"] = esc + "02m" codes["standout"] = esc + "03m" codes["underline"] = esc + "04m" codes["blink"] = esc + "05m" codes["overline"] = esc + "06m" codes["white"] = codes["bold"] def colorize(color_key, text): return co...
null
173,597
codes = {} codes[""] = "" codes["reset"] = esc + "39;49;00m" codes["bold"] = esc + "01m" codes["faint"] = esc + "02m" codes["standout"] = esc + "03m" codes["underline"] = esc + "04m" codes["blink"] = esc + "05m" codes["overline"] = esc + "06m" codes["white"] = codes["bold"] The provided code snippet includes necessary...
Format ``text`` with a color and/or some attributes:: color normal color *color* bold color _color_ underlined color +color+ blinking color
173,598
import os import sys import shutil import argparse from textwrap import dedent from pygments import __version__, highlight from pygments.util import ClassNotFound, OptionError, docstring_headline, \ guess_decode, guess_decode_from_terminal, terminal_encoding, \ UnclosingTextIOWrapper from pygments.lexers import...
null
173,599
import sys from docutils import nodes from docutils.statemachine import ViewList from docutils.parsers.rst import Directive from sphinx.util.nodes import nested_parse_with_titles class PygmentsDoc(Directive): """ A directive to collect all lexers/formatters/filters and generate autoclass directives for them...
null
173,600
LEXER_ENTRY_POINT = 'pygments.lexers' def iter_entry_points(group_name): try: from importlib.metadata import entry_points except ImportError: try: from importlib_metadata import entry_points except ImportError: try: from pkg_resources import iter_e...
null
173,601
FORMATTER_ENTRY_POINT = 'pygments.formatters' def iter_entry_points(group_name): try: from importlib.metadata import entry_points except ImportError: try: from importlib_metadata import entry_points except ImportError: try: from pkg_resources impor...
null
173,602
STYLE_ENTRY_POINT = 'pygments.styles' def iter_entry_points(group_name): try: from importlib.metadata import entry_points except ImportError: try: from importlib_metadata import entry_points except ImportError: try: from pkg_resources import iter_e...
null
173,603
FILTER_ENTRY_POINT = 'pygments.filters' def iter_entry_points(group_name): try: from importlib.metadata import entry_points except ImportError: try: from importlib_metadata import entry_points except ImportError: try: from pkg_resources import iter...
null
173,604
The provided code snippet includes necessary dependencies for implementing the `apply_filters` function. Write a Python function `def apply_filters(stream, filters, lexer=None)` to solve the following problem: Use this method to apply an iterable of filters to a stream. If lexer is given it's forwarded to the filter,...
Use this method to apply an iterable of filters to a stream. If lexer is given it's forwarded to the filter, otherwise the filter receives `None`.
173,605
class FunctionFilter(Filter): """ Abstract class used by `simplefilter` to create simple function filters on the fly. The `simplefilter` decorator automatically creates subclasses of this class for functions passed to it. """ function = None def __init__(self, **options): if not ...
Decorator that converts a function into a filter:: @simplefilter def lowercase(self, lexer, stream, options): for ttype, value in stream: yield ttype, value.lower()
173,606
import re from pygments.lexer import Lexer, RegexLexer, bygroups, words, do_insertions, \ include, default, line_re from pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Generic, Whitespace class include(str): # pylint: disable=invalid-name """ Indicates that a st...
null
173,607
import re from pygments.lexer import Lexer, RegexLexer, bygroups, words, do_insertions, \ include, default, line_re from pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Generic, Whitespace class include(str): # pylint: disable=invalid-name """ Indicates that a st...
null
173,608
import re from pygments.lexer import ExtendedRegexLexer, RegexLexer, default, words, \ bygroups, include, using, line_re from pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace, Literal, Error, Generic from pygments.lexers.shell import BashLexer from pygments...
null
173,609
import re from pygments.lexer import RegexLexer, include, bygroups, using, this, words, \ inherit, default from pygments.token import Text, Keyword, Name, String, Operator, \ Number, Punctuation, Literal, Comment from pygments.lexers.c_cpp import CLexer, CppLexer class include(str): # pylint: disable=invalid-...
Generate a subclass of baselexer that accepts the Objective-C syntax extensions.
173,610
if __name__ == '__main__': # pragma: no cover import re from urllib.request import urlopen from pygments.util import format_lines # One man's constant is another man's variable. SOURCE_URL = 'https://github.com/postgres/postgres/raw/master' KEYWORDS_URL = SOURCE_URL + '/src/include/parser/kwlis...
null
173,611
if __name__ == '__main__': # pragma: no cover import glob import os import pprint import re import shutil import tarfile from urllib.request import urlretrieve PHP_MANUAL_URL = 'http://us3.php.net/distributions/manual/php_manual_en.tar.gz' PHP_MANUAL_DIR = './php-chunked-xht...
null
173,612
import re from pygments.lexer import RegexLexer, bygroups from pygments.token import Comment, Name, Text, Punctuation, String, Keyword def _create_tag_line_pattern(inner_pattern, ignore_case=False): return ((r"(?i)" if ignore_case else r"") + r"^(##)( *)" # groups 1, 2 + inner_pattern # group 3 ...
null
173,613
import re from pygments.lexer import RegexLexer, include, bygroups, using, words, \ DelegatingLexer, default from pygments.lexers.c_cpp import CppLexer, CLexer from pygments.lexers.d import DLexer from pygments.token import Text, Name, Number, String, Comment, Punctuation, \ Other, Keyword, Operator, Whitespace...
Common objdump lexer tokens to wrap an ASM lexer.
173,614
MYSQL_DATATYPES = ( # Numeric data types 'bigint', 'bit', 'bool', 'boolean', 'dec', 'decimal', 'double', 'fixed', 'float', 'float4', 'float8', 'int', 'int1', 'int2', 'int3', 'int4', 'int8', 'integer', 'mediumint', 'middleint', 'nume...
null
173,615
import re import copy from pygments.lexer import ExtendedRegexLexer, RegexLexer, include, bygroups, \ default, words, inherit from pygments.token import Comment, Operator, Keyword, Name, String, Number, \ Punctuation, Whitespace from pygments.lexers._css_builtins import _css_properties Whitespace = Text.Whites...
null
173,616
import re import copy from pygments.lexer import ExtendedRegexLexer, RegexLexer, include, bygroups, \ default, words, inherit from pygments.token import Comment, Operator, Keyword, Name, String, Number, \ Punctuation, Whitespace from pygments.lexers._css_builtins import _css_properties def _starts_block(token,...
null
173,617
import re from pygments.lexer import Lexer, RegexLexer, do_insertions, bygroups, words from pygments.token import Punctuation, Whitespace, Text, Comment, Operator, \ Keyword, Name, String, Number, Generic, Literal from pygments.lexers import get_lexer_by_name, ClassNotFound from pygments.lexers._postgres_builtins i...
Parse the content of a $-string using a lexer The lexer is chosen looking for a nearby LANGUAGE or assumed as plpgsql if inside a DO statement and no LANGUAGE has been found.
173,618
import re from pygments.lexer import bygroups, default, inherit, words from pygments.lexers.lisp import SchemeLexer from pygments.lexers._lilypond_builtins import ( keywords, pitch_language_names, clefs, scales, repeat_types, units, chord_modifiers, pitches, music_functions, dynamics, articulations, music_c...
null
173,619
import re from pygments.lexer import Lexer from pygments.token import Token def normalize(string, remove=''): string = string.lower() for char in remove + ' ': if char in string: string = string.replace(char, '') return string
null
173,620
def extract_completion(var_type): s = subprocess.Popen(['scilab', '-nwni'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output = s.communicate('''\ fd = mopen("/dev/stderr", "wt"); mputl(strcat(completion("", "%s"), "||"), fd); mclose(fd)\n''' % ...
null
173,621
from pygments.lexer import RegexLexer, bygroups from pygments.lexer import words as words_ from pygments.lexers._usd_builtins import COMMON_ATTRIBUTES, KEYWORDS, \ OPERATORS, SPECIAL_NAMES, TYPES from pygments.token import Comment, Keyword, Name, Number, Operator, \ Punctuation, String, Text, Whitespace def _k...
null
173,622
from pygments.lexer import RegexLexer, words, include, bygroups, using, \ this, default from pygments.token import Text, Comment, Operator, Keyword, Name, \ Number, Punctuation, String, Whitespace def _shortened(word): dpos = word.find('$') return '|'.join(word[:dpos] + word[dpos+1:i] + r'\b' ...
null
173,623
if __name__ == '__main__': # pragma: no cover import re from urllib.request import FancyURLopener from pygments.util import format_lines opener = Opener() def get_version(): def get_sm_functions(): def regenerate(filename, natives): run() def run(): version = get_version() ...
null
173,624
if __name__ == '__main__': # pragma: no cover import re from urllib.request import urlopen import pprint # you can't generally find out what module a function belongs to if you # have only its name. Because of this, here are some callback functions # that recognize if a gioven function belongs ...
null
173,625
from pygments.lexer import include, RegexLexer, words from pygments.token import Comment, Keyword, Name, Number, Operator, \ Punctuation, String, Text, Whitespace String = Literal.String def string_rules(quote_mark): return [ (r"[^{}\\]".format(quote_mark), String), (r"\\.", String.Escape), ...
null
173,626
from pygments.lexer import include, RegexLexer, words from pygments.token import Comment, Keyword, Name, Number, Operator, \ Punctuation, String, Text, Whitespace Name = Token.Name def quoted_field_name(quote_mark): return [ (r'([^{quote}\\]|\\.)*{quote}'.format(quote=quote_mark), Name.Variab...
null
173,627
def _getauto(): var = ( ('BufAdd','BufAdd'), ('BufCreate','BufCreate'), ('BufDelete','BufDelete'), ('BufEnter','BufEnter'), ('BufFilePost','BufFilePost'), ('BufFilePre','BufFilePre'), ('BufHidden','BufHidden'), ('BufLeave','BufLeave'), ('BufN...
null
173,628
def _getcommand(): var = ( ('a','a'), ('ab','ab'), ('abc','abclear'), ('abo','aboveleft'), ('al','all'), ('ar','ar'), ('ar','args'), ('arga','argadd'), ('argd','argdelete'), ('argdo','argdo'), ('arge','argedit'), ('arg...
null
173,629
def _getoption(): var = ( ('acd','acd'), ('ai','ai'), ('akm','akm'), ('al','al'), ('aleph','aleph'), ('allowrevins','allowrevins'), ('altkeymap','altkeymap'), ('ambiwidth','ambiwidth'), ('ambw','ambw'), ('anti','anti'), ('anti...
null
173,630
def combine(*args): return ''.join(globals()[cat] for cat in args)
null
173,631
cats = ['Cc', 'Cf', 'Cn', 'Co', 'Cs', 'Ll', 'Lm', 'Lo', 'Lt', 'Lu', 'Mc', 'Me', 'Mn', 'Nd', 'Nl', 'No', 'Pc', 'Pd', 'Pe', 'Pf', 'Pi', 'Po', 'Ps', 'Sc', 'Sk', 'Sm', 'So', 'Zl', 'Zp', 'Zs'] def allexcept(*args): newcats = cats[:] for arg in args: newcats.remove(arg) return ''.join(globals()[cat] for ...
null
173,632
def _handle_runs(char_list): # pragma: no cover buf = [] for c in char_list: if len(c) == 1: if buf and buf[-1][1] == chr(ord(c)-1): buf[-1] = (buf[-1][0], c) else: buf.append((c, c)) else: buf.append((c, c)) for a, b in ...
null
173,633
import functools import os import sys import os.path from io import StringIO from pygments.formatter import Formatter from pygments.token import Token, Text, STANDARD_TYPES from pygments.util import get_bool_opt, get_int_opt, get_list_opt _escape_html_table = { ord('&'): '&amp;', ord('<'): '&lt;', ord('>'):...
Escape &, <, > as well as single and double quotes for HTML.
173,634
import functools import os import sys import os.path from io import StringIO from pygments.formatter import Formatter from pygments.token import Token, Text, STANDARD_TYPES from pygments.util import get_bool_opt, get_int_opt, get_list_opt def webify(color): if color.startswith('calc') or color.startswith('var'): ...
null
173,635
import functools import os import sys import os.path from io import StringIO from pygments.formatter import Formatter from pygments.token import Token, Text, STANDARD_TYPES from pygments.util import get_bool_opt, get_int_opt, get_list_opt STANDARD_TYPES = { Token: '', Text: ...
null
173,636
from pygments.formatter import Formatter from pygments.token import Comment from pygments.util import get_bool_opt, get_int_opt The provided code snippet includes necessary dependencies for implementing the `escape_html` function. Write a Python function `def escape_html(text)` to solve the following problem: Escape &...
Escape &, <, > as well as single and double quotes for HTML.
173,637
from pygments.formatter import Formatter from pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Token, Whitespace from pygments.util import get_choice_opt IRC_COLOR_MAP = { 'white': 0, 'black': 1, 'blue': 2, 'brightgreen': 3, 'brightred': 4, 'yellow': ...
null
173,638
from pygments.formatter import Formatter _escape_table = { ord('&'): '&amp;', ord('<'): '&lt;', } The provided code snippet includes necessary dependencies for implementing the `escape_special_chars` function. Write a Python function `def escape_special_chars(text, table=_escape_table)` to solve the following ...
Escape & and < for Pango Markup.
173,639
from io import StringIO from pygments.formatter import Formatter from pygments.lexer import Lexer, do_insertions from pygments.token import Token, STANDARD_TYPES from pygments.util import get_bool_opt, get_int_opt def escape_tex(text, commandprefix): return text.replace('\\', '\x00'). \ replace('{'...
null
173,640
from io import StringIO from pygments.formatter import Formatter from pygments.lexer import Lexer, do_insertions from pygments.token import Token, STANDARD_TYPES from pygments.util import get_bool_opt, get_int_opt STANDARD_TYPES = { Token: '', Text: '', Whi...
null
173,641
The provided code snippet includes necessary dependencies for implementing the `is_token_subtype` function. Write a Python function `def is_token_subtype(ttype, other)` to solve the following problem: Return True if ``ttype`` is a subtype of ``other``. exists for backwards compatibility. use ``ttype in other`` now. ...
Return True if ``ttype`` is a subtype of ``other``. exists for backwards compatibility. use ``ttype in other`` now.
173,642
class _TokenType(tuple): parent = None def split(self): buf = [] node = self while node is not None: buf.append(node) node = node.parent buf.reverse() return buf def __init__(self, *args): # no need to call super.__init__ self.s...
Convert a string into a token type:: >>> string_to_token('String.Double') Token.Literal.String.Double >>> string_to_token('Token.Literal.Number') Token.Literal.Number >>> string_to_token('') Token Tokens that are already tokens are returned unchanged: >>> string_to_token(String) Token.Literal.String
173,643
from pygments.style import Style from pygments.token import Comment, Error, Generic, Keyword, Name, Number, \ Operator, String, Token Token = _TokenType() Error = Token.Error Keyword = Token.Keyword Name = Token.Name String = Literal.String Number = Literal.Number Operator = Token.Operator Comment = Token.Commen...
null
173,644
import re from re import escape from os.path import commonprefix from itertools import groupby from operator import itemgetter def regex_opt_inner(strings, open_paren): """Return a regex that matches any string in the sorted list of strings.""" close_paren = open_paren and ')' or '' # print strings, repr(op...
Return a compiled regex that matches any string in the given list. The strings to match must be literal strings, not regexes. They will be regex-escaped. *prefix* and *suffix* are pre- and appended to the final regex.
173,645
import codecs from pygments.util import get_bool_opt from pygments.styles import get_style_by_name def get_style_by_name(name): if name in STYLE_MAP: mod, cls = STYLE_MAP[name].split('::') builtin = "yes" else: for found_name, style in find_plugin_styles(): if name == found_...
null
173,646
The provided code snippet includes necessary dependencies for implementing the `only` function. Write a Python function `def only(iterable, default=None, too_long=None)` to solve the following problem: If *iterable* has only one item, return it. If it has zero items, return *default*. If it has more than one item, ra...
If *iterable* has only one item, return it. If it has zero items, return *default*. If it has more than one item, raise the exception given by *too_long*, which is ``ValueError`` by default. >>> only([], default='missing') 'missing' >>> only([1]) 1 >>> only([1, 2]) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most re...
173,647
import functools import os import pathlib import types import warnings from typing import Union, Iterable, ContextManager, BinaryIO, TextIO, Any from . import _common def deprecated(func): @functools.wraps(func) def wrapper(*args, **kwargs): warnings.warn( f"{func.__name__} is deprecated. U...
null
173,648
import functools import os import pathlib import types import warnings from typing import Union, Iterable, ContextManager, BinaryIO, TextIO, Any from . import _common Package = Union[types.ModuleType, str] Resource = str def normalize_path(path: Any) -> str: """Normalize a path by ensuring it is a string. If th...
Return a file-like object opened for binary reading of the resource.
173,649
import functools import os import pathlib import types import warnings from typing import Union, Iterable, ContextManager, BinaryIO, TextIO, Any from . import _common Package = Union[types.ModuleType, str] Resource = str def normalize_path(path: Any) -> str: """Normalize a path by ensuring it is a string. If th...
Return the binary contents of the resource.
173,650
import functools import os import pathlib import types import warnings from typing import Union, Iterable, ContextManager, BinaryIO, TextIO, Any from . import _common Package = Union[types.ModuleType, str] Resource = str def open_text( package: Package, resource: Resource, encoding: str = 'utf-8', error...
Return the decoded string of the resource. The decoding-related arguments have the same semantics as those of bytes.decode().
173,651
import functools import os import pathlib import types import warnings from typing import Union, Iterable, ContextManager, BinaryIO, TextIO, Any from . import _common Package = Union[types.ModuleType, str] def path( package: Package, resource: Resource, ) -> ContextManager[pathlib.Path]: """A context manage...
Return an iterable of entries in `package`. Note that not all entries are resources. Specifically, directories are not considered resources. Use `is_resource()` on each entry returned here to check if it is a resource or not.
173,652
import functools import os import pathlib import types import warnings from typing import Union, Iterable, ContextManager, BinaryIO, TextIO, Any from . import _common Package = Union[types.ModuleType, str] def normalize_path(path: Any) -> str: """Normalize a path by ensuring it is a string. If the resulting str...
True if `name` is a resource inside `package`. Directories are *not* resources.
173,653
import os import pathlib import tempfile import functools import contextlib import types import importlib import inspect import warnings import itertools from typing import Union, Optional, cast from .abc import ResourceReader, Traversable from ._compat import wrap_spec The provided code snippet includes necessary dep...
Replace 'package' parameter as 'anchor' and warn about the change. Other errors should fall through. >>> files('a', 'b') Traceback (most recent call last): TypeError: files() takes from 0 to 1 positional arguments but 2 were given
173,654
import os import pathlib import tempfile import functools import contextlib import types import importlib import inspect import warnings import itertools from typing import Union, Optional, cast from .abc import ResourceReader, Traversable from ._compat import wrap_spec def _(cand: str) -> types.ModuleType: return...
null
173,655
import os import pathlib import tempfile import functools import contextlib import types import importlib import inspect import warnings import itertools from typing import Union, Optional, cast from .abc import ResourceReader, Traversable from ._compat import wrap_spec def resolve(cand: Optional[Anchor]) -> types.Modu...
null
173,656
import os import pathlib import tempfile import functools import contextlib import types import importlib import inspect import warnings import itertools from typing import Union, Optional, cast from .abc import ResourceReader, Traversable from ._compat import wrap_spec The provided code snippet includes necessary dep...
Degenerate behavior for pathlib.Path objects.
173,657
from contextlib import suppress from io import TextIOWrapper from . import abc class TextIOWrapper(TextIOBase, TextIO): def __init__( self, buffer: IO[bytes], encoding: Optional[str] = ..., errors: Optional[str] = ..., newline: Optional[str] = ..., line_buffering: bo...
null
173,658
from contextlib import suppress from io import TextIOWrapper from . import abc class SpecLoaderAdapter: """ Adapt a package spec to adapt the underlying loader. """ def __init__(self, spec, adapter=lambda spec: spec.loader): self.spec = spec self.loader = adapter(spec) def __getattr_...
Construct a package spec with traversable compatibility on the spec/loader/reader.
173,659
import abc import os import sys import pathlib from contextlib import suppress from typing import Union def runtime_checkable(cls): # type: ignore return cls
null
173,660
import collections import itertools import pathlib import operator from . import abc from ._itertools import only from ._compat import ZipPath def remove_duplicates(items): return iter(collections.OrderedDict.fromkeys(items))
null
173,661
import re import sys from ast import literal_eval from functools import total_ordering from typing import NamedTuple, Sequence, Union def literal_eval(node_or_string: Union[str, AST]) -> Any: ... Union: _SpecialForm = ... The provided code snippet includes necessary dependencies for implementing the `python_bytes_to...
Checks for unicode BOMs and PEP 263 encoding declarations. Then returns a unicode object like in :py:meth:`bytes.decode`. :param encoding: See :py:meth:`bytes.decode` documentation. :param errors: See :py:meth:`bytes.decode` documentation. ``errors`` can be ``'strict'``, ``'replace'`` or ``'ignore'``.
173,662
import re import difflib from collections import namedtuple import logging from parso.utils import split_lines from parso.python.parser import Parser from parso.python.tree import EndMarker from parso.python.tokenize import PythonToken, BOM_UTF8_STRING from parso.python.token import PythonTokenTypes def _is_indentation...
null
173,663
import re import difflib from collections import namedtuple import logging from parso.utils import split_lines from parso.python.parser import Parser from parso.python.tree import EndMarker from parso.python.tokenize import PythonToken, BOM_UTF8_STRING from parso.python.token import PythonTokenTypes def _get_indentatio...
null
173,664
import re import difflib from collections import namedtuple import logging from parso.utils import split_lines from parso.python.parser import Parser from parso.python.tree import EndMarker from parso.python.tokenize import PythonToken, BOM_UTF8_STRING from parso.python.token import PythonTokenTypes _INDENTATION_TOKENS...
Checks if the parent/children relationship is correct. This is a check that only runs during debugging/testing.
173,665
import re import difflib from collections import namedtuple import logging from parso.utils import split_lines from parso.python.parser import Parser from parso.python.tree import EndMarker from parso.python.tokenize import PythonToken, BOM_UTF8_STRING from parso.python.token import PythonTokenTypes def _assert_nodes_...
null
173,666
import re import difflib from collections import namedtuple import logging from parso.utils import split_lines from parso.python.parser import Parser from parso.python.tree import EndMarker from parso.python.tokenize import PythonToken, BOM_UTF8_STRING from parso.python.token import PythonTokenTypes def split_lines(st...
null
173,667
import re import difflib from collections import namedtuple import logging from parso.utils import split_lines from parso.python.parser import Parser from parso.python.tree import EndMarker from parso.python.tokenize import PythonToken, BOM_UTF8_STRING from parso.python.token import PythonTokenTypes def _ends_with_newl...
null
173,668
import re import difflib from collections import namedtuple import logging from parso.utils import split_lines from parso.python.parser import Parser from parso.python.tree import EndMarker from parso.python.tokenize import PythonToken, BOM_UTF8_STRING from parso.python.token import PythonTokenTypes def _func_or_class...
null
173,669
import re import difflib from collections import namedtuple import logging from parso.utils import split_lines from parso.python.parser import Parser from parso.python.tree import EndMarker from parso.python.tokenize import PythonToken, BOM_UTF8_STRING from parso.python.token import PythonTokenTypes def _flows_finished...
null
173,670
import re import difflib from collections import namedtuple import logging from parso.utils import split_lines from parso.python.parser import Parser from parso.python.tree import EndMarker from parso.python.tokenize import PythonToken, BOM_UTF8_STRING from parso.python.token import PythonTokenTypes def _is_flow_node(...
null
173,671
import re import difflib from collections import namedtuple import logging from parso.utils import split_lines from parso.python.parser import Parser from parso.python.tree import EndMarker from parso.python.tokenize import PythonToken, BOM_UTF8_STRING from parso.python.token import PythonTokenTypes class _PositionUpda...
null
173,672
import re from typing import Tuple from parso.tree import Node, BaseNode, Leaf, ErrorNode, ErrorLeaf, search_ancestor from parso.python.prefix import split_prefix from parso.utils import split_lines class Param(PythonBaseNode): """ It's a helper class that makes business logic with params much easier. The ...
`argslist_list` is a list that can contain an argslist as a first item, but most not. It's basically the items between the parameter brackets (which is at most one item). This function modifies the parser structure. It generates `Param` objects from the normal ast. Those param objects do not exist in a normal ast, but ...
173,673
import re from typing import Tuple from parso.tree import Node, BaseNode, Leaf, ErrorNode, ErrorLeaf, search_ancestor from parso.python.prefix import split_prefix from parso.utils import split_lines The provided code snippet includes necessary dependencies for implementing the `_defined_names` function. Write a Pytho...
A helper function to find the defined names in statements, for loops and list comprehensions.
173,674
import re from contextlib import contextmanager from typing import Tuple from parso.python.errors import ErrorFinder, ErrorFinderConfig from parso.normalizer import Rule from parso.python.tree import Flow, Scope def _is_magic_name(name): return name.value.startswith('__') and name.value.endswith('__')
null
173,675
import codecs import warnings import re from contextlib import contextmanager from parso.normalizer import Normalizer, NormalizerConfig, Issue, Rule from parso.python.tokenize import _get_token_collection def _get_comprehension_type(atom): first, second = atom.children[:2] if second.type == 'testlist_comp' and ...
null
173,676
import codecs import warnings import re from contextlib import contextmanager from parso.normalizer import Normalizer, NormalizerConfig, Issue, Rule from parso.python.tokenize import _get_token_collection The provided code snippet includes necessary dependencies for implementing the `_skip_parens_bottom_up` function. ...
Returns an ancestor node of an expression, skipping all levels of parens bottom-up.
173,677
import codecs import warnings import re from contextlib import contextmanager from parso.normalizer import Normalizer, NormalizerConfig, Issue, Rule from parso.python.tokenize import _get_token_collection def _iter_params(parent_node): return (n for n in parent_node.children if n.type == 'param' or n.type == 'oper...
null
173,678
import codecs import warnings import re from contextlib import contextmanager from parso.normalizer import Normalizer, NormalizerConfig, Issue, Rule from parso.python.tokenize import _get_token_collection def _iter_stmts(scope): """ Iterates over all statements and splits up simple_stmt. """ for child ...
Checks if the import is the first statement of a file.
173,679
import codecs import warnings import re from contextlib import contextmanager from parso.normalizer import Normalizer, NormalizerConfig, Issue, Rule from parso.python.tokenize import _get_token_collection def _iter_definition_exprs_from_lists(exprlist): def check_expr(child): if child.type == 'atom': ...
null