buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
class DEFAULTS:
verify = True
ca_bundle = None
safe_write = False
render = True
@staticmethod
def _as_dict(): | class DEFAULTS:
verify = True
ca_bundle = None
safe_write = False
@staticmethod
def _as_dict(): |
def path_to_nested(dict_obj: Dict) -> Dict:
return dict_obj
class RecursiveValue:
def __init__(self, name: str):
self.name = name
def __str__(self) -> str:
return f'<recursive value "{self.name}">'
def __getitem__(self, key: str) -> str:
return str(self)
def extract_error_m... | def path_to_nested(dict_obj: Dict) -> Dict:
return dict_obj
def extract_error_messages(exc: BaseException) -> Iterable[str]:
while True:
exc_str = str(exc).strip() |
def bracket_split_build_line(
if leaves:
# Since body is a new indent level, remove spurious leading whitespace.
normalize_prefix(leaves[0], inside_brackets=True)
# Ensure a trailing comma when expected.
if original.is_import:
if leaves[-1].type !=... | def bracket_split_build_line(
if leaves:
# Since body is a new indent level, remove spurious leading whitespace.
normalize_prefix(leaves[0], inside_brackets=True)
# Ensure a trailing comma for imports, but be careful not to add one after
# any comments.
... |
class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
@patch("black.dump_to_file", dump_to_stderr)
def test_cantfit(self) -> None:
source, expected = read_data("cantfit") | class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
@patch("black.dump_to_file", dump_to_stderr)
def test_comments7(self) -> None:
source, expected = read_data("comments7")
actual = fs(source)
... |
class ContractsManager(object):
def eb_wrapper(failure):
case = _create_testcase(method, 'errback')
exc_info = failure.value, failure.type, failure.getTracebackObject()
results.addError(case, exc_info)
request.callback = cb_wrapper | class ContractsManager(object):
def eb_wrapper(failure):
case = _create_testcase(method, 'errback')
exc_info = failure.type, failure.value, failure.getTracebackObject()
results.addError(case, exc_info)
request.callback = cb_wrapper |
from unittest import TextTestResult
from twisted.trial import unittest
from scrapy.spiders import Spider
from scrapy.http import Request
from scrapy.item import Item, Field | from unittest import TextTestResult
from twisted.python import failure
from twisted.trial import unittest
from scrapy.spidermiddlewares.httperror import HttpError
from scrapy.spiders import Spider
from scrapy.http import Request
from scrapy.item import Item, Field |
class ContractsManagerTest(unittest.TestCase):
self.results)
request.callback(response)
self.should_fail() | class ContractsManagerTest(unittest.TestCase):
self.results)
request.callback(response)
self.should_fail()
def test_errback(self):
spider = TestSpider()
response = ResponseMock()
try:
raise HttpError(response, 'Ignoring non-200 response')
... |
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... |
def categorical_accuracy(y_true, y_pred):
def sparse_categorical_accuracy(y_true, y_pred):
# flatten y_true in case it's in shape (num_samples, 1) instead of (num_samples,)
return K.cast(K.equal(K.flatten(y_true),
K.cast(K.argmax(y_pred, axis=-1), K.floatx())),
K.fl... | def categorical_accuracy(y_true, y_pred):
def sparse_categorical_accuracy(y_true, y_pred):
# reshape in case it's in shape (num_samples, 1) instead of (num_samples,)
if K.ndim(y_true) == K.ndim(y_pred):
y_true = K.squeeze(y_true, -1)
# convert dense predictions to labels
y_pred_labels = K.argm... |
def test_sparse_metrics():
assert K.eval(metric(y_a, y_b)).shape == (6,)
def test_sparse_categorical_accuracy_correctness():
y_a = K.variable(np.random.randint(0, 7, (6,)), dtype=K.floatx())
y_b = K.variable(np.random.random((6, 7)), dtype=K.floatx())
# use one_hot embedding to convert sparse labe... | def test_sparse_metrics():
assert K.eval(metric(y_a, y_b)).shape == (6,)
@pytest.mark.parametrize('shape', [(6,), (6, 3), (6, 3, 1)])
def test_sparse_categorical_accuracy_correctness(shape):
y_a = K.variable(np.random.randint(0, 7, shape), dtype=K.floatx())
y_b_shape = shape + (7,)
y_b = K.variabl... |
class MultiIndex(Index):
if names is lib.no_default:
names = [getattr(it, "name", None) for it in iterables]
codes = cartesian_product(codes)
return MultiIndex(levels, codes, sortorder=sortorder, names=names)
| class MultiIndex(Index):
if names is lib.no_default:
names = [getattr(it, "name", None) for it in iterables]
# codes are all ndarrays, so cartesian_product is lossless
codes = cartesian_product(codes)
return MultiIndex(levels, codes, sortorder=sortorder, names=names)
|
import numpy as np
from pandas.core.dtypes.common import is_list_like
import pandas.core.common as com
def cartesian_product(X):
""" | import numpy as np
from pandas.core.dtypes.common import is_list_like
def cartesian_product(X):
""" |
def cartesian_product(X):
# if any factor is empty, the cartesian product is empty
b = np.zeros_like(cumprodX)
return [
np.tile(
np.repeat(np.asarray(com.values_from_object(x)), b[i]), np.product(a[i])
)
for i, x in enumerate(X)
] | def cartesian_product(X):
# if any factor is empty, the cartesian product is empty
b = np.zeros_like(cumprodX)
return [_tile_compat(np.repeat(x, b[i]), np.product(a[i])) for i, x in enumerate(X)]
def _tile_compat(arr, num: int):
"""
Index compat for np.tile.
Notes
-----
Does ... |
class TestPivotTable:
tm.assert_frame_equal(result, expected)
def test_pivot_integer_columns(self):
# caused by upstream bug in unstack
| class TestPivotTable:
tm.assert_frame_equal(result, expected)
def test_pivot_table_retains_tz(self):
dti = date_range("2016-01-01", periods=3, tz="Europe/Amsterdam")
df = DataFrame({"A": np.random.randn(3), "B": np.random.randn(3), "C": dti})
result = df.pivot_table(index=["B", "C"... |
class TestCartesianProduct:
tm.assert_index_equal(result1, expected1)
tm.assert_index_equal(result2, expected2)
def test_empty(self):
# product of empty factors
X = [[], [0, 1], []] | class TestCartesianProduct:
tm.assert_index_equal(result1, expected1)
tm.assert_index_equal(result2, expected2)
def test_tzaware_retained(self):
x = date_range("2000-01-01", periods=2, tz="US/Pacific")
y = np.array([3, 4])
result1, result2 = cartesian_product([x, y])
... |
def capfirst(x):
# Set up regular expressions
re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.S)
re_chars = re.compile(r'<.*?>|(.)', re.S)
re_tag = re.compile(r'<(/)?(\S+?)(?:(\s*/)|\s.*?)?>', re.S)
re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines
re_camel_case = re.compile(r'(((?<=[a-z])[A... | def capfirst(x):
# Set up regular expressions
re_words = re.compile(r'<[^>]+?>|([^<>\s]+)', re.S)
re_chars = re.compile(r'<[^>]+?>|(.)', re.S)
re_tag = re.compile(r'<(/)?(\S+?)(?:(\s*/)|\s.*?)?>', re.S)
re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines
re_camel_case = re.compile(r'(((?<=[a-z])[A-Z])|... |
class FunctionTests(SimpleTestCase):
def test_truncate2(self):
self.assertEqual(
truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 4),
'<p>one <a href="#">two - three <br>four ...</a></p>',
)
def test_truncate3(self):
self.assertEqual(
... | class FunctionTests(SimpleTestCase):
def test_truncate2(self):
self.assertEqual(
truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 4),
'<p>one <a href="#">two - three ...</a></p>',
)
def test_truncate3(self):
self.assertEqual(
... |
class TestUtilsText(SimpleTestCase):
# lazy strings are handled correctly
self.assertEqual(text.Truncator(lazystr('The quick brown fox')).chars(12), 'The quick...')
def test_truncate_words(self):
truncator = text.Truncator('The quick brown fox jumped over the lazy dog.')
self.assert... | class TestUtilsText(SimpleTestCase):
# lazy strings are handled correctly
self.assertEqual(text.Truncator(lazystr('The quick brown fox')).chars(12), 'The quick...')
def test_truncate_chars_html(self):
perf_test_values = [
(('</a' + '\t' * 50000) + '//>', None),
('&' ... |
class TestUtilsText(SimpleTestCase):
truncator = text.Truncator('<i>Buenos días! ¿Cómo está?</i>')
self.assertEqual('<i>Buenos días! ¿Cómo...</i>', truncator.words(3, '...', html=True))
truncator = text.Truncator('<p>I <3 python, what about you... | class TestUtilsText(SimpleTestCase):
truncator = text.Truncator('<i>Buenos días! ¿Cómo está?</i>')
self.assertEqual('<i>Buenos días! ¿Cómo...</i>', truncator.words(3, '...', html=True))
truncator = text.Truncator('<p>I <3 python, what about you... |
from django.db import NotSupportedError, transaction
from django.db.backends import utils
from django.utils import timezone
from django.utils.encoding import force_str
class BaseDatabaseOperations: | from django.db import NotSupportedError, transaction
from django.db.backends import utils
from django.utils import timezone
from django.utils.encoding import force_str
from django.utils.regex_helper import _lazy_re_compile
class BaseDatabaseOperations: |
class BaseDatabaseOperations:
# Prefix for EXPLAIN queries, or None EXPLAIN isn't supported.
explain_prefix = None
def __init__(self, connection):
self.connection = connection
self._cache = None | class BaseDatabaseOperations:
# Prefix for EXPLAIN queries, or None EXPLAIN isn't supported.
explain_prefix = None
extract_trunc_lookup_pattern = _lazy_re_compile(r"[\w\-_()]+")
def __init__(self, connection):
self.connection = connection
self._cache = None |
class Extract(TimezoneMixin, Transform):
super().__init__(expression, **extra)
def as_sql(self, compiler, connection):
sql, params = compiler.compile(self.lhs)
lhs_output_field = self.lhs.output_field
if isinstance(lhs_output_field, DateTimeField): | class Extract(TimezoneMixin, Transform):
super().__init__(expression, **extra)
def as_sql(self, compiler, connection):
if not connection.ops.extract_trunc_lookup_pattern.fullmatch(self.lookup_name):
raise ValueError("Invalid lookup_name: %s" % self.lookup_name)
sql, params = com... |
class TruncBase(TimezoneMixin, Transform):
super().__init__(expression, output_field=output_field, **extra)
def as_sql(self, compiler, connection):
inner_sql, inner_params = compiler.compile(self.lhs)
tzname = None
if isinstance(self.lhs.output_field, DateTimeField): | class TruncBase(TimezoneMixin, Transform):
super().__init__(expression, output_field=output_field, **extra)
def as_sql(self, compiler, connection):
if not connection.ops.extract_trunc_lookup_pattern.fullmatch(self.kind):
raise ValueError("Invalid kind: %s" % self.kind)
inner_sql... |
class DateFunctionTests(TestCase):
self.assertEqual(qs.count(), 1)
self.assertGreaterEqual(str(qs.query).lower().count('extract'), 2)
def test_extract_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 10, 50,... | class DateFunctionTests(TestCase):
self.assertEqual(qs.count(), 1)
self.assertGreaterEqual(str(qs.query).lower().count('extract'), 2)
def test_extract_lookup_name_sql_injection(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(201... |
class DateFunctionTests(TestCase):
)
self.assertEqual(DTModel.objects.filter(start_datetime__second=ExtractSecond('start_datetime')).count(), 2)
def test_trunc_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) | class DateFunctionTests(TestCase):
)
self.assertEqual(DTModel.objects.filter(start_datetime__second=ExtractSecond('start_datetime')).count(), 2)
def test_trunc_lookup_name_sql_injection(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 1... |
from cryptography.hazmat.primitives.ciphers import modes
class _CipherContext(object):
_ENCRYPT = 1
_DECRYPT = 0
_MAX_CHUNK_SIZE = 2 ** 31 - 1
def __init__(self, backend, cipher, mode, operation):
self._backend = backend | from cryptography.hazmat.primitives.ciphers import modes
class _CipherContext(object):
_ENCRYPT = 1
_DECRYPT = 0
_MAX_CHUNK_SIZE = 2 ** 30 - 1
def __init__(self, backend, cipher, mode, operation):
self._backend = backend |
class TestUtil(unittest.TestCase):
self.assertEqual(urljoin('http://foo.de/', ''), None)
self.assertEqual(urljoin('http://foo.de/', ['foobar']), None)
self.assertEqual(urljoin('http://foo.de/a/b/c.txt', '.././../d.txt'), 'http://foo.de/d.txt')
def test_url_or_none(self):
self.assert... | class TestUtil(unittest.TestCase):
self.assertEqual(urljoin('http://foo.de/', ''), None)
self.assertEqual(urljoin('http://foo.de/', ['foobar']), None)
self.assertEqual(urljoin('http://foo.de/a/b/c.txt', '.././../d.txt'), 'http://foo.de/d.txt')
self.assertEqual(urljoin('http://foo.de/a/b/... |
def urljoin(base, path):
path = path.decode('utf-8')
if not isinstance(path, compat_str) or not path:
return None
if re.match(r'^(?:https?:)?//', path):
return path
if isinstance(base, bytes):
base = base.decode('utf-8') | def urljoin(base, path):
path = path.decode('utf-8')
if not isinstance(path, compat_str) or not path:
return None
if re.match(r'^(?:[a-zA-Z][a-zA-Z0-9+-.]*:)?//', path):
return path
if isinstance(base, bytes):
base = base.decode('utf-8') |
except ImportError:
from gzip import GzipFile
import six
# - Python>=3.5 GzipFile's read() has issues returning leftover
# uncompressed data when input is corrupted | except ImportError:
from gzip import GzipFile
import six
import re
# - Python>=3.5 GzipFile's read() has issues returning leftover
# uncompressed data when input is corrupted |
def gunzip(data):
raise
return output
def is_gzipped(response):
"""Return True if the response is gzipped, or False otherwise"""
ctype = response.headers.get('Content-Type', b'')
return ctype in (b'application/x-gzip', b'application/gzip') | def gunzip(data):
raise
return output
_is_gzipped_re = re.compile(br'^application/(x-)?gzip\b', re.I)
def is_gzipped(response):
"""Return True if the response is gzipped, or False otherwise"""
ctype = response.headers.get('Content-Type', b'')
return _is_gzipped_re.search(ctype) is not ... |
import unittest
from os.path import join
from scrapy.utils.gz import gunzip
from tests import tests_datadir
SAMPLEDIR = join(tests_datadir, 'compressed') | import unittest
from os.path import join
from scrapy.utils.gz import gunzip, is_gzipped
from scrapy.http import Response, Headers
from tests import tests_datadir
SAMPLEDIR = join(tests_datadir, 'compressed') |
class GunzipTest(unittest.TestCase):
with open(join(SAMPLEDIR, 'truncated-crc-error-short.gz'), 'rb') as f:
text = gunzip(f.read())
assert text.endswith(b'</html>') | class GunzipTest(unittest.TestCase):
with open(join(SAMPLEDIR, 'truncated-crc-error-short.gz'), 'rb') as f:
text = gunzip(f.read())
assert text.endswith(b'</html>')
def test_is_x_gzipped_right(self):
hdrs = Headers({"Content-Type": "application/x-gzip"})
r1 = Respons... |
import stat
import tarfile
import zipfile
class ArchiveException(Exception):
""" | import stat
import tarfile
import zipfile
from django.core.exceptions import SuspiciousOperation
class ArchiveException(Exception):
""" |
class BaseArchive:
return False
return True
def extract(self):
raise NotImplementedError('subclasses of BaseArchive must provide an extract() method')
| class BaseArchive:
return False
return True
def target_filename(self, to_path, name):
target_path = os.path.abspath(to_path)
filename = os.path.abspath(os.path.join(target_path, name))
if not filename.startswith(target_path):
raise SuspiciousOperation("Ar... |
class TarArchive(BaseArchive):
name = member.name
if leading:
name = self.split_leading_dir(name)[1]
filename = os.path.join(to_path, name)
if member.isdir():
if filename and not os.path.exists(filename):
os.makedirs(fil... | class TarArchive(BaseArchive):
name = member.name
if leading:
name = self.split_leading_dir(name)[1]
filename = self.target_filename(to_path, name)
if member.isdir():
if filename and not os.path.exists(filename):
os.make... |
class ZipArchive(BaseArchive):
info = self._archive.getinfo(name)
if leading:
name = self.split_leading_dir(name)[1]
filename = os.path.join(to_path, name)
dirname = os.path.dirname(filename)
if dirname and not os.path.exists(dirname):
... | class ZipArchive(BaseArchive):
info = self._archive.getinfo(name)
if leading:
name = self.split_leading_dir(name)[1]
if not name:
continue
filename = self.target_filename(to_path, name)
dirname = os.path.dirname(filename)
... |
import sys
import tempfile
import unittest
from django.utils.archive import Archive, extract
TEST_DIR = os.path.join(os.path.dirname(__file__), 'archives') | import sys
import tempfile
import unittest
from django.core.exceptions import SuspiciousOperation
from django.test import SimpleTestCase
from django.utils.archive import Archive, extract
TEST_DIR = os.path.join(os.path.dirname(__file__), 'archives') |
class TestGzipTar(ArchiveTester, unittest.TestCase):
class TestBzip2Tar(ArchiveTester, unittest.TestCase):
archive = 'foobar.tar.bz2' | class TestGzipTar(ArchiveTester, unittest.TestCase):
class TestBzip2Tar(ArchiveTester, unittest.TestCase):
archive = 'foobar.tar.bz2'
class TestArchiveInvalid(SimpleTestCase):
def test_extract_function_traversal(self):
archives_dir = os.path.join(os.path.dirname(__file__), 'traversal_archives')
... |
class PKey(object):
:raises: ``IOError`` -- if there was an error writing the file.
"""
with open(filename, "w") as f:
os.chmod(filename, o600)
self._write_private_key(f, key, format, password=password)
| class PKey(object):
:raises: ``IOError`` -- if there was an error writing the file.
"""
# Ensure that we create new key files directly with a user-only mode,
# instead of opening, writing, then chmodding, which leaves us open to
# CVE-2022-24302.
# NOTE: O_TRUNC is a noo... |
Some unit tests for public/private key objects.
import unittest
import os
from binascii import hexlify
from hashlib import md5
| Some unit tests for public/private key objects.
import unittest
import os
import stat
from binascii import hexlify
from hashlib import md5
|
from paramiko import (
SSHException,
)
from paramiko.py3compat import StringIO, byte_chr, b, bytes, PY2
from cryptography.exceptions import UnsupportedAlgorithm
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateNumbers
from mock import patch
import pytest
from .util import _support, is_low_entro... | from paramiko import (
SSHException,
)
from paramiko.py3compat import StringIO, byte_chr, b, bytes, PY2
from paramiko.common import o600
from cryptography.exceptions import UnsupportedAlgorithm
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateNumbers
from mock import patch, Mock
import pytest
f... |
class KeyTest(unittest.TestCase):
key1.load_certificate,
_support("test_rsa.key-cert.pub"),
) | class KeyTest(unittest.TestCase):
key1.load_certificate,
_support("test_rsa.key-cert.pub"),
)
@patch("paramiko.pkey.os")
def _test_keyfile_race(self, os_, exists):
# Re: CVE-2022-24302
password = "television"
newpassword = "radio"
source = _suppor... |
def get_new_command(command):
def side_effect(old_cmd, command):
with tarfile.TarFile(_tar_file(old_cmd.script_parts)[0]) as archive:
for file in archive.getnames():
try:
os.remove(file)
except OSError: | def get_new_command(command):
def side_effect(old_cmd, command):
with tarfile.TarFile(_tar_file(old_cmd.script_parts)[0]) as archive:
for file in archive.getnames():
if not os.path.abspath(file).startswith(os.getcwd()):
# it's unsafe to overwrite files outside of the current dire... |
def get_new_command(command):
def side_effect(old_cmd, command):
with zipfile.ZipFile(_zip_file(old_cmd), 'r') as archive:
for file in archive.namelist():
try:
os.remove(file)
except OSError: | def get_new_command(command):
def side_effect(old_cmd, command):
with zipfile.ZipFile(_zip_file(old_cmd), 'r') as archive:
for file in archive.namelist():
if not os.path.abspath(file).startswith(os.getcwd()):
# it's unsafe to overwrite files outside of the current directory
... |
def _get_spider_loader(settings):
'Please use SPIDER_LOADER_CLASS.',
category=ScrapyDeprecationWarning, stacklevel=2
)
cls_path = settings.get('SPIDER_LOADER_CLASS',
settings.get('SPIDER_MANAGER_CLASS'))
loader_cls = load_object(cls_path)
verifyCla... | def _get_spider_loader(settings):
'Please use SPIDER_LOADER_CLASS.',
category=ScrapyDeprecationWarning, stacklevel=2
)
cls_path = settings.get('SPIDER_MANAGER_CLASS',
settings.get('SPIDER_LOADER_CLASS'))
loader_cls = load_object(cls_path)
verifyCla... |
from zope.interface.verify import DoesNotImplement
from scrapy.crawler import Crawler, CrawlerRunner
from scrapy.settings import Settings, default_settings
from scrapy.utils.spider import DefaultSpider
from scrapy.utils.misc import load_object
| from zope.interface.verify import DoesNotImplement
from scrapy.crawler import Crawler, CrawlerRunner
from scrapy.settings import Settings, default_settings
from scrapy.spiderloader import SpiderLoader
from scrapy.utils.spider import DefaultSpider
from scrapy.utils.misc import load_object
|
class SpiderLoaderWithWrongInterface(object):
pass
class CrawlerRunnerTestCase(unittest.TestCase):
def test_spider_manager_verify_interface(self): | class SpiderLoaderWithWrongInterface(object):
pass
class CustomSpiderLoader(SpiderLoader):
pass
class CrawlerRunnerTestCase(unittest.TestCase):
def test_spider_manager_verify_interface(self): |
class CrawlerRunnerTestCase(unittest.TestCase):
self.assertIn("CrawlerRunner.spider_loader", str(w[0].message))
sl_cls = load_object(runner.settings['SPIDER_LOADER_CLASS'])
self.assertIsInstance(spiders, sl_cls) | class CrawlerRunnerTestCase(unittest.TestCase):
self.assertIn("CrawlerRunner.spider_loader", str(w[0].message))
sl_cls = load_object(runner.settings['SPIDER_LOADER_CLASS'])
self.assertIsInstance(spiders, sl_cls)
def test_spidermanager_deprecation(self):
with warnings.cat... |
EXAMPLES = r'''
secured: '{{ item.secured }}'
state: present
with_items:
- { name: AWS_ACCESS_KEY, value: ABCD1234 }
- { name: AWS_SECRET, value: qwe789poi123vbn0, secured: True }
- name: Remove pipeline variable | EXAMPLES = r'''
secured: '{{ item.secured }}'
state: present
with_items:
- { name: AWS_ACCESS_KEY, value: ABCD1234, secured: False }
- { name: AWS_SECRET, value: qwe789poi123vbn0, secured: True }
- name: Remove pipeline variable |
EXAMPLES = r'''
RETURN = r''' # '''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.source_control.bitbucket import BitbucketHelper
error_messages = { | EXAMPLES = r'''
RETURN = r''' # '''
from ansible.module_utils.basic import AnsibleModule, _load_params
from ansible.module_utils.source_control.bitbucket import BitbucketHelper
error_messages = { |
def delete_pipeline_variable(module, bitbucket, variable_uuid):
))
def main():
argument_spec = BitbucketHelper.bitbucket_argument_spec()
argument_spec.update( | def delete_pipeline_variable(module, bitbucket, variable_uuid):
))
class BitBucketPipelineVariable(AnsibleModule):
def __init__(self, *args, **kwargs):
params = _load_params() or {}
if params.get('secured'):
kwargs['argument_spec']['value'].update({'no_log': True})
supe... |
def main():
secured=dict(type='bool', default=False),
state=dict(type='str', choices=['present', 'absent'], required=True),
)
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True,
) | def main():
secured=dict(type='bool', default=False),
state=dict(type='str', choices=['present', 'absent'], required=True),
)
module = BitBucketPipelineVariable(
argument_spec=argument_spec,
supports_check_mode=True,
) |
def _recursively_freeze(value):
"""
if isinstance(value, Mapping):
return _FrozenOrderedDict(((k, _recursively_freeze(v)) for k, v in value.items()))
elif isinstance(value, list):
return tuple(_recursively_freeze(v) for v in value)
return value
class DictParameter(Parameter):
"""
... | def _recursively_freeze(value):
"""
if isinstance(value, Mapping):
return _FrozenOrderedDict(((k, _recursively_freeze(v)) for k, v in value.items()))
elif isinstance(value, list) or isinstance(value, tuple):
return tuple(_recursively_freeze(v) for v in value)
return value
class _DictPa... |
class DictParameter(Parameter):
tags, that are dynamically constructed outside Luigi), or you have a complex parameter containing logically related
values (like a database connection config).
"""
class _DictParamEncoder(JSONEncoder):
"""
JSON encoder for :py:class:`~DictParameter`, whic... | class DictParameter(Parameter):
tags, that are dynamically constructed outside Luigi), or you have a complex parameter containing logically related
values (like a database connection config).
"""
def normalize(self, value):
"""
Ensure that dictionary parameter is converted to a _FrozenOr... |
class DictParameter(Parameter):
return json.loads(s, object_pairs_hook=_FrozenOrderedDict)
def serialize(self, x):
return json.dumps(x, cls=DictParameter._DictParamEncoder)
class ListParameter(Parameter): | class DictParameter(Parameter):
return json.loads(s, object_pairs_hook=_FrozenOrderedDict)
def serialize(self, x):
return json.dumps(x, cls=_DictParamEncoder)
class ListParameter(Parameter): |
class ListParameter(Parameter):
"""
def normalize(self, x):
"""
Ensure that list parameter is converted to a tuple so it can be hashed.
:param str x: the value to parse.
:return: the normalized (hashable/immutable) value. | class ListParameter(Parameter):
"""
def normalize(self, x):
"""
Ensure that struct is recursively converted to a tuple so it can be hashed.
:param str x: the value to parse.
:return: the normalized (hashable/immutable) value. |
class ListParameter(Parameter):
:param str x: the value to parse.
:return: the parsed value.
"""
return list(json.loads(x))
def serialize(self, x):
""" | class ListParameter(Parameter):
:param str x: the value to parse.
:return: the parsed value.
"""
return list(json.loads(x, object_pairs_hook=_FrozenOrderedDict))
def serialize(self, x):
""" |
class ListParameter(Parameter):
:param x: the value to serialize.
"""
return json.dumps(x)
class TupleParameter(Parameter):
"""
Parameter whose value is a ``tuple`` or ``tuple`` of tuples.
| class ListParameter(Parameter):
:param x: the value to serialize.
"""
return json.dumps(x, cls=_DictParamEncoder)
class TupleParameter(ListParameter):
"""
Parameter whose value is a ``tuple`` or ``tuple`` of tuples.
|
class TupleParameter(Parameter):
$ luigi --module my_tasks MyTask --book_locations '((12,3),(4,15),(52,1))'
"""
def parse(self, x):
"""
Parse an individual value from the input. | class TupleParameter(Parameter):
$ luigi --module my_tasks MyTask --book_locations '((12,3),(4,15),(52,1))'
"""
def parse(self, x):
"""
Parse an individual value from the input. |
class TupleParameter(Parameter):
# Therefore, if json.loads(x) returns a ValueError, try ast.literal_eval(x).
# ast.literal_eval(t_str) == t
try:
return tuple(tuple(x) for x in json.loads(x)) # loop required to parse tuple of tuples
except ValueError:
return lite... | class TupleParameter(Parameter):
# Therefore, if json.loads(x) returns a ValueError, try ast.literal_eval(x).
# ast.literal_eval(t_str) == t
try:
# loop required to parse tuple of tuples
return tuple(tuple(x) for x in json.loads(x, object_pairs_hook=_FrozenOrderedDict))
... |
class TestParametersHashability(LuigiTestCase):
p = luigi.parameter.ListParameter()
self.assertEqual(hash(Foo(args=[1, "hello"]).args), hash(p.normalize(p.parse('[1,"hello"]'))))
def test_tuple(self):
class Foo(luigi.Task):
args = luigi.parameter.TupleParameter() | class TestParametersHashability(LuigiTestCase):
p = luigi.parameter.ListParameter()
self.assertEqual(hash(Foo(args=[1, "hello"]).args), hash(p.normalize(p.parse('[1,"hello"]'))))
def test_list_dict(self):
class Foo(luigi.Task):
args = luigi.parameter.ListParameter()
p =... |
class TestParametersHashability(LuigiTestCase):
p = luigi.parameter.TupleParameter()
self.assertEqual(hash(Foo(args=(1, "hello")).args), hash(p.parse('(1,"hello")')))
def test_task(self):
class Bar(luigi.Task):
pass | class TestParametersHashability(LuigiTestCase):
p = luigi.parameter.TupleParameter()
self.assertEqual(hash(Foo(args=(1, "hello")).args), hash(p.parse('(1,"hello")')))
def test_tuple_dict(self):
class Foo(luigi.Task):
args = luigi.parameter.TupleParameter()
p = luigi.par... |
import re
import shlex
import pkgutil
import xml.etree.ElementTree as ET
from ansible.errors import AnsibleError
from ansible.module_utils._text import to_bytes, to_text | import re
import shlex
import pkgutil
import xml.etree.ElementTree as ET
import ntpath
from ansible.errors import AnsibleError
from ansible.module_utils._text import to_bytes, to_text |
class ShellModule(ShellBase):
return ""
def join_path(self, *args):
parts = []
for arg in args:
arg = self._unquote(arg).replace('/', '\\')
parts.extend([a for a in arg.split('\\') if a])
path = '\\'.join(parts)
if path.startswith('~'):
re... | class ShellModule(ShellBase):
return ""
def join_path(self, *args):
# use normpath() to remove doubled slashed and convert forward to backslashes
parts = [ntpath.normpath(self._unquote(arg)) for arg in args]
# Becuase ntpath.join treats any component that begins with a backslash as... |
from ansible.plugins.shell.powershell import _parse_clixml
def test_parse_clixml_empty(): | from ansible.plugins.shell.powershell import _parse_clixml, ShellModule
def test_parse_clixml_empty(): |
def test_parse_clixml_multiple_streams():
expected = b"hi info"
actual = _parse_clixml(multiple_stream, stream="Info")
assert actual == expected | def test_parse_clixml_multiple_streams():
expected = b"hi info"
actual = _parse_clixml(multiple_stream, stream="Info")
assert actual == expected
def test_join_path_unc():
pwsh = ShellModule()
unc_path_parts = ['\\\\host\\share\\dir1\\\\dir2\\', '\\dir3/dir4', 'dir5', 'dir6\\']
expected = '\\\\... |
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
try:
loc = self._get_string_slice(key)
return series[loc]
except (TypeError, ValueError):
pass
asdt, reso = parse_time_string(key, self.freq) | class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
try:
loc = self._get_string_slice(key)
return series[loc]
except (TypeError, ValueError, OverflowError):
pass
asdt, reso = parse_time_string(key, self.freq) |
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
"""
if isinstance(key, str):
try:
return self._get_string_slice(key)
except (TypeError, KeyError, ValueError, OverflowError):
pass
try:
asdt, r... | class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
"""
if isinstance(key, str):
try:
loc = self._get_string_slice(key)
return loc
except (TypeError, ValueError):
pass
try:
asdt,... |
class TestIndexing:
ps0 = [p0, p1, p2]
idx0 = pd.PeriodIndex(ps0)
for p in ps0:
assert p in idx0
assert str(p) in idx0
assert "2017-09-01 00:00:01" in idx0
assert "2017-09" in idx0
| class TestIndexing:
ps0 = [p0, p1, p2]
idx0 = pd.PeriodIndex(ps0)
ser = pd.Series(range(6, 9), index=idx0)
for p in ps0:
assert p in idx0
assert str(p) in idx0
# GH#31172
# Higher-resolution period-like are _not_ considered as contained
... |
class UrlParseTestCase(unittest.TestCase):
p = urllib.parse.urlsplit(url)
self.assertEqual(p.port, None)
def test_attributes_bad_port(self):
"""Check handling of non-integer ports."""
p = urllib.parse.urlsplit("http://www.example.net:foo") | class UrlParseTestCase(unittest.TestCase):
p = urllib.parse.urlsplit(url)
self.assertEqual(p.port, None)
def test_urlsplit_remove_unsafe_bytes(self):
# Remove ASCII tabs and newlines from input, for http common case scenario.
url = "h\nttp://www.python\n.org\t/java\nscript:\talert('... |
scheme_chars = ('abcdefghijklmnopqrstuvwxyz'
'0123456789'
'+-.')
# XXX: Consider replacing with functools.lru_cache
MAX_CACHE_SIZE = 20
_parse_cache = {} | scheme_chars = ('abcdefghijklmnopqrstuvwxyz'
'0123456789'
'+-.')
# Unsafe bytes to be removed per WHATWG spec
_UNSAFE_URL_BYTES_TO_REMOVE = ['\t', '\r', '\n']
# XXX: Consider replacing with functools.lru_cache
MAX_CACHE_SIZE = 20
_parse_cache = {} |
def _checknetloc(netloc):
raise ValueError("netloc '" + netloc2 + "' contains invalid " +
"characters under NFKC normalization")
def urlsplit(url, scheme='', allow_fragments=True):
"""Parse a URL into 5 components:
<scheme>://<netloc>/<path>?<query>#<fragment> | def _checknetloc(netloc):
raise ValueError("netloc '" + netloc2 + "' contains invalid " +
"characters under NFKC normalization")
def _remove_unsafe_bytes_from_url(url):
for b in _UNSAFE_URL_BYTES_TO_REMOVE:
url = url.replace(b, "")
return url
def urlsplit(url, ... |
def urlsplit(url, scheme='', allow_fragments=True):
Note that we don't break the components up in smaller bits
(e.g. netloc is a single string) and we don't expand % escapes."""
url, scheme, _coerce_result = _coerce_args(url, scheme)
allow_fragments = bool(allow_fragments)
key = url, scheme, allow_f... | def urlsplit(url, scheme='', allow_fragments=True):
Note that we don't break the components up in smaller bits
(e.g. netloc is a single string) and we don't expand % escapes."""
url, scheme, _coerce_result = _coerce_args(url, scheme)
url = _remove_unsafe_bytes_from_url(url)
scheme = _remove_unsafe_b... |
class DictTest(IronPythonTestCase):
x = str(d)
self.assertTrue(x.find("'abc'") != -1)
if is_cli:
self.assertTrue(x.find("'abc': <mappingproxy") != -1)
else:
self.assertTrue(x.find("'abc': mappingproxy") != -1)
del C.abc
keys, values = d.keys(), d... | class DictTest(IronPythonTestCase):
x = str(d)
self.assertTrue(x.find("'abc'") != -1)
self.assertTrue(x.find("'abc': mappingproxy") != -1)
del C.abc
keys, values = d.keys(), d.values() |
def test_not_match(command):
@pytest.mark.parametrize('command, output', [
(Command(script='git push', stderr=git_err), 'git push --force'),
(Command(script='git push nvbn', stderr=git_err), 'git push --force nvbn'),
(Command(script='git push nvbn master', stderr=git_err), 'git push --force nvbn master')]... | def test_not_match(command):
@pytest.mark.parametrize('command, output', [
(Command(script='git push', stderr=git_err), 'git push --force-with-lease'),
(Command(script='git push nvbn', stderr=git_err), 'git push --force-with-lease nvbn'),
(Command(script='git push nvbn master', stderr=git_err), 'git push ... |
def match(command):
@git_support
def get_new_command(command):
return replace_argument(command.script, 'push', 'push --force')
enabled_by_default = False | def match(command):
@git_support
def get_new_command(command):
return replace_argument(command.script, 'push', 'push --force-with-lease')
enabled_by_default = False |
def _get_grouper(
elif is_in_axis(gpr): # df.groupby('name')
if gpr in obj:
if validate:
obj._check_label_or_level_ambiguity(gpr)
in_axis, name, gpr = True, gpr, obj[gpr]
exclusions.append(name)
elif obj._is_level_refer... | def _get_grouper(
elif is_in_axis(gpr): # df.groupby('name')
if gpr in obj:
if validate:
obj._check_label_or_level_ambiguity(gpr, axis=axis)
in_axis, name, gpr = True, gpr, obj[gpr]
exclusions.append(name)
elif obj._is_... |
def test_groupby_groups_in_BaseGrouper():
result = df.groupby(["beta", pd.Grouper(level="alpha")])
expected = df.groupby(["beta", "alpha"])
assert result.groups == expected.groups | def test_groupby_groups_in_BaseGrouper():
result = df.groupby(["beta", pd.Grouper(level="alpha")])
expected = df.groupby(["beta", "alpha"])
assert result.groups == expected.groups
@pytest.mark.parametrize("group_name", ["x", ["x"]])
def test_groupby_axis_1(group_name):
# GH 27614
df = pd.DataFrame... |
class Functional(training_lib.Model):
than with subclassed `Model`s, specifically:
- Model cloning (`keras.models.clone`)
- Serialization (`model.get_config()/from_config`, `model.to_json()/to_yaml()`
- Whole-model saving (`model.save()`)
A `Functional` model can be instantiated by passing two arguments to | class Functional(training_lib.Model):
than with subclassed `Model`s, specifically:
- Model cloning (`keras.models.clone`)
- Serialization (`model.get_config()/from_config`, `model.to_json()`
- Whole-model saving (`model.save()`)
A `Functional` model can be instantiated by passing two arguments to |
from tensorflow.python.platform import test
from tensorflow.python.training.tracking.util import Checkpoint
try:
import yaml # pylint:disable=g-import-not-at-top
except ImportError:
yaml = None
class NetworkConstructionTest(keras_parameterized.TestCase):
| from tensorflow.python.platform import test
from tensorflow.python.training.tracking.util import Checkpoint
class NetworkConstructionTest(keras_parameterized.TestCase):
|
def test_multi_input_multi_output_recursion(self):
json_str = model.to_json()
models.model_from_json(json_str)
if yaml is not None:
yaml_str = model.to_yaml()
models.model_from_yaml(yaml_str)
@combinations.generate(combinations.combine(mode=['graph', 'eager']))
def test_invalid_g... | def test_multi_input_multi_output_recursion(self):
json_str = model.to_json()
models.model_from_json(json_str)
@combinations.generate(combinations.combine(mode=['graph', 'eager']))
def test_invalid_graphs(self):
a = layers.Input(shape=(32,), name='input_a') |
def test_constant_initializer_with_numpy(self):
json_str = model.to_json()
models.model_from_json(json_str)
if yaml is not None:
yaml_str = model.to_yaml()
models.model_from_yaml(yaml_str)
def test_subclassed_error_if_init_not_called(self):
class MyNetwork(training_lib.Model): | def test_constant_initializer_with_numpy(self):
json_str = model.to_json()
models.model_from_json(json_str)
def test_subclassed_error_if_init_not_called(self):
class MyNetwork(training_lib.Model): |
import h5py
except ImportError:
h5py = None
try:
import yaml
except ImportError:
yaml = None
# pylint: enable=g-import-not-at-top
| import h5py
except ImportError:
h5py = None
# pylint: enable=g-import-not-at-top
|
def to_json(self, **kwargs):
def to_yaml(self, **kwargs):
"""Returns a yaml string containing the network configuration.
To load a network from a yaml save file, use
`keras.models.model_from_yaml(yaml_string, custom_objects={})`.
| def to_json(self, **kwargs):
def to_yaml(self, **kwargs):
"""Returns a yaml string containing the network configuration.
Note: Since TF 2.6, this method is no longer supported and will raise a
RuntimeError.
To load a network from a yaml save file, use
`keras.models.model_from_yaml(yaml_string, c... |
def to_yaml(self, **kwargs):
A YAML string.
Raises:
ImportError: if yaml module is not found.
"""
if yaml is None:
raise ImportError(
'Requires yaml module installed (`pip install pyyaml`).')
return yaml.dump(self._updated_config(), **kwargs)
def reset_states(self):
... | def to_yaml(self, **kwargs):
A YAML string.
Raises:
RuntimeError: announces that the method poses a security risk
"""
raise RuntimeError(
'Method `model.to_yaml()` has been removed due to security risk of '
'arbitrary code execution. Please use `model.to_json()` instead.'
... |
from tensorflow.python.keras.saving.saved_model import json_utils
from tensorflow.python.util.tf_export import keras_export
# pylint: disable=g-import-not-at-top
try:
import yaml
except ImportError:
yaml = None
# pylint: enable=g-import-not-at-top
@keras_export('keras.models.model_from_config')
def model_from_co... | from tensorflow.python.keras.saving.saved_model import json_utils
from tensorflow.python.util.tf_export import keras_export
@keras_export('keras.models.model_from_config')
def model_from_config(config, custom_objects=None):
"""Instantiates a Keras model from its config.
Usage:
```
# for a Functional API mode... |
def model_from_config(config, custom_objects=None):
def model_from_yaml(yaml_string, custom_objects=None):
"""Parses a yaml model configuration file and returns a model instance.
Usage:
>>> model = tf.keras.Sequential([
... tf.keras.layers.Dense(5, input_shape=(3,)),
... tf.keras.layers.Softmax()])
... | def model_from_config(config, custom_objects=None):
def model_from_yaml(yaml_string, custom_objects=None):
"""Parses a yaml model configuration file and returns a model instance.
Note: Since TF 2.6, this method is no longer supported and will raise a
RuntimeError.
Args:
yaml_string: YAML string or open ... |
def model_from_yaml(yaml_string, custom_objects=None):
A Keras model instance (uncompiled).
Raises:
ImportError: if yaml module is not found.
"""
if yaml is None:
raise ImportError('Requires yaml module installed (`pip install pyyaml`).')
# The method unsafe_load only exists in PyYAML 5.x+, so ... | def model_from_yaml(yaml_string, custom_objects=None):
A Keras model instance (uncompiled).
Raises:
RuntimeError: announces that the method poses a security risk
"""
raise RuntimeError(
'Method `model_from_yaml()` has been removed due to security risk of '
'arbitrary code execution. Pleas... |
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 BaseMaskedArray(ExtensionArray, ExtensionOpsMixin):
def __len__(self) -> int:
return len(self._data)
def to_numpy(
self, dtype=None, copy=False, na_value: "Scalar" = lib.no_default,
): | class BaseMaskedArray(ExtensionArray, ExtensionOpsMixin):
def __len__(self) -> int:
return len(self._data)
def __invert__(self):
return type(self)(~self._data, self._mask)
def to_numpy(
self, dtype=None, copy=False, na_value: "Scalar" = lib.no_default,
): |
class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
# inv fails with 0 len
return self
arr = operator.inv(com.values_from_object(self))
return self.__array_wrap__(arr)
def __nonzero__(self):
raise ValueError( | class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
# inv fails with 0 len
return self
new_data = self._data.apply(operator.invert)
result = self._constructor(new_data).__finalize__(self)
return result
def __nonzero__(self):
raise ValueError... |
def check_bool_indexer(index: Index, key) -> np.ndarray:
result = result.astype(bool)._values
else:
if is_sparse(result):
result = result.to_dense()
result = check_bool_array_indexer(index, result)
return result | def check_bool_indexer(index: Index, key) -> np.ndarray:
result = result.astype(bool)._values
else:
if is_sparse(result):
result = np.asarray(result)
result = check_bool_array_indexer(index, result)
return result |
def test_invert(fill_value):
expected = SparseArray(~arr, fill_value=not fill_value)
tm.assert_sp_array_equal(result, expected)
@pytest.mark.parametrize("fill_value", [0, np.nan])
@pytest.mark.parametrize("op", [operator.pos, operator.neg]) | def test_invert(fill_value):
expected = SparseArray(~arr, fill_value=not fill_value)
tm.assert_sp_array_equal(result, expected)
result = ~pd.Series(sparray)
expected = pd.Series(expected)
tm.assert_series_equal(result, expected)
result = ~pd.DataFrame({"A": sparray})
expected = pd.DataFram... |
def test_ufunc_reduce_raises(values):
np.add.reduce(a)
class TestLogicalOps(BaseOpsUtil):
def test_numpy_scalars_ok(self, all_logical_operators):
a = pd.array([True, False, None], dtype="boolean") | def test_ufunc_reduce_raises(values):
np.add.reduce(a)
class TestUnaryOps:
def test_invert(self):
a = pd.array([True, False, None], dtype="boolean")
expected = pd.array([False, True, None], dtype="boolean")
tm.assert_extension_array_equal(~a, expected)
expected = pd.Series... |
from .interface import BaseInterfaceTests # noqa
from .io import BaseParsingTests # noqa
from .methods import BaseMethodsTests # noqa
from .missing import BaseMissingTests # noqa
from .ops import BaseArithmeticOpsTests, BaseComparisonOpsTests, BaseOpsUtil # noqa
from .printing import BasePrintingTests # noqa
from... | from .interface import BaseInterfaceTests # noqa
from .io import BaseParsingTests # noqa
from .methods import BaseMethodsTests # noqa
from .missing import BaseMissingTests # noqa
from .ops import ( # noqa
BaseArithmeticOpsTests,
BaseComparisonOpsTests,
BaseOpsUtil,
BaseUnaryOpsTests,
)
from .printi... |
class BaseComparisonOpsTests(BaseOpsUtil):
assert result is NotImplemented
else:
raise pytest.skip(f"{type(data).__name__} does not implement __eq__") | class BaseComparisonOpsTests(BaseOpsUtil):
assert result is NotImplemented
else:
raise pytest.skip(f"{type(data).__name__} does not implement __eq__")
class BaseUnaryOpsTests(BaseOpsUtil):
def test_invert(self, data):
s = pd.Series(data, name="name")
result = ~s
... |
class TestPrinting(base.BasePrintingTests):
pass
# TODO parsing not yet supported
# class TestParsing(base.BaseParsingTests):
# pass | class TestPrinting(base.BasePrintingTests):
pass
class TestUnaryOps(base.BaseUnaryOpsTests):
pass
# TODO parsing not yet supported
# class TestParsing(base.BaseParsingTests):
# pass |
class TestDataFrameUnaryOperators:
tm.assert_frame_equal(-(df < 0), ~(df < 0))
@pytest.mark.parametrize(
"df",
[ | class TestDataFrameUnaryOperators:
tm.assert_frame_equal(-(df < 0), ~(df < 0))
def test_invert_mixed(self):
shape = (10, 5)
df = pd.concat(
[
pd.DataFrame(np.zeros(shape, dtype="bool")),
pd.DataFrame(np.zeros(shape, dtype=int)),
],
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.