id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
35,354
from __future__ import unicode_literals import itertools import struct _compat_int_types = (int,) try: _compat_int_types = (int, long) except NameError: pass def _compat_int_from_byte_vals(bytvals, endianess): assert endianess == 'big' res = 0 for bv in bytvals: assert isins...
null
35,355
from __future__ import unicode_literals import itertools import struct def _compat_range(start, end, step=1): assert step > 0 i = start while i < end: yield i i += step
null
35,356
from __future__ import unicode_literals import itertools import struct class AddressValueError(ValueError): """A Value Error related to the address.""" class NetmaskValueError(ValueError): """A Value Error related to the netmask.""" class IPv4Interface(IPv4Address): def __init__(self, address): if i...
Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Interface or IPv6Interface object. Raises: ValueError: if the string passe...
35,357
from __future__ import unicode_literals import itertools import struct def _compat_to_bytes(intval, length, endianess): assert isinstance(intval, _compat_int_types) assert endianess == 'big' if length == 4: if intval < 0 or intval >= 2 ** 32: raise struct.error("integer out of range for ...
Represent an address as 4 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv4 IP address. Returns: The integer address packed as 4 bytes in network (big-endian) order. Raises: ValueError: If the integer is negative or too large to be an IPv4 IP address.
35,358
from __future__ import unicode_literals import itertools import struct def _compat_to_bytes(intval, length, endianess): assert isinstance(intval, _compat_int_types) assert endianess == 'big' if length == 4: if intval < 0 or intval >= 2 ** 32: raise struct.error("integer out of range for ...
Represent an address as 16 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv6 IP address. Returns: The integer address packed as 16 bytes in network (big-endian) order.
35,359
from __future__ import unicode_literals import itertools import struct try: _compat_str = unicode except NameError: _compat_str = str assert bytes != str class AddressValueError(ValueError): """A Value Error related to the address.""" The provided code snippet includes necessary dependencies for implem...
Helper to split the netmask and raise AddressValueError if needed
35,360
from __future__ import unicode_literals import itertools import struct def _find_address_range(addresses): """Find a sequence of sorted deduplicated IPv#Address. Args: addresses: a list of IPv#Address objects. Yields: A tuple containing the first and last IP addresses in the sequence. ""...
Collapse a list of IP objects. Example: collapse_addresses([IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]) -> [IPv4Network('192.0.2.0/24')] Args: addresses: An iterator of IPv4Network or IPv6Network objects. Returns: An iterator of the collapsed IPv(4|6)Network objects. Raises: TypeError: If passed a list...
35,361
from __future__ import unicode_literals import itertools import struct class _BaseAddress(_IPAddressBase): """A generic IP object. This IP class contains the version independent methods which are used by single IP addresses. """ __slots__ = () def __int__(self): return self._ip def _...
Return a key suitable for sorting between networks and addresses. Address and Network objects are not sortable by default; they're fundamentally different so the expression IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24') doesn't make any sense. There are some times however, where you may wish to have ipaddress ...
35,362
import codecs from html.entities import codepoint2name import re import logging import string try: # First try the fast C implementation. # PyPI package: cchardet import cchardet except ImportError: try: # Fall back to the pure Python implementation # Debian package: python-chardet ...
null
35,363
import codecs from html.entities import codepoint2name import re import logging import string def chardet_dammit(s): if isinstance(s, str): return None return chardet.detect(s)['encoding']
null
35,364
import codecs from html.entities import codepoint2name import re import logging import string def chardet_dammit(s): return None
null
35,365
from io import BytesIO from io import StringIO from lxml import etree from thirdparty.bs4.element import ( Comment, Doctype, NamespacedAttribute, ProcessingInstruction, XMLProcessingInstruction, ) from thirdparty.bs4.builder import ( FAST, HTML, HTMLTreeBuilder, PERMISSIVE, Parse...
Invert a dictionary.
35,366
from html.parser import HTMLParser import sys import warnings from thirdparty.bs4.element import ( CData, Comment, Declaration, Doctype, ProcessingInstruction, ) from thirdparty.bs4.dammit import EntitySubstitution, UnicodeDammit from thirdparty.bs4.builder import ( HTML, HTMLTreeBuilder...
null
35,367
import re import sys import warnings from thirdparty.bs4.formatter import ( Formatter, HTMLFormatter, XMLFormatter, ) The provided code snippet includes necessary dependencies for implementing the `_alias` function. Write a Python function `def _alias(attr)` to solve the following problem: Alias one attrib...
Alias one attribute name to another for backward compatibility
35,368
import cProfile from io import StringIO from html.parser import HTMLParser from thirdparty import bs4 from thirdparty.bs4 import BeautifulSoup, __version__ from thirdparty.bs4.builder import builder_registry import os import pstats import random import tempfile import time import traceback import sys import cProfile _...
Diagnostic suite for isolating common problems. :param data: A string containing markup that needs to be explained. :return: None; diagnostics are printed to standard output.
35,369
import cProfile from io import StringIO from html.parser import HTMLParser from thirdparty import bs4 from thirdparty.bs4 import BeautifulSoup, __version__ from thirdparty.bs4.builder import builder_registry import os import pstats import random import tempfile import time import traceback import sys import cProfile T...
Print out the lxml events that occur during parsing. This lets you see how lxml parses a document when no Beautiful Soup code is running. You can use this to determine whether an lxml-specific problem is in Beautiful Soup's lxml tree builders or in lxml itself. :param data: Some markup. :param html: If True, markup wil...
35,370
import cProfile from io import StringIO from html.parser import HTMLParser from thirdparty import bs4 from thirdparty.bs4 import BeautifulSoup, __version__ from thirdparty.bs4.builder import builder_registry import os import pstats import random import tempfile import time import traceback import sys import cProfile cl...
Print out the HTMLParser events that occur during parsing. This lets you see how HTMLParser parses a document when no Beautiful Soup code is running. :param data: Some markup.
35,371
import cProfile from io import StringIO from html.parser import HTMLParser from thirdparty import bs4 from thirdparty.bs4 import BeautifulSoup, __version__ from thirdparty.bs4.builder import builder_registry import os import pstats import random import tempfile import time import traceback import sys import cProfile de...
Very basic head-to-head performance benchmark.
35,372
import cProfile from io import StringIO from html.parser import HTMLParser from thirdparty import bs4 from thirdparty.bs4 import BeautifulSoup, __version__ from thirdparty.bs4.builder import builder_registry import os import pstats import random import tempfile import time import traceback import sys import cProfile de...
Use Python's profiler on a randomly generated document.
35,373
from __future__ import absolute_import, division, unicode_literals import re import warnings from .constants import DataLossWarning reChar = re.compile(r"#x([\d|A-F]{4,4})") reCharRange = re.compile(r"\[#x([\d|A-F]{4,4})-#x([\d|A-F]{4,4})\]") def normaliseCharList(charList): charList = sorted(charList) for item...
null
35,374
from __future__ import absolute_import, division, unicode_literals import re import warnings from .constants import DataLossWarning max_unicode = int("FFFF", 16) def missingRanges(charList): rv = [] if charList[0] != 0: rv.append([0, charList[0][0] - 1]) for i, item in enumerate(charList[:-1]): ...
null
35,375
from __future__ import absolute_import, division, unicode_literals import re import warnings from .constants import DataLossWarning def escapeRegexp(string): specialCharacters = (".", "^", "$", "*", "+", "?", "{", "}", "[", "]", "|", "(", ")", "-") for char in specialCharacters: ...
null
35,376
from __future__ import absolute_import, division, unicode_literals from types import ModuleType from six import text_type, PY3 def moduleFactoryFactory(factory): moduleCache = {} def moduleFactory(baseModule, *args, **kwargs): if isinstance(ModuleType.__name__, type("")): name = "_%s_facto...
null
35,377
from __future__ import absolute_import, division, unicode_literals from types import ModuleType from six import text_type, PY3 def memoize(func): cache = {} def wrapped(*args, **kwargs): key = (tuple(args), tuple(kwargs.items())) if key not in cache: cache[key] = func(*args, **kwar...
null
35,378
from __future__ import absolute_import, division, unicode_literals from collections import OrderedDict import re from six import string_types from . import base from .._utils import moduleFactoryFactory tag_regexp = re.compile("{([^}]*)}(.*)") def getETreeBuilder(ElementTreeImplementation): ElementTree = ElementTr...
null
35,379
from __future__ import absolute_import, division, unicode_literals from six import text_type from collections import OrderedDict from lxml import etree from ..treebuilders.etree import tag_regexp from . import base from .. import _ihatexml def ensure_str(s): if s is None: return None elif isinstance(s,...
null
35,380
from __future__ import absolute_import, division, unicode_literals from genshi.core import QName, Attrs from genshi.core import START, END, TEXT, COMMENT, DOCTYPE The provided code snippet includes necessary dependencies for implementing the `to_genshi` function. Write a Python function `def to_genshi(walker)` to solv...
Convert a tree to a genshi tree :arg walker: the treewalker to use to walk the tree to convert it :returns: generator of genshi nodes
35,381
from __future__ import absolute_import, division, unicode_literals from xml.sax.xmlreader import AttributesNSImpl from ..constants import adjustForeignAttributes, unadjustForeignAttributes prefix_mapping = {} for prefix, localName, namespace in adjustForeignAttributes.values(): if prefix is not None: prefix...
Call SAX-like content handler based on treewalker walker :arg walker: the treewalker to use to walk the tree to convert it :arg handler: SAX handler to use
35,382
from __future__ import absolute_import, division, unicode_literals from six import text_type from six.moves import http_client, urllib import codecs import re from io import BytesIO, StringIO import webencodings from .constants import EOF, spaceCharacters, asciiLetters, asciiUppercase from .constants import _ReparseExc...
null
35,383
from __future__ import absolute_import, division, unicode_literals from six import text_type from six.moves import http_client, urllib import codecs import re from io import BytesIO, StringIO import webencodings from .constants import EOF, spaceCharacters, asciiLetters, asciiUppercase from .constants import _ReparseExc...
Return the python codec name corresponding to an encoding or None if the string doesn't correspond to a valid encoding.
35,384
from __future__ import absolute_import, division, unicode_literals from xml.dom import minidom, Node import weakref from . import base from .. import constants from ..constants import namespaces from .._utils import moduleFactoryFactory namespaces = { "html": "http://www.w3.org/1999/xhtml", "mathml": "http://w...
null
35,385
from __future__ import absolute_import, division, unicode_literals from six import text_type import re from copy import copy from . import base from .. import _ihatexml from .. import constants from ..constants import namespaces from .._utils import moduleFactoryFactory tag_regexp = re.compile("{([^}]*)}(.*)") namespa...
null
35,386
from __future__ import absolute_import, division, unicode_literals import warnings import re import sys from . import base from ..constants import DataLossWarning from .. import constants from . import etree as etree_builders from .. import _ihatexml import lxml.etree as etree from six import PY3, binary_type tag_regex...
null
35,387
from __future__ import absolute_import, division, unicode_literals import warnings import re import sys from . import base from ..constants import DataLossWarning from .. import constants from . import etree as etree_builders from .. import _ihatexml import lxml.etree as etree from six import PY3, binary_type comment_t...
Serialize an element and its child nodes to a string
35,388
from __future__ import absolute_import, division, unicode_literals from six import with_metaclass, viewkeys import types from . import _inputstream from . import _tokenizer from . import treebuilders from .treebuilders.base import Marker from . import _utils from .constants import ( spaceCharacters, asciiUpper2Lowe...
Parse an HTML fragment as a string or file-like object into a tree :arg doc: the fragment to parse as a string or file-like object :arg container: the container context to parse the fragment in :arg treebuilder: the treebuilder to use when parsing :arg namespaceHTMLElements: whether or not to namespace HTML elements :r...
35,389
from __future__ import absolute_import, division, unicode_literals from six import with_metaclass, viewkeys import types from . import _inputstream from . import _tokenizer from . import treebuilders from .treebuilders.base import Marker from . import _utils from .constants import ( spaceCharacters, asciiUpper2Lowe...
null
35,390
from __future__ import absolute_import, division, unicode_literals from six import with_metaclass, viewkeys import types from . import _inputstream from . import _tokenizer from . import treebuilders from .treebuilders.base import Marker from . import _utils from .constants import ( spaceCharacters, asciiUpper2Lowe...
null
35,391
from __future__ import absolute_import, division, unicode_literals from six import text_type import re from codecs import register_error, xmlcharrefreplace_errors from .constants import voidElements, booleanAttributes, spaceCharacters from .constants import rcdataElements, entities, xmlEntities from . import treewalker...
null
35,392
from __future__ import absolute_import, division, unicode_literals from six import text_type import re from codecs import register_error, xmlcharrefreplace_errors from .constants import voidElements, booleanAttributes, spaceCharacters from .constants import rcdataElements, entities, xmlEntities from . import treewalker...
Serializes the input token stream using the specified treewalker :arg input: the token stream to serialize :arg tree: the treewalker to use :arg encoding: the encoding to use :arg serializer_opts: any options to pass to the :py:class:`html5lib.serializer.HTMLSerializer` that gets created :returns: the tree serialized a...
35,393
from __future__ import absolute_import, division, unicode_literals import re from . import base from ..constants import rcdataElements, spaceCharacters SPACES_REGEX = re.compile("[%s]+" % spaceCharacters) def collapse_spaces(text): return SPACES_REGEX.sub(' ', text)
null
35,394
from __future__ import absolute_import, division, unicode_literals from . import base from collections import OrderedDict The provided code snippet includes necessary dependencies for implementing the `_attr_key` function. Write a Python function `def _attr_key(attr)` to solve the following problem: Return an appropri...
Return an appropriate key for an attribute for sorting Attributes have a namespace that can be either ``None`` or a string. We can't compare the two because they're different types, so we convert ``None`` to an empty string first.
35,395
import re import datetime from warnings import warn COL_NAMES = {} def xl_col_to_name(col, col_abs=False): """ Convert a zero indexed column cell reference to a string. Args: col: The cell column. Int. col_abs: Optional flag to make the column absolute. Bool. Returns: Column st...
Optimized version of the xl_rowcol_to_cell function. Only used internally. Args: row: The cell row. Int. col: The cell column. Int. Returns: A1 style string.
35,396
import re import datetime from warnings import warn range_parts = re.compile(r'(\$?)([A-Z]{1,3})(\$?)(\d+)') The provided code snippet includes necessary dependencies for implementing the `xl_cell_to_rowcol_abs` function. Write a Python function `def xl_cell_to_rowcol_abs(cell_str)` to solve the following problem: Con...
Convert an absolute cell reference in A1 notation to a zero indexed row and column, with True/False values for absolute rows or columns. Args: cell_str: A1 style string. Returns: row, col, row_abs, col_abs: Zero indexed cell row and column indices.
35,397
import re import datetime from warnings import warn def xl_rowcol_to_cell(row, col, row_abs=False, col_abs=False): """ Convert a zero indexed row and column cell reference to a A1 style string. Args: row: The cell row. Int. col: The cell column. Int. row_abs: Optional flag to...
Convert zero indexed row and col cell references to a A1:B1 range string. Args: first_row: The first cell row. Int. first_col: The first cell column. Int. last_row: The last cell row. Int. last_col: The last cell column. Int. Returns: A1:B1 style range string.
35,398
import re import datetime from warnings import warn def xl_range_abs(first_row, first_col, last_row, last_col): """ Convert zero indexed row and col cell references to a $A$1:$B$1 absolute range string. Args: first_row: The first cell row. Int. first_col: The first cell column. Int. ...
Convert worksheet name and zero indexed row and col cell references to a Sheet1!A1:B1 range formula string. Args: sheetname: The worksheet name. String. first_row: The first cell row. Int. first_col: The first cell column. Int. last_row: The last cell row. Int. last_col: The last cell column. Int. Returns: A1:B1 style ...
35,399
import re import datetime from warnings import warn def xl_color(color): # Used in conjunction with the XlsxWriter *color() methods to convert # a color name into an RGB formatted string. These colors are for # backward compatibility with older versions of Excel. named_colors = { 'black': '#0000...
null
35,400
import re import datetime from warnings import warn def get_sparkline_style(style_id): styles = [ {'series': {'theme': "4", 'tint': "-0.499984740745262"}, 'negative': {'theme': "5"}, 'markers': {'theme': "4", 'tint': "-0.499984740745262"}, 'first': {'theme': "4", 'tint': "0...
null
35,401
import re import datetime from warnings import warn def supported_datetime(dt): # Determine is an argument is a supported datetime object. return(isinstance(dt, (datetime.datetime, datetime.date, datetime.time, datetime.timedelta)...
null
35,402
import re import datetime from warnings import warn def remove_datetime_timezone(dt_obj, remove_timezone): # Excel doesn't support timezones in datetimes/times so we remove the # tzinfo from the object if the user has specified that option in the # constructor. if remove_timezone: dt_obj = dt_ob...
null
35,403
import codecs import datetime import os import re import sys import tempfile from collections import defaultdict from collections import namedtuple from math import isnan from math import isinf from warnings import warn from .compatibility import StringIO from .compatibility import force_unicode from .compatibility imp...
Decorator function to convert A1 notation in cell method calls to the default row/col notation.
35,404
import codecs import datetime import os import re import sys import tempfile from collections import defaultdict from collections import namedtuple from math import isnan from math import isinf from warnings import warn from .compatibility import StringIO from .compatibility import force_unicode from .compatibility imp...
Decorator function to convert A1 notation in range method calls to the default row/col notation.
35,405
import codecs import datetime import os import re import sys import tempfile from collections import defaultdict from collections import namedtuple from math import isnan from math import isinf from warnings import warn from .compatibility import StringIO from .compatibility import force_unicode from .compatibility imp...
Decorator function to convert A1 notation in columns method calls to the default row/col notation.
35,406
import sys from decimal import Decimal from fractions import Fraction if sys.version_info[0] == 2: int_types = (int, long) num_types = (float, int, long, Decimal, Fraction) str_types = basestring else: int_types = (int) num_types = (float, int, Decimal, Fraction) str_types = str The provided co...
Return string as a native string
35,407
import struct def pack_string(s): if s is None: return struct.pack(">h", -1) l = len(s) return struct.pack(">H%dsb" % l, l, s.encode('utf8'), 0)
null
35,408
import struct def unpack(stream, fmt): def unpack_string(stream): size, = unpack(stream, ">h") if size == -1: # null string return None res, = unpack(stream, "%ds" % size) stream.read(1) # \0 return res
null
35,411
from __future__ import absolute_import import platform from ctypes import ( CDLL, CFUNCTYPE, POINTER, c_bool, c_byte, c_char_p, c_int32, c_long, c_size_t, c_uint32, c_ulong, c_void_p, ) from ctypes.util import find_library from urllib3.packages.six import raise_from versi...
Loads a CDLL by name, falling back to known path on 10.16+
35,414
import base64 import ctypes import itertools import os import re import ssl import struct import tempfile from .bindings import CFConst, CoreFoundation, Security _PEM_CERTS_RE = re.compile( b"-----BEGIN CERTIFICATE-----\n(.*?)\n-----END CERTIFICATE-----", re.DOTALL ) def _cf_data_from_bytes(bytestring): """ ...
Given a bundle of certs in PEM format, turns them into a CFArray of certs that can be used to validate a cert chain.
35,418
from __future__ import absolute_import import contextlib import ctypes import errno import os.path import shutil import socket import ssl import struct import threading import weakref import six from .. import util from ._securetransport.bindings import CoreFoundation, Security, SecurityConst from ._securetransport.low...
Monkey-patch urllib3 with SecureTransport-backed SSL-support.
35,419
from __future__ import absolute_import import contextlib import ctypes import errno import os.path import shutil import socket import ssl import struct import threading import weakref import six from .. import util from ._securetransport.bindings import CoreFoundation, Security, SecurityConst from ._securetransport.low...
Undo monkey-patching by :func:`inject_into_urllib3`.
35,420
from __future__ import absolute_import import contextlib import ctypes import errno import os.path import shutil import socket import ssl import struct import threading import weakref import six from .. import util from ._securetransport.bindings import CoreFoundation, Security, SecurityConst from ._securetransport.low...
SecureTransport read callback. This is called by ST to request that data be returned from the socket.
35,421
from __future__ import absolute_import import contextlib import ctypes import errno import os.path import shutil import socket import ssl import struct import threading import weakref import six from .. import util from ._securetransport.bindings import CoreFoundation, Security, SecurityConst from ._securetransport.low...
SecureTransport write callback. This is called by ST to request that data actually be sent on the network.
35,422
from __future__ import absolute_import import contextlib import ctypes import errno import os.path import shutil import socket import ssl import struct import threading import weakref import six from .. import util from ._securetransport.bindings import CoreFoundation, Security, SecurityConst from ._securetransport.low...
null
35,423
from __future__ import absolute_import import contextlib import ctypes import errno import os.path import shutil import socket import ssl import struct import threading import weakref import six from .. import util from ._securetransport.bindings import CoreFoundation, Security, SecurityConst from ._securetransport.low...
null
35,425
from __future__ import absolute_import import OpenSSL.SSL from thirdparty.cryptography import x509 from thirdparty.cryptography.hazmat.backends.openssl import backend as openssl_backend from thirdparty.cryptography.hazmat.backends.openssl.x509 import _Certificate from io import BytesIO from socket import error as Socke...
Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.
35,426
from __future__ import absolute_import import OpenSSL.SSL from thirdparty.cryptography import x509 from thirdparty.cryptography.hazmat.backends.openssl import backend as openssl_backend from thirdparty.cryptography.hazmat.backends.openssl.x509 import _Certificate from io import BytesIO from socket import error as Socke...
Undo monkey-patching by :func:`inject_into_urllib3`.
35,427
from __future__ import absolute_import import OpenSSL.SSL from thirdparty.cryptography import x509 from thirdparty.cryptography.hazmat.backends.openssl import backend as openssl_backend from thirdparty.cryptography.hazmat.backends.openssl.x509 import _Certificate try: from thirdparty.cryptography.x509 import Unsupp...
Given an PyOpenSSL certificate, provides all the subject alternative names.
35,428
from __future__ import absolute_import import OpenSSL.SSL from thirdparty.cryptography import x509 from thirdparty.cryptography.hazmat.backends.openssl import backend as openssl_backend from thirdparty.cryptography.hazmat.backends.openssl.x509 import _Certificate from io import BytesIO from socket import error as Socke...
null
35,429
from __future__ import absolute_import import OpenSSL.SSL from thirdparty.cryptography import x509 from thirdparty.cryptography.hazmat.backends.openssl import backend as openssl_backend from thirdparty.cryptography.hazmat.backends.openssl.x509 import _Certificate from io import BytesIO from socket import error as Socke...
null
35,430
from __future__ import absolute_import import errno import logging import socket import sys import warnings from socket import error as SocketError from socket import timeout as SocketTimeout from .connection import ( BaseSSLError, BrokenPipeError, DummyConnection, HTTPConnection, HTTPException, ...
Given a url, return an :class:`.ConnectionPool` instance of its host. This is a shortcut for not having to parse out the scheme, host, and port of the url before creating an :class:`.ConnectionPool` instance. :param url: Absolute URL string that must include the scheme. Port is optional. :param \\**kw: Passes additiona...
35,431
from __future__ import absolute_import import errno import logging import socket import sys import warnings from socket import error as SocketError from socket import timeout as SocketTimeout from .connection import ( BaseSSLError, BrokenPipeError, DummyConnection, HTTPConnection, HTTPException, ...
Normalize hosts for comparisons and use with sockets.
35,435
from __future__ import absolute_import import io import logging import zlib from contextlib import contextmanager from socket import error as SocketError from socket import timeout as SocketTimeout try: import brotli except ImportError: brotli = None from ._collections import HTTPHeaderDict from .connection imp...
null
35,437
from __future__ import absolute_import import collections import functools import logging from ._collections import RecentlyUsedContainer from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, port_by_scheme from .exceptions import ( LocationValueError, MaxRetryError, ProxySchemeUnknown, P...
null
35,438
import re import sys class CertificateError(ValueError): pass def _dnsname_match(dn, hostname, max_wildcards=1): """Matching according to RFC 6125, section 6.4.3 http://tools.ietf.org/html/rfc6125#section-6.4.3 """ pats = [] if not dn: return False # Ported from python3-syntax: #...
Verify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 rules are followed, but IP addresses are not accepted for *hostname*. CertificateError is raised on failure. On success, the function returns nothing.
35,440
from __future__ import absolute_import import functools import itertools import operator import sys import types if sys.platform == "win32": _moved_attributes += [MovedModule("winreg", "_winreg")] if sys.version_info[:2] == (3, 2): exec_( """def raise_from(value, from_value): try: if from_va...
Import module, returning the module after the last dot.
35,463
from __future__ import absolute_import import functools import itertools import operator import sys import types if sys.platform == "win32": _moved_attributes += [MovedModule("winreg", "_winreg")] if sys.version_info[:2] == (3, 2): exec_( """def raise_from(value, from_value): try: if from_va...
Execute code in a namespace.
35,464
from __future__ import absolute_import import functools import itertools import operator import sys import types if sys.platform == "win32": _moved_attributes += [MovedModule("winreg", "_winreg")] if sys.version_info[:2] == (3, 2): exec_( """def raise_from(value, from_value): try: if from_va...
The new-style print function for Python 2.4 and 2.5.
35,465
from __future__ import absolute_import import functools import itertools import operator import sys import types if sys.platform == "win32": _moved_attributes += [MovedModule("winreg", "_winreg")] if sys.version_info[:2] == (3, 2): exec_( """def raise_from(value, from_value): try: if from_va...
null
35,466
from __future__ import absolute_import import functools import itertools import operator import sys import types def wraps( wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, updated=functools.WRAPPER_UPDATES, ): def wrapper(f): f = functools.wraps(wrapped, assigned, updat...
null
35,468
from __future__ import absolute_import import functools import itertools import operator import sys import types The provided code snippet includes necessary dependencies for implementing the `ensure_binary` function. Write a Python function `def ensure_binary(s, encoding="utf-8", errors="strict")` to solve the follow...
Coerce **s** to six.binary_type. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> encoded to `bytes` - `bytes` -> `bytes`
35,469
from __future__ import absolute_import import functools import itertools import operator import sys import types PY2 = sys.version_info[0] == 2 The provided code snippet includes necessary dependencies for implementing the `python_2_unicode_compatible` function. Write a Python function `def python_2_unicode_compatible...
A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class.
35,470
from __future__ import absolute_import import datetime import logging import os import re import socket import warnings from socket import error as SocketError from socket import timeout as SocketTimeout from .packages import six from .packages.six.moves.http_client import HTTPConnection as _HTTPConnection from .packag...
null
35,471
from __future__ import absolute_import import datetime import logging import os import re import socket import warnings from socket import error as SocketError from socket import timeout as SocketTimeout from .packages import six from .packages.six.moves.http_client import HTTPConnection as _HTTPConnection from .packag...
null
35,482
from __future__ import absolute_import import hmac import os import sys import warnings from binascii import hexlify, unhexlify from hashlib import md5, sha1, sha256 from ..exceptions import ( InsecurePlatformWarning, ProxySchemeUnsupported, SNIMissingWarning, SSLError, ) from ..packages import six from...
All arguments except for server_hostname, ssl_context, and ca_cert_dir have the same meaning as they do when using :func:`ssl.wrap_socket`. :param server_hostname: When SNI is supported, the expected hostname of the certificate :param ssl_context: A pre-made :class:`SSLContext` object. If none is provided, one will be ...
35,484
from .ssl_ import create_urllib3_context, resolve_cert_reqs, resolve_ssl_version def resolve_cert_reqs(candidate): """ Resolves the argument to a numeric constant, which can be passed to the wrap_socket function/method from the ssl module. Defaults to :data:`ssl.CERT_REQUIRED`. If given a string it...
Generates a default proxy ssl context if one hasn't been provided by the user.
35,485
from __future__ import absolute_import import socket from thirdparty.urllib3.exceptions import LocationParseError from ..contrib import _appengine_environ from ..packages import six from .wait import NoWayToWaitForSocketError, wait_for_read class NoWayToWaitForSocketError(Exception): pass def wait_f...
Returns True if the connection is dropped and should be closed. :param conn: :class:`http.client.HTTPConnection` object. Note: For platforms like AppEngine, this will always return ``False`` to let the platform handle connection recycling transparently for us.
35,486
from __future__ import absolute_import import socket from thirdparty.urllib3.exceptions import LocationParseError from ..contrib import _appengine_environ from ..packages import six from .wait import NoWayToWaitForSocketError, wait_for_read def _set_socket_options(sock, options): if options is None: return ...
Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the global default time...
35,487
from __future__ import absolute_import import socket from thirdparty.urllib3.exceptions import LocationParseError from ..contrib import _appengine_environ from ..packages import six from .wait import NoWayToWaitForSocketError, wait_for_read The provided code snippet includes necessary dependencies for implementing the...
Returns True if the system can bind an IPv6 address.
35,488
import os import sys try: from importlib.resources import path as get_path, read_text _CACERT_CTX = None _CACERT_PATH = None except ImportError: # This fallback will work for Python versions prior to 3.7 that lack the # importlib.resources module but relies on the existing `where` function # so ...
null
35,489
from __future__ import absolute_import, division, print_function import abc import binascii import inspect import sys import warnings def read_only_property(name): return property(lambda self: getattr(self, name))
null
35,490
from __future__ import absolute_import, division, print_function import abc import binascii import inspect import sys import warnings def verify_interface(iface, klass): def register_interface(iface): def register_decorator(klass): verify_interface(iface, klass) iface.register(klass) return...
null
35,491
from __future__ import absolute_import, division, print_function import abc import binascii import inspect import sys import warnings def verify_interface(iface, klass): for method in iface.__abstractmethods__: if not hasattr(klass, method): raise InterfaceNotImplemented( "{} is ...
null
35,492
from __future__ import absolute_import, division, print_function import abc import binascii import inspect import sys import warnings class _DeprecatedValue(object): def __init__(self, value, message, warning_class): self.value = value self.message = message self.warning_class = warning_clas...
null
35,493
from __future__ import absolute_import, division, print_function import abc import binascii import inspect import sys import warnings def cached_property(func): cached_name = "_cached_{}".format(func) sentinel = object() def inner(instance): cache = getattr(instance, cached_name, sentinel) ...
null
35,494
from __future__ import absolute_import, division, print_function import abc import datetime from enum import Enum import six from thirdparty.cryptography import x509 from thirdparty.cryptography.hazmat.primitives import hashes from thirdparty.cryptography.x509.base import ( _EARLIEST_UTC_TIME, _convert_to_naive...
null
35,495
from __future__ import absolute_import, division, print_function import abc import datetime from enum import Enum import six from thirdparty.cryptography import x509 from thirdparty.cryptography.hazmat.primitives import hashes from thirdparty.cryptography.x509.base import ( _EARLIEST_UTC_TIME, _convert_to_naive...
null
35,496
from __future__ import absolute_import, division, print_function import abc import datetime from enum import Enum import six from thirdparty.cryptography import x509 from thirdparty.cryptography.hazmat.primitives import hashes from thirdparty.cryptography.x509.base import ( _EARLIEST_UTC_TIME, _convert_to_naive...
null
35,497
from __future__ import absolute_import, division, print_function from enum import Enum import six from thirdparty.cryptography import utils from thirdparty.cryptography.hazmat.backends import _get_backend from thirdparty.cryptography.x509.oid import NameOID, ObjectIdentifier The provided code snippet includes necessar...
Escape special characters in RFC4514 Distinguished Name value.
35,498
from __future__ import absolute_import, division, print_function import abc import datetime import hashlib import ipaddress from enum import Enum import six from thirdparty.cryptography import utils from thirdparty.cryptography.hazmat._der import ( BIT_STRING, DERReader, OBJECT_IDENTIFIER, SEQUENCE, ) f...
null
35,499
from __future__ import absolute_import, division, print_function import abc import datetime import hashlib import ipaddress from enum import Enum import six from thirdparty.cryptography import utils from thirdparty.cryptography.hazmat._der import ( BIT_STRING, DERReader, OBJECT_IDENTIFIER, SEQUENCE, ) f...
null
35,500
from __future__ import absolute_import, division, print_function import abc import datetime import os from enum import Enum import six from thirdparty.cryptography import utils from thirdparty.cryptography.hazmat.backends import _get_backend from thirdparty.cryptography.hazmat.primitives.asymmetric import ( dsa, ...
null