buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
class TestUtilsHttp(unittest.TestCase):
r'http://testserver\me:pass@example.com',
r'http://testserver\@example.com',
r'http:\\testserver\confirm\me@example.com',
'\n'):
self.assertFalse(http.is_safe_url(bad_url, ... | class TestUtilsHttp(unittest.TestCase):
r'http://testserver\me:pass@example.com',
r'http://testserver\@example.com',
r'http:\\testserver\confirm\me@example.com',
'http:999999999',
'ftp:9999999999',
... |
class TestUtilsHttp(unittest.TestCase):
'HTTPS://testserver/',
'//testserver/',
'http://testserver/confirm?email=me@example.com',
'/url%20with%20spaces/'):
self.assertTrue(http.is_safe_url(good_url, host='testserver'), "%s s... | class TestUtilsHttp(unittest.TestCase):
'HTTPS://testserver/',
'//testserver/',
'http://testserver/confirm?email=me@example.com',
'/url%20with%20spaces/',
'path/http:2222222222'):
self.assertTrue(http.is... |
class SimpleTaskState(object):
elif task.scheduler_disable_time is not None:
return
if new_status == FAILED and task.can_disable():
task.add_failure()
if task.has_excessive_failures():
task.scheduler_disable_time = time.time() | class SimpleTaskState(object):
elif task.scheduler_disable_time is not None:
return
if new_status == FAILED and task.can_disable() and task.status != DISABLED:
task.add_failure()
if task.has_excessive_failures():
task.scheduler_disable_time = ... |
class CentralPlannerTest(unittest.TestCase):
self.sch.add_task(worker=WORKER, task_id='A')
self.assertEqual(self.sch.get_work(worker=WORKER)['task_id'], 'A')
def test_disable_by_worker(self):
self.sch.add_task(worker=WORKER, task_id='A', status=DISABLED)
self.assertEqual(len(self.sc... | class CentralPlannerTest(unittest.TestCase):
self.sch.add_task(worker=WORKER, task_id='A')
self.assertEqual(self.sch.get_work(worker=WORKER)['task_id'], 'A')
def test_automatic_re_enable(self):
self.sch = CentralPlannerScheduler(disable_failures=2, disable_persist=100)
self.setTime(... |
ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
def test_dfxp2srt(self):
dfxp_data = '''<... | ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
self.assertEqual(parse_dfxp_time_expr('00:00:0... |
def parse_dfxp_time_expr(time_expr):
if mobj:
return float(mobj.group('time_offset'))
mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:\.\d+)?)$', time_expr)
if mobj:
return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3))
def srt_subtitles_timecode(seconds): | def parse_dfxp_time_expr(time_expr):
if mobj:
return float(mobj.group('time_offset'))
mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
if mobj:
return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
def srt_subtitles_timecod... |
class _AtIndexer(_ScalarAccessIndexer):
"can only have integer indexers"
)
else:
if is_integer(i) and not ax.holds_integer():
raise ValueError(
"At based indexing on an non-integer "
... | class _AtIndexer(_ScalarAccessIndexer):
"can only have integer indexers"
)
else:
if is_integer(i) and not (ax.holds_integer() or ax.is_floating()):
raise ValueError(
"At based indexing on an non-integer "... |
class TestFloat64Index(Numeric):
)
def test_lookups_datetimelike_values(self, vals):
# If we have datetime64 or timedelta64 values, make sure they are
# wrappped correctly
ser = pd.Series(vals, index=range(3, 6))
ser.index = ser.index.astype("float64")
| class TestFloat64Index(Numeric):
)
def test_lookups_datetimelike_values(self, vals):
# If we have datetime64 or timedelta64 values, make sure they are
# wrappped correctly GH#31163
ser = pd.Series(vals, index=range(3, 6))
ser.index = ser.index.astype("float64")
|
class TestFloat64Index(Numeric):
result = ser.at[4.0]
assert isinstance(result, type(expected)) and result == expected
# Note: ser.at[4] raises ValueError; TODO: should we make this match loc?
result = ser.iloc[1]
assert isinstance(result, type(expected)) and result == expected | class TestFloat64Index(Numeric):
result = ser.at[4.0]
assert isinstance(result, type(expected)) and result == expected
# GH#31329 .at[4] should cast to 4.0, matching .loc behavior
result = ser.at[4]
assert isinstance(result, type(expected)) and result == expected
result... |
class TestUtil(unittest.TestCase):
d = json.loads(stripped)
self.assertEqual(d, [{"id": "532cb", "x": 3}])
def test_uppercase_escape(self):
self.assertEqual(uppercase_escape('aä'), 'aä')
self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐') | class TestUtil(unittest.TestCase):
d = json.loads(stripped)
self.assertEqual(d, [{"id": "532cb", "x": 3}])
stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
d = json.loads(stripped)
self.assertEqual(d, {'STATUS': 'OK'})
def test_uppercase_escape(self):
... |
from ..utils import (
unified_strdate,
parse_duration,
qualities,
url_basename,
)
| from ..utils import (
unified_strdate,
parse_duration,
qualities,
strip_jsonp,
url_basename,
)
|
class NPOIE(InfoExtractor):
'http://e.omroep.nl/metadata/aflevering/%s' % video_id,
video_id,
# We have to remove the javascript callback
transform_source=lambda j: re.sub(r'parseMetadata\((.*?)\);\n//.*$', r'\1', j)
)
token_page = self._download_webpage(
... | class NPOIE(InfoExtractor):
'http://e.omroep.nl/metadata/aflevering/%s' % video_id,
video_id,
# We have to remove the javascript callback
transform_source=strip_jsonp,
)
token_page = self._download_webpage(
'http://ida.omroep.nl/npoplayer/i.js'... |
def parse_age_limit(s):
def strip_jsonp(code):
return re.sub(r'(?s)^[a-zA-Z0-9_]+\s*\(\s*(.*)\);?\s*?\s*$', r'\1', code)
def js_to_json(code): | def parse_age_limit(s):
def strip_jsonp(code):
return re.sub(
r'(?s)^[a-zA-Z0-9_]+\s*\(\s*(.*)\);?\s*?(?://[^\n]*)*$', r'\1', code)
def js_to_json(code): |
class BracketTracker:
bracket_match: Dict[Tuple[Depth, NodeType], Leaf] = Factory(dict)
delimiters: Dict[LeafID, Priority] = Factory(dict)
previous: Optional[Leaf] = None
_for_loop_variable: int = 0
_lambda_arguments: int = 0
def mark(self, leaf: Leaf) -> None:
"""Mark `leaf` with brack... | class BracketTracker:
bracket_match: Dict[Tuple[Depth, NodeType], Leaf] = Factory(dict)
delimiters: Dict[LeafID, Priority] = Factory(dict)
previous: Optional[Leaf] = None
_for_loop_depths: List[int] = Factory(list)
_lambda_argument_depths: List[int] = Factory(list)
def mark(self, leaf: Leaf) ->... |
class BracketTracker:
"""
if leaf.type == token.NAME and leaf.value == "for":
self.depth += 1
self._for_loop_variable += 1
return True
return False
def maybe_decrement_after_for_loop_variable(self, leaf: Leaf) -> bool:
"""See `maybe_increment_for... | class BracketTracker:
"""
if leaf.type == token.NAME and leaf.value == "for":
self.depth += 1
self._for_loop_depths.append(self.depth)
return True
return False
def maybe_decrement_after_for_loop_variable(self, leaf: Leaf) -> bool:
"""See `maybe_i... |
class BracketTracker:
"""
if leaf.type == token.NAME and leaf.value == "lambda":
self.depth += 1
self._lambda_arguments += 1
return True
return False
def maybe_decrement_after_lambda_arguments(self, leaf: Leaf) -> bool:
"""See `maybe_increment_la... | class BracketTracker:
"""
if leaf.type == token.NAME and leaf.value == "lambda":
self.depth += 1
self._lambda_argument_depths.append(self.depth)
return True
return False
def maybe_decrement_after_lambda_arguments(self, leaf: Leaf) -> bool:
"""See... |
class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, line_length=ll)
def test_report_verbose(self) -> None:
report = black.Report(verbose=True)
out_lines = [] | class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, line_length=ll)
@patch("black.dump_to_file", dump_to_stderr)
def test_bracket_match(self) -> None:
source, expected = read_data("bracketmatch")
actual = fs(source)... |
class tqdm(object):
# Format left/right sides of the bar, and format the bar
# later in the remaining space (avoid breaking display)
l_bar_user, r_bar_user = bar_format.split('{bar}')
l_bar, r_bar = l_bar.format(**bar_args), r_bar.format(**... | class tqdm(object):
# Format left/right sides of the bar, and format the bar
# later in the remaining space (avoid breaking display)
l_bar_user, r_bar_user = bar_format.split('{bar}')
l_bar, r_bar = l_bar_user.format(**bar_args), r_bar_user... |
def test_format_meter():
"100KiB [00:13, 7.69KiB/s]"
assert format_meter(100, 1000, 12, ncols=0, rate=7.33) == \
" 10% 100/1000 [00:12<02:02, 7.33it/s]"
assert format_meter(20, 100, 12, ncols=30, rate=8.1,
bar_format=r'{l_bar}{bar}|{n_fmt}/{total_fmt}') == \
" 20... | def test_format_meter():
"100KiB [00:13, 7.69KiB/s]"
assert format_meter(100, 1000, 12, ncols=0, rate=7.33) == \
" 10% 100/1000 [00:12<02:02, 7.33it/s]"
# Check that bar_format correctly adapts {bar} size to the rest
assert format_meter(20, 100, 12, ncols=13, rate=8.1,
... |
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 GalaxyCLI(CLI):
''' create an options parser for bin/ansible '''
super(GalaxyCLI, self).init_parser(
desc="Perform various Role related operations.",
)
# common | class GalaxyCLI(CLI):
''' create an options parser for bin/ansible '''
super(GalaxyCLI, self).init_parser(
desc="Perform various Role and Collection related operations.",
)
# common |
class GalaxyCLI(CLI):
obj_name = context.CLIARGS['{0}_name'.format(galaxy_type)]
inject_data = dict(
description='your description',
ansible_plugin_list_dir=get_versioned_doclink('plugins/plugins.html'),
)
if galaxy_type == 'role': | class GalaxyCLI(CLI):
obj_name = context.CLIARGS['{0}_name'.format(galaxy_type)]
inject_data = dict(
description='your {0} description'.format(galaxy_type),
ansible_plugin_list_dir=get_versioned_doclink('plugins/plugins.html'),
)
if galaxy_type == 'role': |
class GalaxyCLI(CLI):
if not os.path.exists(b_dir_path):
os.makedirs(b_dir_path)
display.display("- %s was created successfully" % obj_name)
def execute_info(self):
""" | class GalaxyCLI(CLI):
if not os.path.exists(b_dir_path):
os.makedirs(b_dir_path)
display.display("- %s %s was created successfully" % (galaxy_type.title(), obj_name))
def execute_info(self):
""" |
def test_collection_default(collection_skeleton):
assert metadata['authors'] == ['your name <example@domain.com>']
assert metadata['readme'] == 'README.md'
assert metadata['version'] == '1.0.0'
assert metadata['description'] == 'your description'
assert metadata['license'] == ['GPL-2.0-or-later']
... | def test_collection_default(collection_skeleton):
assert metadata['authors'] == ['your name <example@domain.com>']
assert metadata['readme'] == 'README.md'
assert metadata['version'] == '1.0.0'
assert metadata['description'] == 'your collection description'
assert metadata['license'] == ['GPL-2.0-or... |
def test_collection_build(collection_artifact):
assert coll_info['authors'] == ['your name <example@domain.com>']
assert coll_info['readme'] == 'README.md'
assert coll_info['tags'] == []
assert coll_info['description'] == 'your description'
assert coll_info['license'] == ['GPL-2.... | def test_collection_build(collection_artifact):
assert coll_info['authors'] == ['your name <example@domain.com>']
assert coll_info['readme'] == 'README.md'
assert coll_info['tags'] == []
assert coll_info['description'] == 'your collection description'
assert coll_info['license'] ... |
class URLValidator(RegexValidator):
r'\Z', re.IGNORECASE)
message = _('Enter a valid URL.')
schemes = ['http', 'https', 'ftp', 'ftps']
def __init__(self, schemes=None, **kwargs):
super().__init__(**kwargs) | class URLValidator(RegexValidator):
r'\Z', re.IGNORECASE)
message = _('Enter a valid URL.')
schemes = ['http', 'https', 'ftp', 'ftps']
unsafe_chars = frozenset('\t\r\n')
def __init__(self, schemes=None, **kwargs):
super().__init__(**kwargs) |
class URLValidator(RegexValidator):
self.schemes = schemes
def __call__(self, value):
# Check first if the scheme is valid
scheme = value.split('://')[0].lower()
if scheme not in self.schemes:
raise ValidationError(self.message, code=self.code) | class URLValidator(RegexValidator):
self.schemes = schemes
def __call__(self, value):
if isinstance(value, str) and self.unsafe_chars.intersection(value):
raise ValidationError(self.message, code=self.code)
# Check if the scheme is valid.
scheme = value.split('://')[... |
TEST_DATA = [
(URLValidator(EXTENDED_SCHEMES), 'git+ssh://git@github.com/example/hg-git.git', None),
(URLValidator(EXTENDED_SCHEMES), 'git://-invalid.com', ValidationError),
# Trailing newlines not accepted
(URLValidator(), 'http://www.djangoproject.com/\n', ValidationError),
(URLValidator(), 'http... | TEST_DATA = [
(URLValidator(EXTENDED_SCHEMES), 'git+ssh://git@github.com/example/hg-git.git', None),
(URLValidator(EXTENDED_SCHEMES), 'git://-invalid.com', ValidationError),
# Newlines and tabs are not accepted.
(URLValidator(), 'http://www.djangoproject.com/\n', ValidationError),
(URLValidator(), ... |
class ResponseTypes(object):
def from_content_disposition(self, content_disposition):
try:
filename = to_native_str(content_disposition).split(';')[1].split('=')[1]
filename = filename.strip('"\'')
return self.from_filename(filename)
except IndexError: | class ResponseTypes(object):
def from_content_disposition(self, content_disposition):
try:
filename = to_native_str(content_disposition,
encoding='latin-1', errors='replace').split(';')[1].split('=')[1]
filename = filename.strip('"\'')
return self.from_fi... |
import unittest
from scrapy.responsetypes import responsetypes
| # -*- coding: utf-8 -*-
import unittest
from scrapy.responsetypes import responsetypes
|
class ResponseTypesTest(unittest.TestCase):
def test_from_content_disposition(self):
mappings = [
('attachment; filename="data.xml"', XmlResponse),
('attachment; filename=data.xml', XmlResponse),
]
for source, cls in mappings:
retcls = responsetypes.from_... | class ResponseTypesTest(unittest.TestCase):
def test_from_content_disposition(self):
mappings = [
(b'attachment; filename="data.xml"', XmlResponse),
(b'attachment; filename=data.xml', XmlResponse),
(u'attachment;filename=data£.tar.gz'.encode('utf-8'), Response),
... |
class InlineParser(ScannerParser):
#: _emphasis_ __strong__
ASTERISK_EMPHASIS = (
r'(\*{1,2})(?=[^\s*])('
r'(?:\\[\\*]|[^*])*'
r'(?:' + ESCAPE_TEXT + r'|[^\s*]))\1'
)
UNDERSCORE_EMPHASIS = (
r'\b(_{1,2})(?=[^\s_])([\s\S]*?' | class InlineParser(ScannerParser):
#: _emphasis_ __strong__
ASTERISK_EMPHASIS = (
r'(\*{1,2})(?=[^\s*])('
r'(?:(?:(?<!\\)(?:\\\\)*\*)|[^*])+'
r')(?<!\\)\1'
)
UNDERSCORE_EMPHASIS = (
r'\b(_{1,2})(?=[^\s_])([\s\S]*?' |
if __name__ == "__main__":
if os.path.exists('/tmp/bar'):
shutil.rmtree('/tmp/bar')
luigi.run(['--task', 'examples.Foo', '--workers', '2', '--local-scheduler']) | if __name__ == "__main__":
if os.path.exists('/tmp/bar'):
shutil.rmtree('/tmp/bar')
luigi.run(['examples.Foo', '--workers', '2', '--local-scheduler']) |
def run(cmdline_args=None, main_task_cls=None,
:param use_dynamic_argparse:
:param local_scheduler:
"""
if use_dynamic_argparse:
interface = DynamicArgParseInterface()
else: | def run(cmdline_args=None, main_task_cls=None,
:param use_dynamic_argparse:
:param local_scheduler:
"""
if cmdline_args is None:
cmdline_args = sys.argv[1:]
if use_dynamic_argparse:
interface = DynamicArgParseInterface()
else: |
from helpers import unittest
import luigi
import luigi.date_interval
import luigi.notifications
from luigi.interface import core, Interface, WorkerSchedulerFactory
from luigi.worker import Worker
from mock import Mock
luigi.notifications.DEBUG = True
class InterfaceTest(unittest.TestCase):
def setUp(self):
... | from helpers import unittest
import luigi
import luigi.date_interval
import luigi.notifications
import sys
from luigi.interface import core, Interface, WorkerSchedulerFactory
from luigi.worker import Worker
from mock import Mock, patch
from helpers import LuigiTestCase
luigi.notifications.DEBUG = True
class Interfac... |
class InterfaceTest(unittest.TestCase):
self.worker_scheduler_factory = WorkerSchedulerFactory()
self.worker_scheduler_factory.create_worker = Mock(return_value=self.worker)
self.worker_scheduler_factory.create_local_scheduler = Mock()
class NoOpTask(luigi.Task):
param = lui... | class InterfaceTest(unittest.TestCase):
self.worker_scheduler_factory = WorkerSchedulerFactory()
self.worker_scheduler_factory.create_worker = Mock(return_value=self.worker)
self.worker_scheduler_factory.create_local_scheduler = Mock()
super(InterfaceTest, self).setUp()
class No... |
class InterfaceTest(unittest.TestCase):
self.assertFalse(self._run_interface())
def _run_interface(self):
return Interface.run([self.task_a, self.task_b], self.worker_scheduler_factory, {'no_lock': True})
| class InterfaceTest(unittest.TestCase):
self.assertFalse(self._run_interface())
def test_just_run_main_task_cls(self):
class MyTestTask(luigi.Task):
pass
class MyOtherTestTask(luigi.Task):
my_param = luigi.Parameter()
with patch.object(sys, 'argv', ['my_mo... |
import os
# Import salt libs
import salt.utils.files
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six | import os
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.verify
# Import 3rd-party libs
from salt.ext import six |
def write(data, path, saltenv="base", index=0):
return (
"The path passed in {0} is not relative to the environment " "{1}"
).format(path, saltenv)
dest = os.path.join(__opts__["pillar_roots"][saltenv][index], path)
dest_dir = os.path.dirname(dest)
if not os.path.isdir(dest_dir): | def write(data, path, saltenv="base", index=0):
return (
"The path passed in {0} is not relative to the environment " "{1}"
).format(path, saltenv)
roots_dir = __opts__["pillar_roots"][saltenv][index]
dest = os.path.join(roots_dir, path)
if not salt.utils.verify.clean_path(roots_... |
def debug_build(program):
program = os.path.basename(program)
name = os.path.splitext(program)[0]
return name.endswith("_d")
def remove_python_envvars(): | def debug_build(program):
program = os.path.basename(program)
name = os.path.splitext(program)[0]
return name.casefold().endswith("_d".casefold())
def remove_python_envvars(): |
def get_expected_config(self, expected_preconfig, expected, env, api,
if expected['stdio_errors'] is self.GET_DEFAULT_CONFIG:
expected['stdio_errors'] = 'surrogateescape'
if sys.platform == 'win32':
default_executable = self.test_exe
elif expected['program_name']... | def get_expected_config(self, expected_preconfig, expected, env, api,
if expected['stdio_errors'] is self.GET_DEFAULT_CONFIG:
expected['stdio_errors'] = 'surrogateescape'
if MS_WINDOWS:
default_executable = self.test_exe
elif expected['program_name'] is not self.... |
def check_pre_config(self, configs, expected):
pre_config = dict(configs['pre_config'])
for key, value in list(expected.items()):
if value is self.IGNORE_CONFIG:
del pre_config[key]
del expected[key]
self.assertEqual(pre_config, expected)
| def check_pre_config(self, configs, expected):
pre_config = dict(configs['pre_config'])
for key, value in list(expected.items()):
if value is self.IGNORE_CONFIG:
pre_config.pop(key, None)
del expected[key]
self.assertEqual(pre_config, expected)
|
def check_config(self, configs, expected):
config = dict(configs['config'])
for key, value in list(expected.items()):
if value is self.IGNORE_CONFIG:
del config[key]
del expected[key]
self.assertEqual(config, expected)
| def check_config(self, configs, expected):
config = dict(configs['config'])
for key, value in list(expected.items()):
if value is self.IGNORE_CONFIG:
config.pop(key, None)
del expected[key]
self.assertEqual(config, expected)
|
def check_all_configs(self, testname, expected_config=None,
self.check_pre_config(configs, expected_preconfig)
self.check_config(configs, expected_config)
self.check_global_config(configs)
def test_init_default_config(self):
self.check_all_configs("test_init_initialize_config", api=... | def check_all_configs(self, testname, expected_config=None,
self.check_pre_config(configs, expected_preconfig)
self.check_config(configs, expected_config)
self.check_global_config(configs)
return configs
def test_init_default_config(self):
self.check_all_configs("test_init_i... |
def test_init_setpath(self):
}
self.default_program_name(config)
env = {'TESTPATH': os.path.pathsep.join(paths)}
self.check_all_configs("test_init_setpath", config,
api=API_COMPAT, env=env,
ignore_stderr=True) | def test_init_setpath(self):
}
self.default_program_name(config)
env = {'TESTPATH': os.path.pathsep.join(paths)}
self.check_all_configs("test_init_setpath", config,
api=API_COMPAT, env=env,
ignore_stderr=True) |
def tmpdir_with_python(self):
# Copy pythonXY.dll (or pythonXY_d.dll)
ver = sys.version_info
dll = f'python{ver.major}{ver.minor}'
if debug_build(sys.executable):
dll += '_d'
dll += '.dll'
dll = os.path.j... | def tmpdir_with_python(self):
# Copy pythonXY.dll (or pythonXY_d.dll)
ver = sys.version_info
dll = f'python{ver.major}{ver.minor}'
dll3 = f'python{ver.major}'
if debug_build(sys.executable):
dll += '_d'
... |
def test_init_pyvenv_cfg(self):
config['base_prefix'] = pyvenv_home
config['prefix'] = pyvenv_home
env = self.copy_paths_by_env(config)
self.check_all_configs("test_init_compat_config", config,
api=API_COMPAT, env=env,
... | def test_init_pyvenv_cfg(self):
config['base_prefix'] = pyvenv_home
config['prefix'] = pyvenv_home
env = self.copy_paths_by_env(config)
actual = self.check_all_configs("test_init_compat_config", config,
api=API_COMPAT, e... |
class LoadAuth(object):
if rm_tok:
self.rm_token(tok)
return tdata
| class LoadAuth(object):
if rm_tok:
self.rm_token(tok)
return {}
return tdata
|
def interpolate_1d(
inds = lib.maybe_convert_objects(inds)
else:
inds = xvalues
result[invalid] = np.interp(inds[invalid], inds[valid], yvalues[valid])
result[preserve_nans] = np.nan
return result
| def interpolate_1d(
inds = lib.maybe_convert_objects(inds)
else:
inds = xvalues
# np.interp requires sorted X values, #21037
indexer = np.argsort(inds[valid])
result[invalid] = np.interp(
inds[invalid], inds[valid][indexer], yvalues[valid][indexer]... |
class TestSeriesInterpolateData:
pytest.skip(
"This interpolation method is not supported for Timedelta Index yet."
) | class TestSeriesInterpolateData:
pytest.skip(
"This interpolation method is not supported for Timedelta Index yet."
)
@pytest.mark.parametrize(
"ascending, expected_values",
[(True, [1, 2, 3, 9, 10]), (False, [10, 9, 3, 2, 1])],
)
def test_interpolate... |
class TestUtil(unittest.TestCase):
def test_str_to_int(self):
self.assertEqual(str_to_int('123,456'), 123456)
self.assertEqual(str_to_int('123.456'), 123456)
def test_url_basename(self):
self.assertEqual(url_basename('http://foo.de/'), '') | class TestUtil(unittest.TestCase):
def test_str_to_int(self):
self.assertEqual(str_to_int('123,456'), 123456)
self.assertEqual(str_to_int('123.456'), 123456)
self.assertEqual(str_to_int(523), 523)
def test_url_basename(self):
self.assertEqual(url_basename('http://foo.de/'), '') |
def str_or_none(v, default=None):
def str_to_int(int_str):
""" A more relaxed version of int_or_none """
if int_str is None:
return None
int_str = re.sub(r'[,\.\+]', '', int_str)
return int(int_str)
| def str_or_none(v, default=None):
def str_to_int(int_str):
""" A more relaxed version of int_or_none """
if not isinstance(int_str, compat_str):
return int_str
int_str = re.sub(r'[,\.\+]', '', int_str)
return int(int_str)
|
class TestFormatSelection(unittest.TestCase):
downloaded = ydl.downloaded_info_dicts[0]
self.assertEqual(downloaded['format_id'], '38')
info_dict = _make_result(list(formats_order), extractor='youtube')
ydl = YDL({'format': '(bestvideo[ext=mp4],bestvideo[ext=webm])+bestaudio'})
... | class TestFormatSelection(unittest.TestCase):
downloaded = ydl.downloaded_info_dicts[0]
self.assertEqual(downloaded['format_id'], '38')
info_dict = _make_result(list(formats_order), extractor='youtube')
ydl = YDL({'format': 'bestvideo/best,bestaudio'})
yie = YoutubeIE(ydl)
... |
class YoutubeDL(object):
elif string == '/':
first_choice = current_selector
second_choice = _parse_format_selection(tokens, inside_choice=True)
current_selector = None
selectors.append(FormatSelector(PIC... | class YoutubeDL(object):
elif string == '/':
first_choice = current_selector
second_choice = _parse_format_selection(tokens, inside_choice=True)
current_selector = FormatSelector(PICKFIRST, (first_choice, second_choice), [])
... |
options:
description:
- Whether to disable the GPG checking of signatures of packages being
installed. Has an effect only if state is I(present) or I(latest).
type: bool
default: 'no'
| options:
description:
- Whether to disable the GPG checking of signatures of packages being
installed. Has an effect only if state is I(present) or I(latest).
- This setting affects packages installed from a repository as well as
"local" packages installed from the filesystem or a URL.
... |
class DnfModule(YumDnf):
results=[],
)
if self.download_only:
for package in self.base.transaction.install_set:
response['results'].append("Downloaded: {0}".format(package)) | class DnfModule(YumDnf):
results=[],
)
# Validate GPG. This is NOT done in dnf.Base (it's done in the
# upstream CLI subclass of dnf.Base)
if not self.disable_gpg_check:
for package in self.base.transaction.... |
class RadialLocator(mticker.Locator):
:class:`~matplotlib.ticker.Locator` (which may be different
depending on the scale of the *r*-axis.
"""
def __init__(self, base, axes=None):
self.base = base
self._axes = axes | class RadialLocator(mticker.Locator):
:class:`~matplotlib.ticker.Locator` (which may be different
depending on the scale of the *r*-axis.
"""
def __init__(self, base, axes=None):
self.base = base
self._axes = axes |
class RadialLocator(mticker.Locator):
# docstring inherited
return self.base.refresh()
def view_limits(self, vmin, vmax):
vmin, vmax = self.base.view_limits(vmin, vmax)
if vmax > vmin: | class RadialLocator(mticker.Locator):
# docstring inherited
return self.base.refresh()
def nonsingular(self, vmin, vmax):
# docstring inherited
return ((0, 1) if (vmin, vmax) == (-np.inf, np.inf) # Init. limits.
else self.base.nonsingular(vmin, vmax))
def view_... |
def test_log_scales_invalid():
ax.set_ylim(-1, 10)
@image_comparison(['stackplot_test_image', 'stackplot_test_image'])
def test_stackplot():
fig = plt.figure() | def test_log_scales_invalid():
ax.set_ylim(-1, 10)
def test_polar_no_data():
plt.subplot(projection="polar")
ax = plt.gca()
assert ax.get_rmin() == 0 and ax.get_rmax() == 1
plt.close("all")
# Used to behave differently (by triggering an autoscale with no data).
plt.polar()
ax = plt... |
from ..packages import six, rfc3986
from ..packages.rfc3986.exceptions import RFC3986Exception, ValidationError
from ..packages.rfc3986.validators import Validator
url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'] | from ..packages import six, rfc3986
from ..packages.rfc3986.exceptions import RFC3986Exception, ValidationError
from ..packages.rfc3986.validators import Validator
from ..packages.rfc3986 import abnf_regexp, normalizers, compat, misc
url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'] |
# Regex for detecting URLs with schemes. RFC 3986 Section 3.1
SCHEME_REGEX = re.compile(r"^(?:[a-zA-Z][a-zA-Z0-9+\-]*:|/)")
class Url(namedtuple('Url', url_attrs)):
""" | # Regex for detecting URLs with schemes. RFC 3986 Section 3.1
SCHEME_REGEX = re.compile(r"^(?:[a-zA-Z][a-zA-Z0-9+\-]*:|/)")
PATH_CHARS = abnf_regexp.UNRESERVED_CHARS_SET | abnf_regexp.SUB_DELIMITERS_SET | {':', '@', '/'}
QUERY_CHARS = FRAGMENT_CHARS = PATH_CHARS | {'?'}
class Url(namedtuple('Url', url_attrs)):
"... |
def split_first(s, delims):
return s[:min_idx], s[min_idx + 1:], min_delim
def parse_url(url):
"""
Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is | def split_first(s, delims):
return s[:min_idx], s[min_idx + 1:], min_delim
def _encode_invalid_chars(component, allowed_chars, encoding='utf-8'):
"""Percent-encodes a URI component without reapplying
onto an already percent-encoded component. Based on
rfc3986.normalizers.encode_component()
"""
... |
def parse_url(url):
return Url()
is_string = not isinstance(url, six.binary_type)
if not is_string:
url = url.decode("utf-8")
# RFC 3986 doesn't like URLs that have a host but don't start
# with a scheme and we support URLs like that so we need to | def parse_url(url):
return Url()
is_string = not isinstance(url, six.binary_type)
# RFC 3986 doesn't like URLs that have a host but don't start
# with a scheme and we support URLs like that so we need to |
def parse_url(url):
if not SCHEME_REGEX.search(url):
url = "//" + url
try:
iri_ref = rfc3986.IRIReference.from_string(url, encoding="utf-8")
except (ValueError, RFC3986Exception):
six.raise_from(LocationParseError(url), None)
def idna_encode(name):
if name and any([ord(... | def parse_url(url):
if not SCHEME_REGEX.search(url):
url = "//" + url
def idna_encode(name):
if name and any([ord(x) > 128 for x in name]):
try: |
def idna_encode(name):
raise LocationParseError(u"Name '%s' is not a valid IDNA label" % name)
return name
has_authority = iri_ref.authority is not None
uri_ref = iri_ref.encode(idna_encoder=idna_encode)
# rfc3986 strips the authority if it's invalid
if has_authority and uri_re... | def idna_encode(name):
raise LocationParseError(u"Name '%s' is not a valid IDNA label" % name)
return name
try:
split_iri = misc.IRI_MATCHER.match(compat.to_str(url)).groupdict()
iri_ref = rfc3986.IRIReference(
split_iri['scheme'], split_iri['authority'],
... |
def idna_encode(name):
*validator.COMPONENT_NAMES
).validate(uri_ref)
except ValidationError:
six.raise_from(LocationParseError(url), None)
# For the sake of backwards compatibility we put empty
# string values for path if there are any defined values | def idna_encode(name):
*validator.COMPONENT_NAMES
).validate(uri_ref)
except ValidationError:
return six.raise_from(LocationParseError(url), None)
# For the sake of backwards compatibility we put empty
# string values for path if there are any defined values |
def test_invalid_host(self, location):
'http://user\\@google.com',
'http://google\\.com',
'user\\@google.com',
'http://google.com#fragment#',
'http://user@user@google.com/',
])
def test_invalid_url(self, url):
with pytest.raises(LocationParseError): | def test_invalid_host(self, location):
'http://user\\@google.com',
'http://google\\.com',
'user\\@google.com',
'http://user@user@google.com/',
# Invalid IDNA labels
u'http://\uD7FF.com',
u'http://❤️',
# Unicode surrogates
u'http://\uD800.com',
... |
def test_invalid_url(self, url):
('HTTPS://Example.Com/?Key=Value', 'https://example.com/?Key=Value'),
('Https://Example.Com/#Fragment', 'https://example.com/#Fragment'),
('[::Ff%etH0%Ff]/%ab%Af', '[::ff%25etH0%Ff]/%AB%AF'),
])
def test_parse_url_normalization(self, url, expected_normali... | def test_invalid_url(self, url):
('HTTPS://Example.Com/?Key=Value', 'https://example.com/?Key=Value'),
('Https://Example.Com/#Fragment', 'https://example.com/#Fragment'),
('[::Ff%etH0%Ff]/%ab%Af', '[::ff%25etH0%Ff]/%AB%AF'),
# Invalid characters for the query/fragment getting encoded
... |
def test_parse_url_normalization(self, url, expected_normalized_url):
# Uppercase IRI
(u'http://Königsgäßchen.de/straße',
Url('http', host='xn--knigsgchen-b4a3dun.de', path='/stra%C3%9Fe'))
]
@pytest.mark.parametrize( | def test_parse_url_normalization(self, url, expected_normalized_url):
# Uppercase IRI
(u'http://Königsgäßchen.de/straße',
Url('http', host='xn--knigsgchen-b4a3dun.de', path='/stra%C3%9Fe')),
# Unicode Surrogates
(u'http://google.com/\uD800', Url('http', host='google.com', path... |
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... |
class DataFrame(NDFrame):
" or if the Series has a name"
)
if other.name is None:
index = None
else:
# other must have the same index name as self, otherwise
# index name will be reset
index = In... | class DataFrame(NDFrame):
" or if the Series has a name"
)
index = Index([other.name], name=self.index.name)
idx_diff = other.index.difference(self.columns)
try:
combined_columns = self.columns.append(idx_diff)
except T... |
class TestDataFrameConcatCommon:
expected = DataFrame({"bar": Series([Timestamp("20130101"), 1])})
tm.assert_frame_equal(result, expected)
def test_update(self):
df = DataFrame(
[[1.5, np.nan, 3.0], [1.5, np.nan, 3.0], [1.5, np.nan, 3], [1.5, np.nan, 3]] | class TestDataFrameConcatCommon:
expected = DataFrame({"bar": Series([Timestamp("20130101"), 1])})
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"timestamp", ["2019-07-19 07:04:57+0100", "2019-07-19 07:04:57"]
)
def test_append_timestamps_aware_or_naive(self, tz_... |
def gen_python_files_in_dir(
"""Generate all files under `path` whose paths are not excluded by the
`exclude` regex, but are included by the `include` regex.
`report` is where output about exclusions goes.
"""
assert root.is_absolute(), f"INTERNAL ERROR: `root` must be absolute but is {root}"
f... | def gen_python_files_in_dir(
"""Generate all files under `path` whose paths are not excluded by the
`exclude` regex, but are included by the `include` regex.
Symbolic links pointing outside of the root directory are ignored.
`report` is where output about exclusions goes.
"""
assert root.is_ab... |
import sys
from tempfile import TemporaryDirectory
from typing import Any, BinaryIO, Generator, List, Tuple, Iterator
import unittest
from unittest.mock import patch
from click import unstyle
from click.testing import CliRunner | import sys
from tempfile import TemporaryDirectory
from typing import Any, BinaryIO, Generator, List, Tuple, Iterator
import unittest
from unittest.mock import patch, MagicMock
from click import unstyle
from click.testing import CliRunner |
class BlackTestCase(unittest.TestCase):
with self.assertRaises(AssertionError):
black.assert_equivalent("{}", "None")
if __name__ == "__main__":
unittest.main(module="test_black") | class BlackTestCase(unittest.TestCase):
with self.assertRaises(AssertionError):
black.assert_equivalent("{}", "None")
def test_symlink_out_of_root_directory(self) -> None:
# prepare argumens
path = MagicMock()
root = THIS_DIR
child = MagicMock()
include =... |
def main():
# request makes further api requests
app.run(host='0.0.0.0',
port=settings.config.api_port,
debug=True,
threaded=True,
use_reloader=False,
ssl_context=context) | def main():
# request makes further api requests
app.run(host='0.0.0.0',
port=settings.config.api_port,
debug=settings.config.debug,
use_evalex=False,
threaded=True,
use_reloader=False,
ssl_context=context) |
from __future__ import division
import os
import re
import sys
import mimetypes
import threading
from time import sleep, time | from __future__ import division
import os
import re
import sys
import errno
import mimetypes
import threading
from time import sleep, time |
def filename_from_url(url, content_type):
return fn
def get_unique_filename(filename, exists=os.path.exists):
attempt = 0
while True:
suffix = '-' + str(attempt) if attempt > 0 else ''
if not exists(filename + suffix):
return filename + suffix
attempt += 1
| def filename_from_url(url, content_type):
return fn
def trim_filename(filename, max_len):
if len(filename) > max_len:
trim_by = len(filename) - max_len
name, ext = os.path.splitext(filename)
if trim_by >= len(name):
filename = filename[:-trim_by]
else:
f... |
import os
import time
import pytest
from requests.structures import CaseInsensitiveDict
from httpie.compat import urlopen | import os
import time
import pytest
import mock
from requests.structures import CaseInsensitiveDict
from httpie.compat import urlopen |
class TestDownloadUtils:
content_type='x-foo/bar'
)
def test_unique_filename(self):
def attempts(unique_on_attempt=0):
# noinspection PyUnresolvedReferences,PyUnusedLocal
def exists(filename): | class TestDownloadUtils:
content_type='x-foo/bar'
)
@pytest.mark.parametrize(
'orig_name, unique_on_attempt, expected',
[
# Simple
('foo.bar', 0, 'foo.bar'),
('foo.bar', 1, 'foo.bar-1'),
('foo.bar', 10, 'foo.bar-10'),
#... |
class TestDownloadUtils:
exists.attempt = 0
return exists
assert 'foo.bar' == get_unique_filename('foo.bar', attempts(0))
assert 'foo.bar-1' == get_unique_filename('foo.bar', attempts(1))
assert 'foo.bar-10' == get_unique_filename('foo.bar', attempts(10))
class TestDow... | class TestDownloadUtils:
exists.attempt = 0
return exists
get_filename_max_length.return_value = 10
actual = get_unique_filename(orig_name, attempts(unique_on_attempt))
assert expected == actual
class TestDownloads: |
def gunzip(data):
# contains the whole page content
if output or getattr(f, 'extrabuf', None):
try:
output += f.extrabuf
finally:
break
else: | def gunzip(data):
# contains the whole page content
if output or getattr(f, 'extrabuf', None):
try:
output += f.extrabuf[-f.extrasize:]
finally:
break
else: |
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 | import unittest
from os.path import join
from w3lib.encoding import html_to_unicode
from scrapy.utils.gz import gunzip, is_gzipped
from scrapy.http import Response, Headers
from tests import tests_datadir |
class GunzipTest(unittest.TestCase):
hdrs = Headers({"Content-Type": "application/x-gzip;charset=utf-8"})
r1 = Response("http://www.example.com", headers=hdrs)
self.assertTrue(is_gzipped(r1)) | class GunzipTest(unittest.TestCase):
hdrs = Headers({"Content-Type": "application/x-gzip;charset=utf-8"})
r1 = Response("http://www.example.com", headers=hdrs)
self.assertTrue(is_gzipped(r1))
def test_gunzip_illegal_eof(self):
with open(join(SAMPLEDIR, 'unexpected-eof.gz'), 'rb') as... |
def test_buffer_size(fig_test, fig_ref):
ax = fig_ref.add_subplot()
ax.set_yticks([0, 1])
ax.set_yticklabels(["€", ""]) | def test_buffer_size(fig_test, fig_ref):
ax = fig_ref.add_subplot()
ax.set_yticks([0, 1])
ax.set_yticklabels(["€", ""])
def test_fontproperties_kwarg_precedence():
"""Test that kwargs take precedence over fontproperties defaults."""
plt.figure()
text1 = plt.xlabel("value", fontproperties='Time... |
class Text(Artist):
def update(self, kwargs):
# docstring inherited
# Update bbox last, as it depends on font properties.
sentinel = object() # bbox can be None, so use another sentinel.
bbox = kwargs.pop("bbox", sentinel)
super().update(kwargs)
if bbox is not senti... | class Text(Artist):
def update(self, kwargs):
# docstring inherited
sentinel = object() # bbox can be None, so use another sentinel.
# Update fontproperties first, as it has lowest priority.
fontproperties = kwargs.pop("fontproperties", sentinel)
if fontproperties is not se... |
Name: Max Speed, dtype: float64
if copy:
new_values = new_values.copy()
assert isinstance(self.index, PeriodIndex)
new_index = self.index.to_timestamp(freq=freq, how=how) # type: ignore
return self._constructor(new_values, index=new_index).__finalize__(
self, me... | Name: Max Speed, dtype: float64
if copy:
new_values = new_values.copy()
if not isinstance(self.index, PeriodIndex):
raise TypeError(f"unsupported Type {type(self.index).__name__}")
new_index = self.index.to_timestamp(freq=freq, how=how) # type: ignore
return sel... |
Name: Max Speed, dtype: float64
if copy:
new_values = new_values.copy()
assert isinstance(self.index, DatetimeIndex)
new_index = self.index.to_period(freq=freq) # type: ignore
return self._constructor(new_values, index=new_index).__finalize__(
self, method="to_p... | Name: Max Speed, dtype: float64
if copy:
new_values = new_values.copy()
if not isinstance(self.index, DatetimeIndex):
raise TypeError(f"unsupported Type {type(self.index).__name__}")
new_index = self.index.to_period(freq=freq) # type: ignore
return self._constru... |
import numpy as np
from pandas import (
DataFrame, | import numpy as np
import pytest
from pandas import (
DataFrame, |
class TestToPeriod:
expected = df.copy()
expected.columns = exp_idx
tm.assert_frame_equal(df.to_period(axis=1), expected) | class TestToPeriod:
expected = df.copy()
expected.columns = exp_idx
tm.assert_frame_equal(df.to_period(axis=1), expected)
def test_to_period_raises(self, indices):
# https://github.com/pandas-dev/pandas/issues/33327
index = indices
ser = Series(index=index, dtype=obj... |
from datetime import timedelta
from pandas import Series, Timedelta, date_range, period_range, to_datetime
import pandas._testing as tm
| from datetime import timedelta
import pytest
from pandas import PeriodIndex, Series, Timedelta, date_range, period_range, to_datetime
import pandas._testing as tm
|
class TestToTimestamp:
exp_index = exp_index + Timedelta(1, "s") - Timedelta(1, "ns")
tm.assert_index_equal(result.index, exp_index)
assert result.name == "foo" | class TestToTimestamp:
exp_index = exp_index + Timedelta(1, "s") - Timedelta(1, "ns")
tm.assert_index_equal(result.index, exp_index)
assert result.name == "foo"
def test_to_timestamp_raises(self, indices):
# https://github.com/pandas-dev/pandas/issues/33327
index = indices
... |
class DatabaseFeatures(BaseDatabaseFeatures):
only_supports_unbounded_with_preceding_and_following = True
supports_aggregate_filter_clause = True
supported_explain_formats = {'JSON', 'TEXT', 'XML', 'YAML'}
validates_explain_options = False # A query will error on invalid options.
supports_deferrabl... | class DatabaseFeatures(BaseDatabaseFeatures):
only_supports_unbounded_with_preceding_and_following = True
supports_aggregate_filter_clause = True
supported_explain_formats = {'JSON', 'TEXT', 'XML', 'YAML'}
supports_deferrable_unique_constraints = True
has_json_operators = True
json_key_contains_... |
from django.db.backends.base.operations import BaseDatabaseOperations
class DatabaseOperations(BaseDatabaseOperations):
cast_char_field_without_max_length = 'varchar'
explain_prefix = 'EXPLAIN'
cast_data_types = {
'AutoField': 'integer',
'BigAutoField': 'bigint', | from django.db.backends.base.operations import BaseDatabaseOperations
class DatabaseOperations(BaseDatabaseOperations):
cast_char_field_without_max_length = 'varchar'
explain_prefix = 'EXPLAIN'
explain_options = frozenset(
[
"ANALYZE",
"BUFFERS",
"COSTS",
... |
class DatabaseOperations(BaseDatabaseOperations):
return super().subtract_temporals(internal_type, lhs, rhs)
def explain_query_prefix(self, format=None, **options):
prefix = super().explain_query_prefix(format)
extra = {}
if format:
extra['FORMAT'] = format
if op... | class DatabaseOperations(BaseDatabaseOperations):
return super().subtract_temporals(internal_type, lhs, rhs)
def explain_query_prefix(self, format=None, **options):
extra = {}
# Normalize options.
if options:
options = {
name.upper(): "true" if value else... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.