buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
TEST_DATA = [
(URLValidator(), None, ValidationError),
(URLValidator(), 56, ValidationError),
(URLValidator(), 'no_scheme', ValidationError),
# Trailing newlines not accepted
(URLValidator(), 'http://www.djangoproject.com/\n', ValidationError),
(URLValidator(), 'http://[::ffff:192.9.5.5]\n', Val... | TEST_DATA = [
(URLValidator(), None, ValidationError),
(URLValidator(), 56, ValidationError),
(URLValidator(), 'no_scheme', ValidationError),
# Newlines and tabs are not accepted.
(URLValidator(), 'http://www.djangoproject.com/\n', ValidationError),
(URLValidator(), 'http://[::ffff:192.9.5.5]\n'... |
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... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import random
import shlex | from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import errno
import fcntl
import os
import random
import shlex |
import subprocess
import sys
import tempfile
import warnings
from binascii import hexlify
from binascii import unhexlify
from binascii import Error as BinasciiError | import subprocess
import sys
import tempfile
import warnings
from binascii import hexlify
from binascii import unhexlify
from binascii import Error as BinasciiError |
class VaultEditor:
os.remove(tmp_path)
def _edit_file_helper(self, filename, secret,
existing_data=None, force_save=False, vault_id=None):
# Create a tempfile
root, ext = os.path.splitext(os.path.realpath(filename))
fd, tmp_path = tempfile.mkstemp(suffix=... | class VaultEditor:
os.remove(tmp_path)
def _edit_file_helper(self, filename, secret, existing_data=None, force_save=False, vault_id=None):
# Create a tempfile
root, ext = os.path.splitext(os.path.realpath(filename))
fd, tmp_path = tempfile.mkstemp(suffix=ext, dir=C.DEFAULT_LOCAL_T... |
class VaultEditor:
# Figure out the vault id from the file, to select the right secret to re-encrypt it
# (duplicates parts of decrypt, but alas...)
dummy, dummy, cipher_name, vault_id = parse_vaulttext_envelope(b_vaulttext,
... | class VaultEditor:
# Figure out the vault id from the file, to select the right secret to re-encrypt it
# (duplicates parts of decrypt, but alas...)
dummy, dummy, cipher_name, vault_id = parse_vaulttext_envelope(b_vaulttext, filename=filename)
# vault id here may not be the vault id ac... |
class VaultEditor:
return data
# TODO: add docstrings for arg types since this code is picky about that
def write_data(self, data, filename, shred=True):
"""Write the data bytes to given path
This is used to write a byte string to a file or stdout. It is used for | class VaultEditor:
return data
def write_data(self, data, thefile, shred=True, mode=0o600):
# TODO: add docstrings for arg types since this code is picky about that
"""Write the data bytes to given path
This is used to write a byte string to a file or stdout. It is used for |
class VaultEditor:
should be a byte string and not a text type.
:arg data: the byte string (bytes) data
:arg filename: filename to save 'data' to.
:arg shred: if shred==True, make sure that the original data is first shredded so that is cannot be recovered.
:returns: None
... | class VaultEditor:
should be a byte string and not a text type.
:arg data: the byte string (bytes) data
:arg thefile: file descriptor or filename to save 'data' to.
:arg shred: if shred==True, make sure that the original data is first shredded so that is cannot be recovered.
:re... |
dependency tree to find the noun phrase they are referring to – for example:
$9.4 million --> Net income.
Compatible with: spaCy v2.0.0+
Last tested with: v2.1.0
"""
from __future__ import unicode_literals, print_function
| dependency tree to find the noun phrase they are referring to – for example:
$9.4 million --> Net income.
Compatible with: spaCy v2.0.0+
Last tested with: v2.2.1
"""
from __future__ import unicode_literals, print_function
|
def main(model="en_core_web_sm"):
def filter_spans(spans):
# Filter a sequence of spans so they don't contain overlaps
get_sort_key = lambda span: (span.end - span.start, span.start)
sorted_spans = sorted(spans, key=get_sort_key, reverse=True)
result = []
seen_tokens = set()
for span in sorted_... | def main(model="en_core_web_sm"):
def filter_spans(spans):
# Filter a sequence of spans so they don't contain overlaps
# For spaCy 2.1.4+: this function is available as spacy.util.filter_spans()
get_sort_key = lambda span: (span.end - span.start, -span.start)
sorted_spans = sorted(spans, key=get_sort_k... |
def test_filter_spans(doc):
assert len(filtered[1]) == 5
assert filtered[0].start == 1 and filtered[0].end == 4
assert filtered[1].start == 5 and filtered[1].end == 10 | def test_filter_spans(doc):
assert len(filtered[1]) == 5
assert filtered[0].start == 1 and filtered[0].end == 4
assert filtered[1].start == 5 and filtered[1].end == 10
# Test filtering overlaps with earlier preference for identical length
spans = [doc[1:4], doc[2:5], doc[5:10], doc[7:9], doc[1:4]]
... |
def filter_spans(spans):
spans (iterable): The spans to filter.
RETURNS (list): The filtered spans.
"""
get_sort_key = lambda span: (span.end - span.start, span.start)
sorted_spans = sorted(spans, key=get_sort_key, reverse=True)
result = []
seen_tokens = set() | def filter_spans(spans):
spans (iterable): The spans to filter.
RETURNS (list): The filtered spans.
"""
get_sort_key = lambda span: (span.end - span.start, -span.start)
sorted_spans = sorted(spans, key=get_sort_key, reverse=True)
result = []
seen_tokens = set() |
def test_match(wrong):
assert match(Command(wrong, stderr=git_stash_err))
@pytest.mark.parametrize('wrong,fixed', [
('git stash opp', 'git stash pop'),
('git stash Some message', 'git stash save Some message'), | def test_match(wrong):
assert match(Command(wrong, stderr=git_stash_err))
def test_not_match():
assert not match(Command("git", stderr=git_stash_err))
@pytest.mark.parametrize('wrong,fixed', [
('git stash opp', 'git stash pop'),
('git stash Some message', 'git stash save Some message'), |
from thefuck.specific.git import git_support
@git_support
def match(command):
return (command.script.split()[1] == 'stash'
and 'usage:' in command.stderr)
# git's output here is too complicated to be parsed (see the test file)
stash_commands = ( | from thefuck.specific.git import git_support
@git_support
def match(command):
splited_script = command.script.split()
if len(splited_script) > 1:
return (splited_script[1] == 'stash'
and 'usage:' in command.stderr)
else:
return False
# git's output here is too complicated t... |
import ctypes
import datetime as dt
import decimal
import io | import datetime as dt
import decimal
import io |
def test_encode_surrogate_characters():
assert ujson.dumps({"\ud800": "\udfff"}, ensure_ascii=False, sort_keys=True) == out2
@pytest.mark.xfail(
hasattr(sys, "pypy_version_info") and os.name == "nt",
reason="This feature needs fixing! See #552",
)
@pytest.mark.parametrize(
"test_input, expected",
... | def test_encode_surrogate_characters():
assert ujson.dumps({"\ud800": "\udfff"}, ensure_ascii=False, sort_keys=True) == out2
@pytest.mark.parametrize(
"test_input, expected",
[ |
def test_encode_surrogate_characters():
],
)
def test_decode_surrogate_characters(test_input, expected):
# FIXME Wrong output (combined char) on platforms with 16-bit wchar_t
if test_input == '"\uD83D\uDCA9"' and ctypes.sizeof(ctypes.c_wchar) == 2:
pytest.skip("Raw surrogate pairs are not supported ... | def test_encode_surrogate_characters():
],
)
def test_decode_surrogate_characters(test_input, expected):
assert ujson.loads(test_input) == expected
assert ujson.loads(test_input.encode("utf-8", "surrogatepass")) == expected
|
def test_getproxies_environment_keep_no_proxies(self):
self.assertTrue(urllib.proxy_bypass_environment('anotherdomain.com:8888'))
self.assertTrue(urllib.proxy_bypass_environment('newdomain.com:1234'))
def test_proxy_bypass_environment_host_match(self):
bypass = urllib.proxy_bypass_environme... | def test_getproxies_environment_keep_no_proxies(self):
self.assertTrue(urllib.proxy_bypass_environment('anotherdomain.com:8888'))
self.assertTrue(urllib.proxy_bypass_environment('newdomain.com:1234'))
def test_proxy_cgi_ignore(self):
try:
self.env.set('HTTP_PROXY', 'http://somew... |
def getproxies_environment():
If you need a different way, you can pass a proxies dictionary to the
[Fancy]URLopener constructor.
"""
proxies = {}
for name, value in os.environ.items():
name = name.lower()
if value and name[-6:] == '_proxy':
proxies[name[:-6]] = value
... | def getproxies_environment():
If you need a different way, you can pass a proxies dictionary to the
[Fancy]URLopener constructor.
"""
# Get all variables
proxies = {}
for name, value in os.environ.items():
name = name.lower()
if value and name[-6:] == '_proxy':
proxie... |
setup(
python_requires="~=3.6",
install_requires=[
"urwid>=1.1.1",
"pygments>=1.0",
"jedi>=0.18,<1"
],
test_requires=[ | setup(
python_requires="~=3.6",
install_requires=[
"urwid>=1.1.1",
"pygments>=2.7.4",
"jedi>=0.18,<1"
],
test_requires=[ |
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... |
class StringMethods(NoNewAttributesMixin):
if isinstance(others, ABCSeries):
return [others]
elif isinstance(others, ABCIndexClass):
return [Series(others._values, index=others)]
elif isinstance(others, ABCDataFrame):
return [others[x] for x in others]
... | class StringMethods(NoNewAttributesMixin):
if isinstance(others, ABCSeries):
return [others]
elif isinstance(others, ABCIndexClass):
return [Series(others._values, index=idx)]
elif isinstance(others, ABCDataFrame):
return [others[x] for x in others]
el... |
def test_string_array_extract():
result = result.astype(object)
tm.assert_equal(result, expected) | def test_string_array_extract():
result = result.astype(object)
tm.assert_equal(result, expected)
@pytest.mark.parametrize("klass", [tuple, list, np.array, pd.Series, pd.Index])
def test_cat_different_classes(klass):
# https://github.com/pandas-dev/pandas/issues/33425
s = pd.Series(["a", "b", "c"])
... |
def main():
level=dict(type='str', choices=['authNoPriv', 'authPriv']),
integrity=dict(type='str', choices=['md5', 'sha']),
privacy=dict(type='str', choices=['aes', 'des']),
authkey=dict(type='str'),
privkey=dict(type='str'),
),
required_togeth... | def main():
level=dict(type='str', choices=['authNoPriv', 'authPriv']),
integrity=dict(type='str', choices=['md5', 'sha']),
privacy=dict(type='str', choices=['aes', 'des']),
authkey=dict(type='str', no_log=True),
privkey=dict(type='str', no_log=True),
... |
import os
# Import salt libs
import salt.utils.files
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six | import os
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.verify
# Import 3rd-party libs
from salt.ext import six |
def write(data, path, saltenv="base", index=0):
return (
"The path passed in {0} is not relative to the environment " "{1}"
).format(path, saltenv)
dest = os.path.join(__opts__["pillar_roots"][saltenv][index], path)
dest_dir = os.path.dirname(dest)
if not os.path.isdir(dest_dir): | def write(data, path, saltenv="base", index=0):
return (
"The path passed in {0} is not relative to the environment " "{1}"
).format(path, saltenv)
roots_dir = __opts__["pillar_roots"][saltenv][index]
dest = os.path.join(roots_dir, path)
if not salt.utils.verify.clean_path(roots_... |
class MultiPartParser:
remaining = len(stripped_chunk) % 4
while remaining != 0:
over_chunk = field_stream.read(4 - remaining)
stripped_chunk += b"".join(over_chunk.split())
... | class MultiPartParser:
remaining = len(stripped_chunk) % 4
while remaining != 0:
over_chunk = field_stream.read(4 - remaining)
if not over_chunk:
... |
class FileUploadTests(TestCase):
def test_big_base64_newlines_upload(self):
self._test_base64_upload("Big data" * 68000, encode=base64.encodebytes)
def test_unicode_file_name(self):
with sys_tempfile.TemporaryDirectory() as temp_dir:
# This file contains Chinese symbols and an accen... | class FileUploadTests(TestCase):
def test_big_base64_newlines_upload(self):
self._test_base64_upload("Big data" * 68000, encode=base64.encodebytes)
def test_base64_invalid_upload(self):
payload = client.FakePayload('\r\n'.join([
'--' + client.BOUNDARY,
'Content-Dispositi... |
from PIL import Image
"Tests/images/sgi_crash.bin",
"Tests/images/crash-6b7f2244da6d0ae297ee0754a424213444e92778.sgi",
"Tests/images/ossfuzz-5730089102868480.sgi",
],
)
def test_crashes(test_file): | from PIL import Image
"Tests/images/sgi_crash.bin",
"Tests/images/crash-6b7f2244da6d0ae297ee0754a424213444e92778.sgi",
"Tests/images/ossfuzz-5730089102868480.sgi",
"Tests/images/crash-754d9c7ec485ffb76a90eeaab191ef69a2a3a3cd.sgi",
"Tests/images/crash-465703f71a0f0094873a3e0e82c9f... |
class NDFrame(PandasObject, SelectionMixin):
"""
inplace = validate_bool_kwarg(inplace, "inplace")
if axis == 0:
ax = self._info_axis_name
_maybe_transposed_self = self
elif axis == 1:
_maybe_transposed_self = self.T
ax = 1
else:
... | class NDFrame(PandasObject, SelectionMixin):
"""
inplace = validate_bool_kwarg(inplace, "inplace")
axis = self._get_axis_number(axis)
if axis == 0:
ax = self._info_axis_name
_maybe_transposed_self = self
elif axis == 1:
_maybe_transposed_self... |
class TestDataFrameMissingData:
cat = Categorical([np.nan, 2, np.nan])
val = Categorical([np.nan, np.nan, np.nan])
df = DataFrame({"cats": cat, "vals": val})
res = df.fillna(df.median())
v_exp = [np.nan, np.nan, np.nan]
df_exp = DataFrame({"cats": [2, 2, 2], "vals": v_exp... | class TestDataFrameMissingData:
cat = Categorical([np.nan, 2, np.nan])
val = Categorical([np.nan, np.nan, np.nan])
df = DataFrame({"cats": cat, "vals": val})
with tm.assert_produces_warning(RuntimeWarning):
res = df.fillna(df.median())
v_exp = [np.nan, np.nan, np.nan]... |
class TestDataFrameInterpolate:
expected = df.interpolate()
assert_frame_equal(result, expected)
def test_rowwise_alt(self):
df = DataFrame(
{ | class TestDataFrameInterpolate:
expected = df.interpolate()
assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"axis_name, axis_number",
[
pytest.param("rows", 0, id="rows_0"),
pytest.param("index", 0, id="index_0"),
pytest.param("colu... |
# Imports
#-----------------------------------------------------------------------------
try:
from http.cookies import SimpleCookie # Py 3
except ImportError: | # Imports
#-----------------------------------------------------------------------------
try:
from urllib.parse import urlparse # Py 3
except ImportError:
from urlparse import urlparse # Py 2
try:
from http.cookies import SimpleCookie # Py 3
except ImportError: |
#-----------------------------------------------------------------------------
class ZMQStreamHandler(websocket.WebSocketHandler):
def clear_cookie(self, *args, **kwargs):
"""meaningless for websockets"""
pass | #-----------------------------------------------------------------------------
class ZMQStreamHandler(websocket.WebSocketHandler):
def same_origin(self):
"""Check to see that origin and host match in the headers."""
# The difference between version 8 and 13 is that in 8 the
# client sends... |
def allow_draft76(self):
class AuthenticatedZMQStreamHandler(ZMQStreamHandler, IPythonHandler):
def open(self, kernel_id):
self.kernel_id = cast_unicode(kernel_id, 'ascii')
self.session = Session(config=self.config)
self.save_on_message = self.on_message | def allow_draft76(self):
class AuthenticatedZMQStreamHandler(ZMQStreamHandler, IPythonHandler):
def open(self, kernel_id):
# Check to see that origin matches host directly, including ports
if not self.same_origin():
self.log.warn("Cross Origin WebSocket Attempt.")
raise web.... |
def on_first_message(self, msg):
if self.get_current_user() is None:
self.log.warn("Couldn't authenticate WebSocket connection")
raise web.HTTPError(403)
self.on_message = self.save_on_message | def on_first_message(self, msg):
if self.get_current_user() is None:
self.log.warn("Couldn't authenticate WebSocket connection")
raise web.HTTPError(403)
self.on_message = self.save_on_message |
def test_pdf_append_to_bytesio():
f = io.BytesIO(f.getvalue())
im.save(f, format="PDF", append=True)
assert len(f.getvalue()) > initial_size | def test_pdf_append_to_bytesio():
f = io.BytesIO(f.getvalue())
im.save(f, format="PDF", append=True)
assert len(f.getvalue()) > initial_size
@pytest.mark.timeout(1)
def test_redos():
malicious = b" trailer<<>>" + b"\n" * 3456
# This particular exception isn't relevant here.
# The important th... |
import functools
import inspect
import logging
import ssl
import warnings
import requests
from requests import adapters
try:
from requests.packages.urllib3.exceptions import InsecureRequestWarning
except ImportError: | import functools
import inspect
import logging
import os
import ssl
import warnings
import requests
from requests import adapters
from requests.adapters import DEFAULT_POOLBLOCK, DEFAULT_POOLSIZE, DEFAULT_RETRIES
try:
from requests.packages.urllib3.exceptions import InsecureRequestWarning
except ImportError: |
def wrapper(self, *args, **kwargs):
class SSLContextAdapter(adapters.HTTPAdapter):
"""Custom SSLContext Adapter for requests
"""
def init_poolmanager(self, connections, maxsize,
block=adapters.DEFAULT_POOLBLOCK, **pool_kwargs):
context = ssl.SSLContext( | def wrapper(self, *args, **kwargs):
class SSLContextAdapter(adapters.HTTPAdapter):
"""
Custom SSLContext Adapter for requests
"""
def __init__(self, pool_connections=DEFAULT_POOLSIZE,
pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES,
pool_block=DEFAULT_POOL... |
def init_poolmanager(self, connections, maxsize,
if getattr(context, "post_handshake_auth", None) is not None:
context.post_handshake_auth = True
pool_kwargs['ssl_context'] = context
return super().init_poolmanager(
connections, maxsize, block, **pool_kwargs | def init_poolmanager(self, connections, maxsize,
if getattr(context, "post_handshake_auth", None) is not None:
context.post_handshake_auth = True
# Load from the system trust store when possible; per documentation
# this call could silently fail and refuse to configure any
#... |
class PKIConnection:
def __init__(self, protocol='http', hostname='localhost', port='8080',
subsystem=None, accept='application/json',
trust_env=None, verify=False):
"""
Set the parameters for a python-requests based connection to a
Dogtag subsystem. | class PKIConnection:
def __init__(self, protocol='http', hostname='localhost', port='8080',
subsystem=None, accept='application/json',
trust_env=None, verify=True, cert_paths=None):
"""
Set the parameters for a python-requests based connection to a
Dogtag s... |
def __init__(self, protocol='http', hostname='localhost', port='8080',
:param verify: verify TLS/SSL connections and configure CA certs
(default: no)
:type verify: None, bool, str
:return: PKIConnection object.
"""
| def __init__(self, protocol='http', hostname='localhost', port='8080',
:param verify: verify TLS/SSL connections and configure CA certs
(default: no)
:type verify: None, bool, str
:param cert_paths: paths to CA certificates / directories in OpenSSL
format. (default: None)
... |
def __init__(self, protocol='http', hostname='localhost', port='8080',
self.serverURI = self.rootURI
self.session = requests.Session()
self.session.mount("https://", SSLContextAdapter())
self.session.trust_env = trust_env
self.session.verify = verify
| def __init__(self, protocol='http', hostname='localhost', port='8080',
self.serverURI = self.rootURI
self.session = requests.Session()
self.session.mount("https://", SSLContextAdapter(verify=verify, cert_paths=cert_paths))
self.session.trust_env = trust_env
self.session.veri... |
class GroupBy(_GroupBy):
base_func = getattr(libgroupby, how)
for name, obj in self._iterate_slices():
if aggregate:
result_sz = ngroups
else:
result_sz = len(obj.values)
if not cython_dtype:
cython_dtype = obj.values.... | class GroupBy(_GroupBy):
base_func = getattr(libgroupby, how)
for name, obj in self._iterate_slices():
values = obj._data._values
if aggregate:
result_sz = ngroups
else:
result_sz = len(values)
if not cython_dtype:
... |
class GroupBy(_GroupBy):
func(**kwargs) # Call func to modify indexer values in place
if result_is_index:
result = algorithms.take_nd(obj.values, result)
if post_processing:
result = post_processing(result, inferences) | class GroupBy(_GroupBy):
func(**kwargs) # Call func to modify indexer values in place
if result_is_index:
result = algorithms.take_nd(values, result)
if post_processing:
result = post_processing(result, inferences) |
def test_groupby_axis_1(group_name):
results = df.groupby(group_name, axis=1).sum()
expected = df.T.groupby(group_name).sum().T
assert_frame_equal(results, expected) | def test_groupby_axis_1(group_name):
results = df.groupby(group_name, axis=1).sum()
expected = df.T.groupby(group_name).sum().T
assert_frame_equal(results, expected)
@pytest.mark.parametrize(
"op, expected",
[
(
"shift",
{
"time": [
... |
from contextlib import contextmanager
import pytest
from mock import Mock
from thefuck.utils import wrap_settings, \
memoize, get_closest, get_all_executables, replace_argument, \
get_all_matched_commands, is_app, for_app, cache | import pytest
from mock import Mock
import six
from thefuck.utils import wrap_settings, \
memoize, get_closest, get_all_executables, replace_argument, \
get_all_matched_commands, is_app, for_app, cache |
class TestCache(object):
def shelve(self, mocker):
value = {}
@contextmanager
def _shelve(path):
yield value
mocker.patch('thefuck.utils.shelve.open', new_callable=lambda: _shelve)
return value
@pytest.fixture(autouse=True) | class TestCache(object):
def shelve(self, mocker):
value = {}
class _Shelve(object):
def __init__(self, path):
pass
def __setitem__(self, k, v):
value[k] = v
def __getitem__(self, k):
return value[k]
... |
class TestCache(object):
return fn
def test_with_blank_cache(self, shelve, fn):
assert shelve == {}
assert fn() == 'test'
assert shelve == {
'tests.test_utils.<function TestCache.fn.<locals>.fn ': {
'etag': '0', 'value': 'test'}}
def test_with_fille... | class TestCache(object):
return fn
@pytest.fixture
def key(self):
if six.PY3:
return 'tests.test_utils.<function TestCache.fn.<locals>.fn '
else:
return 'tests.test_utils.<function fn '
def test_with_blank_cache(self, shelve, fn, key):
assert shelve... |
from difflib import get_close_matches
from functools import wraps
import shelve
from decorator import decorator
import tempfile
import os | from difflib import get_close_matches
from functools import wraps
import shelve
from decorator import decorator
from contextlib import closing
import tempfile
import os |
def cache(*depends_on):
return fn(*args, **kwargs)
cache_path = os.path.join(tempfile.gettempdir(), '.thefuck-cache')
key = '{}.{}'.format(fn.__module__, repr(fn).split('at')[0])
etag = '.'.join(_get_mtime(name) for name in depends_on)
with shelve.open(cache_path) as db:
... | def cache(*depends_on):
return fn(*args, **kwargs)
cache_path = os.path.join(tempfile.gettempdir(), '.thefuck-cache')
# A bit obscure, but simplest way to generate unique key for
# functions and methods in python 2 and 3:
key = '{}.{}'.format(fn.__module__, repr(fn).split('a... |
default 'raise'
def _with_freq(self, freq):
"""
Helper to set our freq in-place, returning self to allow method chaining.
Parameters
---------- | default 'raise'
def _with_freq(self, freq):
"""
Helper to get a view on the same data, with a new freq.
Parameters
---------- |
default 'raise'
Returns
-------
self
"""
# GH#29843
if freq is None: | default 'raise'
Returns
-------
Same type as self
"""
# GH#29843
if freq is None: |
default 'raise'
assert freq == "infer"
freq = frequencies.to_offset(self.inferred_freq)
self._freq = freq
return self
class DatetimeLikeArrayMixin( | default 'raise'
assert freq == "infer"
freq = frequencies.to_offset(self.inferred_freq)
arr = self.view()
arr._freq = freq
return arr
class DatetimeLikeArrayMixin( |
from pandas.core.indexes.numeric import Int64Index
from pandas.core.ops import get_op_result_name
from pandas.core.tools.timedeltas import to_timedelta
from pandas.tseries.frequencies import DateOffset, to_offset
from pandas.tseries.offsets import Tick
_index_doc_kwargs = dict(ibase._index_doc_kwargs) | from pandas.core.indexes.numeric import Int64Index
from pandas.core.ops import get_op_result_name
from pandas.core.tools.timedeltas import to_timedelta
from pandas.tseries.frequencies import DateOffset
from pandas.tseries.offsets import Tick
_index_doc_kwargs = dict(ibase._index_doc_kwargs) |
class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index):
return self.freq.freqstr
def _with_freq(self, freq):
index = self.copy(deep=False)
if freq is None:
# Even if we _can_ have a freq, we might want to set it to None
index._freq = None
elif len(se... | class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index):
return self.freq.freqstr
def _with_freq(self, freq):
arr = self._data._with_freq(freq)
return type(self)._simple_new(arr, name=self.name)
def _shallow_copy(self, values=None, name: Label = lib.no_default):
name = ... |
class TestDatetimeIndex:
idx_p = tm.round_trip_pickle(idx)
tm.assert_index_equal(idx, idx_p)
def test_reindex_preserves_tz_if_target_is_empty_list_or_array(self):
# GH7774
index = date_range("20130101", periods=3, tz="US/Eastern") | class TestDatetimeIndex:
idx_p = tm.round_trip_pickle(idx)
tm.assert_index_equal(idx, idx_p)
def test_pickle_after_set_freq(self):
dti = date_range("20130101", periods=3, tz="US/Eastern", name="foo")
dti = dti._with_freq(None)
res = tm.round_trip_pickle(dti)
tm.asse... |
class TestTimedeltaIndex(DatetimeLike):
def test_pickle_compat_construction(self):
pass
def test_isin(self):
index = tm.makeTimedeltaIndex(4) | class TestTimedeltaIndex(DatetimeLike):
def test_pickle_compat_construction(self):
pass
def test_pickle_after_set_freq(self):
tdi = timedelta_range("1 day", periods=4, freq="s")
tdi = tdi._with_freq(None)
res = tm.round_trip_pickle(tdi)
tm.assert_index_equal(res, tdi)
... |
class APIRouter(routing.Router):
def add_api_websocket_route(
self, path: str, endpoint: Callable, name: str = None
) -> None:
route = APIWebSocketRoute(path, endpoint=endpoint, name=name)
self.routes.append(route)
def websocket(self, path: str, name: str = None) -> Callable: | class APIRouter(routing.Router):
def add_api_websocket_route(
self, path: str, endpoint: Callable, name: str = None
) -> None:
route = APIWebSocketRoute(
path,
endpoint=endpoint,
name=name,
dependency_overrides_provider=self.dependency_overrides_pr... |
from fastapi import APIRouter, FastAPI, WebSocket
from fastapi.testclient import TestClient
router = APIRouter() | from fastapi import APIRouter, Depends, FastAPI, WebSocket
from fastapi.testclient import TestClient
router = APIRouter() |
async def routerindex(websocket: WebSocket):
await websocket.close()
app.include_router(router)
app.include_router(prefix_router, prefix="/prefix")
| async def routerindex(websocket: WebSocket):
await websocket.close()
async def ws_dependency():
return "Socket Dependency"
@router.websocket("/router-ws-depends/")
async def router_ws_decorator_depends(
websocket: WebSocket, data=Depends(ws_dependency)
):
await websocket.accept()
await websocket... |
def test_router2():
with client.websocket_connect("/router2") as websocket:
data = websocket.receive_text()
assert data == "Hello, router!" | def test_router2():
with client.websocket_connect("/router2") as websocket:
data = websocket.receive_text()
assert data == "Hello, router!"
def test_router_ws_depends():
client = TestClient(app)
with client.websocket_connect("/router-ws-depends/") as websocket:
assert websocket.rec... |
from itertools import cycle as itertools_cycle, groupby
from django.conf import settings
from django.utils import timezone
from django.utils.html import conditional_escape, format_html
from django.utils.lorem_ipsum import paragraphs, words
from django.utils.safestring import mark_safe
| from itertools import cycle as itertools_cycle, groupby
from django.conf import settings
from django.utils import timezone
from django.utils.html import conditional_escape, escape, format_html
from django.utils.lorem_ipsum import paragraphs, words
from django.utils.safestring import mark_safe
|
class CycleNode(Node):
class DebugNode(Node):
def render(self, context):
from pprint import pformat
output = [pformat(val) for val in context]
output.append('\n\n')
output.append(pformat(sys.modules))
return ''.join(output)
| class CycleNode(Node):
class DebugNode(Node):
def render(self, context):
if not settings.DEBUG:
return ''
from pprint import pformat
output = [escape(pformat(val)) for val in context]
output.append('\n\n')
output.append(escape(pformat(sys.modules)))
retu... |
import sys
from django.contrib.auth.models import Group
from django.template import Context, Engine, TemplateSyntaxError
from django.template.base import UNKNOWN_SOURCE
from django.test import SimpleTestCase, override_settings | import sys
from django.template import Context, Engine, TemplateSyntaxError
from django.template.base import UNKNOWN_SOURCE
from django.test import SimpleTestCase, override_settings |
class TemplateTests(SimpleTestCase):
with self.assertRaises(NoReverseMatch):
t.render(Context())
def test_debug_tag_non_ascii(self):
"""
#23060 -- Test non-ASCII model representation in debug output.
"""
group = Group(name="清風")
c1 = Context({"objs": [gro... | class TemplateTests(SimpleTestCase):
with self.assertRaises(NoReverseMatch):
t.render(Context())
def test_extends_generic_template(self):
"""
#24338 -- Allow extending django.template.backends.django.Template |
class tqdm(Comparable):
# NB: Avoid race conditions by setting start_t at the very end of init
self.start_t = self.last_print_t
def __len__(self):
return self.total if self.iterable is None else \
(self.iterable.shape[0] if hasattr(self.iterable, "shape") | class tqdm(Comparable):
# NB: Avoid race conditions by setting start_t at the very end of init
self.start_t = self.last_print_t
def __bool__(self):
if self.total is not None:
return self.total > 0
if self.iterable is None:
raise TypeError('Boolean cast is und... |
def test_threading():
@with_setup(pretest, posttest)
def test_bool():
"""Test boolean cast"""
def internal(our_file, disable):
with tqdm(total=10, file=our_file, disable=disable) as t:
assert t
with tqdm(total=0, file=our_file, disable=disable) as t:
assert not t
... | def test_threading():
@with_setup(pretest, posttest)
def test_bool():
"""Test boolean cast"""
def internal(our_file, disable):
with trange(10, file=our_file, disable=disable) as t:
assert t
with trange(0, file=our_file, disable=disable) as t:
assert not t
def ge... |
class CentralPlannerScheduler(Scheduler):
for task in self._state.get_active_tasks():
self._state.fail_dead_worker_task(task, self._config, assistant_ids)
if task.id not in necessary_tasks and self._state.prune(task, self._config):
remove_tasks.append(task.id)
s... | class CentralPlannerScheduler(Scheduler):
for task in self._state.get_active_tasks():
self._state.fail_dead_worker_task(task, self._config, assistant_ids)
removed = self._state.prune(task, self._config)
if removed and task.id not in necessary_tasks:
remove_ta... |
class CentralPlannerTest(unittest.TestCase):
self.sch.prune()
self.assertFalse(list(self.sch.task_list('', '')))
def test_fail_job_from_dead_worker_with_live_assistant(self):
self.setTime(0)
self.sch.add_task(worker='X', task_id='A') | class CentralPlannerTest(unittest.TestCase):
self.sch.prune()
self.assertFalse(list(self.sch.task_list('', '')))
def test_re_enable_failed_task_assistant(self):
self.setTime(0)
self.sch.add_worker('X', [('assistant', True)])
self.sch.add_task(worker='X', task_id='A', status=... |
def _unstack_multiple(data, clocs, fill_value=None):
result = data
for i in range(len(clocs)):
val = clocs[i]
result = result.unstack(val)
clocs = [v if i > v else v - 1 for v in clocs]
return result | def _unstack_multiple(data, clocs, fill_value=None):
result = data
for i in range(len(clocs)):
val = clocs[i]
result = result.unstack(val, fill_value=fill_value)
clocs = [v if i > v else v - 1 for v in clocs]
return result |
def test_stack_timezone_aware_values():
),
)
tm.assert_series_equal(result, expected) | def test_stack_timezone_aware_values():
),
)
tm.assert_series_equal(result, expected)
def test_unstacking_multi_index_df():
# see gh-30740
df = DataFrame(
{
"name": ["Alice", "Bob"],
"score": [9.5, 8],
"employed": [False, True],
"kids": [... |
class Bidirectional(Wrapper):
return self.forward_layer.updates + self.backward_layer.updates
return []
@property
def losses(self):
if hasattr(self.forward_layer, 'losses'):
return self.forward_layer.losses + self.backward_layer.losses
return []
@property
... | class Bidirectional(Wrapper):
return self.forward_layer.updates + self.backward_layer.updates
return []
def get_updates_for(self, inputs=None):
forward_updates = self.forward_layer.get_updates_for(inputs)
backward_updates = self.backward_layer.get_updates_for(inputs)
ret... |
def test_Bidirectional_trainable():
assert len(layer.trainable_weights) == 6
if __name__ == '__main__':
pytest.main([__file__]) | def test_Bidirectional_trainable():
assert len(layer.trainable_weights) == 6
@keras_test
def test_Bidirectional_updates():
x = Input(shape=(3, 2))
layer = wrappers.Bidirectional(layers.SimpleRNN(3))
assert len(layer.updates) == 0
assert len(layer.get_updates_for(None)) == 0
assert len(layer.ge... |
# this is a package
__version__ = "4.6.2"
def get_include(): | # this is a package
__version__ = "4.6.3"
def get_include(): |
class Storage:
content = File(content, name)
name = self.get_available_name(name, max_length=max_length)
return self._save(name, content)
# These methods are part of the public API, with default implementations.
| class Storage:
content = File(content, name)
name = self.get_available_name(name, max_length=max_length)
name = self._save(name, content)
# Ensure that the name returned from the storage system is still valid.
validate_file_name(name, allow_relative_path=True)
return... |
class Storage:
Return a filename that's free on the target storage system and
available for new content to be written to.
"""
dir_name, file_name = os.path.split(name)
if '..' in pathlib.PurePath(dir_name).parts:
raise SuspiciousFileOperation("Detected path traversal ... | class Storage:
Return a filename that's free on the target storage system and
available for new content to be written to.
"""
name = str(name).replace('\\', '/')
dir_name, file_name = os.path.split(name)
if '..' in pathlib.PurePath(dir_name).parts:
raise Suspi... |
class Storage:
Validate the filename by calling get_valid_name() and return a filename
to be passed to the save() method.
"""
# `filename` may include a path as returned by FileField.upload_to.
dirname, filename = os.path.split(filename)
if '..' in pathlib.PurePath(dirnam... | class Storage:
Validate the filename by calling get_valid_name() and return a filename
to be passed to the save() method.
"""
filename = str(filename).replace('\\', '/')
# `filename` may include a path as returned by FileField.upload_to.
dirname, filename = os.path.split(... |
class FileSystemStorage(Storage):
if self.file_permissions_mode is not None:
os.chmod(full_path, self.file_permissions_mode)
# Store filenames with forward slashes, even on Windows.
return str(name).replace('\\', '/')
| class FileSystemStorage(Storage):
if self.file_permissions_mode is not None:
os.chmod(full_path, self.file_permissions_mode)
# Ensure the saved path is always relative to the storage root.
name = os.path.relpath(full_path, self.location)
# Store filenames with forward slashe... |
class GenerateFilenameStorageTests(SimpleTestCase):
s.generate_filename(file_name)
def test_storage_dangerous_paths_dir_name(self):
file_name = '/tmp/../path'
s = FileSystemStorage()
msg = "Detected path traversal attempt in '/tmp/..'"
with self.assertRaisesMessa... | class GenerateFilenameStorageTests(SimpleTestCase):
s.generate_filename(file_name)
def test_storage_dangerous_paths_dir_name(self):
candidates = [
('tmp/../path', 'tmp/..'),
('tmp\\..\\path', 'tmp/..'),
('/tmp/../path', '/tmp/..'),
('\\tmp... |
class FileStorageTests(SimpleTestCase):
self.storage.delete('path/to/test.file')
@unittest.skipUnless(symlinks_supported(), 'Must be able to symlink to run this test.')
def test_file_save_broken_symlink(self):
"""A new path is created on save when a broken symlink is supplied.""" | class FileStorageTests(SimpleTestCase):
self.storage.delete('path/to/test.file')
def test_file_save_abs_path(self):
test_name = 'path/to/test.file'
f = ContentFile('file saved with path')
f_name = self.storage.save(os.path.join(self.temp_dir, test_name), f)
self.assertEqual... |
class RegexPattern(CheckURLMixin):
self.converters = {}
def match(self, path):
match = self.regex.search(path)
if match:
# If there are any named groups, use those as kwargs, ignoring
# non-named groups. Otherwise, pass all non-named arguments as | class RegexPattern(CheckURLMixin):
self.converters = {}
def match(self, path):
match = (
self.regex.fullmatch(path)
if self._is_endpoint and self.regex.pattern.endswith('$')
else self.regex.search(path)
)
if match:
# If there are any n... |
def _route_to_regex(route, is_endpoint=False):
converters[parameter] = converter
parts.append('(?P<' + parameter + '>' + converter.regex + ')')
if is_endpoint:
parts.append('$')
return ''.join(parts), converters
| def _route_to_regex(route, is_endpoint=False):
converters[parameter] = converter
parts.append('(?P<' + parameter + '>' + converter.regex + ')')
if is_endpoint:
parts.append(r'\Z')
return ''.join(parts), converters
|
class SimplifiedURLTests(SimpleTestCase):
with self.assertRaisesMessage(ImproperlyConfigured, msg):
path('space/<int: num>', empty_view)
@override_settings(ROOT_URLCONF='urlpatterns.converter_urls')
class ConverterTests(SimpleTestCase): | class SimplifiedURLTests(SimpleTestCase):
with self.assertRaisesMessage(ImproperlyConfigured, msg):
path('space/<int: num>', empty_view)
def test_path_trailing_newlines(self):
tests = [
'/articles/2003/\n',
'/articles/2010/\n',
'/en/foo/\n',
... |
class XMLRPCHandlerTests(unittest.TestCase):
self.assertEqual(request._error, 500)
class TraverseTests(unittest.TestCase):
def test_underscore(self):
from supervisor import xmlrpc
self.assertRaises(xmlrpc.RPCError, xmlrpc.traverse, None, '_', None)
def test_notfound(self):
from... | class XMLRPCHandlerTests(unittest.TestCase):
self.assertEqual(request._error, 500)
class TraverseTests(unittest.TestCase):
def test_security_disallows_underscore_methods(self):
from supervisor import xmlrpc
class Root:
pass
class A:
def _danger(self):
... |
class supervisor_xmlrpc_handler(xmlrpc_handler):
return traverse(self.rpcinterface, method, params)
def traverse(ob, method, params):
path = method.split('.')
for name in path:
if name.startswith('_'):
# security (don't allow things that start with an underscore to
# be ... | class supervisor_xmlrpc_handler(xmlrpc_handler):
return traverse(self.rpcinterface, method, params)
def traverse(ob, method, params):
dotted_parts = method.split('.')
# security (CVE-2017-11610, don't allow object traversal)
if len(dotted_parts) != 2:
raise RPCError(Faults.UNKNOWN_METHOD)
... |
class AnsibleModule(object):
if k not in self.argument_spec:
self.argument_spec[k] = v
self._load_params()
self._set_fallbacks()
| class AnsibleModule(object):
if k not in self.argument_spec:
self.argument_spec[k] = v
# Save parameter values that should never be logged
self.no_log_values = set()
self._load_params()
self._set_fallbacks()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.