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
10
def standardize_weights(y, """Performs sample weight validation and standardization. Everything gets normalized to a single sample-wise (or timestep-wise) weight array. # Arguments y: Numpy array of model targets to be weighted.
def standardize_weights(y, """Performs sample weight validation and standardization. Everything gets normalized to a single sample-wise (or timestep-wise) weight array. If both `sample_weights` and `class_weights` are provided, the weights are multiplied together. # Arguments y: Numpy arra...
pytest tests/keras/engine/test_training.py::test_sample_weights
keras
10
def standardize_weights(y, 'sample-wise weights, make sure your ' 'sample_weight array is 1D.') if sample_weight is not None and class_weight is not None: warnings.warn('Found both `sample_weight` and `class_weight`: ' '`class_...
def standardize_weights(y, 'sample-wise weights, make sure your ' 'sample_weight array is 1D.') if sample_weight is not None: if len(sample_weight.shape) > len(y.shape): raise ValueError('Found a sample_weight with shape' +
pytest tests/keras/engine/test_training.py::test_sample_weights
keras
10
def standardize_weights(y, ' for an input with shape ' + str(y.shape) + '. ' 'sample_weight cannot be broadcast.') return sample_weight elif isinstance(class_weight, dict): if len(y.shape) > 2: raise V...
def standardize_weights(y, ' for an input with shape ' + str(y.shape) + '. ' 'sample_weight cannot be broadcast.') class_sample_weight = None if isinstance(class_weight, dict): if len(y.shape) > 2: raise ...
pytest tests/keras/engine/test_training.py::test_sample_weights
keras
10
def standardize_weights(y, ' The classes %s exist in the data but not in ' '`class_weight`.' % (existing_classes - existing_class_weight)) return weights else: if sample_weight_mode is None: return np....
def standardize_weights(y, ' The classes %s exist in the data but not in ' '`class_weight`.' % (existing_classes - existing_class_weight)) if sample_weight is not None and class_sample_weight is not None: return sample_w...
pytest tests/keras/engine/test_training.py::test_sample_weights
pandas
78
Wild 185.0 result = coerce_to_dtypes(result, self.dtypes) if constructor is not None: result = Series(result, index=labels) return result def nunique(self, axis=0, dropna=True) -> Series:
Wild 185.0 result = coerce_to_dtypes(result, self.dtypes) if constructor is not None: result = self._constructor_sliced(result, index=labels) return result def nunique(self, axis=0, dropna=True) -> Series:
pytest pandas/tests/frame/test_subclass.py::TestDataFrameSubclassing::test_subclassed_boolean_reductions
pandas
85
class MultiIndex(Index): if len(uniques) < len(level_index): # Remove unobserved levels from level_index level_index = level_index.take(uniques) if len(level_index): grouper = level_index.take(codes)
class MultiIndex(Index): if len(uniques) < len(level_index): # Remove unobserved levels from level_index level_index = level_index.take(uniques) else: # break references back to us so that setting the name # on the output of a groupby doesn't reflect back ...
pytest pandas/tests/groupby/test_apply.py::test_apply_multi_level_name
pandas
124
class StringMethods(NoNewAttributesMixin): _doc_args["istitle"] = dict(type="titlecase", method="istitle") _doc_args["isnumeric"] = dict(type="numeric", method="isnumeric") _doc_args["isdecimal"] = dict(type="decimal", method="isdecimal") isalnum = _noarg_wrapper( lambda x: x.isalnum(), ...
class StringMethods(NoNewAttributesMixin): _doc_args["istitle"] = dict(type="titlecase", method="istitle") _doc_args["isnumeric"] = dict(type="numeric", method="isnumeric") _doc_args["isdecimal"] = dict(type="decimal", method="isdecimal") # force _noarg_wrapper return type with dtype=bool (GH 29624) ...
pytest pandas/tests/test_strings.py::TestStringMethods::test_empty_str_methods
fastapi
10
def serialize_response( errors.extend(errors_) if errors: raise ValidationError(errors) return jsonable_encoder( value, include=include,
def serialize_response( errors.extend(errors_) if errors: raise ValidationError(errors) if skip_defaults and isinstance(response, BaseModel): value = response.dict(skip_defaults=skip_defaults) return jsonable_encoder( value, include=inc...
pytest tests/test_skip_defaults.py::test_return_defaults
pandas
17
from datetime import datetime, timedelta import operator from typing import Any, Sequence, Type, Union, cast import warnings import numpy as np from pandas._libs import NaT, NaTType, Timestamp, algos, iNaT, lib from pandas._libs.tslibs.c_timestamp import integer_op_not_supported from pandas._libs.tslibs.period import...
""" Base and utility classes for tseries type pandas objects. """ from datetime import datetime, timedelta from typing import Any, List, Optional, Union, cast 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 pan...
pytest pandas/tests/indexes/datetimes/test_insert.py::TestInsert::test_insert_mismatched_types_raises
pandas
17
class DatetimeLikeArrayMixin( return None return self.freq.freqstr @property # NB: override with cache_readonly in immutable subclasses def inferred_freq(self): """ Tryies to return a string representing a frequency guess, generated by infer_freq. Returns None if i...
class DatetimeLikeArrayMixin( return None return self.freq.freqstr def _with_freq(self, freq): index = self.copy(deep=False) if freq is None: # Even if we _can_ have a freq, we might want to set it to None index._freq = None elif len(self) == 0 an...
pytest pandas/tests/indexes/datetimes/test_insert.py::TestInsert::test_insert_mismatched_types_raises
pandas
17
class TestInsertIndexCoercion(CoercionBase): with pytest.raises(TypeError, match=msg): obj.insert(1, pd.Timestamp("2012-01-01", tz="Asia/Tokyo")) msg = "cannot insert DatetimeIndex with incompatible label" with pytest.raises(TypeError, match=msg): obj.insert(1, 1...
class TestInsertIndexCoercion(CoercionBase): with pytest.raises(TypeError, match=msg): obj.insert(1, pd.Timestamp("2012-01-01", tz="Asia/Tokyo")) msg = "cannot insert DatetimeArray with incompatible label" with pytest.raises(TypeError, match=msg): obj.insert(1, 1...
pytest pandas/tests/indexes/datetimes/test_insert.py::TestInsert::test_insert_mismatched_types_raises
pandas
17
class TestInsertIndexCoercion(CoercionBase): ) # ToDo: must coerce to object msg = "cannot insert TimedeltaIndex with incompatible label" with pytest.raises(TypeError, match=msg): obj.insert(1, pd.Timestamp("2012-01-01")) # ToDo: must coerce to object msg = ...
class TestInsertIndexCoercion(CoercionBase): ) # ToDo: must coerce to object msg = "cannot insert TimedeltaArray with incompatible label" with pytest.raises(TypeError, match=msg): obj.insert(1, pd.Timestamp("2012-01-01")) # ToDo: must coerce to object msg = ...
pytest pandas/tests/indexes/datetimes/test_insert.py::TestInsert::test_insert_mismatched_types_raises
pandas
17
class TestPartialSetting: df = orig.copy() # don't allow not string inserts msg = "cannot insert DatetimeIndex with incompatible label" with pytest.raises(TypeError, match=msg): df.loc[100.0, :] = df.iloc[0]
class TestPartialSetting: df = orig.copy() # don't allow not string inserts msg = "cannot insert DatetimeArray with incompatible label" with pytest.raises(TypeError, match=msg): df.loc[100.0, :] = df.iloc[0]
pytest pandas/tests/indexes/datetimes/test_insert.py::TestInsert::test_insert_mismatched_types_raises
keras
31
def ctc_batch_cost(y_true, y_pred, input_length, label_length): Tensor with shape (samples,1) containing the CTC loss of each element. """ label_length = tf.to_int32(tf.squeeze(label_length)) input_length = tf.to_int32(tf.squeeze(input_length)) sparse_labels = tf.to_int32(ctc_label_d...
def ctc_batch_cost(y_true, y_pred, input_length, label_length): Tensor with shape (samples,1) containing the CTC loss of each element. """ label_length = tf.to_int32(tf.squeeze(label_length, axis=-1)) input_length = tf.to_int32(tf.squeeze(input_length, axis=-1)) sparse_labels = tf.to...
pytest tests/keras/backend/backend_test.py::TestBackend::test_ctc
black
22
import asyncio from asyncio.base_events import BaseEventLoop from concurrent.futures import Executor, ProcessPoolExecutor from functools import partial import keyword import os from pathlib import Path import tokenize import sys from typing import ( Dict, Generic, Iterable, Iterator, List, Optional, Set, Tuple, Typ...
import asyncio from asyncio.base_events import BaseEventLoop from concurrent.futures import Executor, ProcessPoolExecutor from functools import partial, wraps import keyword import os from pathlib import Path import tokenize import sys from typing import ( Callable, Dict, Generic, Iterable, Iterator...
python -m unittest -q tests.test_black.BlackTestCase.test_comments3
black
22
Depth = int NodeType = int LeafID = int Priority = int LN = Union[Leaf, Node] out = partial(click.secho, bold=True, err=True) err = partial(click.secho, fg='red', err=True)
Depth = int NodeType = int LeafID = int Priority = int Index = int LN = Union[Leaf, Node] SplitFunc = Callable[['Line', bool], Iterator['Line']] out = partial(click.secho, bold=True, err=True) err = partial(click.secho, fg='red', err=True)
python -m unittest -q tests.test_black.BlackTestCase.test_comments3
black
22
class Line: depth: int = 0 leaves: List[Leaf] = Factory(list) comments: Dict[LeafID, Leaf] = Factory(dict) bracket_tracker: BracketTracker = Factory(BracketTracker) inside_brackets: bool = False has_for: bool = False
class Line: depth: int = 0 leaves: List[Leaf] = Factory(list) comments: List[Tuple[Index, Leaf]] = Factory(list) bracket_tracker: BracketTracker = Factory(BracketTracker) inside_brackets: bool = False has_for: bool = False
python -m unittest -q tests.test_black.BlackTestCase.test_comments3
black
22
class Line: self.bracket_tracker.mark(leaf) self.maybe_remove_trailing_comma(leaf) self.maybe_increment_for_loop_variable(leaf) if self.maybe_adapt_standalone_comment(leaf): return if not self.append_comment(leaf): self.leaves.append(l...
class Line: self.bracket_tracker.mark(leaf) self.maybe_remove_trailing_comma(leaf) self.maybe_increment_for_loop_variable(leaf) if not self.append_comment(leaf): self.leaves.append(leaf) def append_safe(self, leaf: Leaf, preformatted: bool = False) -> None: ...
python -m unittest -q tests.test_black.BlackTestCase.test_comments3
black
22
class Line: and self.leaves[0].value == 'yield' ) def maybe_remove_trailing_comma(self, closing: Leaf) -> bool: """Remove trailing comma if there is one and it's safe.""" if not (
class Line: and self.leaves[0].value == 'yield' ) @property def contains_standalone_comments(self) -> bool: """If so, needs to be split before emitting.""" for leaf in self.leaves: if leaf.type == STANDALONE_COMMENT: return True return Fa...
python -m unittest -q tests.test_black.BlackTestCase.test_comments3
black
22
class Line: return False if closing.type == token.RBRACE: self.leaves.pop() return True if closing.type == token.RSQB: comma = self.leaves[-1] if comma.parent and comma.parent.type == syms.listmaker: self.leaves.pop() ...
class Line: return False if closing.type == token.RBRACE: self.remove_trailing_comma() return True if closing.type == token.RSQB: comma = self.leaves[-1] if comma.parent and comma.parent.type == syms.listmaker: self.remove_tra...
python -m unittest -q tests.test_black.BlackTestCase.test_comments3
black
22
class Line: break if commas > 1: self.leaves.pop() return True return False
class Line: break if commas > 1: self.remove_trailing_comma() return True return False
python -m unittest -q tests.test_black.BlackTestCase.test_comments3
black
22
class Line: return False def maybe_adapt_standalone_comment(self, comment: Leaf) -> bool: """Hack a standalone comment to act as a trailing comment for line splitting. If this line has brackets and a standalone `comment`, we need to adapt it to be able to still reformat the line. ...
class Line: return False def append_comment(self, comment: Leaf) -> bool: """Add an inline or standalone comment to the line.""" if ( comment.type == STANDALONE_COMMENT and self.bracket_tracker.any_open_brackets() ): comment.prefix = '' ...
python -m unittest -q tests.test_black.BlackTestCase.test_comments3
black
22
class Line: res = f'{first.prefix}{indent}{first.value}' for leaf in leaves: res += str(leaf) for comment in self.comments.values(): res += str(comment) return res + '\n'
class Line: res = f'{first.prefix}{indent}{first.value}' for leaf in leaves: res += str(leaf) for _, comment in self.comments: res += str(comment) return res + '\n'
python -m unittest -q tests.test_black.BlackTestCase.test_comments3
black
22
class UnformattedLines(Line): """Does nothing and returns False.""" return False def maybe_adapt_standalone_comment(self, comment: Leaf) -> bool: """Does nothing and returns False.""" return False @dataclass class EmptyLineTracker:
class UnformattedLines(Line): """Does nothing and returns False.""" return False @dataclass class EmptyLineTracker:
python -m unittest -q tests.test_black.BlackTestCase.test_comments3
black
22
def split_line( If `py36` is True, splitting may generate syntax that is only compatible with Python 3.6 and later. """ if isinstance(line, UnformattedLines): yield line return line_str = str(line).strip('\n') if len(line_str) <= line_length and '\n' not in line_str: yie...
def split_line( If `py36` is True, splitting may generate syntax that is only compatible with Python 3.6 and later. """ if isinstance(line, UnformattedLines) or line.is_comment: yield line return line_str = str(line).strip('\n') if ( len(line_str) <= line_length ...
python -m unittest -q tests.test_black.BlackTestCase.test_comments3
black
22
def split_line( # split altogether. result: List[Line] = [] try: for l in split_func(line, py36=py36): if str(l).strip('\n') == line_str: raise CannotSplit("Split function returned an unchanged result")
def split_line( # split altogether. result: List[Line] = [] try: for l in split_func(line, py36): if str(l).strip('\n') == line_str: raise CannotSplit("Split function returned an unchanged result")
python -m unittest -q tests.test_black.BlackTestCase.test_comments3
black
22
def left_hand_split(line: Line, py36: bool = False) -> Iterator[Line]: ): for leaf in leaves: result.append(leaf, preformatted=True) comment_after = line.comments.get(id(leaf)) if comment_after: result.append(comment_after, preformatted=True) bracket_s...
def left_hand_split(line: Line, py36: bool = False) -> Iterator[Line]: ): for leaf in leaves: result.append(leaf, preformatted=True) for comment_after in line.comments_after(leaf): result.append(comment_after, preformatted=True) bracket_split_succeeded_or_raise(he...
python -m unittest -q tests.test_black.BlackTestCase.test_comments3
black
22
def right_hand_split(line: Line, py36: bool = False) -> Iterator[Line]: ): for leaf in leaves: result.append(leaf, preformatted=True) comment_after = line.comments.get(id(leaf)) if comment_after: result.append(comment_after, preformatted=True) bracket_...
def right_hand_split(line: Line, py36: bool = False) -> Iterator[Line]: ): for leaf in leaves: result.append(leaf, preformatted=True) for comment_after in line.comments_after(leaf): result.append(comment_after, preformatted=True) bracket_split_succeeded_or_raise(h...
python -m unittest -q tests.test_black.BlackTestCase.test_comments3
black
22
def bracket_split_succeeded_or_raise(head: Line, body: Line, tail: Line) -> None ) def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]: """Split according to delimiters of the highest priority. This kind of split doesn't increase indentation. If `py36` is True, the split wil...
def bracket_split_succeeded_or_raise(head: Line, body: Line, tail: Line) -> None ) def dont_increase_indentation(split_func: SplitFunc) -> SplitFunc: """Normalize prefix of the first leaf in every line returned by `split_func`. This is a decorator over relevant split functions. """ @wrap...
python -m unittest -q tests.test_black.BlackTestCase.test_comments3
black
22
def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]: current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets) lowest_depth = sys.maxsize trailing_comma_safe = True for leaf in line.leaves: current_line.append(leaf, preformatted=True) comment_after = l...
def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]: current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets) lowest_depth = sys.maxsize trailing_comma_safe = True def append_to_line(leaf: Leaf) -> Iterator[Line]: """Append `leaf` to current line or to new l...
python -m unittest -q tests.test_black.BlackTestCase.test_comments3
black
22
def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]: trailing_comma_safe = trailing_comma_safe and py36 leaf_priority = delimiters.get(id(leaf)) if leaf_priority == delimiter_priority: normalize_prefix(current_line.leaves[0], inside_brackets=True) yi...
def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]: trailing_comma_safe = trailing_comma_safe and py36 leaf_priority = delimiters.get(id(leaf)) if leaf_priority == delimiter_priority: yield current_line current_line = Line(depth=line.depth, inside_...
python -m unittest -q tests.test_black.BlackTestCase.test_comments3
black
22
def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]: and trailing_comma_safe ): current_line.append(Leaf(token.COMMA, ',')) normalize_prefix(current_line.leaves[0], inside_brackets=True) yield current_line
def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]: and trailing_comma_safe ): current_line.append(Leaf(token.COMMA, ',')) yield current_line @dont_increase_indentation def standalone_comment_split(line: Line, py36: bool = False) -> Iterator[Line]: """Spl...
python -m unittest -q tests.test_black.BlackTestCase.test_comments3
pandas
36
from pandas.core.dtypes.common import ( ensure_object, is_bool_dtype, is_complex_dtype, is_datetime64_dtype, is_datetime64tz_dtype, is_datetimelike_v_numeric, is_dtype_equal, is_extension_array_dtype, is_float_dtype, is_integer_dtype, is_object_dtype, is_period_dtype, ...
from pandas.core.dtypes.common import ( ensure_object, is_bool_dtype, is_complex_dtype, is_datetimelike_v_numeric, is_dtype_equal, is_extension_array_dtype, is_float_dtype, is_integer_dtype, is_object_dtype, is_scalar, is_string_dtype, is_string_like_dtype, needs_i8_c...
pytest pandas/tests/dtypes//test_missing.py::TestIsNA::test_isna_old_datetimelike
pandas
36
def _isna_new(obj): raise NotImplementedError("isna is not defined for MultiIndex") elif isinstance(obj, type): return False elif isinstance( obj, ( ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray, ABCDatetimeArr...
def _isna_new(obj): raise NotImplementedError("isna is not defined for MultiIndex") elif isinstance(obj, type): return False elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)): return _isna_ndarraylike(obj) elif isinstance(obj, ABCDataFrame): retu...
pytest pandas/tests/dtypes//test_missing.py::TestIsNA::test_isna_old_datetimelike
pandas
36
def _isna_new(obj): elif hasattr(obj, "__array__"): return _isna_ndarraylike(np.asarray(obj)) else: return obj is None def _isna_old(obj):
def _isna_new(obj): elif hasattr(obj, "__array__"): return _isna_ndarraylike(np.asarray(obj)) else: return False def _isna_old(obj):
pytest pandas/tests/dtypes//test_missing.py::TestIsNA::test_isna_old_datetimelike
pandas
36
def _isna_old(obj): elif hasattr(obj, "__array__"): return _isna_ndarraylike_old(np.asarray(obj)) else: return obj is None _isna = _isna_new
def _isna_old(obj): elif hasattr(obj, "__array__"): return _isna_ndarraylike_old(np.asarray(obj)) else: return False _isna = _isna_new
pytest pandas/tests/dtypes//test_missing.py::TestIsNA::test_isna_old_datetimelike
pandas
36
def _use_inf_as_na(key): def _isna_ndarraylike(obj): is_extension = is_extension_array_dtype(obj) if not is_extension: # Avoid accessing `.values` on things like # PeriodIndex, which may be expensive. values = getattr(obj, "_values", obj) else: values = obj dtype = va...
def _use_inf_as_na(key): def _isna_ndarraylike(obj): is_extension = is_extension_array_dtype(obj.dtype) values = getattr(obj, "_values", obj) dtype = values.dtype if is_extension: result = values.isna() elif is_string_dtype(dtype): result = _isna_string_dtype(values, dtype, old=Fa...
pytest pandas/tests/dtypes//test_missing.py::TestIsNA::test_isna_old_datetimelike
pandas
36
def _isna_ndarraylike_old(obj): dtype = values.dtype if is_string_dtype(dtype): # Working around NumPy ticket 1542 shape = values.shape if is_string_like_dtype(dtype): result = np.zeros(values.shape, dtype=bool) else: result = np.empty(shape, dtype=bool)...
def _isna_ndarraylike_old(obj): dtype = values.dtype if is_string_dtype(dtype): result = _isna_string_dtype(values, dtype, old=True) elif needs_i8_conversion(dtype): # this is the NaT pattern result = values.view("i8") == iNaT else:
pytest pandas/tests/dtypes//test_missing.py::TestIsNA::test_isna_old_datetimelike
pandas
36
def _isna_ndarraylike_old(obj): return result def notna(obj): """ Detect non-missing values for an array-like object.
def _isna_ndarraylike_old(obj): return result def _isna_string_dtype(values: np.ndarray, dtype: np.dtype, old: bool) -> np.ndarray: # Working around NumPy ticket 1542 shape = values.shape if is_string_like_dtype(dtype): result = np.zeros(values.shape, dtype=bool) else: result = np...
pytest pandas/tests/dtypes//test_missing.py::TestIsNA::test_isna_old_datetimelike
pandas
36
def na_value_for_dtype(dtype, compat: bool = True): if is_extension_array_dtype(dtype): return dtype.na_value if ( is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype) or is_timedelta64_dtype(dtype) or is_period_dtype(dtype) ): return NaT elif is_fl...
def na_value_for_dtype(dtype, compat: bool = True): if is_extension_array_dtype(dtype): return dtype.na_value if needs_i8_conversion(dtype): return NaT elif is_float_dtype(dtype): return np.nan
pytest pandas/tests/dtypes//test_missing.py::TestIsNA::test_isna_old_datetimelike
pandas
59
class _Rolling_and_Expanding(_Rolling): # only default unset pairwise = True if pairwise is None else pairwise other = self._shallow_copy(other) window = self._get_window(other) def _get_corr(a, b): a = a.rolling(
class _Rolling_and_Expanding(_Rolling): # only default unset pairwise = True if pairwise is None else pairwise other = self._shallow_copy(other) window = self._get_window(other) if not self.is_freq_type else self.win_freq def _get_corr(a, b): a = a.rolling(
pytest pandas/tests/window/test_pairwise.py::TestPairwise::test_corr_freq_memory_error
pandas
105
class DataFrame(NDFrame): ) return result def transpose(self, *args, **kwargs): """ Transpose index and columns.
class DataFrame(NDFrame): ) return result def transpose(self, *args, copy: bool = False): """ Transpose index and columns.
pytest pandas/tests/arithmetic/test_period.py::TestPeriodIndexArithmetic::test_parr_add_sub_tdt64_nat_array
pandas
105
class DataFrame(NDFrame): Parameters ---------- *args, **kwargs Additional arguments and keywords have no effect but might be accepted for compatibility with numpy. Returns -------
class DataFrame(NDFrame): Parameters ---------- *args : tuple, optional Accepted for compatibility with NumPy. copy : bool, default False Whether to copy the data after transposing, even for DataFrames with a single dtype. Note that a cop...
pytest pandas/tests/arithmetic/test_period.py::TestPeriodIndexArithmetic::test_parr_add_sub_tdt64_nat_array
pandas
105
class DataFrame(NDFrame): dtype: object """ nv.validate_transpose(args, dict()) return super().transpose(1, 0, **kwargs) T = property(transpose)
class DataFrame(NDFrame): dtype: object """ nv.validate_transpose(args, dict()) # construct the args dtypes = list(self.dtypes) if self._is_homogeneous_type and dtypes and is_extension_array_dtype(dtypes[0]): # We have EAs with the same dtype. We can preserve...
pytest pandas/tests/arithmetic/test_period.py::TestPeriodIndexArithmetic::test_parr_add_sub_tdt64_nat_array
pandas
105
class NDFrame(PandasObject, SelectionMixin): self._data.set_axis(axis, labels) self._clear_item_cache() def transpose(self, *args, **kwargs): """ Permute the dimensions of the %(klass)s Parameters ---------- args : %(args_transpose)s copy : bool, def...
class NDFrame(PandasObject, SelectionMixin): self._data.set_axis(axis, labels) self._clear_item_cache() def swapaxes(self, axis1, axis2, copy=True): """ Interchange axes and swap values axes appropriately.
pytest pandas/tests/arithmetic/test_period.py::TestPeriodIndexArithmetic::test_parr_add_sub_tdt64_nat_array
pandas
105
def box_df_fail(request): return request.param @pytest.fixture( params=[ (pd.Index, False), (pd.Series, False), (pd.DataFrame, False), pytest.param((pd.DataFrame, True), marks=pytest.mark.xfail), (tm.to_array, False), ], ids=id_func, ) def box_transpose_fail(req...
def box_df_fail(request): return request.param @pytest.fixture(params=[pd.Index, pd.Series, pd.DataFrame, tm.to_array], ids=id_func) def box_with_array(request): """
pytest pandas/tests/arithmetic/test_period.py::TestPeriodIndexArithmetic::test_parr_add_sub_tdt64_nat_array
pandas
105
class BaseReshapingTests(BaseExtensionTests): # Check that we have a view, not a copy result[0] = result[1] assert data[0] == data[1]
class BaseReshapingTests(BaseExtensionTests): # Check that we have a view, not a copy result[0] = result[1] assert data[0] == data[1] def test_transpose(self, data): df = pd.DataFrame({"A": data[:4], "B": data[:4]}, index=["a", "b", "c", "d"]) result = df.T expected ...
pytest pandas/tests/arithmetic/test_period.py::TestPeriodIndexArithmetic::test_parr_add_sub_tdt64_nat_array
pandas
105
class TestReshaping(BaseJSON, base.BaseReshapingTests): # this matches otherwise return super().test_unstack(data, index) class TestGetitem(BaseJSON, base.BaseGetitemTests): pass
class TestReshaping(BaseJSON, base.BaseReshapingTests): # this matches otherwise return super().test_unstack(data, index) @pytest.mark.xfail(reason="Inconsistent sizes.") def test_transpose(self, data): super().test_transpose(data) class TestGetitem(BaseJSON, base.BaseGetitemTests): ...
pytest pandas/tests/arithmetic/test_period.py::TestPeriodIndexArithmetic::test_parr_add_sub_tdt64_nat_array
pandas
105
class TestReshaping(BaseNumPyTests, base.BaseReshapingTests): # Fails creating expected super().test_merge_on_extension_array_duplicates(data) class TestSetitem(BaseNumPyTests, base.BaseSetitemTests): @skip_nested
class TestReshaping(BaseNumPyTests, base.BaseReshapingTests): # Fails creating expected super().test_merge_on_extension_array_duplicates(data) @skip_nested def test_transpose(self, data): super().test_transpose(data) class TestSetitem(BaseNumPyTests, base.BaseSetitemTests): @skip_...
pytest pandas/tests/arithmetic/test_period.py::TestPeriodIndexArithmetic::test_parr_add_sub_tdt64_nat_array
youtube-dl
28
def _htmlentity_transform(entity): numstr = '0%s' % numstr else: base = 10 return compat_chr(int(numstr, base)) # Unknown entity in name, return its literal representation return ('&%s;' % entity)
def _htmlentity_transform(entity): numstr = '0%s' % numstr else: base = 10 # See https://github.com/rg3/youtube-dl/issues/7518 try: return compat_chr(int(numstr, base)) except ValueError: pass # Unknown entity in name, return its liter...
python -m unittest -q test.test_utils.TestUtil.test_unescape_html
tornado
1
class WebSocketHandler(tornado.web.RequestHandler): .. versionadded:: 3.1 """ assert self.stream is not None self.stream.set_nodelay(value) def on_connection_close(self) -> None: if self.ws_connection:
class WebSocketHandler(tornado.web.RequestHandler): .. versionadded:: 3.1 """ assert self.ws_connection is not None self.ws_connection.set_nodelay(value) def on_connection_close(self) -> None: if self.ws_connection:
python -m unittest -q tornado.test.websocket_test.WebSocketTest.test_nodelay
tornado
1
class WebSocketProtocol(abc.ABC): async def _receive_frame_loop(self) -> None: raise NotImplementedError() class _PerMessageDeflateCompressor(object): def __init__(
class WebSocketProtocol(abc.ABC): async def _receive_frame_loop(self) -> None: raise NotImplementedError() @abc.abstractmethod def set_nodelay(self, x: bool) -> None: raise NotImplementedError() class _PerMessageDeflateCompressor(object): def __init__(
python -m unittest -q tornado.test.websocket_test.WebSocketTest.test_nodelay
tornado
1
class WebSocketProtocol13(WebSocketProtocol): self.write_ping(b"") self.last_ping = now class WebSocketClientConnection(simple_httpclient._HTTPConnection): """WebSocket client connection.
class WebSocketProtocol13(WebSocketProtocol): self.write_ping(b"") self.last_ping = now def set_nodelay(self, x: bool) -> None: self.stream.set_nodelay(x) class WebSocketClientConnection(simple_httpclient._HTTPConnection): """WebSocket client connection.
python -m unittest -q tornado.test.websocket_test.WebSocketTest.test_nodelay
youtube-dl
13
def urljoin(base, path): path = path.decode('utf-8') if not isinstance(path, compat_str) or not path: return None if re.match(r'^(?:https?:)?//', path): return path if isinstance(base, bytes): base = base.decode('utf-8')
def urljoin(base, path): path = path.decode('utf-8') if not isinstance(path, compat_str) or not path: return None if re.match(r'^(?:[a-zA-Z][a-zA-Z0-9+-.]*:)?//', path): return path if isinstance(base, bytes): base = base.decode('utf-8')
python -m unittest -q test.test_utils.TestUtil.test_urljoin
pandas
62
class Block(PandasObject): """ transpose = self.ndim == 2 # coerce None values, if appropriate if value is None: if self.is_numeric:
class Block(PandasObject): """ transpose = self.ndim == 2 if isinstance(indexer, np.ndarray) and indexer.ndim > self.ndim: raise ValueError(f"Cannot set values with ndim > {self.ndim}") # coerce None values, if appropriate if value is None: if self.is_nu...
pytest pandas/tests/indexing/test_indexing.py::TestFancy::test_setitem_ndarray_3d
pandas
62
the string values returned are correct.""" missing_value = StataMissingValue(um) loc = missing_loc[umissing_loc == j] replacement.iloc[loc] = missing_value else: # All replacements are identical dtype = series.dtype
the string values returned are correct.""" missing_value = StataMissingValue(um) loc = missing_loc[umissing_loc == j] if loc.ndim == 2 and loc.shape[1] == 1: # GH#31813 avoid trying to set Series values with wrong ...
pytest pandas/tests/indexing/test_indexing.py::TestFancy::test_setitem_ndarray_3d
luigi
17
class core(task.Config): class _WorkerSchedulerFactory(object): def create_local_scheduler(self): return scheduler.CentralPlannerScheduler(prune_on_get_work=True) def create_remote_scheduler(self, url): return rpc.RemoteScheduler(url)
class core(task.Config): class _WorkerSchedulerFactory(object): def create_local_scheduler(self): return scheduler.CentralPlannerScheduler(prune_on_get_work=True, record_task_history=False) def create_remote_scheduler(self, url): return rpc.RemoteScheduler(url)
pytest test/scheduler_test.py::SchedulerTest::test_local_scheduler_task_history_status
matplotlib
24
def _make_getset_interval(method_name, lim_name, attr_name): setter(self, min(vmin, vmax, oldmin), max(vmin, vmax, oldmax), ignore=True) else: setter(self, max(vmin, vmax, oldmax), min(vmin, vmax, oldmin), ignore=True) sel...
def _make_getset_interval(method_name, lim_name, attr_name): setter(self, min(vmin, vmax, oldmin), max(vmin, vmax, oldmax), ignore=True) else: setter(self, max(vmin, vmax, oldmin), min(vmin, vmax, oldmax), ignore=True) sel...
pytest lib/matplotlib/tests/test_axes.py::test_set_ticks_inverted
black
19
class EmptyLineTracker: # Don't insert empty lines between decorators. return 0, 0 newlines = 2 if current_line.depth: newlines -= 1
class EmptyLineTracker: # Don't insert empty lines between decorators. return 0, 0 if is_decorator and self.previous_line and self.previous_line.is_comment: # Don't insert empty lines between decorator comments. return 0, 0 newlin...
python -m unittest -q tests.test_black.BlackTestCase.test_comment_in_decorator
pandas
151
class PandasArray(ExtensionArray, ExtensionOpsMixin, NDArrayOperatorsMixin): if not lib.is_scalar(value): value = np.asarray(value) values = self._ndarray t = np.result_type(value, values) if t != self._ndarray.dtype: values = values.astype(t, casting="safe") ...
class PandasArray(ExtensionArray, ExtensionOpsMixin, NDArrayOperatorsMixin): if not lib.is_scalar(value): value = np.asarray(value) value = np.asarray(value, dtype=self._ndarray.dtype) self._ndarray[key] = value def __len__(self) -> int: return len(self._ndarray)
pytest pandas/tests/arrays/test_numpy.py::test_setitem_no_coercion
pandas
6
def get_grouper( return False try: return gpr is obj[gpr.name] except (KeyError, IndexError): return False for i, (gpr, level) in enumerate(zip(keys, levels)):
def get_grouper( return False try: return gpr is obj[gpr.name] except (KeyError, IndexError, ValueError): # TODO: ValueError: Given date string not likely a datetime. # should be KeyError? return False for i, (gpr, level) in enumerate(zip(...
pytest pandas/tests/groupby/test_size.py::test_size_period_index
keras
2
def l2_normalize(x, axis=-1): return x / np.sqrt(y) def binary_crossentropy(target, output, from_logits=False): if not from_logits: output = np.clip(output, 1e-7, 1 - 1e-7)
def l2_normalize(x, axis=-1): return x / np.sqrt(y) def in_top_k(predictions, targets, k): top_k = np.argsort(-predictions)[:, :k] targets = targets.reshape(-1, 1) return np.any(targets == top_k, axis=-1) def binary_crossentropy(target, output, from_logits=False): if not from_logits: out...
pytest tests/keras/backend/backend_test.py::TestBackend::test_in_top_k
scrapy
39
class Spider(object_ref): crawler.signals.connect(self.close, signals.spider_closed) def start_requests(self): if self.make_requests_from_url is not Spider.make_requests_from_url: warnings.warn( "Spider.make_requests_from_url method is deprecated; " "it w...
class Spider(object_ref): crawler.signals.connect(self.close, signals.spider_closed) def start_requests(self): cls = self.__class__ if cls.make_requests_from_url is not Spider.make_requests_from_url: warnings.warn( "Spider.make_requests_from_url method is depreca...
python -m unittest -q tests.test_spider.DeprecationTest.test_make_requests_from_url_deprecated
youtube-dl
4
class JSInterpreter(object): return opfunc(x, y) m = re.match( r'^(?P<func>%s)\((?P<args>[a-zA-Z0-9_$,]+)\)$' % _NAME_RE, expr) if m: fname = m.group('func') argvals = tuple([ int(v) if v.isdigit() else local_vars[v] for v ...
class JSInterpreter(object): return opfunc(x, y) m = re.match( r'^(?P<func>%s)\((?P<args>[a-zA-Z0-9_$,]*)\)$' % _NAME_RE, expr) if m: fname = m.group('func') argvals = tuple([ int(v) if v.isdigit() else local_vars[v] for v ...
python -m unittest -q test.test_jsinterp.TestJSInterpreter.test_call
thefuck
25
def match(command, settings): @sudo_support def get_new_command(command, settings): return re.sub('^mkdir (.*)', 'mkdir -p \\1', command.script)
def match(command, settings): @sudo_support def get_new_command(command, settings): return re.sub('\\bmkdir (.*)', 'mkdir -p \\1', command.script)
pytest tests/rules/test_mkdir_p.py::test_get_new_command
youtube-dl
32
from ..utils import ( unified_strdate, parse_duration, qualities, url_basename, )
from ..utils import ( unified_strdate, parse_duration, qualities, strip_jsonp, url_basename, )
python -m unittest -q test.test_utils.TestUtil.test_strip_jsonp
youtube-dl
32
class NPOIE(InfoExtractor): 'http://e.omroep.nl/metadata/aflevering/%s' % video_id, video_id, # We have to remove the javascript callback transform_source=lambda j: re.sub(r'parseMetadata\((.*?)\);\n//.*$', r'\1', j) ) token_page = self._download_webpage( ...
class NPOIE(InfoExtractor): 'http://e.omroep.nl/metadata/aflevering/%s' % video_id, video_id, # We have to remove the javascript callback transform_source=strip_jsonp, ) token_page = self._download_webpage( 'http://ida.omroep.nl/npoplayer/i.js'...
python -m unittest -q test.test_utils.TestUtil.test_strip_jsonp
youtube-dl
32
def parse_age_limit(s): def strip_jsonp(code): return re.sub(r'(?s)^[a-zA-Z0-9_]+\s*\(\s*(.*)\);?\s*?\s*$', r'\1', code) def js_to_json(code):
def parse_age_limit(s): def strip_jsonp(code): return re.sub( r'(?s)^[a-zA-Z0-9_]+\s*\(\s*(.*)\);?\s*?(?://[^\n]*)*$', r'\1', code) def js_to_json(code):
python -m unittest -q test.test_utils.TestUtil.test_strip_jsonp
pandas
43
def _align_method_FRAME( def _should_reindex_frame_op( left: "DataFrame", right, axis, default_axis: int, fill_value, level ) -> bool: """ Check if this is an operation between DataFrames that will need to reindex. """ assert isinstance(left, ABCDataFrame) if not isinstance(right, ABCDataFram...
def _align_method_FRAME( def _should_reindex_frame_op( left: "DataFrame", right, op, axis, default_axis: int, fill_value, level ) -> bool: """ Check if this is an operation between DataFrames that will need to reindex. """ assert isinstance(left, ABCDataFrame) if op is operator.pow or op is r...
pytest pandas/tests/frame/test_arithmetic.py::test_pow_with_realignment
pandas
43
def _arith_method_FRAME(cls, op, special): @Appender(doc) def f(self, other, axis=default_axis, level=None, fill_value=None): if _should_reindex_frame_op(self, other, axis, default_axis, fill_value, level): return _frame_arith_method_with_reindex(self, other, op) self, other = _ali...
def _arith_method_FRAME(cls, op, special): @Appender(doc) def f(self, other, axis=default_axis, level=None, fill_value=None): if _should_reindex_frame_op( self, other, op, axis, default_axis, fill_value, level ): return _frame_arith_method_with_reindex(self, other, op) ...
pytest pandas/tests/frame/test_arithmetic.py::test_pow_with_realignment
ansible
2
class _Alpha: raise ValueError def __gt__(self, other): return not self.__lt__(other) def __le__(self, other): return self.__lt__(other) or self.__eq__(other) def __ge__(self, other): return self.__gt__(other) or self.__eq__(other) class _Numeric:
class _Alpha: raise ValueError def __le__(self, other): return self.__lt__(other) or self.__eq__(other) def __gt__(self, other): return not self.__le__(other) def __ge__(self, other): return not self.__lt__(other) class _Numeric:
pytest test/units/utils/test_version.py::test_numeric
ansible
2
class _Numeric: raise ValueError def __gt__(self, other): return not self.__lt__(other) def __le__(self, other): return self.__lt__(other) or self.__eq__(other) def __ge__(self, other): return self.__gt__(other) or self.__eq__(other) class SemanticVersion(Version):
class _Numeric: raise ValueError def __le__(self, other): return self.__lt__(other) or self.__eq__(other) def __gt__(self, other): return not self.__le__(other) def __ge__(self, other): return not self.__lt__(other) class SemanticVersion(Version):
pytest test/units/utils/test_version.py::test_numeric
keras
44
class RNN(Layer): @property def trainable_weights(self): if isinstance(self.cell, Layer): return self.cell.trainable_weights return []
class RNN(Layer): @property def trainable_weights(self): if not self.trainable: return [] if isinstance(self.cell, Layer): return self.cell.trainable_weights return []
pytest tests/keras/layers/recurrent_test.py::test_trainability
keras
44
class RNN(Layer): @property def non_trainable_weights(self): if isinstance(self.cell, Layer): return self.cell.non_trainable_weights return []
class RNN(Layer): @property def non_trainable_weights(self): if isinstance(self.cell, Layer): if not self.trainable: return self.cell.weights return self.cell.non_trainable_weights return []
pytest tests/keras/layers/recurrent_test.py::test_trainability
tqdm
1
def tenumerate(iterable, start=0, total=None, tqdm_class=tqdm_auto, if isinstance(iterable, np.ndarray): return tqdm_class(np.ndenumerate(iterable), total=total or len(iterable), **tqdm_kwargs) return enumerate(tqdm_class(iterable, start, **tqdm_kwargs)) def _tzip...
def tenumerate(iterable, start=0, total=None, tqdm_class=tqdm_auto, if isinstance(iterable, np.ndarray): return tqdm_class(np.ndenumerate(iterable), total=total or len(iterable), **tqdm_kwargs) return enumerate(tqdm_class(iterable, **tqdm_kwargs), start) def _tzip...
python3 -m pytest tqdm/tests/tests_contrib.py::test_enumerate
scrapy
18
class ResponseTypes(object): def from_content_disposition(self, content_disposition): try: filename = to_native_str(content_disposition).split(';')[1].split('=')[1] filename = filename.strip('"\'') return self.from_filename(filename) except IndexError:
class ResponseTypes(object): def from_content_disposition(self, content_disposition): try: filename = to_native_str(content_disposition, encoding='latin-1', errors='replace').split(';')[1].split('=')[1] filename = filename.strip('"\'') return self.from_fi...
python -m unittest -q tests.test_responsetypes.ResponseTypesTest.test_from_content_disposition
keras
27
class Bidirectional(Wrapper): return self.forward_layer.updates + self.backward_layer.updates return [] @property def losses(self): if hasattr(self.forward_layer, 'losses'): return self.forward_layer.losses + self.backward_layer.losses return [] @property ...
class Bidirectional(Wrapper): return self.forward_layer.updates + self.backward_layer.updates return [] def get_updates_for(self, inputs=None): forward_updates = self.forward_layer.get_updates_for(inputs) backward_updates = self.backward_layer.get_updates_for(inputs) ret...
pytest tests/keras/layers/wrappers_test.py::test_Bidirectional_losses
luigi
1
class MetricsHandler(tornado.web.RequestHandler): self._scheduler = scheduler def get(self): metrics = self._scheduler._state._metrics_collector.generate_latest() if metrics: metrics.configure_http_handler(self) self.write(metrics)
class MetricsHandler(tornado.web.RequestHandler): self._scheduler = scheduler def get(self): metrics_collector = self._scheduler._state._metrics_collector metrics = metrics_collector.generate_latest() if metrics: metrics_collector.configure_http_handler(self) ...
pytest test/server_test.py::MetricsHandlerTest::test_get
scrapy
14
except ImportError: from gzip import GzipFile import six # - Python>=3.5 GzipFile's read() has issues returning leftover # uncompressed data when input is corrupted
except ImportError: from gzip import GzipFile import six import re # - Python>=3.5 GzipFile's read() has issues returning leftover # uncompressed data when input is corrupted
python -m unittest -q tests.test_utils_gz.GunzipTest.test_is_gzipped_with_charset
scrapy
14
def gunzip(data): raise return output def is_gzipped(response): """Return True if the response is gzipped, or False otherwise""" ctype = response.headers.get('Content-Type', b'') return ctype in (b'application/x-gzip', b'application/gzip')
def gunzip(data): raise return output _is_gzipped_re = re.compile(br'^application/(x-)?gzip\b', re.I) def is_gzipped(response): """Return True if the response is gzipped, or False otherwise""" ctype = response.headers.get('Content-Type', b'') return _is_gzipped_re.search(ctype) is not ...
python -m unittest -q tests.test_utils_gz.GunzipTest.test_is_gzipped_with_charset
black
3
def target_version_option_callback( @click.option( "--config", type=click.Path( exists=False, file_okay=True, dir_okay=False, readable=True, allow_dash=False ), is_eager=True, callback=read_pyproject_toml,
def target_version_option_callback( @click.option( "--config", type=click.Path( exists=True, file_okay=True, dir_okay=False, readable=True, allow_dash=False ), is_eager=True, callback=read_pyproject_toml,
python -m unittest -q tests.test_black.BlackTestCase.test_invalid_config_return_code
pandas
20
class MonthOffset(SingleConstructorOffset): @apply_index_wraps def apply_index(self, i): shifted = liboffsets.shift_months(i.asi8, self.n, self._day_opt) # TODO: going through __new__ raises on call to _validate_frequency; # are we passing incorrect freq? return type(i)._simple_...
class MonthOffset(SingleConstructorOffset): @apply_index_wraps def apply_index(self, i): shifted = liboffsets.shift_months(i.asi8, self.n, self._day_opt) return type(i)._simple_new(shifted, dtype=i.dtype) class MonthEnd(MonthOffset):
pytest pandas/tests/tseries/offsets/test_yqm_offsets.py::test_apply_index
pandas
20
class QuarterOffset(DateOffset): shifted = liboffsets.shift_quarters( dtindex.asi8, self.n, self.startingMonth, self._day_opt ) # TODO: going through __new__ raises on call to _validate_frequency; # are we passing incorrect freq? return type(dtindex)._simple_new( ...
class QuarterOffset(DateOffset): shifted = liboffsets.shift_quarters( dtindex.asi8, self.n, self.startingMonth, self._day_opt ) return type(dtindex)._simple_new(shifted, dtype=dtindex.dtype) class BQuarterEnd(QuarterOffset):
pytest pandas/tests/tseries/offsets/test_yqm_offsets.py::test_apply_index
pandas
20
class YearOffset(DateOffset): shifted = liboffsets.shift_quarters( dtindex.asi8, self.n, self.month, self._day_opt, modby=12 ) # TODO: going through __new__ raises on call to _validate_frequency; # are we passing incorrect freq? return type(dtindex)._simple_new( ...
class YearOffset(DateOffset): shifted = liboffsets.shift_quarters( dtindex.asi8, self.n, self.month, self._day_opt, modby=12 ) return type(dtindex)._simple_new(shifted, dtype=dtindex.dtype) def is_on_offset(self, dt: datetime) -> bool: if self.normalize and not _is_norma...
pytest pandas/tests/tseries/offsets/test_yqm_offsets.py::test_apply_index
PySnooper
2
import functools import inspect import opcode import sys import re import collections
import functools import inspect import opcode import os import sys import re import collections
pytest -q -s tests/test_pysnooper.py::test_custom_repr_single
PySnooper
2
import traceback from .variables import CommonVariable, Exploding, BaseVariable from . import utils, pycompat ipython_filename_pattern = re.compile('^<ipython-input-([0-9]+)-.*>$') def get_local_reprs(frame, watch=()): code = frame.f_code vars_order = code.co_varnames + code.co_cellvars + code.co_freevars ...
import traceback from .variables import CommonVariable, Exploding, BaseVariable from . import utils, pycompat if pycompat.PY2: from io import open ipython_filename_pattern = re.compile('^<ipython-input-([0-9]+)-.*>$') def get_local_reprs(frame, watch=(), custom_repr=()): code = frame.f_code vars_order ...
pytest -q -s tests/test_pysnooper.py::test_custom_repr_single
PySnooper
2
def get_source_from_frame(frame): # apply tokenize.detect_encoding to decode the source into a # string, then we should do that ourselves. if isinstance(source[0], bytes): encoding = 'ascii' for line in source[:2]: # File coding may be specified. Match pattern from PEP-263 ...
def get_source_from_frame(frame): # apply tokenize.detect_encoding to decode the source into a # string, then we should do that ourselves. if isinstance(source[0], bytes): encoding = 'utf-8' for line in source[:2]: # File coding may be specified. Match pattern from PEP-263 ...
pytest -q -s tests/test_pysnooper.py::test_custom_repr_single
PySnooper
2
class FileWriter(object): self.overwrite = overwrite def write(self, s): with open(self.path, 'w' if self.overwrite else 'a') as output_file: output_file.write(s) self.overwrite = False thread_global = threading.local() class Tracer: '''
class FileWriter(object): self.overwrite = overwrite def write(self, s): with open(self.path, 'w' if self.overwrite else 'a', encoding='utf-8') as output_file: output_file.write(s) self.overwrite = False thread_global = threading.local() DISABLED = bool(os.ge...
pytest -q -s tests/test_pysnooper.py::test_custom_repr_single
PySnooper
2
class Tracer: @pysnooper.snoop(thread_info=True) ''' def __init__( self,
class Tracer: @pysnooper.snoop(thread_info=True) Customize how values are represented as strings:: @pysnooper.snoop(custom_repr=((type1, custom_repr_func1), (condition2, custom_repr_func2), ...)) ''' def __init__( self,
pytest -q -s tests/test_pysnooper.py::test_custom_repr_single
PySnooper
2
class Tracer: prefix='', overwrite=False, thread_info=False, ): self._write = get_write_function(output, overwrite)
class Tracer: prefix='', overwrite=False, thread_info=False, custom_repr=(), ): self._write = get_write_function(output, overwrite)
pytest -q -s tests/test_pysnooper.py::test_custom_repr_single
PySnooper
2
class Tracer: self.target_codes = set() self.target_frames = set() self.thread_local = threading.local() def __call__(self, function): self.target_codes.add(function.__code__) @functools.wraps(function)
class Tracer: self.target_codes = set() self.target_frames = set() self.thread_local = threading.local() if len(custom_repr) == 2 and not all(isinstance(x, pycompat.collections_abc.Iterable) for x in custom_repr): custom_repr = (custom_repr,) sel...
pytest -q -s tests/test_pysnooper.py::test_custom_repr_single
PySnooper
2
class Tracer: self._write(s) def __enter__(self): calling_frame = inspect.currentframe().f_back if not self._is_internal_frame(calling_frame): calling_frame.f_trace = self.trace self.target_frames.add(calling_frame) stack = self.thread_local.__dict__.setdefa...
class Tracer: self._write(s) def __enter__(self): if DISABLED: return calling_frame = inspect.currentframe().f_back if not self._is_internal_frame(calling_frame): calling_frame.f_trace = self.trace self.target_frames.add(calling_frame) st...
pytest -q -s tests/test_pysnooper.py::test_custom_repr_single
PySnooper
2
class Tracer: current_thread_len) return thread_info.ljust(self.thread_info_padding) def trace(self, frame, event, arg): ### Checking whether we should trace this line: #######################
class Tracer: current_thread_len) return thread_info.ljust(self.thread_info_padding) def trace(self, frame, event, arg): ### Checking whether we should trace this line: #######################
pytest -q -s tests/test_pysnooper.py::test_custom_repr_single
PySnooper
2
class Tracer: # # old_local_reprs = self.frame_to_local_reprs.get(frame, {}) self.frame_to_local_reprs[frame] = local_reprs = \ get_local_reprs(frame, watch=self.watch) newish_stri...
class Tracer: # # old_local_reprs = self.frame_to_local_reprs.get(frame, {}) self.frame_to_local_reprs[frame] = local_reprs = \ get_local_reprs(frame, watch=self.watch, custom_repr=self.cus...
pytest -q -s tests/test_pysnooper.py::test_custom_repr_single
PySnooper
2
class Tracer: thread_global.depth -= 1 if not ended_by_exception: return_value_repr = utils.get_shortish_repr(arg) self.write('{indent}Return value:.. {return_value_repr}'. format(**locals()))
class Tracer: thread_global.depth -= 1 if not ended_by_exception: return_value_repr = utils.get_shortish_repr(arg, custom_repr=self.custom_repr) self.write('{indent}Return value:.. {return_value_repr}'. format(**locals()))
pytest -q -s tests/test_pysnooper.py::test_custom_repr_single
thefuck
29
class Settings(dict): return self.get(item) def update(self, **kwargs): """Returns new settings with new values from `kwargs`.""" conf = dict(self) conf.update(kwargs) return Settings(conf)
class Settings(dict): return self.get(item) def update(self, **kwargs): """ Returns new settings with values from `kwargs` for unset settings. """ conf = dict(kwargs) conf.update(self) return Settings(conf)
pytest tests/test_utils.py::test_wrap_settings
youtube-dl
8
class YoutubeDL(object): elif string == '/': first_choice = current_selector second_choice = _parse_format_selection(tokens, inside_choice=True) current_selector = None selectors.append(FormatSelector(PIC...
class YoutubeDL(object): elif string == '/': first_choice = current_selector second_choice = _parse_format_selection(tokens, inside_choice=True) current_selector = FormatSelector(PICKFIRST, (first_choice, second_choice), []) ...
python -m unittest -q test.test_YoutubeDL.TestFormatSelection.test_youtube_format_selection
pandas
113
def any_int_dtype(request): return request.param @pytest.fixture(params=ALL_REAL_DTYPES) def any_real_dtype(request): """
def any_int_dtype(request): return request.param @pytest.fixture(params=ALL_EA_INT_DTYPES) def any_nullable_int_dtype(request): """ Parameterized fixture for any nullable integer dtype. * 'UInt8' * 'Int8' * 'UInt16' * 'Int16' * 'UInt32' * 'Int32' * 'UInt64' * 'Int64' "...
pytest pandas/tests/extension/test_integer.py::TestComparisonOps::test_compare_to_int
pandas
113
from pandas.core.dtypes.missing import isna, notna from pandas.core import nanops, ops from pandas.core.algorithms import take from pandas.core.arrays import ExtensionArray, ExtensionOpsMixin from pandas.core.ops.common import unpack_zerodim_and_defer from pandas.core.tools.numeric import to_numeric
from pandas.core.dtypes.missing import isna, notna from pandas.core import nanops, ops from pandas.core.algorithms import take from pandas.core.arrays import ExtensionArray, ExtensionOpsMixin from pandas.core.ops import invalid_comparison from pandas.core.ops.common import unpack_zerodim_and_defer from pandas.core.tool...
pytest pandas/tests/extension/test_integer.py::TestComparisonOps::test_compare_to_int
pandas
113
class IntegerArray(ExtensionArray, ExtensionOpsMixin): with warnings.catch_warnings(): warnings.filterwarnings("ignore", "elementwise", FutureWarning) with np.errstate(all="ignore"): result = op(self._data, other) # nans propagate ...
class IntegerArray(ExtensionArray, ExtensionOpsMixin): with warnings.catch_warnings(): warnings.filterwarnings("ignore", "elementwise", FutureWarning) with np.errstate(all="ignore"): method = getattr(self._data, f"__{op_name}__") result...
pytest pandas/tests/extension/test_integer.py::TestComparisonOps::test_compare_to_int