buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
""" test scalar indexing, including at and iat """
import numpy as np
import pytest | """ test scalar indexing, including at and iat """
from datetime import datetime, timedelta
import numpy as np
import pytest |
class TestScalar2:
s = Series([1, 2])
result = s[np.array(0)]
assert result == 1 | class TestScalar2:
s = Series([1, 2])
result = s[np.array(0)]
assert result == 1
def test_iat_dont_wrap_object_datetimelike():
# GH#32809 .iat calls go through DataFrame._get_value, should not
# call maybe_box_datetimelike
dti = date_range("2016-01-01", periods=3)
tdi = dti - ... |
def authenticate(self, context, auth=None):
self.token_api.create_token(
context, token_id, dict(key=token_id,
id=token_id,
user=user_ref,
tenant=tenant_ref,
... | def authenticate(self, context, auth=None):
self.token_api.create_token(
context, token_id, dict(key=token_id,
id=token_id,
expires=auth_token_data['expires'],
user=user_re... |
class TestSortedCorrectedCommandsSequence(object):
settings)
assert set(seq) == {CorrectedCommand('ls', priority=100),
CorrectedCommand('ls', side_effect, 300)} | class TestSortedCorrectedCommandsSequence(object):
settings)
assert set(seq) == {CorrectedCommand('ls', priority=100),
CorrectedCommand('ls', side_effect, 300)}
class TestCorrectedCommand(object):
def test_equality(self):
assert CorrectedCommand('ls', None,... |
from .logs import debug
Command = namedtuple('Command', ('script', 'stdout', 'stderr'))
CorrectedCommand = namedtuple('CorrectedCommand', ('script', 'side_effect', 'priority'))
Rule = namedtuple('Rule', ('name', 'match', 'get_new_command',
'enabled_by_default', 'side_effect',
... | from .logs import debug
Command = namedtuple('Command', ('script', 'stdout', 'stderr'))
Rule = namedtuple('Rule', ('name', 'match', 'get_new_command',
'enabled_by_default', 'side_effect',
'priority', 'requires_output'))
class CorrectedCommand(object):
def __i... |
class SortedCorrectedCommandsSequence(object):
return []
for command in self._commands:
if command.script != first.script or \
command.side_effect != first.side_effect:
return [first, command]
return [first]
def _remove_duplicates... | class SortedCorrectedCommandsSequence(object):
return []
for command in self._commands:
if command != first:
return [first, command]
return [first]
def _remove_duplicates(self, corrected_commands):
"""Removes low-priority duplicates."""
comma... |
WRONGCERT = data_file("XXXnonexisting.pem")
BADKEY = data_file("badkey.pem")
NOKIACERT = data_file("nokia.pem")
def handle_error(prefix): | WRONGCERT = data_file("XXXnonexisting.pem")
BADKEY = data_file("badkey.pem")
NOKIACERT = data_file("nokia.pem")
NULLBYTECERT = data_file("nullbytecert.pem")
def handle_error(prefix): |
def test_parse_cert(self):
('DNS', 'projects.forum.nokia.com'))
)
def test_DER_to_PEM(self):
with open(SVN_PYTHON_ORG_ROOT_CERT, 'r') as f:
pem = f.read() | def test_parse_cert(self):
('DNS', 'projects.forum.nokia.com'))
)
def test_parse_cert_CVE_2013_4073(self):
p = ssl._ssl._test_decode_cert(NULLBYTECERT)
if support.verbose:
sys.stdout.write("\n" + pprint.pformat(p) + "\n")
subject... |
def fail(cert, hostname):
fail(cert, 'foo.a.com')
fail(cert, 'bar.foo.com')
# Slightly fake real-world example
cert = {'notAfter': 'Jun 26 21:41:46 2011 GMT',
'subject': ((('commonName', 'linuxfrz.org'),),), | def fail(cert, hostname):
fail(cert, 'foo.a.com')
fail(cert, 'bar.foo.com')
# NULL bytes are bad, CVE-2013-4073
cert = {'subject': ((('commonName',
'null.python.org\x00example.org'),),)}
ok(cert, 'null.python.org\x00example.org') # or raise an error... |
def validate_baseindexer_support(func_name: Optional[str]) -> None:
"median",
"std",
"var",
"kurt",
"quantile",
} | def validate_baseindexer_support(func_name: Optional[str]) -> None:
"median",
"std",
"var",
"skew",
"kurt",
"quantile",
} |
class _Window(PandasObject, ShallowMixin, SelectionMixin):
def calc(x):
x = np.concatenate((x, additional_nans))
if not isinstance(window, BaseIndexer):
min_periods = calculate_min_periods(
window, self.min_peri... | class _Window(PandasObject, ShallowMixin, SelectionMixin):
def calc(x):
x = np.concatenate((x, additional_nans))
if not isinstance(self.window, BaseIndexer):
min_periods = calculate_min_periods(
window, self.min... |
def test_win_type_not_implemented():
df.rolling(indexer, win_type="boxcar")
@pytest.mark.parametrize("func", ["skew", "cov", "corr"])
def test_notimplemented_functions(func):
# GH 32865
class CustomIndexer(BaseIndexer): | def test_win_type_not_implemented():
df.rolling(indexer, win_type="boxcar")
@pytest.mark.parametrize("func", ["cov", "corr"])
def test_notimplemented_functions(func):
# GH 32865
class CustomIndexer(BaseIndexer): |
def test_rolling_forward_window(constructor, func, np_func, expected, np_kwargs)
result3 = getattr(rolling3, func)()
expected3 = constructor(rolling3.apply(lambda x: np_func(x, **np_kwargs)))
tm.assert_equal(result3, expected3) | def test_rolling_forward_window(constructor, func, np_func, expected, np_kwargs)
result3 = getattr(rolling3, func)()
expected3 = constructor(rolling3.apply(lambda x: np_func(x, **np_kwargs)))
tm.assert_equal(result3, expected3)
@pytest.mark.parametrize("constructor", [Series, DataFrame])
def test_rolling_... |
def crosstab(
from pandas import DataFrame
df = DataFrame(data, index=common_idx)
if values is None:
df["__dummy__"] = 0
kwargs = {"aggfunc": len, "fill_value": 0} | def crosstab(
from pandas import DataFrame
df = DataFrame(data, index=common_idx)
original_df_cols = df.columns
if values is None:
df["__dummy__"] = 0
kwargs = {"aggfunc": len, "fill_value": 0} |
def crosstab(
kwargs = {"aggfunc": aggfunc}
table = df.pivot_table(
"__dummy__",
index=rownames,
columns=colnames,
margins=margins, | def crosstab(
kwargs = {"aggfunc": aggfunc}
table = df.pivot_table(
["__dummy__"],
index=rownames,
columns=colnames,
margins=margins, |
def crosstab(
**kwargs,
)
# Post-process
if normalize is not False:
table = _normalize( | def crosstab(
**kwargs,
)
# GH18321, after pivoting, an extra top level of column index of `__dummy__` is
# created, and this extra level should not be included in the further steps
if not table.empty:
cols_diff = df.columns.difference(original_df_cols)[0]
table = table[cols_dif... |
class TestCrosstab:
result = pd.crosstab(s1, s2)
tm.assert_frame_equal(result, expected)
def test_crosstab_unsorted_order(self):
df = pd.DataFrame({"b": [3, 1, 2], "a": [5, 4, 6]}, index=["C", "A", "B"])
result = pd.crosstab(df.index, [df.b, df.a]) | class TestCrosstab:
result = pd.crosstab(s1, s2)
tm.assert_frame_equal(result, expected)
def test_crosstab_both_tuple_names(self):
# GH 18321
s1 = pd.Series(range(3), name=("a", "b"))
s2 = pd.Series(range(3), name=("c", "d"))
expected = pd.DataFrame(
np.... |
setup(
name='sopel_plugins.channelmgnt',
version='1.0.2',
description='Channelmgnt plugin for Sopel',
long_description=readme,
long_description_content_type='text/markdown', # This is important! |
setup(
name='sopel_plugins.channelmgnt',
version='1.0.3',
description='Channelmgnt plugin for Sopel',
long_description=readme,
long_description_content_type='text/markdown', # This is important! |
def makemodechange(bot, trigger, mode, isusermode=False, isbqmode=False, selfsaf
bot.say('Attempting to OP...')
bot.say('op ' + trigger.sender, 'ChanServ')
time.sleep(1)
if isusermode and not trigger.group(2):
bot.write(['MODE', trigger.sender, mode, trigger.nick]... | def makemodechange(bot, trigger, mode, isusermode=False, isbqmode=False, selfsaf
bot.say('Attempting to OP...')
bot.say('op ' + trigger.sender, 'ChanServ')
time.sleep(1)
if isusermode and not trigger.group(2) and selfsafe:
bot.write(['MODE', trigger.sender, mode, ... |
def assert_series_equal(
f"is not equal to {right._values}."
)
raise AssertionError(msg)
elif is_interval_dtype(left.dtype) or is_interval_dtype(right.dtype):
assert_interval_array_equal(left.array, right.array)
elif is_categorical_dtype(left.dtype) or is_categori... | def assert_series_equal(
f"is not equal to {right._values}."
)
raise AssertionError(msg)
elif is_interval_dtype(left.dtype) and is_interval_dtype(right.dtype):
assert_interval_array_equal(left.array, right.array)
elif is_categorical_dtype(left.dtype) or is_categor... |
def assert_series_equal(
check_dtype=check_dtype,
obj=str(obj),
)
elif is_extension_array_dtype(left.dtype) or is_extension_array_dtype(right.dtype):
assert_extension_array_equal(left._values, right._values)
elif needs_i8_conversion(left.dtype) or needs_i8_conversion(righ... | def assert_series_equal(
check_dtype=check_dtype,
obj=str(obj),
)
elif is_extension_array_dtype(left.dtype) and is_extension_array_dtype(right.dtype):
assert_extension_array_equal(left._values, right._values)
elif needs_i8_conversion(left.dtype) or needs_i8_conversion(rig... |
import pytest
from pandas import DataFrame
import pandas._testing as tm
| import pytest
import pandas as pd
from pandas import DataFrame
import pandas._testing as tm
|
def test_frame_equal_unicode(df1, df2, msg, by_blocks_fixture, obj_fixture):
msg = msg.format(obj=obj_fixture)
with pytest.raises(AssertionError, match=msg):
tm.assert_frame_equal(df1, df2, by_blocks=by_blocks_fixture, obj=obj_fixture) | def test_frame_equal_unicode(df1, df2, msg, by_blocks_fixture, obj_fixture):
msg = msg.format(obj=obj_fixture)
with pytest.raises(AssertionError, match=msg):
tm.assert_frame_equal(df1, df2, by_blocks=by_blocks_fixture, obj=obj_fixture)
def test_assert_frame_equal_extension_dtype_mismatch():
# http... |
import pytest
from pandas import Categorical, DataFrame, Series
import pandas._testing as tm
| import pytest
import pandas as pd
from pandas import Categorical, DataFrame, Series
import pandas._testing as tm
|
ordered=False\\)"""
_assert_series_equal_both(s1, s2, check_categorical=check_categorical)
def test_series_equal_series_type():
class MySeries(Series):
pass | ordered=False\\)"""
_assert_series_equal_both(s1, s2, check_categorical=check_categorical)
def test_assert_series_equal_extension_dtype_mismatch():
# https://github.com/pandas-dev/pandas/issues/32747
left = Series(pd.array([1, 2, 3], dtype="Int64"))
right = left.astype(int)
msg = """Attribute... |
class Network(Layer):
unprocessed_nodes = {}
def add_unprocessed_node(layer, node_data):
if layer not in unprocessed_nodes:
unprocessed_nodes[layer] = [node_data]
else:
unprocessed_nodes[layer].append(node_data)
def process_node(layer, no... | class Network(Layer):
unprocessed_nodes = {}
def add_unprocessed_node(layer, node_data):
"""Add node to layer list
Args:
layer: layer object
node_data: Node data specifying layer call
"""
if layer not in unprocessed_nodes:... |
class Network(Layer):
else:
raise ValueError('Improperly formatted model config.')
inbound_layer = created_layers[inbound_layer_name]
if len(inbound_layer._inbound_nodes) <= inbound_node_index:
add_unprocessed_node(layer, node_data)... | class Network(Layer):
else:
raise ValueError('Improperly formatted model config.')
inbound_layer = created_layers[inbound_layer_name]
# Raise an error if the corresponding layer node
# has not yet been created
if len(inb... |
class Network(Layer):
# First, we create all layers and enqueue nodes to be processed
for layer_data in config['layers']:
process_layer(layer_data)
# Then we process nodes in order of layer depth.
# Nodes that cannot yet be processed (if the inbound node
# does not ye... | class Network(Layer):
# First, we create all layers and enqueue nodes to be processed
for layer_data in config['layers']:
process_layer(layer_data)
# Then we process nodes in order of layer depth.
# Nodes that cannot yet be processed (if the inbound node
# does not y... |
class Network(Layer):
while unprocessed_nodes:
for layer_data in config['layers']:
layer = created_layers[layer_data['name']]
if layer in unprocessed_nodes:
for node_data in unprocessed_nodes.pop(layer):
process_node(layer, ... | class Network(Layer):
while unprocessed_nodes:
for layer_data in config['layers']:
layer = created_layers[layer_data['name']]
# Process all nodes in layer, if not yet processed
if layer in unprocessed_nodes:
node_data_list = unproc... |
def test_layer_sharing_at_heterogeneous_depth_with_concat():
np.testing.assert_allclose(output_val, output_val_2, atol=1e-6)
def test_multi_output_mask():
"""Fixes #7589"""
class TestMultiOutputLayer(Layer): | def test_layer_sharing_at_heterogeneous_depth_with_concat():
np.testing.assert_allclose(output_val, output_val_2, atol=1e-6)
def test_layer_sharing_at_heterogeneous_depth_order():
# This tests for the bug in this issue
# https://github.com/keras-team/keras/issues/11159
# It occurs with layer sharing a... |
def create_cloned_field(field: ModelField) -> ModelField:
original_type.__name__, __config__=original_type.__config__
)
for f in original_type.__fields__.values():
use_type.__fields__[f.name] = f
use_type.__validators__ = original_type.__validators__
if PYDANTIC_1:
... | def create_cloned_field(field: ModelField) -> ModelField:
original_type.__name__, __config__=original_type.__config__
)
for f in original_type.__fields__.values():
use_type.__fields__[f.name] = create_cloned_field(f)
use_type.__validators__ = original_type.__validators__
... |
import securesystemslib.util
import six
import iso8601
# The Timestamp role does not have signed metadata about it; otherwise we
# would need an infinite regress of metadata. Therefore, we use some | import securesystemslib.util
import six
import iso8601
import requests.exceptions
# The Timestamp role does not have signed metadata about it; otherwise we
# would need an infinite regress of metadata. Therefore, we use some |
def _update_root_metadata(self, current_root_metadata):
None.
"""
# Retrieve the latest, remote root.json.
latest_root_metadata_file = self._get_metadata_file(
'root', 'root.json', DEFAULT_ROOT_UPPERLENGTH, None)
latest_root_metadata = securesystemslib.util.load_json_string(
late... | def _update_root_metadata(self, current_root_metadata):
None.
"""
def neither_403_nor_404(mirror_error):
if isinstance(mirror_error, requests.exceptions.HTTPError):
if mirror_error.response.status_code in {403, 404}:
return False
return True
# Temporarily set consistent... |
# to suspend execution for a specified amount of time. See
# theupdateframework/tuf/issue#338.
SLEEP_BEFORE_ROUND = None | # to suspend execution for a specified amount of time. See
# theupdateframework/tuf/issue#338.
SLEEP_BEFORE_ROUND = None
# Maximum number of root metadata file rotations we should perform in order to
# prevent a denial-of-service (DoS) attack.
MAX_NUMBER_ROOT_ROTATIONS = 2**5 |
from six.moves.urllib.parse import urlunparse
from scrapy.utils.httpobj import urlparse_cached
from scrapy.exceptions import NotConfigured
class HttpProxyMiddleware(object):
| from six.moves.urllib.parse import urlunparse
from scrapy.utils.httpobj import urlparse_cached
from scrapy.exceptions import NotConfigured
from scrapy.utils.python import to_bytes
class HttpProxyMiddleware(object):
|
class HttpProxyMiddleware(object):
proxy_url = urlunparse((proxy_type or orig_type, hostport, '', '', '', ''))
if user:
user_pass = '%s:%s' % (unquote(user), unquote(password))
creds = base64.b64encode(user_pass).strip()
else:
creds = None | class HttpProxyMiddleware(object):
proxy_url = urlunparse((proxy_type or orig_type, hostport, '', '', '', ''))
if user:
user_pass = to_bytes('%s:%s' % (unquote(user), unquote(password)))
creds = base64.b64encode(user_pass).strip()
else:
creds = None |
class HttpProxyMiddleware(object):
creds, proxy = self.proxies[scheme]
request.meta['proxy'] = proxy
if creds:
request.headers['Proxy-Authorization'] = 'Basic ' + creds | class HttpProxyMiddleware(object):
creds, proxy = self.proxies[scheme]
request.meta['proxy'] = proxy
if creds:
request.headers['Proxy-Authorization'] = b'Basic ' + creds |
class TestDefaultHeadersMiddleware(TestCase):
req = Request('http://scrapytest.org')
assert mw.process_request(req, spider) is None
self.assertEquals(req.meta, {'proxy': 'https://proxy:3128'})
self.assertEquals(req.headers.get('Proxy-Authorization'), 'Basic dXNlcjpwYXNz')
def test_p... | class TestDefaultHeadersMiddleware(TestCase):
req = Request('http://scrapytest.org')
assert mw.process_request(req, spider) is None
self.assertEquals(req.meta, {'proxy': 'https://proxy:3128'})
self.assertEquals(req.headers.get('Proxy-Authorization'), b'Basic dXNlcjpwYXNz')
def test_... |
class TestDefaultHeadersMiddleware(TestCase):
req = Request('http://scrapytest.org')
assert mw.process_request(req, spider) is None
self.assertEquals(req.meta, {'proxy': 'https://proxy:3128'})
self.assertEquals(req.headers.get('Proxy-Authorization'), 'Basic dXNlcjo=')
def test_proxy... | class TestDefaultHeadersMiddleware(TestCase):
req = Request('http://scrapytest.org')
assert mw.process_request(req, spider) is None
self.assertEquals(req.meta, {'proxy': 'https://proxy:3128'})
self.assertEquals(req.headers.get('Proxy-Authorization'), b'Basic dXNlcjo=')
def test_prox... |
class RetryTest(unittest.TestCase):
def test_priority_adjust(self):
req = Request('http://www.scrapytest.org/503')
rsp = Response('http://www.scrapytest.org/503', body='', status=503)
req2 = self.mw.process_response(req, rsp, self.spider)
assert req2.priority < req.priority
def... | class RetryTest(unittest.TestCase):
def test_priority_adjust(self):
req = Request('http://www.scrapytest.org/503')
rsp = Response('http://www.scrapytest.org/503', body=b'', status=503)
req2 = self.mw.process_response(req, rsp, self.spider)
assert req2.priority < req.priority
de... |
class RetryTest(unittest.TestCase):
def test_503(self):
req = Request('http://www.scrapytest.org/503')
rsp = Response('http://www.scrapytest.org/503', body='', status=503)
# first retry
req = self.mw.process_response(req, rsp, self.spider) | class RetryTest(unittest.TestCase):
def test_503(self):
req = Request('http://www.scrapytest.org/503')
rsp = Response('http://www.scrapytest.org/503', body=b'', status=503)
# first retry
req = self.mw.process_response(req, rsp, self.spider) |
class RobotsTxtMiddleware(object):
rp_dfd.callback(rp)
def _robots_error(self, failure, netloc):
self._parsers.pop(netloc).callback(None) | class RobotsTxtMiddleware(object):
rp_dfd.callback(rp)
def _robots_error(self, failure, netloc):
rp_dfd = self._parsers[netloc]
self._parsers[netloc] = None
rp_dfd.callback(None) |
class RobotsTxtMiddlewareTest(unittest.TestCase):
deferred.addCallback(lambda _: self.assertTrue(middleware._logerror.called))
return deferred
def test_ignore_robotstxt_request(self):
self.crawler.settings.set('ROBOTSTXT_OBEY', True)
def ignore_request(request, spider): | class RobotsTxtMiddlewareTest(unittest.TestCase):
deferred.addCallback(lambda _: self.assertTrue(middleware._logerror.called))
return deferred
def test_robotstxt_immediate_error(self):
self.crawler.settings.set('ROBOTSTXT_OBEY', True)
err = error.DNSLookupError('Robotstxt address no... |
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... |
def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False):
if is_object_dtype(dtype):
return tslib.ints_to_pydatetime(arr.view(np.int64))
elif dtype == np.int64:
return arr.view(dtype)
# allow frequency conversions | def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False):
if is_object_dtype(dtype):
return tslib.ints_to_pydatetime(arr.view(np.int64))
elif dtype == np.int64:
if isna(arr).any():
raise ValueError("Cannot convert NaT values to integer")
... |
def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False):
if is_object_dtype(dtype):
return tslibs.ints_to_pytimedelta(arr.view(np.int64))
elif dtype == np.int64:
return arr.view(dtype)
if dtype not in [_INT64_DTYPE, _TD_DTYPE]: | def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False):
if is_object_dtype(dtype):
return tslibs.ints_to_pytimedelta(arr.view(np.int64))
elif dtype == np.int64:
if isna(arr).any():
raise ValueError("Cannot convert NaT values to integer")
... |
import pytest
import pandas.util._test_decorators as td
import pandas.core.dtypes.common as com
from pandas.core.dtypes.dtypes import (
CategoricalDtype, | import pytest
import pandas.util._test_decorators as td
from pandas.core.dtypes.cast import astype_nansafe
import pandas.core.dtypes.common as com
from pandas.core.dtypes.dtypes import (
CategoricalDtype, |
from pandas.core.dtypes.dtypes import (
IntervalDtype,
PeriodDtype,
)
import pandas as pd
from pandas.conftest import ( | from pandas.core.dtypes.dtypes import (
IntervalDtype,
PeriodDtype,
)
from pandas.core.dtypes.missing import isna
import pandas as pd
from pandas.conftest import ( |
def test__get_dtype_fails(input_param, expected_error_message):
)
def test__is_dtype_type(input_param, result):
assert com._is_dtype_type(input_param, lambda tipo: tipo == result) | def test__get_dtype_fails(input_param, expected_error_message):
)
def test__is_dtype_type(input_param, result):
assert com._is_dtype_type(input_param, lambda tipo: tipo == result)
@pytest.mark.parametrize("val", [np.datetime64("NaT"), np.timedelta64("NaT")])
@pytest.mark.parametrize("typ", [np.int64])
def test_as... |
def __init__(self, host, port=None, strict=None,
(self.host, self.port) = self._get_hostport(host, port)
# This is stored as an instance variable to allow unittests
# to replace with a suitable mock
self._create_connection = socket.create_connection | def __init__(self, host, port=None, strict=None,
(self.host, self.port) = self._get_hostport(host, port)
self._validate_host(self.host)
# This is stored as an instance variable to allow unittests
# to replace with a suitable mock
self._create_connection = socket.create_connect... |
def _validate_path(self, url):
).format(matched=match.group(), url=url)
raise InvalidURL(msg)
def putheader(self, header, *values):
"""Send a request header line to the server.
| def _validate_path(self, url):
).format(matched=match.group(), url=url)
raise InvalidURL(msg)
def _validate_host(self, host):
"""Validate a host so it doesn't contain control characters."""
# Prevent CVE-2019-18348.
match = _contains_disallowed_url_pchar_re.search(ho... |
def test_proxy_tunnel_without_status_line(self):
with self.assertRaisesRegexp(socket.error, "Invalid response"):
conn._tunnel()
def test_putrequest_override_validation(self):
"""
It should be possible to override the default validation
behavior in putrequest (bpo-38216). | def test_proxy_tunnel_without_status_line(self):
with self.assertRaisesRegexp(socket.error, "Invalid response"):
conn._tunnel()
def test_putrequest_override_domain_validation(self):
"""
It should be possible to override the default validation
behavior in putrequest (bpo-... |
def _validate_path(self, url):
conn.sock = FakeSocket('')
conn.putrequest('GET', '/\x00')
class OfflineTest(TestCase):
def test_responses(self): | def _validate_path(self, url):
conn.sock = FakeSocket('')
conn.putrequest('GET', '/\x00')
def test_putrequest_override_host_validation(self):
class UnsafeHTTPConnection(httplib.HTTPConnection):
def _validate_host(self, url):
pass
conn = UnsafeHTTPConnect... |
def test_unsupported_algorithm(self):
)
@unittest.skipUnless(ssl, "ssl module required")
def test_url_with_control_char_rejected(self):
for char_no in range(0, 0x21) + range(0x7f, 0x100):
char = chr(char_no)
schemeless_url = "//localhost:7777/test%s/" % char | def test_unsupported_algorithm(self):
)
@unittest.skipUnless(ssl, "ssl module required")
def test_url_path_with_control_char_rejected(self):
for char_no in range(0, 0x21) + range(0x7f, 0x100):
char = chr(char_no)
schemeless_url = "//localhost:7777/test%s/" % char |
def test_url_with_control_char_rejected(self):
self.unfakehttp()
@unittest.skipUnless(ssl, "ssl module required")
def test_url_with_newline_header_injection_rejected(self):
self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.")
host = "localhost:7777?a=1 HTTP/1.1\r\nX-injected: header\... | def test_url_with_control_char_rejected(self):
self.unfakehttp()
@unittest.skipUnless(ssl, "ssl module required")
def test_url_path_with_newline_header_injection_rejected(self):
self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.")
host = "localhost:7777?a=1 HTTP/1.1\r\nX-injected: he... |
def test_url_with_newline_header_injection_rejected(self):
# calls urllib.parse.quote() on the URL which makes all of the
# above attempts at injection within the url _path_ safe.
InvalidURL = httplib.InvalidURL
with self.assertRaisesRegexp(
InvalidURL, r"... | def test_url_with_newline_header_injection_rejected(self):
# calls urllib.parse.quote() on the URL which makes all of the
# above attempts at injection within the url _path_ safe.
InvalidURL = httplib.InvalidURL
with self.assertRaisesRegexp(InvalidURL,
... |
def rnn(step_function, inputs, initial_states,
tiled_mask_t = tf.tile(mask_t,
tf.stack([1, tf.shape(output)[1]]))
output = tf.where(tiled_mask_t, output, states[0])
new_states = [tf.where(tiled_mask_t, new_states[i], states[i]) for i... | def rnn(step_function, inputs, initial_states,
tiled_mask_t = tf.tile(mask_t,
tf.stack([1, tf.shape(output)[1]]))
output = tf.where(tiled_mask_t, output, states[0])
new_states = [
tf.where(tf.tile(mask_t, tf.stack... |
class TestBackend(object):
assert_allclose(outputs_list[i - 1], outputs_list[i], atol=1e-05)
assert_allclose(state_list[i - 1], state_list[i], atol=1e-05)
def test_rnn_no_states(self):
# implement a simple RNN without states
input_dim = 8 | class TestBackend(object):
assert_allclose(outputs_list[i - 1], outputs_list[i], atol=1e-05)
assert_allclose(state_list[i - 1], state_list[i], atol=1e-05)
def test_rnn_additional_states(self):
# implement a simple RNN with an additional state
# whose shape is differe... |
This module implements the FormRequest class which is a more convenient class
See documentation in docs/topics/request-response.rst
"""
from six.moves.urllib.parse import urljoin, urlencode
import lxml.html
from parsel.selector import create_root_node
import six
from scrapy.http.request import Request
from scrapy.util... | This module implements the FormRequest class which is a more convenient class
See documentation in docs/topics/request-response.rst
"""
import six
from six.moves.urllib.parse import urljoin, urlencode
import lxml.html
from parsel.selector import create_root_node
from w3lib.html import strip_html5_whitespace
from scr... |
class FormRequest(Request):
def _get_form_url(form, url):
if url is None:
return urljoin(form.base_url, form.action)
return urljoin(form.base_url, url)
| class FormRequest(Request):
def _get_form_url(form, url):
if url is None:
action = form.get('action')
if action is None:
return form.base_url
return urljoin(form.base_url, strip_html5_whitespace(action))
return urljoin(form.base_url, url)
|
class FormRequestTest(RequestTest):
fs = _qs(req, to_unicode=True, encoding='latin1')
self.assertTrue(fs[u'price in \u00a5'])
def test_from_response_multiple_forms_clickdata(self):
response = _buildresponse(
"""<form name="form1"> | class FormRequestTest(RequestTest):
fs = _qs(req, to_unicode=True, encoding='latin1')
self.assertTrue(fs[u'price in \u00a5'])
def test_from_response_multiple_forms_clickdata(self):
response = _buildresponse(
"""<form name="form1"> |
class FormRequestTest(RequestTest):
"""
<html>
<head>
<base href="http://b.com/">
</head>
<body>
<form action="test_form"> | class FormRequestTest(RequestTest):
"""
<html>
<head>
<base href=" http://b.com/">
</head>
<body>
<form action="test_form"> |
class FormRequestTest(RequestTest):
req = self.request_class.from_response(response)
self.assertEqual(req.url, 'http://b.com/test_form')
def test_from_response_css(self):
response = _buildresponse(
"""<form action="post.php" method="POST"> | class FormRequestTest(RequestTest):
req = self.request_class.from_response(response)
self.assertEqual(req.url, 'http://b.com/test_form')
def test_spaces_in_action(self):
resp = _buildresponse('<body><form action=" path\n"></form></body>')
req = self.request_class.from_response(resp)... |
class FormRequestTest(RequestTest):
self.assertRaises(ValueError, self.request_class.from_response,
response, formcss="input[name='abc']")
def _buildresponse(body, **kwargs):
kwargs.setdefault('body', body)
kwargs.setdefault('url', 'http://example.com')
kwargs.setdefault('... | class FormRequestTest(RequestTest):
self.assertRaises(ValueError, self.request_class.from_response,
response, formcss="input[name='abc']")
def _buildresponse(body, **kwargs):
kwargs.setdefault('body', body)
kwargs.setdefault('url', 'http://example.com')
kwargs.setdefault(... |
class TensorBoard(Callback):
tf.summary.image(mapped_weight_name, w_img)
if hasattr(layer, 'output'):
tf.summary.histogram('{}_out'.format(layer.name),
layer.output)
self.merged = tf.summary.merge_all()
... | class TensorBoard(Callback):
tf.summary.image(mapped_weight_name, w_img)
if hasattr(layer, 'output'):
if isinstance(layer.output, list):
for i, output in enumerate(layer.output):
tf.summary.histogram('{}_out... |
from keras import optimizers
from keras import initializers
from keras import callbacks
from keras.models import Sequential, Model
from keras.layers import Input, Dense, Dropout, add
from keras.layers.convolutional import Conv2D
from keras.layers.pooling import MaxPooling2D, GlobalAveragePooling2D
from keras.utils.test... | from keras import optimizers
from keras import initializers
from keras import callbacks
from keras.models import Sequential, Model
from keras.layers import Input, Dense, Dropout, add, dot, Lambda
from keras.layers.convolutional import Conv2D
from keras.layers.pooling import MaxPooling2D, GlobalAveragePooling1D, GlobalA... |
def test_TensorBoard_multi_input_output(tmpdir):
(X_train, y_train), (X_test, y_test) = get_test_data(
num_train=train_samples,
num_test=test_samples,
input_shape=(input_dim,),
classification=True,
num_classes=num_classes)
y_test = np_utils.to_categorical(y_test) | def test_TensorBoard_multi_input_output(tmpdir):
(X_train, y_train), (X_test, y_test) = get_test_data(
num_train=train_samples,
num_test=test_samples,
input_shape=(input_dim, input_dim),
classification=True,
num_classes=num_classes)
y_test = np_utils.to_categorical(y_test... |
def test_TensorBoard_multi_input_output(tmpdir):
i += 1
i = i % max_batch_index
inp1 = Input((input_dim,))
inp2 = Input((input_dim,))
inp = add([inp1, inp2])
hidden = Dense(num_hidden, activation='relu')(inp)
hidden = Dropout(0.1)(hidden)
output1 = Dense(num_classes, act... | def test_TensorBoard_multi_input_output(tmpdir):
i += 1
i = i % max_batch_index
inp1 = Input((input_dim, input_dim))
inp2 = Input((input_dim, input_dim))
inp_3d = add([inp1, inp2])
inp_2d = GlobalAveragePooling1D()(inp_3d)
inp_pair = Lambda(lambda x: x)([inp_3d, inp_2d]) # ... |
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... |
from django.db import close_old_connections, connection
from django.test import (
RequestFactory, SimpleTestCase, TransactionTestCase, override_settings,
)
class HandlerTests(SimpleTestCase): | from django.db import close_old_connections, connection
from django.test import (
RequestFactory, SimpleTestCase, TransactionTestCase, override_settings,
)
from django.utils.version import PY37
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... |
This module implements the FormRequest class which is a more convenient class
See documentation in docs/topics/request-response.rst
"""
from six.moves.urllib.parse import urljoin, urlencode
import lxml.html
from parsel.selector import create_root_node
import six
from scrapy.http.request import Request
from scrapy.util... | This module implements the FormRequest class which is a more convenient class
See documentation in docs/topics/request-response.rst
"""
import six
from six.moves.urllib.parse import urljoin, urlencode
import lxml.html
from parsel.selector import create_root_node
from w3lib.html import strip_html5_whitespace
from scr... |
class FormRequest(Request):
def _get_form_url(form, url):
if url is None:
return urljoin(form.base_url, form.action)
return urljoin(form.base_url, url)
| class FormRequest(Request):
def _get_form_url(form, url):
if url is None:
action = form.get('action')
if action is None:
return form.base_url
return urljoin(form.base_url, strip_html5_whitespace(action))
return urljoin(form.base_url, url)
|
class FormRequestTest(RequestTest):
fs = _qs(req, to_unicode=True, encoding='latin1')
self.assertTrue(fs[u'price in \u00a5'])
def test_from_response_multiple_forms_clickdata(self):
response = _buildresponse(
"""<form name="form1"> | class FormRequestTest(RequestTest):
fs = _qs(req, to_unicode=True, encoding='latin1')
self.assertTrue(fs[u'price in \u00a5'])
def test_from_response_multiple_forms_clickdata(self):
response = _buildresponse(
"""<form name="form1"> |
class FormRequestTest(RequestTest):
"""
<html>
<head>
<base href="http://b.com/">
</head>
<body>
<form action="test_form"> | class FormRequestTest(RequestTest):
"""
<html>
<head>
<base href=" http://b.com/">
</head>
<body>
<form action="test_form"> |
class FormRequestTest(RequestTest):
req = self.request_class.from_response(response)
self.assertEqual(req.url, 'http://b.com/test_form')
def test_from_response_css(self):
response = _buildresponse(
"""<form action="post.php" method="POST"> | class FormRequestTest(RequestTest):
req = self.request_class.from_response(response)
self.assertEqual(req.url, 'http://b.com/test_form')
def test_spaces_in_action(self):
resp = _buildresponse('<body><form action=" path\n"></form></body>')
req = self.request_class.from_response(resp)... |
class FormRequestTest(RequestTest):
self.assertRaises(ValueError, self.request_class.from_response,
response, formcss="input[name='abc']")
def _buildresponse(body, **kwargs):
kwargs.setdefault('body', body)
kwargs.setdefault('url', 'http://example.com')
kwargs.setdefault('... | class FormRequestTest(RequestTest):
self.assertRaises(ValueError, self.request_class.from_response,
response, formcss="input[name='abc']")
def _buildresponse(body, **kwargs):
kwargs.setdefault('body', body)
kwargs.setdefault('url', 'http://example.com')
kwargs.setdefault(... |
def _parse_jp2_header(fp):
else:
hlen = 8
if tbox == b'jp2h':
header = fp.read(lbox - hlen)
break | def _parse_jp2_header(fp):
else:
hlen = 8
if lbox < hlen:
raise SyntaxError('Invalid JP2 header length')
if tbox == b'jp2h':
header = fp.read(lbox - hlen)
break |
def test_not_match(command):
@pytest.mark.parametrize('command, output', [
(Command(script='git push', stderr=git_err), 'git push --force'),
(Command(script='git push nvbn', stderr=git_err), 'git push --force nvbn'),
(Command(script='git push nvbn master', stderr=git_err), 'git push --force nvbn master')]... | def test_not_match(command):
@pytest.mark.parametrize('command, output', [
(Command(script='git push', stderr=git_err), 'git push --force-with-lease'),
(Command(script='git push nvbn', stderr=git_err), 'git push --force-with-lease nvbn'),
(Command(script='git push nvbn master', stderr=git_err), 'git push ... |
def match(command):
@git_support
def get_new_command(command):
return replace_argument(command.script, 'push', 'push --force')
enabled_by_default = False | def match(command):
@git_support
def get_new_command(command):
return replace_argument(command.script, 'push', 'push --force-with-lease')
enabled_by_default = False |
def _make_result(formats, **kwargs):
'id': 'testid',
'title': 'testttitle',
'extractor': 'testex',
}
res.update(**kwargs)
return res | def _make_result(formats, **kwargs):
'id': 'testid',
'title': 'testttitle',
'extractor': 'testex',
'extractor_key': 'TestEx',
}
res.update(**kwargs)
return res |
class TestYoutubeDL(unittest.TestCase):
'_type': 'url_transparent',
'url': 'foo2:',
'ie_key': 'Foo2',
'title': 'foo1 title'
}
class Foo2IE(InfoExtractor): | class TestYoutubeDL(unittest.TestCase):
'_type': 'url_transparent',
'url': 'foo2:',
'ie_key': 'Foo2',
'title': 'foo1 title',
'id': 'foo1_id',
}
class Foo2IE(InfoExtractor): |
class TestYoutubeDL(unittest.TestCase):
downloaded = ydl.downloaded_info_dicts[0]
self.assertEqual(downloaded['url'], TEST_URL)
self.assertEqual(downloaded['title'], 'foo1 title')
if __name__ == '__main__': | class TestYoutubeDL(unittest.TestCase):
downloaded = ydl.downloaded_info_dicts[0]
self.assertEqual(downloaded['url'], TEST_URL)
self.assertEqual(downloaded['title'], 'foo1 title')
self.assertEqual(downloaded['id'], 'testid')
self.assertEqual(downloaded['extractor'], 'testex')
... |
class YoutubeDL(object):
force_properties = dict(
(k, v) for k, v in ie_result.items() if v is not None)
for f in ('_type', 'url', 'ie_key'):
if f in force_properties:
del force_properties[f]
new_result = info.copy() | class YoutubeDL(object):
force_properties = dict(
(k, v) for k, v in ie_result.items() if v is not None)
for f in ('_type', 'url', 'id', 'extractor', 'extractor_key', 'ie_key'):
if f in force_properties:
del force_properties[f]
new... |
from django.test.utils import override_settings
from django.urls import reverse
from django.utils.timezone import now
from allauth.account.forms import BaseSignupForm, SignupForm
from allauth.account.models import (
EmailAddress,
EmailConfirmation, | from django.test.utils import override_settings
from django.urls import reverse
from django.utils.timezone import now
from allauth.account.forms import BaseSignupForm, ResetPasswordForm, SignupForm
from allauth.account.models import (
EmailAddress,
EmailConfirmation, |
class ConfirmationViewTests(TestCase):
args=[key]))
assert mock_perform_login.called | class ConfirmationViewTests(TestCase):
args=[key]))
assert mock_perform_login.called
class TestCVE2019_19844(TestCase):
global_request = RequestFactory().get('/')
def test_user_email_unicode_collision(self):
User = get_user_model()
User.objects.create_user('m... |
from collections import OrderedDict
from datetime import timedelta
| import unicodedata
from collections import OrderedDict
from datetime import timedelta
|
from .adapter import get_adapter
from .app_settings import EmailVerificationMethod
def get_next_redirect_url(request, redirect_field_name="next"):
"""
Returns the next URL to redirect to, if it was explicitly passed | from .adapter import get_adapter
from .app_settings import EmailVerificationMethod
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).
"""
norm_s1 = unicodedata.norm... |
def filter_users_by_email(email):
from .models import EmailAddress
User = get_user_model()
mails = EmailAddress.objects.filter(email__iexact=email)
users = [e.user for e in mails.prefetch_related('user')]
if app_settings.USER_MODEL_EMAIL_FIELD:
q_dict = {app_settings.USER_MODEL_EMAIL_FIELD +... | def filter_users_by_email(email):
from .models import EmailAddress
User = get_user_model()
mails = EmailAddress.objects.filter(email__iexact=email)
users = []
for e in mails.prefetch_related('user'):
if _unicode_ci_compare(e.email, email):
users.append(e.user)
if app_settings... |
def check_required_arguments(argument_spec, module_parameters):
missing.append(k)
if missing:
msg = "missing required arguments: %s" % ", ".join(missing)
raise TypeError(to_native(msg))
return missing | def check_required_arguments(argument_spec, module_parameters):
missing.append(k)
if missing:
msg = "missing required arguments: %s" % ", ".join(sorted(missing))
raise TypeError(to_native(msg))
return missing |
def test_check_mutually_exclusive_found(mutually_exclusive_terms):
'fox': 'red',
'socks': 'blue',
}
expected = "TypeError('parameters are mutually exclusive: string1|string2, box|fox|socks',)"
with pytest.raises(TypeError) as e:
check_mutually_exclusive(mutually_exclusive_terms, par... | def test_check_mutually_exclusive_found(mutually_exclusive_terms):
'fox': 'red',
'socks': 'blue',
}
expected = "parameters are mutually exclusive: string1|string2, box|fox|socks"
with pytest.raises(TypeError) as e:
check_mutually_exclusive(mutually_exclusive_terms, params)
asse... |
def test_check_mutually_exclusive_none():
def test_check_mutually_exclusive_no_params(mutually_exclusive_terms):
with pytest.raises(TypeError) as te:
check_mutually_exclusive(mutually_exclusive_terms, None)
assert "TypeError: 'NoneType' object is not iterable" in to_native(te.error) | def test_check_mutually_exclusive_none():
def test_check_mutually_exclusive_no_params(mutually_exclusive_terms):
with pytest.raises(TypeError) as te:
check_mutually_exclusive(mutually_exclusive_terms, None)
assert "'NoneType' object is not iterable" in to_native(te.value) |
def default_urlconf(request):
var s = link.getElementsByTagName('span')[0];
var uarr = String.fromCharCode(0x25b6);
var darr = String.fromCharCode(0x25bc);
s.innerHTML = s.innerHTML == uarr ? darr : uarr;
return false;
}
function switchPastebinFriendly(link) {
s1 = "Switch to... | def default_urlconf(request):
var s = link.getElementsByTagName('span')[0];
var uarr = String.fromCharCode(0x25b6);
var darr = String.fromCharCode(0x25bc);
s.textContent = s.textContent == uarr ? darr : uarr;
return false;
}
function switchPastebinFriendly(link) {
s1 = "Switc... |
class ChapterXtra1Admin(admin.ModelAdmin):
class ArticleAdmin(admin.ModelAdmin):
list_display = ('content', 'date', callable_year, 'model_year',
'modeladmin_year', 'model_year_reversed')
list_filter = ('date', 'section')
view_on_site = False
fieldsets = ( | class ChapterXtra1Admin(admin.ModelAdmin):
class ArticleAdmin(admin.ModelAdmin):
list_display = ('content', 'date', callable_year, 'model_year',
'modeladmin_year', 'model_year_reversed', 'section')
list_editable = ('section',)
list_filter = ('date', 'section')
view_on_site = False
... |
from django.utils.encoding import python_2_unicode_compatible
class Section(models.Model):
"""
A simple section that links to articles, to test linking to related items | from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Section(models.Model):
"""
A simple section that links to articles, to test linking to related items |
class Section(models.Model):
"""
name = models.CharField(max_length=100)
@property
def name_property(self):
""" | class Section(models.Model):
"""
name = models.CharField(max_length=100)
def __str__(self):
return self.name
@property
def name_property(self):
""" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.