project stringclasses 17
values | bug_id int64 1 169 | buggy stringlengths 81 57.2k | fixed stringlengths 85 31.2k | test_command stringlengths 44 133 |
|---|---|---|---|---|
keras | 3 | def _clone_functional_model(model, input_tensors=None):
kwargs['mask'] = computed_masks
output_tensors = to_list(
layer(computed_tensors, **kwargs))
output_masks = to_list(
layer.compute_mask(computed_ten... | def _clone_functional_model(model, input_tensors=None):
kwargs['mask'] = computed_masks
output_tensors = to_list(
layer(computed_tensors, **kwargs))
if layer.supports_masking:
output_masks = to_list(
... | pytest tests/keras/test_sequential_model.py::test_clone_functional_model_with_multi_outputs |
scrapy | 38 | def _get_clickable(clickdata, form):
"""
clickables = [
el for el in form.xpath(
'descendant::*[(self::input or self::button)'
' and re:test(@type, "^submit$", "i")]'
'|descendant::button[not(@type)]',
namespaces={"re": "http://exslt.org/regular-expression... | def _get_clickable(clickdata, form):
"""
clickables = [
el for el in form.xpath(
'descendant::input[re:test(@type, "^(submit|image)$", "i")]'
'|descendant::button[not(@type) or re:test(@type, "^submit$", "i")]',
namespaces={"re": "http://exslt.org/regular-expressions"... | python -m unittest -q tests.test_http_request.FormRequestTest.test_from_response_clickdata_does_not_ignore_image |
pandas | 7 | class Index(IndexOpsMixin, PandasObject):
left_indexer = self.get_indexer(target, "pad", limit=limit)
right_indexer = self.get_indexer(target, "backfill", limit=limit)
target = np.asarray(target)
left_distances = abs(self.values[left_indexer] - target)
right_distances = abs(self... | class Index(IndexOpsMixin, PandasObject):
left_indexer = self.get_indexer(target, "pad", limit=limit)
right_indexer = self.get_indexer(target, "backfill", limit=limit)
left_distances = np.abs(self[left_indexer] - target)
right_distances = np.abs(self[right_indexer] - target)
op... | pytest pandas/tests/frame/indexing/test_indexing.py::TestDataFrameIndexing::test_reindex_nearest_tz |
pandas | 63 | class _AtIndexer(_ScalarAccessIndexer):
if is_setter:
return list(key)
for ax, i in zip(self.obj.axes, key):
if ax.is_integer():
if not is_integer(i):
raise ValueError(
"At based indexing on an integer index "
... | class _AtIndexer(_ScalarAccessIndexer):
if is_setter:
return list(key)
lkey = list(key)
for n, (ax, i) in enumerate(zip(self.obj.axes, key)):
lkey[n] = ax._convert_scalar_indexer(i, kind="loc")
return tuple(lkey)
@Appender(IndexingMixin.iat.__doc__) | pytest pandas/tests/indexing/test_scalar.py::TestScalar2::test_series_at_raises_type_error |
cookiecutter | 4 | class InvalidModeException(CookiecutterException):
Raised when cookiecutter is called with both `no_input==True` and
`replay==True` at the same time.
""" | class InvalidModeException(CookiecutterException):
Raised when cookiecutter is called with both `no_input==True` and
`replay==True` at the same time.
"""
class FailedHookException(CookiecutterException):
"""
Raised when a hook script fails
""" | tox tests/test_hooks.py::TestExternalHooks::test_run_failing_hook |
cookiecutter | 4 | from binaryornot.check import is_binary
from .exceptions import (
NonTemplatedInputDirException,
ContextDecodingException,
OutputDirExistsException
)
from .find import find_template
from .utils import make_sure_path_exists, work_in
from .hooks import run_hook, EXIT_SUCCESS
def copy_without_render(path, co... | from binaryornot.check import is_binary
from .exceptions import (
NonTemplatedInputDirException,
ContextDecodingException,
FailedHookException,
OutputDirExistsException
)
from .find import find_template
from .utils import make_sure_path_exists, work_in
from .hooks import run_hook
def copy_without_rend... | tox tests/test_hooks.py::TestExternalHooks::test_run_failing_hook |
cookiecutter | 4 | def generate_files(repo_dir, context=None, output_dir='.',
# run pre-gen hook from repo_dir
with work_in(repo_dir):
if run_hook('pre_gen_project', project_dir, context) != EXIT_SUCCESS:
logging.error("Stopping generation because pre_gen_project"
" hook script didn'... | def generate_files(repo_dir, context=None, output_dir='.',
# run pre-gen hook from repo_dir
with work_in(repo_dir):
try:
run_hook('pre_gen_project', project_dir, context)
except FailedHookException:
shutil.rmtree(project_dir, ignore_errors=True)
logging.error... | tox tests/test_hooks.py::TestExternalHooks::test_run_failing_hook |
cookiecutter | 4 | import tempfile
from jinja2 import Template
from cookiecutter import utils
_HOOKS = [ | import tempfile
from jinja2 import Template
from cookiecutter import utils
from .exceptions import FailedHookException
_HOOKS = [ | tox tests/test_hooks.py::TestExternalHooks::test_run_failing_hook |
cookiecutter | 4 | def run_script(script_path, cwd='.'):
shell=run_thru_shell,
cwd=cwd
)
return proc.wait()
def run_script_with_context(script_path, cwd, context): | def run_script(script_path, cwd='.'):
shell=run_thru_shell,
cwd=cwd
)
exit_status = proc.wait()
if exit_status != EXIT_SUCCESS:
raise FailedHookException(
"Hook script failed (exit status: %d)" % exit_status)
def run_script_with_context(script_path, cwd, context): | tox tests/test_hooks.py::TestExternalHooks::test_run_failing_hook |
cookiecutter | 4 | def run_script_with_context(script_path, cwd, context):
) as temp:
temp.write(Template(contents).render(**context))
return run_script(temp.name, cwd)
def run_hook(hook_name, project_dir, context): | def run_script_with_context(script_path, cwd, context):
) as temp:
temp.write(Template(contents).render(**context))
run_script(temp.name, cwd)
def run_hook(hook_name, project_dir, context): | tox tests/test_hooks.py::TestExternalHooks::test_run_failing_hook |
cookiecutter | 4 | def run_hook(hook_name, project_dir, context):
script = find_hooks().get(hook_name)
if script is None:
logging.debug('No hooks found')
return EXIT_SUCCESS
return run_script_with_context(script, project_dir, context) | def run_hook(hook_name, project_dir, context):
script = find_hooks().get(hook_name)
if script is None:
logging.debug('No hooks found')
return
run_script_with_context(script, project_dir, context) | tox tests/test_hooks.py::TestExternalHooks::test_run_failing_hook |
youtube-dl | 12 | class YoutubeDL(object):
comparison_value = m.group('value')
str_op = STR_OPERATORS[m.group('op')]
if m.group('negation'):
op = lambda attr, value: not str_op
else:
op = str_op
| class YoutubeDL(object):
comparison_value = m.group('value')
str_op = STR_OPERATORS[m.group('op')]
if m.group('negation'):
op = lambda attr, value: not str_op(attr, value)
else:
op = str_op
| python -m unittest -q test.test_YoutubeDL.TestFormatSelection.test_format_selection_string_ops |
pandas | 150 | def array_equivalent(left, right, strict_nan=False):
if not isinstance(right_value, float) or not np.isnan(right_value):
return False
else:
if left_value != right_value:
return False
return True
| def array_equivalent(left, right, strict_nan=False):
if not isinstance(right_value, float) or not np.isnan(right_value):
return False
else:
if np.any(left_value != right_value):
return False
return True
| pytest pandas/tests/dtypes/test_missing.py::test_array_equivalent_nested |
black | 18 | from asyncio.base_events import BaseEventLoop
from concurrent.futures import Executor, ProcessPoolExecutor
from enum import Enum, Flag
from functools import partial, wraps
import keyword
import logging
from multiprocessing import Manager | from asyncio.base_events import BaseEventLoop
from concurrent.futures import Executor, ProcessPoolExecutor
from enum import Enum, Flag
from functools import partial, wraps
import io
import keyword
import logging
from multiprocessing import Manager | python -m unittest -q tests.test_black.BlackTestCase.test_preserves_line_endings |
black | 18 | def format_file_in_place(
"""
if src.suffix == ".pyi":
mode |= FileMode.PYI
with tokenize.open(src) as src_buffer:
src_contents = src_buffer.read()
try:
dst_contents = format_file_contents(
src_contents, line_length=line_length, fast=fast, mode=mode | def format_file_in_place(
"""
if src.suffix == ".pyi":
mode |= FileMode.PYI
with open(src, "rb") as buf:
newline, encoding, src_contents = prepare_input(buf.read())
try:
dst_contents = format_file_contents(
src_contents, line_length=line_length, fast=fast, mode=mode | python -m unittest -q tests.test_black.BlackTestCase.test_preserves_line_endings |
black | 18 | def format_file_in_place(
return False
if write_back == write_back.YES:
with open(src, "w", encoding=src_buffer.encoding) as f:
f.write(dst_contents)
elif write_back == write_back.DIFF:
src_name = f"{src} (original)" | def format_file_in_place(
return False
if write_back == write_back.YES:
with open(src, "w", encoding=encoding, newline=newline) as f:
f.write(dst_contents)
elif write_back == write_back.DIFF:
src_name = f"{src} (original)" | python -m unittest -q tests.test_black.BlackTestCase.test_preserves_line_endings |
black | 18 | def format_file_in_place(
if lock:
lock.acquire()
try:
sys.stdout.write(diff_contents)
finally:
if lock:
lock.release() | def format_file_in_place(
if lock:
lock.acquire()
try:
f = io.TextIOWrapper(
sys.stdout.buffer,
encoding=encoding,
newline=newline,
write_through=True,
)
f.write(diff_contents)
f.d... | python -m unittest -q tests.test_black.BlackTestCase.test_preserves_line_endings |
black | 18 | def format_stdin_to_stdout(
`line_length`, `fast`, `is_pyi`, and `force_py36` arguments are passed to
:func:`format_file_contents`.
"""
src = sys.stdin.read()
dst = src
try:
dst = format_file_contents(src, line_length=line_length, fast=fast, mode=mode) | def format_stdin_to_stdout(
`line_length`, `fast`, `is_pyi`, and `force_py36` arguments are passed to
:func:`format_file_contents`.
"""
newline, encoding, src = prepare_input(sys.stdin.buffer.read())
dst = src
try:
dst = format_file_contents(src, line_length=line_length, fast=fast, mode=... | python -m unittest -q tests.test_black.BlackTestCase.test_preserves_line_endings |
black | 18 | def format_stdin_to_stdout(
finally:
if write_back == WriteBack.YES:
sys.stdout.write(dst)
elif write_back == WriteBack.DIFF:
src_name = "<stdin> (original)"
dst_name = "<stdin> (formatted)"
sys.stdout.write(diff(src, dst, src_name, dst_name))
def... | def format_stdin_to_stdout(
finally:
if write_back == WriteBack.YES:
f = io.TextIOWrapper(
sys.stdout.buffer,
encoding=encoding,
newline=newline,
write_through=True,
)
f.write(dst)
f.detach()
... | python -m unittest -q tests.test_black.BlackTestCase.test_preserves_line_endings |
black | 18 | def format_str(
return dst_contents
GRAMMARS = [
pygram.python_grammar_no_print_statement_no_exec_statement,
pygram.python_grammar_no_print_statement, | def format_str(
return dst_contents
def prepare_input(src: bytes) -> Tuple[str, str, str]:
"""Analyze `src` and return a tuple of (newline, encoding, decoded_contents)
Where `newline` is either CRLF or LF, and `decoded_contents` is decoded with
universal newlines (i.e. only LF).
"""
srcbuf = ... | python -m unittest -q tests.test_black.BlackTestCase.test_preserves_line_endings |
black | 18 | def lib2to3_parse(src_txt: str) -> Node:
"""Given a string with source, return the lib2to3 Node."""
grammar = pygram.python_grammar_no_print_statement
if src_txt[-1] != "\n":
nl = "\r\n" if "\r\n" in src_txt[:1024] else "\n"
src_txt += nl
for grammar in GRAMMARS:
drv = driver.Dri... | def lib2to3_parse(src_txt: str) -> Node:
"""Given a string with source, return the lib2to3 Node."""
grammar = pygram.python_grammar_no_print_statement
if src_txt[-1] != "\n":
src_txt += "\n"
for grammar in GRAMMARS:
drv = driver.Driver(grammar, pytree.convert)
try: | python -m unittest -q tests.test_black.BlackTestCase.test_preserves_line_endings |
matplotlib | 25 | class EventCollection(LineCollection):
.. plot:: gallery/lines_bars_and_markers/eventcollection_demo.py
"""
segment = (lineoffset + linelength / 2.,
lineoffset - linelength / 2.)
if positions is None or len(positions) == 0:
segments = []
elif hasa... | class EventCollection(LineCollection):
.. plot:: gallery/lines_bars_and_markers/eventcollection_demo.py
"""
if positions is None:
raise ValueError('positions must be an array-like object')
# Force a copy of positions
positions = np.array(positions, copy=True)
... | pytest lib/matplotlib/tests/test_collections.py::test_EventCollection_nosort |
luigi | 16 | class CentralPlannerScheduler(Scheduler):
for task in self._state.get_active_tasks():
self._state.fail_dead_worker_task(task, self._config, assistant_ids)
if task.id not in necessary_tasks and self._state.prune(task, self._config):
remove_tasks.append(task.id)
s... | class CentralPlannerScheduler(Scheduler):
for task in self._state.get_active_tasks():
self._state.fail_dead_worker_task(task, self._config, assistant_ids)
removed = self._state.prune(task, self._config)
if removed and task.id not in necessary_tasks:
remove_ta... | pytest test/central_planner_test.py::CentralPlannerTest::test_re_enable_failed_task_assistant |
ansible | 3 | class DistributionFiles:
elif 'SteamOS' in data:
debian_facts['distribution'] = 'SteamOS'
# nothing else to do, SteamOS gets correct info from python functions
elif path == '/etc/lsb-release' and 'Kali' in data:
debian_facts['distribution'] = 'Kali'
releas... | class DistributionFiles:
elif 'SteamOS' in data:
debian_facts['distribution'] = 'SteamOS'
# nothing else to do, SteamOS gets correct info from python functions
elif path in ('/etc/lsb-release', '/etc/os-release') and 'Kali' in data:
# Kali does not provide /etc/lsb-re... | pytest test/units/module_utils/test_distribution_version.py::test_distribution_version |
scrapy | 19 | class WrappedRequest(object):
"""
return self.request.meta.get('is_unverifiable', False)
# python3 uses request.unverifiable
@property
def unverifiable(self):
return self.is_unverifiable()
def get_origin_req_host(self):
return urlparse_cached(self.request).hostname
... | class WrappedRequest(object):
"""
return self.request.meta.get('is_unverifiable', False)
def get_origin_req_host(self):
return urlparse_cached(self.request).hostname
# python3 uses attributes instead of methods
@property
def full_url(self):
return self.get_full_url()
... | python -m unittest -q tests.test_http_cookies.WrappedRequestTest.test_get_origin_req_host |
keras | 45 | class LSTMCell(Layer):
inputs_f = inputs
inputs_c = inputs
inputs_o = inputs
x_i = K.dot(inputs_i, self.kernel_i) + self.bias_i
x_f = K.dot(inputs_f, self.kernel_f) + self.bias_f
x_c = K.dot(inputs_c, self.kernel_c) + self.bias_c
... | class LSTMCell(Layer):
inputs_f = inputs
inputs_c = inputs
inputs_o = inputs
x_i = K.dot(inputs_i, self.kernel_i)
x_f = K.dot(inputs_f, self.kernel_f)
x_c = K.dot(inputs_c, self.kernel_c)
x_o = K.dot(inputs_o, self.kernel_o)... | pytest tests/keras/layers/recurrent_test.py::test_implementation_mode[LSTM] |
youtube-dl | 5 | def unified_timestamp(date_str, day_first=True):
date_str = date_str.replace(',', ' ')
pm_delta = datetime.timedelta(hours=12 if re.search(r'(?i)PM', date_str) else 0)
timezone, date_str = extract_timezone(date_str)
# Remove AM/PM + timezone | def unified_timestamp(date_str, day_first=True):
date_str = date_str.replace(',', ' ')
pm_delta = 12 if re.search(r'(?i)PM', date_str) else 0
timezone, date_str = extract_timezone(date_str)
# Remove AM/PM + timezone | python -m unittest -q test.test_utils.TestUtil.test_unified_timestamps |
youtube-dl | 5 | def unified_timestamp(date_str, day_first=True):
for expression in date_formats(day_first):
try:
dt = datetime.datetime.strptime(date_str, expression) - timezone + pm_delta
return calendar.timegm(dt.timetuple())
except ValueError:
pass
timetuple = email.utils... | def unified_timestamp(date_str, day_first=True):
for expression in date_formats(day_first):
try:
dt = datetime.datetime.strptime(date_str, expression) - timezone + datetime.timedelta(hours=pm_delta)
return calendar.timegm(dt.timetuple())
except ValueError:
pass
... | python -m unittest -q test.test_utils.TestUtil.test_unified_timestamps |
thefuck | 24 | from .logs import debug
Command = namedtuple('Command', ('script', 'stdout', 'stderr'))
CorrectedCommand = namedtuple('CorrectedCommand', ('script', 'side_effect', 'priority'))
Rule = namedtuple('Rule', ('name', 'match', 'get_new_command',
'enabled_by_default', 'side_effect',
... | from .logs import debug
Command = namedtuple('Command', ('script', 'stdout', 'stderr'))
Rule = namedtuple('Rule', ('name', 'match', 'get_new_command',
'enabled_by_default', 'side_effect',
'priority', 'requires_output'))
class CorrectedCommand(object):
def __i... | pytest tests/test_types.py::TestCorrectedCommand::test_hashable |
thefuck | 24 | class SortedCorrectedCommandsSequence(object):
return []
for command in self._commands:
if command.script != first.script or \
command.side_effect != first.side_effect:
return [first, command]
return [first]
def _remove_duplicates... | class SortedCorrectedCommandsSequence(object):
return []
for command in self._commands:
if command != first:
return [first, command]
return [first]
def _remove_duplicates(self, corrected_commands):
"""Removes low-priority duplicates."""
comma... | pytest tests/test_types.py::TestCorrectedCommand::test_hashable |
pandas | 42 | def assert_series_equal(
f"is not equal to {right._values}."
)
raise AssertionError(msg)
elif is_interval_dtype(left.dtype) or is_interval_dtype(right.dtype):
assert_interval_array_equal(left.array, right.array)
elif is_categorical_dtype(left.dtype) or is_categori... | def assert_series_equal(
f"is not equal to {right._values}."
)
raise AssertionError(msg)
elif is_interval_dtype(left.dtype) and is_interval_dtype(right.dtype):
assert_interval_array_equal(left.array, right.array)
elif is_categorical_dtype(left.dtype) or is_categor... | pytest pandas/tests/util/test_assert_series_equal.py::test_assert_series_equal_interval_dtype_mismatch |
pandas | 42 | def assert_series_equal(
check_dtype=check_dtype,
obj=str(obj),
)
elif is_extension_array_dtype(left.dtype) or is_extension_array_dtype(right.dtype):
assert_extension_array_equal(left._values, right._values)
elif needs_i8_conversion(left.dtype) or needs_i8_conversion(righ... | def assert_series_equal(
check_dtype=check_dtype,
obj=str(obj),
)
elif is_extension_array_dtype(left.dtype) and is_extension_array_dtype(right.dtype):
assert_extension_array_equal(left._values, right._values)
elif needs_i8_conversion(left.dtype) or needs_i8_conversion(rig... | pytest pandas/tests/util/test_assert_series_equal.py::test_assert_series_equal_interval_dtype_mismatch |
youtube-dl | 33 | from __future__ import unicode_literals
import re
from .subtitles import SubtitlesInfoExtractor
from .common import ExtractorError
from ..utils import parse_iso8601 | from __future__ import unicode_literals
from .subtitles import SubtitlesInfoExtractor
from .common import ExtractorError
from ..utils import parse_iso8601 | python -m unittest -q test.test_utils.TestUtil.test_parse_iso8601 |
youtube-dl | 33 | class DRTVIE(SubtitlesInfoExtractor):
}
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
video_id = mobj.group('id')
programcard = self._download_json(
'http://www.dr.dk/mu/programcard/expanded/%s' % video_id, video_id, 'Downloading video JSON') | class DRTVIE(SubtitlesInfoExtractor):
}
def _real_extract(self, url):
video_id = self._match_id(url)
programcard = self._download_json(
'http://www.dr.dk/mu/programcard/expanded/%s' % video_id, video_id, 'Downloading video JSON') | python -m unittest -q test.test_utils.TestUtil.test_parse_iso8601 |
youtube-dl | 33 | class DRTVIE(SubtitlesInfoExtractor):
title = data['Title']
description = data['Description']
timestamp = parse_iso8601(data['CreatedTime'][:-5])
thumbnail = None
duration = None | class DRTVIE(SubtitlesInfoExtractor):
title = data['Title']
description = data['Description']
timestamp = parse_iso8601(data['CreatedTime'])
thumbnail = None
duration = None | python -m unittest -q test.test_utils.TestUtil.test_parse_iso8601 |
youtube-dl | 33 | def parse_iso8601(date_str, delimiter='T'):
return None
m = re.search(
r'Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$',
date_str)
if not m:
timezone = datetime.timedelta() | def parse_iso8601(date_str, delimiter='T'):
return None
m = re.search(
r'(\.[0-9]+)?(?:Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
date_str)
if not m:
timezone = datetime.timedelta() | python -m unittest -q test.test_utils.TestUtil.test_parse_iso8601 |
youtube-dl | 33 | def parse_iso8601(date_str, delimiter='T'):
timezone = datetime.timedelta(
hours=sign * int(m.group('hours')),
minutes=sign * int(m.group('minutes')))
date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
dt = datetime.datetime.strptime(date_str, date_format) - timez... | def parse_iso8601(date_str, delimiter='T'):
timezone = datetime.timedelta(
hours=sign * int(m.group('hours')),
minutes=sign * int(m.group('minutes')))
date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
dt = datetime.datetime.strptime(date_str, date_format) - timezo... | python -m unittest -q test.test_utils.TestUtil.test_parse_iso8601 |
thefuck | 28 | import re
import os
from thefuck.utils import memoize
from thefuck import shells
patterns = (
# js, node:
'^ at {file}:{line}:{col}', | import re
import os
from thefuck.utils import memoize, wrap_settings
from thefuck import shells
# order is important: only the first match is considered
patterns = (
# js, node:
'^ at {file}:{line}:{col}', | pytest tests/rules/test_fix_file.py::test_get_new_command_with_settings |
thefuck | 28 | patterns = (
# lua:
'^lua: {file}:{line}:',
# fish:
'^{file} \(line {line}\):',
# bash, sh, ssh:
'^{file}: line {line}: ',
# ghc, make, ruby, zsh:
'^{file}:{line}:',
# cargo, clang, gcc, go, pep8, rustc:
'^{file}:{line}:{col}',
# pe... | patterns = (
# lua:
'^lua: {file}:{line}:',
# fish:
'^{file} \\(line {line}\\):',
# bash, sh, ssh:
'^{file}: line {line}: ',
# cargo, clang, gcc, go, pep8, rustc:
'^{file}:{line}:{col}',
# ghc, make, ruby, zsh:
'^{file}:{line}:',
# ... | pytest tests/rules/test_fix_file.py::test_get_new_command_with_settings |
thefuck | 28 | def match(command, settings):
return _search(command.stderr) or _search(command.stdout)
def get_new_command(command, settings):
m = _search(command.stderr) or _search(command.stdout)
# Note: there does not seem to be a standard for columns, so they are just
# ignored for now
editor_call = '{} {} ... | def match(command, settings):
return _search(command.stderr) or _search(command.stdout)
@wrap_settings({'fixlinecmd': '{editor} {file} +{line}',
'fixcolcmd': None})
def get_new_command(command, settings):
m = _search(command.stderr) or _search(command.stdout)
# Note: there does not seem t... | pytest tests/rules/test_fix_file.py::test_get_new_command_with_settings |
youtube-dl | 9 | class YoutubeDL(object):
else:
filter_parts.append(string)
def _parse_format_selection(tokens, endwith=[]):
selectors = []
current_selector = None
for type, string, start, _, _ in tokens: | class YoutubeDL(object):
else:
filter_parts.append(string)
def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False):
selectors = []
current_selector = None
for type, string, start, _, _ in tokens: | python -m unittest -q test.test_YoutubeDL.TestFormatSelection.test_youtube_format_selection |
youtube-dl | 9 | class YoutubeDL(object):
elif type in [tokenize.NAME, tokenize.NUMBER]:
current_selector = FormatSelector(SINGLE, string, [])
elif type == tokenize.OP:
if string in endwith:
break
elif string == ')':
... | class YoutubeDL(object):
elif type in [tokenize.NAME, tokenize.NUMBER]:
current_selector = FormatSelector(SINGLE, string, [])
elif type == tokenize.OP:
if string == ')':
if not inside_group:
# ')'... | python -m unittest -q test.test_YoutubeDL.TestFormatSelection.test_youtube_format_selection |
youtube-dl | 9 | class YoutubeDL(object):
elif string == '(':
if current_selector:
raise syntax_error('Unexpected "("', start)
current_selector = FormatSelector(GROUP, _parse_format_selection(tokens, [')']), [])
elif stri... | class YoutubeDL(object):
elif string == '(':
if current_selector:
raise syntax_error('Unexpected "("', start)
group = _parse_format_selection(tokens, inside_group=True)
current_selector = FormatSelect... | python -m unittest -q test.test_YoutubeDL.TestFormatSelection.test_youtube_format_selection |
PySnooper | 3 | def get_write_function(output):
stderr.write(s)
elif isinstance(output, (pycompat.PathLike, str)):
def write(s):
with open(output_path, 'a') as output_file:
output_file.write(s)
else:
assert isinstance(output, utils.WritableStream) | def get_write_function(output):
stderr.write(s)
elif isinstance(output, (pycompat.PathLike, str)):
def write(s):
with open(output, 'a') as output_file:
output_file.write(s)
else:
assert isinstance(output, utils.WritableStream) | pytest -q -s tests/test_pysnooper.py::test_file_output |
pandas | 21 | class Series(base.IndexOpsMixin, generic.NDFrame):
else:
return self.iloc[key]
if isinstance(key, list):
# handle the dup indexing case GH#4246
return self.loc[key]
return self.reindex(key)
def _get_values_tuple(self, key):
# mpl hackaro... | class Series(base.IndexOpsMixin, generic.NDFrame):
else:
return self.iloc[key]
# handle the dup indexing case GH#4246
return self.loc[key]
def _get_values_tuple(self, key):
# mpl hackaround | pytest pandas/tests/series/indexing/test_getitem.py::TestSeriesGetitemListLike::test_getitem_no_matches |
ansible | 16 | class LinuxHardware(Hardware):
# The fields for ARM CPUs do not always include 'vendor_id' or 'model name',
# and sometimes includes both 'processor' and 'Processor'.
# Always use 'processor' count for ARM systems
if collected_facts.get('ansible_architecture', '').startswith(('armv', 'a... | class LinuxHardware(Hardware):
# The fields for ARM CPUs do not always include 'vendor_id' or 'model name',
# and sometimes includes both 'processor' and 'Processor'.
# The fields for Power CPUs include 'processor' and 'cpu'.
# Always use 'processor' count for ARM and Power systems
... | pytest test/units/module_utils/facts/hardware/test_linux_get_cpu_info.py::test_get_cpu_info_missing_arch |
ansible | 16 | CPU_INFO_TEST_SCENARIOS = [
'7', 'POWER7 (architected), altivec supported'
],
'processor_cores': 1,
'processor_count': 16,
'processor_threads_per_core': 1,
'processor_vcpus': 16
},
},
{ | CPU_INFO_TEST_SCENARIOS = [
'7', 'POWER7 (architected), altivec supported'
],
'processor_cores': 1,
'processor_count': 8,
'processor_threads_per_core': 1,
'processor_vcpus': 8
},
},
{ | pytest test/units/module_utils/facts/hardware/test_linux_get_cpu_info.py::test_get_cpu_info_missing_arch |
ansible | 16 | CPU_INFO_TEST_SCENARIOS = [
'23', 'POWER8 (architected), altivec supported',
],
'processor_cores': 1,
'processor_count': 48,
'processor_threads_per_core': 1,
'processor_vcpus': 48
},
},
{ | CPU_INFO_TEST_SCENARIOS = [
'23', 'POWER8 (architected), altivec supported',
],
'processor_cores': 1,
'processor_count': 24,
'processor_threads_per_core': 1,
'processor_vcpus': 24
},
},
{ | pytest test/units/module_utils/facts/hardware/test_linux_get_cpu_info.py::test_get_cpu_info_missing_arch |
pandas | 112 | from pandas.core.dtypes.cast import (
)
from pandas.core.dtypes.common import (
ensure_platform_int,
is_datetime64tz_dtype,
is_datetime_or_timedelta_dtype,
is_dtype_equal, | from pandas.core.dtypes.cast import (
)
from pandas.core.dtypes.common import (
ensure_platform_int,
is_categorical,
is_datetime64tz_dtype,
is_datetime_or_timedelta_dtype,
is_dtype_equal, | pytest pandas/tests/frame/test_analytics.py::TestDataFrameAnalytics::test_round_interval_category_columns |
pandas | 112 | from pandas.core.dtypes.generic import ABCSeries
from pandas.core.dtypes.missing import isna
from pandas._typing import AnyArrayLike
from pandas.core.arrays.interval import IntervalArray, _interval_shared_docs
import pandas.core.common as com
import pandas.core.indexes.base as ibase | from pandas.core.dtypes.generic import ABCSeries
from pandas.core.dtypes.missing import isna
from pandas._typing import AnyArrayLike
from pandas.core.algorithms import take_1d
from pandas.core.arrays.interval import IntervalArray, _interval_shared_docs
import pandas.core.common as com
import pandas.core.indexes.base a... | pytest pandas/tests/frame/test_analytics.py::TestDataFrameAnalytics::test_round_interval_category_columns |
pandas | 112 | class IntervalIndex(IntervalMixin, Index):
left_indexer = self.left.get_indexer(target_as_index.left)
right_indexer = self.right.get_indexer(target_as_index.right)
indexer = np.where(left_indexer == right_indexer, left_indexer, -1)
elif not is_object_dtype(target_as_index):
... | class IntervalIndex(IntervalMixin, Index):
left_indexer = self.left.get_indexer(target_as_index.left)
right_indexer = self.right.get_indexer(target_as_index.right)
indexer = np.where(left_indexer == right_indexer, left_indexer, -1)
elif is_categorical(target_as_index):
... | pytest pandas/tests/frame/test_analytics.py::TestDataFrameAnalytics::test_round_interval_category_columns |
pandas | 112 | import re
import numpy as np
import pytest
from pandas import Interval, IntervalIndex, Timedelta, date_range, timedelta_range
from pandas.core.indexes.base import InvalidIndexError
import pandas.util.testing as tm
| import re
import numpy as np
import pytest
from pandas import (
CategoricalIndex,
Interval,
IntervalIndex,
Timedelta,
date_range,
timedelta_range,
)
from pandas.core.indexes.base import InvalidIndexError
import pandas.util.testing as tm
| pytest pandas/tests/frame/test_analytics.py::TestDataFrameAnalytics::test_round_interval_category_columns |
pandas | 112 | class TestGetIndexer:
expected = np.array([0] * size, dtype="intp")
tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize(
"tuples, closed",
[ | class TestGetIndexer:
expected = np.array([0] * size, dtype="intp")
tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize(
"target",
[
IntervalIndex.from_tuples([(7, 8), (1, 2), (3, 4), (0, 1)]),
IntervalIndex.from_tuples([(0, 1), (1, 2), (3,... | pytest pandas/tests/frame/test_analytics.py::TestDataFrameAnalytics::test_round_interval_category_columns |
spacy | 1 | def add_codes(err_cls):
class ErrorsWithCodes(object):
def __getattribute__(self, code):
msg = getattr(err_cls, code)
return "[{code}] {msg}".format(code=code, msg=msg)
return ErrorsWithCodes()
| def add_codes(err_cls):
class ErrorsWithCodes(object):
def __getattribute__(self, code):
if not code.startswith('__'):
msg = getattr(err_cls, code)
return "[{code}] {msg}".format(code=code, msg=msg)
else:
return super().__getattribute_... | py.test spacy/tests/test_errors.py::test_add_codes |
keras | 26 | def rnn(step_function, inputs, initial_states,
tiled_mask_t = tf.tile(mask_t,
tf.stack([1, tf.shape(output)[1]]))
output = tf.where(tiled_mask_t, output, states[0])
new_states = [tf.where(tiled_mask_t, new_states[i], states[i]) for i... | def rnn(step_function, inputs, initial_states,
tiled_mask_t = tf.tile(mask_t,
tf.stack([1, tf.shape(output)[1]]))
output = tf.where(tiled_mask_t, output, states[0])
new_states = [
tf.where(tf.tile(mask_t, tf.stack... | pytest tests/keras/backend/backend_test.py::TestBackend::test_rnn_additional_states |
scrapy | 15 | def url_has_any_extension(url, extensions):
def _safe_ParseResult(parts, encoding='utf8', path_encoding='utf8'):
return (
to_native_str(parts.scheme),
to_native_str(parts.netloc.encode('idna')),
# default encoding for path component SHOULD be UTF-8
quote(to_bytes(parts.path, path_... | def url_has_any_extension(url, extensions):
def _safe_ParseResult(parts, encoding='utf8', path_encoding='utf8'):
# IDNA encoding can fail for too long labels (>63 characters)
# or missing labels (e.g. http://.example.com)
try:
netloc = parts.netloc.encode('idna')
except UnicodeError:
n... | python -m unittest -q tests.test_utils_url.CanonicalizeUrlTest.test_canonicalize_url_idna_exceptions |
black | 2 | def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]:
"""
container: Optional[LN] = container_of(leaf)
while container is not None and container.type != token.ENDMARKER:
is_fmt_on = False
for comment in list_comments(container.prefix, is_endmarker=False):
if comment.value in FM... | def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]:
"""
container: Optional[LN] = container_of(leaf)
while container is not None and container.type != token.ENDMARKER:
if fmt_on(container):
return
# fix for fmt: on in children
if contains_fmt_on_at_column(container, ... | python -m unittest -q tests.test_black.BlackTestCase.test_fmtonoff4 |
pandas | 92 | class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
if not is_list:
start = self.index[0]
if isinstance(self.index, PeriodIndex):
where = Period(where, freq=self.index.freq).ordinal
start = start.ordinal
if where < start:
... | class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
if not is_list:
start = self.index[0]
if isinstance(self.index, PeriodIndex):
where = Period(where, freq=self.index.freq)
if where < start:
if not is_series: | pytest pandas/tests/frame/methods/test_asof.py::TestFrameAsof::test_missing |
pandas | 92 | class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
@Substitution(klass="PeriodIndex")
@Appender(_shared_docs["searchsorted"])
def searchsorted(self, value, side="left", sorter=None):
if isinstance(value, Period):
if value.freq != self.freq:
raise r... | class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
@Substitution(klass="PeriodIndex")
@Appender(_shared_docs["searchsorted"])
def searchsorted(self, value, side="left", sorter=None):
if isinstance(value, Period) or value is NaT:
self._data._check_compatible_with(v... | pytest pandas/tests/frame/methods/test_asof.py::TestFrameAsof::test_missing |
pandas | 92 | class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
t1, t2 = self._parsed_string_to_bounds(reso, parsed)
return slice(
self.searchsorted(t1.ordinal, side="left"),
self.searchsorted(t2.ordinal, side="right"),
)
def _convert_tolerance(self, tole... | class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
t1, t2 = self._parsed_string_to_bounds(reso, parsed)
return slice(
self.searchsorted(t1, side="left"), self.searchsorted(t2, side="right")
)
def _convert_tolerance(self, tolerance, target): | pytest pandas/tests/frame/methods/test_asof.py::TestFrameAsof::test_missing |
pandas | 92 | class TimeGrouper(Grouper):
rng += freq_mult
# adjust bin edge indexes to account for base
rng -= bin_shift
bins = memb.searchsorted(rng, side="left")
if nat_count > 0:
# NaT handling as in pandas._lib.lib.generate_bins_dt64() | class TimeGrouper(Grouper):
rng += freq_mult
# adjust bin edge indexes to account for base
rng -= bin_shift
# Wrap in PeriodArray for PeriodArray.searchsorted
prng = type(memb._data)(rng, dtype=memb.dtype)
bins = memb.searchsorted(prng, side="left")
if nat_count... | pytest pandas/tests/frame/methods/test_asof.py::TestFrameAsof::test_missing |
pandas | 92 | class TestPeriodIndex(DatetimeLike):
idx = PeriodIndex([2000, 2007, 2007, 2009, 2009], freq="A-JUN")
ts = Series(np.random.randn(len(idx)), index=idx)
result = ts[2007]
expected = ts[1:3]
tm.assert_series_equal(result, expected)
result[:] = 1 | class TestPeriodIndex(DatetimeLike):
idx = PeriodIndex([2000, 2007, 2007, 2009, 2009], freq="A-JUN")
ts = Series(np.random.randn(len(idx)), index=idx)
result = ts["2007"]
expected = ts[1:3]
tm.assert_series_equal(result, expected)
result[:] = 1 | pytest pandas/tests/frame/methods/test_asof.py::TestFrameAsof::test_missing |
pandas | 92 | class TestPeriodIndex(DatetimeLike):
idx = PeriodIndex([2000, 2007, 2007, 2009, 2007], freq="A-JUN")
ts = Series(np.random.randn(len(idx)), index=idx)
result = ts[2007]
expected = ts[idx == "2007"]
tm.assert_series_equal(result, expected)
| class TestPeriodIndex(DatetimeLike):
idx = PeriodIndex([2000, 2007, 2007, 2009, 2007], freq="A-JUN")
ts = Series(np.random.randn(len(idx)), index=idx)
result = ts["2007"]
expected = ts[idx == "2007"]
tm.assert_series_equal(result, expected)
| pytest pandas/tests/frame/methods/test_asof.py::TestFrameAsof::test_missing |
pandas | 92 | class TestPeriodIndex:
p2 = pd.Period("2014-01-04", freq=freq)
assert pidx.searchsorted(p2) == 3
msg = "Input has different freq=H from PeriodIndex"
with pytest.raises(IncompatibleFrequency, match=msg):
pidx.searchsorted(pd.Period("2014-01-01", freq="H"))
msg = "Inp... | class TestPeriodIndex:
p2 = pd.Period("2014-01-04", freq=freq)
assert pidx.searchsorted(p2) == 3
assert pidx.searchsorted(pd.NaT) == 0
msg = "Input has different freq=H from PeriodArray"
with pytest.raises(IncompatibleFrequency, match=msg):
pidx.searchsorted(pd.Peri... | pytest pandas/tests/frame/methods/test_asof.py::TestFrameAsof::test_missing |
pandas | 133 | class NDFrame(PandasObject, SelectionMixin):
"""
inplace = validate_bool_kwarg(inplace, "inplace")
if axis == 0:
ax = self._info_axis_name
_maybe_transposed_self = self
elif axis == 1:
_maybe_transposed_self = self.T
ax = 1
else:
... | class NDFrame(PandasObject, SelectionMixin):
"""
inplace = validate_bool_kwarg(inplace, "inplace")
axis = self._get_axis_number(axis)
if axis == 0:
ax = self._info_axis_name
_maybe_transposed_self = self
elif axis == 1:
_maybe_transposed_self... | pytest pandas/tests/frame/test_missing.py::TestDataFrameInterpolate::test_interp_axis_names |
black | 14 | from typing import (
Callable,
Collection,
Dict,
Generic,
Iterable,
Iterator, | from typing import (
Callable,
Collection,
Dict,
Generator,
Generic,
Iterable,
Iterator, | python -m unittest -q tests.test_black.BlackTestCase.test_get_future_imports |
black | 14 | def generate_trailers_to_omit(line: Line, line_length: int) -> Iterator[Set[Leaf
def get_future_imports(node: Node) -> Set[str]:
"""Return a set of __future__ imports in the file."""
imports = set()
for child in node.children:
if child.type != syms.simple_stmt:
break | def generate_trailers_to_omit(line: Line, line_length: int) -> Iterator[Set[Leaf
def get_future_imports(node: Node) -> Set[str]:
"""Return a set of __future__ imports in the file."""
imports: Set[str] = set()
def get_imports_from_children(children: List[LN]) -> Generator[str, None, None]:
for chil... | python -m unittest -q tests.test_black.BlackTestCase.test_get_future_imports |
black | 14 | def get_future_imports(node: Node) -> Set[str]:
module_name = first_child.children[1]
if not isinstance(module_name, Leaf) or module_name.value != "__future__":
break
for import_from_child in first_child.children[3:]:
if isinstance(import_from_child, L... | def get_future_imports(node: Node) -> Set[str]:
module_name = first_child.children[1]
if not isinstance(module_name, Leaf) or module_name.value != "__future__":
break
imports |= set(get_imports_from_children(first_child.children[3:]))
else:
break
... | python -m unittest -q tests.test_black.BlackTestCase.test_get_future_imports |
black | 14 | #!/usr/bin/env python2
from __future__ import unicode_literals
u'hello'
U"hello" | #!/usr/bin/env python2
from __future__ import unicode_literals as _unicode_literals
from __future__ import absolute_import
from __future__ import print_function as lol, with_function
u'hello'
U"hello" | python -m unittest -q tests.test_black.BlackTestCase.test_get_future_imports |
black | 14 | Ur"hello"
#!/usr/bin/env python2
from __future__ import unicode_literals
"hello"
"hello" | Ur"hello"
#!/usr/bin/env python2
from __future__ import unicode_literals as _unicode_literals
from __future__ import absolute_import
from __future__ import print_function as lol, with_function
"hello"
"hello" | python -m unittest -q tests.test_black.BlackTestCase.test_get_future_imports |
matplotlib | 29 | class Axis(martist.Artist):
the top for the y-axis; the "inverse" direction is increasing to the
left for the x-axis and to the bottom for the y-axis.
"""
a, b = self.get_view_interval()
if inverted:
self.set_view_interval(max(a, b), min(a, b), ignore=True)
el... | class Axis(martist.Artist):
the top for the y-axis; the "inverse" direction is increasing to the
left for the x-axis and to the bottom for the y-axis.
"""
# Currently, must be implemented in subclasses using set_xlim/set_ylim
# rather than generically using set_view_interval, so ... | pytest lib/matplotlib/tests/test_axes.py::test_inverted_cla |
matplotlib | 29 | class XAxis(Axis):
def get_minpos(self):
return self.axes.dataLim.minposx
def set_default_intervals(self):
# docstring inherited
xmin, xmax = 0., 1. | class XAxis(Axis):
def get_minpos(self):
return self.axes.dataLim.minposx
def set_inverted(self, inverted):
# docstring inherited
a, b = self.get_view_interval()
self.axes.set_xlim(sorted((a, b), reverse=inverted), auto=None)
def set_default_intervals(self):
# docst... | pytest lib/matplotlib/tests/test_axes.py::test_inverted_cla |
matplotlib | 29 | class YAxis(Axis):
def get_minpos(self):
return self.axes.dataLim.minposy
def set_default_intervals(self):
# docstring inherited
ymin, ymax = 0., 1. | class YAxis(Axis):
def get_minpos(self):
return self.axes.dataLim.minposy
def set_inverted(self, inverted):
# docstring inherited
a, b = self.get_view_interval()
self.axes.set_ylim(sorted((a, b), reverse=inverted), auto=None)
def set_default_intervals(self):
# docst... | pytest lib/matplotlib/tests/test_axes.py::test_inverted_cla |
scrapy | 34 | See documentation in docs/topics/item.rst
from pprint import pformat
from collections import MutableMapping
from abc import ABCMeta
import six
| See documentation in docs/topics/item.rst
from pprint import pformat
from collections import MutableMapping
from abc import ABCMeta
import six
| python -m unittest -q tests.test_item.ItemTest.test_metaclass_multiple_inheritance_diamond |
scrapy | 34 | class ItemMeta(ABCMeta):
new_bases = tuple(base._class for base in bases if hasattr(base, '_class'))
_class = super(ItemMeta, mcs).__new__(mcs, 'x_' + class_name, new_bases, attrs)
fields = {}
new_attrs = {}
for n in dir(_class):
v = getattr(_class, n) | class ItemMeta(ABCMeta):
new_bases = tuple(base._class for base in bases if hasattr(base, '_class'))
_class = super(ItemMeta, mcs).__new__(mcs, 'x_' + class_name, new_bases, attrs)
fields = getattr(_class, 'fields', {})
new_attrs = {}
for n in dir(_class):
v = getatt... | python -m unittest -q tests.test_item.ItemTest.test_metaclass_multiple_inheritance_diamond |
tornado | 12 | import hmac
import time
import uuid
from tornado.concurrent import TracebackFuture, return_future
from tornado import gen
from tornado import httpclient
from tornado import escape | import hmac
import time
import uuid
from tornado.concurrent import TracebackFuture, return_future, chain_future
from tornado import gen
from tornado import httpclient
from tornado import escape | python -m unittest -q tornado.test.auth_test.AuthTest.test_facebook_login |
tornado | 12 | class FacebookGraphMixin(OAuth2Mixin):
future.set_exception(AuthError('Facebook auth error: %s' % str(response)))
return
args = escape.parse_qs_bytes(escape.native_str(response.body))
session = {
"access_token": args["access_token"][-1],
"expires": args.g... | class FacebookGraphMixin(OAuth2Mixin):
future.set_exception(AuthError('Facebook auth error: %s' % str(response)))
return
args = urlparse.parse_qs(escape.native_str(response.body))
session = {
"access_token": args["access_token"][-1],
"expires": args.get("... | python -m unittest -q tornado.test.auth_test.AuthTest.test_facebook_login |
tornado | 12 | class FacebookGraphMixin(OAuth2Mixin):
Added the ability to override ``self._FACEBOOK_BASE_URL``.
"""
url = self._FACEBOOK_BASE_URL + path
return self.oauth2_request(url, callback, access_token,
post_args, **args)
def _oauth_signature(consumer_toke... | class FacebookGraphMixin(OAuth2Mixin):
Added the ability to override ``self._FACEBOOK_BASE_URL``.
"""
url = self._FACEBOOK_BASE_URL + path
# Thanks to the _auth_return_future decorator, our "callback"
# argument is a Future, which we cannot pass as a callback to
# oaut... | python -m unittest -q tornado.test.auth_test.AuthTest.test_facebook_login |
pandas | 19 | class _LocIndexer(_LocationIndexer):
return self._getbool_axis(key, axis=axis)
elif is_list_like_indexer(key):
# convert various list-like indexers
# to a list of keys
# we will use the *values* of the object
# and NOT the index if its a PandasObject
... | class _LocIndexer(_LocationIndexer):
return self._getbool_axis(key, axis=axis)
elif is_list_like_indexer(key):
# an iterable multi-selection
if not (isinstance(key, tuple) and isinstance(labels, ABCMultiIndex)):
| pytest pandas/tests/series/indexing/test_getitem.py::TestSeriesGetitemListLike::test_getitem_intlist_multiindex_numeric_level |
thefuck | 10 | def get_new_command(command):
if '2' in command.script:
return command.script.replace("2", "3")
split_cmd2 = command.script_parts
split_cmd3 = split_cmd2[:]
split_cmd2.insert(1, ' 2 ')
split_cmd3.insert(1, ' 3 ')
last_arg = command.script_parts[-1]
return [
last_arg + ' -... | def get_new_command(command):
if '2' in command.script:
return command.script.replace("2", "3")
last_arg = command.script_parts[-1]
help_command = last_arg + ' --help'
# If there are no man pages for last_arg, suggest `last_arg --help` instead.
# Otherwise, suggest `--help` after suggestin... | pytest tests/rules/test_man.py::test_get_new_command |
matplotlib | 30 | def makeMappingArray(N, data, gamma=1.0):
if (np.diff(x) < 0).any():
raise ValueError("data mapping points must have x in increasing order")
# begin generation of lookup table
x = x * (N - 1)
xind = (N - 1) * np.linspace(0, 1, N) ** gamma
ind = np.searchsorted(x, xind)[1:-1]
distance = ... | def makeMappingArray(N, data, gamma=1.0):
if (np.diff(x) < 0).any():
raise ValueError("data mapping points must have x in increasing order")
# begin generation of lookup table
if N == 1:
# convention: use the y = f(x=1) value for a 1-element lookup table
lut = np.array(y0[-1])
el... | pytest lib/matplotlib/tests/test_colors.py::test_makeMappingArray |
pandas | 145 | def dispatch_to_series(left, right, func, str_rep=None, axis=None):
# in which case we specifically want to operate row-by-row
assert right.index.equals(left.columns)
def column_op(a, b):
return {i: func(a.iloc[:, i], b.iloc[i]) for i in range(len(a.columns))}
elif isinstance(r... | def dispatch_to_series(left, right, func, str_rep=None, axis=None):
# in which case we specifically want to operate row-by-row
assert right.index.equals(left.columns)
if right.dtype == "timedelta64[ns]":
# ensure we treat NaT values as the correct dtype
# Note: we do not... | pytest pandas/tests/frame/test_arithmetic.py::TestFrameArithmetic::test_td64_op_nat_casting |
pandas | 76 | class Parser:
if (new_data == data).all():
data = new_data
result = True
except (TypeError, ValueError):
pass
# coerce ints to 64 | class Parser:
if (new_data == data).all():
data = new_data
result = True
except (TypeError, ValueError, OverflowError):
pass
# coerce ints to 64 | pytest pandas/tests/io/json/test_pandas.py::TestPandasContainer::test_frame_int_overflow |
youtube-dl | 26 | def js_to_json(code):
'(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
/\*.*?\*/|,(?=\s*[\]}])|
[a-zA-Z_][.a-zA-Z_0-9]*|
(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:\s*:)?|
[0-9]+(?=\s*:)
''', fix_kv, code)
| def js_to_json(code):
'(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
/\*.*?\*/|,(?=\s*[\]}])|
[a-zA-Z_][.a-zA-Z_0-9]*|
\b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:\s*:)?|
[0-9]+(?=\s*:)
''', fix_kv, code)
| python -m unittest -q test.test_utils.TestUtil.test_js_to_json_realworld |
pandas | 57 | def assert_series_equal(
check_exact=False,
check_datetimelike_compat=False,
check_categorical=True,
obj="Series",
):
""" | def assert_series_equal(
check_exact=False,
check_datetimelike_compat=False,
check_categorical=True,
check_category_order=True,
obj="Series",
):
""" | pytest pandas/tests/arrays/categorical/test_replace.py::test_replace |
pandas | 57 | def assert_series_equal(
Compare datetime-like which is comparable ignoring dtype.
check_categorical : bool, default True
Whether to compare internal Categorical exactly.
obj : str, default 'Series'
Specify object name being compared, internally used to show appropriate
assertion... | def assert_series_equal(
Compare datetime-like which is comparable ignoring dtype.
check_categorical : bool, default True
Whether to compare internal Categorical exactly.
check_category_order : bool, default True
Whether to compare category order of internal Categoricals
.. vers... | pytest pandas/tests/arrays/categorical/test_replace.py::test_replace |
pandas | 57 | def assert_series_equal(
if check_categorical:
if is_categorical_dtype(left) or is_categorical_dtype(right):
assert_categorical_equal(left.values, right.values, obj=f"{obj} category")
# This could be refactored to use the NDFrame.equals method | def assert_series_equal(
if check_categorical:
if is_categorical_dtype(left) or is_categorical_dtype(right):
assert_categorical_equal(
left.values,
right.values,
obj=f"{obj} category",
check_category_order=check_category_order,
... | pytest pandas/tests/arrays/categorical/test_replace.py::test_replace |
pandas | 57 | class Categorical(ExtensionArray, PandasObject):
"""
inplace = validate_bool_kwarg(inplace, "inplace")
cat = self if inplace else self.copy()
if to_replace in cat.categories:
if isna(value):
cat.remove_categories(to_replace, inplace=True)
else:
... | class Categorical(ExtensionArray, PandasObject):
"""
inplace = validate_bool_kwarg(inplace, "inplace")
cat = self if inplace else self.copy()
# build a dict of (to replace -> value) pairs
if is_list_like(to_replace):
# if to_replace is list-like and value is scalar
... | pytest pandas/tests/arrays/categorical/test_replace.py::test_replace |
pandas | 38 | def _unstack_multiple(data, clocs, fill_value=None):
comp_ids, obs_ids = compress_group_index(group_index, sort=False)
recons_codes = decons_obs_group_ids(comp_ids, obs_ids, shape, ccodes, xnull=False)
if rlocs == []:
# Everything is in clocs, so the dummy df has a regular index
dummy_index... | def _unstack_multiple(data, clocs, fill_value=None):
comp_ids, obs_ids = compress_group_index(group_index, sort=False)
recons_codes = decons_obs_group_ids(comp_ids, obs_ids, shape, ccodes, xnull=False)
if not rlocs:
# Everything is in clocs, so the dummy df has a regular index
dummy_index =... | pytest pandas/tests/frame/test_reshape.py::TestDataFrameReshape::test_unstack_multi_level_rows_and_cols |
pandas | 38 | def _unstack_multiple(data, clocs, fill_value=None):
for i in range(len(clocs)):
val = clocs[i]
result = result.unstack(val, fill_value=fill_value)
clocs = [v if i > v else v - 1 for v in clocs]
return result
| def _unstack_multiple(data, clocs, fill_value=None):
for i in range(len(clocs)):
val = clocs[i]
result = result.unstack(val, fill_value=fill_value)
clocs = [v if v < val else v - 1 for v in clocs]
return result
| pytest pandas/tests/frame/test_reshape.py::TestDataFrameReshape::test_unstack_multi_level_rows_and_cols |
luigi | 22 | class Worker(object):
Structure for tracking worker activity and keeping their references.
"""
def __init__(self, worker_id, last_active=None):
self.id = worker_id
self.reference = None # reference to the worker in the real world. (Currently a dict containing just the host)
self.la... | class Worker(object):
Structure for tracking worker activity and keeping their references.
"""
def __init__(self, worker_id, last_active=time.time()):
self.id = worker_id
self.reference = None # reference to the worker in the real world. (Currently a dict containing just the host)
... | pytest test/scheduler_test.py::SchedulerTest::test_worker_prune_after_init |
pandas | 164 | def _convert_listlike_datetimes(
return DatetimeIndex(arg, tz=tz, name=name)
except ValueError:
pass
return arg
| def _convert_listlike_datetimes(
return DatetimeIndex(arg, tz=tz, name=name)
except ValueError:
pass
elif tz:
# DatetimeArray, DatetimeIndex
return arg.tz_localize(tz)
return arg
| pytest pandas/tests/indexes/datetimes/test_tools.py::TestToDatetimeMisc::test_to_datetime_dta_tz |
thefuck | 31 | def match(command, settings):
@utils.git_support
def get_new_command(command, settings):
return '{} --staged'.format(command.script) | def match(command, settings):
@utils.git_support
def get_new_command(command, settings):
return command.script.replace(' diff', ' diff --staged') | pytest tests/rules/test_git_diff_staged.py::test_get_new_command |
fastapi | 5 | def create_cloned_field(field: ModelField) -> ModelField:
original_type.__name__, __config__=original_type.__config__
)
for f in original_type.__fields__.values():
use_type.__fields__[f.name] = f
use_type.__validators__ = original_type.__validators__
if PYDANTIC_1:
... | def create_cloned_field(field: ModelField) -> ModelField:
original_type.__name__, __config__=original_type.__config__
)
for f in original_type.__fields__.values():
use_type.__fields__[f.name] = create_cloned_field(f)
use_type.__validators__ = original_type.__validators__
... | pytest tests/test_filter_pydantic_sub_model.py::test_filter_sub_model |
matplotlib | 11 | class Text(Artist):
#return _unit_box
if not self.get_visible():
return Bbox.unit()
if dpi is not None:
dpi_orig = self.figure.dpi
self.figure.dpi = dpi
if self.get_text() == '':
tx, ty = self._get_xy_display()
return Bbox.from_... | class Text(Artist):
#return _unit_box
if not self.get_visible():
return Bbox.unit()
if dpi is None:
dpi = self.figure.dpi
if self.get_text() == '':
with cbook._setattr_cm(self.figure, dpi=dpi):
tx, ty = self._get_xy_display()
... | pytest lib/matplotlib/tests/test_text.py::test_non_default_dpi |
matplotlib | 11 | class Text(Artist):
if self._renderer is None:
raise RuntimeError('Cannot get window extent w/o renderer')
bbox, info, descent = self._get_layout(self._renderer)
x, y = self.get_unitless_position()
x, y = self.get_transform().transform((x, y))
bbox = bbox.translated(... | class Text(Artist):
if self._renderer is None:
raise RuntimeError('Cannot get window extent w/o renderer')
with cbook._setattr_cm(self.figure, dpi=dpi):
bbox, info, descent = self._get_layout(self._renderer)
x, y = self.get_unitless_position()
x, y = self... | pytest lib/matplotlib/tests/test_text.py::test_non_default_dpi |
matplotlib | 3 | class MarkerStyle:
self._snap_threshold = None
self._joinstyle = 'round'
self._capstyle = 'butt'
self._filled = True
self._marker_function()
def __bool__(self): | class MarkerStyle:
self._snap_threshold = None
self._joinstyle = 'round'
self._capstyle = 'butt'
# Initial guess: Assume the marker is filled unless the fillstyle is
# set to 'none'. The marker function will override this for unfilled
# markers.
self._filled = sel... | pytest lib/matplotlib/tests/test_marker.py::test_marker_fillstyle |
keras | 33 | def text_to_word_sequence(text,
if lower:
text = text.lower()
if sys.version_info < (3,) and isinstance(text, unicode):
translate_map = dict((ord(c), unicode(split)) for c in filters)
else:
translate_map = maketrans(filters, split * len(filters))
text = text.translate(translate... | def text_to_word_sequence(text,
if lower:
text = text.lower()
if sys.version_info < (3,):
if isinstance(text, unicode):
translate_map = dict((ord(c), unicode(split)) for c in filters)
text = text.translate(translate_map)
elif len(split) == 1:
translat... | pytest tests/keras/preprocessing/text_test.py::test_text_to_word_sequence_unicode_multichar_split |
pandas | 107 | 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... | pytest pandas/tests/frame/test_combine_concat.py::TestDataFrameConcatCommon::test_append_timestamps_aware_or_naive |
pandas | 34 | class TimeGrouper(Grouper):
# because replace() will swallow the nanosecond part
# thus last bin maybe slightly before the end if the end contains
# nanosecond part and lead to `Values falls after last bin` error
binner = labels = date_range(
freq=self.freq,
start... | class TimeGrouper(Grouper):
# because replace() will swallow the nanosecond part
# thus last bin maybe slightly before the end if the end contains
# nanosecond part and lead to `Values falls after last bin` error
# GH 25758: If DST lands at midnight (e.g. 'America/Havana'), user feedback... | pytest pandas/tests/resample/test_datetime_index.py::test_downsample_dst_at_midnight |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.