buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
class Line:
bracket_depth = leaf.bracket_depth
if bracket_depth == depth and leaf.type == token.COMMA:
commas += 1
if leaf.parent and leaf.parent.type == syms.arglist:
commas += 1
break
| class Line:
bracket_depth = leaf.bracket_depth
if bracket_depth == depth and leaf.type == token.COMMA:
commas += 1
if leaf.parent and leaf.parent.type in {
syms.arglist,
syms.typedargslist,
}:
... |
def bracket_split_build_line(
if leaves:
# Since body is a new indent level, remove spurious leading whitespace.
normalize_prefix(leaves[0], inside_brackets=True)
# Ensure a trailing comma for imports, but be careful not to add one after
# any comments.
... | def bracket_split_build_line(
if leaves:
# Since body is a new indent level, remove spurious leading whitespace.
normalize_prefix(leaves[0], inside_brackets=True)
# Ensure a trailing comma for imports and standalone function arguments, but
# be careful not to add ... |
class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
@patch("black.dump_to_file", dump_to_stderr)
def test_expression(self) -> None:
source, expected = read_data("expression") | class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
@patch("black.dump_to_file", dump_to_stderr)
def test_function_trailing_comma(self) -> None:
source, expected = read_data("function_trailing_comma")
... |
class TestUtil(unittest.TestCase):
inp = '''{"duration": "00:01:07"}'''
self.assertEqual(js_to_json(inp), '''{"duration": "00:01:07"}''')
def test_js_to_json_edgecases(self):
on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\... | class TestUtil(unittest.TestCase):
inp = '''{"duration": "00:01:07"}'''
self.assertEqual(js_to_json(inp), '''{"duration": "00:01:07"}''')
inp = '''{segments: [{"offset":-3.885780586188048e-16,"duration":39.75000000000001}]}'''
self.assertEqual(js_to_json(inp), '''{"segments": [{"offset"... |
class TestUtil(unittest.TestCase):
on = js_to_json('{/*comment\n*/42/*comment\n*/:/*comment\n*/42/*comment\n*/}')
self.assertEqual(json.loads(on), {'42': 42})
def test_extract_attributes(self):
self.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
self.assertEqual(extract_at... | class TestUtil(unittest.TestCase):
on = js_to_json('{/*comment\n*/42/*comment\n*/:/*comment\n*/42/*comment\n*/}')
self.assertEqual(json.loads(on), {'42': 42})
on = js_to_json('{42:4.2e1}')
self.assertEqual(json.loads(on), {'42': 42.0})
def test_extract_attributes(self):
sel... |
def js_to_json(code):
"(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"|
'(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
{comment}|,(?={skip}[\]}}])|
[a-zA-Z_][.a-zA-Z_0-9]*|
\b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:{skip}:)?|
[0-9]+(?={skip}:)
'''.format(comment=COMMENT_R... | def js_to_json(code):
"(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"|
'(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
{comment}|,(?={skip}[\]}}])|
(?:(?<![0-9])[eE]|[a-df-zA-DF-Z_])[.a-zA-Z_0-9]*|
\b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:{skip}:)?|
[0-9]+(?={skip}:)
'''... |
See documentation in docs/topics/downloader-middleware.rst
"""
from w3lib.http import basic_auth_header
from scrapy import signals
class HttpAuthMiddleware(object): |
See documentation in docs/topics/downloader-middleware.rst
"""
import warnings
from w3lib.http import basic_auth_header
from scrapy import signals
from scrapy.exceptions import ScrapyDeprecationWarning
from scrapy.utils.httpobj import urlparse_cached
from scrapy.utils.url import url_is_from_any_domain
class HttpAu... |
def spider_opened(self, spider):
pwd = getattr(spider, 'http_pass', '')
if usr or pwd:
self.auth = basic_auth_header(usr, pwd)
def process_request(self, request, spider):
auth = getattr(self, 'auth', None)
if auth and b'Authorization' not in request.headers:
... | def spider_opened(self, spider):
pwd = getattr(spider, 'http_pass', '')
if usr or pwd:
self.auth = basic_auth_header(usr, pwd)
if not hasattr(spider, 'http_auth_domain'):
warnings.warn('Using HttpAuthMiddleware without http_auth_domain is deprecated and can cause ... |
import unittest
from scrapy.http import Request
from scrapy.downloadermiddlewares.httpauth import HttpAuthMiddleware
from scrapy.spiders import Spider
class TestSpider(Spider):
http_user = 'foo'
http_pass = 'bar'
class HttpAuthMiddlewareTest(unittest.TestCase): | import unittest
from w3lib.http import basic_auth_header
from scrapy.http import Request
from scrapy.downloadermiddlewares.httpauth import HttpAuthMiddleware
from scrapy.spiders import Spider
class TestSpiderLegacy(Spider):
http_user = 'foo'
http_pass = 'bar'
class TestSpider(Spider):
http_user = 'foo... |
def setUp(self):
def tearDown(self):
del self.mw
def test_auth(self):
req = Request('http://scrapytest.org/')
assert self.mw.process_request(req, self.spider) is None
self.assertEqual(req.headers['Authorization'], b'Basic Zm9vOmJhcg==')
def test_auth_already_set(self):
... | def setUp(self):
def tearDown(self):
del self.mw
def test_no_auth(self):
req = Request('http://example-noauth.com/')
assert self.mw.process_request(req, self.spider) is None
self.assertNotIn('Authorization', req.headers)
def test_auth_domain(self):
req = Request('ht... |
##parameters=default_tab, obj=None, portal_tabs=[]
##title=
##
from AccessControl import Unauthorized
| ##parameters=default_tab, obj=None, portal_tabs=[]
##title=
##
from zExceptions import Forbidden
if container.REQUEST['PUBLISHED'] is script:
raise Forbidden('Script may not be published.')
from AccessControl import Unauthorized
|
'self', which will cause the list to be sorted in place without a sort
function.
"""
list_len = len(input_list)
| 'self', which will cause the list to be sorted in place without a sort
function.
"""
from zExceptions import Forbidden
if container.REQUEST['PUBLISHED'] is script:
raise Forbidden('Script may not be published.')
list_len = len(input_list)
|
##bind subpath=traverse_subpath
##parameters=qs=None, **kw
##title=Creates a query string based on existing string plus keyword arguments
from Products.PythonScripts.standard import url_quote_plus
L = [] | ##bind subpath=traverse_subpath
##parameters=qs=None, **kw
##title=Creates a query string based on existing string plus keyword arguments
from zExceptions import Forbidden
if container.REQUEST['PUBLISHED'] is script:
raise Forbidden('Script may not be published.')
from Products.PythonScripts.standard import url_quo... |
##parameters=input_id
return r"""
| ##parameters=input_id
from zExceptions import Forbidden
if container.REQUEST['PUBLISHED'] is script:
raise Forbidden('Script may not be published.')
return r"""
|
def test_bad_server_hostname(self):
with self.assertRaises(ValueError):
ctx.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(),
server_hostname=".example.org")
class MemoryBIOTests(unittest.TestCase): | def test_bad_server_hostname(self):
with self.assertRaises(ValueError):
ctx.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(),
server_hostname=".example.org")
with self.assertRaises(TypeError):
ctx.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(),
... |
def makecmdoptions(self):
def __str__(self):
return "<SvnAuth username=%s ...>" %(self.username,)
rex_blame = re.compile(r'\s*(\d+)\s*(\S+) (.*)')
class SvnWCCommandPath(common.PathBase):
""" path implementation offering access/modification to svn working copies. | def makecmdoptions(self):
def __str__(self):
return "<SvnAuth username=%s ...>" %(self.username,)
rex_blame = re.compile(r'\s*(\d+)\s+(\S+) (.*)')
class SvnWCCommandPath(common.PathBase):
""" path implementation offering access/modification to svn working copies. |
"""
import os
import threading
from itertools import chain
| """
import os
import re
import sys
import threading
from itertools import chain
|
_cache = {}
_cache_lock = threading.RLock()
_dirname = os.path.join(os.path.dirname(__file__), 'locale-data')
def normalize_locale(name): | _cache = {}
_cache_lock = threading.RLock()
_dirname = os.path.join(os.path.dirname(__file__), 'locale-data')
_windows_reserved_name_re = re.compile("^(con|prn|aux|nul|com[0-9]|lpt[0-9])$", re.I)
def normalize_locale(name): |
def normalize_locale(name):
return locale_id
def exists(name):
"""Check whether locale data is available for the given locale.
| def normalize_locale(name):
return locale_id
def resolve_locale_filename(name):
"""
Resolve a locale identifier to a `.dat` path on disk.
"""
# Clean up any possible relative paths.
name = os.path.basename(name)
# Ensure we're not left with one of the Windows reserved names.
... |
def exists(name):
return False
if name in _cache:
return True
file_found = os.path.exists(os.path.join(_dirname, '%s.dat' % name))
return True if file_found else bool(normalize_locale(name))
| def exists(name):
return False
if name in _cache:
return True
file_found = os.path.exists(resolve_locale_filename(name))
return True if file_found else bool(normalize_locale(name))
|
def load(name, merge_inherited=True):
:raise `IOError`: if no locale data file is found for the given locale
identifer, or one of the locales it inherits from
"""
_cache_lock.acquire()
try:
data = _cache.get(name) | def load(name, merge_inherited=True):
:raise `IOError`: if no locale data file is found for the given locale
identifer, or one of the locales it inherits from
"""
name = os.path.basename(name)
_cache_lock.acquire()
try:
data = _cache.get(name) |
def load(name, merge_inherited=True):
else:
parent = '_'.join(parts[:-1])
data = load(parent).copy()
filename = os.path.join(_dirname, '%s.dat' % name)
with open(filename, 'rb') as fileobj:
if name != 'root' and merge_in... | def load(name, merge_inherited=True):
else:
parent = '_'.join(parts[:-1])
data = load(parent).copy()
filename = resolve_locale_filename(name)
with open(filename, 'rb') as fileobj:
if name != 'root' and merge_inherited:
... |
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://babel.edgewall.org/log/.
import unittest
import random
from operator import methodcaller
from babel import localedata
class MergeResolveTestCase(unittest.TestCase): | # individuals. For the exact contribution history, see the revision
# history and logs, available at http://babel.edgewall.org/log/.
import os
import pickle
import sys
import tempfile
import unittest
import random
from operator import methodcaller
import pytest
from babel import localedata, Locale, UnknownLocaleErro... |
def listdir_spy(*args):
localedata.locale_identifiers.cache = None
assert localedata.locale_identifiers()
assert len(listdir_calls) == 2 | def listdir_spy(*args):
localedata.locale_identifiers.cache = None
assert localedata.locale_identifiers()
assert len(listdir_calls) == 2
def test_locale_name_cleanup():
"""
Test that locale identifiers are cleaned up to avoid directory traversal.
"""
no_exist_name = os.path.join(tempfile.g... |
from pandas.core.dtypes.cast import (
)
from pandas.core.dtypes.common import (
ensure_platform_int,
is_datetime64tz_dtype,
is_datetime_or_timedelta_dtype,
is_dtype_equal, | from pandas.core.dtypes.cast import (
)
from pandas.core.dtypes.common import (
ensure_platform_int,
is_categorical,
is_datetime64tz_dtype,
is_datetime_or_timedelta_dtype,
is_dtype_equal, |
from pandas.core.dtypes.generic import ABCSeries
from pandas.core.dtypes.missing import isna
from pandas._typing import AnyArrayLike
from pandas.core.arrays.interval import IntervalArray, _interval_shared_docs
import pandas.core.common as com
import pandas.core.indexes.base as ibase | from pandas.core.dtypes.generic import ABCSeries
from pandas.core.dtypes.missing import isna
from pandas._typing import AnyArrayLike
from pandas.core.algorithms import take_1d
from pandas.core.arrays.interval import IntervalArray, _interval_shared_docs
import pandas.core.common as com
import pandas.core.indexes.base a... |
class IntervalIndex(IntervalMixin, Index):
left_indexer = self.left.get_indexer(target_as_index.left)
right_indexer = self.right.get_indexer(target_as_index.right)
indexer = np.where(left_indexer == right_indexer, left_indexer, -1)
elif not is_object_dtype(target_as_index):
... | class IntervalIndex(IntervalMixin, Index):
left_indexer = self.left.get_indexer(target_as_index.left)
right_indexer = self.right.get_indexer(target_as_index.right)
indexer = np.where(left_indexer == right_indexer, left_indexer, -1)
elif is_categorical(target_as_index):
... |
class TestDataFrameAnalytics:
tm.assert_frame_equal(result, expected)
# ---------------------------------------------------------------------
# Clip
| class TestDataFrameAnalytics:
tm.assert_frame_equal(result, expected)
def test_round_interval_category_columns(self):
# GH 30063
columns = pd.CategoricalIndex(pd.interval_range(0, 2))
df = DataFrame([[0.66, 1.1], [0.3, 0.25]], columns=columns)
result = df.round()
e... |
import re
import numpy as np
import pytest
from pandas import Interval, IntervalIndex, Timedelta, date_range, timedelta_range
from pandas.core.indexes.base import InvalidIndexError
import pandas.util.testing as tm
| import re
import numpy as np
import pytest
from pandas import (
CategoricalIndex,
Interval,
IntervalIndex,
Timedelta,
date_range,
timedelta_range,
)
from pandas.core.indexes.base import InvalidIndexError
import pandas.util.testing as tm
|
class TestGetIndexer:
expected = np.array([0] * size, dtype="intp")
tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize(
"tuples, closed",
[ | class TestGetIndexer:
expected = np.array([0] * size, dtype="intp")
tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize(
"target",
[
IntervalIndex.from_tuples([(7, 8), (1, 2), (3, 4), (0, 1)]),
IntervalIndex.from_tuples([(0, 1), (1, 2), (3,... |
def set_user_password(self, context, user_id, user):
def update_user_tenant(self, context, user_id, user):
"""Update the default tenant."""
# ensure that we're a member of that tenant
tenant_id = user.get('tenantId')
self.identity_api.add_user_to_tenant(context, tenant_id, user_id) | def set_user_password(self, context, user_id, user):
def update_user_tenant(self, context, user_id, user):
"""Update the default tenant."""
self.assert_admin(context)
# ensure that we're a member of that tenant
tenant_id = user.get('tenantId')
self.identity_api.add_user_to_t... |
class Series(base.IndexOpsMixin, generic.NDFrame):
indexer = self.index.get_indexer_for(key)
return self.iloc[indexer]
else:
return self._get_values(key)
if isinstance(key, (list, tuple)):
# TODO: de-dup with tuple case handled above? | class Series(base.IndexOpsMixin, generic.NDFrame):
indexer = self.index.get_indexer_for(key)
return self.iloc[indexer]
else:
return self.iloc[key]
if isinstance(key, (list, tuple)):
# TODO: de-dup with tuple case handled above? |
class TestFancy:
idxr = idxr(obj)
nd3 = np.random.randint(5, size=(2, 2, 2))
msg = (
r"Buffer has wrong number of dimensions \(expected 1, "
r"got 3\)|"
"Cannot index with multidimensional key|"
r"Wrong number of dimensions. values.ndim != ndim \[... | class TestFancy:
idxr = idxr(obj)
nd3 = np.random.randint(5, size=(2, 2, 2))
msg = "|".join(
[
r"Buffer has wrong number of dimensions \(expected 1, got 3\)",
"Cannot index with multidimensional key",
r"Wrong number of dimensions. valu... |
def url_concat(url, args):
>>> url_concat("http://example.com/foo?a=b", [("c", "d"), ("c", "d2")])
'http://example.com/foo?a=b&c=d&c=d2'
"""
parsed_url = urlparse(url)
if isinstance(args, dict):
parsed_query = parse_qsl(parsed_url.query, keep_blank_values=True) | def url_concat(url, args):
>>> url_concat("http://example.com/foo?a=b", [("c", "d"), ("c", "d2")])
'http://example.com/foo?a=b&c=d&c=d2'
"""
if args is None:
return url
parsed_url = urlparse(url)
if isinstance(args, dict):
parsed_query = parse_qsl(parsed_url.query, keep_blank_val... |
class TestUrlConcat(unittest.TestCase):
)
self.assertEqual(url, "https://localhost/path?r=1&t=2")
def test_url_concat_with_frag(self):
url = url_concat(
"https://localhost/path#tab", | class TestUrlConcat(unittest.TestCase):
)
self.assertEqual(url, "https://localhost/path?r=1&t=2")
def test_url_concat_none_params(self):
url = url_concat(
"https://localhost/path?r=1&t=2",
None,
)
self.assertEqual(url, "https://localhost/path?r=1&t=2"... |
import sys
import tarfile
import threading
import time
import zipfile
from abc import abstractmethod
from multiprocessing.pool import ThreadPool | import sys
import tarfile
import threading
import time
import traceback
import zipfile
from abc import abstractmethod
from multiprocessing.pool import ThreadPool |
class OrderedEnqueuer(SequenceEnqueuer):
yield inputs
except Exception as e:
self.stop()
raise StopIteration(e)
def _send_sequence(self):
"""Send current Sequence to all workers.""" | class OrderedEnqueuer(SequenceEnqueuer):
yield inputs
except Exception as e:
self.stop()
six.raise_from(StopIteration(e), e)
def _send_sequence(self):
"""Send current Sequence to all workers.""" |
class GeneratorEnqueuer(SequenceEnqueuer):
self._use_multiprocessing = use_multiprocessing
self._threads = []
self._stop_event = None
self.queue = None
self.seed = seed
| class GeneratorEnqueuer(SequenceEnqueuer):
self._use_multiprocessing = use_multiprocessing
self._threads = []
self._stop_event = None
self._manager = None
self.queue = None
self.seed = seed
|
class GeneratorEnqueuer(SequenceEnqueuer):
try:
if self._use_multiprocessing or self.queue.qsize() < max_queue_size:
generator_output = next(self._generator)
self.queue.put(generator_output)
else:
... | class GeneratorEnqueuer(SequenceEnqueuer):
try:
if self._use_multiprocessing or self.queue.qsize() < max_queue_size:
generator_output = next(self._generator)
self.queue.put((True, generator_output))
else:
... |
class GeneratorEnqueuer(SequenceEnqueuer):
else:
thread.join(timeout)
if self._use_multiprocessing:
if self.queue is not None:
self.queue.close()
self._threads = []
self._stop_event = None | class GeneratorEnqueuer(SequenceEnqueuer):
else:
thread.join(timeout)
if self._manager:
self._manager.shutdown()
self._threads = []
self._stop_event = None |
class GeneratorEnqueuer(SequenceEnqueuer):
"""
while self.is_running():
if not self.queue.empty():
inputs = self.queue.get()
if inputs is not None:
yield inputs
else:
all_finished = all([not thread.is_alive() for... | class GeneratorEnqueuer(SequenceEnqueuer):
"""
while self.is_running():
if not self.queue.empty():
success, value = self.queue.get()
# Rethrow any exceptions found in the queue
if not success:
six.reraise(value.__class__, va... |
def test_generator_enqueuer_fail_threads():
FaultSequence()), use_multiprocessing=False)
enqueuer.start(3, 10)
gen_output = enqueuer.get()
with pytest.raises(StopIteration):
next(gen_output)
| def test_generator_enqueuer_fail_threads():
FaultSequence()), use_multiprocessing=False)
enqueuer.start(3, 10)
gen_output = enqueuer.get()
with pytest.raises(IndexError):
next(gen_output)
|
def test_generator_enqueuer_fail_processes():
FaultSequence()), use_multiprocessing=True)
enqueuer.start(3, 10)
gen_output = enqueuer.get()
with pytest.raises(StopIteration):
next(gen_output)
| def test_generator_enqueuer_fail_processes():
FaultSequence()), use_multiprocessing=True)
enqueuer.start(3, 10)
gen_output = enqueuer.get()
with pytest.raises(IndexError):
next(gen_output)
|
def test_multiprocessing_fit_error():
"""Raises an exception after a few good batches"""
for i in range(good_batches):
yield (np.random.randint(batch_size, 256, (50, 2)),
np.random.randint(batch_size, 2, 50))
raise RuntimeError
model = Sequential() | def test_multiprocessing_fit_error():
"""Raises an exception after a few good batches"""
for i in range(good_batches):
yield (np.random.randint(batch_size, 256, (50, 2)),
np.random.randint(batch_size, 12, 50))
raise RuntimeError
model = Sequential() |
def test_multiprocessing_fit_error():
samples = batch_size * (good_batches + 1)
with pytest.raises(StopIteration):
model.fit_generator(
custom_generator(), samples, 1,
workers=4, use_multiprocessing=True,
)
with pytest.raises(StopIteration):
model.fit_gener... | def test_multiprocessing_fit_error():
samples = batch_size * (good_batches + 1)
with pytest.raises(RuntimeError):
model.fit_generator(
custom_generator(), samples, 1,
workers=4, use_multiprocessing=True,
)
with pytest.raises(RuntimeError):
model.fit_generat... |
def test_multiprocessing_fit_error():
def test_multiprocessing_evaluate_error():
batch_size = 10
good_batches = 3
def custom_generator():
"""Raises an exception after a few good batches"""
for i in range(good_batches):
yield (np.random.randint(batch_size, 256, (50, 2)),
... | def test_multiprocessing_fit_error():
def test_multiprocessing_evaluate_error():
batch_size = 10
good_batches = 3
workers = 4
def custom_generator():
"""Raises an exception after a few good batches"""
for i in range(good_batches):
yield (np.random.randint(batch_size, 256, (5... |
def test_multiprocessing_predict_error():
model.add(Dense(1, input_shape=(5,)))
model.compile(loss='mse', optimizer='adadelta')
with pytest.raises(StopIteration):
model.predict_generator(
custom_generator(), good_batches * workers + 1, 1,
workers=workers, use_multiprocessing... | def test_multiprocessing_predict_error():
model.add(Dense(1, input_shape=(5,)))
model.compile(loss='mse', optimizer='adadelta')
with pytest.raises(RuntimeError):
model.predict_generator(
custom_generator(), good_batches * workers + 1, 1,
workers=workers, use_multiprocessing=... |
class _ScalarAccessIndexer(_NDFrameIndexerBase):
if not isinstance(key, tuple):
key = _tuplify(self.ndim, key)
if len(key) != self.ndim:
raise ValueError("Not enough indexers for scalar access (setting)!")
key = list(self._convert_key(key, is_setter=True))
self.... | class _ScalarAccessIndexer(_NDFrameIndexerBase):
if not isinstance(key, tuple):
key = _tuplify(self.ndim, key)
key = list(self._convert_key(key, is_setter=True))
if len(key) != self.ndim:
raise ValueError("Not enough indexers for scalar access (setting)!")
self.... |
class _AtIndexer(_ScalarAccessIndexer):
Require they keys to be the same type as the index. (so we don't
fallback)
"""
# allow arbitrary setting
if is_setter:
return list(key) | class _AtIndexer(_ScalarAccessIndexer):
Require they keys to be the same type as the index. (so we don't
fallback)
"""
# GH 26989
# For series, unpacking key needs to result in the label.
# This is already the case for len(key) == 1; e.g. (1,)
if self.ndim == 1 an... |
def test_iat_series_with_period_index():
expected = ser[index[0]]
result = ser.iat[0]
assert expected == result | def test_iat_series_with_period_index():
expected = ser[index[0]]
result = ser.iat[0]
assert expected == result
def test_at_with_tuple_index_get():
# GH 26989
# DataFrame.at getter works with Index of tuples
df = DataFrame({"a": [1, 2]}, index=[(1, 2), (3, 4)])
assert df.index.nlevels == 1... |
from youtube_dl.utils import (
shell_quote,
smuggle_url,
str_to_int,
timeconvert,
unescapeHTML,
unified_strdate, | from youtube_dl.utils import (
shell_quote,
smuggle_url,
str_to_int,
struct_unpack,
timeconvert,
unescapeHTML,
unified_strdate, |
class TestUtil(unittest.TestCase):
testPL(5, 2, (2, 99), [2, 3, 4])
testPL(5, 2, (20, 99), [])
if __name__ == '__main__':
unittest.main() | class TestUtil(unittest.TestCase):
testPL(5, 2, (2, 99), [2, 3, 4])
testPL(5, 2, (20, 99), [])
def test_struct_unpack(self):
self.assertEqual(struct_unpack(u'!B', b'\x00'), (0,))
if __name__ == '__main__':
unittest.main() |
import base64
import io
import itertools
import os
from struct import unpack, pack
import time
import xml.etree.ElementTree as etree
from .common import FileDownloader
from .http import HttpFD
from ..utils import (
compat_urllib_request,
compat_urlparse,
format_bytes, | import base64
import io
import itertools
import os
import time
import xml.etree.ElementTree as etree
from .common import FileDownloader
from .http import HttpFD
from ..utils import (
struct_pack,
struct_unpack,
compat_urllib_request,
compat_urlparse,
format_bytes, |
class FlvReader(io.BytesIO):
# Utility functions for reading numbers and strings
def read_unsigned_long_long(self):
return unpack('!Q', self.read(8))[0]
def read_unsigned_int(self):
return unpack('!I', self.read(4))[0]
def read_unsigned_char(self):
return unpack('!B', self.rea... | class FlvReader(io.BytesIO):
# Utility functions for reading numbers and strings
def read_unsigned_long_long(self):
return struct_unpack('!Q', self.read(8))[0]
def read_unsigned_int(self):
return struct_unpack('!I', self.read(4))[0]
def read_unsigned_char(self):
return struct_... |
def write_flv_header(stream, metadata):
# Script data
stream.write(b'\x12')
# Size of the metadata with 3 bytes
stream.write(pack('!L', len(metadata))[1:])
stream.write(b'\x00\x00\x00\x00\x00\x00\x00')
stream.write(metadata)
# Magic numbers extracted from the output files produced by AdobeHD... | def write_flv_header(stream, metadata):
# Script data
stream.write(b'\x12')
# Size of the metadata with 3 bytes
stream.write(struct_pack('!L', len(metadata))[1:])
stream.write(b'\x00\x00\x00\x00\x00\x00\x00')
stream.write(metadata)
# Magic numbers extracted from the output files produced by ... |
import platform
import re
import ssl
import socket
import subprocess
import sys
import traceback | import platform
import re
import ssl
import socket
import struct
import subprocess
import sys
import traceback |
def uppercase_escape(s):
return re.sub(
r'\\U([0-9a-fA-F]{8})',
lambda m: compat_chr(int(m.group(1), base=16)), s) | def uppercase_escape(s):
return re.sub(
r'\\U([0-9a-fA-F]{8})',
lambda m: compat_chr(int(m.group(1), base=16)), s)
try:
struct.pack(u'!I', 0)
except TypeError:
# In Python 2.6 (and some 2.7 versions), struct requires a bytes argument
def struct_pack(spec, *args):
if isinstance(s... |
Tests for L{twisted.web.twcgi}.
"""
import sys
import os
import json
from io import BytesIO
from twisted.trial import unittest
from twisted.internet import reactor, interfaces, error
from twisted.python import util, failure, log
from twisted.web.http import NOT_FOUND, INTERNAL_SERVER_ERROR
from twisted.web import cl... | Tests for L{twisted.web.twcgi}.
"""
import sys, os
from twisted.trial import unittest
from twisted.internet import reactor, interfaces, error
from twisted.python import util, failure, log
from twisted.web.http import NOT_FOUND, INTERNAL_SERVER_ERROR
from twisted.web import client, twcgi, server, resource
from twisted... |
print
print "cgi output"
'''
HEADER_OUTPUT_CGI = '''\
import json
import os
print("")
print("")
vals = {x:y for x,y in os.environ.items() if x.startswith("HTTP_")}
print(json.dumps(vals))
'''
class PythonScript(twcgi.FilteredScript):
filter = sys.executable
| print
print "cgi output"
'''
class PythonScript(twcgi.FilteredScript):
filter = sys.executable
|
class CGITests(unittest.TestCase):
return factory.deferred
def test_noProxyPassthrough(self):
"""
The CGI script is never called with the Proxy header passed through.
"""
cgiFilename = self.writeCGI(HEADER_OUTPUT_CGI)
portnum = self.startServer(cgiFilename)
... | class CGITests(unittest.TestCase):
return factory.deferred
def test_duplicateHeaderCGI(self):
"""
If a CGI script emits two instances of the same header, both are sent in |
class CGIScript(resource.Resource):
# Propagate HTTP headers
for title, header in request.getAllHeaders().items():
envname = title.replace('-', '_').upper()
if title not in ('content-type', 'content-length', 'proxy'):
envname = "HTTP_" + envname
env[en... | class CGIScript(resource.Resource):
# Propagate HTTP headers
for title, header in request.getAllHeaders().items():
envname = title.replace('-', '_').upper()
if title not in ('content-type', 'content-length'):
envname = "HTTP_" + envname
env[envname] = ... |
from __future__ import division
import os
import re
import sys
import mimetypes
import threading
from time import sleep, time | from __future__ import division
import os
import re
import sys
import errno
import mimetypes
import threading
from time import sleep, time |
def filename_from_url(url, content_type):
return fn
def get_unique_filename(filename, exists=os.path.exists):
attempt = 0
while True:
suffix = '-' + str(attempt) if attempt > 0 else ''
if not exists(filename + suffix):
return filename + suffix
attempt += 1
| def filename_from_url(url, content_type):
return fn
def trim_filename(filename, max_len):
if len(filename) > max_len:
trim_by = len(filename) - max_len
name, ext = os.path.splitext(filename)
if trim_by >= len(name):
filename = filename[:-trim_by]
else:
f... |
import os
import time
import pytest
from requests.structures import CaseInsensitiveDict
from httpie.compat import urlopen | import os
import time
import pytest
import mock
from requests.structures import CaseInsensitiveDict
from httpie.compat import urlopen |
class TestDownloadUtils:
content_type='x-foo/bar'
)
def test_unique_filename(self):
def attempts(unique_on_attempt=0):
# noinspection PyUnresolvedReferences,PyUnusedLocal
def exists(filename): | class TestDownloadUtils:
content_type='x-foo/bar'
)
@pytest.mark.parametrize(
'orig_name, unique_on_attempt, expected',
[
# Simple
('foo.bar', 0, 'foo.bar'),
('foo.bar', 1, 'foo.bar-1'),
('foo.bar', 10, 'foo.bar-10'),
#... |
class TestDownloadUtils:
exists.attempt = 0
return exists
assert 'foo.bar' == get_unique_filename('foo.bar', attempts(0))
assert 'foo.bar-1' == get_unique_filename('foo.bar', attempts(1))
assert 'foo.bar-10' == get_unique_filename('foo.bar', attempts(10))
class TestDow... | class TestDownloadUtils:
exists.attempt = 0
return exists
get_filename_max_length.return_value = 10
actual = get_unique_filename(orig_name, attempts(unique_on_attempt))
assert expected == actual
class TestDownloads: |
def generate_timestamp():
def generate_nonce(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.randint(0, 9)) for i in range(length)])
def generate_verifier(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.randint(0, 9)) for i in range(length)])
clas... | def generate_timestamp():
def generate_nonce(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.SystemRandom().randint(0, 9)) for i in range(length)])
def generate_verifier(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.SystemRandom().randint(0, 9)) f... |
class Request(dict):
@classmethod
def make_nonce(cls):
"""Generate pseudorandom number."""
return str(random.randint(0, 100000000))
@classmethod
def from_request(cls, http_method, http_url, headers=None, parameters=None, | class Request(dict):
@classmethod
def make_nonce(cls):
"""Generate pseudorandom number."""
return str(random.SystemRandom().randint(0, 100000000))
@classmethod
def from_request(cls, http_method, http_url, headers=None, parameters=None, |
from waitress.buffers import OverflowableBuffer
from waitress.receiver import ChunkedReceiver, FixedStreamReceiver
from waitress.utilities import (
BadRequest,
RequestEntityTooLarge, |
from waitress.buffers import OverflowableBuffer
from waitress.receiver import ChunkedReceiver, FixedStreamReceiver
from waitress.rfc7230 import HEADER_FIELD_RE, ONLY_DIGIT_RE
from waitress.utilities import (
BadRequest,
RequestEntityTooLarge, |
find_double_newline,
)
from .rfc7230 import HEADER_FIELD
def unquote_bytes_to_wsgi(bytestring):
return unquote_to_bytes(bytestring).decode("latin-1") | find_double_newline,
)
def unquote_bytes_to_wsgi(bytestring):
return unquote_to_bytes(bytestring).decode("latin-1") |
def parse_header(self, header_plus):
headers = self.headers
for line in lines:
header = HEADER_FIELD.match(line)
if not header:
raise ParsingError("Invalid header") | def parse_header(self, header_plus):
headers = self.headers
for line in lines:
header = HEADER_FIELD_RE.match(line)
if not header:
raise ParsingError("Invalid header") |
def parse_header(self, header_plus):
self.connection_close = True
if not self.chunked:
try:
cl = int(headers.get("CONTENT_LENGTH", 0))
except ValueError:
raise ParsingError("Content-Length is invalid")
self.content_length = cl... | def parse_header(self, header_plus):
self.connection_close = True
if not self.chunked:
cl = headers.get("CONTENT_LENGTH", "0")
if not ONLY_DIGIT_RE.match(cl.encode("latin-1")):
raise ParsingError("Content-Length is invalid")
cl = int(cl)
... |
"""Data Chunk Receiver
"""
from waitress.utilities import BadRequest, find_double_newline
| """Data Chunk Receiver
"""
from waitress.rfc7230 import CHUNK_EXT_RE, ONLY_HEXDIG_RE
from waitress.utilities import BadRequest, find_double_newline
|
def received(self, s):
s = b""
else:
self.chunk_end = b""
if pos == 0:
# Chop off the terminating CR LF from the chunk
s = s[2:] | def received(self, s):
s = b""
else:
self.chunk_end = b""
if pos == 0:
# Chop off the terminating CR LF from the chunk
s = s[2:] |
def received(self, s):
line = s[:pos]
s = s[pos + 2 :]
self.control_line = b""
line = line.strip()
if line:
# Begin a new chunk.
semi = line.find(b";")
... | def received(self, s):
line = s[:pos]
s = s[pos + 2 :]
self.control_line = b""
if line:
# Begin a new chunk.
semi = line.find(b";")
if semi >= 0:
... |
import re
WS = "[ \t]"
OWS = WS + "{0,}?"
RWS = WS + "{1,}?" |
import re
HEXDIG = "[0-9a-fA-F]"
DIGIT = "[0-9]"
WS = "[ \t]"
OWS = WS + "{0,}?"
RWS = WS + "{1,}?" |
# ; visible (printing) characters
VCHAR = r"\x21-\x7e"
# header-field = field-name ":" OWS field-value OWS
# field-name = token
# field-value = *( field-content / obs-fold ) | # ; visible (printing) characters
VCHAR = r"\x21-\x7e"
# The '\\' between \x5b and \x5d is needed to escape \x5d (']')
QDTEXT = "[\t \x21\x23-\x5b\\\x5d-\x7e" + OBS_TEXT + "]"
QUOTED_PAIR = r"\\" + "([\t " + VCHAR + OBS_TEXT + "])"
QUOTED_STRING = '"(?:(?:' + QDTEXT + ")|(?:" + QUOTED_PAIR + '))*"'
... |
# Which allows the field value here to just see if there is even a value in the first place
FIELD_VALUE = "(?:" + FIELD_CONTENT + ")?"
HEADER_FIELD = re.compile(
(
"^(?P<name>" + TOKEN + "):" + OWS + "(?P<value>" + FIELD_VALUE + ")" + OWS + "$"
).encode("latin-1")
) | # Which allows the field value here to just see if there is even a value in the first place
FIELD_VALUE = "(?:" + FIELD_CONTENT + ")?"
# chunk-ext = *( ";" chunk-ext-name [ "=" chunk-ext-val ] )
# chunk-ext-name = token
# chunk-ext-val = token / quoted-string
CHUNK_EXT_NAME = TOKEN
CHUNK_EXT_VAL = "(?:" + TOKEN... |
import stat
import time
from .rfc7230 import OBS_TEXT, VCHAR
logger = logging.getLogger("waitress")
queue_logger = logging.getLogger("waitress.queue") | import stat
import time
from .rfc7230 import QUOTED_PAIR_RE, QUOTED_STRING_RE
logger = logging.getLogger("waitress")
queue_logger = logging.getLogger("waitress.queue") |
def parse_http_date(d):
return retval
# RFC 5234 Appendix B.1 "Core Rules":
# VCHAR = %x21-7E
# ; visible (printing) characters
vchar_re = VCHAR
# RFC 7230 Section 3.2.6 "Field Value Components":
# quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE
# qdtext = HTAB / SP /%x21... | def parse_http_date(d):
return retval
def undquote(value):
if value.startswith('"') and value.endswith('"'):
# So it claims to be DQUOTE'ed, let's validate that
matches = QUOTED_STRING_RE.match(value)
if matches and matches.end() == len(value):
# Remove the DQUOTE's from t... |
def undquote(value):
# Remove all backslashes that are followed by a valid vchar or
# obs-text
value = quoted_pair.sub(r"\1", value)
return value
elif not value.startswith('"') and not value.endswith('"'): | def undquote(value):
# Remove all backslashes that are followed by a valid vchar or
# obs-text
value = QUOTED_PAIR_RE.sub(r"\1", value)
return value
elif not value.startswith('"') and not value.endswith('"'): |
def test_chunking_request_without_content(self):
self.assertFalse("transfer-encoding" in headers)
def test_chunking_request_with_content(self):
control_line = b"20;\r\n" # 20 hex = 32 dec
s = b"This string has 32 characters.\r\n"
expected = s * 12
header = b"GET / HTTP/... | def test_chunking_request_without_content(self):
self.assertFalse("transfer-encoding" in headers)
def test_chunking_request_with_content(self):
control_line = b"20\r\n" # 20 hex = 32 dec
s = b"This string has 32 characters.\r\n"
expected = s * 12
header = b"GET / HTTP/1... |
def test_chunking_request_with_content(self):
self.assertFalse("transfer-encoding" in headers)
def test_broken_chunked_encoding(self):
control_line = b"20;\r\n" # 20 hex = 32 dec
s = b"This string has 32 characters.\r\n"
to_send = b"GET / HTTP/1.1\r\nTransfer-Encoding: chunked\... | def test_chunking_request_with_content(self):
self.assertFalse("transfer-encoding" in headers)
def test_broken_chunked_encoding(self):
control_line = b"20\r\n" # 20 hex = 32 dec
s = b"This string has 32 characters.\r\n"
to_send = b"GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r... |
def test_broken_chunked_encoding(self):
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_broken_chunked_encoding_missing_chunk_end(self):
control_line = b"20;\r\n" # 20 hex = 32 dec
s = b"This string has 32 characters.\r\n"
... | def test_broken_chunked_encoding(self):
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_broken_chunked_encoding_invalid_hex(self):
control_line = b"0x20\r\n" # 20 hex = 32 dec
s = b"This string has 32 characters.\r\n"
to_se... |
def test_received_chunked_completed_sets_content_length(self):
b"Transfer-Encoding: chunked\r\n"
b"X-Foo: 1\r\n"
b"\r\n"
b"1d;\r\n"
b"This string has 29 characters\r\n"
b"0\r\n\r\n"
) | def test_received_chunked_completed_sets_content_length(self):
b"Transfer-Encoding: chunked\r\n"
b"X-Foo: 1\r\n"
b"\r\n"
b"1d\r\n"
b"This string has 29 characters\r\n"
b"0\r\n\r\n"
) |
def test_parse_header_bad_content_length(self):
else: # pragma: nocover
self.assertTrue(False)
def test_parse_header_multiple_content_length(self):
data = b"GET /foobar HTTP/8.4\r\ncontent-length: 10\r\ncontent-length: 20\r\n"
| def test_parse_header_bad_content_length(self):
else: # pragma: nocover
self.assertTrue(False)
def test_parse_header_bad_content_length_plus(self):
data = b"GET /foobar HTTP/8.4\r\ncontent-length: +10\r\n"
try:
self.parser.parse_header(data)
except ParsingE... |
import unittest
class TestFixedStreamReceiver(unittest.TestCase):
def _makeOne(self, cl, buf): | import unittest
import pytest
class TestFixedStreamReceiver(unittest.TestCase):
def _makeOne(self, cl, buf): |
def test_received_multiple_chunks_split(self):
self.assertEqual(inst.error, None)
class DummyBuffer:
def __init__(self, data=None):
if data is None: | def test_received_multiple_chunks_split(self):
self.assertEqual(inst.error, None)
class TestChunkedReceiverParametrized:
def _makeOne(self, buf):
from waitress.receiver import ChunkedReceiver
return ChunkedReceiver(buf)
@pytest.mark.parametrize(
"invalid_extension", [b"\n", b... |
def word_tokenize(self, s):
return self._word_tokenizer_re().findall(s)
_period_context_fmt = r"""
\S* # some word material
%(SentEndChars)s # a potential sentence ending
(?=(?P<after_tok>
%(NonWord)s # either other punct... | def word_tokenize(self, s):
return self._word_tokenizer_re().findall(s)
_period_context_fmt = r"""
%(SentEndChars)s # a potential sentence ending
(?=(?P<after_tok>
%(NonWord)s # either other punctuation |
def debug_decisions(self, text):
See format_debug_decision() to help make this output readable.
"""
for match in self._lang_vars.period_context_re().finditer(text):
decision_text = match.group() + match.group("after_tok")
tokens = self._tokenize_words(decision_text)
... | def debug_decisions(self, text):
See format_debug_decision() to help make this output readable.
"""
for match, decision_text in self._match_potential_end_contexts(text):
tokens = self._tokenize_words(decision_text)
tokens = list(self._annotate_first_pass(tokens))
... |
def sentences_from_text(self, text, realign_boundaries=True):
"""
return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)]
def _slices_from_text(self, text):
last_break = 0
for match in self._lang_vars.period_context_re().finditer(text):
context = matc... | def sentences_from_text(self, text, realign_boundaries=True):
"""
return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)]
def _match_potential_end_contexts(self, text):
"""
Given a text, find the matches of potential sentence breaks,
alongside the context... |
class SitemapSpider(Spider):
def _parse_sitemap(self, response):
if response.url.endswith('/robots.txt'):
for url in sitemap_urls_from_robots(response.body):
yield Request(url, callback=self._parse_sitemap)
else:
body = self._get_sitemap_body(response) | class SitemapSpider(Spider):
def _parse_sitemap(self, response):
if response.url.endswith('/robots.txt'):
for url in sitemap_urls_from_robots(response.text):
yield Request(url, callback=self._parse_sitemap)
else:
body = self._get_sitemap_body(response) |
class SitemapSpiderTest(SpiderTest):
r = Response(url="http://www.example.com/sitemap.xml.gz", body=self.GZBODY)
self.assertSitemapBody(r, self.BODY)
class BaseSpiderDeprecationTest(unittest.TestCase):
| class SitemapSpiderTest(SpiderTest):
r = Response(url="http://www.example.com/sitemap.xml.gz", body=self.GZBODY)
self.assertSitemapBody(r, self.BODY)
def test_get_sitemap_urls_from_robotstxt(self):
robots = b"""# Sitemap files
Sitemap: http://example.com/sitemap.xml
Sitemap: http://example.... |
class OffsiteMiddleware(object):
if not allowed_domains:
return re.compile('') # allow all by default
url_pattern = re.compile("^https?://.*$")
for domain in allowed_domains:
if url_pattern.match(domain):
message = ("allowed_domains accepts only domains, ... | class OffsiteMiddleware(object):
if not allowed_domains:
return re.compile('') # allow all by default
url_pattern = re.compile("^https?://.*$")
domains = []
for domain in allowed_domains:
if domain is None:
continue
elif url_pattern.ma... |
class TestOffsiteMiddleware2(TestOffsiteMiddleware):
class TestOffsiteMiddleware3(TestOffsiteMiddleware2):
def _get_spider(self):
return Spider('foo')
class TestOffsiteMiddleware4(TestOffsiteMiddleware3):
def _get_spider(self):
bad_hostname = urlparse('http:////scrapytest.org').hostname
... | class TestOffsiteMiddleware2(TestOffsiteMiddleware):
class TestOffsiteMiddleware3(TestOffsiteMiddleware2):
def _get_spiderargs(self):
return dict(name='foo')
class TestOffsiteMiddleware4(TestOffsiteMiddleware3):
def _get_spiderargs(self):
bad_hostname = urlparse('http:////scrapytest.org').h... |
class ResponseTypes(object):
def from_content_disposition(self, content_disposition):
try:
filename = to_native_str(content_disposition).split(';')[1].split('=')[1]
filename = filename.strip('"\'')
return self.from_filename(filename)
except IndexError: | class ResponseTypes(object):
def from_content_disposition(self, content_disposition):
try:
filename = to_native_str(content_disposition,
encoding='latin-1', errors='replace').split(';')[1].split('=')[1]
filename = filename.strip('"\'')
return self.from_fi... |
import unittest
from scrapy.responsetypes import responsetypes
| # -*- coding: utf-8 -*-
import unittest
from scrapy.responsetypes import responsetypes
|
class ResponseTypesTest(unittest.TestCase):
def test_from_content_disposition(self):
mappings = [
('attachment; filename="data.xml"', XmlResponse),
('attachment; filename=data.xml', XmlResponse),
]
for source, cls in mappings:
retcls = responsetypes.from_... | class ResponseTypesTest(unittest.TestCase):
def test_from_content_disposition(self):
mappings = [
(b'attachment; filename="data.xml"', XmlResponse),
(b'attachment; filename=data.xml', XmlResponse),
(u'attachment;filename=data£.tar.gz'.encode('utf-8'), Response),
... |
def test_urlsplit_normalization(self):
urlparse.urlsplit(u'http://\u30d5\u309a\ufe1380')
for scheme in [u"http", u"https", u"ftp"]:
for c in denorm_chars:
url = u"{}://netloc{}false.netloc/path".format(scheme, c)
if test_support.verbose:
... | def test_urlsplit_normalization(self):
urlparse.urlsplit(u'http://\u30d5\u309a\ufe1380')
for scheme in [u"http", u"https", u"ftp"]:
for netloc in [u"netloc{}false.netloc", u"n{}user@netloc"]:
for c in denorm_chars:
url = u"{}://{}/path".format(scheme,... |
def _checknetloc(netloc):
# looking for characters like \u2100 that expand to 'a/c'
# IDNA uses NFKC equivalence, so normalize for this check
import unicodedata
n = netloc.rpartition('@')[2] # ignore anything to the left of '@'
n = n.replace(':', '') # ignore characters already included
n... | def _checknetloc(netloc):
# looking for characters like \u2100 that expand to 'a/c'
# IDNA uses NFKC equivalence, so normalize for this check
import unicodedata
n = netloc.replace(u'@', u'') # ignore characters already included
n = n.replace(u':', u'') # but not the surrounding text
n = n.r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.