buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
def _set(self, key, value, timeout=None): # I didn't found a good way to avoid pickling/unpickling if # key is smaller than chunksize, because in case or <werkzeug.requests> # getting the length consume the data iterator. serialized = pickle.dumps(value, 2) values = {} le...
def _set(self, key, value, timeout=None): # I didn't found a good way to avoid pickling/unpickling if # key is smaller than chunksize, because in case or <werkzeug.requests> # getting the length consume the data iterator. serialized = self._serializer.dumps(value) values = {} ...
def _get(self, key): if not serialized: return None return pickle.loads(serialized)
def _get(self, key): if not serialized: return None return self._serializer.loads(serialized)
:copyright: (c) 2010 by Thadeus Burgess. :license: BSD, see LICENSE for more details. """ from flask_caching.backends.base import BaseCache from flask_caching.backends.base import iteritems_wrapper try: import cPickle as pickle except ImportError: # pragma: no cover import pickle # type: ignore cla...
:copyright: (c) 2010 by Thadeus Burgess. :license: BSD, see LICENSE for more details. """ from flask_caching.backends.base import ( BaseCache, extract_serializer_args, iteritems_wrapper ) class RedisCache(BaseCache):
def __init__( key_prefix=None, **kwargs ): super().__init__(default_timeout) if host is None: raise ValueError("RedisCache host parameter may not be None") if isinstance(host, str):
def __init__( key_prefix=None, **kwargs ): super().__init__(default_timeout, **extract_serializer_args(kwargs)) if host is None: raise ValueError("RedisCache host parameter may not be None") if isinstance(host, str):
def dump_object(self, value): t = type(value) if t == int: return str(value).encode("ascii") return b"!" + pickle.dumps(value) def load_object(self, value): """The reversal of :meth:`dump_object`. This might be called with
def dump_object(self, value): t = type(value) if t == int: return str(value).encode("ascii") return b"!" + self._serializer.dumps(value) def load_object(self, value): """The reversal of :meth:`dump_object`. This might be called with
def load_object(self, value): return None if value.startswith(b"!"): try: return pickle.loads(value[1:]) except pickle.PickleError: return None try: return int(value)
def load_object(self, value): return None if value.startswith(b"!"): try: return self._serializer.loads(value[1:]) except self._serialization_error: return None try: return int(value)
import logging from time import time from flask_caching.backends.base import BaseCache try: import cPickle as pickle except ImportError: # pragma: no cover import pickle # type: ignore logger = logging.getLogger(__name__)
import logging from time import time from flask_caching.backends.base import BaseCache, extract_serializer_args logger = logging.getLogger(__name__)
class SimpleCache(BaseCache): to ``False``. """ def __init__(self, threshold=500, default_timeout=300, ignore_errors=False): super().__init__(default_timeout) self._cache = {} self.clear = self._cache.clear self._threshold = threshold
class SimpleCache(BaseCache): to ``False``. """ def __init__( self, threshold=500, default_timeout=300, ignore_errors=False, **kwargs ): super().__init__(default_timeout, **extract_serializer_args(kwargs)) self._cache = {} self.clear = self._cache.c...
def get(self, key): if not expired: hit_or_miss = "hit" try: result = pickle.loads(value) except Exception as exc: logger.error("get key %r -> %s", key, exc) expiredstr = "(expired)" if expired else ""
def get(self, key): if not expired: hit_or_miss = "hit" try: result = self._serializer.loads(value) except Exception as exc: logger.error("get key %r -> %s", key, exc) expiredstr = "(expired)" if expired else ""
def get(self, key): def set(self, key, value, timeout=None): expires = self._normalize_timeout(timeout) self._prune() item = (expires, pickle.dumps(value, pickle.HIGHEST_PROTOCOL)) self._cache[key] = item logger.debug("set key %r", key) return True
def get(self, key): def set(self, key, value, timeout=None): expires = self._normalize_timeout(timeout) self._prune() item = (expires, self._serializer.dumps(value)) self._cache[key] = item logger.debug("set key %r", key) return True
def set(self, key, value, timeout=None): def add(self, key, value, timeout=None): expires = self._normalize_timeout(timeout) self._prune() item = (expires, pickle.dumps(value, pickle.HIGHEST_PROTOCOL)) updated = False should_add = key not in self._cache if should_add:
def set(self, key, value, timeout=None): def add(self, key, value, timeout=None): expires = self._normalize_timeout(timeout) self._prune() item = (expires, self._serializer.dumps(value)) updated = False should_add = key not in self._cache if should_add:
""" import platform from flask_caching.backends.base import BaseCache try: import cPickle as pickle except ImportError: # pragma: no cover import pickle # type: ignore class UWSGICache(BaseCache):
""" import platform from flask_caching.backends.base import BaseCache, extract_serializer_args class UWSGICache(BaseCache):
class UWSGICache(BaseCache): you only have to provide the name of the cache. """ def __init__(self, default_timeout=300, cache=""): super().__init__(default_timeout) if platform.python_implementation() == "PyPy": raise RuntimeError(
class UWSGICache(BaseCache): you only have to provide the name of the cache. """ def __init__(self, default_timeout=300, cache="", **kwargs): super().__init__(default_timeout, **extract_serializer_args(kwargs)) if platform.python_implementation() == "PyPy": raise RuntimeErr...
def get(self, key): rv = self._uwsgi.cache_get(key, self.cache) if rv is None: return return pickle.loads(rv) def delete(self, key): return self._uwsgi.cache_del(key, self.cache)
def get(self, key): rv = self._uwsgi.cache_get(key, self.cache) if rv is None: return return self._serializer.loads(rv) def delete(self, key): return self._uwsgi.cache_del(key, self.cache)
def delete(self, key): def set(self, key, value, timeout=None): return self._uwsgi.cache_update( key, pickle.dumps(value), self._normalize_timeout(timeout), self.cache, )
def delete(self, key): def set(self, key, value, timeout=None): return self._uwsgi.cache_update( key, self._serializer.dumps(value), self._normalize_timeout(timeout), self.cache, )
def set(self, key, value, timeout=None): def add(self, key, value, timeout=None): return self._uwsgi.cache_set( key, pickle.dumps(value), self._normalize_timeout(timeout), self.cache, )
def set(self, key, value, timeout=None): def add(self, key, value, timeout=None): return self._uwsgi.cache_set( key, self._serializer.dumps(value), self._normalize_timeout(timeout), self.cache, )
import pytest import flask_caching as fsc try: __import__("pytest_xprocess")
import pytest import flask_caching as fsc from flask_caching.serialization import json, JSONError, pickle, PickleError try: __import__("pytest_xprocess")
def xprocess(): pytest.skip("pytest-xprocess not installed.") @pytest.fixture def app(request): app = flask.Flask( request.module.__name__, template_folder=os.path.dirname(__file__) ) app.testing = True app.config["CACHE_TYPE"] = "simple" return app
def xprocess(): pytest.skip("pytest-xprocess not installed.") @pytest.fixture(params=[ {}, {'serializer_impl': pickle, 'serializer_error': PickleError}, {'serializer_impl': json, 'serializer_error': JSONError} ]) def serialization_args(request): return request.param.copy() @pytest.fixture(pa...
def test_generic_has(self, c): assert c.has("foo") in (False, 0) assert c.has("spam") in (False, 0) def test_generic_get_bytes(self, c): assert c.set("foo", b"bar") assert c.get("foo") == b"bar" class TestSimpleCache(GenericCacheTests): @pytest.fixture def make_cache(self)...
def test_generic_has(self, c): assert c.has("foo") in (False, 0) assert c.has("spam") in (False, 0) class TestSimpleCache(GenericCacheTests): @pytest.fixture def make_cache(self, serialization_args): return lambda: backends.SimpleCache(**serialization_args) def test_purge(self): ...
def test_purge(self): class TestFileSystemCache(GenericCacheTests): @pytest.fixture def make_cache(self, tmpdir): return lambda **kw: backends.FileSystemCache(cache_dir=str(tmpdir), **kw) def test_filesystemcache_hashes(self, make_cache, hash_method): cache = make_cache(hash_method=hash_me...
def test_purge(self): class TestFileSystemCache(GenericCacheTests): @pytest.fixture def make_cache(self, tmpdir, serialization_args): return lambda **kw: backends.FileSystemCache( cache_dir=str(tmpdir), **{**kw, **serialization_args} ) def test_filesystemcache_hashes(self, make...
def requirements(self, redis_server): pass @pytest.fixture(params=(None, False, True, gen_key_prefix)) def make_cache(self, request): key_prefix = "werkzeug-test-case:" if request.param is None: host = "localhost"
def requirements(self, redis_server): pass @pytest.fixture(params=(None, False, True, gen_key_prefix)) def make_cache(self, request, serialization_args): key_prefix = "werkzeug-test-case:" if request.param is None: host = "localhost"
def make_cache(self, request): else: host = redis.Redis() c = backends.RedisCache(host=host, key_prefix=key_prefix) yield lambda: c c.clear()
def make_cache(self, request): else: host = redis.Redis() c = backends.RedisCache(host=host, key_prefix=key_prefix, **serialization_args) yield lambda: c c.clear()
def requirements(self, memcache_server): pass @pytest.fixture def make_cache(self): c = backends.MemcachedCache(key_prefix="werkzeug-test-case:") yield lambda: c c.clear()
def requirements(self, memcache_server): pass @pytest.fixture def make_cache(self, serialization_args): c = backends.MemcachedCache(key_prefix="werkzeug-test-case:", **serialization_args) yield lambda: c c.clear()
import hashlib import time from flask import request def test_cached_view(app, cache):
import hashlib import time import pytest from flask import request, Response def test_cached_view(app, cache):
def cached_view(): assert the_time != rv.data.decode("utf-8") def test_cached_view_unless(app, cache): @app.route("/a") @cache.cached(5, unless=lambda: True)
def cached_view(): assert the_time != rv.data.decode("utf-8") @pytest.mark.parametrize('response,mime_type', ( ('123', 'text/plain'), ('["1"]', 'application/json'), ('<html></html>', 'text/html'), (b"\x00", 'application/octet-stream'), ('123', None) )) @pytest.mark.parametrize('status', (200, '200 OK'...
class Templar: res = ansible_native_concat(rf) else: res = j2_concat(rf) if getattr(new_context, 'unsafe', False): res = wrap_var(res) except TypeError as te: if 'AnsibleUndefined' in to_native(te):
class Templar: res = ansible_native_concat(rf) else: res = j2_concat(rf) unsafe = getattr(new_context, 'unsafe', False) if unsafe: res = wrap_var(res) except TypeError as te: if 'Ansib...
class Templar: res_newlines = _count_newlines_from_end(res) if data_newlines > res_newlines: res += self.environment.newline_sequence * (data_newlines - res_newlines) return res except (UndefinedError, AnsibleUndefinedVariable) as e: if...
class Templar: res_newlines = _count_newlines_from_end(res) if data_newlines > res_newlines: res += self.environment.newline_sequence * (data_newlines - res_newlines) if unsafe: res = wrap_var(res) return res ...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = """ author: - xuxinkun
from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = r""" author: - xuxinkun
DOCUMENTATION = """ options: kubectl_pod: description: - Pod name. Required when the host name does not match pod name. default: '' vars: - name: ansible_kubectl_pod
DOCUMENTATION = """ options: kubectl_pod: description: - Pod name. - Required when the host name does not match pod name. default: '' vars: - name: ansible_kubectl_pod
DOCUMENTATION = """ - name: K8S_AUTH_POD kubectl_container: description: - Container name. Required when a pod contains more than one container. default: '' vars: - name: ansible_kubectl_container
DOCUMENTATION = """ - name: K8S_AUTH_POD kubectl_container: description: - Container name. - Required when a pod contains more than one container. default: '' vars: - name: ansible_kubectl_container
class Connection(ConnectionBase): """ Build the local kubectl exec command to run cmd on remote_host """ local_cmd = [self.transport_cmd] # Build command options based on doc string doc_yaml = AnsibleLoader(self.documentation).get_single_data()
class Connection(ConnectionBase): """ Build the local kubectl exec command to run cmd on remote_host """ local_cmd = [self.transport_cmd] censored_local_cmd = [self.transport_cmd] # Build command options based on doc string doc_yaml = AnsibleLoader(self.documentation).ge...
class Connection(ConnectionBase): # Translate verify_ssl to skip_verify_ssl, and output as string skip_verify_ssl = not self.get_option(key) local_cmd.append(u'{0}={1}'.format(self.connection_options[key], str(skip_verify_ssl).lower())) elif not key.endswith('...
class Connection(ConnectionBase): # Translate verify_ssl to skip_verify_ssl, and output as string skip_verify_ssl = not self.get_option(key) local_cmd.append(u'{0}={1}'.format(self.connection_options[key], str(skip_verify_ssl).lower())) censored_local_cmd....
class Connection(ConnectionBase): """ Run a command in the container """ super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable) local_cmd = self._build_exec_cmd([self._play_context.executable, '-c', cmd]) display.vvv("EXEC %s" % (local_cmd,), host=self._play_cont...
class Connection(ConnectionBase): """ Run a command in the container """ super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable) local_cmd, censored_local_cmd = self._build_exec_cmd([self._play_context.executable, '-c', cmd]) display.vvv("EXEC %s" % (censored_loca...
class Connection(ConnectionBase): count = ' count=0' else: count = '' args = self._build_exec_cmd([self._play_context.executable, "-c", "dd of=%s bs=%s%s" % (out_path, BUFSIZE, count)]) args = [to_bytes(i, errors='surrogate_or_strict') for i in args] ...
class Connection(ConnectionBase): count = ' count=0' else: count = '' args, dummy = self._build_exec_cmd([self._play_context.executable, "-c", "dd of=%s bs=%s%s" % (out_path, BUFSIZE, count)]) args = [to_bytes(i, errors='surrogate_or_strict') for i in ...
class Connection(ConnectionBase): # kubectl doesn't have native support for fetching files from # running containers, so we use kubectl exec to implement this args = self._build_exec_cmd([self._play_context.executable, "-c", "dd if=%s bs=%s" % (in_path, BUFSIZE)]) args = [to_bytes(i, er...
class Connection(ConnectionBase): # kubectl doesn't have native support for fetching files from # running containers, so we use kubectl exec to implement this args, dummy = self._build_exec_cmd([self._play_context.executable, "-c", "dd if=%s bs=%s" % (in_path, BUFSIZE)]) args = [to_byte...
else: def parse_cookie(cookie): if cookie == '': return {} if not isinstance(cookie, http_cookies.BaseCookie): try: c = SimpleCookie() c.load(cookie) except http_cookies.CookieError: # Invalid cookie return {} else: c = cookie...
else: def parse_cookie(cookie): """ Return a dictionary parsed from a `Cookie:` header string. """ cookiedict = {} if six.PY2: cookie = force_str(cookie) for chunk in cookie.split(str(';')): if str('=') in chunk: key, val = chunk.split(str('='), 1) else: ...
from django.http import ( from django.test import TestCase from django.utils import six from django.utils._os import upath from django.utils.encoding import force_text, smart_str from django.utils.functional import lazy lazystr = lazy(force_text, six.text_type)
from django.http import ( from django.test import TestCase from django.utils import six from django.utils._os import upath from django.utils.encoding import force_str, force_text, smart_str from django.utils.functional import lazy lazystr = lazy(force_text, six.text_type)
class CookieTests(unittest.TestCase): c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c['test'].value, c2['test'].value) def test_decode_2(self): """
class CookieTests(unittest.TestCase): c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c['test'].value, c2['test'].value) c3 = parse_cookie(c.output()[12:]) self.assertEqual(c['test'].value, c3['test']) def test_decode_2(self): """
class CookieTests(unittest.TestCase): c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c['test'].value, c2['test'].value) def test_nonstandard_keys(self): """
class CookieTests(unittest.TestCase): c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c['test'].value, c2['test'].value) c3 = parse_cookie(c.output()[12:]) self.assertEqual(c['test'].value, c3['test']) def test_nonstandard_keys(self): """
class CookieTests(unittest.TestCase): """ self.assertIn('good_cookie', parse_cookie('a:=b; a:=c; good_cookie=yes').keys()) def test_httponly_after_load(self): """ Test that we can use httponly attribute on cookies that we load
class CookieTests(unittest.TestCase): """ self.assertIn('good_cookie', parse_cookie('a:=b; a:=c; good_cookie=yes').keys()) def test_python_cookies(self): """ Test cases copied from Python's Lib/test/test_http_cookies.py """ self.assertEqual(parse_cookie('chips=ahoy; ...
from django.core.exceptions import SuspiciousOperation from django.core.handlers.wsgi import LimitedStream, WSGIRequest from django.http import ( HttpRequest, HttpResponse, RawPostDataException, UnreadablePostError, build_request_repr, parse_cookie, ) from django.test import RequestFactory, SimpleTestCase, over...
from django.core.exceptions import SuspiciousOperation from django.core.handlers.wsgi import LimitedStream, WSGIRequest from django.http import ( HttpRequest, HttpResponse, RawPostDataException, UnreadablePostError, build_request_repr, ) from django.test import RequestFactory, SimpleTestCase, override_settings ...
class RequestsTests(SimpleTestCase): request = WSGIRequest({'PATH_INFO': wsgi_str("/سلام/"), 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) self.assertEqual(request.path, "/سلام/") def test_parse_cookie(self): self.assertEqual(parse_cookie('invalid@key=true'), {}) def test_httpr...
class RequestsTests(SimpleTestCase): request = WSGIRequest({'PATH_INFO': wsgi_str("/سلام/"), 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) self.assertEqual(request.path, "/سلام/") def test_httprequest_location(self): request = HttpRequest() self.assertEqual(request.build_abs...
def url_has_any_extension(url, extensions): def _safe_ParseResult(parts, encoding='utf8', path_encoding='utf8'): return ( to_native_str(parts.scheme), to_native_str(parts.netloc.encode('idna')), # default encoding for path component SHOULD be UTF-8 quote(to_bytes(parts.path, path_...
def url_has_any_extension(url, extensions): def _safe_ParseResult(parts, encoding='utf8', path_encoding='utf8'): # IDNA encoding can fail for too long labels (>63 characters) # or missing labels (e.g. http://.example.com) try: netloc = parts.netloc.encode('idna') except UnicodeError: n...
class CanonicalizeUrlTest(unittest.TestCase): # without encoding, already canonicalized URL is canonicalized identically self.assertEqual(canonicalize_url(canonicalized), canonicalized) class AddHttpIfNoScheme(unittest.TestCase):
class CanonicalizeUrlTest(unittest.TestCase): # without encoding, already canonicalized URL is canonicalized identically self.assertEqual(canonicalize_url(canonicalized), canonicalized) def test_canonicalize_url_idna_exceptions(self): # missing DNS label self.assertEqual( ...
class TimeGrouper(Grouper): # because replace() will swallow the nanosecond part # thus last bin maybe slightly before the end if the end contains # nanosecond part and lead to `Values falls after last bin` error binner = labels = date_range( freq=self.freq, start...
class TimeGrouper(Grouper): # because replace() will swallow the nanosecond part # thus last bin maybe slightly before the end if the end contains # nanosecond part and lead to `Values falls after last bin` error # GH 25758: If DST lands at midnight (e.g. 'America/Havana'), user feedback...
def test_downsample_across_dst_weekly(): tm.assert_series_equal(result, expected) def test_resample_with_nat(): # GH 13020 index = DatetimeIndex(
def test_downsample_across_dst_weekly(): tm.assert_series_equal(result, expected) def test_downsample_dst_at_midnight(): # GH 25758 start = datetime(2018, 11, 3, 12) end = datetime(2018, 11, 5, 12) index = pd.date_range(start, end, freq="1H") index = index.tz_localize("UTC").tz_convert("Americ...
from django.http import ( HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotFound, HttpResponseServerError,
from urllib.parse import quote from django.http import ( HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotFound, HttpResponseServerError,
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') exception The message from the exception which triggered the 404 (if one was ...
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/'). It's quoted to prevent a content injection attack. exception The ...
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): if isinstance(message, str): exception_repr = message context = { 'request_path': request.path, 'exception': exception_repr, } try:
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): if isinstance(message, str): exception_repr = message context = { 'request_path': quote(request.path), 'exception': exception_repr, } try:
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): raise template = Engine().from_string( '<h1>Not Found</h1>' '<p>The requested URL {{ request_path }} was not found on this server.</p>') body = template.render(Context(context)) con...
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): raise template = Engine().from_string( '<h1>Not Found</h1>' '<p>The requested resource was not found on this server.</p>') body = template.render(Context(context)) content_type = 't...
import unittest from django.core.exceptions import ImproperlyConfigured
import sys import unittest from django.core.exceptions import ImproperlyConfigured
try: except ImportError: # Python < 3.5 HTTPStatus = None class HandlerTests(SimpleTestCase):
try: except ImportError: # Python < 3.5 HTTPStatus = None PY37 = sys.version_info >= (3, 7, 0) class HandlerTests(SimpleTestCase):
class HandlerRequestTests(SimpleTestCase): def test_invalid_urls(self): response = self.client.get('~%A9helloworld') self.assertContains(response, '~%A9helloworld', status_code=404) response = self.client.get('d%aao%aaw%aan%aal%aao%aaa%aad%aa/') self.assertContains(response, 'd%AAo...
class HandlerRequestTests(SimpleTestCase): def test_invalid_urls(self): response = self.client.get('~%A9helloworld') self.assertEqual(response.status_code, 404) self.assertEqual(response.context['request_path'], '/~%25A9helloworld' if PY37 else '/%7E%25A9helloworld') response = sel...
class PamdRule(PamdLine): valid_control_actions = ['ignore', 'bad', 'die', 'ok', 'done', 'reset'] def __init__(self, rule_type, rule_control, rule_path, rule_args=None): self._control = None self._args = None self.rule_type = rule_type
class PamdRule(PamdLine): valid_control_actions = ['ignore', 'bad', 'die', 'ok', 'done', 'reset'] def __init__(self, rule_type, rule_control, rule_path, rule_args=None): self.prev = None self.next = None self._control = None self._args = None self.rule_type = rule_type
class PamdService(object): if current_line.matches(rule_type, rule_control, rule_path): if current_line.prev is not None: current_line.prev.next = current_line.next current_line.next.prev = current_line.prev else: se...
class PamdService(object): if current_line.matches(rule_type, rule_control, rule_path): if current_line.prev is not None: current_line.prev.next = current_line.next if current_line.next is not None: current_line.next.prev = curr...
session required pam_unix.so""" auth required pam_env.so """ self.pamd = PamdService(self.system_auth_string) def test_properly_parsed(self):
session required pam_unix.so""" auth required pam_env.so """ self.no_header_system_auth_string = """auth required pam_env.so auth sufficient pam_unix.so nullok try_first_pass auth requisite pam_succeed_if.so uid auth required pam_deny.so """ self.pamd = PamdSer...
session required pam_unix.so""" self.assertFalse(self.pamd.remove('account', 'required', 'pam_unix.so')) test_rule = PamdRule('account', 'required', 'pam_unix.so') self.assertNotIn(str(test_rule), str(self.pamd))
session required pam_unix.so""" self.assertFalse(self.pamd.remove('account', 'required', 'pam_unix.so')) test_rule = PamdRule('account', 'required', 'pam_unix.so') self.assertNotIn(str(test_rule), str(self.pamd)) def test_remove_first_rule(self): no_header_service = PamdService(s...
from .helper import on_ci "Tests/images/crash-4f085cc12ece8cde18758d42608bed6a2a2cfb1c.tif", "Tests/images/crash-86214e58da443d2b80820cff9677a38a33dcbbca.tif", "Tests/images/crash-f46f5b2f43c370fe65706c11449f567ecc345e74.tif", ], ) @pytest.mark.filterwarnings("ignore:Possibly corrupt EXIF da...
from .helper import on_ci "Tests/images/crash-4f085cc12ece8cde18758d42608bed6a2a2cfb1c.tif", "Tests/images/crash-86214e58da443d2b80820cff9677a38a33dcbbca.tif", "Tests/images/crash-f46f5b2f43c370fe65706c11449f567ecc345e74.tif", "Tests/images/crash-63b1dffefc8c075ddc606c0a2f5fdc15ece78863....
class Sequential(Model): def __init__(self, layers=None, name=None): super(Sequential, self).__init__(name=name) # Add to the model any layers passed to the constructor. if layers:
class Sequential(Model): def __init__(self, layers=None, name=None): super(Sequential, self).__init__(name=name) self._build_input_shape = None # Add to the model any layers passed to the constructor. if layers:
class Sequential(Model): for layer in self._layers: x = layer(x) self.outputs = [x] if self._layers: self._layers[0].batch_input_shape = batch_shape if self.inputs: self._init_graph_network(self.inputs,
class Sequential(Model): for layer in self._layers: x = layer(x) self.outputs = [x] self._build_input_shape = input_shape if self.inputs: self._init_graph_network(self.inputs,
class Sequential(Model): return (proba > 0.5).astype('int32') def get_config(self): config = [] for layer in self.layers: config.append({ 'class_name': layer.__class__.__name__, 'config': layer.get_config() }) return copy.d...
class Sequential(Model): return (proba > 0.5).astype('int32') def get_config(self): layer_configs = [] for layer in self.layers: layer_configs.append({ 'class_name': layer.__class__.__name__, 'config': layer.get_config() }) ...
def test_sequential(in_tmpdir): nloss = model.evaluate(x_test, y_test, verbose=0) assert(loss == nloss) # test serialization config = model.get_config() Sequential.from_config(config) model.summary() json_str = model.to_json()
def test_sequential(in_tmpdir): nloss = model.evaluate(x_test, y_test, verbose=0) assert(loss == nloss) # Test serialization config = model.get_config() assert 'name' in config new_model = Sequential.from_config(config) assert new_model.weights # Model should be built. model.summary()...
def test_nested_sequential(in_tmpdir): nloss = model.evaluate(x_test, y_test, verbose=0) assert(loss == nloss) # test serialization config = model.get_config() Sequential.from_config(config)
def test_nested_sequential(in_tmpdir): nloss = model.evaluate(x_test, y_test, verbose=0) assert(loss == nloss) # Test serialization config = model.get_config() Sequential.from_config(config)
def test_sequential_deferred_build(): assert len(model.layers) == 2 assert len(model.weights) == 4 config = model.get_config() new_model = keras.models.Sequential.from_config(config) assert new_model.built is True assert len(new_model.layers) == 2 assert len(new_model.weights) == 4
def test_sequential_deferred_build(): assert len(model.layers) == 2 assert len(model.weights) == 4 # Test serialization config = model.get_config() assert 'name' in config new_model = Sequential.from_config(config) assert new_model.built is True assert len(new_model.layers) == 2 ass...
class Series(base.IndexOpsMixin, generic.NDFrame): """ kwargs["inplace"] = validate_bool_kwarg(kwargs.get("inplace", False), "inplace") non_mapping = is_scalar(index) or ( is_list_like(index) and not is_dict_like(index) ) if non_mapping: return self._set_...
class Series(base.IndexOpsMixin, generic.NDFrame): """ kwargs["inplace"] = validate_bool_kwarg(kwargs.get("inplace", False), "inplace") if callable(index) or is_dict_like(index): return super().rename(index=index, **kwargs) else: return self._set_name(index, inpl...
class TestSeriesAlterAxes: expected = Series([1, 2, 3], index=expected_index) tm.assert_series_equal(result, expected) def test_set_axis_inplace_axes(self, axis_series): # GH14636 ser = Series(np.arange(4), index=[1, 3, 5, 7], dtype="int64")
class TestSeriesAlterAxes: expected = Series([1, 2, 3], index=expected_index) tm.assert_series_equal(result, expected) def test_rename_with_custom_indexer(self): # GH 27814 class MyIndexer: pass ix = MyIndexer() s = Series([1, 2, 3]).rename(ix) a...
class ExtensionBlock(Block): new_values = self.values if inplace else self.values.copy() if isinstance(new, np.ndarray) and len(new) == len(mask): new = new[mask] mask = _safe_reshape(mask, new_values.shape)
class ExtensionBlock(Block): new_values = self.values if inplace else self.values.copy() if isinstance(new, (np.ndarray, ExtensionArray)) and len(new) == len(mask): new = new[mask] mask = _safe_reshape(mask, new_values.shape)
class TestUpdate: # GH 33215 series.update(other) tm.assert_series_equal(series, expected)
class TestUpdate: # GH 33215 series.update(other) tm.assert_series_equal(series, expected) @pytest.mark.parametrize( "result, target, expected", [ ( Series(["a", None], dtype="string"), Series([None, "b"], dtype="string"), ...
def do_POST(self): L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) L.append(self.rfile.read(chunk_size)) size_remaining -= len(L[-1]) data = ''.join(L)
def do_POST(self): L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) chunk = self.rfile.read(chunk_size) if not chunk: break L.append(chunk) size_remaining -= len(L[-1]...
from ansible.parsing.dataloader import DataLoader from ansible.release import __version__ from ansible.utils.path import unfrackpath from ansible.utils.vars import load_extra_vars, load_options_vars from ansible.vars.manager import VariableManager from ansible.parsing.vault import PromptVaultSecret, get_file_vault_secr...
from ansible.parsing.dataloader import DataLoader from ansible.release import __version__ from ansible.utils.path import unfrackpath from ansible.utils.vars import load_extra_vars, load_options_vars from ansible.utils.unsafe_proxy import AnsibleUnsafeBytes from ansible.vars.manager import VariableManager from ansible.p...
class CLI(with_metaclass(ABCMeta, object)): except EOFError: pass return (sshpass, becomepass) def normalize_become_options(self):
class CLI(with_metaclass(ABCMeta, object)): except EOFError: pass # we 'wrap' the passwords to prevent templating as # they can contain special chars and trigger it incorrectly if sshpass: sshpass = AnsibleUnsafeBytes(sshpass) if becomepass: b...
__metaclass__ = type from collections import Mapping, MutableSequence, Set from ansible.module_utils.six import string_types, text_type from ansible.module_utils._text import to_text
__metaclass__ = type from collections import Mapping, MutableSequence, Set from ansible.module_utils.six import string_types, text_type, binary_type from ansible.module_utils._text import to_text
class AnsibleUnsafeText(text_type, AnsibleUnsafe): pass class UnsafeProxy(object): def __new__(cls, obj, *args, **kwargs): # In our usage we should only receive unicode strings. # This conditional and conversion exists to sanity check the values # we're given but we may want to take it...
class AnsibleUnsafeText(text_type, AnsibleUnsafe): pass class AnsibleUnsafeBytes(binary_type, AnsibleUnsafe): pass class UnsafeProxy(object): def __new__(cls, obj, *args, **kwargs): if isinstance(obj, AnsibleUnsafe): # Already marked unsafe return obj # In our us...
Roger E. Masse """ from test.test_support import verbose, unlink import imageop, uu, os def main(use_rgbimg=1): # Create binary test files uu.decode(get_qualified_path('testrgb'+os.extsep+'uue'), 'test'+os.extsep+'rgb')
Roger E. Masse """ from test.test_support import verbose, unlink, run_unittest import imageop, uu, os, unittest SIZES = (1, 2, 3, 4) _VALUES = (1, 2, 2**10, 2**15-1, 2**15, 2**15+1, 2**31-2, 2**31-1) VALUES = tuple( -x for x in reversed(_VALUES) ) + (0,) + _VALUES AAAAA = "A" * 1024 class InputValidationTests(u...
def get_qualified_path(name): if os.path.exists(fullname): return fullname return name # rgbimg (unlike imgfile) is portable to platforms other than SGI. # So we prefer to use it. main(use_rgbimg=1)
def get_qualified_path(name): if os.path.exists(fullname): return fullname return name
class LocalFileSystem(FileSystem): raise RuntimeError('Destination exists: %s' % new_path) d = os.path.dirname(new_path) if d and not os.path.exists(d): self.fs.mkdir(d) os.rename(old_path, new_path)
class LocalFileSystem(FileSystem): raise RuntimeError('Destination exists: %s' % new_path) d = os.path.dirname(new_path) if d and not os.path.exists(d): self.mkdir(d) os.rename(old_path, new_path)
class FileSystemTest(unittest.TestCase): pass self.assertTrue([self.path + '/file'], list(self.fs.listdir(self.path + '/'))) class TestImportFile(unittest.TestCase):
class FileSystemTest(unittest.TestCase): pass self.assertTrue([self.path + '/file'], list(self.fs.listdir(self.path + '/'))) def test_move_to_new_dir(self): # Regression test for a bug in LocalFileSystem.move src = os.path.join(self.path, 'src.txt') dest = os.path.join(s...
class LocalCache(collections.OrderedDict): self.limit = limit def __setitem__(self, key, value): while len(self) >= self.limit: self.popitem(last=False) super(LocalCache, self).__setitem__(key, value)
class LocalCache(collections.OrderedDict): self.limit = limit def __setitem__(self, key, value): if self.limit: while len(self) >= self.limit: self.popitem(last=False) super(LocalCache, self).__setitem__(key, value)
if six.PY2: else: from collections.abc import Mapping, MutableMapping from scrapy.utils.datatypes import CaselessDict, SequenceExclude __doctests__ = ['scrapy.utils.datatypes']
if six.PY2: else: from collections.abc import Mapping, MutableMapping from scrapy.utils.datatypes import CaselessDict, SequenceExclude, LocalCache __doctests__ = ['scrapy.utils.datatypes']
class SequenceExcludeTest(unittest.TestCase): for v in [-3, "test", 1.1]: self.assertNotIn(v, d) if __name__ == "__main__": unittest.main()
class SequenceExcludeTest(unittest.TestCase): for v in [-3, "test", 1.1]: self.assertNotIn(v, d) class LocalCacheTest(unittest.TestCase): def test_cache_with_limit(self): cache = LocalCache(limit=2) cache['a'] = 1 cache['b'] = 2 cache['c'] = 3 self.asse...
def from_bytes( Raises: ValueError: The provided byte string is not an ``openssh-key-v1`` key list or the declared key count is negative. UserWarning: The check numbers in the decrypted private byte string do not match (likely due to an incorrect passphra...
def from_bytes( Raises: ValueError: The provided byte string is not an ``openssh-key-v1`` key list, when the declared key count is negative, or when an EOF is found while parsing the key. UserWarning: The check numbers in the decrypted private byte strin...
def from_bytes( at the end of the decrypted private byte string are not as expected. """ byte_stream = PascalStyleByteStream(byte_string) header = byte_stream.read_from_format_instructions_dict( cls.HEADER_FORMAT_INSTRUCTIONS_DICT ) i...
def from_bytes( at the end of the decrypted private byte string are not as expected. """ try: byte_stream = PascalStyleByteStream(byte_string) header = byte_stream.read_from_format_instructions_dict( cls.HEADER_FORMAT_INSTRUCTIONS_...
class LoadAuth(object): if rm_tok: self.rm_token(tok) return tdata
class LoadAuth(object): if rm_tok: self.rm_token(tok) return {} return tdata
def load_inputs_from_input_arg_string(inputs_str, input_exprs_str, input_examples = preprocess_input_examples_arg_string(input_examples_str) for input_tensor_key, (filename, variable_name) in inputs.items(): data = np.load(file_io.FileIO(filename, mode='rb')) # When a variable_name key is specified for th...
def load_inputs_from_input_arg_string(inputs_str, input_exprs_str, input_examples = preprocess_input_examples_arg_string(input_examples_str) for input_tensor_key, (filename, variable_name) in inputs.items(): data = np.load(file_io.FileIO(filename, mode='rb'), allow_pickle=True) # When a variable_name key ...
class EventCollection(LineCollection): .. plot:: gallery/lines_bars_and_markers/eventcollection_demo.py """ segment = (lineoffset + linelength / 2., lineoffset - linelength / 2.) if positions is None or len(positions) == 0: segments = [] elif hasa...
class EventCollection(LineCollection): .. plot:: gallery/lines_bars_and_markers/eventcollection_demo.py """ if positions is None: raise ValueError('positions must be an array-like object') # Force a copy of positions positions = np.array(positions, copy=True) ...
def test_pathcollection_legend_elements(): ax.add_artist(l) fig.canvas.draw()
def test_pathcollection_legend_elements(): ax.add_artist(l) fig.canvas.draw() def test_EventCollection_nosort(): # Check that EventCollection doesn't modify input in place arr = np.array([3, 2, 1, 10]) coll = EventCollection(arr) np.testing.assert_array_equal(arr, np.array([3, 2, 1, 10]))
from pandas._libs.tslibs import ( timezones, tzconversion, ) from pandas.errors import PerformanceWarning from pandas.core.dtypes.common import (
from pandas._libs.tslibs import ( timezones, tzconversion, ) import pandas._libs.tslibs.frequencies as libfrequencies from pandas.errors import PerformanceWarning from pandas.core.dtypes.common import (
default 'raise' "You must pass a freq argument as current index has none." ) freq = get_period_alias(freq) return PeriodArray._from_datetime64(self._data, freq, tz=self.tz)
default 'raise' "You must pass a freq argument as current index has none." ) res = get_period_alias(freq) # https://github.com/pandas-dev/pandas/issues/33358 if res is None: base, stride = libfrequencies._base_and_stride(freq) ...
import dateutil.tz from dateutil.tz import tzlocal import pytest
import warnings import dateutil.tz from dateutil.tz import tzlocal import pytest
class TestToPeriod: with pytest.raises(ValueError, match=INVALID_FREQ_ERR_MSG): date_range("01-Jan-2012", periods=8, freq="EOM") def test_period_dt64_round_trip(self): dti = date_range("1/1/2000", "1/7/2002", freq="B") pi = dti.to_period()
class TestToPeriod: with pytest.raises(ValueError, match=INVALID_FREQ_ERR_MSG): date_range("01-Jan-2012", periods=8, freq="EOM") def test_to_period_infer(self): # https://github.com/pandas-dev/pandas/issues/33358 rng = date_range( start="2019-12-22 06:40:00+00:00", ...
def test_retry_method_not_in_whitelist(self): retry = Retry() with pytest.raises(ReadTimeoutError): retry.increment(method='POST', error=error)
def test_retry_method_not_in_whitelist(self): retry = Retry() with pytest.raises(ReadTimeoutError): retry.increment(method='POST', error=error) def test_retry_default_remove_headers_on_redirect(self): retry = Retry() assert list(retry.remove_headers_on_redirect) == ['Au...
def test_too_many_redirects(self): except MaxRetryError: pass def test_raise_on_redirect(self): http = PoolManager() self.addCleanup(http.clear)
def test_too_many_redirects(self): except MaxRetryError: pass def test_redirect_cross_host_remove_headers(self): http = PoolManager() self.addCleanup(http.clear) r = http.request('GET', '%s/redirect' % self.base_url, fields={'target': '%s/header...
def urlopen(self, method, url, redirect=True, **kw): kw['assert_same_host'] = False kw['redirect'] = False if 'headers' not in kw: kw['headers'] = self.headers if self.proxy is not None and u.scheme == "http": response = conn.urlopen(method, url, **kw)
def urlopen(self, method, url, redirect=True, **kw): kw['assert_same_host'] = False kw['redirect'] = False if 'headers' not in kw: kw['headers'] = self.headers.copy() if self.proxy is not None and u.scheme == "http": response = conn.urlopen(method, url, **kw)
def urlopen(self, method, url, redirect=True, **kw): if not isinstance(retries, Retry): retries = Retry.from_int(retries, redirect=redirect) try: retries = retries.increment(method, url, response=response, _pool=conn) except MaxRetryError:
def urlopen(self, method, url, redirect=True, **kw): if not isinstance(retries, Retry): retries = Retry.from_int(retries, redirect=redirect) # Strip headers marked as unsafe to forward to the redirected location. # Check remove_headers_on_redirect to avoid a potential network call w...
log = logging.getLogger(__name__) # Data structure for representing the metadata of requests that result in a retry. RequestHistory = namedtuple('RequestHistory', ["method", "url", "error", "status", "redirect_location"])
log = logging.getLogger(__name__) # Data structure for representing the metadata of requests that result in a retry. RequestHistory = namedtuple('RequestHistory', ["method", "url", "error", "status", "redirect_location"])
class Retry(object): Whether to respect Retry-After header on status codes defined as :attr:`Retry.RETRY_AFTER_STATUS_CODES` or not. """ DEFAULT_METHOD_WHITELIST = frozenset([
class Retry(object): Whether to respect Retry-After header on status codes defined as :attr:`Retry.RETRY_AFTER_STATUS_CODES` or not. :param iterable remove_headers_on_redirect: Sequence of headers to remove from the request when a response indicating a redirect is returned before fi...
class Retry(object): RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503]) #: Maximum backoff time. BACKOFF_MAX = 120 def __init__(self, total=10, connect=None, read=None, redirect=None, status=None, method_whitelist=DEFAULT_METHOD_WHITELIST, status_forcelist=None, b...
class Retry(object): RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503]) DEFAULT_REDIRECT_HEADERS_BLACKLIST = frozenset(['Authorization']) #: Maximum backoff time. BACKOFF_MAX = 120 def __init__(self, total=10, connect=None, read=None, redirect=None, status=None, method_whitel...
def __init__(self, total=10, connect=None, read=None, redirect=None, status=None self.raise_on_status = raise_on_status self.history = history or tuple() self.respect_retry_after_header = respect_retry_after_header def new(self, **kw): params = dict(
def __init__(self, total=10, connect=None, read=None, redirect=None, status=None self.raise_on_status = raise_on_status self.history = history or tuple() self.respect_retry_after_header = respect_retry_after_header self.remove_headers_on_redirect = remove_headers_on_redirect def new...
def new(self, **kw): raise_on_redirect=self.raise_on_redirect, raise_on_status=self.raise_on_status, history=self.history, ) params.update(kw) return type(self)(**params)
def new(self, **kw): raise_on_redirect=self.raise_on_redirect, raise_on_status=self.raise_on_status, history=self.history, remove_headers_on_redirect=self.remove_headers_on_redirect ) params.update(kw) return type(self)(**params)
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"}