buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class TestIndexReductions: assert result[0] == expected # invalid ops for op in ["skew", "kurt", "sem", "prod"]: msg = "reduction operation '{}' not allowed for this dtype" with pytest.raises(TypeError, match=msg.format(op)): getattr(td, op)() # ...
class TestIndexReductions: assert result[0] == expected # invalid ops for op in ["skew", "kurt", "sem", "prod", "var"]: msg = "reduction operation '{}' not allowed for this dtype" with pytest.raises(TypeError, match=msg.format(op)): getattr(td, op)() ...
class TestSeriesReductions: assert pd.isna(result) # timedelta64[ns] result = getattr(Series(dtype="m8[ns]"), method)() assert result is pd.NaT def test_nansum_buglet(self): ser = Series([1.0, np.nan], index=[0, 1])
class TestSeriesReductions: assert pd.isna(result) # timedelta64[ns] tdser = Series([], dtype="m8[ns]") if method == "var": with pytest.raises(TypeError, match="operation 'var' not allowed"): getattr(tdser, method)() else: result = getattr...
from matplotlib._pylab_helpers import Gcf from matplotlib.backend_managers import ToolManager from matplotlib.transforms import Affine2D from matplotlib.path import Path _log = logging.getLogger(__name__)
from matplotlib._pylab_helpers import Gcf from matplotlib.backend_managers import ToolManager from matplotlib.transforms import Affine2D from matplotlib.path import Path from matplotlib.cbook import _setattr_cm _log = logging.getLogger(__name__)
class KeyEvent(LocationEvent): self.key = key def _get_renderer(figure, print_method=None, *, draw_disabled=False): """ Get the renderer that would be used to save a `~.Figure`, and cache it on the figure. If *draw_disabled* is True, additionally replace drawing methods on *renderer* by n...
class KeyEvent(LocationEvent): self.key = key def _get_renderer(figure, print_method=None): """ Get the renderer that would be used to save a `~.Figure`, and cache it on the figure. If you need a renderer without any active draw methods use cbook._setattr_cm to temporary patch them out at...
def _get_renderer(figure, print_method=None, *, draw_disabled=False): except Done as exc: renderer, = figure._cachedRenderer, = exc.args if draw_disabled: for meth_name in dir(RendererBase): if (meth_name.startswith("draw_") or meth_name in ["open_group",...
def _get_renderer(figure, print_method=None, *, draw_disabled=False): except Done as exc: renderer, = figure._cachedRenderer, = exc.args return renderer
class FigureCanvasBase: renderer = _get_renderer( self.figure, functools.partial( print_method, orientation=orientation), draw_disabled=True) self.figure.draw(renderer) ...
class FigureCanvasBase: renderer = _get_renderer( self.figure, functools.partial( print_method, orientation=orientation) ) no_ops = { meth_name: lambda *args, *...
default: 'top' from .tight_layout import ( get_renderer, get_subplotspec_list, get_tight_layout_figure) subplotspec_list = get_subplotspec_list(self.axes) if None in subplotspec_list:
default: 'top' from .tight_layout import ( get_renderer, get_subplotspec_list, get_tight_layout_figure) from .cbook import _setattr_cm from .backend_bases import RendererBase subplotspec_list = get_subplotspec_list(self.axes) if None in subplotspec_list:
default: 'top' if renderer is None: renderer = get_renderer(self) kwargs = get_tight_layout_figure( self, self.axes, subplotspec_list, renderer, pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect) if kwargs: self.subplots_adjust(**kwargs)
default: 'top' if renderer is None: renderer = get_renderer(self) no_ops = { meth_name: lambda *args, **kwargs: None for meth_name in dir(RendererBase) if (meth_name.startswith("draw_") or meth_name in ["open_group", "close_group"]) ...
def test_tight_pcolorfast(): # Previously, the bbox would include the area of the image clipped out by # the axes, resulting in a very tall image given the y limits of (0, 0.1). assert width > height
def test_tight_pcolorfast(): # Previously, the bbox would include the area of the image clipped out by # the axes, resulting in a very tall image given the y limits of (0, 0.1). assert width > height def test_noop_tight_bbox(): from PIL import Image x_size, y_size = (10, 7) dpi = 100 # mak...
def get_renderer(fig): return canvas.get_renderer() else: from . import backend_bases return backend_bases._get_renderer(fig, draw_disabled=True) def get_subplotspec_list(axes_list, grid_spec=None):
def get_renderer(fig): return canvas.get_renderer() else: from . import backend_bases return backend_bases._get_renderer(fig) def get_subplotspec_list(axes_list, grid_spec=None):
def _connect(self): def _create_database(self, last_upgrade_to_run): """ Make sure that the database is created and sets the file permissions. This should be done before storing any sensitive data in it. """ # Create the tables in the database conn = self._connect() ...
def _connect(self): def _create_database(self, last_upgrade_to_run): """ Make sure that the database is created and has appropriate file permissions. This should be done before storing any sensitive data in it. """ # Prepare a file fd = os.open( self.file...
def _create_database(self, last_upgrade_to_run): finally: conn.close() # Set the file permissions os.chmod(self.filename, stat.S_IRUSR | stat.S_IWUSR) def _create_tables(self, conn, last_upgrade_to_run): conn.execute( """
def _create_database(self, last_upgrade_to_run): finally: conn.close() def _create_tables(self, conn, last_upgrade_to_run): conn.execute( """
import os import platform import shutil import tempfile import pytest
import os import platform import shutil import stat import tempfile import pytest
def setUp(self, request): os.unlink(self.db_path) except OSError: pass self.home = tempfile.mkdtemp() yield for cleanup_method in [lambda: os.unlink(self.db_path), lambda: shutil.rmtree(self.home)]: try: cleanup_method exce...
def setUp(self, request): os.unlink(self.db_path) except OSError: pass self.test_home = tempfile.mkdtemp() yield for cleanup_method in [ lambda: os.unlink(self.db_path), lambda: shutil.rmtree(self.test_home) ]: try: ...
def _make_sqlite_account_info(self, env=None, last_upgrade_to_run=None): :param dict env: Override Environment variables. """ # Override HOME to ensure hermetic tests with mock.patch('os.environ', env or {'HOME': self.home}): return SqliteAccountInfo( file_nam...
def _make_sqlite_account_info(self, env=None, last_upgrade_to_run=None): :param dict env: Override Environment variables. """ # Override HOME to ensure hermetic tests with mock.patch('os.environ', env or {'HOME': self.test_home}): return SqliteAccountInfo( fil...
def _make_sqlite_account_info(self, env=None, last_upgrade_to_run=None): def test_uses_default(self): account_info = self._make_sqlite_account_info( env={ 'HOME': self.home, 'USERPROFILE': self.home, } ) actual_path = os.path.abspath(ac...
def _make_sqlite_account_info(self, env=None, last_upgrade_to_run=None): def test_uses_default(self): account_info = self._make_sqlite_account_info( env={ 'HOME': self.test_home, 'USERPROFILE': self.test_home, } ) actual_path = os.path....
def test_uses_xdg_config_home(self, apiver): def test_uses_existing_file_and_ignores_xdg(self): with WindowsSafeTempDir() as d: default_db_file_location = os.path.join(self.home, '.b2_account_info') open(default_db_file_location, 'a').close() account_info = self._make_sq...
def test_uses_xdg_config_home(self, apiver): def test_uses_existing_file_and_ignores_xdg(self): with WindowsSafeTempDir() as d: default_db_file_location = os.path.join(self.test_home, '.b2_account_info') open(default_db_file_location, 'a').close() account_info = self._ma...
def test_account_info_env_var_overrides_xdg_config_home(self): with WindowsSafeTempDir() as d: account_info = self._make_sqlite_account_info( env={ 'HOME': self.home, 'USERPROFILE': self.home, XDG_CONFIG_HOME_ENV_VAR: d, ...
def test_account_info_env_var_overrides_xdg_config_home(self): with WindowsSafeTempDir() as d: account_info = self._make_sqlite_account_info( env={ 'HOME': self.test_home, 'USERPROFILE': self.test_home, XDG_CONFIG_HOME_ENV_V...
class TestUtil(unittest.TestCase): inp = '''{"foo":101}''' self.assertEqual(js_to_json(inp), '''{"foo":101}''') 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\"4"})
class TestUtil(unittest.TestCase): inp = '''{"foo":101}''' self.assertEqual(js_to_json(inp), '''{"foo":101}''') 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 js_to_json(code): }.get(m.group(0), m.group(0)), v[1:-1]) INTEGER_TABLE = ( (r'^0[xX][0-9a-fA-F]+', 16), (r'^0+[0-7]+', 8), ) for regex, base in INTEGER_TABLE: im = re.match(regex, v) if im: i = int(im.group(0), ba...
def js_to_json(code): }.get(m.group(0), m.group(0)), v[1:-1]) INTEGER_TABLE = ( (r'^(0[xX][0-9a-fA-F]+)\s*:?$', 16), (r'^(0+[0-7]+)\s*:?$', 8), ) for regex, base in INTEGER_TABLE: im = re.match(regex, v) if im: i = int...
def test_getproxies_environment_keep_no_proxies(self): self.assertTrue(urllib.request.proxy_bypass_environment('anotherdomain.com:8888')) self.assertTrue(urllib.request.proxy_bypass_environment('newdomain.com:1234')) def test_proxy_bypass_environment_host_match(self): bypass = urllib.reques...
def test_getproxies_environment_keep_no_proxies(self): self.assertTrue(urllib.request.proxy_bypass_environment('anotherdomain.com:8888')) self.assertTrue(urllib.request.proxy_bypass_environment('newdomain.com:1234')) def test_proxy_cgi_ignore(self): try: self.env.set('HTTP_PROXY...
def getproxies_environment(): name = name.lower() if value and name[-6:] == '_proxy': proxies[name[:-6]] = value for name, value in os.environ.items(): if name[-6:] == '_proxy': name = name.lower()
def getproxies_environment(): name = name.lower() if value and name[-6:] == '_proxy': proxies[name[:-6]] = value # CVE-2016-1000110 - If we are running as CGI script, forget HTTP_PROXY # (non-all-lowercase) as it may be set from the web server by a "Proxy:" # header from the clie...
class FileSystemStorage(Storage): directory = os.path.dirname(full_path) try: if self.directory_permissions_mode is not None: # os.makedirs applies the global umask, so we reset it, # for consistency with file_permissions_mode behavior. old_uma...
class FileSystemStorage(Storage): directory = os.path.dirname(full_path) try: if self.directory_permissions_mode is not None: # Set the umask because os.makedirs() doesn't apply the "mode" # argument to intermediate-level directories. old_umask...
import time import unittest from datetime import datetime, timedelta from io import StringIO from urllib.request import urlopen from django.core.cache import cache
import time import unittest from datetime import datetime, timedelta from io import StringIO from pathlib import Path from urllib.request import urlopen from django.core.cache import cache
class FileStoragePermissions(unittest.TestCase): @override_settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765) def test_file_upload_directory_permissions(self): self.storage = FileSystemStorage(self.storage_dir) name = self.storage.save("the_directory/the_file", ContentFile("data")) dir_mo...
class FileStoragePermissions(unittest.TestCase): @override_settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765) def test_file_upload_directory_permissions(self): self.storage = FileSystemStorage(self.storage_dir) name = self.storage.save('the_directory/subdir/the_file', ContentFile('data')) ...
import sys import tempfile import unittest from io import StringIO from unittest import mock from django.conf import settings
import sys import tempfile import unittest from io import StringIO from pathlib import Path from unittest import mock from django.conf import settings
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_permissions(self): call_command('collectstatic', **self.command_params) test_file = os.path.join(settings.STATIC_ROOT, "test.txt") test_dir = os.path.join(settings.STATIC_ROOT, "subdir") file_mod...
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_permissions(self): call_command('collectstatic', **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / 'test.txt' file_mode = test_file.stat().st_mode & 0o777 ...
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_default_permissions(self): call_command('collectstatic', **self.command_params) test_file = os.path.join(settings.STATIC_ROOT, "test.txt") test_dir = os.path.join(settings.STATIC_ROOT, "subdir") ...
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_default_permissions(self): call_command('collectstatic', **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / 'test.txt' file_mode = test_file.stat().st_mode ...
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_subclass_of_static_storage(self): call_command('collectstatic', **self.command_params) test_file = os.path.join(settings.STATIC_ROOT, "test.txt") test_dir = os.path.join(settings.STATIC_ROOT, "subdir") ...
class TestStaticFilePermissions(CollectionTestCase): ) def test_collect_static_files_subclass_of_static_storage(self): call_command('collectstatic', **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / 'test.txt' file_mode = test_file.stat().s...
""" Constants specific to the SQL storage portion of the ORM. """ # Size of each "chunk" for get_iterator calls. # Larger values are slightly faster at the expense of more storage space.
""" Constants specific to the SQL storage portion of the ORM. """ from django.utils.regex_helper import _lazy_re_compile # Size of each "chunk" for get_iterator calls. # Larger values are slightly faster at the expense of more storage space.
ORDER_DIR = { 'ASC': ('ASC', 'DESC'), 'DESC': ('DESC', 'ASC'), } # SQL join types. INNER = 'INNER JOIN'
ORDER_DIR = { 'ASC': ('ASC', 'DESC'), 'DESC': ('DESC', 'ASC'), } ORDER_PATTERN = _lazy_re_compile(r'[-+]?[.\w]+$') # SQL join types. INNER = 'INNER JOIN'
from django.db.models.lookups import Lookup from django.db.models.query_utils import ( Q, check_rel_lookup_compatibility, refs_expression, ) from django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE from django.db.models.sql.datastructures import ( BaseTable, Empty, Join, MultiJoin, )
from django.db.models.lookups import Lookup from django.db.models.query_utils import ( Q, check_rel_lookup_compatibility, refs_expression, ) from django.db.models.sql.constants import ( INNER, LOUTER, ORDER_DIR, ORDER_PATTERN, SINGLE, ) from django.db.models.sql.datastructures import ( BaseTable, Empty, Joi...
class Query(BaseExpression): errors = [] for item in ordering: if isinstance(item, str): if '.' in item: warnings.warn( 'Passing column raw column aliases to order_by() is ' 'deprecated. Wrap %r in a RawSQL e...
class Query(BaseExpression): errors = [] for item in ordering: if isinstance(item, str): if '.' in item and ORDER_PATTERN.match(item): warnings.warn( 'Passing column raw column aliases to order_by() is ' 'dep...
class QuerySetExceptionTests(SimpleTestCase): with self.assertRaisesMessage(FieldError, msg): Article.objects.order_by('*') def test_invalid_queryset_model(self): msg = 'Cannot use QuerySet for "Article": Use a QuerySet for "ExtraInfo".' with self.assertRaisesMessage(ValueError,...
class QuerySetExceptionTests(SimpleTestCase): with self.assertRaisesMessage(FieldError, msg): Article.objects.order_by('*') def test_order_by_escape_prevention(self): msg = ( "Cannot resolve keyword 'queries.name);' into field. Choices are: " "created, id, name" ...
def upload_scan(self, filename): if filename.endswith('.json') or filename.endswith('.jsonld'): headers['Content-Type'] = 'application/ld+json' with open(filename,"r") as f: response = requests.post(url, headers=headers, data=f, verify=False) elif filename.endswit...
def upload_scan(self, filename): if filename.endswith('.json') or filename.endswith('.jsonld'): headers['Content-Type'] = 'application/ld+json' with open(filename,"r") as f: response = requests.post(url, headers=headers, data=f, verify=not self.config['insecure']) ...
def download_project_scans(self, project_name,version_name, output_folder=None): if not os.path.exists(project_name): os.mkdir(project_name) pathname = os.path.join(project_name, filename) responce = requests.get(url, headers=self.get_heade...
def download_project_scans(self, project_name,version_name, output_folder=None): if not os.path.exists(project_name): os.mkdir(project_name) pathname = os.path.join(project_name, filename) responce = requests.get(url, headers=self.get_heade...
VERSION = (0, 0, 52) __version__ = '.'.join(map(str, VERSION))
VERSION = (0, 0, 53) __version__ = '.'.join(map(str, VERSION))
class S3CopyToTable(rdbms.CopyToTable): if '.' in self.table: query = ("select 1 as table_exists " "from information_schema.tables " "where table_schema = %s and table_name = %s limit 1") else: query = ("select 1 as table_exists " ...
class S3CopyToTable(rdbms.CopyToTable): if '.' in self.table: query = ("select 1 as table_exists " "from information_schema.tables " "where table_schema = lower(%s) and table_name = lower(%s) limit 1") else: query = ("select 1 as table_ex...
class TestS3CopyToTable(unittest.TestCase): # Check the SQL query in `S3CopyToTable.does_table_exist`. mock_cursor.execute.assert_called_with("select 1 as table_exists " "from pg_table_def " "where tablename = ...
class TestS3CopyToTable(unittest.TestCase): # Check the SQL query in `S3CopyToTable.does_table_exist`. mock_cursor.execute.assert_called_with("select 1 as table_exists " "from pg_table_def " "where tablename = ...
class TestS3CopyToTable(unittest.TestCase): mock_cursor.execute.assert_any_call( "select 1 as table_exists " "from pg_table_def " "where tablename = %s limit 1", (task.table,), )
class TestS3CopyToTable(unittest.TestCase): mock_cursor.execute.assert_any_call( "select 1 as table_exists " "from pg_table_def " "where tablename = lower(%s) limit 1", (task.table,), )
class TestS3CopyToSchemaTable(unittest.TestCase): mock_cursor.execute.assert_called_with( "select 1 as table_exists " "from information_schema.tables " "where table_schema = %s and " "table_name = %s limit 1", tuple(task.table.split('.')), )
class TestS3CopyToSchemaTable(unittest.TestCase): mock_cursor.execute.assert_called_with( "select 1 as table_exists " "from information_schema.tables " "where table_schema = lower(%s) and " "table_name = lower(%s) limit 1", tuple(task.table.split('.'))...
class core(task.Config): class _WorkerSchedulerFactory(object): def create_local_scheduler(self): return scheduler.CentralPlannerScheduler(prune_on_get_work=True) def create_remote_scheduler(self, url): return rpc.RemoteScheduler(url)
class core(task.Config): class _WorkerSchedulerFactory(object): def create_local_scheduler(self): return scheduler.CentralPlannerScheduler(prune_on_get_work=True, record_task_history=False) def create_remote_scheduler(self, url): return rpc.RemoteScheduler(url)
class SchedulerTest(unittest.TestCase): cps = luigi.scheduler.CentralPlannerScheduler() self.assertEqual({'a': 100, 'b': 200}, cps._resources) def test_load_recovers_tasks_index(self): cps = luigi.scheduler.CentralPlannerScheduler() cps.add_task(worker='A', task_id='1')
class SchedulerTest(unittest.TestCase): cps = luigi.scheduler.CentralPlannerScheduler() self.assertEqual({'a': 100, 'b': 200}, cps._resources) @with_config({'scheduler': {'record_task_history': 'True'}, 'task_history': {'db_connection': 'sqlite:////none/existing/path/hist.db'}}) ...
class AsyncClientMixin(object): low["__user__"] = user low["__tag__"] = tag return self.low(fun, low, full_return=False) def cmd_async(self, low): """
class AsyncClientMixin(object): low["__user__"] = user low["__tag__"] = tag try: return self.cmd_sync(low) except salt.exceptions.EauthAuthenticationError as exc: log.error(exc) def cmd_async(self, low): """
class ClearFuncs(TransportMethods): """ Send a master control function back to the wheel system """ # All wheel ops pass through eauth auth_type, err_name, key, sensitive_load_keys = self._prep_auth_info(clear_load)
class ClearFuncs(TransportMethods): """ Send a master control function back to the wheel system """ jid = clear_load.get("__jid__", salt.utils.jid.gen_jid(self.opts)) # All wheel ops pass through eauth auth_type, err_name, key, sensitive_load_keys = self._prep_auth_info(c...
class ClearFuncs(TransportMethods): if error: # Authentication error occurred: do not continue. return {"error": error} # Authorize
class ClearFuncs(TransportMethods): if error: # Authentication error occurred: do not continue. data = {"error": error, "jid": jid} self.event.fire_event(data, tagify([jid, "new"], "wheel")) return {"error": error} # Authorize
class ClearFuncs(TransportMethods): clear_load.get("kwarg", {}), ) if not wheel_check: return { "error": { "name": err_name, "message": 'Authentication failure of type "{0}" occurred for ' ...
class ClearFuncs(TransportMethods): clear_load.get("kwarg", {}), ) if not wheel_check: err_data = { "name": err_name, "message": 'Authentication failure of type "{0}" occurred for ' "user {1}.".format(aut...
class ClearFuncs(TransportMethods): # Authorized. Do the job! try: jid = salt.utils.jid.gen_jid(self.opts) fun = clear_load.pop("fun") tag = tagify(jid, prefix="wheel") data = {
class ClearFuncs(TransportMethods): # Authorized. Do the job! try: fun = clear_load.pop("fun") tag = tagify(jid, prefix="wheel") data = {
class WheelClient( }) {'jid': '20131219224744416681', 'tag': 'salt/wheel/20131219224744416681'} """ fun = low.pop("fun") return self.asynchronous(fun, low) def cmd(
class WheelClient( }) {'jid': '20131219224744416681', 'tag': 'salt/wheel/20131219224744416681'} """ fun = low.get("fun") return self.asynchronous(fun, low) def cmd(
class NetapiClientTest(TestCase): def test_wheel_async(self): # Give this test a little breathing room time.sleep(3) low = {"client": "wheel_async", "fun": "key.list_all"} low.update(self.eauth_creds) ret = self.netapi.run(low) self.assertIn("jid", ret) self....
class NetapiClientTest(TestCase): def test_wheel_async(self): # Give this test a little breathing room time.sleep(3) timeout = 60 opts = salt.config.master_config( os.path.join(RUNTIME_VARS.TMP_CONF_DIR, "master") ) with salt.utils.event.get_event("master"...
class SplunkHTTPCollectorSource(object): else: ansible_role = None data = {} data['uuid'] = result._task._uuid data['session'] = self.session
class SplunkHTTPCollectorSource(object): else: ansible_role = None if 'args' in result._task_fields: del result._task_fields['args'] data = {} data['uuid'] = result._task._uuid data['session'] = self.session
class SumologicHTTPCollectorSource(object): else: ansible_role = None data = {} data['uuid'] = result._task._uuid data['session'] = self.session
class SumologicHTTPCollectorSource(object): else: ansible_role = None if 'args' in result._task_fields: del result._task_fields['args'] data = {} data['uuid'] = result._task._uuid data['session'] = self.session
def _create_instance(self, context, instance_type, security_group, block_device_mapping) instances.append(instance) instance_uuids.append(instance['uuid']) # In the case of any exceptions, attempt DB cleanup and rollback the # quota reservations.
def _create_instance(self, context, instance_type, security_group, block_device_mapping) instances.append(instance) instance_uuids.append(instance['uuid']) self._validate_bdm(context, instance) # send a state update notification for...
def _update_block_device_mapping(self, elevated_context, self.db.block_device_mapping_update_or_create(elevated_context, values) def _populate_instance_for_bdm(self, context, instance, instance_type, image, block_device_mapping): ...
def _update_block_device_mapping(self, elevated_context, self.db.block_device_mapping_update_or_create(elevated_context, values) def _validate_bdm(self, context, instance): for bdm in self.db.block_device_mapping_get_all_by_instance( ...
def create_db_entry_for_new_instance(self, context, instance_type, image, self._populate_instance_for_bdm(context, instance, instance_type, image, block_device_mapping) # send a state update notification for the initial create to # show it going from non-existent to BUILDING ...
def create_db_entry_for_new_instance(self, context, instance_type, image, self._populate_instance_for_bdm(context, instance, instance_type, image, block_device_mapping) return instance def _check_create_policies(self, context, availability_zone,
class InvalidSnapshot(Invalid): message = _("Invalid snapshot") + ": %(reason)s" class VolumeUnattached(Invalid): message = _("Volume %(volume_id)s is not attached to anything")
class InvalidSnapshot(Invalid): message = _("Invalid snapshot") + ": %(reason)s" class InvalidBDM(Invalid): message = _("Block Device Mapping is Invalid.") class InvalidBDMSnapshot(InvalidBDM): message = _("Block Device Mapping is Invalid: " "failed to get snapshot %(id)s.") class Inva...
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...
class S3CopyToTable(rdbms.CopyToTable): if not (self.table): raise Exception("table need to be specified") path = self.s3_load_path() connection = self.output().connect() if not self.does_table_exist(connection): # try creating table
class S3CopyToTable(rdbms.CopyToTable): if not (self.table): raise Exception("table need to be specified") path = self.s3_load_path connection = self.output().connect() if not self.does_table_exist(connection): # try creating table
class TestFish(object): mock.return_value.stdout.read.side_effect = [( b'cd\nfish_config\nfuck\nfunced\nfuncsave\ngrep\nhistory\nll\nls\n' b'man\nmath\npopd\npushd\nruby'), b'alias fish_key_reader /usr/bin/fish_key_reader\nalias g git'] return mock @pytest.mark.p...
class TestFish(object): mock.return_value.stdout.read.side_effect = [( b'cd\nfish_config\nfuck\nfunced\nfuncsave\ngrep\nhistory\nll\nls\n' b'man\nmath\npopd\npushd\nruby'), (b'alias fish_key_reader /usr/bin/fish_key_reader\nalias g git\n' b'alias alias_with_equal...
class TestFish(object): 'pushd': 'pushd', 'ruby': 'ruby', 'g': 'git', 'fish_key_reader': '/usr/bin/fish_key_reader'} def test_app_alias(self, shell): a...
class TestFish(object): 'pushd': 'pushd', 'ruby': 'ruby', 'g': 'git', 'fish_key_reader': '/usr/bin/fish_key_reader', 'alias_w...
def _get_functions(overridden): def _get_aliases(overridden): aliases = {} proc = Popen(['fish', '-ic', 'alias'], stdout=PIPE, stderr=DEVNULL) alias_out = proc.stdout.read().decode('utf-8').strip().split('\n') for alias in alias_out: name, value = alias.replace('alias ', '', 1).split(' ', 1) ...
def _get_functions(overridden): def _get_aliases(overridden): aliases = {} proc = Popen(['fish', '-ic', 'alias'], stdout=PIPE, stderr=DEVNULL) alias_out = proc.stdout.read().decode('utf-8').strip() if not alias_out: return aliases for alias in alias_out.split('\n'): for separator in ...
import sys import types import importlib from xml.etree import ElementTree # we do not use this ourselves, but mock methods often want to use this
import sys import types import importlib import imp from xml.etree import ElementTree # we do not use this ourselves, but mock methods often want to use this
def load_module(name): if os.path.exists(name) and os.path.splitext(name)[1] == '.py': sys.path.insert(0, os.path.dirname(os.path.abspath(name))) try: m = os.path.splitext(os.path.basename(name))[0] module = importlib.import_module(m) finally: sys.path.po...
def load_module(name): if os.path.exists(name) and os.path.splitext(name)[1] == '.py': mod = imp.new_module(os.path.splitext(os.path.basename(name))[0]) with open(name) as f: exec(f.read(), mod.__dict__, mod.__dict__) return mod return importlib.import_module('dbusmock.temp...
def load(mock, parameters): self.addCleanup(p_mock.terminate) self.addCleanup(p_mock.stdout.close) self.assertEqual(dbus_ultimate.Answer(), 42) # should appear in introspection
def load(mock, parameters): self.addCleanup(p_mock.terminate) self.addCleanup(p_mock.stdout.close) # ensure that we don't use/write any .pyc files, they are dangerous # in a world-writable directory like /tmp self.assertFalse(os.path.exists(my_template.name +...
# this is a package __version__ = "4.6.2" def get_include():
# this is a package __version__ = "4.6.3" def get_include():
class DataFrame(NDFrame): if is_transposed: data = data.T result = data._data.quantile( qs=q, axis=1, interpolation=interpolation, transposed=is_transposed )
class DataFrame(NDFrame): if is_transposed: data = data.T if len(data.columns) == 0: # GH#23925 _get_numeric_data may have dropped all columns cols = Index([], name=self.columns.name) if is_list_like(q): return self._constructor([], index=...
class TestDataFrameQuantile: ) tm.assert_frame_equal(res, exp) def test_quantile_empty(self): # floats df = DataFrame(columns=["a", "b"], dtype="float64")
class TestDataFrameQuantile: ) tm.assert_frame_equal(res, exp) def test_quantile_empty_no_rows(self): # floats df = DataFrame(columns=["a", "b"], dtype="float64")
class TestDataFrameQuantile: # FIXME (gives NaNs instead of NaT in 0.18.1 or 0.19.0) # res = df.quantile(0.5, numeric_only=False)
class TestDataFrameQuantile: # FIXME (gives NaNs instead of NaT in 0.18.1 or 0.19.0) # res = df.quantile(0.5, numeric_only=False) def test_quantile_empty_no_columns(self): # GH#23925 _get_numeric_data may drop all columns df = pd.DataFrame(pd.date_range("1/1/18", periods=5)) ...
class _AtIndexer(_ScalarAccessIndexer): if is_setter: return list(key) for ax, i in zip(self.obj.axes, key): if ax.is_integer(): if not is_integer(i): raise ValueError( "At based indexing on an integer index " ...
class _AtIndexer(_ScalarAccessIndexer): if is_setter: return list(key) lkey = list(key) for n, (ax, i) in enumerate(zip(self.obj.axes, key)): lkey[n] = ax._convert_scalar_indexer(i, kind="loc") return tuple(lkey) @Appender(IndexingMixin.iat.__doc__)
class TestScalar2: result = df.iat[2, 0] assert result == 2 def test_at_to_fail(self): # at should not fallback # GH 7814 s = Series([1, 2, 3], index=list("abc")) result = s.at["a"] assert result == 1 msg = ( "At based indexing on an non-i...
class TestScalar2: result = df.iat[2, 0] assert result == 2 def test_series_at_raises_type_error(self): # at should not fallback # GH 7814 # GH#31724 .at should match .loc ser = Series([1, 2, 3], index=list("abc")) result = ser.at["a"] assert result =...
def debug_build(program): program = os.path.basename(program) name = os.path.splitext(program)[0] return name.endswith("_d") def remove_python_envvars():
def debug_build(program): program = os.path.basename(program) name = os.path.splitext(program)[0] return name.casefold().endswith("_d".casefold()) def remove_python_envvars():
def get_expected_config(self, expected_preconfig, expected, env, api, if expected['stdio_errors'] is self.GET_DEFAULT_CONFIG: expected['stdio_errors'] = 'surrogateescape' if sys.platform == 'win32': default_executable = self.test_exe elif expected['program_name']...
def get_expected_config(self, expected_preconfig, expected, env, api, if expected['stdio_errors'] is self.GET_DEFAULT_CONFIG: expected['stdio_errors'] = 'surrogateescape' if MS_WINDOWS: default_executable = self.test_exe elif expected['program_name'] is not self....
def check_pre_config(self, configs, expected): pre_config = dict(configs['pre_config']) for key, value in list(expected.items()): if value is self.IGNORE_CONFIG: del pre_config[key] del expected[key] self.assertEqual(pre_config, expected)
def check_pre_config(self, configs, expected): pre_config = dict(configs['pre_config']) for key, value in list(expected.items()): if value is self.IGNORE_CONFIG: pre_config.pop(key, None) del expected[key] self.assertEqual(pre_config, expected)
def check_config(self, configs, expected): config = dict(configs['config']) for key, value in list(expected.items()): if value is self.IGNORE_CONFIG: del config[key] del expected[key] self.assertEqual(config, expected)
def check_config(self, configs, expected): config = dict(configs['config']) for key, value in list(expected.items()): if value is self.IGNORE_CONFIG: config.pop(key, None) del expected[key] self.assertEqual(config, expected)
def check_all_configs(self, testname, expected_config=None, self.check_pre_config(configs, expected_preconfig) self.check_config(configs, expected_config) self.check_global_config(configs) def test_init_default_config(self): self.check_all_configs("test_init_initialize_config", api=...
def check_all_configs(self, testname, expected_config=None, self.check_pre_config(configs, expected_preconfig) self.check_config(configs, expected_config) self.check_global_config(configs) return configs def test_init_default_config(self): self.check_all_configs("test_init_i...
def test_init_setpath(self): } self.default_program_name(config) env = {'TESTPATH': os.path.pathsep.join(paths)} self.check_all_configs("test_init_setpath", config, api=API_COMPAT, env=env, ignore_stderr=True)
def test_init_setpath(self): } self.default_program_name(config) env = {'TESTPATH': os.path.pathsep.join(paths)} self.check_all_configs("test_init_setpath", config, api=API_COMPAT, env=env, ignore_stderr=True)
def tmpdir_with_python(self): # Copy pythonXY.dll (or pythonXY_d.dll) ver = sys.version_info dll = f'python{ver.major}{ver.minor}' if debug_build(sys.executable): dll += '_d' dll += '.dll' dll = os.path.j...
def tmpdir_with_python(self): # Copy pythonXY.dll (or pythonXY_d.dll) ver = sys.version_info dll = f'python{ver.major}{ver.minor}' dll3 = f'python{ver.major}' if debug_build(sys.executable): dll += '_d' ...
def test_init_pyvenv_cfg(self): config['base_prefix'] = pyvenv_home config['prefix'] = pyvenv_home env = self.copy_paths_by_env(config) self.check_all_configs("test_init_compat_config", config, api=API_COMPAT, env=env, ...
def test_init_pyvenv_cfg(self): config['base_prefix'] = pyvenv_home config['prefix'] = pyvenv_home env = self.copy_paths_by_env(config) actual = self.check_all_configs("test_init_compat_config", config, api=API_COMPAT, e...
class FrameApply: from pandas import Series if not should_reduce: EMPTY_SERIES = Series([]) try: r = self.f(EMPTY_SERIES, *self.args, **self.kwds) except Exception: pass else: should_reduce = not isinstance...
class FrameApply: from pandas import Series if not should_reduce: try: r = self.f(Series([])) except Exception: pass else: should_reduce = not isinstance(r, Series) if should_reduce: if len(self.agg...
class TestDataFrameApply: # Ensure that x.append hasn't been called assert x == [] def test_apply_deprecate_reduce(self): empty_frame = DataFrame()
class TestDataFrameApply: # Ensure that x.append hasn't been called assert x == [] @pytest.mark.parametrize("func", ["sum", "prod", "any", "all"]) def test_apply_funcs_over_empty(self, func): # GH 28213 df = DataFrame(columns=["a", "b", "c"]) result = df.apply(getattr(n...
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