buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
def test_array_ufunc_series_defer():
tm.assert_series_equal(r1, expected)
tm.assert_series_equal(r2, expected) | def test_array_ufunc_series_defer():
tm.assert_series_equal(r1, expected)
tm.assert_series_equal(r2, expected)
def test_groupby_agg():
# Ensure that the result of agg is inferred to be decimal dtype
# https://github.com/pandas-dev/pandas/issues/29141
data = make_data()[:5]
df = pd.DataFrame(... |
def target_version_option_callback(
@click.option(
"--config",
type=click.Path(
exists=False, file_okay=True, dir_okay=False, readable=True, allow_dash=False
),
is_eager=True,
callback=read_pyproject_toml, | def target_version_option_callback(
@click.option(
"--config",
type=click.Path(
exists=True, file_okay=True, dir_okay=False, readable=True, allow_dash=False
),
is_eager=True,
callback=read_pyproject_toml, |
class BlackTestCase(unittest.TestCase):
raise result.exception
self.assertEqual(result.exit_code, 0)
class BlackDTestCase(AioHTTPTestCase):
async def get_application(self) -> web.Application: | class BlackTestCase(unittest.TestCase):
raise result.exception
self.assertEqual(result.exit_code, 0)
def test_invalid_config_return_code(self) -> None:
tmp_file = Path(black.dump_to_file())
try:
tmp_config = Path(black.dump_to_file())
tmp_config.u... |
def run(self):
'cookiecutter>=1.6.0',
'diff-match-patch>=20181111',
'intervaltree>=3.0.2',
'ipython>=7.6.0,<8.0.0',
'jedi>=0.17.2,<0.19.0',
'jellyfish>=0.7',
'jsonschema>=3.2.0', | def run(self):
'cookiecutter>=1.6.0',
'diff-match-patch>=20181111',
'intervaltree>=3.0.2',
'ipython>=7.31.1,<8.0.0',
'jedi>=0.17.2,<0.19.0',
'jellyfish>=0.7',
'jsonschema>=3.2.0', |
# None for pynsist install for now
# (check way to add dist.info/egg.info from packages without wheels available)
INTERVALTREE_REQVER = None if is_pynsist() else '>=3.0.2'
IPYTHON_REQVER = ">=7.6.0;<8.0.0"
JEDI_REQVER = '>=0.17.2;<0.19.0'
JELLYFISH_REQVER = '>=0.7'
JSONSCHEMA_REQVER = '>=3.2.0' | # None for pynsist install for now
# (check way to add dist.info/egg.info from packages without wheels available)
INTERVALTREE_REQVER = None if is_pynsist() else '>=3.0.2'
IPYTHON_REQVER = ">=7.31.1;<8.0.0"
JEDI_REQVER = '>=0.17.2;<0.19.0'
JELLYFISH_REQVER = '>=0.7'
JSONSCHEMA_REQVER = '>=3.2.0' |
import warnings
import numpy as np
from pandas._libs import NaT, Timestamp, lib, tslib
import pandas._libs.internals as libinternals
from pandas._libs.tslibs import Timedelta, conversion
from pandas._libs.tslibs.timezones import tz_compare | import warnings
import numpy as np
from pandas._libs import NaT, Timestamp, lib, tslib, writers
import pandas._libs.internals as libinternals
from pandas._libs.tslibs import Timedelta, conversion
from pandas._libs.tslibs.timezones import tz_compare |
class Block(PandasObject):
mask = isna(values)
if not self.is_object and not quoting:
values = values.astype(str)
else:
values = np.array(values, dtype="object")
| class Block(PandasObject):
mask = isna(values)
if not self.is_object and not quoting:
itemsize = writers.word_len(na_rep)
values = values.astype("<U{size}".format(size=itemsize))
else:
values = np.array(values, dtype="object")
|
z
assert len(zp.filelist) == 1
archived_file = os.path.basename(zp.filelist[0].filename)
assert archived_file == expected_arcname | z
assert len(zp.filelist) == 1
archived_file = os.path.basename(zp.filelist[0].filename)
assert archived_file == expected_arcname
@pytest.mark.parametrize("df_new_type", ["Int64"])
def test_to_csv_na_rep_long_string(self, df_new_type):
# see gh-25099
df = pd.... |
class ActionBase(with_metaclass(ABCMeta, object)):
Create and return a temporary path on a remote box.
'''
become_unprivileged = self._is_become_unprivileged()
remote_tmp = self.get_shell_option('remote_tmp', default='~/.ansible/tmp')
# deal with tmpdir creation
basefil... | class ActionBase(with_metaclass(ABCMeta, object)):
Create and return a temporary path on a remote box.
'''
# Network connection plugins (network_cli, netconf, etc.) execute on the controller, rather than the remote host.
# As such, we want to avoid using remote_user for paths as remote... |
class ActionBase(with_metaclass(ABCMeta, object)):
elif u'No space left on device' in result['stderr']:
output = result['stderr']
else:
output = ('Authentication or permission failure. '
'In some cases, you may have been able to authentic... | class ActionBase(with_metaclass(ABCMeta, object)):
elif u'No space left on device' in result['stderr']:
output = result['stderr']
else:
output = ('Failed to create temporary directory.'
'In some cases, you may have been able to authentica... |
import random
import re
import time
import ansible.constants as C
from ansible.errors import AnsibleError
from ansible.module_utils.six import text_type
from ansible.module_utils.six.moves import shlex_quote | import random
import re
import time
from ansible.errors import AnsibleError
from ansible.module_utils.six import text_type
from ansible.module_utils.six.moves import shlex_quote |
class ShellBase(AnsiblePlugin):
except KeyError:
pass
def env_prefix(self, **kwargs):
return ' '.join(['%s=%s' % (k, shlex_quote(text_type(v))) for k, v in kwargs.items()])
| class ShellBase(AnsiblePlugin):
except KeyError:
pass
@staticmethod
def _generate_temp_dir_name():
return 'ansible-tmp-%s-%s-%s' % (time.time(), os.getpid(), random.randint(0, 2**48))
def env_prefix(self, **kwargs):
return ' '.join(['%s=%s' % (k, shlex_quote(text_type(v... |
class ShellBase(AnsiblePlugin):
def mkdtemp(self, basefile=None, system=False, mode=0o700, tmpdir=None):
if not basefile:
basefile = 'ansible-tmp-%s-%s' % (time.time(), random.randint(0, 2**48))
# When system is specified we have to create this in a directory where
# other user... | class ShellBase(AnsiblePlugin):
def mkdtemp(self, basefile=None, system=False, mode=0o700, tmpdir=None):
if not basefile:
basefile = self.__class__._generate_temp_dir_name()
# When system is specified we have to create this in a directory where
# other users can read and access... |
class ShellBase(AnsiblePlugin):
# passed in tmpdir if it is valid or the first one from the setting if not.
if system:
tmpdir = tmpdir.rstrip('/')
if tmpdir in self.get_option('system_tmpdirs'):
basetmpdir = tmpdir | class ShellBase(AnsiblePlugin):
# passed in tmpdir if it is valid or the first one from the setting if not.
if system:
if tmpdir:
tmpdir = tmpdir.rstrip('/')
if tmpdir in self.get_option('system_tmpdirs'):
basetmpdir = tmpdir |
class ShellBase(AnsiblePlugin):
basetmp = self.join_path(basetmpdir, basefile)
cmd = 'mkdir -p %s echo %s %s' % (self._SHELL_SUB_LEFT, basetmp, self._SHELL_SUB_RIGHT)
cmd += ' %s echo %s=%s echo %s %s' % (self._SHELL_AND, basefile, self._SHELL_SUB_LEFT, basetmp, self._SHELL_SUB_RIGHT)
... | class ShellBase(AnsiblePlugin):
basetmp = self.join_path(basetmpdir, basefile)
# use mkdir -p to ensure parents exist, but mkdir fullpath to ensure last one is created by us
cmd = 'mkdir -p %s echo %s %s' % (self._SHELL_SUB_LEFT, basetmpdir, self._SHELL_SUB_RIGHT)
cmd += '%s mkdir %s' ... |
class ShellModule(ShellBase):
def mkdtemp(self, basefile=None, system=False, mode=None, tmpdir=None):
# Windows does not have an equivalent for the system temp files, so
# the param is ignored
basefile = self._escape(self._unquote(basefile))
basetmpdir = tmpdir if tmpdir else self.ge... | class ShellModule(ShellBase):
def mkdtemp(self, basefile=None, system=False, mode=None, tmpdir=None):
# Windows does not have an equivalent for the system temp files, so
# the param is ignored
if not basefile:
basefile = self.__class__._generate_temp_dir_name()
basefile =... |
class DatetimeLikeArrayMixin(
def _validate_insert_value(self, value):
if isinstance(value, self._recognized_scalars):
value = self._scalar_type(value)
elif is_valid_nat_for_dtype(value, self.dtype):
# GH#18295
value = NaT
elif lib.is_scalar(value) and isn... | class DatetimeLikeArrayMixin(
def _validate_insert_value(self, value):
if isinstance(value, self._recognized_scalars):
value = self._scalar_type(value)
self._check_compatible_with(value, setitem=True)
# TODO: if we dont have compat, should we raise or astype(object)?
... |
class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index):
-------
new_index : Index
"""
item = self._data._validate_insert_value(item)
freq = None
if isinstance(item, self._data._scalar_type) or item is NaT:
self._data._check_compatible_with(item, seti... | class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index):
-------
new_index : Index
"""
if isinstance(item, str):
# TODO: Why are strings special?
# TODO: Should we attempt _scalar_from_string?
return self.astype(object).insert(loc, item)
... |
class TestInsert:
assert result.name == expected.name
assert result.tz == expected.tz
assert result.freq is None | class TestInsert:
assert result.name == expected.name
assert result.tz == expected.tz
assert result.freq is None
@pytest.mark.parametrize(
"item", [0, np.int64(0), np.float64(0), np.array(0), np.timedelta64(456)]
)
def test_insert_mismatched_types_rai... |
class TestTimedeltaIndexInsert:
with pytest.raises(TypeError, match="incompatible label"):
idx.insert(0, np.datetime64("NaT"))
def test_insert_dont_cast_strings(self):
# To match DatetimeIndex and PeriodIndex behavior, dont try to
# parse strings to Timedelta | class TestTimedeltaIndexInsert:
with pytest.raises(TypeError, match="incompatible label"):
idx.insert(0, np.datetime64("NaT"))
@pytest.mark.parametrize(
"item", [0, np.int64(0), np.float64(0), np.array(0), np.datetime64(456, "us")]
)
def test_insert_mismatched_types_raises(self,... |
class TestInsertIndexCoercion(CoercionBase):
with pytest.raises(TypeError, match=msg):
obj.insert(1, pd.Timestamp("2012-01-01", tz="Asia/Tokyo"))
msg = "cannot insert DatetimeIndex with incompatible label"
with pytest.raises(TypeError, match=msg):
obj.insert(1, 1... | class TestInsertIndexCoercion(CoercionBase):
with pytest.raises(TypeError, match=msg):
obj.insert(1, pd.Timestamp("2012-01-01", tz="Asia/Tokyo"))
msg = "cannot insert DatetimeArray with incompatible label"
with pytest.raises(TypeError, match=msg):
obj.insert(1, 1... |
class TestInsertIndexCoercion(CoercionBase):
)
# ToDo: must coerce to object
msg = "cannot insert TimedeltaIndex with incompatible label"
with pytest.raises(TypeError, match=msg):
obj.insert(1, pd.Timestamp("2012-01-01"))
# ToDo: must coerce to object
msg = ... | class TestInsertIndexCoercion(CoercionBase):
)
# ToDo: must coerce to object
msg = "cannot insert TimedeltaArray with incompatible label"
with pytest.raises(TypeError, match=msg):
obj.insert(1, pd.Timestamp("2012-01-01"))
# ToDo: must coerce to object
msg = ... |
class TestPartialSetting:
df = orig.copy()
# don't allow not string inserts
msg = "cannot insert DatetimeIndex with incompatible label"
with pytest.raises(TypeError, match=msg):
df.loc[100.0, :] = df.iloc[0] | class TestPartialSetting:
df = orig.copy()
# don't allow not string inserts
msg = "cannot insert DatetimeArray with incompatible label"
with pytest.raises(TypeError, match=msg):
df.loc[100.0, :] = df.iloc[0] |
class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray)
if is_datetime64_any_dtype(other) and is_timedelta64_dtype(self.dtype):
# ndarray[datetime64] cannot be subtracted from self, so
# we need to wrap in DatetimeArray/Index and flip the operation
if... | class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray)
if is_datetime64_any_dtype(other) and is_timedelta64_dtype(self.dtype):
# ndarray[datetime64] cannot be subtracted from self, so
# we need to wrap in DatetimeArray/Index and flip the operation
if... |
class TestTimedeltaArraylikeAddSubOps:
result = other + idx
tm.assert_equal(result, expected)
def test_td64arr_add_sub_timestamp(self, box_with_array):
# GH#11925
ts = Timestamp("2012-01-01")
# TODO: parametrize over types of datetime scalar?
tdi = timedelta_range("... | class TestTimedeltaArraylikeAddSubOps:
result = other + idx
tm.assert_equal(result, expected)
@pytest.mark.parametrize(
"ts",
[
Timestamp("2012-01-01"),
Timestamp("2012-01-01").to_pydatetime(),
Timestamp("2012-01-01").to_datetime64(),
],
... |
import logging
from six.moves.urllib.parse import urljoin
from w3lib.url import safe_url_string
| import logging
from six.moves.urllib.parse import urljoin, urlparse
from w3lib.url import safe_url_string
|
class RedirectMiddleware(BaseRedirectMiddleware):
if 'Location' not in response.headers or response.status not in allowed_status:
return response
location = safe_url_string(response.headers['location'])
redirected_url = urljoin(request.url, location)
| class RedirectMiddleware(BaseRedirectMiddleware):
if 'Location' not in response.headers or response.status not in allowed_status:
return response
location = safe_url_string(response.headers['Location'])
if response.headers['Location'].startswith(b'//'):
request_scheme = ... |
class RedirectMiddlewareTest(unittest.TestCase):
del rsp.headers['Location']
assert self.mw.process_response(req, rsp, self.spider) is rsp
def test_max_redirect_times(self):
self.mw.max_redirect_times = 1 | class RedirectMiddlewareTest(unittest.TestCase):
del rsp.headers['Location']
assert self.mw.process_response(req, rsp, self.spider) is rsp
def test_redirect_302_relative(self):
url = 'http://www.example.com/302'
url2 = '///i8n.example2.com/302'
url3 = 'http://i8n.example2.co... |
def generate_commands(vlan_id, to_set, to_remove):
if "vlan_id" in to_remove:
return ["no vlan {0}".format(vlan_id)]
for key, value in to_set.items():
if key == "vlan_id" or value is None:
continue
commands.append("{0} {1}".format(key, value))
for key in to_remove:
... | def generate_commands(vlan_id, to_set, to_remove):
if "vlan_id" in to_remove:
return ["no vlan {0}".format(vlan_id)]
for key in to_remove:
if key in to_set.keys():
continue
commands.append("no {0}".format(key))
for key, value in to_set.items():
if key == "vlan_i... |
class TestEosVlansModule(TestEosModule):
self.execute_show_command.return_value = []
set_module_args(dict(
config=[dict(
vlan_id=30,
name="thirty",
state="suspend"
)], state="replaced"
))
commands = ['vlan 30', 'name... | class TestEosVlansModule(TestEosModule):
self.execute_show_command.return_value = []
set_module_args(dict(
config=[dict(
vlan_id=10,
name="tenreplaced",
state="suspend"
)], state="replaced"
))
commands = ['vlan 10', ... |
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import cPickle
from PyQt5.Qt import (
Qt, QListWidget, QListWidgetItem, QItemSelectionModel, QAction, | __license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import json
from PyQt5.Qt import (
Qt, QListWidget, QListWidgetItem, QItemSelectionModel, QAction, |
def pos_key(b):
self.edited.emit(bm)
def bm_to_item(self, bm):
return bytearray(cPickle.dumps(bm, -1))
def item_to_bm(self, item):
return cPickle.loads(bytes(item.data(Qt.UserRole)))
def get_bookmarks(self):
return list(self) | def pos_key(b):
self.edited.emit(bm)
def bm_to_item(self, bm):
return bm.copy()
def item_to_bm(self, item):
return item.data(Qt.UserRole).copy()
def get_bookmarks(self):
return list(self) |
def get_bookmarks(self):
def export_bookmarks(self):
filename = choose_save_file(
self, 'export-viewer-bookmarks', _('Export bookmarks'),
filters=[(_('Saved bookmarks'), ['pickle'])], all_files=False, initial_filename='bookmarks.pickle')
if filename:
with open(fil... | def get_bookmarks(self):
def export_bookmarks(self):
filename = choose_save_file(
self, 'export-viewer-bookmarks', _('Export bookmarks'),
filters=[(_('Saved bookmarks'), ['calibre-bookmarks'])], all_files=False, initial_filename='bookmarks.calibre-bookmarks')
if filename:
... |
from calibre.srv.routes import endpoint, json
from calibre.srv.utils import get_library_data, get_use_roman
from calibre.utils.config import prefs, tweaks
from calibre.utils.icu import sort_key
from calibre.utils.localization import get_lang
from calibre.utils.search_query_parser import ParseException
| from calibre.srv.routes import endpoint, json
from calibre.srv.utils import get_library_data, get_use_roman
from calibre.utils.config import prefs, tweaks
from calibre.utils.icu import sort_key, numeric_sort_key
from calibre.utils.localization import get_lang
from calibre.utils.search_query_parser import ParseException... |
def field_names(ctx, rd, field):
Optional: ?library_id=<default library>
'''
db, library_id = get_library_data(ctx, rd)[:2]
return tuple(db.all_field_names(field)) | def field_names(ctx, rd, field):
Optional: ?library_id=<default library>
'''
db, library_id = get_library_data(ctx, rd)[:2]
return tuple(sorted(db.all_field_names(field), key=numeric_sort_key)) |
from scrapy.exceptions import DontCloseSpider
from scrapy.http import Response, Request
from scrapy.utils.misc import load_object
from scrapy.utils.reactor import CallLaterOnce
from scrapy.utils.log import logformatter_adapter
logger = logging.getLogger(__name__)
| from scrapy.exceptions import DontCloseSpider
from scrapy.http import Response, Request
from scrapy.utils.misc import load_object
from scrapy.utils.reactor import CallLaterOnce
from scrapy.utils.log import logformatter_adapter, failure_to_exc_info
logger = logging.getLogger(__name__)
|
class ExecutionEngine(object):
d = self._download(request, spider)
d.addBoth(self._handle_downloader_output, request, spider)
d.addErrback(lambda f: logger.info('Error while handling downloader output',
extra={'spider': spider, 'failure': f}))
d... | class ExecutionEngine(object):
d = self._download(request, spider)
d.addBoth(self._handle_downloader_output, request, spider)
d.addErrback(lambda f: logger.info('Error while handling downloader output',
exc_info=failure_to_exc_info(f),
... |
class ExecutionEngine(object):
# response is a Response or Failure
d = self.scraper.enqueue_scrape(response, request, spider)
d.addErrback(lambda f: logger.error('Error while enqueuing downloader output',
extra={'spider': spider, 'failure': f}))
... | class ExecutionEngine(object):
# response is a Response or Failure
d = self.scraper.enqueue_scrape(response, request, spider)
d.addErrback(lambda f: logger.error('Error while enqueuing downloader output',
exc_info=failure_to_exc_info(f),
... |
class ExecutionEngine(object):
def log_failure(msg):
def errback(failure):
logger.error(msg, extra={'spider': spider, 'failure': failure})
return errback
dfd.addBoth(lambda _: self.downloader.close()) | class ExecutionEngine(object):
def log_failure(msg):
def errback(failure):
logger.error(
msg,
exc_info=failure_to_exc_info(failure),
extra={'spider': spider}
)
return errback
dfd.addBoth... |
from twisted.internet import defer
from scrapy.utils.defer import defer_result, defer_succeed, parallel, iter_errback
from scrapy.utils.spider import iterate_spider_output
from scrapy.utils.misc import load_object
from scrapy.utils.log import logformatter_adapter
from scrapy.exceptions import CloseSpider, DropItem, Ign... | from twisted.internet import defer
from scrapy.utils.defer import defer_result, defer_succeed, parallel, iter_errback
from scrapy.utils.spider import iterate_spider_output
from scrapy.utils.misc import load_object
from scrapy.utils.log import logformatter_adapter, failure_to_exc_info
from scrapy.exceptions import Close... |
class Scraper(object):
dfd.addErrback(
lambda f: logger.error('Scraper bug processing %(request)s',
{'request': request},
extra={'spider': spider, 'failure': f}))
self._scrape_next(spider, slot)
return dfd
| class Scraper(object):
dfd.addErrback(
lambda f: logger.error('Scraper bug processing %(request)s',
{'request': request},
exc_info=failure_to_exc_info(f),
extra={'spider': spider}))
self.... |
class Scraper(object):
logger.error(
"Spider error processing %(request)s (referer: %(referer)s)",
{'request': request, 'referer': referer},
extra={'spider': spider, 'failure': _failure}
)
self.signals.send_catch_log(
signal=signals.spider_error, | class Scraper(object):
logger.error(
"Spider error processing %(request)s (referer: %(referer)s)",
{'request': request, 'referer': referer},
exc_info=failure_to_exc_info(_failure),
extra={'spider': spider}
)
self.signals.send_catch_log(
... |
class Scraper(object):
if download_failure.frames:
logger.error('Error downloading %(request)s',
{'request': request},
extra={'spider': spider, 'failure': download_failure})
else:
errmsg = download_failure.... | class Scraper(object):
if download_failure.frames:
logger.error('Error downloading %(request)s',
{'request': request},
exc_info=failure_to_exc_info(download_failure),
extra={'spider': spider})
... |
class Scraper(object):
spider=spider, exception=output.value)
else:
logger.error('Error processing %(item)s', {'item': item},
extra={'spider': spider, 'failure': output})
else:
logkws = self.logformatter.scraped(output, res... | class Scraper(object):
spider=spider, exception=output.value)
else:
logger.error('Error processing %(item)s', {'item': item},
exc_info=failure_to_exc_info(output),
extra={'spider': spider})
else:
... |
from six.moves.urllib import robotparser
from scrapy.exceptions import NotConfigured, IgnoreRequest
from scrapy.http import Request
from scrapy.utils.httpobj import urlparse_cached
logger = logging.getLogger(__name__)
| from six.moves.urllib import robotparser
from scrapy.exceptions import NotConfigured, IgnoreRequest
from scrapy.http import Request
from scrapy.utils.httpobj import urlparse_cached
from scrapy.utils.log import failure_to_exc_info
logger = logging.getLogger(__name__)
|
class RobotsTxtMiddleware(object):
if failure.type is not IgnoreRequest:
logger.error("Error downloading %(request)s: %(f_exception)s",
{'request': request, 'f_exception': failure.value},
extra={'spider': spider, 'failure': failure})
def _parse_... | class RobotsTxtMiddleware(object):
if failure.type is not IgnoreRequest:
logger.error("Error downloading %(request)s: %(f_exception)s",
{'request': request, 'f_exception': failure.value},
exc_info=failure_to_exc_info(failure),
... |
from scrapy.utils.ftp import ftp_makedirs_cwd
from scrapy.exceptions import NotConfigured
from scrapy.utils.misc import load_object
from scrapy.utils.python import get_func_args
logger = logging.getLogger(__name__)
| from scrapy.utils.ftp import ftp_makedirs_cwd
from scrapy.exceptions import NotConfigured
from scrapy.utils.misc import load_object
from scrapy.utils.python import get_func_args
from scrapy.utils.log import failure_to_exc_info
logger = logging.getLogger(__name__)
|
class FeedExporter(object):
d.addCallback(lambda _: logger.info(logfmt % "Stored", log_args,
extra={'spider': spider}))
d.addErrback(lambda f: logger.error(logfmt % "Error storing", log_args,
extra={'spider': spider,... | class FeedExporter(object):
d.addCallback(lambda _: logger.info(logfmt % "Stored", log_args,
extra={'spider': spider}))
d.addErrback(lambda f: logger.error(logfmt % "Error storing", log_args,
exc_info=failure_to_exc_... |
import warnings
from twisted.python.failure import Failure
from scrapy.exceptions import ScrapyDeprecationWarning
logger = logging.getLogger(__name__)
| import warnings
from twisted.python.failure import Failure
from scrapy.exceptions import ScrapyDeprecationWarning
from scrapy.utils.log import failure_to_exc_info
logger = logging.getLogger(__name__)
|
def err(_stuff=None, _why=None, **kw):
level = kw.pop('level', logging.ERROR)
failure = kw.pop('failure', _stuff) or Failure()
message = kw.pop('why', _why) or failure.value
logger.log(level, message, *[kw] if kw else [], extra={'failure': failure}) | def err(_stuff=None, _why=None, **kw):
level = kw.pop('level', logging.ERROR)
failure = kw.pop('failure', _stuff) or Failure()
message = kw.pop('why', _why) or failure.value
logger.log(level, message, *[kw] if kw else [], exc_info=failure_to_exc_info(failure)) |
from scrapy.pipelines.media import MediaPipeline
from scrapy.exceptions import NotConfigured, IgnoreRequest
from scrapy.http import Request
from scrapy.utils.misc import md5sum
logger = logging.getLogger(__name__)
| from scrapy.pipelines.media import MediaPipeline
from scrapy.exceptions import NotConfigured, IgnoreRequest
from scrapy.http import Request
from scrapy.utils.misc import md5sum
from scrapy.utils.log import failure_to_exc_info
logger = logging.getLogger(__name__)
|
class FilesPipeline(MediaPipeline):
dfd.addErrback(
lambda f:
logger.error(self.__class__.__name__ + '.store.stat_file',
extra={'spider': info.spider, 'failure': f})
)
return dfd
| class FilesPipeline(MediaPipeline):
dfd.addErrback(
lambda f:
logger.error(self.__class__.__name__ + '.store.stat_file',
exc_info=failure_to_exc_info(f),
extra={'spider': info.spider})
)
return dfd
|
from twisted.python.failure import Failure
from scrapy.utils.defer import mustbe_deferred, defer_result
from scrapy.utils.request import request_fingerprint
from scrapy.utils.misc import arg_to_iter
logger = logging.getLogger(__name__)
| from twisted.python.failure import Failure
from scrapy.utils.defer import mustbe_deferred, defer_result
from scrapy.utils.request import request_fingerprint
from scrapy.utils.misc import arg_to_iter
from scrapy.utils.log import failure_to_exc_info
logger = logging.getLogger(__name__)
|
class MediaPipeline(object):
dfd.addCallback(self._check_media_to_download, request, info)
dfd.addBoth(self._cache_result_and_execute_waiters, fp, info)
dfd.addErrback(lambda f: logger.error(
f.value, extra={'spider': info.spider, 'failure': f})
)
return dfd.addBoth(l... | class MediaPipeline(object):
dfd.addCallback(self._check_media_to_download, request, info)
dfd.addBoth(self._cache_result_and_execute_waiters, fp, info)
dfd.addErrback(lambda f: logger.error(
f.value, exc_info=failure_to_exc_info(f), extra={'spider': info.spider})
)
r... |
class MediaPipeline(object):
logger.error(
'%(class)s found errors processing %(item)s',
{'class': self.__class__.__name__, 'item': item},
extra={'spider': info.spider, 'failure': value}
)
return item | class MediaPipeline(object):
logger.error(
'%(class)s found errors processing %(item)s',
{'class': self.__class__.__name__, 'item': item},
exc_info=failure_to_exc_info(value),
extra={'spider': info.spider... |
# -*- coding: utf-8 -*-
import os
import sys
import logging
import warnings | # -*- coding: utf-8 -*-
import sys
import logging
import warnings |
from scrapy.exceptions import ScrapyDeprecationWarning
logger = logging.getLogger(__name__)
class FailureFormatter(logging.Filter):
"""Extract exc_info from Failure instances provided as contextual data
This filter mimics Twisted log.err formatting for its first `_stuff`
argument, which means that reprs ... | from scrapy.exceptions import ScrapyDeprecationWarning
logger = logging.getLogger(__name__)
def failure_to_exc_info(failure):
"""Extract exc_info from Failure instances"""
if isinstance(failure, Failure):
return (failure.type, failure.value, failure.tb)
class TopLevelFormatter(logging.Filter): |
class TopLevelFormatter(logging.Filter):
DEFAULT_LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'failure_formatter': {
'()': 'scrapy.utils.log.FailureFormatter',
},
},
'loggers': {
'scrapy': {
'level': 'DEBUG',
'f... | class TopLevelFormatter(logging.Filter):
DEFAULT_LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'loggers': {
'scrapy': {
'level': 'DEBUG',
},
'twisted': {
'level': 'ERROR', |
from twisted.python.failure import Failure
from scrapy.xlib.pydispatch.dispatcher import Any, Anonymous, liveReceivers, \
getAllReceivers, disconnect
from scrapy.xlib.pydispatch.robustapply import robustApply
logger = logging.getLogger(__name__)
| from twisted.python.failure import Failure
from scrapy.xlib.pydispatch.dispatcher import Any, Anonymous, liveReceivers, \
getAllReceivers, disconnect
from scrapy.xlib.pydispatch.robustapply import robustApply
from scrapy.utils.log import failure_to_exc_info
logger = logging.getLogger(__name__)
|
def send_catch_log_deferred(signal=Any, sender=Anonymous, *arguments, **named):
if dont_log is None or not isinstance(failure.value, dont_log):
logger.error("Error caught on signal handler: %(receiver)s",
{'receiver': recv},
extra={'spider': spider, ... | def send_catch_log_deferred(signal=Any, sender=Anonymous, *arguments, **named):
if dont_log is None or not isinstance(failure.value, dont_log):
logger.error("Error caught on signal handler: %(receiver)s",
{'receiver': recv},
exc_info=failure_to_exc_i... |
from scrapy.http import Request, Response
from scrapy.spiders import Spider
from scrapy.utils.request import request_fingerprint
from scrapy.pipelines.media import MediaPipeline
from scrapy.utils.signal import disconnect_all
from scrapy import signals
| from scrapy.http import Request, Response
from scrapy.spiders import Spider
from scrapy.utils.request import request_fingerprint
from scrapy.pipelines.media import MediaPipeline
from scrapy.utils.log import failure_to_exc_info
from scrapy.utils.signal import disconnect_all
from scrapy import signals
|
class BaseMediaPipelineTestCase(unittest.TestCase):
assert len(l.records) == 1
record = l.records[0]
assert record.levelname == 'ERROR'
assert record.failure is fail
# disable failure logging and check again
self.pipe.LOG_FAILED_RESULTS = False | class BaseMediaPipelineTestCase(unittest.TestCase):
assert len(l.records) == 1
record = l.records[0]
assert record.levelname == 'ERROR'
self.assertTupleEqual(record.exc_info, failure_to_exc_info(fail))
# disable failure logging and check again
self.pipe.LOG_FAILED_RESULT... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import sys
import logging
import unittest | # -*- coding: utf-8 -*-
from __future__ import print_function
import sys
import logging
import unittest |
import unittest
from testfixtures import LogCapture
from twisted.python.failure import Failure
from scrapy.utils.log import (FailureFormatter, TopLevelFormatter,
LogCounterHandler, StreamLogger)
from scrapy.utils.test import get_crawler
class FailureFormatterTest(unittest.TestCase):
... | import unittest
from testfixtures import LogCapture
from twisted.python.failure import Failure
from scrapy.utils.log import (failure_to_exc_info, TopLevelFormatter,
LogCounterHandler, StreamLogger)
from scrapy.utils.test import get_crawler
class FailureToExcInfoTest(unittest.TestCase):
... |
class FileBasedCache(BaseCache):
self._delete(fname)
def _createdir(self):
os.makedirs(self._dir, 0o700, exist_ok=True)
def _key_to_file(self, key, version=None):
""" | class FileBasedCache(BaseCache):
self._delete(fname)
def _createdir(self):
# Set the umask because os.makedirs() doesn't apply the "mode" argument
# to intermediate-level directories.
old_umask = os.umask(0o077)
try:
os.makedirs(self._dir, 0o700, exist_ok=Tru... |
import os
import pickle
import re
import shutil
import tempfile
import threading
import time
import unittest
from pathlib import Path
from unittest import mock
from django.conf import settings
from django.core import management, signals | import os
import pickle
import re
import shutil
import sys
import tempfile
import threading
import time
import unittest
from pathlib import Path
from unittest import mock, skipIf
from django.conf import settings
from django.core import management, signals |
class FileBasedCacheTests(BaseCacheTests, TestCase):
# Returns the default instead of erroring.
self.assertEqual(cache.get('foo', 'baz'), 'baz')
def test_get_does_not_ignore_non_filenotfound_exceptions(self):
with mock.patch('builtins.open', side_effect=OSError):
with self.asser... | class FileBasedCacheTests(BaseCacheTests, TestCase):
# Returns the default instead of erroring.
self.assertEqual(cache.get('foo', 'baz'), 'baz')
@skipIf(
sys.platform == 'win32',
'Windows only partially supports umasks and chmod.',
)
def test_cache_dir_permissions(self):
... |
def _make_concat_multiindex(indexes, keys, levels=None, names=None) -> MultiInde
for hlevel, level in zip(zipped, levels):
to_concat = []
for key, index in zip(hlevel, indexes):
try:
i = level.get_loc(key)
except KeyError as err:
... | def _make_concat_multiindex(indexes, keys, levels=None, names=None) -> MultiInde
for hlevel, level in zip(zipped, levels):
to_concat = []
for key, index in zip(hlevel, indexes):
mask = level == key
if not mask.any():
raise ValueError(f"... |
def test_concat_multiindex_datetime_object_index():
)
result = concat([s, s2], axis=1)
tm.assert_frame_equal(result, expected) | def test_concat_multiindex_datetime_object_index():
)
result = concat([s, s2], axis=1)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("keys", [["e", "f", "f"], ["f", "e", "f"]])
def test_duplicate_keys(keys):
# GH 33654
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
s1 = Se... |
def _readInlineImage(self, stream):
# left at beginning of ID
tmp = stream.read(3)
assert tmp[:2] == b_("ID")
data = b_("")
while True:
# Read the inline image, while checking for EI (End Image) operator.
tok = stream.read(1)
if tok == b_("E"):... | def _readInlineImage(self, stream):
# left at beginning of ID
tmp = stream.read(3)
assert tmp[:2] == b_("ID")
data = BytesIO()
# Read the inline image, while checking for EI (End Image) operator.
while True:
# Read 8 kB at a time and check if the chunk contain... |
def _readInlineImage(self, stream):
stream.seek(-1, 1)
break
else:
stream.seek(-1,1)
data += info
else:
stream.seek(-1, 1)
data += tok
e... | def _readInlineImage(self, stream):
stream.seek(-1, 1)
break
else:
stream.seek(-1, 1)
data.write(info)
else:
stream.seek(-1, 1)
data.write(tok)
... |
class LocalCache(collections.OrderedDict):
self.limit = limit
def __setitem__(self, key, value):
while len(self) >= self.limit:
self.popitem(last=False)
super(LocalCache, self).__setitem__(key, value)
| class LocalCache(collections.OrderedDict):
self.limit = limit
def __setitem__(self, key, value):
if self.limit:
while len(self) >= self.limit:
self.popitem(last=False)
super(LocalCache, self).__setitem__(key, value)
|
if six.PY2:
else:
from collections.abc import Mapping, MutableMapping
from scrapy.utils.datatypes import CaselessDict, SequenceExclude
__doctests__ = ['scrapy.utils.datatypes'] | if six.PY2:
else:
from collections.abc import Mapping, MutableMapping
from scrapy.utils.datatypes import CaselessDict, SequenceExclude, LocalCache
__doctests__ = ['scrapy.utils.datatypes'] |
class SequenceExcludeTest(unittest.TestCase):
for v in [-3, "test", 1.1]:
self.assertNotIn(v, d)
if __name__ == "__main__":
unittest.main()
| class SequenceExcludeTest(unittest.TestCase):
for v in [-3, "test", 1.1]:
self.assertNotIn(v, d)
class LocalCacheTest(unittest.TestCase):
def test_cache_with_limit(self):
cache = LocalCache(limit=2)
cache['a'] = 1
cache['b'] = 2
cache['c'] = 3
self.asse... |
class CollectionRequirement:
requirement = req
op = operator.eq
# In the case we are checking a new requirement on a base requirement (parent != None) we can't accept
# version as '*' (unknown version) unless the requirement is also '*'.
i... | class CollectionRequirement:
requirement = req
op = operator.eq
# In the case we are checking a new requirement on a base requirement (parent != None) we can't accept
# version as '*' (unknown version) unless the requirement is also '*'.
if parent and... |
class CollectionRequirement:
manifest = info['manifest_file']['collection_info']
namespace = manifest['namespace']
name = manifest['name']
version = manifest['version']
dependencies = manifest['dependencies']
else:
display.warning("Collecti... | class CollectionRequirement:
manifest = info['manifest_file']['collection_info']
namespace = manifest['namespace']
name = manifest['name']
version = to_text(manifest['version'], errors='surrogate_or_strict')
if not hasattr(LooseVersion(version), 'version'):
... |
def _get_collection_info(dep_map, existing_collections, collection, requirement,
existing = [c for c in existing_collections if to_text(c) == to_text(collection_info)]
if existing and not collection_info.force:
# Test that the installed collection fits the requirement
existing[0].add_requirement... | def _get_collection_info(dep_map, existing_collections, collection, requirement,
existing = [c for c in existing_collections if to_text(c) == to_text(collection_info)]
if existing and not collection_info.force:
# Test that the installed collection fits the requirement
existing[0].add_requirement... |
def test_build_requirement_from_path(collection_artifact):
assert actual.dependencies == {}
def test_build_requirement_from_path_with_manifest(collection_artifact):
manifest_path = os.path.join(collection_artifact[0], b'MANIFEST.json')
manifest_value = json.dumps({
'collection_info': {
... | def test_build_requirement_from_path(collection_artifact):
assert actual.dependencies == {}
@pytest.mark.parametrize('version', ['1.1.1', 1.1, 1])
def test_build_requirement_from_path_with_manifest(version, collection_artifact):
manifest_path = os.path.join(collection_artifact[0], b'MANIFEST.json')
manife... |
def test_build_requirement_from_path_with_manifest(collection_artifact):
assert actual.b_path == collection_artifact[0]
assert actual.api is None
assert actual.skip is True
assert actual.versions == set([u'1.1.1'])
assert actual.latest_version == u'1.1.1'
assert actual.dependencies == {'ansible_... | def test_build_requirement_from_path_with_manifest(collection_artifact):
assert actual.b_path == collection_artifact[0]
assert actual.api is None
assert actual.skip is True
assert actual.versions == set([to_text(version)])
assert actual.latest_version == to_text(version)
assert actual.dependenci... |
def test_build_requirement_from_path_invalid_manifest(collection_artifact):
collection.CollectionRequirement.from_path(collection_artifact[0], True)
def test_build_requirement_from_tar(collection_artifact):
actual = collection.CollectionRequirement.from_tar(collection_artifact[1], True, True)
| def test_build_requirement_from_path_invalid_manifest(collection_artifact):
collection.CollectionRequirement.from_path(collection_artifact[0], True)
def test_build_requirement_from_path_no_version(collection_artifact, monkeypatch):
manifest_path = os.path.join(collection_artifact[0], b'MANIFEST.json')
... |
def test_add_collection_requirements(versions, requirement, expected_filter, exp
assert req.latest_version == expected_latest
def test_add_collection_requirement_to_unknown_installed_version():
req = collection.CollectionRequirement('namespace', 'name', None, 'https://galaxy.com', ['*'], '*', False,
... | def test_add_collection_requirements(versions, requirement, expected_filter, exp
assert req.latest_version == expected_latest
def test_add_collection_requirement_to_unknown_installed_version(monkeypatch):
mock_display = MagicMock()
monkeypatch.setattr(Display, 'display', mock_display)
req = collectio... |
##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 render_full(self, evalex=False, secret=None,
evalex_trusted=True):
"""Render the Full HTML page with the traceback info."""
exc = escape(self.exception)
return PAGE_HTML % {
'evalex': evalex and 'true' or 'false',
'evalex_trusted': eval... | def render_full(self, evalex=False, secret=None,
evalex_trusted=True):
"""Render the Full HTML page with the traceback info."""
exc = escape(self.exception)
ptext = escape(self.plaintext)
return PAGE_HTML % {
'evalex': evalex and 'true' or 'false... |
def render_full(self, evalex=False, secret=None,
'exception': exc,
'exception_type': escape(self.exception_type),
'summary': self.render_summary(include_title=False),
'plaintext': self.plaintext,
'plaintext_cs': re.sub('-{2,}', '-'... | def render_full(self, evalex=False, secret=None,
'exception': exc,
'exception_type': escape(self.exception_type),
'summary': self.render_summary(include_title=False),
'plaintext': ptext,
'plaintext_cs': re.sub('-{2,}', '-', self.pl... |
import io
import pytest
from PIL import EpsImagePlugin, Image, features | import io
import pytest
from PIL import EpsImagePlugin, Image, features |
def test_emptyline():
assert image.mode == "RGB"
assert image.size == (460, 352)
assert image.format == "EPS" | def test_emptyline():
assert image.mode == "RGB"
assert image.size == (460, 352)
assert image.format == "EPS"
@pytest.mark.timeout(timeout=5)
@pytest.mark.parametrize(
"test_file",
[
("Tests/images/timeout-d675703545fee17acab56e5fec644c19979175de.eps")
],
)
def test_timeout(test_file):... |
class PSFile:
self.fp.seek(offset, whence)
def readline(self):
s = self.char or b""
self.char = None
c = self.fp.read(1)
while c not in b"\r\n":
s = s + c
c = self.fp.read(1)
self.char = self.fp.read(1) | class PSFile:
self.fp.seek(offset, whence)
def readline(self):
s = [self.char or b""]
self.char = None
c = self.fp.read(1)
while (c not in b"\r\n") and len(c):
s.append(c)
c = self.fp.read(1)
self.char = self.fp.read(1) |
class PSFile:
if self.char in b"\r\n":
self.char = None
return s.decode("latin-1")
def _accept(prefix): | class PSFile:
if self.char in b"\r\n":
self.char = None
return b"".join(s).decode("latin-1")
def _accept(prefix): |
class SeriesGroupBy(GroupBy):
periods=periods, fill_method=fill_method, limit=limit, freq=freq
)
)
filled = getattr(self, fill_method)(limit=limit)
fill_grp = filled.groupby(self.grouper.codes)
shifted = fill_grp.shift(periods=periods, freq=freq) | class SeriesGroupBy(GroupBy):
periods=periods, fill_method=fill_method, limit=limit, freq=freq
)
)
if fill_method is None: # GH30463
fill_method = "pad"
limit = 0
filled = getattr(self, fill_method)(limit=limit)
fill_grp = ... |
class GroupBy(_GroupBy):
axis=axis,
)
)
filled = getattr(self, fill_method)(limit=limit)
fill_grp = filled.groupby(self.grouper.codes)
shifted = fill_grp.shift(periods=periods, freq=freq) | class GroupBy(_GroupBy):
axis=axis,
)
)
if fill_method is None: # GH30463
fill_method = "pad"
limit = 0
filled = getattr(self, fill_method)(limit=limit)
fill_grp = filled.groupby(self.grouper.codes)
shifted = fill_g... |
def test_pad_stable_sorting(fill_method):
),
],
)
@pytest.mark.parametrize(
"periods,fill_method,limit",
[
(1, "ffill", None),
(1, "ffill", 1),
(1, "bfill", None),
(1, "bfill", 1),
(-1, "ffill", None),
(-1, "ffill", 1),
(-1, "bfill", None),
... | def test_pad_stable_sorting(fill_method):
),
],
)
@pytest.mark.parametrize("periods", [1, -1])
@pytest.mark.parametrize("fill_method", ["ffill", "bfill", None])
@pytest.mark.parametrize("limit", [None, 1])
def test_pct_change(test_series, freq, periods, fill_method, limit):
# GH 21200, 21621, 30463
... |
class AbstractBasicAuthHandler:
# (single quotes are a violation of the RFC, but appear in the wild)
rx = re.compile('(?:^|,)' # start of the string or ','
'[ \t]*' # optional whitespaces
'([^ \t]+)' # scheme like "Basic"
'[ \t]+' # mandatory w... | class AbstractBasicAuthHandler:
# (single quotes are a violation of the RFC, but appear in the wild)
rx = re.compile('(?:^|,)' # start of the string or ','
'[ \t]*' # optional whitespaces
'([^ \t,]+)' # scheme like "Basic"
'[ \t]+' # mandatory ... |
# Copyright (C) 1998-2005 by the Free Software Foundation, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License | # Copyright (C) 1998-2006 by the Free Software Foundation, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License |
def main():
# page don't work.
if true_filename.endswith('/index.html') and parts[-1] <> 'index.html':
action += SLASH
print Utils.maketext(
'private.html',
{'action' : action,
'realname': mlist.real_name,
'message' : message,
... | def main():
# page don't work.
if true_filename.endswith('/index.html') and parts[-1] <> 'index.html':
action += SLASH
# Escape web input parameter to avoid cross-site scripting.
print Utils.maketext(
'private.html',
{'action' : Utils.websafe(action),... |
# this is a package
__version__ = "4.6.2"
def get_include(): | # this is a package
__version__ = "4.6.3"
def get_include(): |
class TestUtil(unittest.TestCase):
self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
def test_strip_jsonp(self):
stripped... | class TestUtil(unittest.TestCase):
self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
self.assertEqual(parse_iso8601('2014-03-2... |
from __future__ import unicode_literals
import re
from .subtitles import SubtitlesInfoExtractor
from .common import ExtractorError
from ..utils import parse_iso8601 | from __future__ import unicode_literals
from .subtitles import SubtitlesInfoExtractor
from .common import ExtractorError
from ..utils import parse_iso8601 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.