buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
def connect(self): if use_proxy: self.sock = socks.socksocket(af, socktype, proto) self.sock.setproxy( proxy_type, proxy_host, proxy_port, proxy_rdns, ...
def connect(self): if use_proxy: self.sock = socks.socksocket(af, socktype, proto) self.sock.setproxy( proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, ) else: s...
def connect(self): if has_timeout(self.timeout): self.sock.settimeout(self.timeout) if self.debuglevel > 0: print( "connect: ({0}, {1}) ************".format(self.host, self.port) ) if ...
def connect(self): if has_timeout(self.timeout): self.sock.settimeout(self.timeout) if self.debuglevel > 0: print("connect: ({0}, {1}) ************".format(self.host, self.port)) if use_proxy: print( ...
def connect(self): if use_proxy: print( "proxy: {0}".format( str( ( proxy_host, proxy_port, ...
def connect(self): if use_proxy: print( "proxy: {0}".format( str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers,)) ) ) i...
def __init__( self.proxy_info = proxy_info("https") context = _build_ssl_context( self.disable_ssl_certificate_validation, self.ca_certs, cert_file, key_file, maximum_version=tls_maximum_version, minimum_version=tls_minimum_version, key_password=key_password, ...
def __init__( self.proxy_info = proxy_info("https") context = _build_ssl_context( self.disable_ssl_certificate_validation, self.ca_certs, cert_file, key_file, maximum_version=tls_maximum_version, minimum_version=tls_minimum_ver...
def connect(self): """Connect to a host on a given (SSL) port.""" if self.proxy_info and self.proxy_info.isgood() and self.proxy_info.applies_to(self.host): use_proxy = True proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers = ( ...
def connect(self): """Connect to a host on a given (SSL) port.""" if self.proxy_info and self.proxy_info.isgood() and self.proxy_info.applies_to(self.host): use_proxy = True ( proxy_type, proxy_host, proxy_port, prox...
def connect(self): sock = socks.socksocket(family, socktype, proto) sock.setproxy( proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, ...
def connect(self): sock = socks.socksocket(family, socktype, proto) sock.setproxy( proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, ) else: sock = socket.socket(family, socktyp...
def connect(self): self.sock = self._context.wrap_socket(sock, server_hostname=self.host) # Python 3.3 compatibility: emulate the check_hostname behavior if ( not hasattr(self._context, "check_hostname") and not self.disable_ssl_ce...
def connect(self): self.sock = self._context.wrap_socket(sock, server_hostname=self.host) # Python 3.3 compatibility: emulate the check_hostname behavior if not hasattr(self._context, "check_hostname") and not self.disable_ssl_certificate_validation: ...
def connect(self): if use_proxy: print( "proxy: {0}".format( str( ( proxy_host, proxy_port, ...
def connect(self): if use_proxy: print( "proxy: {0}".format( str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers,)) ) ) excep...
def connect(self): if use_proxy: print( "proxy: {0}".format( str( ( proxy_host, proxy_port, ...
def connect(self): if use_proxy: print( "proxy: {0}".format( str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers,)) ) ) i...
def _auth_from_challenge(self, host, request_uri, headers, response, content): """A generator that creates Authorization objects that can be applied to requests. """ challenges = _parse_www_authenticate(response, "www-authenticate") for cred in self.credentials.iter(host): ...
def _auth_from_challenge(self, host, request_uri, headers, response, content): """A generator that creates Authorization objects that can be applied to requests. """ challenges = auth._parse_www_authenticate(response, "www-authenticate") for cred in self.credentials.iter(host)...
def _conn_request(self, conn, request_uri, method, body, headers): conn.close() raise ServerNotFoundError("Unable to find the server at %s" % conn.host) except socket.error as e: errno_ = ( e.args[0].errno if isinstance(e.args[0], socket.er...
def _conn_request(self, conn, request_uri, method, body, headers): conn.close() raise ServerNotFoundError("Unable to find the server at %s" % conn.host) except socket.error as e: errno_ = e.args[0].errno if isinstance(e.args[0], socket.error) else e.errno ...
def _conn_request(self, conn, request_uri, method, body, headers): return (response, content) def _request( self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey, ): """Do the ac...
def _conn_request(self, conn, request_uri, method, body, headers): return (response, content) def _request( self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey, ): """Do the actual request using the connection object and also follow one lev...
def _request( del headers["if-none-match"] if "if-modified-since" in headers: del headers["if-modified-since"] if ( "authorization" in headers and not self.forward_authorization_header...
def _request( del headers["if-none-match"] if "if-modified-since" in headers: del headers["if-modified-since"] if "authorization" in headers and not self.forward_authorization_headers: del headers["authorizat...
def _request( redirect_method = "GET" body = None (response, content) = self.request( location, method=redirect_method, body=body, ...
def _request( redirect_method = "GET" body = None (response, content) = self.request( location, method=redirect_method, body=body, headers=headers, redirections=redirections - 1, ) ...
def _normalize_headers(self, headers): # including all socket.* and httplib.* exceptions. def request( self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None, ): """ Performs a single HTTP re...
def _normalize_headers(self, headers): # including all socket.* and httplib.* exceptions. def request( self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None, ): """ Performs a single HTTP request. The 'uri' is the URI of the HTTP resource...
def request( being and instance of the 'Response' class, the second being a string that contains the response entity body. """ conn_key = '' try: if headers is None:
def request( being and instance of the 'Response' class, the second being a string that contains the response entity body. """ conn_key = "" try: if headers is None:
def request( info = email.message_from_bytes(info) for k, v in info.items(): if v.startswith("=?") and v.endswith("?="): info.replace_header( k, str(*email.header.decode_header...
def request( info = email.message_from_bytes(info) for k, v in info.items(): if v.startswith("=?") and v.endswith("?="): info.replace_header(k, str(*email.header.decode_header(v)[0])) except (...
def request( # Should cached permanent redirects be counted in our redirection count? For now, yes. if redirections <= 0: raise RedirectLimit( "Redirected more times than redirection_limit allows.", {...
def request( # Should cached permanent redirects be counted in our redirection count? For now, yes. if redirections <= 0: raise RedirectLimit( "Redirected more times than redirection_limit allows.", {}, "", ...
def request( return (response, content) if entry_disposition == "STALE": if ( "etag" in info and not self.ignore_etag and not "if-none-match" in headers ...
def request( return (response, content) if entry_disposition == "STALE": if "etag" in info and not self.ignore_etag and not "if-none-match" in headers: headers["if-none-match"] = info["etag"] if "las...
def request( pass (response, new_content) = self._request( conn, authority, uri, request_uri, method, body, ...
def request( pass (response, new_content) = self._request( conn, authority, uri, request_uri, method, body, headers, redirections, cachekey, ) if response.status == 304 and method == "GET":
def request( merged_response = Response(info) if hasattr(response, "_stale_digest"): merged_response._stale_digest = response._stale_digest _updateCache( headers, merged_response, content, self.cache, cachekey ...
def request( merged_response = Response(info) if hasattr(response, "_stale_digest"): merged_response._stale_digest = response._stale_digest _updateCache(headers, merged_response, content, self.cache, cachekey) respon...
def request( content = b"" else: (response, content) = self._request( conn, authority, uri, request_uri, method, body, ...
def request( content = b"" else: (response, content) = self._request( conn, authority, uri, request_uri, method, body, headers, redirections, cachekey, ) except Exception as e: is_timeout = isinstance...
def request( response.reason = str(e) elif isinstance(e, socket.timeout): content = b"Request Timeout" response = Response( { "content-type": "text/plain", "status"...
def request( response.reason = str(e) elif isinstance(e, socket.timeout): content = b"Request Timeout" response = Response({"content-type": "text/plain", "status": "408", "content-length": len(content),}) response.reason = "...
class TestCommand(setuptools.command.test.test): def run_tests(self): # pytest may be not installed yet import pytest args = ['--forked', '--fulltrace', '--no-cov', 'tests/'] if self.test_suite: args += ['-k', self.test_suite] sys.stderr.write('setup.py:test run p...
class TestCommand(setuptools.command.test.test): def run_tests(self): # pytest may be not installed yet import pytest args = ["--forked", "--fulltrace", "--no-cov", "tests/"] if self.test_suite: args += ["-k", self.test_suite] sys.stderr.write("setup.py:test run ...
def read_requirements(name): package_dir=pkgdir, packages=["httplib2"], package_data={"httplib2": ["*.txt"]}, tests_require=read_requirements("requirements-test.txt"), cmdclass={"test": TestCommand}, classifiers=[
def read_requirements(name): package_dir=pkgdir, packages=["httplib2"], package_data={"httplib2": ["*.txt"]}, install_requires=read_requirements("requirements.txt"), tests_require=read_requirements("requirements-test.txt"), cmdclass={"test": TestCommand}, classifiers=[
def parse_http_message(kind, buf): msg = kind() msg.raw = start_line if kind is HttpRequest: assert re.match( br".+ HTTP/\d\.\d\r\n$", start_line ), "Start line does not look like HTTP request: " + repr(start_line) msg.method, msg.uri, msg.proto = start_line.rstrip().deco...
def parse_http_message(kind, buf): msg = kind() msg.raw = start_line if kind is HttpRequest: assert re.match(br".+ HTTP/\d\.\d\r\n$", start_line), "Start line does not look like HTTP request: " + repr( start_line ) msg.method, msg.uri, msg.proto = start_line.rstrip().deco...
class MockHTTPConnection(object): """ def __init__( self, host, port=None, key_file=None, cert_file=None, strict=None, timeout=None, proxy_info=None, ): self.host = host self.port = port
class MockHTTPConnection(object): """ def __init__( self, host, port=None, key_file=None, cert_file=None, strict=None, timeout=None, proxy_info=None, ): self.host = host self.port = port
class MockHTTPBadStatusConnection(object): num_calls = 0 def __init__( self, host, port=None, key_file=None, cert_file=None, strict=None, timeout=None, proxy_info=None, ): self.host = host self.port = port
class MockHTTPBadStatusConnection(object): num_calls = 0 def __init__( self, host, port=None, key_file=None, cert_file=None, strict=None, timeout=None, proxy_info=None, ): self.host = host self.port = port
def server_socket_thread(srv): # at least in other/connection_close test # should not be a problem since socket would close upon garbage collection if gcounter[0] > request_count: gresult[0] = Exception( "Request count expected={0} ...
def server_socket_thread(srv): # at least in other/connection_close test # should not be a problem since socket would close upon garbage collection if gcounter[0] > request_count: gresult[0] = Exception("Request count expected={0} actual={1}".format(re...
def http_response_bytes( if add_etag: headers.setdefault("etag", '"{0}"'.format(hashlib.md5(body).hexdigest())) header_string = "".join("{0}: {1}\r\n".format(k, v) for k, v in headers.items()) if ( not undefined_body_length and proto != "HTTP/1.0" and "content-length" not in ...
def http_response_bytes( if add_etag: headers.setdefault("etag", '"{0}"'.format(hashlib.md5(body).hexdigest())) header_string = "".join("{0}: {1}\r\n".format(k, v) for k, v in headers.items()) if not undefined_body_length and proto != "HTTP/1.0" and "content-length" not in headers: raise Exc...
def server_reflect(**kwargs): return server_request(http_handler, **kwargs) def http_parse_auth(s): """https://tools.ietf.org/html/rfc7235#section-2.1 """ scheme, rest = s.split(" ", 1) result = {} while True: m = httplib2.WWW_AUTH_RELAXED.search(rest) if not m: bre...
def server_reflect(**kwargs): return server_request(http_handler, **kwargs) def store_request_response(out): def wrapper(fun): @functools.wraps(fun)
def http_reflect_with_auth_handler(request): auth_header = request.headers.get("authorization", "") if not auth_header: return deny() if " " not in auth_header: return http_response_bytes(status=400, body=b"authorization header syntax error") scheme, data = auth_h...
def http_reflect_with_auth_handler(request): auth_header = request.headers.get("authorization", "") if not auth_header: return deny() try: auth_parsed = httplib2.auth._parse_www_authenticate(request.headers, "authorization") print("debug: auth_parsed", auth_pa...
def http_reflect_with_auth_handler(request): gserver_nonce[0] = nextnonce gnextnonce[0] = None server_nonce_current = gserver_nonce[0] auth_info = http_parse_auth(data) client_cnonce = auth_info.get("cnonce", "") client_nc = auth_info.get("...
def http_reflect_with_auth_handler(request): gserver_nonce[0] = nextnonce gnextnonce[0] = None server_nonce_current = gserver_nonce[0] client_cnonce = auth_info.get("cnonce", "") client_nc = auth_info.get("nc", "") client_nonce = auth_info....
def http_reflect_with_auth_handler(request): return deny(body=b"auth-info nc missing") if client_opaque != server_opaque: return deny( body="auth-info opaque mismatch expected={} actual={}".format( server_opaque, client_opaque ...
def http_reflect_with_auth_handler(request): return deny(body=b"auth-info nc missing") if client_opaque != server_opaque: return deny( body="auth-info opaque mismatch expected={} actual={}".format(server_opaque, client_opaque).encode() ) ...
def http_reflect_with_auth_handler(request): x_wsse = request.headers.get("x-wsse", "") if x_wsse.count(",") != 3: return http_response_bytes(status=400, body=b"x-wsse header syntax error") auth_info = http_parse_auth(x_wsse) client_username = auth_info.ge...
def http_reflect_with_auth_handler(request): x_wsse = request.headers.get("x-wsse", "") if x_wsse.count(",") != 3: return http_response_bytes(status=400, body=b"x-wsse header syntax error") wsse_params = httplib2.auth._parse_www_authenticate(request.headers, "x-wsse")...
def http_reflect_with_auth_handler(request): digest = hashlib.sha1("".join((client_nonce, client_created, allow_password)).encode("utf-8")).digest() digest_b64 = base64.b64encode(digest).decode() print("$$$ check client={} == real={}".format(client_digest, digest_b64)) i...
def http_reflect_with_auth_handler(request): digest = hashlib.sha1("".join((client_nonce, client_created, allow_password)).encode("utf-8")).digest() digest_b64 = base64.b64encode(digest).decode() print("debug: check client={} == real={}".format(client_digest, digest_b64)) ...
import httplib2 import pytest import tests
import time import httplib2 import pytest import tests
def test_basic(): # Test Basic Authentication http = httplib2.Http() password = tests.gen_password() handler = tests.http_reflect_with_auth( allow_scheme="basic", allow_credentials=(("joe", password),) ) with tests.server_request(handler, request_count=3) as uri: response, conten...
def test_basic(): # Test Basic Authentication http = httplib2.Http() password = tests.gen_password() handler = tests.http_reflect_with_auth(allow_scheme="basic", allow_credentials=(("joe", password),)) with tests.server_request(handler, request_count=3) as uri: response, content = http.reque...
def test_basic_for_domain(): # Test Basic Authentication http = httplib2.Http() password = tests.gen_password() handler = tests.http_reflect_with_auth( allow_scheme="basic", allow_credentials=(("joe", password),) ) with tests.server_request(handler, request_count=4) as uri: respo...
def test_basic_for_domain(): # Test Basic Authentication http = httplib2.Http() password = tests.gen_password() handler = tests.http_reflect_with_auth(allow_scheme="basic", allow_credentials=(("joe", password),)) with tests.server_request(handler, request_count=4) as uri: response, content =...
def test_basic_two_credentials(): password1 = tests.gen_password() password2 = tests.gen_password() allowed = [("joe", password1)] # exploit shared mutable list handler = tests.http_reflect_with_auth( allow_scheme="basic", allow_credentials=allowed ) with tests.server_request(handler, r...
def test_basic_two_credentials(): password1 = tests.gen_password() password2 = tests.gen_password() allowed = [("joe", password1)] # exploit shared mutable list handler = tests.http_reflect_with_auth(allow_scheme="basic", allow_credentials=allowed) with tests.server_request(handler, request_count=7...
def test_digest(): # Test that we support Digest Authentication http = httplib2.Http() password = tests.gen_password() handler = tests.http_reflect_with_auth( allow_scheme="digest", allow_credentials=(("joe", password),) ) with tests.server_request(handler, request_count=3) as uri: ...
def test_digest(): # Test that we support Digest Authentication http = httplib2.Http() password = tests.gen_password() handler = tests.http_reflect_with_auth(allow_scheme="digest", allow_credentials=(("joe", password),)) with tests.server_request(handler, request_count=3) as uri: response, c...
def test_digest_next_nonce_nc(): password = tests.gen_password() grenew_nonce = [None] handler = tests.http_reflect_with_auth( allow_scheme="digest", allow_credentials=(("joe", password),), out_renew_nonce=grenew_nonce, ) with tests.server_request(handler, request_count=5) as...
def test_digest_next_nonce_nc(): password = tests.gen_password() grenew_nonce = [None] handler = tests.http_reflect_with_auth( allow_scheme="digest", allow_credentials=(("joe", password),), out_renew_nonce=grenew_nonce, ) with tests.server_request(handler, request_count=5) as uri: ht...
def test_digest_auth_stale(): http.add_credentials("joe", password) response, _ = http.request(uri, "GET") assert response.status == 200 info = httplib2._parse_www_authenticate( requests[0][1].headers, "www-authenticate" ) grenew_nonce[0]() response, _...
def test_digest_auth_stale(): http.add_credentials("joe", password) response, _ = http.request(uri, "GET") assert response.status == 200 info = httplib2.auth._parse_www_authenticate(requests[0][1].headers, "www-authenticate") grenew_nonce[0]() response, _ = http.request(u...
def test_digest_auth_stale(): ({}, {}), ({"www-authenticate": ""}, {}), ( { "www-authenticate": 'Test realm="test realm" , foo=foo ,bar="bar", baz=baz,qux=qux' }, { "test": { "realm": "test realm", ...
def test_digest_auth_stale(): ({}, {}), ({"www-authenticate": ""}, {}), ( {"www-authenticate": 'Test realm="test realm" , foo=foo ,bar="bar", baz=baz,qux=qux'}, {"test": {"realm": "test realm", "foo": "foo", "bar": "bar", "baz": "baz", "qux": "qux"}}, ), (...
def test_digest_auth_stale(): # 'wsse': {'realm': 'very', 'profile': 'UsernameToken'}}), # more quote combos ( { "www-authenticate": 'Digest realm="myrealm", nonce="KBAA=3", algorithm=MD5, qop="auth", stale=true' }, { "digest"...
def test_digest_auth_stale(): # 'wsse': {'realm': 'very', 'profile': 'UsernameToken'}}), # more quote combos ( {"www-authenticate": 'Digest realm="myrealm", nonce="KBAA=3", algorithm=MD5, qop="auth", stale=true'}, {"digest": {"realm": "myrealm", "nonce": "KBAA=3", "algo...
def test_parse_www_authenticate_correct(data, strict): # FIXME: move strict to parse argument httplib2.USE_WWW_AUTH_STRICT_PARSING = strict try: assert httplib2._parse_www_authenticate(headers) == info finally: httplib2.USE_WWW_AUTH_STRICT_PARSING = 0 def test_parse_www_authenticate_ma...
def test_parse_www_authenticate_correct(data, strict): # FIXME: move strict to parse argument httplib2.USE_WWW_AUTH_STRICT_PARSING = strict try: assert httplib2.auth._parse_www_authenticate(headers) == info finally: httplib2.USE_WWW_AUTH_STRICT_PARSING = 0 @pytest.mark.parametrize( ...
def test_digest_object(): host = None request_uri = "/test/digest/" headers = {} response = { "www-authenticate": 'Digest realm="myrealm", nonce="KBAA=35", algorithm=MD5, qop="auth"' } content = b"" d = httplib2.DigestAuthentication( credentials, host, request_uri, headers, ...
def test_digest_object(): host = None request_uri = "/test/digest/" headers = {} response = {"www-authenticate": 'Digest realm="myrealm", nonce="KBAA=35", algorithm=MD5, qop="auth"'} content = b"" d = httplib2.DigestAuthentication(credentials, host, request_uri, headers, response, content, None...
def test_digest_object_with_opaque(): request_uri = "/digest/opaque/" headers = {} response = { "www-authenticate": 'Digest realm="myrealm", nonce="30352fd", algorithm=MD5, ' 'qop="auth", opaque="atestopaque"' } content = "" d = httplib2.DigestAuthentication( credentials...
def test_digest_object_with_opaque(): request_uri = "/digest/opaque/" headers = {} response = { "www-authenticate": 'Digest realm="myrealm", nonce="30352fd", algorithm=MD5, ' 'qop="auth", opaque="atestopaque"' } content = "" d = httplib2.DigestAuthentication(credentials, host, request_u...
def test_digest_object_stale(): request_uri = "/digest/stale/" headers = {} response = httplib2.Response({}) response["www-authenticate"] = ( 'Digest realm="myrealm", nonce="bd669f", ' 'algorithm=MD5, qop="auth", stale=true' ) response.status = 401 content = b"" d = httpl...
def test_digest_object_stale(): request_uri = "/digest/stale/" headers = {} response = httplib2.Response({}) response["www-authenticate"] = 'Digest realm="myrealm", nonce="bd669f", ' 'algorithm=MD5, qop="auth", stale=true' response.status = 401 content = b"" d = httplib2.DigestAuthentication...
def test_digest_object_auth_info(): request_uri = "/digest/nextnonce/" headers = {} response = httplib2.Response({}) response["www-authenticate"] = ( 'Digest realm="myrealm", nonce="barney", ' 'algorithm=MD5, qop="auth", stale=true' ) response["authentication-info"] = 'nextnonce=...
def test_digest_object_auth_info(): request_uri = "/digest/nextnonce/" headers = {} response = httplib2.Response({}) response["www-authenticate"] = 'Digest realm="myrealm", nonce="barney", ' 'algorithm=MD5, qop="auth", stale=true' response["authentication-info"] = 'nextnonce="fred"' content = b"...
class CkMinions: def validate_tgt(self, valid, expr, tgt_type, minions=None, expr_form=None): """ Return a Bool. This function returns if the expression sent in is within the scope of the valid expression """ v_minions = set(self.check_minions(valid, "compound").get("minion...
class CkMinions: def validate_tgt(self, valid, expr, tgt_type, minions=None, expr_form=None): """ Validate the target minions against the possible valid minions. If ``minions`` is provided, they will be compared against the valid minions. Otherwise, ``expr`` and ``tgt_type`` will b...
import salt.utils.minions import salt.utils.network from tests.support.mock import patch
import pytest import salt.utils.minions import salt.utils.network from tests.support.mock import patch
def test_connected_ids(): test ckminion connected_ids when local_port_tcp returns 127.0.0.1 """ opts = {"publish_port": 4505} minion = "minion" ip = salt.utils.network.ip_addrs() mdata = {"grains": {"ipv4": ip, "ipv6": []}} ckminions = salt.utils.minions.CkMinions({"minion_data_cache": T...
def test_connected_ids(): test ckminion connected_ids when local_port_tcp returns 127.0.0.1 """ opts = {"publish_port": 4505, "minion_data_cache": True} minion = "minion" ip = salt.utils.network.ip_addrs() mdata = {"grains": {"ipv4": ip, "ipv6": []}} patch_net = patch("salt.utils.network...
class Index(IndexOpsMixin, PandasObject): _infer_as_myclass = False _engine_type = libindex.ObjectEngine _accessors = {"str"}
class Index(IndexOpsMixin, PandasObject): _infer_as_myclass = False _engine_type = libindex.ObjectEngine # whether we support partial string indexing. Overridden # in DatetimeIndex and PeriodIndex _supports_partial_string_indexing = False _accessors = {"str"}
class DatetimeIndex(DatetimeIndexOpsMixin, Int64Index, DatetimeDelegateMixin): ) _engine_type = libindex.DatetimeEngine _tz = None _freq = None
class DatetimeIndex(DatetimeIndexOpsMixin, Int64Index, DatetimeDelegateMixin): ) _engine_type = libindex.DatetimeEngine _supports_partial_string_indexing = True _tz = None _freq = None
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin): _data = None _engine_type = libindex.PeriodEngine # ------------------------------------------------------------------------ # Index Constructors
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin): _data = None _engine_type = libindex.PeriodEngine _supports_partial_string_indexing = True # ------------------------------------------------------------------------ # Index Constructors
class _LocIndexer(_LocationIndexer): if isinstance(ax, MultiIndex): return False if not ax.is_unique: return False
class _LocIndexer(_LocationIndexer): if isinstance(ax, MultiIndex): return False if isinstance(k, str) and ax._supports_partial_string_indexing: # partial string indexing, df.loc['2000', 'A'] # should not be considered scalar retur...
class _LocIndexer(_LocationIndexer): """Translate any partial string timestamp matches in key, returning the new key (GH 10331)""" if isinstance(labels, MultiIndex): if isinstance(key, str) and labels.levels[0].is_all_dates: # Convert key '2016-01-01' to ...
class _LocIndexer(_LocationIndexer): """Translate any partial string timestamp matches in key, returning the new key (GH 10331)""" if isinstance(labels, MultiIndex): if ( isinstance(key, str) and labels.levels[0]._supports_partial_string_indexing ...
class _LocIndexer(_LocationIndexer): # (..., slice('2016-01-01', '2016-01-01', None), ...) new_key = [] for i, component in enumerate(key): if isinstance(component, str) and labels.levels[i].is_all_dates: new_key.append(slice(co...
class _LocIndexer(_LocationIndexer): # (..., slice('2016-01-01', '2016-01-01', None), ...) new_key = [] for i, component in enumerate(key): if ( isinstance(component, str) and labels.levels[i]._supports_p...
def convert_to_index_sliceable(obj, key): # We might have a datetimelike string that we can translate to a # slice here via partial string indexing if idx.is_all_dates: try: return idx._get_string_slice(key) except (KeyError, ValueError, NotImplementedErr...
def convert_to_index_sliceable(obj, key): # We might have a datetimelike string that we can translate to a # slice here via partial string indexing if idx._supports_partial_string_indexing: try: return idx._get_string_slice(key) except (KeyError, ValueErr...
class TestSlicing: with pytest.raises(ValueError, match="The index must be timezone"): df = df.tz_localize(None) df[start:end]
class TestSlicing: with pytest.raises(ValueError, match="The index must be timezone"): df = df.tz_localize(None) df[start:end] def test_slice_reduce_to_series(self): # GH 27516 df = pd.DataFrame( {"A": range(24)}, index=pd.date_range("2000", periods=24, f...
class TestFormatSelection(unittest.TestCase): def test_format_selection_string_ops(self): formats = [ {'format_id': 'abc-cba', 'ext': 'mp4', 'url': TEST_URL}, ] info_dict = _make_result(formats)
class TestFormatSelection(unittest.TestCase): def test_format_selection_string_ops(self): formats = [ {'format_id': 'abc-cba', 'ext': 'mp4', 'url': TEST_URL}, {'format_id': 'zxc-cxz', 'ext': 'webm', 'url': TEST_URL}, ] info_dict = _make_result(formats)
class TestFormatSelection(unittest.TestCase): # does not equal (!=) ydl = YDL({'format': '[format_id!=abc-cba]'}) self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy()) # starts with (^=)
class TestFormatSelection(unittest.TestCase): # does not equal (!=) ydl = YDL({'format': '[format_id!=abc-cba]'}) ydl.process_ie_result(info_dict.copy()) downloaded = ydl.downloaded_info_dicts[0] self.assertEqual(downloaded['format_id'], 'zxc-cxz') ydl = YDL({'format': ...
class TestFormatSelection(unittest.TestCase): self.assertEqual(downloaded['format_id'], 'abc-cba') # does not start with (!^=) ydl = YDL({'format': '[format_id!^=abc-cba]'}) self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy()) # ends with ($=)
class TestFormatSelection(unittest.TestCase): self.assertEqual(downloaded['format_id'], 'abc-cba') # does not start with (!^=) ydl = YDL({'format': '[format_id!^=abc]'}) ydl.process_ie_result(info_dict.copy()) downloaded = ydl.downloaded_info_dicts[0] self.assertEqual(do...
class TestFormatSelection(unittest.TestCase): self.assertEqual(downloaded['format_id'], 'abc-cba') # does not end with (!$=) ydl = YDL({'format': '[format_id!$=abc-cba]'}) self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy()) # contains (*=) ydl = Y...
class TestFormatSelection(unittest.TestCase): self.assertEqual(downloaded['format_id'], 'abc-cba') # does not end with (!$=) ydl = YDL({'format': '[format_id!$=cba]'}) ydl.process_ie_result(info_dict.copy()) downloaded = ydl.downloaded_info_dicts[0] self.assertEqual(down...
class YoutubeDL(object): comparison_value = m.group('value') str_op = STR_OPERATORS[m.group('op')] if m.group('negation'): op = lambda attr, value: not str_op else: op = str_op
class YoutubeDL(object): comparison_value = m.group('value') str_op = STR_OPERATORS[m.group('op')] if m.group('negation'): op = lambda attr, value: not str_op(attr, value) else: op = str_op
from PIL import Image @pytest.mark.parametrize( "test_file", ["Tests/images/sgi_overrun_expandrowF04.bin", "Tests/images/sgi_crash.bin"], ) def test_crashes(test_file): with open(test_file, "rb") as f:
from PIL import Image @pytest.mark.parametrize( "test_file", [ "Tests/images/sgi_overrun_expandrowF04.bin", "Tests/images/sgi_crash.bin", "Tests/images/crash-6b7f2244da6d0ae297ee0754a424213444e92778.sgi", "Tests/images/ossfuzz-5730089102868480.sgi", ], ) def test_crashes(te...
def parse_uri(self, uri): "like so: " "swift+http://user:pass@authurl.com/v1/container/obj" ) logger.error(_("Invalid store uri %(uri)s: %(reason)s") % locals()) raise exception.BadStoreUri() pieces = urlparse.urlparse(uri)
def parse_uri(self, uri): "like so: " "swift+http://user:pass@authurl.com/v1/container/obj" ) logger.error(_("Invalid store URI: %(reason)s") % locals()) raise exception.BadStoreUri() pieces = urlparse.urlparse(uri)
def parse_uri(self, uri): # the account and user. Combine them into a single username of # account:user if len(cred_parts) == 1: reason = (_("Badly formed credentials '%(creds)s' in Swift " "URI") % locals()) logger.error(re...
def parse_uri(self, uri): # the account and user. Combine them into a single username of # account:user if len(cred_parts) == 1: reason = (_("Badly formed credentials in Swift URI.")) logger.error(reason) raise exception.BadStoreUri() ...
def parse_uri(self, uri): path_parts.insert(0, netloc) self.authurl = '/'.join(path_parts) except IndexError: reason = _("Badly formed Swift URI: %s") % uri logger.error(reason) raise exception.BadStoreUri()
def parse_uri(self, uri): path_parts.insert(0, netloc) self.authurl = '/'.join(path_parts) except IndexError: reason = _("Badly formed Swift URI.") logger.error(reason) raise exception.BadStoreUri()
def get(self, location): except swift_client.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() raise exception.NotFound(_("Swift could not find image at " "uri %(uri)s") % locals()) ...
def get(self, location): except swift_client.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() msg = _("Swift could not find image at URI.") raise exception.NotFound(msg) else: raise
def add(self, image_id, image_file, image_size): except swift_client.ClientException, e: if e.http_status == httplib.CONFLICT: raise exception.Duplicate(_("Swift already has an image at " "location %s") % location.get_uri()) msg =...
def add(self, image_id, image_file, image_size): except swift_client.ClientException, e: if e.http_status == httplib.CONFLICT: raise exception.Duplicate(_("Swift already has an image at " "this location.")) msg = (_("Failed to add...
def delete(self, location): except swift_client.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() raise exception.NotFound(_("Swift could not find image at " "uri %(uri)s") % locals()) ...
def delete(self, location): except swift_client.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() msg = _("Swift could not find image at URI.") raise exception.NotFound(msg) else: rais...
import stat from django.http import ( FileResponse, Http404, HttpResponse, HttpResponseNotModified, HttpResponseRedirect, ) from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils.http import http_date, parse_http_date from django.utils.six.moves.urllib.parse import unquote ...
import stat from django.http import ( FileResponse, Http404, HttpResponse, HttpResponseNotModified, ) from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils._os import safe_join from django.utils.http import http_date, parse_http_date from django.utils.six.moves.urllib.parse im...
def serve(request, path, document_root=None, show_indexes=False): but if you'd like to override it, you can create a template called ``static/directory_index.html``. """ path = posixpath.normpath(unquote(path)) path = path.lstrip('/') newpath = '' for part in path.split('/'): if not ...
def serve(request, path, document_root=None, show_indexes=False): but if you'd like to override it, you can create a template called ``static/directory_index.html``. """ path = posixpath.normpath(unquote(path)).lstrip('/') fullpath = safe_join(document_root, path) if os.path.isdir(fullpath): ...
class WaitIterator(object): self.current_index = self.current_future = None self._running_future = None self_ref = weakref.ref(self) for future in futures: future.add_done_callback(functools.partial(
class WaitIterator(object): self.current_index = self.current_future = None self._running_future = None # Use a weak reference to self to avoid cycles that may delay # garbage collection. self_ref = weakref.ref(self) for future in futures: future.add_done_cal...
class WaitIterator(object): the inputs. """ self._running_future = TracebackFuture() if self._finished: self._return_result(self._finished.popleft())
class WaitIterator(object): the inputs. """ self._running_future = TracebackFuture() # As long as there is an active _running_future, we must # ensure that the WaitIterator is not GC'd (due to the # use of weak references in __init__). Add a callback that # refere...
class WaitIteratorTest(AsyncTestCase): self.assertEqual(g.current_index, 3, 'wrong index') i += 1 if __name__ == '__main__': unittest.main()
class WaitIteratorTest(AsyncTestCase): self.assertEqual(g.current_index, 3, 'wrong index') i += 1 @gen_test def test_no_ref(self): # In this usage, there is no direct hard reference to the # WaitIterator itself, only the Future it returns. Since # WaitIte...
class HTTP1Connection(httputil.HTTPConnection): self._chunking_output = ( start_line.method in ("POST", "PUT", "PATCH") and "Content-Length" not in headers and "Transfer-Encoding" not in headers ) else: assert isinstance(start_l...
class HTTP1Connection(httputil.HTTPConnection): self._chunking_output = ( start_line.method in ("POST", "PUT", "PATCH") and "Content-Length" not in headers and ( "Transfer-Encoding" not in headers or headers["Transfer-En...
Transfer-Encoding: chunked # don't either). self.assertEqual(301, response.code) def test_credentials_in_url(self): url = self.get_url("/auth").replace("http://", "http://me:secret@") response = self.fetch(url)
Transfer-Encoding: chunked # don't either). self.assertEqual(301, response.code) def test_redirect_put_with_body(self): response = self.fetch( "/redirect?url=/put&status=307", method="PUT", body="hello" ) self.assertEqual(response.body, b"Put body: hello") d...
def _get_object(data, position, as_class, tz_aware, uuid_subtype): object = _elements_to_dict(encoded, as_class, tz_aware, uuid_subtype) position += obj_size if "$ref" in object: return (DBRef(object.pop("$ref"), object.pop("$id"), object.pop("$db", None), object), position) ...
def _get_object(data, position, as_class, tz_aware, uuid_subtype): object = _elements_to_dict(encoded, as_class, tz_aware, uuid_subtype) position += obj_size if "$ref" in object: return (DBRef(object.pop("$ref"), object.pop("$id", None), object.pop("$db", None), object), positi...
from bson.binary import Binary, UUIDLegacy, OLD_UUID_SUBTYPE, UUID_SUBTYPE from bson.code import Code from bson.objectid import ObjectId from bson.py3compat import b from bson.son import SON
from bson.binary import Binary, UUIDLegacy, OLD_UUID_SUBTYPE, UUID_SUBTYPE from bson.code import Code from bson.dbref import DBRef from bson.objectid import ObjectId from bson.py3compat import b from bson.son import SON
def test_bad_encode(self): self.assertRaises(InvalidDocument, c.save, {"x": c}) warnings.simplefilter("default") def test_as_class(self): c = self.db.test c.drop()
def test_bad_encode(self): self.assertRaises(InvalidDocument, c.save, {"x": c}) warnings.simplefilter("default") def test_bad_dbref(self): c = self.db.test c.drop() # Incomplete DBRefs. self.assertRaises( InvalidDocument, c.insert, {'ref': {'...
from django.utils.translation import gettext, gettext_lazy as _ UserModel = get_user_model() class ReadOnlyPasswordHashWidget(forms.Widget): template_name = 'auth/widgets/read_only_password_hash.html' read_only = True
from django.utils.translation import gettext, gettext_lazy as _ UserModel = get_user_model() def _unicode_ci_compare(s1, s2): """ Perform case-insensitive comparison of two identifiers, using the recommended algorithm from Unicode Technical Report 36, section 2.11.2(B)(2). """ return unicodeda...
class PasswordResetForm(forms.Form): that prevent inactive users and users with unusable passwords from resetting their password. """ active_users = UserModel._default_manager.filter(**{ '%s__iexact' % UserModel.get_email_field_name(): email, 'is_active': True, ...
class PasswordResetForm(forms.Form): that prevent inactive users and users with unusable passwords from resetting their password. """ email_field_name = UserModel.get_email_field_name() active_users = UserModel._default_manager.filter(**{ '%s__iexact' % email_field_na...
class PasswordResetForm(forms.Form): user. """ email = self.cleaned_data["email"] for user in self.get_users(email): if not domain_override: current_site = get_current_site(request)
class PasswordResetForm(forms.Form): user. """ email = self.cleaned_data["email"] email_field_name = UserModel.get_email_field_name() for user in self.get_users(email): if not domain_override: current_site = get_current_site(request)
class PasswordResetForm(forms.Form): domain = current_site.domain else: site_name = domain = domain_override context = { 'email': email, 'domain': domain, 'site_name': site_name, 'uid': urlsafe_base64...
class PasswordResetForm(forms.Form): domain = current_site.domain else: site_name = domain = domain_override user_email = getattr(user, email_field_name) context = { 'email': user_email, 'domain': domain, ...
class PasswordResetForm(forms.Form): } self.send_mail( subject_template_name, email_template_name, context, from_email, email, html_email_template_name=html_email_template_name, )
class PasswordResetForm(forms.Form): } self.send_mail( subject_template_name, email_template_name, context, from_email, user_email, html_email_template_name=html_email_template_name, )
class PasswordResetFormTest(TestDataMixin, TestCase): self.assertFalse(form.is_valid()) self.assertEqual(form['email'].errors, [_('Enter a valid email address.')]) def test_nonexistent_email(self): """ Test nonexistent email address. This should not fail because it would
class PasswordResetFormTest(TestDataMixin, TestCase): self.assertFalse(form.is_valid()) self.assertEqual(form['email'].errors, [_('Enter a valid email address.')]) def test_user_email_unicode_collision(self): User.objects.create_user('mike123', 'mike@example.org', 'test123') User.ob...
class _AtIndexer(_ScalarAccessIndexer): if is_setter: return list(key) for ax, i in zip(self.obj.axes, key): if ax.is_integer(): if not is_integer(i): raise ValueError( "At based indexing on an integer index " ...
class _AtIndexer(_ScalarAccessIndexer): if is_setter: return list(key) lkey = list(key) for n, (ax, i) in enumerate(zip(self.obj.axes, key)): lkey[n] = ax._convert_scalar_indexer(i, kind="loc") return tuple(lkey) @Appender(IndexingMixin.iat.__doc__)
class TestScalar2: result = df.iat[2, 0] assert result == 2 def test_at_to_fail(self): # at should not fallback # GH 7814 s = Series([1, 2, 3], index=list("abc")) result = s.at["a"] assert result == 1 msg = ( "At based indexing on an non-i...
class TestScalar2: result = df.iat[2, 0] assert result == 2 def test_series_at_raises_type_error(self): # at should not fallback # GH 7814 # GH#31724 .at should match .loc ser = Series([1, 2, 3], index=list("abc")) result = ser.at["a"] assert result =...
from .helper import on_ci "Tests/images/crash_1.tif", "Tests/images/crash_2.tif", "Tests/images/crash-2020-10-test.tif", ], ) @pytest.mark.filterwarnings("ignore:Possibly corrupt EXIF data")
from .helper import on_ci "Tests/images/crash_1.tif", "Tests/images/crash_2.tif", "Tests/images/crash-2020-10-test.tif", "Tests/images/crash-1152ec2d1a1a71395b6f2ce6721c38924d025bf3.tif", "Tests/images/crash-0e16d3bfb83be87356d026d66919deaefca44dac.tif", ], ) @pytest.mark.fil...
class DataFrame(NDFrame): ) return result def transpose(self, *args, **kwargs): """ Transpose index and columns.
class DataFrame(NDFrame): ) return result def transpose(self, *args, copy: bool = False): """ Transpose index and columns.
class DataFrame(NDFrame): Parameters ---------- *args, **kwargs Additional arguments and keywords have no effect but might be accepted for compatibility with numpy. Returns -------
class DataFrame(NDFrame): Parameters ---------- *args : tuple, optional Accepted for compatibility with NumPy. copy : bool, default False Whether to copy the data after transposing, even for DataFrames with a single dtype. Note that a cop...
class DataFrame(NDFrame): dtype: object """ nv.validate_transpose(args, dict()) return super().transpose(1, 0, **kwargs) T = property(transpose)
class DataFrame(NDFrame): dtype: object """ nv.validate_transpose(args, dict()) # construct the args dtypes = list(self.dtypes) if self._is_homogeneous_type and dtypes and is_extension_array_dtype(dtypes[0]): # We have EAs with the same dtype. We can preserve...
class NDFrame(PandasObject, SelectionMixin): self._data.set_axis(axis, labels) self._clear_item_cache() def transpose(self, *args, **kwargs): """ Permute the dimensions of the %(klass)s Parameters ---------- args : %(args_transpose)s copy : bool, def...
class NDFrame(PandasObject, SelectionMixin): self._data.set_axis(axis, labels) self._clear_item_cache() def swapaxes(self, axis1, axis2, copy=True): """ Interchange axes and swap values axes appropriately.
def box_df_fail(request): return request.param @pytest.fixture( params=[ (pd.Index, False), (pd.Series, False), (pd.DataFrame, False), pytest.param((pd.DataFrame, True), marks=pytest.mark.xfail), (tm.to_array, False), ], ids=id_func, ) def box_transpose_fail(req...
def box_df_fail(request): return request.param @pytest.fixture(params=[pd.Index, pd.Series, pd.DataFrame, tm.to_array], ids=id_func) def box_with_array(request): """
class TestPeriodIndexArithmetic: rng -= pd.offsets.MonthEnd(5) tm.assert_index_equal(rng, expected) def test_pi_add_offset_n_gt1(self, box_transpose_fail): # GH#23215 # add offset to PeriodIndex with freq.n > 1 box, transpose = box_transpose_fail per = pd.Period("20...
class TestPeriodIndexArithmetic: rng -= pd.offsets.MonthEnd(5) tm.assert_index_equal(rng, expected) @pytest.mark.parametrize("transpose", [True, False]) def test_pi_add_offset_n_gt1(self, box_with_array, transpose): # GH#23215 # add offset to PeriodIndex with freq.n > 1 ...
class TestPeriodIndexArithmetic: with pytest.raises(IncompatibleFrequency, match=msg): rng -= other def test_parr_add_sub_td64_nat(self, box_transpose_fail): # GH#23320 special handling for timedelta64("NaT") box, transpose = box_transpose_fail pi = pd.period_range("199...
class TestPeriodIndexArithmetic: with pytest.raises(IncompatibleFrequency, match=msg): rng -= other @pytest.mark.parametrize("transpose", [True, False]) def test_parr_add_sub_td64_nat(self, box_with_array, transpose): # GH#23320 special handling for timedelta64("NaT") pi = p...
class TestPeriodIndexArithmetic: TimedeltaArray._from_sequence(["NaT"] * 9), ], ) def test_parr_add_sub_tdt64_nat_array(self, box_df_fail, other): # FIXME: DataFrame fails because when when operating column-wise # timedelta64 entries become NaT and are treated like datetimes...
class TestPeriodIndexArithmetic: TimedeltaArray._from_sequence(["NaT"] * 9), ], ) def test_parr_add_sub_tdt64_nat_array(self, box_with_array, other): pi = pd.period_range("1994-04-01", periods=9, freq="19D") expected = pd.PeriodIndex(["NaT"] * 9, freq="19D") obj = tm...