buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class Axes(_AxesBase): except ValueError: pass # Failed to convert to float array; must be color specs. else: # If c can be either mapped values or a RGB(A) color, prefer # the former if shapes match, the latter otherwise. if c.siz...
class Axes(_AxesBase): except ValueError: pass # Failed to convert to float array; must be color specs. else: # handle the documented special case of a 2D array with 1 # row which as RGB(A) to broadcast. if c.shape == (1, 4) or c.s...
class TestScatter: c=c_case, edgecolors="black", kwargs={}, xsize=xsize, get_next_color_func=get_next_color) def _params(c=None, xsize=2, *, edgecolors=None, **kwargs): return (c, edgecolors, kwargs if kwargs is not None else {}, xsize)
class TestScatter: c=c_case, edgecolors="black", kwargs={}, xsize=xsize, get_next_color_func=get_next_color) @pytest.mark.style('default') @check_figures_equal(extensions=["png"]) def test_scatter_single_color_c(self, fig_test, fig_ref): rgb = [[1, 0.5, 0.05]...
REQUIRES = [ "pip>=8.0.3,<20.3", "python-slugify==4.0.1", "pytz>=2020.5", "pyyaml==5.3.1", "requests==2.25.1", "ruamel.yaml==0.15.100", "voluptuous==0.12.1",
REQUIRES = [ "pip>=8.0.3,<20.3", "python-slugify==4.0.1", "pytz>=2020.5", "pyyaml==5.4.1", "requests==2.25.1", "ruamel.yaml==0.15.100", "voluptuous==0.12.1",
def yaml_msg_str(type_, yaml_str, filename=None): if yaml_str.strip() == '': msg_dict = {} else: msg_dict = yaml.load(yaml_str) if not isinstance(msg_dict, dict): if filename: raise ValueError("yaml file [%s] does not contain a dictionary" % filename)
def yaml_msg_str(type_, yaml_str, filename=None): if yaml_str.strip() == '': msg_dict = {} else: msg_dict = yaml.safe_load(yaml_str) if not isinstance(msg_dict, dict): if filename: raise ValueError("yaml file [%s] does not contain a dictionary" % filename)
def yaml_msgs_str(type_, yaml_str, filename=None): @type filename: str """ import yaml yaml_doc = yaml.load(yaml_str) msgs = [] for msg_dict in yaml_doc: if not isinstance(msg_dict, dict):
def yaml_msgs_str(type_, yaml_str, filename=None): @type filename: str """ import yaml yaml_doc = yaml.safe_load(yaml_str) msgs = [] for msg_dict in yaml_doc: if not isinstance(msg_dict, dict):
""" 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" ...
class FileSystemStorage(Storage): if not os.path.exists(directory): 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. ...
class FileSystemStorage(Storage): if not os.path.exists(directory): 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. ...
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 django.conf import settings from django.contrib.staticfiles import finders, storage
import sys import tempfile import unittest from io import StringIO from pathlib import Path from django.conf import settings from django.contrib.staticfiles import finders, storage
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...
logger = None if getattr(C, 'DEFAULT_LOG_PATH'): path = C.DEFAULT_LOG_PATH if path and (os.path.exists(path) and os.access(path, os.W_OK)) or os.access(os.path.dirname(path), os.W_OK): logging.basicConfig(filename=path, level=logging.DEBUG, format='%(asctime)s p=%(process)d u...
logger = None if getattr(C, 'DEFAULT_LOG_PATH'): path = C.DEFAULT_LOG_PATH if path and (os.path.exists(path) and os.access(path, os.W_OK)) or os.access(os.path.dirname(path), os.W_OK): # NOTE: level is kept at INFO to avoid security disclosures caused by certain libraries when using DEBUG loggin...
def array_equivalent(left, right, strict_nan=False): if not isinstance(right_value, float) or not np.isnan(right_value): return False else: if np.any(left_value != right_value): return False return True # NaNs can occur in ...
def array_equivalent(left, right, strict_nan=False): if not isinstance(right_value, float) or not np.isnan(right_value): return False else: try: if np.any(left_value != right_value): return False ...
class Index(IndexOpsMixin, PandasObject): # if other is not object, use other's logic for coercion return other.equals(self) try: return array_equivalent( com.values_from_object(self), com.values_from_object(other) ) except Exception: ...
class Index(IndexOpsMixin, PandasObject): # if other is not object, use other's logic for coercion return other.equals(self) return array_equivalent( com.values_from_object(self), com.values_from_object(other) ) def identical(self, other): """
import pandas as pd from pandas import DatetimeIndex, Float64Index, NaT, Series, TimedeltaIndex, date_range from pandas.util import testing as tm @pytest.mark.parametrize("notna_f", [notna, notnull]) def test_notna_notnull(notna_f):
import pandas as pd from pandas import DatetimeIndex, Float64Index, NaT, Series, TimedeltaIndex, date_range from pandas.util import testing as tm now = pd.Timestamp.now() utcnow = pd.Timestamp.now("UTC") @pytest.mark.parametrize("notna_f", [notna, notnull]) def test_notna_notnull(notna_f):
def test_array_equivalent(): assert not array_equivalent(DatetimeIndex([0, np.nan]), TimedeltaIndex([0, np.nan])) def test_array_equivalent_compat(): # see gh-13388 m = np.array([(1, 2), (3, 4)], dtype=[("a", int), ("b", float)])
def test_array_equivalent(): assert not array_equivalent(DatetimeIndex([0, np.nan]), TimedeltaIndex([0, np.nan])) @pytest.mark.parametrize( "lvalue, rvalue", [ # There are 3 variants for each of lvalue and rvalue. We include all # three for the tz-naive `now` and exclude the datetim64 var...
"""rope, a python refactoring library""" INFO = __doc__ VERSION = '0.10.7' COPYRIGHT = """\ Copyright (C) 2015-2016 Nicholas Smith Copyright (C) 2014-2015 Matej Cepl Copyright (C) 2006-2012 Ali Gholami Rudi Copyright (C) 2009-2012 Anton Gritsay
"""rope, a python refactoring library""" INFO = __doc__ VERSION = '0.11.0' COPYRIGHT = """\ Copyright (C) 2015-2018 Nicholas Smith Copyright (C) 2014-2015 Matej Cepl Copyright (C) 2006-2012 Ali Gholami Rudi Copyright (C) 2009-2012 Anton Gritsay
class TestImage: with pytest.warns(DeprecationWarning): assert test_module.PILLOW_VERSION > "7.0.0" def test_overrun(self): """For overrun completeness, test as: valgrind pytest -qq Tests/test_image.py::TestImage::test_overrun | grep decode.c """ for file in [ ...
class TestImage: with pytest.warns(DeprecationWarning): assert test_module.PILLOW_VERSION > "7.0.0" @pytest.mark.parametrize("path", [ "fli_overrun.bin", "sgi_overrun.bin", "sgi_overrun_expandrow.bin", "sgi_overrun_expandrow2.bin", "pc...
class PcxImageFile(ImageFile.ImageFile): version = s[1] bits = s[3] planes = s[65] stride = i16(s, 66) logger.debug( "PCX version %s, bits %s, planes %s, stride %s", version, bits, planes, stride, ) self...
class PcxImageFile(ImageFile.ImageFile): version = s[1] bits = s[3] planes = s[65] ignored_stride = i16(s, 66) logger.debug( "PCX version %s, bits %s, planes %s, stride %s", version, bits, planes, ignored_stride, ...
class PcxImageFile(ImageFile.ImageFile): self.mode = mode self._size = bbox[2] - bbox[0], bbox[3] - bbox[1] bbox = (0, 0) + self.size logger.debug("size: %sx%s", *self.size)
class PcxImageFile(ImageFile.ImageFile): self.mode = mode self._size = bbox[2] - bbox[0], bbox[3] - bbox[1] # don't trust the passed in stride. Calculate for ourselves. # CVE-2020-35655 stride = (self._size[0] * bits + 7) // 8 stride += stride % 2 bbox = (0, 0) ...
class MultiPartParser: remaining = len(stripped_chunk) % 4 while remaining != 0: over_chunk = field_stream.read(4 - remaining) stripped_chunk += b"".join(over_chunk.split()) ...
class MultiPartParser: remaining = len(stripped_chunk) % 4 while remaining != 0: over_chunk = field_stream.read(4 - remaining) if not over_chunk: ...
class FileUploadTests(TestCase): def test_big_base64_newlines_upload(self): self._test_base64_upload("Big data" * 68000, encode=base64.encodebytes) def test_unicode_file_name(self): with sys_tempfile.TemporaryDirectory() as temp_dir: # This file contains Chinese symbols and an accen...
class FileUploadTests(TestCase): def test_big_base64_newlines_upload(self): self._test_base64_upload("Big data" * 68000, encode=base64.encodebytes) def test_base64_invalid_upload(self): payload = client.FakePayload('\r\n'.join([ '--' + client.BOUNDARY, 'Content-Dispositi...
from __future__ import print_function import warnings import numpy as np from .training_utils import iter_sequence_infinite from .. import backend as K from ..utils.data_utils import Sequence
from __future__ import print_function import warnings import numpy as np from .training_utils import is_sequence from .training_utils import iter_sequence_infinite from .. import backend as K from ..utils.data_utils import Sequence
def fit_generator(model, if do_validation: model._make_test_function() is_sequence = isinstance(generator, Sequence) if not is_sequence and use_multiprocessing and workers > 1: warnings.warn( UserWarning('Using a generator with `use_multiprocessing=True`' ...
def fit_generator(model, if do_validation: model._make_test_function() use_sequence_api = is_sequence(generator) if not use_sequence_api and use_multiprocessing and workers > 1: warnings.warn( UserWarning('Using a generator with `use_multiprocessing=True`' ...
def fit_generator(model, # python 2 has 'next', 3 has '__next__' # avoid any explicit version checks val_gen = (hasattr(validation_data, 'next') or hasattr(validation_data, '__next__') or isinstance(validation_data, Sequence)) if (val_gen and not isinstance(validation_data...
def fit_generator(model, # python 2 has 'next', 3 has '__next__' # avoid any explicit version checks val_use_sequence_api = is_sequence(validation_data) val_gen = (hasattr(validation_data, 'next') or hasattr(validation_data, '__next__') or val_use_sequence_api) if (val...
def fit_generator(model, if val_gen and workers > 0: # Create an Enqueuer that can be reused val_data = validation_data if isinstance(val_data, Sequence): val_enqueuer = OrderedEnqueuer( val_data, ...
def fit_generator(model, if val_gen and workers > 0: # Create an Enqueuer that can be reused val_data = validation_data if is_sequence(val_data): val_enqueuer = OrderedEnqueuer( val_data, use_...
def fit_generator(model, val_enqueuer_gen = val_enqueuer.get() elif val_gen: val_data = validation_data if isinstance(val_data, Sequence): val_enqueuer_gen = iter_sequence_infinite(val_data) validation_steps = validation...
def fit_generator(model, val_enqueuer_gen = val_enqueuer.get() elif val_gen: val_data = validation_data if is_sequence(val_data): val_enqueuer_gen = iter_sequence_infinite(val_data) validation_steps = validation_steps or...
def fit_generator(model, cbk.validation_data = val_data if workers > 0: if is_sequence: enqueuer = OrderedEnqueuer( generator, use_multiprocessing=use_multiprocessing,
def fit_generator(model, cbk.validation_data = val_data if workers > 0: if use_sequence_api: enqueuer = OrderedEnqueuer( generator, use_multiprocessing=use_multiprocessing,
def fit_generator(model, enqueuer.start(workers=workers, max_queue_size=max_queue_size) output_generator = enqueuer.get() else: if is_sequence: output_generator = iter_sequence_infinite(generator) else: output_generator = generator
def fit_generator(model, enqueuer.start(workers=workers, max_queue_size=max_queue_size) output_generator = enqueuer.get() else: if use_sequence_api: output_generator = iter_sequence_infinite(generator) else: output_generator = gener...
def evaluate_generator(model, generator, steps_done = 0 outs_per_batch = [] batch_sizes = [] is_sequence = isinstance(generator, Sequence) if not is_sequence and use_multiprocessing and workers > 1: warnings.warn( UserWarning('Using a generator with `use_multiprocessing=True`' ...
def evaluate_generator(model, generator, steps_done = 0 outs_per_batch = [] batch_sizes = [] use_sequence_api = is_sequence(generator) if not use_sequence_api and use_multiprocessing and workers > 1: warnings.warn( UserWarning('Using a generator with `use_multiprocessing=True`' ...
def evaluate_generator(model, generator, try: if workers > 0: if is_sequence: enqueuer = OrderedEnqueuer( generator, use_multiprocessing=use_multiprocessing)
def evaluate_generator(model, generator, try: if workers > 0: if use_sequence_api: enqueuer = OrderedEnqueuer( generator, use_multiprocessing=use_multiprocessing)
def evaluate_generator(model, generator, enqueuer.start(workers=workers, max_queue_size=max_queue_size) output_generator = enqueuer.get() else: if is_sequence: output_generator = iter_sequence_infinite(generator) else: output_genera...
def evaluate_generator(model, generator, enqueuer.start(workers=workers, max_queue_size=max_queue_size) output_generator = enqueuer.get() else: if use_sequence_api: output_generator = iter_sequence_infinite(generator) else: output_g...
def predict_generator(model, generator, steps_done = 0 all_outs = [] is_sequence = isinstance(generator, Sequence) if not is_sequence and use_multiprocessing and workers > 1: warnings.warn( UserWarning('Using a generator with `use_multiprocessing=True`' ' and...
def predict_generator(model, generator, steps_done = 0 all_outs = [] use_sequence_api = is_sequence(generator) if not use_sequence_api and use_multiprocessing and workers > 1: warnings.warn( UserWarning('Using a generator with `use_multiprocessing=True`' ' an...
def predict_generator(model, generator, try: if workers > 0: if is_sequence: enqueuer = OrderedEnqueuer( generator, use_multiprocessing=use_multiprocessing)
def predict_generator(model, generator, try: if workers > 0: if use_sequence_api: enqueuer = OrderedEnqueuer( generator, use_multiprocessing=use_multiprocessing)
def predict_generator(model, generator, enqueuer.start(workers=workers, max_queue_size=max_queue_size) output_generator = enqueuer.get() else: if is_sequence: output_generator = iter_sequence_infinite(generator) else: output_generat...
def predict_generator(model, generator, enqueuer.start(workers=workers, max_queue_size=max_queue_size) output_generator = enqueuer.get() else: if use_sequence_api: output_generator = iter_sequence_infinite(generator) else: output_ge...
import warnings from .. import backend as K from .. import losses from ..utils.generic_utils import to_list
import warnings from .. import backend as K from .. import losses from ..utils import Sequence from ..utils.generic_utils import to_list
def iter_sequence_infinite(seq): while True: for item in seq: yield item
def iter_sequence_infinite(seq): while True: for item in seq: yield item def is_sequence(seq): """Determine if an object follows the Sequence API. # Arguments seq: a possible Sequence object # Returns boolean, whether the object follows the Sequence API. """ ...
class Sequence(object): ``` """ @abstractmethod def __getitem__(self, index): """Gets batch at position `index`.
class Sequence(object): ``` """ use_sequence_api = True @abstractmethod def __getitem__(self, index): """Gets batch at position `index`.
from __future__ import print_function import numpy as np import pytest from keras.utils.test_utils import get_test_data from keras.models import Sequential from keras import layers
from __future__ import print_function import numpy as np import pytest from keras.preprocessing.image import ImageDataGenerator from keras.utils.test_utils import get_test_data from keras.models import Sequential from keras import layers
def test_image_classification(): model = Sequential.from_config(config) if __name__ == '__main__': pytest.main([__file__])
def test_image_classification(): model = Sequential.from_config(config) def test_image_data_generator_training(): np.random.seed(1337) img_gen = ImageDataGenerator(rescale=1.) # Dummy ImageDataGenerator input_shape = (16, 16, 3) (x_train, y_train), (x_test, y_test) = get_test_data(num_train=500, ...
from keras.utils.data_utils import validate_file from keras import backend as K pytestmark = pytest.mark.skipif( K.backend() == 'tensorflow', reason='Temporarily disabled until the use_multiprocessing problem is solved') if sys.version_info < (3,):
from keras.utils.data_utils import validate_file from keras import backend as K pytestmark = pytest.mark.skipif( K.backend() == 'tensorflow' and 'TRAVIS_PYTHON_VERSION' in os.environ, reason='Temporarily disabled until the use_multiprocessing problem is solved') if sys.version_info < (3,):
from keras.utils import Sequence from keras import backend as K pytestmark = pytest.mark.skipif( K.backend() == 'tensorflow', reason='Temporarily disabled until the use_multiprocessing problem is solved') STEPS_PER_EPOCH = 100
from keras.utils import Sequence from keras import backend as K pytestmark = pytest.mark.skipif( K.backend() == 'tensorflow' and 'TRAVIS_PYTHON_VERSION' in os.environ, reason='Temporarily disabled until the use_multiprocessing problem is solved') STEPS_PER_EPOCH = 100
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 ...
def setup_remote_pydev_debug(): except: LOG.exception(_(error_msg)) raise
def setup_remote_pydev_debug(): except: LOG.exception(_(error_msg)) raise class LimitingReader(object): """Reader to limit the size of an incoming request.""" def __init__(self, data, limit): """ :param data: Underlying data object :param limit: maximum ...
def register_cli_int(*args, **kw): register_str('auth_admin_prefix', default='') register_str('policy_file', default='policy.json') register_str('policy_default_rule', default=None) #ssl options register_bool('enable', group='ssl', default=False)
def register_cli_int(*args, **kw): register_str('auth_admin_prefix', default='') register_str('policy_file', default='policy.json') register_str('policy_default_rule', default=None) #default max request size is 112k register_int('max_request_body_size', default=114688) #ssl options register_bool('enable', group='ssl',...
class Conflict(Error): title = 'Conflict' class UnexpectedError(Error): """An unexpected error prevented the server from fulfilling your request.
class Conflict(Error): title = 'Conflict' class RequestTooLarge(Error): """Request is too large.""" code = 413 title = 'Request is too large.' class UnexpectedError(Error): """An unexpected error prevented the server from fulfilling your request.
# License for the specific language governing permissions and limitations # under the License. from keystone.common import serializer from keystone.common import wsgi from keystone import config from keystone import exception
# License for the specific language governing permissions and limitations # under the License. import webob.dec from keystone.common import serializer from keystone.common import utils from keystone.common import wsgi from keystone import config from keystone import exception
def process_request(self, request): # Rewrites path to root if no path is given. elif not request.environ['PATH_INFO']: request.environ['PATH_INFO'] = '/'
def process_request(self, request): # Rewrites path to root if no path is given. elif not request.environ['PATH_INFO']: request.environ['PATH_INFO'] = '/' class RequestBodySizeLimiter(wsgi.Middleware): """Limit the size of an incoming request.""" def __init__(self, *args, **kwargs...
def _parse_octet(cls, octet_str): if len(octet_str) > 3: msg = "At most 3 characters permitted in %r" raise ValueError(msg % octet_str) # Convert to integer (we know digits are legal) octet_int = int(octet_str, 10) if octet_int > 255:
def _parse_octet(cls, octet_str): if len(octet_str) > 3: msg = "At most 3 characters permitted in %r" raise ValueError(msg % octet_str) # Handle leading zeros as strict as glibc's inet_pton() # See security bug bpo-36384 if octet_str != '0' and octet_str[0] == '0'...
def pickle_test(self, addr): class CommonTestMixin_v4(CommonTestMixin): def test_leading_zeros(self): self.assertInstancesEqual("000.000.000.000", "0.0.0.0") self.assertInstancesEqual("192.168.000.001", "192.168.0.1") self.assertInstancesEqual("016.016.016.016", "16.16.16.16") self....
def pickle_test(self, addr): class CommonTestMixin_v4(CommonTestMixin): def test_leading_zeros(self): # bpo-36384: no leading zeros to avoid ambiguity with octal notation msg = "Leading zeros are not permitted in '\d+'" addresses = [ "000.000.000.000", "192.168.000.0...
MSG_USERAUTH_INFO_REQUEST, MSG_USERAUTH_INFO_RESPONSE = range(60, 62) MSG_USERAUTH_GSSAPI_RESPONSE, MSG_USERAUTH_GSSAPI_TOKEN = range(60, 62) MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE, MSG_USERAUTH_GSSAPI_ERROR,\ MSG_USERAUTH_GSSAPI_ERRTOK, MSG_USERAUTH_GSSAPI_MIC = range(63, 67) MSG_GLOBAL_REQUEST, MSG_REQUEST_SUCCESS...
MSG_USERAUTH_INFO_REQUEST, MSG_USERAUTH_INFO_RESPONSE = range(60, 62) MSG_USERAUTH_GSSAPI_RESPONSE, MSG_USERAUTH_GSSAPI_TOKEN = range(60, 62) MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE, MSG_USERAUTH_GSSAPI_ERROR,\ MSG_USERAUTH_GSSAPI_ERRTOK, MSG_USERAUTH_GSSAPI_MIC = range(63, 67) HIGHEST_USERAUTH_MESSAGE_ID = 79 MSG_GL...
from paramiko.common import ( MSG_CHANNEL_FAILURE, MSG_CHANNEL_DATA, MSG_CHANNEL_EXTENDED_DATA, MSG_CHANNEL_WINDOW_ADJUST, MSG_CHANNEL_REQUEST, MSG_CHANNEL_EOF, MSG_CHANNEL_CLOSE, MIN_WINDOW_SIZE, MIN_PACKET_SIZE, MAX_WINDOW_SIZE, DEFAULT_WINDOW_SIZE, DEFAULT_MAX_PACKET_SIZE, ) from paramiko.compress im...
from paramiko.common import ( MSG_CHANNEL_FAILURE, MSG_CHANNEL_DATA, MSG_CHANNEL_EXTENDED_DATA, MSG_CHANNEL_WINDOW_ADJUST, MSG_CHANNEL_REQUEST, MSG_CHANNEL_EOF, MSG_CHANNEL_CLOSE, MIN_WINDOW_SIZE, MIN_PACKET_SIZE, MAX_WINDOW_SIZE, DEFAULT_WINDOW_SIZE, DEFAULT_MAX_PACKET_SIZE, HIGHEST_USERAUTH_MESSAGE_ID...
class Transport(threading.Thread, ClosingContextManager): max_packet_size = self.default_max_packet_size return clamp_value(MIN_PACKET_SIZE, max_packet_size, MAX_WINDOW_SIZE) def run(self): # (use the exposed "run" method, because if we specify a thread target
class Transport(threading.Thread, ClosingContextManager): max_packet_size = self.default_max_packet_size return clamp_value(MIN_PACKET_SIZE, max_packet_size, MAX_WINDOW_SIZE) def _ensure_authed(self, ptype, message): """ Checks message type against current auth state. I...
class Transport(threading.Thread, ClosingContextManager): continue if ptype in self._handler_table: self._handler_table[ptype](self, m) elif ptype in self._channel_handler_table: chanid = m.get_int() ...
class Transport(threading.Thread, ClosingContextManager): continue if ptype in self._handler_table: error_msg = self._ensure_authed(ptype, m) if error_msg: self._send_message(error_msg) ...
def logical_volume_info(path): return dict(zip(*info)) def remove_logical_volumes(*paths): """Remove one or more logical volume.""" if paths: lvremove = ('lvremove', '-f') + paths execute(*lvremove, attempts=3, run_as_root=True)
def logical_volume_info(path): return dict(zip(*info)) def logical_volume_size(path): """Get logical volume size in bytes. :param path: logical volume path """ # TODO(p-draigbrady) POssibly replace with the more general # use of blockdev --getsize64 in future out, _err = execute('lvs', '-...
part 3</font></u> self.assertEqual(get_element_by_attribute('class', 'foo', html), None) self.assertEqual(get_element_by_attribute('class', 'no-such-foo', html), None) def test_get_elements_by_class(self): html = ''' <span class="foo bar">nice</span><span class="foo bar">also ni...
part 3</font></u> self.assertEqual(get_element_by_attribute('class', 'foo', html), None) self.assertEqual(get_element_by_attribute('class', 'no-such-foo', html), None) html = ''' <div itemprop="author" itemscope>foo</div> ''' self.assertEqual(get_element_by_attribut...
def get_elements_by_attribute(attribute, value, html, escape_value=True): retlist = [] for m in re.finditer(r'''(?xs) <([a-zA-Z0-9:._-]+) (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'))*? \s+%s=['"]?%s['"]? (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[...
def get_elements_by_attribute(attribute, value, html, escape_value=True): retlist = [] for m in re.finditer(r'''(?xs) <([a-zA-Z0-9:._-]+) (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*? \s+%s=['"]?%s['"]? (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='...
all about the internals of models in order to get the information it needs. """ import difflib import functools from collections import Counter, OrderedDict, namedtuple from collections.abc import Iterator, Mapping from itertools import chain, count, product
all about the internals of models in order to get the information it needs. """ import difflib import functools import re from collections import Counter, OrderedDict, namedtuple from collections.abc import Iterator, Mapping from itertools import chain, count, product
from django.utils.tree import Node __all__ = ['Query', 'RawQuery'] def get_field_names_from_opts(opts): return set(chain.from_iterable(
from django.utils.tree import Node __all__ = ['Query', 'RawQuery'] # Quotation marks ('"`[]), whitespace characters, semicolons, or inline # SQL comments are forbidden in column aliases. FORBIDDEN_ALIAS_PATTERN = re.compile(r"['`\"\]\[;\s]|--|/\*|\*/") def get_field_names_from_opts(opts): return set(chain.from_...
class Query: alias = seen[int_model] = join_info.joins[-1] return alias or seen[None] def add_annotation(self, annotation, alias, is_summary=False): """Add a single annotation expression to the Query.""" annotation = annotation.resolve_expression(self, allow_joins=True, reuse=No...
class Query: alias = seen[int_model] = join_info.joins[-1] return alias or seen[None] def check_alias(self, alias): if FORBIDDEN_ALIAS_PATTERN.search(alias): raise ValueError( "Column aliases cannot contain whitespace characters, quotation marks, " ...
class Query: else: param_iter = iter([]) for name, entry in select.items(): entry = str(entry) entry_params = [] pos = entry.find("%s")
class Query: else: param_iter = iter([]) for name, entry in select.items(): self.check_alias(name) entry = str(entry) entry_params = [] pos = entry.find("%s")
class AggregateTestCase(TestCase): Book.objects.aggregate(is_book=True) with self.assertRaisesMessage(TypeError, msg % ', '.join([str(FloatField()), 'True'])): Book.objects.aggregate(FloatField(), Avg('price'), is_book=True)
class AggregateTestCase(TestCase): Book.objects.aggregate(is_book=True) with self.assertRaisesMessage(TypeError, msg % ', '.join([str(FloatField()), 'True'])): Book.objects.aggregate(FloatField(), Avg('price'), is_book=True) def test_alias_sql_injection(self): crafted_alias ...
class NonAggregateAnnotationTestCase(TestCase): total_books=Subquery(long_books_qs, output_field=IntegerField()), ).values('name') self.assertCountEqual(publisher_books_qs, [{'name': 'Sams'}, {'name': 'Morgan Kaufmann'}])
class NonAggregateAnnotationTestCase(TestCase): total_books=Subquery(long_books_qs, output_field=IntegerField()), ).values('name') self.assertCountEqual(publisher_books_qs, [{'name': 'Sams'}, {'name': 'Morgan Kaufmann'}]) def test_alias_sql_injection(self): crafted_alias = """in...
class ValuesExpressionsTests(TestCase): [{'salary': 10}, {'salary': 20}, {'salary': 30}], ) def test_values_expression_group_by(self): # values() applies annotate() first, so values selected are grouped by # id, not firstname.
class ValuesExpressionsTests(TestCase): [{'salary': 10}, {'salary': 20}, {'salary': 30}], ) def test_values_expression_alias_sql_injection(self): crafted_alias = """injected_name" from "expressions_company"; --""" msg = ( "Column aliases cannot contain whitespace cha...
class Queries5Tests(TestCase): 'bar %s' ) class SelectRelatedTests(TestCase): def test_tickets_3045_3288(self):
class Queries5Tests(TestCase): 'bar %s' ) def test_extra_select_alias_sql_injection(self): crafted_alias = """injected_name" from "queries_note"; --""" msg = ( "Column aliases cannot contain whitespace characters, quotation marks, " "semicolons, or SQL co...
class MinimumLengthValidator: ) % {'min_length': self.min_length} class UserAttributeSimilarityValidator: """ Validate whether the password is sufficiently different from the user's
class MinimumLengthValidator: ) % {'min_length': self.min_length} def exceeds_maximum_length_ratio(password, max_similarity, value): """ Test that value is within a reasonable range of password. The following ratio calculations are based on testing SequenceMatcher like this: for i in ran...
class UserAttributeSimilarityValidator: def __init__(self, user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7): self.user_attributes = user_attributes self.max_similarity = max_similarity def validate(self, password, user=None): if not user: return for att...
class UserAttributeSimilarityValidator: def __init__(self, user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7): self.user_attributes = user_attributes if max_similarity < 0.1: raise ValueError('max_similarity must be at least 0.1') self.max_similarity = max_similarity ...
class UserAttributeSimilarityValidatorTest(TestCase): max_similarity=1, ).validate(user.first_name, user=user) self.assertEqual(cm.exception.messages, [expected_error % "first name"]) # max_similarity=0 rejects all passwords. with self.assertRaises(ValidationError) as...
class UserAttributeSimilarityValidatorTest(TestCase): max_similarity=1, ).validate(user.first_name, user=user) self.assertEqual(cm.exception.messages, [expected_error % "first name"]) # Very low max_similarity is rejected. msg = 'max_similarity must be at least 0.1' ...
class _LocIndexer(_LocationIndexer): return self._getbool_axis(key, axis=axis) elif is_list_like_indexer(key): # convert various list-like indexers # to a list of keys # we will use the *values* of the object # and NOT the index if its a PandasObject ...
class _LocIndexer(_LocationIndexer): return self._getbool_axis(key, axis=axis) elif is_list_like_indexer(key): # an iterable multi-selection if not (isinstance(key, tuple) and isinstance(labels, ABCMultiIndex)):
class TestMultiIndexLoc: @pytest.mark.parametrize("key, pos", [([2, 4], [0, 1]), ([2], []), ([2, 3], [])]) def test_loc_multiindex_list_missing_label(self, key, pos): # GH 27148 - lists with missing labels do not raise: df = DataFrame( np.random.randn(3, 3), columns=[[2,...
class TestMultiIndexLoc: @pytest.mark.parametrize("key, pos", [([2, 4], [0, 1]), ([2], []), ([2, 3], [])]) def test_loc_multiindex_list_missing_label(self, key, pos): # GH 27148 - lists with missing labels _do_ raise df = DataFrame( np.random.randn(3, 3), columns=[[2, 2,...
class TestMultiIndexLoc: [ ([], []), # empty ok (["A"], slice(3)), (["A", "D"], slice(3)), (["D", "E"], []), # no values found - fine (["D"], []), # same, with single item list: GH 27148 (pd.IndexSlice[:, ["foo"]], slice(2, None, 3)), (pd.IndexSlice[:, ["fo...
class TestMultiIndexLoc: [ ([], []), # empty ok (["A"], slice(3)), (["A", "D"], []), # "D" isnt present -> raise (["D", "E"], []), # no values found -> raise (["D"], []), # same, with single item list: GH 27148 (pd.IndexSlice[:, ["foo"]], slice(2, None, 3)), ...
def test_loc_getitem_duplicates_multiindex_missing_indexers(indexer, pos): ) s = Series(np.arange(9, dtype="int64"), index=idx).sort_index() expected = s.iloc[pos] result = s.loc[indexer] tm.assert_series_equal(result, expected) def test_series_loc_getitem_fancy(multiindex_year_month_day_dataframe...
def test_loc_getitem_duplicates_multiindex_missing_indexers(indexer, pos): ) s = Series(np.arange(9, dtype="int64"), index=idx).sort_index() expected = s.iloc[pos] if expected.size == 0 and indexer != []: with pytest.raises(KeyError, match=str(indexer)): s.loc[indexer] else: ...
class TestMultiIndexSlicers: with pytest.raises(ValueError, match=msg): df.loc[(slice(None), np.array([True, False])), :] # ambiguous notation # this is interpreted as slicing on both axes (GH #16396) result = df.loc[slice(None), [1]] expected = df.iloc[:, []] ...
class TestMultiIndexSlicers: with pytest.raises(ValueError, match=msg): df.loc[(slice(None), np.array([True, False])), :] with pytest.raises(KeyError, match=r"\[1\] not in index"): # slice(None) is on the index, [1] is on the columns, but 1 is # not in the columns, ...
class TestSeriesGetitemListLike: result = ser[key] tm.assert_series_equal(result, expected) def test_getitem_generator(string_series): gen = (x > 0 for x in string_series)
class TestSeriesGetitemListLike: result = ser[key] tm.assert_series_equal(result, expected) @pytest.mark.parametrize("box", [list, np.array, pd.Index]) @pytest.mark.parametrize("dtype", [np.int64, np.float64, np.uint64]) def test_getitem_intlist_multiindex_numeric_level(self, dtype, box): ...
from .helper import on_ci "Tests/images/crash-4f085cc12ece8cde18758d42608bed6a2a2cfb1c.tif", "Tests/images/crash-86214e58da443d2b80820cff9677a38a33dcbbca.tif", "Tests/images/crash-f46f5b2f43c370fe65706c11449f567ecc345e74.tif", ], ) @pytest.mark.filterwarnings("ignore:Possibly corrupt EXIF da...
from .helper import on_ci "Tests/images/crash-4f085cc12ece8cde18758d42608bed6a2a2cfb1c.tif", "Tests/images/crash-86214e58da443d2b80820cff9677a38a33dcbbca.tif", "Tests/images/crash-f46f5b2f43c370fe65706c11449f567ecc345e74.tif", "Tests/images/crash-63b1dffefc8c075ddc606c0a2f5fdc15ece78863....
def delete(self, req, id): content_type="text/plain") image = self.get_image_meta_or_404(req, id) if image['protected']: msg = _("Image is protected") logger.debug(msg)
def delete(self, req, id): content_type="text/plain") image = self.get_image_meta_or_404(req, id) if not (req.context.is_admin or image['owner'] == None or image['owner'] == req.context.owner): msg = _("Unable to delete image ...
b 2""", # datetime64tz is handled correctly in agg_series, # so is excluded here. # return the same type (Series) as our caller cls = dtype.construct_array_type() result = try_cast_to_ea(cls, result, dtype=dtype) elif numeric...
b 2""", # datetime64tz is handled correctly in agg_series, # so is excluded here. if len(result) and isinstance(result[0], dtype.type): cls = dtype.construct_array_type() result = try_cast_to_ea(cls, result, dtype=dtype) ...
class BaseGrouper: if mask.any(): result = result.astype("float64") result[mask] = np.nan if kind == "aggregate" and self._filter_empty_groups and not counts.all(): assert result.ndim != 2
class BaseGrouper: if mask.any(): result = result.astype("float64") result[mask] = np.nan elif ( how == "add" and is_integer_dtype(orig_values.dtype) and is_extension_array_dtype(orig_values.dtype) ): # We need t...
def test_aggregate_mixed_types(): tm.assert_frame_equal(result, expected) class TestLambdaMangling: def test_basic(self): df = pd.DataFrame({"A": [0, 0, 1, 1], "B": [1, 2, 3, 4]})
def test_aggregate_mixed_types(): tm.assert_frame_equal(result, expected) @pytest.mark.xfail(reason="Not implemented.") def test_aggregate_udf_na_extension_type(): # https://github.com/pandas-dev/pandas/pull/31359 # This is currently failing to cast back to Int64Dtype. # The presence of the NA causes ...
def test_series_groupby_categorical_aggregation_getitem(): result = groups["foo"].agg("mean") expected = groups.agg("mean")["foo"] tm.assert_series_equal(result, expected)
def test_series_groupby_categorical_aggregation_getitem(): result = groups["foo"].agg("mean") expected = groups.agg("mean")["foo"] tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "func, expected_values", [(pd.Series.nunique, [1, 1, 2]), (pd.Series.count, [1, 2, 2])], ) def test_...
def test_resample_integerarray(): result = ts.resample("3T").mean() expected = Series( [1, 4, 7], index=pd.date_range("1/1/2000", periods=3, freq="3T"), dtype="Int64" ) tm.assert_series_equal(result, expected)
def test_resample_integerarray(): result = ts.resample("3T").mean() expected = Series( [1, 4, 7], index=pd.date_range("1/1/2000", periods=3, freq="3T"), dtype="float64", ) tm.assert_series_equal(result, expected)
def test_resample_categorical_data_with_timedeltaindex(): index=pd.to_timedelta([0, 10], unit="s"), ) expected = expected.reindex(["Group_obj", "Group"], axis=1) expected["Group"] = expected["Group_obj"].astype("category") tm.assert_frame_equal(result, expected)
def test_resample_categorical_data_with_timedeltaindex(): index=pd.to_timedelta([0, 10], unit="s"), ) expected = expected.reindex(["Group_obj", "Group"], axis=1) expected["Group"] = expected["Group_obj"] tm.assert_frame_equal(result, expected)
import errno import grp import os import platform import pwd import shutil import socket import time import re from ansible.module_utils._text import to_native from ansible.module_utils.basic import load_platform_subclass, AnsibleModule try:
import errno import grp import os import platform import pty import pwd import select import shutil import socket import subprocess import time import re from ansible.module_utils._text import to_native, to_bytes, to_text from ansible.module_utils.basic import load_platform_subclass, AnsibleModule try:
class User(object): cmd.append(self.ssh_comment) cmd.append('-f') cmd.append(ssh_key_file) cmd.append('-N') if self.ssh_passphrase is not None: cmd.append(self.ssh_passphrase) else: cmd.append('') (rc, out, err) = self.execute_command(cmd)...
class User(object): cmd.append(self.ssh_comment) cmd.append('-f') cmd.append(ssh_key_file) if self.ssh_passphrase is not None: if self.module.check_mode: self.module.debug('In check mode, would have run: "%s"' % cmd) return (0, '', '') ...
class Register(abc.ABCMeta): # We return this in a topologically sorted list of inheritance: this is useful in some cases (#822) reg = OrderedDict() for cls in cls._reg: if cls.run == NotImplemented: continue name = cls.task_family if name in ...
class Register(abc.ABCMeta): # We return this in a topologically sorted list of inheritance: this is useful in some cases (#822) reg = OrderedDict() for cls in cls._reg: name = cls.task_family if name in reg and reg[name] != cls and \
class AmbiguousClass(luigi.Task): pass class NonAmbiguousClass(luigi.ExternalTask): pass class NonAmbiguousClass(luigi.Task): def run(self): NonAmbiguousClass.has_run = True class TaskWithSameName(luigi.Task): def run(self):
class AmbiguousClass(luigi.Task): pass class TaskWithSameName(luigi.Task): def run(self):
class CmdlineTest(unittest.TestCase): def test_cmdline_ambiguous_class(self, logger): self.assertRaises(Exception, luigi.run, ['--local-scheduler', '--no-lock', 'AmbiguousClass']) @mock.patch("logging.getLogger") @mock.patch("warnings.warn") def test_cmdline_non_ambiguous_class(self, warn, logg...
class CmdlineTest(unittest.TestCase): def test_cmdline_ambiguous_class(self, logger): self.assertRaises(Exception, luigi.run, ['--local-scheduler', '--no-lock', 'AmbiguousClass']) @mock.patch("logging.getLogger") @mock.patch("logging.StreamHandler") def test_setup_interface_logging(self, handle...
from datetime import datetime, timedelta import luigi import luigi.task class DummyTask(luigi.Task):
from datetime import datetime, timedelta import luigi import luigi.task from luigi.task_register import load_task class DummyTask(luigi.Task):
class TaskTest(unittest.TestCase): other = DummyTask.from_str_params(original.to_str_params()) self.assertEqual(original, other) def test_id_to_name_and_params(self): task_id = "InputText(date=2014-12-29)" (name, params) = luigi.task.id_to_name_and_params(task_id)
class TaskTest(unittest.TestCase): other = DummyTask.from_str_params(original.to_str_params()) self.assertEqual(original, other) def test_external_tasks_loadable(self): task = load_task("luigi", "ExternalTask", {}) assert(isinstance(task, luigi.ExternalTask)) def test_id_to_nam...
def _set_uid_gid(tarinfo): return archive_name def _call_external_zip(base_dir, zip_filename, verbose=False, dry_run=False): # XXX see if we want to keep an external call here if verbose: zipoptions = "-r" else: zipoptions = "-rq" from distutils.errors import DistutilsExecError ...
def _set_uid_gid(tarinfo): return archive_name def _call_external_zip(base_dir, zip_filename, verbose, dry_run, logger): # XXX see if we want to keep an external call here if verbose: zipoptions = "-r" else: zipoptions = "-rq" cmd = ["zip", zipoptions, zip_filename, base_dir] i...
def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None): zipfile = None if zipfile is None: _call_external_zip(base_dir, zip_filename, verbose, dry_run) else: if logger is not None: logger.info("creating '%s' and adding '%s' to it",
def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None): zipfile = None if zipfile is None: _call_external_zip(base_dir, zip_filename, verbose, dry_run, logger) else: if logger is not None: logger.info("creating '%s' and adding '%s' to it",
class DataFrame(NDFrame): scalar """ if takeable: series = self._iget_item_cache(col) return com.maybe_box_datetimelike(series._values[index]) series = self._get_item_cache(col) engine = self.index._engine
class DataFrame(NDFrame): scalar """ if takeable: series = self._ixs(col, axis=1) return series._values[index] series = self._get_item_cache(col) engine = self.index._engine