project
stringclasses
17 values
bug_id
int64
1
169
buggy
stringlengths
81
57.2k
fixed
stringlengths
85
31.2k
test_command
stringlengths
44
133
black
4
class EmptyLineTracker: lines (two on module-level). """ before, after = self._maybe_empty_lines(current_line) before -= self.previous_after self.previous_after = after self.previous_line = current_line return before, after
class EmptyLineTracker: lines (two on module-level). """ before, after = self._maybe_empty_lines(current_line) before = ( # Black should not insert empty lines at the beginning # of the file 0 if self.previous_line is None else ...
python -m unittest -q tests.test_black.BlackTestCase.test_beginning_backslash
pandas
27
from pandas._libs.tslibs import ( timezones, tzconversion, ) from pandas.errors import PerformanceWarning from pandas.core.dtypes.common import (
from pandas._libs.tslibs import ( timezones, tzconversion, ) import pandas._libs.tslibs.frequencies as libfrequencies from pandas.errors import PerformanceWarning from pandas.core.dtypes.common import (
pytest pandas/tests/indexes/datetimes/test_to_period.py::TestToPeriod::test_to_period_infer
pandas
27
default 'raise' "You must pass a freq argument as current index has none." ) freq = get_period_alias(freq) return PeriodArray._from_datetime64(self._data, freq, tz=self.tz)
default 'raise' "You must pass a freq argument as current index has none." ) res = get_period_alias(freq) # https://github.com/pandas-dev/pandas/issues/33358 if res is None: base, stride = libfrequencies._base_and_stride(freq) ...
pytest pandas/tests/indexes/datetimes/test_to_period.py::TestToPeriod::test_to_period_infer
scrapy
6
class ImagesPipeline(FilesPipeline): background = Image.new('RGBA', image.size, (255, 255, 255)) background.paste(image, image) image = background.convert('RGB') elif image.mode != 'RGB': image = image.convert('RGB')
class ImagesPipeline(FilesPipeline): background = Image.new('RGBA', image.size, (255, 255, 255)) background.paste(image, image) image = background.convert('RGB') elif image.mode == 'P': image = image.convert("RGBA") background = Image.new('RGBA', image...
python -m unittest -q tests.test_pipeline_images.ImagesPipelineTestCase.test_convert_image
ansible
10
class PamdRule(PamdLine): valid_control_actions = ['ignore', 'bad', 'die', 'ok', 'done', 'reset'] def __init__(self, rule_type, rule_control, rule_path, rule_args=None): self._control = None self._args = None self.rule_type = rule_type
class PamdRule(PamdLine): valid_control_actions = ['ignore', 'bad', 'die', 'ok', 'done', 'reset'] def __init__(self, rule_type, rule_control, rule_path, rule_args=None): self.prev = None self.next = None self._control = None self._args = None self.rule_type = rule_type
pytest test/units/modules/system/test_pamd.py::PamdServiceTestCase::test_remove_last_rule
ansible
10
class PamdService(object): if current_line.matches(rule_type, rule_control, rule_path): if current_line.prev is not None: current_line.prev.next = current_line.next current_line.next.prev = current_line.prev else: se...
class PamdService(object): if current_line.matches(rule_type, rule_control, rule_path): if current_line.prev is not None: current_line.prev.next = current_line.next if current_line.next is not None: current_line.next.prev = curr...
pytest test/units/modules/system/test_pamd.py::PamdServiceTestCase::test_remove_last_rule
pandas
48
class DataFrameGroupBy(GroupBy): result = type(block.values)._from_sequence( result.ravel(), dtype=block.values.dtype ) except ValueError: # reshape to be valid for non-Extension Block ...
class DataFrameGroupBy(GroupBy): result = type(block.values)._from_sequence( result.ravel(), dtype=block.values.dtype ) except (ValueError, TypeError): # reshape to be valid for non-Extension Block ...
pytest pandas/tests/groupby/test_function.py::test_apply_to_nullable_integer_returns_float
youtube-dl
39
from ..utils import ( compat_urllib_parse, compat_urllib_request, urlencode_postdata, ExtractorError, )
from ..utils import ( compat_urllib_parse, compat_urllib_request, urlencode_postdata, ExtractorError, limit_length, )
python -m unittest -q test.test_utils.TestUtil.test_limit_length
youtube-dl
39
class FacebookIE(InfoExtractor): 'duration': 38, 'title': 'Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam fin...', } }, { 'url': 'https://www.facebook.com/video.php?v=10204634152394104', 'only_matching': True,
class FacebookIE(InfoExtractor): 'duration': 38, 'title': 'Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam fin...', } }, { 'note': 'Video without discernible title', 'url': 'https://www.facebook.com/video.php?v=274175099429670', 'i...
python -m unittest -q test.test_utils.TestUtil.test_limit_length
youtube-dl
39
class FacebookIE(InfoExtractor): video_title = self._html_search_regex( r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>', webpage, 'alternative title', default=None) if len(video_title) > 80 + 3: ...
class FacebookIE(InfoExtractor): video_title = self._html_search_regex( r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>', webpage, 'alternative title', default=None) video_title = limit_length(video_title, 8...
python -m unittest -q test.test_utils.TestUtil.test_limit_length
youtube-dl
39
except AttributeError: if ret: raise subprocess.CalledProcessError(ret, p.args, output=output) return output
except AttributeError: if ret: raise subprocess.CalledProcessError(ret, p.args, output=output) return output def limit_length(s, length): """ Add ellipses to overly long strings """ if s is None: return None ELLIPSES = '...' if len(s) > length: return s[:len...
python -m unittest -q test.test_utils.TestUtil.test_limit_length
pandas
114
import pandas.core.algorithms as algos from pandas.core.arrays import ExtensionArray from pandas.core.base import IndexOpsMixin, PandasObject import pandas.core.common as com from pandas.core.indexers import maybe_convert_indices from pandas.core.indexes.frozen import FrozenList import pandas.core.missing as missing
import pandas.core.algorithms as algos from pandas.core.arrays import ExtensionArray from pandas.core.base import IndexOpsMixin, PandasObject import pandas.core.common as com from pandas.core.construction import extract_array from pandas.core.indexers import maybe_convert_indices from pandas.core.indexes.frozen import ...
pytest pandas/tests/extension/decimal/test_decimal.py::test_indexing_no_materialize
pandas
114
class Index(IndexOpsMixin, PandasObject): # if we have something that is Index-like, then # use this, e.g. DatetimeIndex # Things like `Series._get_value` (via .at) pass the EA directly here. s = getattr(series, "_values", series) if isinstance(s, (ExtensionArray, Index)) and is_...
class Index(IndexOpsMixin, PandasObject): # if we have something that is Index-like, then # use this, e.g. DatetimeIndex # Things like `Series._get_value` (via .at) pass the EA directly here. s = extract_array(series, extract_numpy=True) if isinstance(s, ExtensionArray): ...
pytest pandas/tests/extension/decimal/test_decimal.py::test_indexing_no_materialize
youtube-dl
3
def unescapeHTML(s): assert type(s) == compat_str return re.sub( r'&([^;]+;)', lambda m: _htmlentity_transform(m.group(1)), s) def get_subprocess_encoding():
def unescapeHTML(s): assert type(s) == compat_str return re.sub( r'&([^&;]+;)', lambda m: _htmlentity_transform(m.group(1)), s) def get_subprocess_encoding():
python -m unittest -q test.test_utils.TestUtil.test_unescape_html
thefuck
22
class SortedCorrectedCommandsSequence(object): def _realise(self): """Realises generator, removes duplicates and sorts commands.""" commands = self._remove_duplicates(self._commands) self._cached = [self._cached[0]] + sorted( commands, key=lambda corrected_command: corrected_com...
class SortedCorrectedCommandsSequence(object): def _realise(self): """Realises generator, removes duplicates and sorts commands.""" if self._cached: commands = self._remove_duplicates(self._commands) self._cached = [self._cached[0]] + sorted( commands, key=la...
pytest tests/test_types.py::TestSortedCorrectedCommandsSequence::test_with_blank
luigi
31
class CentralPlannerScheduler(Scheduler): tasks.sort(key=self._rank(), reverse=True) for task in tasks: in_workers = assistant or worker in task.workers if task.status == 'RUNNING' and in_workers: # Return a list of currently running tasks to the client, ...
class CentralPlannerScheduler(Scheduler): tasks.sort(key=self._rank(), reverse=True) for task in tasks: in_workers = (assistant and task.workers) or worker in task.workers if task.status == 'RUNNING' and in_workers: # Return a list of currently running tasks to t...
pytest test/central_planner_test.py::CentralPlannerTest::test_assistant_get_work_external_task
pandas
44
from pandas.core.dtypes.common import ( ensure_platform_int, is_bool, is_bool_dtype, is_categorical, is_categorical_dtype, is_datetime64_any_dtype, is_dtype_equal,
from pandas.core.dtypes.common import ( ensure_platform_int, is_bool, is_bool_dtype, is_categorical_dtype, is_datetime64_any_dtype, is_dtype_equal,
pytest pandas/tests/indexing/test_loc.py::test_loc_datetimelike_mismatched_dtypes
pandas
44
class Index(IndexOpsMixin, PandasObject): return self._constructor(values, **attributes) except (TypeError, ValueError): pass return Index(values, **attributes) def _update_inplace(self, result, **kwargs):
class Index(IndexOpsMixin, PandasObject): return self._constructor(values, **attributes) except (TypeError, ValueError): pass # Remove tz so Index will try non-DatetimeIndex inference attributes.pop("tz", None) return Index(values, **attributes) ...
pytest pandas/tests/indexing/test_loc.py::test_loc_datetimelike_mismatched_dtypes
pandas
44
class Index(IndexOpsMixin, PandasObject): if pself is not self or ptarget is not target: return pself.get_indexer_non_unique(ptarget) if is_categorical(target): tgt_values = np.asarray(target) elif self.is_all_dates and target.is_all_dates: # GH 30399 tgt_va...
class Index(IndexOpsMixin, PandasObject): if pself is not self or ptarget is not target: return pself.get_indexer_non_unique(ptarget) if is_categorical_dtype(target.dtype): tgt_values = np.asarray(target) else: tgt_values = target._get_engine_target()
pytest pandas/tests/indexing/test_loc.py::test_loc_datetimelike_mismatched_dtypes
pandas
44
import numpy as np from pandas._libs import NaT, iNaT, join as libjoin, lib from pandas._libs.tslibs import timezones from pandas._typing import Label from pandas.compat.numpy import function as nv from pandas.errors import AbstractMethodError from pandas.util._decorators import Appender, cache_readonly, doc from pan...
import numpy as np from pandas._libs import NaT, iNaT, join as libjoin, lib from pandas._libs.tslibs import timezones from pandas._typing import DtypeObj, Label from pandas.compat.numpy import function as nv from pandas.errors import AbstractMethodError from pandas.util._decorators import Appender, cache_readonly, doc...
pytest pandas/tests/indexing/test_loc.py::test_loc_datetimelike_mismatched_dtypes
pandas
44
from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin from pandas.core.base import IndexOpsMixin import pandas.core.indexes.base as ibase from pandas.core.indexes.base import Index, _index_shared_docs from pandas.core.indexes.extensi...
from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin from pandas.core.base import IndexOpsMixin import pandas.core.indexes.base as ibase from pandas.core.indexes.base import Index, _index_shared_docs, ensure_index from pandas.core.i...
pytest pandas/tests/indexing/test_loc.py::test_loc_datetimelike_mismatched_dtypes
pandas
44
class DatetimeIndexOpsMixin(ExtensionIndex): def is_all_dates(self) -> bool: return True # ------------------------------------------------------------------------ # Abstract data attributes
class DatetimeIndexOpsMixin(ExtensionIndex): def is_all_dates(self) -> bool: return True def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: """ Can we compare values of the given dtype to our own? """ raise AbstractMethodError(self) # -------------------------...
pytest pandas/tests/indexing/test_loc.py::test_loc_datetimelike_mismatched_dtypes
pandas
44
class DatetimeIndexOpsMixin(ExtensionIndex): # try to find the dates return (lhs_mask & rhs_mask).nonzero()[0] # -------------------------------------------------------------------- __add__ = make_wrapped_arith_op("__add__")
class DatetimeIndexOpsMixin(ExtensionIndex): # try to find the dates return (lhs_mask & rhs_mask).nonzero()[0] @Appender(Index.get_indexer_non_unique.__doc__) def get_indexer_non_unique(self, target): target = ensure_index(target) pself, ptarget = self._maybe_promote(tar...
pytest pandas/tests/indexing/test_loc.py::test_loc_datetimelike_mismatched_dtypes
pandas
44
import numpy as np from pandas._libs import NaT, Period, Timestamp, index as libindex, lib, tslib as libts from pandas._libs.tslibs import fields, parsing, timezones from pandas._typing import Label from pandas.util._decorators import cache_readonly from pandas.core.dtypes.common import _NS_DTYPE, is_float, is_intege...
import numpy as np from pandas._libs import NaT, Period, Timestamp, index as libindex, lib, tslib as libts from pandas._libs.tslibs import fields, parsing, timezones from pandas._typing import DtypeObj, Label from pandas.util._decorators import cache_readonly from pandas.core.dtypes.common import ( _NS_DTYPE, ...
pytest pandas/tests/indexing/test_loc.py::test_loc_datetimelike_mismatched_dtypes
pandas
44
class DatetimeIndex(DatetimeTimedeltaMixin): return Timestamp(value).asm8 raise ValueError("Passed item and index have different timezone") # -------------------------------------------------------------------- # Rendering Methods
class DatetimeIndex(DatetimeTimedeltaMixin): return Timestamp(value).asm8 raise ValueError("Passed item and index have different timezone") def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: """ Can we compare values of the given dtype to our own? """ if no...
pytest pandas/tests/indexing/test_loc.py::test_loc_datetimelike_mismatched_dtypes
pandas
44
from pandas._libs.lib import no_default from pandas._libs.tslibs import frequencies as libfrequencies, resolution from pandas._libs.tslibs.parsing import parse_time_string from pandas._libs.tslibs.period import Period from pandas._typing import Label from pandas.util._decorators import Appender, cache_readonly from pa...
from pandas._libs.lib import no_default from pandas._libs.tslibs import frequencies as libfrequencies, resolution from pandas._libs.tslibs.parsing import parse_time_string from pandas._libs.tslibs.period import Period from pandas._typing import DtypeObj, Label from pandas.util._decorators import Appender, cache_readonl...
pytest pandas/tests/indexing/test_loc.py::test_loc_datetimelike_mismatched_dtypes
pandas
44
from pandas.core.dtypes.common import ( is_scalar, pandas_dtype, ) from pandas.core.arrays.period import ( PeriodArray,
from pandas.core.dtypes.common import ( is_scalar, pandas_dtype, ) from pandas.core.dtypes.dtypes import PeriodDtype from pandas.core.arrays.period import ( PeriodArray,
pytest pandas/tests/indexing/test_loc.py::test_loc_datetimelike_mismatched_dtypes
pandas
44
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index): # raise when input doesn't have freq raise raise_on_incompatible(self, None) # ------------------------------------------------------------------------ # Rendering Methods
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index): # raise when input doesn't have freq raise raise_on_incompatible(self, None) def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: """ Can we compare values of the given dtype to our own? """ if not isinstance(...
pytest pandas/tests/indexing/test_loc.py::test_loc_datetimelike_mismatched_dtypes
pandas
44
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index): def get_indexer_non_unique(self, target): target = ensure_index(target) if isinstance(target, PeriodIndex): if target.freq != self.freq: no_matches = -1 * np.ones(self.shape, dtype=np.intp) return no_m...
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index): def get_indexer_non_unique(self, target): target = ensure_index(target) if not self._is_comparable_dtype(target.dtype): no_matches = -1 * np.ones(self.shape, dtype=np.intp) return no_matches, no_matches target = ...
pytest pandas/tests/indexing/test_loc.py::test_loc_datetimelike_mismatched_dtypes
pandas
44
""" implement the TimedeltaIndex """ from pandas._libs import NaT, Timedelta, index as libindex from pandas._typing import Label from pandas.util._decorators import Appender from pandas.core.dtypes.common import (
""" implement the TimedeltaIndex """ from pandas._libs import NaT, Timedelta, index as libindex from pandas._typing import DtypeObj, Label from pandas.util._decorators import Appender from pandas.core.dtypes.common import (
pytest pandas/tests/indexing/test_loc.py::test_loc_datetimelike_mismatched_dtypes
pandas
44
class TimedeltaIndex(DatetimeTimedeltaMixin, dtl.TimelikeOps): other = TimedeltaIndex(other) return self, other def get_loc(self, key, method=None, tolerance=None): """ Get integer location for requested label
class TimedeltaIndex(DatetimeTimedeltaMixin, dtl.TimelikeOps): other = TimedeltaIndex(other) return self, other def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: """ Can we compare values of the given dtype to our own? """ return is_timedelta64_dtype(dtype...
pytest pandas/tests/indexing/test_loc.py::test_loc_datetimelike_mismatched_dtypes
youtube-dl
35
class ArteTVPlus7IE(InfoExtractor): info = self._download_json(json_url, video_id) player_info = info['videoJsonPlayer'] info_dict = { 'id': player_info['VID'], 'title': player_info['VTI'], 'description': player_info.get('VDE'), 'upload_date': uni...
class ArteTVPlus7IE(InfoExtractor): info = self._download_json(json_url, video_id) player_info = info['videoJsonPlayer'] upload_date_str = player_info.get('shootingDate') if not upload_date_str: upload_date_str = player_info.get('VDA', '').split(' ')[0] info_dict = ...
python -m unittest -q test.test_utils.TestUtil.test_unified_dates
youtube-dl
35
def unified_strdate(date_str): '%d/%m/%Y', '%d/%m/%y', '%Y/%m/%d %H:%M:%S', '%Y-%m-%d %H:%M:%S', '%d.%m.%Y %H:%M', '%d.%m.%Y %H.%M',
def unified_strdate(date_str): '%d/%m/%Y', '%d/%m/%y', '%Y/%m/%d %H:%M:%S', '%d/%m/%Y %H:%M:%S', '%Y-%m-%d %H:%M:%S', '%d.%m.%Y %H:%M', '%d.%m.%Y %H.%M',
python -m unittest -q test.test_utils.TestUtil.test_unified_dates
pandas
118
from pandas.core.dtypes.generic import ABCMultiIndex from pandas.core.dtypes.missing import notna from pandas.core.arrays import Categorical from pandas.core.frame import DataFrame, _shared_docs from pandas.core.indexes.base import Index from pandas.core.reshape.concat import concat
from pandas.core.dtypes.generic import ABCMultiIndex from pandas.core.dtypes.missing import notna from pandas.core.arrays import Categorical import pandas.core.common as com from pandas.core.frame import DataFrame, _shared_docs from pandas.core.indexes.base import Index from pandas.core.reshape.concat import concat
pytest pandas/tests/reshape/test_melt.py::TestMelt::test_melt_mixed_int_str_value_vars
pandas
118
def melt( else: # Check that `id_vars` are in frame id_vars = list(id_vars) missing = Index(np.ravel(id_vars)).difference(cols) if not missing.empty: raise KeyError( "The following 'id_vars' are not present"
def melt( else: # Check that `id_vars` are in frame id_vars = list(id_vars) missing = Index(com.flatten(id_vars)).difference(cols) if not missing.empty: raise KeyError( "The following 'id_vars' are not present"
pytest pandas/tests/reshape/test_melt.py::TestMelt::test_melt_mixed_int_str_value_vars
pandas
118
def melt( else: value_vars = list(value_vars) # Check that `value_vars` are in frame missing = Index(np.ravel(value_vars)).difference(cols) if not missing.empty: raise KeyError( "The following 'value_vars' are not present in"
def melt( else: value_vars = list(value_vars) # Check that `value_vars` are in frame missing = Index(com.flatten(value_vars)).difference(cols) if not missing.empty: raise KeyError( "The following 'value_vars' are not present in"
pytest pandas/tests/reshape/test_melt.py::TestMelt::test_melt_mixed_int_str_value_vars
ansible
5
def check_required_arguments(argument_spec, module_parameters): missing.append(k) if missing: msg = "missing required arguments: %s" % ", ".join(missing) raise TypeError(to_native(msg)) return missing
def check_required_arguments(argument_spec, module_parameters): missing.append(k) if missing: msg = "missing required arguments: %s" % ", ".join(sorted(missing)) raise TypeError(to_native(msg)) return missing
pytest test/units/module_utils/common/validation/test_check_required_arguments.py::test_check_required_arguments_missing_multiple
ansible
5
def test_check_mutually_exclusive_found(mutually_exclusive_terms): 'fox': 'red', 'socks': 'blue', } expected = "TypeError('parameters are mutually exclusive: string1|string2, box|fox|socks',)" with pytest.raises(TypeError) as e: check_mutually_exclusive(mutually_exclusive_terms, par...
def test_check_mutually_exclusive_found(mutually_exclusive_terms): 'fox': 'red', 'socks': 'blue', } expected = "parameters are mutually exclusive: string1|string2, box|fox|socks" with pytest.raises(TypeError) as e: check_mutually_exclusive(mutually_exclusive_terms, params) asse...
pytest test/units/module_utils/common/validation/test_check_required_arguments.py::test_check_required_arguments_missing_multiple
ansible
5
def test_check_mutually_exclusive_none(): def test_check_mutually_exclusive_no_params(mutually_exclusive_terms): with pytest.raises(TypeError) as te: check_mutually_exclusive(mutually_exclusive_terms, None) assert "TypeError: 'NoneType' object is not iterable" in to_native(te.error)
def test_check_mutually_exclusive_none(): def test_check_mutually_exclusive_no_params(mutually_exclusive_terms): with pytest.raises(TypeError) as te: check_mutually_exclusive(mutually_exclusive_terms, None) assert "'NoneType' object is not iterable" in to_native(te.value)
pytest test/units/module_utils/common/validation/test_check_required_arguments.py::test_check_required_arguments_missing_multiple
tqdm
6
class tqdm(object): return self.total if self.iterable is None else \ (self.iterable.shape[0] if hasattr(self.iterable, "shape") else len(self.iterable) if hasattr(self.iterable, "__len__") else self.total) def __enter__(self): return self
class tqdm(object): return self.total if self.iterable is None else \ (self.iterable.shape[0] if hasattr(self.iterable, "shape") else len(self.iterable) if hasattr(self.iterable, "__len__") else getattr(self, "total", None)) def __enter__(self): return self
python3 -m pytest tqdm/tests/tests_synchronisation.py::test_imap
black
8
def bracket_split_build_line( if leaves: # Since body is a new indent level, remove spurious leading whitespace. normalize_prefix(leaves[0], inside_brackets=True) # Ensure a trailing comma when expected. if original.is_import: if leaves[-1].type !=...
def bracket_split_build_line( if leaves: # Since body is a new indent level, remove spurious leading whitespace. normalize_prefix(leaves[0], inside_brackets=True) # Ensure a trailing comma for imports, but be careful not to add one after # any comments. ...
python -m unittest -q tests.test_black.BlackTestCase.test_comments7
keras
43
def to_categorical(y, num_classes=None): """ y = np.array(y, dtype='int') input_shape = y.shape y = y.ravel() if not num_classes: num_classes = np.max(y) + 1
def to_categorical(y, num_classes=None): """ y = np.array(y, dtype='int') input_shape = y.shape if input_shape and input_shape[-1] == 1: input_shape = tuple(input_shape[:-1]) y = y.ravel() if not num_classes: num_classes = np.max(y) + 1
pytest tests/keras/utils/np_utils_test.py::test_to_categorical
pandas
65
import bz2 from collections import abc import gzip from io import BufferedIOBase, BytesIO import mmap import os import pathlib
import bz2 from collections import abc import gzip from io import BufferedIOBase, BytesIO, RawIOBase import mmap import os import pathlib
pytest pandas/tests/io/parser/test_encoding.py::test_binary_mode_file_buffers
pandas
65
def get_handle( try: from s3fs import S3File need_text_wrapping = (BufferedIOBase, S3File) except ImportError: need_text_wrapping = BufferedIOBase # type: ignore handles: List[IO] = list() f = path_or_buf
def get_handle( try: from s3fs import S3File need_text_wrapping = (BufferedIOBase, RawIOBase, S3File) except ImportError: need_text_wrapping = (BufferedIOBase, RawIOBase) # type: ignore handles: List[IO] = list() f = path_or_buf
pytest pandas/tests/io/parser/test_encoding.py::test_binary_mode_file_buffers
pandas
65
def get_handle( from io import TextIOWrapper g = TextIOWrapper(f, encoding=encoding, newline="") if not isinstance(f, BufferedIOBase): handles.append(g) f = g
def get_handle( from io import TextIOWrapper g = TextIOWrapper(f, encoding=encoding, newline="") if not isinstance(f, (BufferedIOBase, RawIOBase)): handles.append(g) f = g
pytest pandas/tests/io/parser/test_encoding.py::test_binary_mode_file_buffers
pandas
65
Module contains tools for processing files into DataFrames or other objects from collections import abc, defaultdict import csv import datetime from io import BufferedIOBase, StringIO, TextIOWrapper import re import sys from textwrap import fill
Module contains tools for processing files into DataFrames or other objects from collections import abc, defaultdict import csv import datetime from io import BufferedIOBase, RawIOBase, StringIO, TextIOWrapper import re import sys from textwrap import fill
pytest pandas/tests/io/parser/test_encoding.py::test_binary_mode_file_buffers
pandas
65
class CParserWrapper(ParserBase): # Handle the file object with universal line mode enabled. # We will handle the newline character ourselves later on. if isinstance(src, BufferedIOBase): src = TextIOWrapper(src, encoding=encoding, newline="") kwds["enco...
class CParserWrapper(ParserBase): # Handle the file object with universal line mode enabled. # We will handle the newline character ourselves later on. if isinstance(src, (BufferedIOBase, RawIOBase)): src = TextIOWrapper(src, encoding=encoding, newline="") ...
pytest pandas/tests/io/parser/test_encoding.py::test_binary_mode_file_buffers
cookiecutter
2
def find_hook(hook_name, hooks_dir='hooks'): logger.debug('No hooks/dir in template_dir') return None for hook_file in os.listdir(hooks_dir): if valid_hook(hook_file, hook_name): return os.path.abspath(os.path.join(hooks_dir, hook_file)) return None def run_script(script_...
def find_hook(hook_name, hooks_dir='hooks'): logger.debug('No hooks/dir in template_dir') return None scripts = [] for hook_file in os.listdir(hooks_dir): if valid_hook(hook_file, hook_name): scripts.append(os.path.abspath(os.path.join(hooks_dir, hook_file))) if len(scr...
tox tests/test_hooks.py::TestExternalHooks::test_run_hook
cookiecutter
2
def run_hook(hook_name, project_dir, context): :param project_dir: The directory to execute the script from. :param context: Cookiecutter project context. """ script = find_hook(hook_name) if script is None: logger.debug('No %s hook found', hook_name) return logger.debug('Running...
def run_hook(hook_name, project_dir, context): :param project_dir: The directory to execute the script from. :param context: Cookiecutter project context. """ scripts = find_hook(hook_name) if not scripts: logger.debug('No %s hook found', hook_name) return logger.debug('Running h...
tox tests/test_hooks.py::TestExternalHooks::test_run_hook
pandas
98
class Index(IndexOpsMixin, PandasObject): return CategoricalIndex(data, dtype=dtype, copy=copy, name=name, **kwargs) # interval elif ( is_interval_dtype(data) or is_interval_dtype(dtype) ) and not is_object_dtype(dtype): closed = kwargs.get("closed", None) ...
class Index(IndexOpsMixin, PandasObject): return CategoricalIndex(data, dtype=dtype, copy=copy, name=name, **kwargs) # interval elif is_interval_dtype(data) or is_interval_dtype(dtype): closed = kwargs.pop("closed", None) if is_dtype_equal(_o_dtype, dtype): ...
pytest pandas/tests/indexes/period/test_constructors.py::TestPeriodIndex::test_base_constructor_with_period_dtype
pandas
98
class Index(IndexOpsMixin, PandasObject): else: return TimedeltaIndex(data, copy=copy, name=name, dtype=dtype, **kwargs) elif is_period_dtype(data) and not is_object_dtype(dtype): return PeriodIndex(data, copy=copy, name=name, **kwargs) # extension dtype ...
class Index(IndexOpsMixin, PandasObject): else: return TimedeltaIndex(data, copy=copy, name=name, dtype=dtype, **kwargs) elif is_period_dtype(data) or is_period_dtype(dtype): if is_dtype_equal(_o_dtype, dtype): return PeriodIndex(data, copy=False, name=na...
pytest pandas/tests/indexes/period/test_constructors.py::TestPeriodIndex::test_base_constructor_with_period_dtype
pandas
139
class Grouping: self._group_index = CategoricalIndex( Categorical.from_codes( codes=codes, categories=categories, ordered=self.grouper.ordered ) ) # we are done
class Grouping: self._group_index = CategoricalIndex( Categorical.from_codes( codes=codes, categories=categories, ordered=self.grouper.ordered ), name=self.name, ) # we are done
pytest pandas/tests/groupby/test_categorical.py::test_preserve_categories
tornado
6
import threading import time import traceback import math import weakref from tornado.concurrent import Future, is_future, chain_future, future_set_exc_info, future_add_done_callback # noqa: E501 from tornado.log import app_log, gen_log
import threading import time import traceback import math from tornado.concurrent import Future, is_future, chain_future, future_set_exc_info, future_add_done_callback # noqa: E501 from tornado.log import app_log, gen_log
python -m unittest -q tornado.test.asyncio_test.LeakTest.test_asyncio_close_leak
tornado
6
class IOLoop(Configurable): _current = threading.local() # In Python 3, _ioloop_for_asyncio maps from asyncio loops to IOLoops. _ioloop_for_asyncio = weakref.WeakKeyDictionary() @classmethod def configure(cls, impl, **kwargs):
class IOLoop(Configurable): _current = threading.local() # In Python 3, _ioloop_for_asyncio maps from asyncio loops to IOLoops. _ioloop_for_asyncio = dict() @classmethod def configure(cls, impl, **kwargs):
python -m unittest -q tornado.test.asyncio_test.LeakTest.test_asyncio_close_leak
tornado
6
class BaseAsyncIOLoop(IOLoop): self.readers = set() self.writers = set() self.closing = False IOLoop._ioloop_for_asyncio[asyncio_loop] = self super(BaseAsyncIOLoop, self).initialize(**kwargs)
class BaseAsyncIOLoop(IOLoop): self.readers = set() self.writers = set() self.closing = False # If an asyncio loop was closed through an asyncio interface # instead of IOLoop.close(), we'd never hear about it and may # have left a dangling reference in our map. In case an...
python -m unittest -q tornado.test.asyncio_test.LeakTest.test_asyncio_close_leak
tornado
6
class BaseAsyncIOLoop(IOLoop): if all_fds: self.close_fd(fileobj) self.asyncio_loop.close() def add_handler(self, fd, handler, events): fd, fileobj = self.split_fd(fd)
class BaseAsyncIOLoop(IOLoop): if all_fds: self.close_fd(fileobj) self.asyncio_loop.close() del IOLoop._ioloop_for_asyncio[self.asyncio_loop] def add_handler(self, fd, handler, events): fd, fileobj = self.split_fd(fd)
python -m unittest -q tornado.test.asyncio_test.LeakTest.test_asyncio_close_leak
youtube-dl
14
class YoutubeIE(YoutubeBaseInfoExtractor): video_id = mobj.group(2) return video_id @staticmethod def _extract_chapters(description, duration): if not description: return None chapter_lines = re.findall(
class YoutubeIE(YoutubeBaseInfoExtractor): video_id = mobj.group(2) return video_id def _extract_chapters_from_json(self, webpage, video_id, duration): if not webpage: return player = self._parse_json( self._search_regex( r'RELATED_PLAYER_ARGS...
python -m unittest -q test.test_youtube_chapters.TestYoutubeChapters.test_youtube_chapters
youtube-dl
14
class YoutubeIE(YoutubeBaseInfoExtractor): }) return chapters def _real_extract(self, url): url, smuggled_data = unsmuggle_url(url, {})
class YoutubeIE(YoutubeBaseInfoExtractor): }) return chapters def _extract_chapters(self, webpage, description, video_id, duration): return (self._extract_chapters_from_json(webpage, video_id, duration) or self._extract_chapters_from_description(description, duration)) ...
python -m unittest -q test.test_youtube_chapters.TestYoutubeChapters.test_youtube_chapters
youtube-dl
14
class YoutubeIE(YoutubeBaseInfoExtractor): errnote='Unable to download video annotations', fatal=False, data=urlencode_postdata({xsrf_field_name: xsrf_token})) chapters = self._extract_chapters(description_original, video_duration) # Look for the DASH manifest ...
class YoutubeIE(YoutubeBaseInfoExtractor): errnote='Unable to download video annotations', fatal=False, data=urlencode_postdata({xsrf_field_name: xsrf_token})) chapters = self._extract_chapters(video_webpage, description_original, video_id, video_duration) # Loo...
python -m unittest -q test.test_youtube_chapters.TestYoutubeChapters.test_youtube_chapters
matplotlib
23
class _AxesBase(martist.Artist): return dL = self.dataLim x0, x1 = map(x_trf.inverted().transform, dL.intervalx) y0, y1 = map(y_trf.inverted().transform, dL.intervaly) xr = 1.05 * (x1 - x0) yr = 1.05 * (y1 - y0)
class _AxesBase(martist.Artist): return dL = self.dataLim x0, x1 = map(x_trf.transform, dL.intervalx) y0, y1 = map(y_trf.transform, dL.intervaly) xr = 1.05 * (x1 - x0) yr = 1.05 * (y1 - y0)
pytest lib/matplotlib/tests/test_axes.py::test_aspect_nonlinear_adjustable_datalim
pandas
156
class SparseDataFrame(DataFrame): this, other = self.align(other, join="outer", axis=0, level=level, copy=False) new_data = {} for col, series in this.items(): new_data[col] = func(series.values, other.values) fill_value = self._get_op_result_fill_value(other, func)
class SparseDataFrame(DataFrame): this, other = self.align(other, join="outer", axis=0, level=level, copy=False) new_data = {} for col in this.columns: new_data[col] = func(this[col], other) fill_value = self._get_op_result_fill_value(other, func)
pytest pandas/tests/sparse/frame/test_frame.py::TestSparseDataFrameArithmetic::test_add_series_retains_dtype
pandas
156
class SparseDataFrame(DataFrame): new_data = {} for col in left.columns: new_data[col] = func(left[col], float(right[col])) return self._constructor( new_data,
class SparseDataFrame(DataFrame): new_data = {} for col in left.columns: new_data[col] = func(left[col], right[col]) return self._constructor( new_data,
pytest pandas/tests/sparse/frame/test_frame.py::TestSparseDataFrameArithmetic::test_add_series_retains_dtype
luigi
10
class Worker(object): return six.moves.filter(lambda task: task.status in [PENDING, RUNNING], self.tasks) else: return state.get_pending_tasks() def is_trivial_worker(self, state): """
class Worker(object): return six.moves.filter(lambda task: task.status in [PENDING, RUNNING], self.tasks) else: return six.moves.filter(lambda task: self.id in task.workers, state.get_pending_tasks()) def is_trivial_worker(self, state): ""...
pytest test/scheduler_test.py::SchedulerWorkerTest::test_get_pending_tasks_with_many_done_tasks
keras
5
def get_file(fname, Path to the downloaded file """ # noqa if cache_dir is None: cache_dir = os.path.join(os.path.expanduser('~'), '.keras') if md5_hash is not None and file_hash is None: file_hash = md5_hash hash_algorithm = 'md5'
def get_file(fname, Path to the downloaded file """ # noqa if cache_dir is None: if 'KERAS_HOME' in os.environ: cache_dir = os.environ.get('KERAS_HOME') else: cache_dir = os.path.join(os.path.expanduser('~'), '.keras') if md5_hash is not None and file_hash is...
pytest tests/keras/utils/data_utils_test.py::test_data_utils
pandas
1
def is_string_dtype(arr_or_dtype) -> bool: """ These have kind = "O" but aren't string dtypes so need to be explicitly excluded """ is_excluded_checks = (is_period_dtype, is_interval_dtype) return any(is_excluded(dtype) for is_excluded in is_excluded_checks) return _is_dtype...
def is_string_dtype(arr_or_dtype) -> bool: """ These have kind = "O" but aren't string dtypes so need to be explicitly excluded """ is_excluded_checks = (is_period_dtype, is_interval_dtype, is_categorical_dtype) return any(is_excluded(dtype) for is_excluded in is_excluded_checks)...
pytest pandas/tests/dtypes/test_dtypes.py::TestCategoricalDtype::test_not_string
matplotlib
13
class Path: if not args: return Path(np.empty([0, 2], dtype=np.float32)) vertices = np.concatenate([x.vertices for x in args]) codes = np.empty(len(vertices), dtype=cls.code_type) i = 0
class Path: if not args: return Path(np.empty([0, 2], dtype=np.float32)) # concatenate paths vertices = np.concatenate([x.vertices for x in args]) codes = np.empty(len(vertices), dtype=cls.code_type) i = 0
pytest lib/matplotlib/tests/test_path.py::test_make_compound_path_stops
matplotlib
13
class Path: codes[i:i + len(path.codes)] = path.codes i += len(path.vertices) return cls(vertices, codes) def __repr__(self):
class Path: codes[i:i + len(path.codes)] = path.codes i += len(path.vertices) # remove internal STOP's, replace kinal stop if present last_vert = None if codes.size > 0 and codes[-1] == cls.STOP: last_vert = vertices[-1] vertices = vertices[codes ...
pytest lib/matplotlib/tests/test_path.py::test_make_compound_path_stops
fastapi
7
from fastapi.exceptions import RequestValidationError from starlette.exceptions import HTTPException from starlette.requests import Request
from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError from starlette.exceptions import HTTPException from starlette.requests import Request
pytest tests/test_multi_body_errors.py::test_jsonable_encoder_requiring_error
fastapi
7
async def request_validation_exception_handler( request: Request, exc: RequestValidationError ) -> JSONResponse: return JSONResponse( status_code=HTTP_422_UNPROCESSABLE_ENTITY, content={"detail": exc.errors()} )
async def request_validation_exception_handler( request: Request, exc: RequestValidationError ) -> JSONResponse: return JSONResponse( status_code=HTTP_422_UNPROCESSABLE_ENTITY, content={"detail": jsonable_encoder(exc.errors())}, )
pytest tests/test_multi_body_errors.py::test_jsonable_encoder_requiring_error
pandas
166
class DataFrame(NDFrame): # join indexes only using concat if can_concat: if how == "left": res = concat(frames, axis=1, join="outer", verify_integrity=True) return res.reindex(self.index, copy=False) else: ...
class DataFrame(NDFrame): # join indexes only using concat if can_concat: if how == "left": res = concat( frames, axis=1, join="outer", verify_integrity=True, sort=sort ) return res.reindex(self.i...
pytest pandas/tests/frame/test_join.py::test_suppress_future_warning_with_sort_kw
luigi
20
class Task(object): params_str = {} params = dict(self.get_params()) for param_name, param_value in six.iteritems(self.param_kwargs): if params[param_name].significant: params_str[param_name] = params[param_name].serialize(param_value) return params_str
class Task(object): params_str = {} params = dict(self.get_params()) for param_name, param_value in six.iteritems(self.param_kwargs): params_str[param_name] = params[param_name].serialize(param_value) return params_str
pytest test/task_test.py::TaskTest::test_task_to_str_to_task
pandas
55
class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin): res._is_copy = self._is_copy return res def _iget_item_cache(self, item): """Return the cached item, item represents a positional indexer.""" ax = self._info_axis if ax.is_unique: lower = se...
class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin): res._is_copy = self._is_copy return res def _iget_item_cache(self, item: int): """Return the cached item, item represents a positional indexer.""" ax = self._info_axis if ax.is_unique: lower...
pytest pandas/tests/indexing/test_iloc.py::TestiLoc2::test_is_scalar_access
pandas
55
class _iLocIndexer(_LocationIndexer): if not is_integer(k): return False ax = self.obj.axes[i] if not ax.is_unique: return False return True def _validate_integer(self, key: int, axis: int) -> None:
class _iLocIndexer(_LocationIndexer): if not is_integer(k): return False return True def _validate_integer(self, key: int, axis: int) -> None:
pytest pandas/tests/indexing/test_iloc.py::TestiLoc2::test_is_scalar_access
pandas
109
class Categorical(ExtensionArray, PandasObject): Only ordered `Categoricals` have a minimum! Raises ------ TypeError
class Categorical(ExtensionArray, PandasObject): Only ordered `Categoricals` have a minimum! .. versionchanged:: 1.0.0 Returns an NA value on empty arrays Raises ------ TypeError
pytest pandas/tests/arrays/categorical/test_analytics.py::TestCategoricalAnalytics::test_min_max_ordered_empty
pandas
109
class Categorical(ExtensionArray, PandasObject): min : the minimum of this `Categorical` """ self.check_for_ordered("min") good = self._codes != -1 if not good.all(): if skipna:
class Categorical(ExtensionArray, PandasObject): min : the minimum of this `Categorical` """ self.check_for_ordered("min") if not len(self._codes): return self.dtype.na_value good = self._codes != -1 if not good.all(): if skipna:
pytest pandas/tests/arrays/categorical/test_analytics.py::TestCategoricalAnalytics::test_min_max_ordered_empty
pandas
109
class Categorical(ExtensionArray, PandasObject): Only ordered `Categoricals` have a maximum! Raises ------ TypeError
class Categorical(ExtensionArray, PandasObject): Only ordered `Categoricals` have a maximum! .. versionchanged:: 1.0.0 Returns an NA value on empty arrays Raises ------ TypeError
pytest pandas/tests/arrays/categorical/test_analytics.py::TestCategoricalAnalytics::test_min_max_ordered_empty
pandas
109
class Categorical(ExtensionArray, PandasObject): max : the maximum of this `Categorical` """ self.check_for_ordered("max") good = self._codes != -1 if not good.all(): if skipna:
class Categorical(ExtensionArray, PandasObject): max : the maximum of this `Categorical` """ self.check_for_ordered("max") if not len(self._codes): return self.dtype.na_value good = self._codes != -1 if not good.all(): if skipna:
pytest pandas/tests/arrays/categorical/test_analytics.py::TestCategoricalAnalytics::test_min_max_ordered_empty
youtube-dl
24
def _match_one(filter_part, dct): m = operator_rex.search(filter_part) if m: op = COMPARISON_OPERATORS[m.group('op')] if m.group('strval') is not None: if m.group('op') not in ('=', '!='): raise ValueError( 'Operator %s does not support string valu...
def _match_one(filter_part, dct): m = operator_rex.search(filter_part) if m: op = COMPARISON_OPERATORS[m.group('op')] actual_value = dct.get(m.group('key')) if (m.group('strval') is not None or # If the original field is a string and matching comparisonvalue is # ...
python -m unittest -q test.test_YoutubeDL.TestYoutubeDL.test_match_filter
youtube-dl
24
def _match_one(filter_part, dct): raise ValueError( 'Invalid integer value %r in filter part %r' % ( m.group('intval'), filter_part)) actual_value = dct.get(m.group('key')) if actual_value is None: return m.group('none_i...
def _match_one(filter_part, dct): raise ValueError( 'Invalid integer value %r in filter part %r' % ( m.group('intval'), filter_part)) if actual_value is None: return m.group('none_inclusive') return op(actual_value, comp...
python -m unittest -q test.test_YoutubeDL.TestYoutubeDL.test_match_filter
matplotlib
1
from matplotlib._pylab_helpers import Gcf from matplotlib.backend_managers import ToolManager from matplotlib.transforms import Affine2D from matplotlib.path import Path _log = logging.getLogger(__name__)
from matplotlib._pylab_helpers import Gcf from matplotlib.backend_managers import ToolManager from matplotlib.transforms import Affine2D from matplotlib.path import Path from matplotlib.cbook import _setattr_cm _log = logging.getLogger(__name__)
pytest lib/matplotlib/tests/test_bbox_tight.py::test_noop_tight_bbox
matplotlib
1
class KeyEvent(LocationEvent): self.key = key def _get_renderer(figure, print_method=None, *, draw_disabled=False): """ Get the renderer that would be used to save a `~.Figure`, and cache it on the figure. If *draw_disabled* is True, additionally replace drawing methods on *renderer* by n...
class KeyEvent(LocationEvent): self.key = key def _get_renderer(figure, print_method=None): """ Get the renderer that would be used to save a `~.Figure`, and cache it on the figure. If you need a renderer without any active draw methods use cbook._setattr_cm to temporary patch them out at...
pytest lib/matplotlib/tests/test_bbox_tight.py::test_noop_tight_bbox
matplotlib
1
def _get_renderer(figure, print_method=None, *, draw_disabled=False): except Done as exc: renderer, = figure._cachedRenderer, = exc.args if draw_disabled: for meth_name in dir(RendererBase): if (meth_name.startswith("draw_") or meth_name in ["open_group",...
def _get_renderer(figure, print_method=None, *, draw_disabled=False): except Done as exc: renderer, = figure._cachedRenderer, = exc.args return renderer
pytest lib/matplotlib/tests/test_bbox_tight.py::test_noop_tight_bbox
matplotlib
1
class FigureCanvasBase: renderer = _get_renderer( self.figure, functools.partial( print_method, orientation=orientation), draw_disabled=True) self.figure.draw(renderer) ...
class FigureCanvasBase: renderer = _get_renderer( self.figure, functools.partial( print_method, orientation=orientation) ) no_ops = { meth_name: lambda *args, *...
pytest lib/matplotlib/tests/test_bbox_tight.py::test_noop_tight_bbox
matplotlib
1
default: 'top' from .tight_layout import ( get_renderer, get_subplotspec_list, get_tight_layout_figure) subplotspec_list = get_subplotspec_list(self.axes) if None in subplotspec_list:
default: 'top' from .tight_layout import ( get_renderer, get_subplotspec_list, get_tight_layout_figure) from .cbook import _setattr_cm from .backend_bases import RendererBase subplotspec_list = get_subplotspec_list(self.axes) if None in subplotspec_list:
pytest lib/matplotlib/tests/test_bbox_tight.py::test_noop_tight_bbox
matplotlib
1
default: 'top' if renderer is None: renderer = get_renderer(self) kwargs = get_tight_layout_figure( self, self.axes, subplotspec_list, renderer, pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect) if kwargs: self.subplots_adjust(**kwargs)
default: 'top' if renderer is None: renderer = get_renderer(self) no_ops = { meth_name: lambda *args, **kwargs: None for meth_name in dir(RendererBase) if (meth_name.startswith("draw_") or meth_name in ["open_group", "close_group"]) ...
pytest lib/matplotlib/tests/test_bbox_tight.py::test_noop_tight_bbox
matplotlib
1
def get_renderer(fig): return canvas.get_renderer() else: from . import backend_bases return backend_bases._get_renderer(fig, draw_disabled=True) def get_subplotspec_list(axes_list, grid_spec=None):
def get_renderer(fig): return canvas.get_renderer() else: from . import backend_bases return backend_bases._get_renderer(fig) def get_subplotspec_list(axes_list, grid_spec=None):
pytest lib/matplotlib/tests/test_bbox_tight.py::test_noop_tight_bbox
pandas
74
class TimedeltaIndex( "represent unambiguous timedelta values durations." ) if isinstance(data, TimedeltaArray): if copy: data = data.copy() return cls._simple_new(data, name=name, freq=freq)
class TimedeltaIndex( "represent unambiguous timedelta values durations." ) if isinstance(data, TimedeltaArray) and freq is None: if copy: data = data.copy() return cls._simple_new(data, name=name, freq=freq)
pytest pandas/tests/indexes/timedeltas/test_constructors.py::TestTimedeltaIndex::test_infer_from_tdi_mismatch
pandas
89
def _unstack_multiple(data, clocs, fill_value=None): result = data for i in range(len(clocs)): val = clocs[i] result = result.unstack(val) clocs = [v if i > v else v - 1 for v in clocs] return result
def _unstack_multiple(data, clocs, fill_value=None): result = data 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
pytest pandas/tests/frame/test_reshape.py::test_unstacking_multi_index_df
pandas
128
def read_json( dtype = True if convert_axes is None and orient != "table": convert_axes = True compression = _infer_compression(path_or_buf, compression) filepath_or_buffer, _, compression, should_close = get_filepath_or_buffer(
def read_json( dtype = True if convert_axes is None and orient != "table": convert_axes = True if encoding is None: encoding = "utf-8" compression = _infer_compression(path_or_buf, compression) filepath_or_buffer, _, compression, should_close = get_filepath_or_buffer(
pytest pandas/tests/io/json/test_readlines.py::test_readjson_unicode
pandas
147
class DatetimeTZDtype(PandasExtensionDtype): tz = timezones.tz_standardize(tz) elif tz is not None: raise pytz.UnknownTimeZoneError(tz) elif tz is None: raise TypeError("A 'tz' is required.") self._unit = unit
class DatetimeTZDtype(PandasExtensionDtype): tz = timezones.tz_standardize(tz) elif tz is not None: raise pytz.UnknownTimeZoneError(tz) if tz is None: raise TypeError("A 'tz' is required.") self._unit = unit
pytest pandas/tests/dtypes/test_dtypes.py::TestDatetimeTZDtype::test_construct_from_string_raises
pandas
147
class DatetimeTZDtype(PandasExtensionDtype): """ if isinstance(string, str): msg = "Could not construct DatetimeTZDtype from '{}'" try: match = cls._match.match(string) if match: d = match.groupdict() return ...
class DatetimeTZDtype(PandasExtensionDtype): """ if isinstance(string, str): msg = "Could not construct DatetimeTZDtype from '{}'" match = cls._match.match(string) if match: d = match.groupdict() try: return cls(unit...
pytest pandas/tests/dtypes/test_dtypes.py::TestDatetimeTZDtype::test_construct_from_string_raises
thefuck
12
from difflib import get_close_matches from thefuck.utils import get_all_executables, \ get_valid_history_without_current, get_closest from thefuck.specific.sudo import sudo_support @sudo_support def match(command): return (command.script_parts and 'not found' in command.stderr and bool...
from difflib import get_close_matches from thefuck.utils import get_all_executables, \ get_valid_history_without_current, get_closest, which from thefuck.specific.sudo import sudo_support @sudo_support def match(command): return (not which(command.script_parts[0]) and 'not found' in command.stderr...
pytest tests/rules/test_no_command.py::test_match
thefuck
2
def get_all_executables(): tf_entry_points = ['thefuck', 'fuck'] bins = [exe.name.decode('utf8') if six.PY2 else exe.name for path in os.environ.get('PATH', '').split(':') for exe in _safe(lambda: list(Path(path).iterdir()), []) if not _safe(exe.is_dir, True) and...
def get_all_executables(): tf_entry_points = ['thefuck', 'fuck'] bins = [exe.name.decode('utf8') if six.PY2 else exe.name for path in os.environ.get('PATH', '').split(os.pathsep) for exe in _safe(lambda: list(Path(path).iterdir()), []) if not _safe(exe.is_dir, True) ...
pytest tests/test_utils.py::test_get_all_executables_pathsep
sanic
4
class Request: :rtype: str """ # Full URL SERVER_NAME can only be handled in app.url_for if "//" in self.app.config.SERVER_NAME: return self.app.url_for(view_name, _external=True, **kwargs) scheme = self.scheme host = self.server_name
class Request: :rtype: str """ # Full URL SERVER_NAME can only be handled in app.url_for try: if "//" in self.app.config.SERVER_NAME: return self.app.url_for(view_name, _external=True, **kwargs) except AttributeError: pass scheme =...
pytest tests/test_requests.py::test_url_for_without_server_name
scrapy
40
class PythonItemExporter(BaseItemExporter): return dict(self._serialize_dict(value)) if is_listlike(value): return [self._serialize_value(v) for v in value] if self.binary: return to_bytes(value, encoding=self.encoding) else: return to_unicode(valu...
class PythonItemExporter(BaseItemExporter): return dict(self._serialize_dict(value)) if is_listlike(value): return [self._serialize_value(v) for v in value] encode_func = to_bytes if self.binary else to_unicode if isinstance(value, (six.text_type, bytes)): ret...
python -m unittest -q tests.test_exporters.PythonItemExporterTest.test_other_python_types_item
scrapy
23
from six.moves.urllib.parse import urlunparse from scrapy.utils.httpobj import urlparse_cached from scrapy.exceptions import NotConfigured class HttpProxyMiddleware(object):
from six.moves.urllib.parse import urlunparse from scrapy.utils.httpobj import urlparse_cached from scrapy.exceptions import NotConfigured from scrapy.utils.python import to_bytes class HttpProxyMiddleware(object):
python -m unittest -q tests.test_downloadermiddleware_httpproxy.TestDefaultHeadersMiddleware.test_proxy_auth_empty_passwd
scrapy
23
class HttpProxyMiddleware(object): proxy_url = urlunparse((proxy_type or orig_type, hostport, '', '', '', '')) if user: user_pass = '%s:%s' % (unquote(user), unquote(password)) creds = base64.b64encode(user_pass).strip() else: creds = None
class HttpProxyMiddleware(object): proxy_url = urlunparse((proxy_type or orig_type, hostport, '', '', '', '')) if user: user_pass = to_bytes('%s:%s' % (unquote(user), unquote(password))) creds = base64.b64encode(user_pass).strip() else: creds = None
python -m unittest -q tests.test_downloadermiddleware_httpproxy.TestDefaultHeadersMiddleware.test_proxy_auth_empty_passwd
scrapy
23
class HttpProxyMiddleware(object): creds, proxy = self.proxies[scheme] request.meta['proxy'] = proxy if creds: request.headers['Proxy-Authorization'] = 'Basic ' + creds
class HttpProxyMiddleware(object): creds, proxy = self.proxies[scheme] request.meta['proxy'] = proxy if creds: request.headers['Proxy-Authorization'] = b'Basic ' + creds
python -m unittest -q tests.test_downloadermiddleware_httpproxy.TestDefaultHeadersMiddleware.test_proxy_auth_empty_passwd
scrapy
23
class RetryTest(unittest.TestCase): def test_priority_adjust(self): req = Request('http://www.scrapytest.org/503') rsp = Response('http://www.scrapytest.org/503', body='', status=503) req2 = self.mw.process_response(req, rsp, self.spider) assert req2.priority < req.priority def...
class RetryTest(unittest.TestCase): def test_priority_adjust(self): req = Request('http://www.scrapytest.org/503') rsp = Response('http://www.scrapytest.org/503', body=b'', status=503) req2 = self.mw.process_response(req, rsp, self.spider) assert req2.priority < req.priority de...
python -m unittest -q tests.test_downloadermiddleware_httpproxy.TestDefaultHeadersMiddleware.test_proxy_auth_empty_passwd
scrapy
23
class RetryTest(unittest.TestCase): def test_503(self): req = Request('http://www.scrapytest.org/503') rsp = Response('http://www.scrapytest.org/503', body='', status=503) # first retry req = self.mw.process_response(req, rsp, self.spider)
class RetryTest(unittest.TestCase): def test_503(self): req = Request('http://www.scrapytest.org/503') rsp = Response('http://www.scrapytest.org/503', body=b'', status=503) # first retry req = self.mw.process_response(req, rsp, self.spider)
python -m unittest -q tests.test_downloadermiddleware_httpproxy.TestDefaultHeadersMiddleware.test_proxy_auth_empty_passwd