prompt_id
int64
0
941
project
stringclasses
24 values
module
stringlengths
7
49
class
stringlengths
0
32
method
stringlengths
2
37
focal_method_txt
stringlengths
43
41.5k
focal_method_lines
listlengths
2
2
in_stack
bool
2 classes
globals
listlengths
0
16
type_context
stringlengths
79
41.9k
has_branch
bool
2 classes
total_branches
int64
0
3
100
httpie
httpie.cli.definition
_AuthTypeLazyChoices
__contains__
def __contains__(self, item): return item in plugin_manager.get_auth_plugin_mapping()
[ 522, 523 ]
false
[ "parser", "positional", "content_type", "content_processing", "output_processing", "_sorted_kwargs", "_unsorted_kwargs", "output_options", "sessions", "session_name_validator", "auth", "_auth_plugins", "network", "ssl", "troubleshooting" ]
from argparse import (FileType, OPTIONAL, SUPPRESS, ZERO_OR_MORE) from textwrap import dedent, wrap from httpie import __doc__, __version__ from httpie.cli.argparser import HTTPieArgumentParser from httpie.cli.argtypes import ( KeyValueArgType, SessionNameValidator, readable_file_arg, ) from httpie.cli.constant...
false
0
101
httpie
httpie.cli.definition
_AuthTypeLazyChoices
__iter__
def __iter__(self): return iter(sorted(plugin_manager.get_auth_plugin_mapping().keys()))
[ 525, 526 ]
false
[ "parser", "positional", "content_type", "content_processing", "output_processing", "_sorted_kwargs", "_unsorted_kwargs", "output_options", "sessions", "session_name_validator", "auth", "_auth_plugins", "network", "ssl", "troubleshooting" ]
from argparse import (FileType, OPTIONAL, SUPPRESS, ZERO_OR_MORE) from textwrap import dedent, wrap from httpie import __doc__, __version__ from httpie.cli.argparser import HTTPieArgumentParser from httpie.cli.argtypes import ( KeyValueArgType, SessionNameValidator, readable_file_arg, ) from httpie.cli.constant...
false
0
102
httpie
httpie.cli.requestitems
process_file_upload_arg
def process_file_upload_arg(arg: KeyValueArg) -> Tuple[str, IO, str]: parts = arg.value.split(SEPARATOR_FILE_UPLOAD_TYPE) filename = parts[0] mime_type = parts[1] if len(parts) > 1 else None try: f = open(os.path.expanduser(filename), 'rb') except IOError as e: raise ParseError('"%s"...
[ 104, 112 ]
false
[ "JSONType" ]
import os from typing import Callable, Dict, IO, List, Optional, Tuple, Union from httpie.cli.argtypes import KeyValueArg from httpie.cli.constants import ( SEPARATORS_GROUP_MULTIPART, SEPARATOR_DATA_EMBED_FILE_CONTENTS, SEPARATOR_DATA_EMBED_RAW_JSON_FILE, SEPARATOR_DATA_RAW_JSON, SEPARATOR_DATA_STRING, SEP...
false
0
103
httpie
httpie.cli.requestitems
process_data_embed_raw_json_file_arg
def process_data_embed_raw_json_file_arg(arg: KeyValueArg) -> JSONType: contents = load_text_file(arg) value = load_json(arg, contents) return value
[ 127, 130 ]
false
[ "JSONType" ]
import os from typing import Callable, Dict, IO, List, Optional, Tuple, Union from httpie.cli.argtypes import KeyValueArg from httpie.cli.constants import ( SEPARATORS_GROUP_MULTIPART, SEPARATOR_DATA_EMBED_FILE_CONTENTS, SEPARATOR_DATA_EMBED_RAW_JSON_FILE, SEPARATOR_DATA_RAW_JSON, SEPARATOR_DATA_STRING, SEP...
false
0
104
httpie
httpie.cli.requestitems
process_data_raw_json_embed_arg
def process_data_raw_json_embed_arg(arg: KeyValueArg) -> JSONType: value = load_json(arg, arg.value) return value
[ 133, 135 ]
false
[ "JSONType" ]
import os from typing import Callable, Dict, IO, List, Optional, Tuple, Union from httpie.cli.argtypes import KeyValueArg from httpie.cli.constants import ( SEPARATORS_GROUP_MULTIPART, SEPARATOR_DATA_EMBED_FILE_CONTENTS, SEPARATOR_DATA_EMBED_RAW_JSON_FILE, SEPARATOR_DATA_RAW_JSON, SEPARATOR_DATA_STRING, SEP...
false
0
105
httpie
httpie.cli.requestitems
load_text_file
def load_text_file(item: KeyValueArg) -> str: path = item.value try: with open(os.path.expanduser(path), 'rb') as f: return f.read().decode() except IOError as e: raise ParseError('"%s": %s' % (item.orig, e)) except UnicodeDecodeError: raise ParseError( '"...
[ 138, 146 ]
false
[ "JSONType" ]
import os from typing import Callable, Dict, IO, List, Optional, Tuple, Union from httpie.cli.argtypes import KeyValueArg from httpie.cli.constants import ( SEPARATORS_GROUP_MULTIPART, SEPARATOR_DATA_EMBED_FILE_CONTENTS, SEPARATOR_DATA_EMBED_RAW_JSON_FILE, SEPARATOR_DATA_RAW_JSON, SEPARATOR_DATA_STRING, SEP...
false
0
106
httpie
httpie.client
collect_messages
def collect_messages( args: argparse.Namespace, config_dir: Path, request_body_read_callback: Callable[[bytes], None] = None, ) -> Iterable[Union[requests.PreparedRequest, requests.Response]]: httpie_session = None httpie_session_headers = None if args.session or args.session_read_only: ...
[ 32, 130 ]
false
[ "FORM_CONTENT_TYPE", "JSON_CONTENT_TYPE", "JSON_ACCEPT", "DEFAULT_UA" ]
import argparse import http.client import json import sys from contextlib import contextmanager from pathlib import Path from typing import Callable, Iterable, Union from urllib.parse import urlparse, urlunparse import requests import urllib3 from httpie import __version__ from httpie.cli.dicts import RequestHeadersDic...
true
2
107
httpie
httpie.client
build_requests_session
def build_requests_session( verify: bool, ssl_version: str = None, ciphers: str = None, ) -> requests.Session: requests_session = requests.Session() # Install our adapter. https_adapter = HTTPieHTTPSAdapter( ciphers=ciphers, verify=verify, ssl_version=( AVAIL...
[ 146, 172 ]
false
[ "FORM_CONTENT_TYPE", "JSON_CONTENT_TYPE", "JSON_ACCEPT", "DEFAULT_UA" ]
import argparse import http.client import json import sys from contextlib import contextmanager from pathlib import Path from typing import Callable, Iterable, Union from urllib.parse import urlparse, urlunparse import requests import urllib3 from httpie import __version__ from httpie.cli.dicts import RequestHeadersDic...
true
2
108
httpie
httpie.client
finalize_headers
def finalize_headers(headers: RequestHeadersDict) -> RequestHeadersDict: final_headers = RequestHeadersDict() for name, value in headers.items(): if value is not None: # “leading or trailing LWS MAY be removed without # changing the semantics of the field value” # <ht...
[ 180, 193 ]
false
[ "FORM_CONTENT_TYPE", "JSON_CONTENT_TYPE", "JSON_ACCEPT", "DEFAULT_UA" ]
import argparse import http.client import json import sys from contextlib import contextmanager from pathlib import Path from typing import Callable, Iterable, Union from urllib.parse import urlparse, urlunparse import requests import urllib3 from httpie import __version__ from httpie.cli.dicts import RequestHeadersDic...
true
2
109
httpie
httpie.client
make_default_headers
def make_default_headers(args: argparse.Namespace) -> RequestHeadersDict: default_headers = RequestHeadersDict({ 'User-Agent': DEFAULT_UA }) auto_json = args.data and not args.form if args.json or auto_json: default_headers['Accept'] = JSON_ACCEPT if args.json or (auto_json and ...
[ 196, 211 ]
false
[ "FORM_CONTENT_TYPE", "JSON_CONTENT_TYPE", "JSON_ACCEPT", "DEFAULT_UA" ]
import argparse import http.client import json import sys from contextlib import contextmanager from pathlib import Path from typing import Callable, Iterable, Union from urllib.parse import urlparse, urlunparse import requests import urllib3 from httpie import __version__ from httpie.cli.dicts import RequestHeadersDic...
true
2
110
httpie
httpie.client
make_send_kwargs
def make_send_kwargs(args: argparse.Namespace) -> dict: kwargs = { 'timeout': args.timeout or None, 'allow_redirects': False, } return kwargs
[ 214, 219 ]
false
[ "FORM_CONTENT_TYPE", "JSON_CONTENT_TYPE", "JSON_ACCEPT", "DEFAULT_UA" ]
import argparse import http.client import json import sys from contextlib import contextmanager from pathlib import Path from typing import Callable, Iterable, Union from urllib.parse import urlparse, urlunparse import requests import urllib3 from httpie import __version__ from httpie.cli.dicts import RequestHeadersDic...
false
0
111
httpie
httpie.client
make_send_kwargs_mergeable_from_env
def make_send_kwargs_mergeable_from_env(args: argparse.Namespace) -> dict: cert = None if args.cert: cert = args.cert if args.cert_key: cert = cert, args.cert_key kwargs = { 'proxies': {p.key: p.value for p in args.proxy}, 'stream': True, 'verify': { ...
[ 222, 239 ]
false
[ "FORM_CONTENT_TYPE", "JSON_CONTENT_TYPE", "JSON_ACCEPT", "DEFAULT_UA" ]
import argparse import http.client import json import sys from contextlib import contextmanager from pathlib import Path from typing import Callable, Iterable, Union from urllib.parse import urlparse, urlunparse import requests import urllib3 from httpie import __version__ from httpie.cli.dicts import RequestHeadersDic...
true
2
112
httpie
httpie.client
make_request_kwargs
def make_request_kwargs( args: argparse.Namespace, base_headers: RequestHeadersDict = None, request_body_read_callback=lambda chunk: chunk ) -> dict: """ Translate our `args` into `requests.Request` keyword arguments. """ files = args.files # Serialize JSON data, if needed. data = a...
[ 242, 296 ]
false
[ "FORM_CONTENT_TYPE", "JSON_CONTENT_TYPE", "JSON_ACCEPT", "DEFAULT_UA" ]
import argparse import http.client import json import sys from contextlib import contextmanager from pathlib import Path from typing import Callable, Iterable, Union from urllib.parse import urlparse, urlunparse import requests import urllib3 from httpie import __version__ from httpie.cli.dicts import RequestHeadersDic...
true
2
113
httpie
httpie.config
get_default_config_dir
def get_default_config_dir() -> Path: """ Return the path to the httpie configuration directory. This directory isn't guaranteed to exist, and nor are any of its ancestors (only the legacy ~/.httpie, if returned, is guaranteed to exist). XDG Base Directory Specification support: <https://...
[ 19, 54 ]
false
[ "ENV_XDG_CONFIG_HOME", "ENV_HTTPIE_CONFIG_DIR", "DEFAULT_CONFIG_DIRNAME", "DEFAULT_RELATIVE_XDG_CONFIG_HOME", "DEFAULT_RELATIVE_LEGACY_CONFIG_DIR", "DEFAULT_WINDOWS_CONFIG_DIR", "DEFAULT_CONFIG_DIR" ]
import errno import json import os from pathlib import Path from typing import Union from httpie import __version__ from httpie.compat import is_windows ENV_XDG_CONFIG_HOME = 'XDG_CONFIG_HOME' ENV_HTTPIE_CONFIG_DIR = 'HTTPIE_CONFIG_DIR' DEFAULT_CONFIG_DIRNAME = 'httpie' DEFAULT_RELATIVE_XDG_CONFIG_HOME = Path('.config...
true
2
114
httpie
httpie.config
BaseConfigDict
ensure_directory
def ensure_directory(self): try: self.path.parent.mkdir(mode=0o700, parents=True) except OSError as e: if e.errno != errno.EEXIST: raise
[ 73, 78 ]
false
[ "ENV_XDG_CONFIG_HOME", "ENV_HTTPIE_CONFIG_DIR", "DEFAULT_CONFIG_DIRNAME", "DEFAULT_RELATIVE_XDG_CONFIG_HOME", "DEFAULT_RELATIVE_LEGACY_CONFIG_DIR", "DEFAULT_WINDOWS_CONFIG_DIR", "DEFAULT_CONFIG_DIR" ]
import errno import json import os from pathlib import Path from typing import Union from httpie import __version__ from httpie.compat import is_windows ENV_XDG_CONFIG_HOME = 'XDG_CONFIG_HOME' ENV_HTTPIE_CONFIG_DIR = 'HTTPIE_CONFIG_DIR' DEFAULT_CONFIG_DIRNAME = 'httpie' DEFAULT_RELATIVE_XDG_CONFIG_HOME = Path('.config...
true
2
115
httpie
httpie.config
BaseConfigDict
load
def load(self): config_type = type(self).__name__.lower() try: with self.path.open('rt') as f: try: data = json.load(f) except ValueError as e: raise ConfigFileError( f'invalid {config_type} f...
[ 83, 96 ]
false
[ "ENV_XDG_CONFIG_HOME", "ENV_HTTPIE_CONFIG_DIR", "DEFAULT_CONFIG_DIRNAME", "DEFAULT_RELATIVE_XDG_CONFIG_HOME", "DEFAULT_RELATIVE_LEGACY_CONFIG_DIR", "DEFAULT_WINDOWS_CONFIG_DIR", "DEFAULT_CONFIG_DIR" ]
import errno import json import os from pathlib import Path from typing import Union from httpie import __version__ from httpie.compat import is_windows ENV_XDG_CONFIG_HOME = 'XDG_CONFIG_HOME' ENV_HTTPIE_CONFIG_DIR = 'HTTPIE_CONFIG_DIR' DEFAULT_CONFIG_DIRNAME = 'httpie' DEFAULT_RELATIVE_XDG_CONFIG_HOME = Path('.config...
true
2
116
httpie
httpie.config
BaseConfigDict
save
def save(self, fail_silently=False): self['__meta__'] = { 'httpie': __version__ } if self.helpurl: self['__meta__']['help'] = self.helpurl if self.about: self['__meta__']['about'] = self.about self.ensure_directory() json_string ...
[ 98, 120 ]
false
[ "ENV_XDG_CONFIG_HOME", "ENV_HTTPIE_CONFIG_DIR", "DEFAULT_CONFIG_DIRNAME", "DEFAULT_RELATIVE_XDG_CONFIG_HOME", "DEFAULT_RELATIVE_LEGACY_CONFIG_DIR", "DEFAULT_WINDOWS_CONFIG_DIR", "DEFAULT_CONFIG_DIR" ]
import errno import json import os from pathlib import Path from typing import Union from httpie import __version__ from httpie.compat import is_windows ENV_XDG_CONFIG_HOME = 'XDG_CONFIG_HOME' ENV_HTTPIE_CONFIG_DIR = 'HTTPIE_CONFIG_DIR' DEFAULT_CONFIG_DIRNAME = 'httpie' DEFAULT_RELATIVE_XDG_CONFIG_HOME = Path('.config...
true
2
117
httpie
httpie.context
Environment
__init__
def __init__(self, devnull=None, **kwargs): """ Use keyword arguments to overwrite any of the class attributes for this instance. """ assert all(hasattr(type(self), attr) for attr in kwargs.keys()) self.__dict__.update(**kwargs) # The original STDERR unaffec...
[ 59, 84 ]
false
[]
import sys import os from pathlib import Path from typing import IO, Optional from httpie.compat import is_windows from httpie.config import DEFAULT_CONFIG_DIR, Config, ConfigFileError from httpie.utils import repr_dict class Environment: is_windows: bool = is_windows config_dir: Path = DEFAULT_CONFIG_DIR ...
true
2
118
httpie
httpie.core
main
def main(args: List[Union[str, bytes]] = sys.argv, env=Environment()) -> ExitStatus: """ The main function. Pre-process args, handle some special types of invocations, and run the main program with error handling. Return exit status code. """ program_name, *args = args env.program_nam...
[ 21, 108 ]
false
[]
import argparse import os import platform import sys from typing import List, Optional, Tuple, Union import requests from pygments import __version__ as pygments_version from requests import __version__ as requests_version from httpie import __version__ as httpie_version from httpie.cli.constants import OUT_REQ_BODY, O...
true
2
119
httpie
httpie.core
get_output_options
def get_output_options( args: argparse.Namespace, message: Union[requests.PreparedRequest, requests.Response] ) -> Tuple[bool, bool]: return { requests.PreparedRequest: ( OUT_REQ_HEAD in args.output_options, OUT_REQ_BODY in args.output_options, ), requests.Res...
[ 111, 115 ]
false
[]
import argparse import os import platform import sys from typing import List, Optional, Tuple, Union import requests from pygments import __version__ as pygments_version from requests import __version__ as requests_version from httpie import __version__ as httpie_version from httpie.cli.constants import OUT_REQ_BODY, O...
false
0
120
httpie
httpie.core
program
def program(args: argparse.Namespace, env: Environment) -> ExitStatus: """ The main program without error handling. """ # TODO: Refactor and drastically simplify, especially so that the separator logic is elsewhere. exit_status = ExitStatus.SUCCESS downloader = None initial_request: Optiona...
[ 127, 217 ]
false
[]
import argparse import os import platform import sys from typing import List, Optional, Tuple, Union import requests from pygments import __version__ as pygments_version from requests import __version__ as requests_version from httpie import __version__ as httpie_version from httpie.cli.constants import OUT_REQ_BODY, O...
true
2
121
httpie
httpie.models
HTTPResponse
iter_lines
def iter_lines(self, chunk_size): return ((line, b'\n') for line in self._orig.iter_lines(chunk_size))
[ 48, 49 ]
false
[]
from typing import Iterable, Optional from urllib.parse import urlsplit class HTTPResponse(HTTPMessage): def iter_lines(self, chunk_size): return ((line, b'\n') for line in self._orig.iter_lines(chunk_size))
false
0
122
httpie
httpie.models
HTTPRequest
iter_body
def iter_body(self, chunk_size): yield self.body
[ 91, 92 ]
false
[]
from typing import Iterable, Optional from urllib.parse import urlsplit class HTTPRequest(HTTPMessage): def iter_body(self, chunk_size): yield self.body
false
0
123
httpie
httpie.models
HTTPRequest
iter_lines
def iter_lines(self, chunk_size): yield self.body, b''
[ 94, 95 ]
false
[]
from typing import Iterable, Optional from urllib.parse import urlsplit class HTTPRequest(HTTPMessage): def iter_lines(self, chunk_size): yield self.body, b''
false
0
124
httpie
httpie.output.formatters.colors
get_lexer
def get_lexer( mime: str, explicit_json=False, body='' ) -> Optional[Type[Lexer]]: # Build candidate mime type and lexer names. mime_types, lexer_names = [mime], [] type_, subtype = mime.split('/', 1) if '+' not in subtype: lexer_names.append(subtype) else: subtype_name, ...
[ 108, 155 ]
false
[ "AUTO_STYLE", "DEFAULT_STYLE", "SOLARIZED_STYLE", "AVAILABLE_STYLES" ]
import json from typing import Optional, Type import pygments.lexer import pygments.lexers import pygments.style import pygments.styles import pygments.token from pygments.formatters.terminal import TerminalFormatter from pygments.formatters.terminal256 import Terminal256Formatter from pygments.lexer import Lexer from ...
true
2
125
httpie
httpie.output.formatters.colors
ColorFormatter
__init__
def __init__( self, env: Environment, explicit_json=False, color_scheme=DEFAULT_STYLE, **kwargs ): super().__init__(**kwargs) if not env.colors: self.enabled = False return use_auto_style = color_scheme == AUTO_STYLE ...
[ 45, 71 ]
false
[ "AUTO_STYLE", "DEFAULT_STYLE", "SOLARIZED_STYLE", "AVAILABLE_STYLES" ]
import json from typing import Optional, Type import pygments.lexer import pygments.lexers import pygments.style import pygments.styles import pygments.token from pygments.formatters.terminal import TerminalFormatter from pygments.formatters.terminal256 import Terminal256Formatter from pygments.lexer import Lexer from ...
true
2
126
httpie
httpie.output.formatters.colors
ColorFormatter
format_headers
def format_headers(self, headers: str) -> str: return pygments.highlight( code=headers, lexer=self.http_lexer, formatter=self.formatter, ).strip()
[ 73, 74 ]
false
[ "AUTO_STYLE", "DEFAULT_STYLE", "SOLARIZED_STYLE", "AVAILABLE_STYLES" ]
import json from typing import Optional, Type import pygments.lexer import pygments.lexers import pygments.style import pygments.styles import pygments.token from pygments.formatters.terminal import TerminalFormatter from pygments.formatters.terminal256 import Terminal256Formatter from pygments.lexer import Lexer from ...
false
0
127
httpie
httpie.output.formatters.colors
ColorFormatter
format_body
def format_body(self, body: str, mime: str) -> str: lexer = self.get_lexer_for_body(mime, body) if lexer: body = pygments.highlight( code=body, lexer=lexer, formatter=self.formatter, ) return body
[ 80, 88 ]
false
[ "AUTO_STYLE", "DEFAULT_STYLE", "SOLARIZED_STYLE", "AVAILABLE_STYLES" ]
import json from typing import Optional, Type import pygments.lexer import pygments.lexers import pygments.style import pygments.styles import pygments.token from pygments.formatters.terminal import TerminalFormatter from pygments.formatters.terminal256 import Terminal256Formatter from pygments.lexer import Lexer from ...
true
2
128
httpie
httpie.output.formatters.colors
ColorFormatter
get_lexer_for_body
def get_lexer_for_body( self, mime: str, body: str ) -> Optional[Type[Lexer]]: return get_lexer( mime=mime, explicit_json=self.explicit_json, body=body, )
[ 90, 94 ]
false
[ "AUTO_STYLE", "DEFAULT_STYLE", "SOLARIZED_STYLE", "AVAILABLE_STYLES" ]
import json from typing import Optional, Type import pygments.lexer import pygments.lexers import pygments.style import pygments.styles import pygments.token from pygments.formatters.terminal import TerminalFormatter from pygments.formatters.terminal256 import Terminal256Formatter from pygments.lexer import Lexer from ...
false
0
129
httpie
httpie.output.formatters.colors
ColorFormatter
get_style_class
@staticmethod def get_style_class(color_scheme: str) -> Type[pygments.style.Style]: try: return pygments.styles.get_style_by_name(color_scheme) except ClassNotFound: return Solarized256Style
[ 101, 105 ]
false
[ "AUTO_STYLE", "DEFAULT_STYLE", "SOLARIZED_STYLE", "AVAILABLE_STYLES" ]
import json from typing import Optional, Type import pygments.lexer import pygments.lexers import pygments.style import pygments.styles import pygments.token from pygments.formatters.terminal import TerminalFormatter from pygments.formatters.terminal256 import Terminal256Formatter from pygments.lexer import Lexer from ...
false
0
130
httpie
httpie.output.formatters.headers
HeadersFormatter
__init__
def __init__(self, **kwargs): super().__init__(**kwargs) self.enabled = self.format_options['headers']['sort']
[ 5, 7 ]
false
[]
from httpie.plugins import FormatterPlugin class HeadersFormatter(FormatterPlugin): def __init__(self, **kwargs): super().__init__(**kwargs) self.enabled = self.format_options['headers']['sort']
false
0
131
httpie
httpie.output.formatters.headers
HeadersFormatter
format_headers
def format_headers(self, headers: str) -> str: """ Sorts headers by name while retaining relative order of multiple headers with the same name. """ lines = headers.splitlines() headers = sorted(lines[1:], key=lambda h: h.split(':')[0]) return '\r\n'.join(line...
[ 9, 17 ]
false
[]
from httpie.plugins import FormatterPlugin class HeadersFormatter(FormatterPlugin): def __init__(self, **kwargs): super().__init__(**kwargs) self.enabled = self.format_options['headers']['sort'] def format_headers(self, headers: str) -> str: """ Sorts headers by name while r...
false
0
132
httpie
httpie.output.formatters.json
JSONFormatter
__init__
def __init__(self, **kwargs): super().__init__(**kwargs) self.enabled = self.format_options['json']['format']
[ 8, 10 ]
false
[]
import json from httpie.plugins import FormatterPlugin class JSONFormatter(FormatterPlugin): def __init__(self, **kwargs): super().__init__(**kwargs) self.enabled = self.format_options['json']['format']
false
0
133
httpie
httpie.output.formatters.json
JSONFormatter
format_body
def format_body(self, body: str, mime: str) -> str: maybe_json = [ 'json', 'javascript', 'text', ] if (self.kwargs['explicit_json'] or any(token in mime for token in maybe_json)): try: obj = json.loads(body) ...
[ 12, 33 ]
false
[]
import json from httpie.plugins import FormatterPlugin class JSONFormatter(FormatterPlugin): def __init__(self, **kwargs): super().__init__(**kwargs) self.enabled = self.format_options['json']['format'] def format_body(self, body: str, mime: str) -> str: maybe_json = [ '...
true
2
134
httpie
httpie.output.processing
Conversion
get_converter
@staticmethod def get_converter(mime: str) -> Optional[ConverterPlugin]: if is_valid_mime(mime): for converter_class in plugin_manager.get_converters(): if converter_class.supports(mime): return converter_class(mime)
[ 18, 22 ]
false
[ "MIME_RE" ]
import re from typing import Optional, List from httpie.plugins import ConverterPlugin from httpie.plugins.registry import plugin_manager from httpie.context import Environment MIME_RE = re.compile(r'^[^/]+/[^/]+$') class Conversion: @staticmethod def get_converter(mime: str) -> Optional[ConverterPlugin]: ...
true
2
135
httpie
httpie.output.processing
Formatting
__init__
def __init__(self, groups: List[str], env=Environment(), **kwargs): """ :param groups: names of processor groups to be applied :param env: Environment :param kwargs: additional keyword arguments for processors """ available_plugins = plugin_manager.get_formatters_gro...
[ 28, 41 ]
false
[ "MIME_RE" ]
import re from typing import Optional, List from httpie.plugins import ConverterPlugin from httpie.plugins.registry import plugin_manager from httpie.context import Environment MIME_RE = re.compile(r'^[^/]+/[^/]+$') class Formatting: def __init__(self, groups: List[str], env=Environment(), **kwargs): """...
true
2
136
httpie
httpie.output.processing
Formatting
format_headers
def format_headers(self, headers: str) -> str: for p in self.enabled_plugins: headers = p.format_headers(headers) return headers
[ 43, 46 ]
false
[ "MIME_RE" ]
import re from typing import Optional, List from httpie.plugins import ConverterPlugin from httpie.plugins.registry import plugin_manager from httpie.context import Environment MIME_RE = re.compile(r'^[^/]+/[^/]+$') class Formatting: def __init__(self, groups: List[str], env=Environment(), **kwargs): """...
true
2
137
httpie
httpie.output.processing
Formatting
format_body
def format_body(self, content: str, mime: str) -> str: if is_valid_mime(mime): for p in self.enabled_plugins: content = p.format_body(content, mime) return content
[ 48, 52 ]
false
[ "MIME_RE" ]
import re from typing import Optional, List from httpie.plugins import ConverterPlugin from httpie.plugins.registry import plugin_manager from httpie.context import Environment MIME_RE = re.compile(r'^[^/]+/[^/]+$') class Formatting: def __init__(self, groups: List[str], env=Environment(), **kwargs): """...
true
2
138
httpie
httpie.output.streams
BaseStream
__init__
def __init__( self, msg: HTTPMessage, with_headers=True, with_body=True, on_body_chunk_downloaded: Callable[[bytes], None] = None ): """ :param msg: a :class:`models.HTTPMessage` subclass :param with_headers: if `True`, headers will be included ...
[ 29, 46 ]
false
[ "BINARY_SUPPRESSED_NOTICE" ]
from itertools import chain from typing import Callable, Iterable, Union from httpie.context import Environment from httpie.models import HTTPMessage from httpie.output.processing import Conversion, Formatting BINARY_SUPPRESSED_NOTICE = ( b'\n' b'+-----------------------------------------+\n' b'| NOTE: bin...
false
0
139
httpie
httpie.output.streams
BaseStream
__iter__
def __iter__(self) -> Iterable[bytes]: """Return an iterator over `self.msg`.""" if self.with_headers: yield self.get_headers() yield b'\r\n\r\n' if self.with_body: try: for chunk in self.iter_body(): yield chunk ...
[ 56, 71 ]
false
[ "BINARY_SUPPRESSED_NOTICE" ]
from itertools import chain from typing import Callable, Iterable, Union from httpie.context import Environment from httpie.models import HTTPMessage from httpie.output.processing import Conversion, Formatting BINARY_SUPPRESSED_NOTICE = ( b'\n' b'+-----------------------------------------+\n' b'| NOTE: bin...
true
2
140
httpie
httpie.output.streams
RawStream
__init__
def __init__(self, chunk_size=CHUNK_SIZE, **kwargs): super().__init__(**kwargs) self.chunk_size = chunk_size
[ 80, 82 ]
false
[ "BINARY_SUPPRESSED_NOTICE" ]
from itertools import chain from typing import Callable, Iterable, Union from httpie.context import Environment from httpie.models import HTTPMessage from httpie.output.processing import Conversion, Formatting BINARY_SUPPRESSED_NOTICE = ( b'\n' b'+-----------------------------------------+\n' b'| NOTE: bin...
false
0
141
httpie
httpie.output.streams
RawStream
iter_body
def iter_body(self) -> Iterable[bytes]: return self.msg.iter_body(self.chunk_size)
[ 84, 85 ]
false
[ "BINARY_SUPPRESSED_NOTICE" ]
from itertools import chain from typing import Callable, Iterable, Union from httpie.context import Environment from httpie.models import HTTPMessage from httpie.output.processing import Conversion, Formatting BINARY_SUPPRESSED_NOTICE = ( b'\n' b'+-----------------------------------------+\n' b'| NOTE: bin...
false
0
142
httpie
httpie.output.streams
EncodedStream
__init__
def __init__(self, env=Environment(), **kwargs): super().__init__(**kwargs) if env.stdout_isatty: # Use the encoding supported by the terminal. output_encoding = env.stdout_encoding else: # Preserve the message encoding. output_encoding = self....
[ 98, 107 ]
false
[ "BINARY_SUPPRESSED_NOTICE" ]
from itertools import chain from typing import Callable, Iterable, Union from httpie.context import Environment from httpie.models import HTTPMessage from httpie.output.processing import Conversion, Formatting BINARY_SUPPRESSED_NOTICE = ( b'\n' b'+-----------------------------------------+\n' b'| NOTE: bin...
true
2
143
httpie
httpie.output.streams
EncodedStream
iter_body
def iter_body(self) -> Iterable[bytes]: for line, lf in self.msg.iter_lines(self.CHUNK_SIZE): if b'\0' in line: raise BinarySuppressedError() yield line.decode(self.msg.encoding) \ .encode(self.output_encoding, 'replace') + lf
[ 109, 113 ]
false
[ "BINARY_SUPPRESSED_NOTICE" ]
from itertools import chain from typing import Callable, Iterable, Union from httpie.context import Environment from httpie.models import HTTPMessage from httpie.output.processing import Conversion, Formatting BINARY_SUPPRESSED_NOTICE = ( b'\n' b'+-----------------------------------------+\n' b'| NOTE: bin...
true
2
144
httpie
httpie.output.streams
PrettyStream
__init__
def __init__( self, conversion: Conversion, formatting: Formatting, **kwargs, ): super().__init__(**kwargs) self.formatting = formatting self.conversion = conversion self.mime = self.msg.content_type.split(';')[0]
[ 128, 136 ]
false
[ "BINARY_SUPPRESSED_NOTICE" ]
from itertools import chain from typing import Callable, Iterable, Union from httpie.context import Environment from httpie.models import HTTPMessage from httpie.output.processing import Conversion, Formatting BINARY_SUPPRESSED_NOTICE = ( b'\n' b'+-----------------------------------------+\n' b'| NOTE: bin...
false
0
145
httpie
httpie.output.streams
PrettyStream
get_headers
def get_headers(self) -> bytes: return self.formatting.format_headers( self.msg.headers).encode(self.output_encoding)
[ 138, 139 ]
false
[ "BINARY_SUPPRESSED_NOTICE" ]
from itertools import chain from typing import Callable, Iterable, Union from httpie.context import Environment from httpie.models import HTTPMessage from httpie.output.processing import Conversion, Formatting BINARY_SUPPRESSED_NOTICE = ( b'\n' b'+-----------------------------------------+\n' b'| NOTE: bin...
false
0
146
httpie
httpie.output.streams
PrettyStream
iter_body
def iter_body(self) -> Iterable[bytes]: first_chunk = True iter_lines = self.msg.iter_lines(self.CHUNK_SIZE) for line, lf in iter_lines: if b'\0' in line: if first_chunk: converter = self.conversion.get_converter(self.mime) ...
[ 142, 161 ]
false
[ "BINARY_SUPPRESSED_NOTICE" ]
from itertools import chain from typing import Callable, Iterable, Union from httpie.context import Environment from httpie.models import HTTPMessage from httpie.output.processing import Conversion, Formatting BINARY_SUPPRESSED_NOTICE = ( b'\n' b'+-----------------------------------------+\n' b'| NOTE: bin...
true
2
147
httpie
httpie.output.streams
PrettyStream
process_body
def process_body(self, chunk: Union[str, bytes]) -> bytes: if not isinstance(chunk, str): # Text when a converter has been used, # otherwise it will always be bytes. chunk = chunk.decode(self.msg.encoding, 'replace') chunk = self.formatting.format_body(content=chu...
[ 163, 169 ]
false
[ "BINARY_SUPPRESSED_NOTICE" ]
from itertools import chain from typing import Callable, Iterable, Union from httpie.context import Environment from httpie.models import HTTPMessage from httpie.output.processing import Conversion, Formatting BINARY_SUPPRESSED_NOTICE = ( b'\n' b'+-----------------------------------------+\n' b'| NOTE: bin...
true
2
148
httpie
httpie.output.streams
BufferedPrettyStream
iter_body
def iter_body(self) -> Iterable[bytes]: # Read the whole body before prettifying it, # but bail out immediately if the body is binary. converter = None body = bytearray() for chunk in self.msg.iter_body(self.CHUNK_SIZE): if not converter and b'\0' in chunk: ...
[ 182, 198 ]
false
[ "BINARY_SUPPRESSED_NOTICE" ]
from itertools import chain from typing import Callable, Iterable, Union from httpie.context import Environment from httpie.models import HTTPMessage from httpie.output.processing import Conversion, Formatting BINARY_SUPPRESSED_NOTICE = ( b'\n' b'+-----------------------------------------+\n' b'| NOTE: bin...
true
2
149
httpie
httpie.output.writer
write_message
def write_message( requests_message: Union[requests.PreparedRequest, requests.Response], env: Environment, args: argparse.Namespace, with_headers=False, with_body=False, ): if not (with_body or with_headers): return write_stream_kwargs = { 'stream': build_output_stream_for_me...
[ 18, 50 ]
false
[ "MESSAGE_SEPARATOR", "MESSAGE_SEPARATOR_BYTES" ]
import argparse import errno from typing import IO, TextIO, Tuple, Type, Union import requests from httpie.context import Environment from httpie.models import HTTPRequest, HTTPResponse from httpie.output.processing import Conversion, Formatting from httpie.output.streams import ( BaseStream, BufferedPrettyStream, ...
true
2
150
httpie
httpie.output.writer
write_stream
def write_stream( stream: BaseStream, outfile: Union[IO, TextIO], flush: bool ): """Write the output stream.""" try: # Writing bytes so we use the buffer interface (Python 3). buf = outfile.buffer except AttributeError: buf = outfile for chunk in stream: buf....
[ 53, 68 ]
false
[ "MESSAGE_SEPARATOR", "MESSAGE_SEPARATOR_BYTES" ]
import argparse import errno from typing import IO, TextIO, Tuple, Type, Union import requests from httpie.context import Environment from httpie.models import HTTPRequest, HTTPResponse from httpie.output.processing import Conversion, Formatting from httpie.output.streams import ( BaseStream, BufferedPrettyStream, ...
true
2
151
httpie
httpie.output.writer
write_stream_with_colors_win_py3
def write_stream_with_colors_win_py3( stream: 'BaseStream', outfile: TextIO, flush: bool ): """Like `write`, but colorized chunks are written as text directly to `outfile` to ensure it gets processed by colorama. Applies only to Windows with Python 3 and colorized terminal output. """ c...
[ 71, 89 ]
false
[ "MESSAGE_SEPARATOR", "MESSAGE_SEPARATOR_BYTES" ]
import argparse import errno from typing import IO, TextIO, Tuple, Type, Union import requests from httpie.context import Environment from httpie.models import HTTPRequest, HTTPResponse from httpie.output.processing import Conversion, Formatting from httpie.output.streams import ( BaseStream, BufferedPrettyStream, ...
true
2
152
httpie
httpie.output.writer
build_output_stream_for_message
def build_output_stream_for_message( args: argparse.Namespace, env: Environment, requests_message: Union[requests.PreparedRequest, requests.Response], with_headers: bool, with_body: bool, ): stream_class, stream_kwargs = get_stream_type_and_kwargs( env=env, args=args, ) m...
[ 92, 117 ]
false
[ "MESSAGE_SEPARATOR", "MESSAGE_SEPARATOR_BYTES" ]
import argparse import errno from typing import IO, TextIO, Tuple, Type, Union import requests from httpie.context import Environment from httpie.models import HTTPRequest, HTTPResponse from httpie.output.processing import Conversion, Formatting from httpie.output.streams import ( BaseStream, BufferedPrettyStream, ...
true
2
153
httpie
httpie.output.writer
get_stream_type_and_kwargs
def get_stream_type_and_kwargs( env: Environment, args: argparse.Namespace ) -> Tuple[Type['BaseStream'], dict]: """Pick the right stream type and kwargs for it based on `env` and `args`. """ if not env.stdout_isatty and not args.prettify: stream_class = RawStream stream_kwargs = { ...
[ 120, 155 ]
false
[ "MESSAGE_SEPARATOR", "MESSAGE_SEPARATOR_BYTES" ]
import argparse import errno from typing import IO, TextIO, Tuple, Type, Union import requests from httpie.context import Environment from httpie.models import HTTPRequest, HTTPResponse from httpie.output.processing import Conversion, Formatting from httpie.output.streams import ( BaseStream, BufferedPrettyStream, ...
true
2
154
httpie
httpie.plugins.base
AuthPlugin
get_auth
def get_auth(self, username=None, password=None): """ If `auth_parse` is set to `True`, then `username` and `password` contain the parsed credentials. Use `self.raw_auth` to access the raw value passed through `--auth, -a`. Return a ``requests.auth.AuthBase`` subcla...
[ 55, 66 ]
false
[]
class AuthPlugin(BasePlugin): auth_type = None auth_require = True auth_parse = True netrc_parse = False prompt_password = True raw_auth = None def get_auth(self, username=None, password=None): """ If `auth_parse` is set to `True`, then `username` and `pass...
false
0
155
httpie
httpie.plugins.base
TransportPlugin
get_adapter
def get_adapter(self): """ Return a ``requests.adapters.BaseAdapter`` subclass instance to be mounted to ``self.prefix``. """ raise NotImplementedError()
[ 84, 90 ]
false
[]
class TransportPlugin(BasePlugin): prefix = None def get_adapter(self): """ Return a ``requests.adapters.BaseAdapter`` subclass instance to be mounted to ``self.prefix``. """ raise NotImplementedError()
false
0
156
httpie
httpie.plugins.base
ConverterPlugin
__init__
def __init__(self, mime): self.mime = mime
[ 103, 104 ]
false
[]
class ConverterPlugin(BasePlugin): def __init__(self, mime): self.mime = mime
false
0
157
httpie
httpie.plugins.base
ConverterPlugin
convert
def convert(self, content_bytes): raise NotImplementedError
[ 106, 107 ]
false
[]
class ConverterPlugin(BasePlugin): def __init__(self, mime): self.mime = mime def convert(self, content_bytes): raise NotImplementedError
false
0
158
httpie
httpie.plugins.base
FormatterPlugin
__init__
def __init__(self, **kwargs): """ :param env: an class:`Environment` instance :param kwargs: additional keyword argument that some formatters might require. """ self.enabled = True self.kwargs = kwargs self.format_options = kwargs['form...
[ 121, 130 ]
false
[]
class FormatterPlugin(BasePlugin): group_name = 'format' def __init__(self, **kwargs): """ :param env: an class:`Environment` instance :param kwargs: additional keyword argument that some formatters might require. """ self.enabled = True ...
false
0
159
httpie
httpie.plugins.base
FormatterPlugin
format_headers
def format_headers(self, headers: str) -> str: """Return processed `headers` :param headers: The headers as text. """ return headers
[ 132, 138 ]
false
[]
class FormatterPlugin(BasePlugin): group_name = 'format' def __init__(self, **kwargs): """ :param env: an class:`Environment` instance :param kwargs: additional keyword argument that some formatters might require. """ self.enabled = True ...
false
0
160
httpie
httpie.plugins.base
FormatterPlugin
format_body
def format_body(self, content: str, mime: str) -> str: """Return processed `content`. :param mime: E.g., 'application/atom+xml'. :param content: The body content as text """ return content
[ 140, 147 ]
false
[]
class FormatterPlugin(BasePlugin): group_name = 'format' def __init__(self, **kwargs): """ :param env: an class:`Environment` instance :param kwargs: additional keyword argument that some formatters might require. """ self.enabled = True ...
false
0
161
httpie
httpie.plugins.manager
PluginManager
filter
def filter(self, by_type=Type[BasePlugin]): return [plugin for plugin in self if issubclass(plugin, by_type)]
[ 27, 28 ]
false
[ "ENTRY_POINT_NAMES" ]
from itertools import groupby from operator import attrgetter from typing import Dict, List, Type from pkg_resources import iter_entry_points from httpie.plugins import AuthPlugin, ConverterPlugin, FormatterPlugin from httpie.plugins.base import BasePlugin, TransportPlugin ENTRY_POINT_NAMES = [ 'httpie.plugins.aut...
false
0
162
httpie
httpie.plugins.manager
PluginManager
load_installed_plugins
def load_installed_plugins(self): for entry_point_name in ENTRY_POINT_NAMES: for entry_point in iter_entry_points(entry_point_name): plugin = entry_point.load() plugin.package_name = entry_point.dist.key self.register(entry_point.load())
[ 30, 35 ]
false
[ "ENTRY_POINT_NAMES" ]
from itertools import groupby from operator import attrgetter from typing import Dict, List, Type from pkg_resources import iter_entry_points from httpie.plugins import AuthPlugin, ConverterPlugin, FormatterPlugin from httpie.plugins.base import BasePlugin, TransportPlugin ENTRY_POINT_NAMES = [ 'httpie.plugins.aut...
true
2
163
httpie
httpie.plugins.manager
PluginManager
get_auth_plugin_mapping
def get_auth_plugin_mapping(self) -> Dict[str, Type[AuthPlugin]]: return { plugin.auth_type: plugin for plugin in self.get_auth_plugins() }
[ 41, 42 ]
false
[ "ENTRY_POINT_NAMES" ]
from itertools import groupby from operator import attrgetter from typing import Dict, List, Type from pkg_resources import iter_entry_points from httpie.plugins import AuthPlugin, ConverterPlugin, FormatterPlugin from httpie.plugins.base import BasePlugin, TransportPlugin ENTRY_POINT_NAMES = [ 'httpie.plugins.aut...
false
0
164
httpie
httpie.plugins.manager
PluginManager
get_formatters_grouped
def get_formatters_grouped(self) -> Dict[str, List[Type[FormatterPlugin]]]: return { group_name: list(group) for group_name, group in groupby(self.get_formatters(), key=attrgetter('group_name')) }
[ 53, 54 ]
false
[ "ENTRY_POINT_NAMES" ]
from itertools import groupby from operator import attrgetter from typing import Dict, List, Type from pkg_resources import iter_entry_points from httpie.plugins import AuthPlugin, ConverterPlugin, FormatterPlugin from httpie.plugins.base import BasePlugin, TransportPlugin ENTRY_POINT_NAMES = [ 'httpie.plugins.aut...
false
0
165
httpie
httpie.sessions
get_httpie_session
def get_httpie_session( config_dir: Path, session_name: str, host: Optional[str], url: str, ) -> 'Session': if os.path.sep in session_name: path = os.path.expanduser(session_name) else: hostname = host or urlsplit(url).netloc.split('@')[-1] if not hostname: # ...
[ 29, 50 ]
false
[ "SESSIONS_DIR_NAME", "DEFAULT_SESSIONS_DIR", "VALID_SESSION_NAME_PATTERN", "SESSION_IGNORED_HEADER_PREFIXES" ]
import os import re from http.cookies import SimpleCookie from pathlib import Path from typing import Iterable, Optional, Union from urllib.parse import urlsplit from requests.auth import AuthBase from requests.cookies import RequestsCookieJar, create_cookie from httpie.cli.dicts import RequestHeadersDict from httpie.c...
true
2
166
httpie
httpie.sessions
Session
__init__
def __init__(self, path: Union[str, Path]): super().__init__(path=Path(path)) self['headers'] = {} self['cookies'] = {} self['auth'] = { 'type': None, 'username': None, 'password': None }
[ 57, 61 ]
false
[ "SESSIONS_DIR_NAME", "DEFAULT_SESSIONS_DIR", "VALID_SESSION_NAME_PATTERN", "SESSION_IGNORED_HEADER_PREFIXES" ]
import os import re from http.cookies import SimpleCookie from pathlib import Path from typing import Iterable, Optional, Union from urllib.parse import urlsplit from requests.auth import AuthBase from requests.cookies import RequestsCookieJar, create_cookie from httpie.cli.dicts import RequestHeadersDict from httpie.c...
false
0
167
httpie
httpie.sessions
Session
update_headers
def update_headers(self, request_headers: RequestHeadersDict): """ Update the session headers with the request ones while ignoring certain name prefixes. """ headers = self.headers for name, value in request_headers.items(): if value is None: ...
[ 67, 97 ]
false
[ "SESSIONS_DIR_NAME", "DEFAULT_SESSIONS_DIR", "VALID_SESSION_NAME_PATTERN", "SESSION_IGNORED_HEADER_PREFIXES" ]
import os import re from http.cookies import SimpleCookie from pathlib import Path from typing import Iterable, Optional, Union from urllib.parse import urlsplit from requests.auth import AuthBase from requests.cookies import RequestsCookieJar, create_cookie from httpie.cli.dicts import RequestHeadersDict from httpie.c...
true
2
168
httpie
httpie.sessions
Session
remove_cookies
def remove_cookies(self, names: Iterable[str]): for name in names: if name in self['cookies']: del self['cookies'][name]
[ 157, 160 ]
false
[ "SESSIONS_DIR_NAME", "DEFAULT_SESSIONS_DIR", "VALID_SESSION_NAME_PATTERN", "SESSION_IGNORED_HEADER_PREFIXES" ]
import os import re from http.cookies import SimpleCookie from pathlib import Path from typing import Iterable, Optional, Union from urllib.parse import urlsplit from requests.auth import AuthBase from requests.cookies import RequestsCookieJar, create_cookie from httpie.cli.dicts import RequestHeadersDict from httpie.c...
true
2
169
httpie
httpie.uploads
prepare_request_body
def prepare_request_body( body: Union[str, bytes, IO, MultipartEncoder, RequestDataDict], body_read_callback: Callable[[bytes], bytes], content_length_header_value: int = None, chunked=False, offline=False, ) -> Union[str, bytes, IO, MultipartEncoder, ChunkedUploadStream]: is_file_like = hasatt...
[ 36, 97 ]
false
[]
import zlib from typing import Callable, IO, Iterable, Tuple, Union from urllib.parse import urlencode import requests from requests.utils import super_len from requests_toolbelt import MultipartEncoder from httpie.cli.dicts import MultipartRequestDataDict, RequestDataDict class ChunkedUploadStream: def __init_...
true
2
170
httpie
httpie.uploads
get_multipart_data_and_content_type
def get_multipart_data_and_content_type( data: MultipartRequestDataDict, boundary: str = None, content_type: str = None, ) -> Tuple[MultipartEncoder, str]: encoder = MultipartEncoder( fields=data.items(), boundary=boundary, ) if content_type: content_type = content_type.s...
[ 100, 117 ]
false
[]
import zlib from typing import Callable, IO, Iterable, Tuple, Union from urllib.parse import urlencode import requests from requests.utils import super_len from requests_toolbelt import MultipartEncoder from httpie.cli.dicts import MultipartRequestDataDict, RequestDataDict def get_multipart_data_and_content_type( ...
true
2
171
httpie
httpie.uploads
compress_request
def compress_request( request: requests.PreparedRequest, always: bool, ): deflater = zlib.compressobj() if isinstance(request.body, str): body_bytes = request.body.encode() elif hasattr(request.body, 'read'): body_bytes = request.body.read() else: body_bytes = request.bod...
[ 120, 137 ]
false
[]
import zlib from typing import Callable, IO, Iterable, Tuple, Union from urllib.parse import urlencode import requests from requests.utils import super_len from requests_toolbelt import MultipartEncoder from httpie.cli.dicts import MultipartRequestDataDict, RequestDataDict def compress_request( request: requests...
true
2
172
httpie
httpie.uploads
ChunkedUploadStream
__iter__
def __iter__(self) -> Iterable[Union[str, bytes]]: for chunk in self.stream: self.callback(chunk) yield chunk
[ 16, 19 ]
false
[]
import zlib from typing import Callable, IO, Iterable, Tuple, Union from urllib.parse import urlencode import requests from requests.utils import super_len from requests_toolbelt import MultipartEncoder from httpie.cli.dicts import MultipartRequestDataDict, RequestDataDict class ChunkedUploadStream: def __init_...
true
2
173
httpie
httpie.uploads
ChunkedMultipartUploadStream
__iter__
def __iter__(self) -> Iterable[Union[str, bytes]]: while True: chunk = self.encoder.read(self.chunk_size) if not chunk: break yield chunk
[ 28, 33 ]
false
[]
import zlib from typing import Callable, IO, Iterable, Tuple, Union from urllib.parse import urlencode import requests from requests.utils import super_len from requests_toolbelt import MultipartEncoder from httpie.cli.dicts import MultipartRequestDataDict, RequestDataDict class ChunkedMultipartUploadStream: ch...
true
2
174
httpie
httpie.utils
load_json_preserve_order
def load_json_preserve_order(s): return json.loads(s, object_pairs_hook=OrderedDict)
[ 13, 14 ]
false
[]
import json import mimetypes import time from collections import OrderedDict from http.cookiejar import parse_ns_headers from pprint import pformat from typing import List, Optional, Tuple import requests.auth def load_json_preserve_order(s): return json.loads(s, object_pairs_hook=OrderedDict)
false
0
175
httpie
httpie.utils
repr_dict
def repr_dict(d: dict) -> str: return pformat(d)
[ 17, 18 ]
false
[]
import json import mimetypes import time from collections import OrderedDict from http.cookiejar import parse_ns_headers from pprint import pformat from typing import List, Optional, Tuple import requests.auth def repr_dict(d: dict) -> str: return pformat(d)
false
0
176
httpie
httpie.utils
humanize_bytes
def humanize_bytes(n, precision=2): # Author: Doug Latornell # Licence: MIT # URL: https://code.activestate.com/recipes/577081/ """Return a humanized string representation of a number of bytes. Assumes `from __future__ import division`. >>> humanize_bytes(1) '1 B' >>> humanize_bytes(10...
[ 21, 64 ]
false
[]
import json import mimetypes import time from collections import OrderedDict from http.cookiejar import parse_ns_headers from pprint import pformat from typing import List, Optional, Tuple import requests.auth def humanize_bytes(n, precision=2): # Author: Doug Latornell # Licence: MIT # URL: https://code...
true
2
177
httpie
httpie.utils
get_content_type
def get_content_type(filename): """ Return the content type for ``filename`` in format appropriate for Content-Type headers, or ``None`` if the file type is unknown to ``mimetypes``. """ mime, encoding = mimetypes.guess_type(filename, strict=False) if mime: content_type = mime ...
[ 76, 88 ]
false
[]
import json import mimetypes import time from collections import OrderedDict from http.cookiejar import parse_ns_headers from pprint import pformat from typing import List, Optional, Tuple import requests.auth def get_content_type(filename): """ Return the content type for ``filename`` in format appropriate ...
true
2
178
httpie
httpie.utils
get_expired_cookies
def get_expired_cookies( headers: List[Tuple[str, str]], now: float = None ) -> List[dict]: now = now or time.time() def is_expired(expires: Optional[float]) -> bool: return expires is not None and expires <= now attr_sets: List[Tuple[str, str]] = parse_ns_headers( value for name,...
[ 91, 113 ]
false
[]
import json import mimetypes import time from collections import OrderedDict from http.cookiejar import parse_ns_headers from pprint import pformat from typing import List, Optional, Tuple import requests.auth def get_expired_cookies( headers: List[Tuple[str, str]], now: float = None ) -> List[dict]: no...
false
0
179
httpie
httpie.utils
ExplicitNullAuth
__call__
def __call__(self, r): return r
[ 72, 73 ]
false
[]
import json import mimetypes import time from collections import OrderedDict from http.cookiejar import parse_ns_headers from pprint import pformat from typing import List, Optional, Tuple import requests.auth class ExplicitNullAuth(requests.auth.AuthBase): def __call__(self, r): return r
false
0
180
isort
isort.exceptions
InvalidSettingsPath
__init__
def __init__(self, settings_path: str): super().__init__( f"isort was told to use the settings_path: {settings_path} as the base directory or " "file that represents the starting point of config file discovery, but it does not " "exist." ) self.settings_pa...
[ 14, 20 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class InvalidSettingsPath(ISortError): def __init__(self, settings_path: str): super().__init__( f"isort was told to use the settings_path: {settings_path} as the base directory or " "file...
false
0
181
isort
isort.exceptions
ExistingSyntaxErrors
__init__
def __init__(self, file_path: str): super().__init__( f"isort was told to sort imports within code that contains syntax errors: " f"{file_path}." ) self.file_path = file_path
[ 26, 31 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class ExistingSyntaxErrors(ISortError): def __init__(self, file_path: str): super().__init__( f"isort was told to sort imports within code that contains syntax errors: " f"{file_path}." ...
false
0
182
isort
isort.exceptions
IntroducedSyntaxErrors
__init__
def __init__(self, file_path: str): super().__init__( f"isort introduced syntax errors when attempting to sort the imports contained within " f"{file_path}." ) self.file_path = file_path
[ 37, 42 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class IntroducedSyntaxErrors(ISortError): def __init__(self, file_path: str): super().__init__( f"isort introduced syntax errors when attempting to sort the imports contained within " f"{f...
false
0
183
isort
isort.exceptions
FileSkipped
__init__
def __init__(self, message: str, file_path: str): super().__init__(message) self.file_path = file_path
[ 48, 50 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class FileSkipped(ISortError): def __init__(self, message: str, file_path: str): super().__init__(message) self.file_path = file_path
false
0
184
isort
isort.exceptions
FileSkipComment
__init__
def __init__(self, file_path: str): super().__init__( f"{file_path} contains an file skip comment and was skipped.", file_path=file_path )
[ 56, 57 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class FileSkipComment(FileSkipped): def __init__(self, file_path: str): super().__init__( f"{file_path} contains an file skip comment and was skipped.", file_path=file_path )
false
0
185
isort
isort.exceptions
FileSkipSetting
__init__
def __init__(self, file_path: str): super().__init__( f"{file_path} was skipped as it's listed in 'skip' setting" " or matches a glob in 'skip_glob' setting", file_path=file_path, )
[ 65, 66 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class FileSkipSetting(FileSkipped): def __init__(self, file_path: str): super().__init__( f"{file_path} was skipped as it's listed in 'skip' setting" " or matches a glob in 'skip_glob' set...
false
0
186
isort
isort.exceptions
ProfileDoesNotExist
__init__
def __init__(self, profile: str): super().__init__( f"Specified profile of {profile} does not exist. " f"Available profiles: {','.join(profiles)}." ) self.profile = profile
[ 76, 81 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class ProfileDoesNotExist(ISortError): def __init__(self, profile: str): super().__init__( f"Specified profile of {profile} does not exist. " f"Available profiles: {','.join(profiles)}." ...
false
0
187
isort
isort.exceptions
FormattingPluginDoesNotExist
__init__
def __init__(self, formatter: str): super().__init__(f"Specified formatting plugin of {formatter} does not exist. ") self.formatter = formatter
[ 87, 89 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class FormattingPluginDoesNotExist(ISortError): def __init__(self, formatter: str): super().__init__(f"Specified formatting plugin of {formatter} does not exist. ") self.formatter = formatter
false
0
188
isort
isort.exceptions
LiteralParsingFailure
__init__
def __init__(self, code: str, original_error: Exception): super().__init__( f"isort failed to parse the given literal {code}. It's important to note " "that isort literal sorting only supports simple literals parsable by " f"ast.literal_eval which gave the exception of {o...
[ 97, 104 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class LiteralParsingFailure(ISortError): def __init__(self, code: str, original_error: Exception): super().__init__( f"isort failed to parse the given literal {code}. It's important to note " ...
false
0
189
isort
isort.exceptions
LiteralSortTypeMismatch
__init__
def __init__(self, kind: type, expected_kind: type): super().__init__( f"isort was told to sort a literal of type {expected_kind} but was given " f"a literal of type {kind}." ) self.kind = kind self.expected_kind = expected_kind
[ 112, 118 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class LiteralSortTypeMismatch(ISortError): def __init__(self, kind: type, expected_kind: type): super().__init__( f"isort was told to sort a literal of type {expected_kind} but was given " ...
false
0
190
isort
isort.exceptions
AssignmentsFormatMismatch
__init__
def __init__(self, code: str): super().__init__( "isort was told to sort a section of assignments, however the given code:\n\n" f"{code}\n\n" "Does not match isort's strict single line formatting requirement for assignment " "sorting:\n\n" "{variab...
[ 126, 136 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class AssignmentsFormatMismatch(ISortError): def __init__(self, code: str): super().__init__( "isort was told to sort a section of assignments, however the given code:\n\n" f"{code}\n\n" ...
false
0
191
isort
isort.exceptions
UnsupportedSettings
__init__
def __init__(self, unsupported_settings: Dict[str, Dict[str, str]]): errors = "\n".join( self._format_option(name, **option) for name, option in unsupported_settings.items() ) super().__init__( "isort was provided settings that it doesn't support:\n\n" f"...
[ 148, 159 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class UnsupportedSettings(ISortError): def __init__(self, unsupported_settings: Dict[str, Dict[str, str]]): errors = "\n".join( self._format_option(name, **option) for name, option in unsupported_sett...
false
0
192
isort
isort.exceptions
UnsupportedEncoding
__init__
def __init__(self, filename: Union[str, Path]): super().__init__(f"Unknown or unsupported encoding in {filename}") self.filename = filename
[ 165, 167 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class UnsupportedEncoding(ISortError): def __init__(self, filename: Union[str, Path]): super().__init__(f"Unknown or unsupported encoding in {filename}") self.filename = filename
false
0
193
isort
isort.exceptions
MissingSection
__init__
def __init__(self, import_module: str, section: str): super().__init__( f"Found {import_module} import while parsing, but {section} was not included " "in the `sections` setting of your config. Please add it before continuing\n" "See https://pycqa.github.io/isort/#custom-...
[ 173, 174 ]
false
[]
from pathlib import Path from typing import Any, Dict, Union from .profiles import profiles class MissingSection(ISortError): def __init__(self, import_module: str, section: str): super().__init__( f"Found {import_module} import while parsing, but {section} was not included " "in...
false
0
194
isort
isort.format
format_simplified
def format_simplified(import_line: str) -> str: import_line = import_line.strip() if import_line.startswith("from "): import_line = import_line.replace("from ", "") import_line = import_line.replace(" import ", ".") elif import_line.startswith("import "): import_line = import_line.re...
[ 20, 28 ]
false
[ "ADDED_LINE_PATTERN", "REMOVED_LINE_PATTERN" ]
import re import sys from datetime import datetime from difflib import unified_diff from pathlib import Path from typing import Optional, TextIO ADDED_LINE_PATTERN = re.compile(r"\+[^+]") REMOVED_LINE_PATTERN = re.compile(r"-[^-]") def format_simplified(import_line: str) -> str: import_line = import_line.strip() ...
true
2
195
isort
isort.format
format_natural
def format_natural(import_line: str) -> str: import_line = import_line.strip() if not import_line.startswith("from ") and not import_line.startswith("import "): if "." not in import_line: return f"import {import_line}" parts = import_line.split(".") end = parts.pop(-1) ...
[ 31, 40 ]
false
[ "ADDED_LINE_PATTERN", "REMOVED_LINE_PATTERN" ]
import re import sys from datetime import datetime from difflib import unified_diff from pathlib import Path from typing import Optional, TextIO ADDED_LINE_PATTERN = re.compile(r"\+[^+]") REMOVED_LINE_PATTERN = re.compile(r"-[^-]") def format_natural(import_line: str) -> str: import_line = import_line.strip() ...
true
2
196
isort
isort.format
ask_whether_to_apply_changes_to_file
def ask_whether_to_apply_changes_to_file(file_path: str) -> bool: answer = None while answer not in ("yes", "y", "no", "n", "quit", "q"): answer = input(f"Apply suggested changes to '{file_path}' [y/n/q]? ") # nosec answer = answer.lower() if answer in ("no", "n"): return Fa...
[ 76, 85 ]
false
[ "ADDED_LINE_PATTERN", "REMOVED_LINE_PATTERN" ]
import re import sys from datetime import datetime from difflib import unified_diff from pathlib import Path from typing import Optional, TextIO ADDED_LINE_PATTERN = re.compile(r"\+[^+]") REMOVED_LINE_PATTERN = re.compile(r"-[^-]") def ask_whether_to_apply_changes_to_file(file_path: str) -> bool: answer = None ...
true
2
197
isort
isort.format
create_terminal_printer
def create_terminal_printer(color: bool, output: Optional[TextIO] = None): if color and colorama_unavailable: no_colorama_message = ( "\n" "Sorry, but to use --color (color_output) the colorama python package is required.\n\n" "Reference: https://pypi.org/project/colorama...
[ 136, 149 ]
false
[ "ADDED_LINE_PATTERN", "REMOVED_LINE_PATTERN" ]
import re import sys from datetime import datetime from difflib import unified_diff from pathlib import Path from typing import Optional, TextIO ADDED_LINE_PATTERN = re.compile(r"\+[^+]") REMOVED_LINE_PATTERN = re.compile(r"-[^-]") class BasicPrinter: ERROR = "ERROR" SUCCESS = "SUCCESS" def __init__(se...
true
2
243
py_backwards
py_backwards.compiler
compile_files
def compile_files(input_: str, output: str, target: CompilationTarget, root: Optional[str] = None) -> CompilationResult: """Compiles all files from input_ to output.""" dependencies = set() start = time() count = 0 for paths in get_input_output_paths(input_, output, root): ...
[ 76, 85 ]
false
[]
from copy import deepcopy from time import time from traceback import format_exc from typing import List, Tuple, Optional from typed_ast import ast3 as ast from astunparse import unparse, dump from autopep8 import fix_code from .files import get_input_output_paths, InputOutput from .transformers import transformers fro...
true
2
244
py_backwards
py_backwards.conf
init_settings
def init_settings(args: Namespace) -> None: if args.debug: settings.debug = True
[ 11, 13 ]
false
[ "settings" ]
from argparse import Namespace settings = Settings() def init_settings(args: Namespace) -> None: if args.debug: settings.debug = True
true
2