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 | 20 | def format_file_in_place(
with open(src, "w", encoding=src_buffer.encoding) as f:
f.write(dst_contents)
elif write_back == write_back.DIFF:
src_name = f"{src.name} (original)"
dst_name = f"{src.name} (formatted)"
diff_contents = diff(src_contents, dst_contents, src_name... | def format_file_in_place(
with open(src, "w", encoding=src_buffer.encoding) as f:
f.write(dst_contents)
elif write_back == write_back.DIFF:
src_name = f"{src} (original)"
dst_name = f"{src} (formatted)"
diff_contents = diff(src_contents, dst_contents, src_name, dst_name... | python -m unittest -q tests.test_black.BlackTestCase.test_expression_diff |
pandas | 168 | def _get_grouper(
elif is_in_axis(gpr): # df.groupby('name')
if gpr in obj:
if validate:
obj._check_label_or_level_ambiguity(gpr)
in_axis, name, gpr = True, gpr, obj[gpr]
exclusions.append(name)
elif obj._is_level_refer... | def _get_grouper(
elif is_in_axis(gpr): # df.groupby('name')
if gpr in obj:
if validate:
obj._check_label_or_level_ambiguity(gpr, axis=axis)
in_axis, name, gpr = True, gpr, obj[gpr]
exclusions.append(name)
elif obj._is_... | pytest pandas/tests/groupby/test_groupby.py::test_groupby_axis_1 |
fastapi | 9 | def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]:
for f in flat_dependant.body_params:
BodyModel.__fields__[f.name] = get_schema_compatible_field(field=f)
required = any(True for f in flat_dependant.body_params if f.required)
if any(isinstance(f.schema, params.File) for f in... | def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]:
for f in flat_dependant.body_params:
BodyModel.__fields__[f.name] = get_schema_compatible_field(field=f)
required = any(True for f in flat_dependant.body_params if f.required)
BodySchema_kwargs: Dict[str, Any] = dict(default... | pytest tests/test_request_body_parameters_media_type.py::test_openapi_schema |
fastapi | 9 | def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]:
else:
BodySchema = params.Body
field = Field(
name="body",
type_=BodyModel, | def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]:
else:
BodySchema = params.Body
body_param_media_types = [
getattr(f.schema, "media_type")
for f in flat_dependant.body_params
if isinstance(f.schema, params.Body)
]
if len(... | pytest tests/test_request_body_parameters_media_type.py::test_openapi_schema |
fastapi | 9 | def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]:
model_config=BaseConfig,
class_validators={},
alias="body",
schema=BodySchema(None),
)
return field | def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]:
model_config=BaseConfig,
class_validators={},
alias="body",
schema=BodySchema(**BodySchema_kwargs),
)
return field | pytest tests/test_request_body_parameters_media_type.py::test_openapi_schema |
httpie | 4 | class HTTPRequest(HTTPMessage):
)
headers = dict(self._orig.headers)
if 'Host' not in headers:
headers['Host'] = url.netloc.split('@')[-1]
headers = ['%s: %s' % (name, value) | class HTTPRequest(HTTPMessage):
)
headers = dict(self._orig.headers)
if 'Host' not in self._orig.headers:
headers['Host'] = url.netloc.split('@')[-1]
headers = ['%s: %s' % (name, value) | pytest tests/test_regressions.py::test_Host_header_overwrite |
scrapy | 21 | class RobotsTxtMiddleware(object):
rp_dfd.callback(rp)
def _robots_error(self, failure, netloc):
self._parsers.pop(netloc).callback(None) | class RobotsTxtMiddleware(object):
rp_dfd.callback(rp)
def _robots_error(self, failure, netloc):
rp_dfd = self._parsers[netloc]
self._parsers[netloc] = None
rp_dfd.callback(None) | python -m unittest -q tests.test_downloadermiddleware_robotstxt.RobotsTxtMiddlewareTest.test_robotstxt_immediate_error |
pandas | 15 | 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_datetime.py::TestDatetimeIndex::test_pickle_after_set_freq |
pandas | 15 | 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):
arr = self._data._with_freq(freq)
return type(self)._simple_new(arr, name=self.name)
def _shallow_copy(self, values=None, name: Label = lib.no_default):
name = self.name i... | pytest pandas/tests/indexes/datetimes/test_datetime.py::TestDatetimeIndex::test_pickle_after_set_freq |
pandas | 15 | class TestTimedeltaIndex(DatetimeLike):
def test_pickle_compat_construction(self):
pass
def test_isin(self):
index = tm.makeTimedeltaIndex(4) | class TestTimedeltaIndex(DatetimeLike):
def test_pickle_compat_construction(self):
pass
def test_pickle_after_set_freq(self):
tdi = timedelta_range("1 day", periods=4, freq="s")
tdi = tdi._with_freq(None)
res = tm.round_trip_pickle(tdi)
tm.assert_index_equal(res, tdi)
... | pytest pandas/tests/indexes/datetimes/test_datetime.py::TestDatetimeIndex::test_pickle_after_set_freq |
fastapi | 12 | class HTTPBearer(HTTPBase):
else:
return None
if scheme.lower() != "bearer":
raise HTTPException(
status_code=HTTP_403_FORBIDDEN,
detail="Invalid authentication credentials",
)
return HTTPAuthorizationCredentials(scheme=... | class HTTPBearer(HTTPBase):
else:
return None
if scheme.lower() != "bearer":
if self.auto_error:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN,
detail="Invalid authentication credentials",
)
... | pytest tests/test_security_http_bearer_optional.py::test_security_http_bearer_incorrect_scheme_credentials |
pandas | 149 | from pandas.errors import AbstractMethodError
from pandas import DataFrame, get_option
from pandas.io.common import get_filepath_or_buffer, is_s3_url
def get_engine(engine): | from pandas.errors import AbstractMethodError
from pandas import DataFrame, get_option
from pandas.io.common import get_filepath_or_buffer, is_gcs_url, is_s3_url
def get_engine(engine): | pytest pandas/tests/io/test_gcs.py::test_to_parquet_gcs_new_file |
pandas | 149 | class FastParquetImpl(BaseImpl):
if partition_cols is not None:
kwargs["file_scheme"] = "hive"
if is_s3_url(path):
# path is s3:// so we need to open the s3file in 'wb' mode.
# TODO: Support 'ab'
path, _, _, _ = get_filepath_or_buffer(path, mode="wb")
... | class FastParquetImpl(BaseImpl):
if partition_cols is not None:
kwargs["file_scheme"] = "hive"
if is_s3_url(path) or is_gcs_url(path):
# if path is s3:// or gs:// we need to open the file in 'wb' mode.
# TODO: Support 'ab'
path, _, _, _ = get_filepath_or... | pytest pandas/tests/io/test_gcs.py::test_to_parquet_gcs_new_file |
pandas | 126 | class DataFrame(NDFrame):
other = other._convert(datetime=True, timedelta=True)
if not self.columns.equals(combined_columns):
self = self.reindex(columns=combined_columns)
elif isinstance(other, list) and not isinstance(other[0], DataFrame):
other = DataFrame(... | class DataFrame(NDFrame):
other = other._convert(datetime=True, timedelta=True)
if not self.columns.equals(combined_columns):
self = self.reindex(columns=combined_columns)
elif isinstance(other, list):
if not other:
pass
elif not is... | pytest pandas/tests/frame/test_combine_concat.py::TestDataFrameConcatCommon::test_append_empty_list |
pandas | 87 | def crosstab(
from pandas import DataFrame
df = DataFrame(data, index=common_idx)
if values is None:
df["__dummy__"] = 0
kwargs = {"aggfunc": len, "fill_value": 0} | def crosstab(
from pandas import DataFrame
df = DataFrame(data, index=common_idx)
original_df_cols = df.columns
if values is None:
df["__dummy__"] = 0
kwargs = {"aggfunc": len, "fill_value": 0} | pytest pandas/tests/reshape/test_pivot.py::TestCrosstab::test_crosstab_both_tuple_names |
pandas | 87 | def crosstab(
kwargs = {"aggfunc": aggfunc}
table = df.pivot_table(
"__dummy__",
index=rownames,
columns=colnames,
margins=margins, | def crosstab(
kwargs = {"aggfunc": aggfunc}
table = df.pivot_table(
["__dummy__"],
index=rownames,
columns=colnames,
margins=margins, | pytest pandas/tests/reshape/test_pivot.py::TestCrosstab::test_crosstab_both_tuple_names |
pandas | 87 | def crosstab(
**kwargs,
)
# Post-process
if normalize is not False:
table = _normalize( | def crosstab(
**kwargs,
)
# GH18321, after pivoting, an extra top level of column index of `__dummy__` is
# created, and this extra level should not be included in the further steps
if not table.empty:
cols_diff = df.columns.difference(original_df_cols)[0]
table = table[cols_dif... | pytest pandas/tests/reshape/test_pivot.py::TestCrosstab::test_crosstab_both_tuple_names |
pandas | 41 | from pandas._libs import NaT, Timestamp, algos as libalgos, lib, tslib, writers
import pandas._libs.internals as libinternals
from pandas._libs.tslibs import Timedelta, conversion
from pandas._libs.tslibs.timezones import tz_compare
from pandas.util._validators import validate_bool_kwarg
from pandas.core.dtypes.cast i... | from pandas._libs import NaT, Timestamp, algos as libalgos, lib, tslib, writers
import pandas._libs.internals as libinternals
from pandas._libs.tslibs import Timedelta, conversion
from pandas._libs.tslibs.timezones import tz_compare
from pandas._typing import ArrayLike
from pandas.util._validators import validate_bool_... | pytest pandas/tests/internals/test_internals.py::TestShouldStore::test_should_store_categorical |
pandas | 41 | class Block(PandasObject):
def set(self, locs, values):
"""
Modify Block in-place with new item value
Returns
-------
None
"""
self.values[locs] = values
| class Block(PandasObject):
def set(self, locs, values):
"""
Modify block values in-place with new item value.
Notes
-----
`set` never creates a new array or new Block, whereas `setitem` _may_
create a new array and always creates a new Block.
"""
sel... | pytest pandas/tests/internals/test_internals.py::TestShouldStore::test_should_store_categorical |
pandas | 41 | class Block(PandasObject):
def setitem(self, indexer, value):
"""
Set the value inplace, returning a a maybe different typed block.
Parameters
---------- | class Block(PandasObject):
def setitem(self, indexer, value):
"""
Attempt self.values[indexer] = value, possibly creating a new array.
Parameters
---------- | pytest pandas/tests/internals/test_internals.py::TestShouldStore::test_should_store_categorical |
pandas | 41 | class ExtensionBlock(Block):
raise IndexError(f"{self} only contains one item")
return self.values
def should_store(self, value):
return isinstance(value, self._holder)
def set(self, locs, values, check=False):
assert locs.tolist() == [0]
self.values = value... | class ExtensionBlock(Block):
raise IndexError(f"{self} only contains one item")
return self.values
def should_store(self, value: ArrayLike) -> bool:
"""
Can we set the given array-like value inplace?
"""
return isinstance(value, self._holder)
def set... | pytest pandas/tests/internals/test_internals.py::TestShouldStore::test_should_store_categorical |
pandas | 41 | class ExtensionBlock(Block):
def setitem(self, indexer, value):
"""
Set the value inplace, returning a same-typed block.
This differs from Block.setitem by not allowing setitem to change
the dtype of the Block. | class ExtensionBlock(Block):
def setitem(self, indexer, value):
"""
Attempt self.values[indexer] = value, possibly creating a new array.
This differs from Block.setitem by not allowing setitem to change
the dtype of the Block. | pytest pandas/tests/internals/test_internals.py::TestShouldStore::test_should_store_categorical |
pandas | 41 | class FloatBlock(FloatOrComplexBlock):
)
return formatter.get_result_as_array()
def should_store(self, value) -> bool:
# when inserting a column should not coerce integers to floats
# unnecessarily
return issubclass(value.dtype.type, np.floating) and value.dtype == self.dtyp... | class FloatBlock(FloatOrComplexBlock):
)
return formatter.get_result_as_array()
def should_store(self, value: ArrayLike) -> bool:
# when inserting a column should not coerce integers to floats
# unnecessarily
return issubclass(value.dtype.type, np.floating) and value.dtype =... | pytest pandas/tests/internals/test_internals.py::TestShouldStore::test_should_store_categorical |
pandas | 41 | class ComplexBlock(FloatOrComplexBlock):
element, (float, int, complex, np.float_, np.int_)
) and not isinstance(element, (bool, np.bool_))
def should_store(self, value) -> bool:
return issubclass(value.dtype.type, np.complexfloating)
| class ComplexBlock(FloatOrComplexBlock):
element, (float, int, complex, np.float_, np.int_)
) and not isinstance(element, (bool, np.bool_))
def should_store(self, value: ArrayLike) -> bool:
return issubclass(value.dtype.type, np.complexfloating)
| pytest pandas/tests/internals/test_internals.py::TestShouldStore::test_should_store_categorical |
pandas | 41 | class IntBlock(NumericBlock):
)
return is_integer(element)
def should_store(self, value) -> bool:
return is_integer_dtype(value) and value.dtype == self.dtype
| class IntBlock(NumericBlock):
)
return is_integer(element)
def should_store(self, value: ArrayLike) -> bool:
return is_integer_dtype(value) and value.dtype == self.dtype
| pytest pandas/tests/internals/test_internals.py::TestShouldStore::test_should_store_categorical |
pandas | 41 | class DatetimeLikeBlockMixin:
def _holder(self):
return DatetimeArray
@property
def fill_value(self):
return np.datetime64("NaT", "ns") | class DatetimeLikeBlockMixin:
def _holder(self):
return DatetimeArray
def should_store(self, value):
return is_dtype_equal(self.dtype, value.dtype)
@property
def fill_value(self):
return np.datetime64("NaT", "ns") | pytest pandas/tests/internals/test_internals.py::TestShouldStore::test_should_store_categorical |
pandas | 41 | class DatetimeBlock(DatetimeLikeBlockMixin, Block):
).reshape(i8values.shape)
return np.atleast_2d(result)
def should_store(self, value) -> bool:
return is_datetime64_dtype(value.dtype)
def set(self, locs, values):
"""
Modify Block in-place with new item value
... | class DatetimeBlock(DatetimeLikeBlockMixin, Block):
).reshape(i8values.shape)
return np.atleast_2d(result)
def set(self, locs, values):
"""
See Block.set.__doc__
"""
values = conversion.ensure_datetime64ns(values, copy=False)
| pytest pandas/tests/internals/test_internals.py::TestShouldStore::test_should_store_categorical |
pandas | 41 | class DatetimeTZBlock(ExtensionBlock, DatetimeBlock):
_can_hold_element = DatetimeBlock._can_hold_element
to_native_types = DatetimeBlock.to_native_types
fill_value = np.datetime64("NaT", "ns")
@property
def _holder(self): | class DatetimeTZBlock(ExtensionBlock, DatetimeBlock):
_can_hold_element = DatetimeBlock._can_hold_element
to_native_types = DatetimeBlock.to_native_types
fill_value = np.datetime64("NaT", "ns")
should_store = DatetimeBlock.should_store
@property
def _holder(self): | pytest pandas/tests/internals/test_internals.py::TestShouldStore::test_should_store_categorical |
pandas | 41 | class TimeDeltaBlock(DatetimeLikeBlockMixin, IntBlock):
)
return super().fillna(value, **kwargs)
def should_store(self, value) -> bool:
return is_timedelta64_dtype(value.dtype)
def to_native_types(self, slicer=None, na_rep=None, quoting=None, **kwargs):
""" convert to our n... | class TimeDeltaBlock(DatetimeLikeBlockMixin, IntBlock):
)
return super().fillna(value, **kwargs)
def to_native_types(self, slicer=None, na_rep=None, quoting=None, **kwargs):
""" convert to our native types format, slicing if desired """
values = self.values | pytest pandas/tests/internals/test_internals.py::TestShouldStore::test_should_store_categorical |
pandas | 41 | class BoolBlock(NumericBlock):
return issubclass(tipo.type, np.bool_)
return isinstance(element, (bool, np.bool_))
def should_store(self, value) -> bool:
return issubclass(value.dtype.type, np.bool_) and not is_extension_array_dtype(
value
) | class BoolBlock(NumericBlock):
return issubclass(tipo.type, np.bool_)
return isinstance(element, (bool, np.bool_))
def should_store(self, value: ArrayLike) -> bool:
return issubclass(value.dtype.type, np.bool_) and not is_extension_array_dtype(
value
) | pytest pandas/tests/internals/test_internals.py::TestShouldStore::test_should_store_categorical |
pandas | 41 | class ObjectBlock(Block):
def _can_hold_element(self, element: Any) -> bool:
return True
def should_store(self, value) -> bool:
return not (
issubclass(
value.dtype.type, | class ObjectBlock(Block):
def _can_hold_element(self, element: Any) -> bool:
return True
def should_store(self, value: ArrayLike) -> bool:
return not (
issubclass(
value.dtype.type, | pytest pandas/tests/internals/test_internals.py::TestShouldStore::test_should_store_categorical |
pandas | 41 | class CategoricalBlock(ExtensionBlock):
def _holder(self):
return Categorical
def to_native_types(self, slicer=None, na_rep="", quoting=None, **kwargs):
""" convert to our native types format, slicing if desired """
values = self.values | class CategoricalBlock(ExtensionBlock):
def _holder(self):
return Categorical
def should_store(self, arr: ArrayLike):
return isinstance(arr, self._holder) and is_dtype_equal(self.dtype, arr.dtype)
def to_native_types(self, slicer=None, na_rep="", quoting=None, **kwargs):
""" conver... | pytest pandas/tests/internals/test_internals.py::TestShouldStore::test_should_store_categorical |
youtube-dl | 30 | class YoutubeDL(object):
format_spec = selector.selector
def selector_function(formats):
if format_spec == 'all':
for f in formats:
yield f | class YoutubeDL(object):
format_spec = selector.selector
def selector_function(formats):
formats = list(formats)
if not formats:
return
if format_spec == 'all':
for f in formats:
... | python -m unittest -q test.test_YoutubeDL.TestFormatSelection.test_format_filtering |
thefuck | 27 | def match(command, settings):
def get_new_command(command, settings):
return 'open http://' + command.script[5:] | def match(command, settings):
def get_new_command(command, settings):
return command.script.replace('open ', 'open http://') | pytest tests/rules/test_open.py::test_get_new_command |
youtube-dl | 6 | def match_filter_func(filter_str):
def parse_dfxp_time_expr(time_expr):
if not time_expr:
return 0.0
mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
if mobj: | def match_filter_func(filter_str):
def parse_dfxp_time_expr(time_expr):
if not time_expr:
return
mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
if mobj: | python -m unittest -q test.test_utils.TestUtil.test_parse_dfxp_time_expr |
youtube-dl | 6 | def dfxp2srt(dfxp_data):
raise ValueError('Invalid dfxp/TTML subtitle')
for para, index in zip(paras, itertools.count(1)):
begin_time = parse_dfxp_time_expr(para.attrib['begin'])
end_time = parse_dfxp_time_expr(para.attrib.get('end'))
if not end_time:
end_time = begin_ti... | def dfxp2srt(dfxp_data):
raise ValueError('Invalid dfxp/TTML subtitle')
for para, index in zip(paras, itertools.count(1)):
begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
end_time = parse_dfxp_time_expr(para.attrib.get('end'))
dur = parse_dfxp_time_expr(para.attrib.get('... | python -m unittest -q test.test_utils.TestUtil.test_parse_dfxp_time_expr |
tqdm | 3 | class tqdm(Comparable):
# NB: Avoid race conditions by setting start_t at the very end of init
self.start_t = self.last_print_t
def __len__(self):
return self.total if self.iterable is None else \
(self.iterable.shape[0] if hasattr(self.iterable, "shape") | class tqdm(Comparable):
# NB: Avoid race conditions by setting start_t at the very end of init
self.start_t = self.last_print_t
def __bool__(self):
if self.total is not None:
return self.total > 0
if self.iterable is None:
raise TypeError('Boolean cast is und... | python3 -m pytest tqdm/tests/tests_tqdm.py::test_bool |
keras | 29 | class Model(Container):
nested_weighted_metrics = _collect_metrics(weighted_metrics, self.output_names)
self.metrics_updates = []
self.stateful_metric_names = []
with K.name_scope('metrics'):
for i in range(len(self.outputs)):
if i in skip_target_indices: | class Model(Container):
nested_weighted_metrics = _collect_metrics(weighted_metrics, self.output_names)
self.metrics_updates = []
self.stateful_metric_names = []
self.stateful_metric_functions = []
with K.name_scope('metrics'):
for i in range(len(self.outputs)):
... | pytest tests/keras/metrics_test.py::test_stateful_metrics[dict] |
keras | 29 | class Model(Container):
# stateful metrics (i.e. metrics layers).
if isinstance(metric_fn, Layer) and metric_fn.stateful:
self.stateful_metric_names.append(metric_name)
self.metrics_updates += metric_fn.updates
... | class Model(Container):
# stateful metrics (i.e. metrics layers).
if isinstance(metric_fn, Layer) and metric_fn.stateful:
self.stateful_metric_names.append(metric_name)
self.stateful_metric_functions.append(metric_fn... | pytest tests/keras/metrics_test.py::test_stateful_metrics[dict] |
keras | 29 | class Model(Container):
for epoch in range(initial_epoch, epochs):
# Reset stateful metrics
for m in self.metrics:
if isinstance(m, Layer) and m.stateful:
m.reset_states()
callbacks.on_epoch_begin(epoch)
epoch_logs = {}
... | class Model(Container):
for epoch in range(initial_epoch, epochs):
# Reset stateful metrics
for m in self.stateful_metric_functions:
m.reset_states()
callbacks.on_epoch_begin(epoch)
epoch_logs = {}
if steps_per_epoch is not None: | pytest tests/keras/metrics_test.py::test_stateful_metrics[dict] |
keras | 29 | class Model(Container):
"""
if hasattr(self, 'metrics'):
for m in self.metrics:
if isinstance(m, Layer) and m.stateful:
m.reset_states()
stateful_metric_indices = [
i for i, name in enumerate(self.metrics_names)
... | class Model(Container):
"""
if hasattr(self, 'metrics'):
for m in self.stateful_metric_functions:
m.reset_states()
stateful_metric_indices = [
i for i, name in enumerate(self.metrics_names)
if str(name) in self.stateful_metric_name... | pytest tests/keras/metrics_test.py::test_stateful_metrics[dict] |
keras | 29 | class Model(Container):
# Construct epoch logs.
epoch_logs = {}
while epoch < epochs:
for m in self.metrics:
if isinstance(m, Layer) and m.stateful:
m.reset_states()
callbacks.on_epoch_begin(epoch)
... | class Model(Container):
# Construct epoch logs.
epoch_logs = {}
while epoch < epochs:
for m in self.stateful_metric_functions:
m.reset_states()
callbacks.on_epoch_begin(epoch)
steps_done = 0
batch_ind... | pytest tests/keras/metrics_test.py::test_stateful_metrics[dict] |
keras | 29 | class Model(Container):
stateful_metric_indices = []
if hasattr(self, 'metrics'):
for i, m in enumerate(self.metrics):
if isinstance(m, Layer) and m.stateful:
m.reset_states()
stateful_metric_indices = [
i for i, name in enumer... | class Model(Container):
stateful_metric_indices = []
if hasattr(self, 'metrics'):
for m in self.stateful_metric_functions:
m.reset_states()
stateful_metric_indices = [
i for i, name in enumerate(self.metrics_names)
if str(name) in ... | pytest tests/keras/metrics_test.py::test_stateful_metrics[dict] |
pandas | 153 | import warnings
import numpy as np
from pandas._libs import NaT, Timestamp, lib, tslib
import pandas._libs.internals as libinternals
from pandas._libs.tslibs import Timedelta, conversion
from pandas._libs.tslibs.timezones import tz_compare | import warnings
import numpy as np
from pandas._libs import NaT, Timestamp, lib, tslib, writers
import pandas._libs.internals as libinternals
from pandas._libs.tslibs import Timedelta, conversion
from pandas._libs.tslibs.timezones import tz_compare | pytest pandas/tests/io/formats/test_to_csv.py::TestToCSV::test_to_csv_na_rep_long_string |
pandas | 153 | class Block(PandasObject):
mask = isna(values)
if not self.is_object and not quoting:
values = values.astype(str)
else:
values = np.array(values, dtype="object")
| class Block(PandasObject):
mask = isna(values)
if not self.is_object and not quoting:
itemsize = writers.word_len(na_rep)
values = values.astype("<U{size}".format(size=itemsize))
else:
values = np.array(values, dtype="object")
| pytest pandas/tests/io/formats/test_to_csv.py::TestToCSV::test_to_csv_na_rep_long_string |
matplotlib | 26 | 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 |
luigi | 15 | class SimpleTaskState(object):
def get_necessary_tasks(self):
necessary_tasks = set()
for task in self.get_active_tasks():
if task.status not in (DONE, DISABLED) or \
getattr(task, 'scheduler_disable_time', None) is not None:
necessary_tasks.update(tas... | class SimpleTaskState(object):
def get_necessary_tasks(self):
necessary_tasks = set()
for task in self.get_active_tasks():
if task.status not in (DONE, DISABLED, UNKNOWN) or \
task.scheduler_disable_time is not None:
necessary_tasks.update(task.deps)
... | pytest test/central_planner_test.py::CentralPlannerTest::test_assistants_dont_nurture_finished_statuses |
pandas | 60 | class _Rolling_and_Expanding(_Rolling):
raise ValueError("engine must be either 'numba' or 'cython'")
# TODO: Why do we always pass center=False?
# name=func for WindowGroupByMixin._apply
return self._apply(
apply_func,
center=False,
floor=0,
... | class _Rolling_and_Expanding(_Rolling):
raise ValueError("engine must be either 'numba' or 'cython'")
# TODO: Why do we always pass center=False?
# name=func & raw=raw for WindowGroupByMixin._apply
return self._apply(
apply_func,
center=False,
flo... | pytest pandas/tests/window/test_grouper.py::TestGrouperGrouping::test_groupby_rolling |
youtube-dl | 11 | def str_or_none(v, default=None):
def str_to_int(int_str):
""" A more relaxed version of int_or_none """
if int_str is None:
return None
int_str = re.sub(r'[,\.\+]', '', int_str)
return int(int_str)
| def str_or_none(v, default=None):
def str_to_int(int_str):
""" A more relaxed version of int_or_none """
if not isinstance(int_str, compat_str):
return int_str
int_str = re.sub(r'[,\.\+]', '', int_str)
return int(int_str)
| python -m unittest -q test.test_utils.TestUtil.test_str_to_int |
tornado | 3 | class AsyncHTTPClient(Configurable):
return
self._closed = True
if self._instance_cache is not None:
if self._instance_cache.get(self.io_loop) is not self:
raise RuntimeError("inconsistent AsyncHTTPClient cache")
del self._instance_cache[self.io_loop]
... | class AsyncHTTPClient(Configurable):
return
self._closed = True
if self._instance_cache is not None:
cached_val = self._instance_cache.pop(self.io_loop, None)
# If there's an object other than self in the instance
# cache for our IOLoop, something has gott... | python -m unittest -q tornado.test.httpclient_test.SyncHTTPClientSubprocessTest |
pandas | 4 | class Index(IndexOpsMixin, PandasObject):
multi_join_idx = multi_join_idx.remove_unused_levels()
return multi_join_idx, lidx, ridx
jl = list(overlap)[0]
| class Index(IndexOpsMixin, PandasObject):
multi_join_idx = multi_join_idx.remove_unused_levels()
if return_indexers:
return multi_join_idx, lidx, ridx
else:
return multi_join_idx
jl = list(overlap)[0]
| pytest pandas/tests/indexes/multi/test_join.py::test_join_multi_return_indexers |
tornado | 11 | class HTTP1Connection(httputil.HTTPConnection):
if content_length is not None:
return self._read_fixed_body(content_length, delegate)
if headers.get("Transfer-Encoding") == "chunked":
return self._read_chunked_body(delegate)
if self.is_client:
return self._re... | class HTTP1Connection(httputil.HTTPConnection):
if content_length is not None:
return self._read_fixed_body(content_length, delegate)
if headers.get("Transfer-Encoding", "").lower() == "chunked":
return self._read_chunked_body(delegate)
if self.is_client:
ret... | python -m unittest -q tornado.test.httpserver_test.HTTPServerRawTest.test_chunked_request_uppercase |
scrapy | 37 | class Request(object_ref):
s = safe_url_string(url, self.encoding)
self._url = escape_ajax(s)
if ':' not in self._url:
raise ValueError('Missing scheme in request url: %s' % self._url)
url = property(_get_url, obsolete_setter(_set_url, 'url')) | class Request(object_ref):
s = safe_url_string(url, self.encoding)
self._url = escape_ajax(s)
if ('://' not in self._url) and (not self._url.startswith('data:')):
raise ValueError('Missing scheme in request url: %s' % self._url)
url = property(_get_url, obsolete_setter(_set_url... | python -m unittest -q tests.test_http_request.RequestTest.test_url_no_scheme |
pandas | 8 | class Block(PandasObject):
mask = missing.mask_missing(values, to_replace)
if not mask.any():
if inplace:
return [self]
return [self.copy()]
try:
blocks = self.putmask(mask, value, inplace=inplace)
# Note: it is _not_ the case th... | class Block(PandasObject):
mask = missing.mask_missing(values, to_replace)
try:
blocks = self.putmask(mask, value, inplace=inplace)
# Note: it is _not_ the case that self._can_hold_element(value) | pytest pandas/tests/frame/methods/test_replace.py::TestDataFrameReplace::test_replace_no_replacement_dtypes |
black | 17 | def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]:
"""
srcbuf = io.BytesIO(src)
encoding, lines = tokenize.detect_encoding(srcbuf.readline)
newline = "\r\n" if b"\r\n" == lines[0][-2:] else "\n"
srcbuf.seek(0)
with io.TextIOWrapper(srcbuf, encoding) as tiow: | def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]:
"""
srcbuf = io.BytesIO(src)
encoding, lines = tokenize.detect_encoding(srcbuf.readline)
if not lines:
return "", encoding, "\n"
newline = "\r\n" if b"\r\n" == lines[0][-2:] else "\n"
srcbuf.seek(0)
with io.TextI... | python -m unittest -q tests.test_black.BlackTestCase.test_empty |
black | 17 | GRAMMARS = [
def lib2to3_parse(src_txt: str) -> Node:
"""Given a string with source, return the lib2to3 Node."""
grammar = pygram.python_grammar_no_print_statement
if src_txt[-1] != "\n":
src_txt += "\n"
for grammar in GRAMMARS:
drv = driver.Driver(grammar, pytree.convert) | GRAMMARS = [
def lib2to3_parse(src_txt: str) -> Node:
"""Given a string with source, return the lib2to3 Node."""
grammar = pygram.python_grammar_no_print_statement
if src_txt[-1:] != "\n":
src_txt += "\n"
for grammar in GRAMMARS:
drv = driver.Driver(grammar, pytree.convert) | python -m unittest -q tests.test_black.BlackTestCase.test_empty |
luigi | 19 | class SimpleTaskState(object):
elif task.scheduler_disable_time is not None:
return
if new_status == FAILED and task.can_disable():
task.add_failure()
if task.has_excessive_failures():
task.scheduler_disable_time = time.time() | class SimpleTaskState(object):
elif task.scheduler_disable_time is not None:
return
if new_status == FAILED and task.can_disable() and task.status != DISABLED:
task.add_failure()
if task.has_excessive_failures():
task.scheduler_disable_time = ... | pytest test/central_planner_test.py::CentralPlannerTest::test_automatic_re_enable_with_one_failure_allowed |
pandas | 91 | class TimedeltaIndex(
@Appender(_shared_docs["searchsorted"])
def searchsorted(self, value, side="left", sorter=None):
if isinstance(value, (np.ndarray, Index)):
value = np.array(value, dtype=_TD_DTYPE, copy=False)
else:
value = Timedelta(value).asm8.view(_TD_DTYPE)
... | class TimedeltaIndex(
@Appender(_shared_docs["searchsorted"])
def searchsorted(self, value, side="left", sorter=None):
if isinstance(value, (np.ndarray, Index)):
if not type(self._data)._is_recognized_dtype(value):
raise TypeError(
"searchsorted requires c... | pytest pandas/tests/arrays/test_timedeltas.py::TestTimedeltaArray::test_searchsorted_invalid_types |
pandas | 130 | class BinGrouper(BaseGrouper):
ngroups,
)
@cache_readonly
def result_index(self):
if len(self.binlabels) != 0 and isna(self.binlabels[0]): | class BinGrouper(BaseGrouper):
ngroups,
)
@cache_readonly
def recons_codes(self):
# get unique result indices, and prepend 0 as groupby starts from the first
return [np.r_[0, np.flatnonzero(self.bins[1:] != self.bins[:-1]) + 1]]
@cache_readonly
def result_index(self... | pytest pandas/tests/groupby/test_value_counts.py::test_series_groupby_value_counts_with_grouper |
black | 1 | def reformat_many(
if sys.platform == "win32":
# Work around https://bugs.python.org/issue26903
worker_count = min(worker_count, 61)
executor = ProcessPoolExecutor(max_workers=worker_count)
try:
loop.run_until_complete(
schedule_formatting( | def reformat_many(
if sys.platform == "win32":
# Work around https://bugs.python.org/issue26903
worker_count = min(worker_count, 61)
try:
executor = ProcessPoolExecutor(max_workers=worker_count)
except OSError:
# we arrive here if the underlying system does not support multi-... | python -m unittest -q tests.test_black.BlackTestCase.test_works_in_mono_process_only_environment |
black | 1 | def reformat_many(
)
finally:
shutdown(loop)
executor.shutdown()
async def schedule_formatting( | def reformat_many(
)
finally:
shutdown(loop)
if executor is not None:
executor.shutdown()
async def schedule_formatting( | python -m unittest -q tests.test_black.BlackTestCase.test_works_in_mono_process_only_environment |
black | 1 | async def schedule_formatting(
mode: Mode,
report: "Report",
loop: asyncio.AbstractEventLoop,
executor: Executor,
) -> None:
"""Run formatting of `sources` in parallel using the provided `executor`.
| async def schedule_formatting(
mode: Mode,
report: "Report",
loop: asyncio.AbstractEventLoop,
executor: Optional[Executor],
) -> None:
"""Run formatting of `sources` in parallel using the provided `executor`.
| python -m unittest -q tests.test_black.BlackTestCase.test_works_in_mono_process_only_environment |
scrapy | 16 | to the w3lib.url module. Always import those from there instead.
"""
import posixpath
import re
from six.moves.urllib.parse import (ParseResult, urlunparse, urldefrag,
urlparse, parse_qsl, urlencode,
unquote)
# scrapy.utils.url was moved to w3lib.... | to the w3lib.url module. Always import those from there instead.
"""
import posixpath
import re
import six
from six.moves.urllib.parse import (ParseResult, urlunparse, urldefrag,
urlparse, parse_qsl, urlencode,
quote, unquote)
if six.PY3:
from ... | python -m unittest -q tests.test_utils_url.CanonicalizeUrlTest.test_canonicalize_parse_url |
scrapy | 16 | def url_has_any_extension(url, extensions):
return posixpath.splitext(parse_url(url).path)[1].lower() in extensions
def canonicalize_url(url, keep_blank_values=True, keep_fragments=False,
encoding=None):
"""Canonicalize the given url by applying the following procedures:
- sort query... | def url_has_any_extension(url, extensions):
return posixpath.splitext(parse_url(url).path)[1].lower() in extensions
def _safe_ParseResult(parts, encoding='utf8', path_encoding='utf8'):
return (
to_native_str(parts.scheme),
to_native_str(parts.netloc.encode('idna')),
# default encoding... | python -m unittest -q tests.test_utils_url.CanonicalizeUrlTest.test_canonicalize_parse_url |
scrapy | 16 | def parse_url(url, encoding=None):
"""
if isinstance(url, ParseResult):
return url
return urlparse(to_native_str(url, encoding))
def escape_ajax(url): | def parse_url(url, encoding=None):
"""
if isinstance(url, ParseResult):
return url
return urlparse(to_unicode(url, encoding))
if six.PY3:
from urllib.parse import _coerce_args, unquote_to_bytes
def parse_qsl_to_bytes(qs, keep_blank_values=False, strict_parsing=False):
"""Parse a q... | python -m unittest -q tests.test_utils_url.CanonicalizeUrlTest.test_canonicalize_parse_url |
spacy | 2 | def load_model_from_path(model_path, meta=False, **overrides):
for name in pipeline:
if name not in disable:
config = meta.get("pipeline_args", {}).get(name, {})
factory = factories.get(name, name)
component = nlp.create_pipe(factory, config=config)
nlp.add_pi... | def load_model_from_path(model_path, meta=False, **overrides):
for name in pipeline:
if name not in disable:
config = meta.get("pipeline_args", {}).get(name, {})
config.update(overrides)
factory = factories.get(name, name)
component = nlp.create_pipe(factory, ... | py.test spacy/tests/regression/test_issue5137.py::test_issue5137 |
spacy | 10 | class Errors(object):
E168 = ("Unknown field: {field}")
E169 = ("Can't find module: {module}")
E170 = ("Cannot apply transition {name}: invalid for the current state.")
@add_codes | class Errors(object):
E168 = ("Unknown field: {field}")
E169 = ("Can't find module: {module}")
E170 = ("Cannot apply transition {name}: invalid for the current state.")
E171 = ("Matcher.add received invalid on_match callback argument: expected "
"callable or None, but got: {arg_type}")
@ad... | py.test spacy/tests/matcher/test_matcher_api.py::test_matcher_valid_callback |
keras | 25 | def _preprocess_numpy_input(x, data_format, mode):
# Returns
Preprocessed Numpy array.
"""
if mode == 'tf':
x /= 127.5
x -= 1. | def _preprocess_numpy_input(x, data_format, mode):
# Returns
Preprocessed Numpy array.
"""
x = x.astype(K.floatx())
if mode == 'tf':
x /= 127.5
x -= 1. | pytest tests/keras/applications/imagenet_utils_test.py::test_preprocess_input |
luigi | 3 | class TupleParameter(ListParameter):
try:
# loop required to parse tuple of tuples
return tuple(tuple(x) for x in json.loads(x, object_pairs_hook=_FrozenOrderedDict))
except ValueError:
return literal_eval(x) # if this causes an error, let that error be raised.
cla... | class TupleParameter(ListParameter):
try:
# loop required to parse tuple of tuples
return tuple(tuple(x) for x in json.loads(x, object_pairs_hook=_FrozenOrderedDict))
except (ValueError, TypeError):
return tuple(literal_eval(x)) # if this causes an error, let that er... | pytest test/parameter_test.py::TestSerializeTupleParameter::testSerialize |
ansible | 15 | def map_obj_to_commands(updates, module, warnings):
else:
add('protocol unix-socket')
if needs_update('state') and not needs_update('vrf'):
if want['state'] == 'stopped':
add('shutdown')
elif want['state'] == 'started': | def map_obj_to_commands(updates, module, warnings):
else:
add('protocol unix-socket')
if needs_update('state'):
if want['state'] == 'stopped':
add('shutdown')
elif want['state'] == 'started': | pytest test/units/modules/network/eos/test_eos_eapi.py::TestEosEapiModule::test_eos_eapi_vrf |
scrapy | 3 | import logging
from six.moves.urllib.parse import urljoin
from w3lib.url import safe_url_string
| import logging
from six.moves.urllib.parse import urljoin, urlparse
from w3lib.url import safe_url_string
| python -m unittest -q tests.test_downloadermiddleware_redirect.RedirectMiddlewareTest.test_redirect_302_relative |
scrapy | 3 | class RedirectMiddleware(BaseRedirectMiddleware):
if 'Location' not in response.headers or response.status not in allowed_status:
return response
location = safe_url_string(response.headers['location'])
redirected_url = urljoin(request.url, location)
| class RedirectMiddleware(BaseRedirectMiddleware):
if 'Location' not in response.headers or response.status not in allowed_status:
return response
location = safe_url_string(response.headers['Location'])
if response.headers['Location'].startswith(b'//'):
request_scheme = ... | python -m unittest -q tests.test_downloadermiddleware_redirect.RedirectMiddlewareTest.test_redirect_302_relative |
pandas | 111 | class Index(IndexOpsMixin, PandasObject):
"unicode",
"mixed",
]:
return self._invalid_indexer("label", key)
elif kind in ["loc"] and is_integer(key):
if not self.holds_integer():
return self._inv... | class Index(IndexOpsMixin, PandasObject):
"unicode",
"mixed",
]:
self._invalid_indexer("label", key)
elif kind in ["loc"] and is_integer(key):
if not self.holds_integer():
self._invalid_indexer("... | pytest pandas/tests/indexing/test_floats.py::TestFloatIndexers::test_scalar_non_numeric |
pandas | 111 | class CategoricalIndex(Index, accessor.PandasDelegate):
@Appender(_index_shared_docs["_convert_scalar_indexer"])
def _convert_scalar_indexer(self, key, kind=None):
if self.categories._defer_to_indexing:
return self.categories._convert_scalar_indexer(key, kind=kind)
return super()._... | class CategoricalIndex(Index, accessor.PandasDelegate):
@Appender(_index_shared_docs["_convert_scalar_indexer"])
def _convert_scalar_indexer(self, key, kind=None):
if kind == "loc":
try:
return self.categories._convert_scalar_indexer(key, kind=kind)
except TypeEr... | pytest pandas/tests/indexing/test_floats.py::TestFloatIndexers::test_scalar_non_numeric |
pandas | 22 | def get_weighted_roll_func(cfunc: Callable) -> Callable:
def validate_baseindexer_support(func_name: Optional[str]) -> None:
# GH 32865: These functions work correctly with a BaseIndexer subclass
BASEINDEXER_WHITELIST = {
"min",
"max",
"mean", | def get_weighted_roll_func(cfunc: Callable) -> Callable:
def validate_baseindexer_support(func_name: Optional[str]) -> None:
# GH 32865: These functions work correctly with a BaseIndexer subclass
BASEINDEXER_WHITELIST = {
"count",
"min",
"max",
"mean", | pytest pandas/tests/window/test_base_indexer.py::test_rolling_forward_window |
pandas | 22 | class _Rolling_and_Expanding(_Rolling):
)
def count(self):
if isinstance(self.window, BaseIndexer):
validate_baseindexer_support("count")
blocks, obj = self._create_blocks()
results = [] | class _Rolling_and_Expanding(_Rolling):
)
def count(self):
# GH 32865. Using count with custom BaseIndexer subclass
# implementations shouldn't end up here
assert not isinstance(self.window, BaseIndexer)
blocks, obj = self._create_blocks()
results = [] | pytest pandas/tests/window/test_base_indexer.py::test_rolling_forward_window |
pandas | 22 | class Rolling(_Rolling_and_Expanding):
def count(self):
# different impl for freq counting
if self.is_freq_type:
window_func = self._get_roll_func("roll_count")
return self._apply(window_func, center=self.center, name="count")
| class Rolling(_Rolling_and_Expanding):
def count(self):
# different impl for freq counting
# GH 32865. Use a custom count function implementation
# when using a BaseIndexer subclass as a window
if self.is_freq_type or isinstance(self.window, BaseIndexer):
window_func = s... | pytest pandas/tests/window/test_base_indexer.py::test_rolling_forward_window |
thefuck | 1 | def match(command):
def get_new_command(command):
broken_cmd = re.findall(r'ERROR: unknown command \"([a-z]+)\"',
command.output)[0]
new_cmd = re.findall(r'maybe you meant \"([a-z]+)\"', command.output)[0]
return replace_argument(command.script, broken_cmd, new_cmd) | def match(command):
def get_new_command(command):
broken_cmd = re.findall(r'ERROR: unknown command "([^"]+)"',
command.output)[0]
new_cmd = re.findall(r'maybe you meant "([^"]+)"', command.output)[0]
return replace_argument(command.script, broken_cmd, new_cmd) | pytest tests/rules/test_pip_unknown_command.py::test_get_new_command |
pandas | 144 | class BarPlot(MPLPlot):
def _decorate_ticks(self, ax, name, ticklabels, start_edge, end_edge):
ax.set_xlim((start_edge, end_edge))
ax.set_xticks(self.tick_pos)
ax.set_xticklabels(ticklabels)
if name is not None and self.use_index:
ax.set_xlabel(name)
| class BarPlot(MPLPlot):
def _decorate_ticks(self, ax, name, ticklabels, start_edge, end_edge):
ax.set_xlim((start_edge, end_edge))
if self.xticks is not None:
ax.set_xticks(np.array(self.xticks))
else:
ax.set_xticks(self.tick_pos)
ax.set_xticklabels(tick... | pytest pandas/tests/plotting/test_series.py::TestSeriesPlots::test_xtick_barPlot |
thefuck | 11 | def match(command):
@git_support
def get_new_command(command):
push_upstream = command.stderr.split('\n')[-3].strip().partition('git ')[2]
return replace_argument(command.script, 'push', push_upstream) | def match(command):
@git_support
def get_new_command(command):
# If --set-upstream or -u are passed, remove it and its argument. This is
# because the remaining arguments are concatenated onto the command suggested
# by git, which includes --set-upstream and its argument
upstream_option_index = -1
... | pytest tests/rules/test_git_push.py::test_get_new_command |
pandas | 18 | def validate_baseindexer_support(func_name: Optional[str]) -> None:
"median",
"std",
"var",
"kurt",
"quantile",
} | def validate_baseindexer_support(func_name: Optional[str]) -> None:
"median",
"std",
"var",
"skew",
"kurt",
"quantile",
} | pytest pandas/tests/window/test_base_indexer.py::test_rolling_forward_skewness |
pandas | 18 | class _Window(PandasObject, ShallowMixin, SelectionMixin):
def calc(x):
x = np.concatenate((x, additional_nans))
if not isinstance(window, BaseIndexer):
min_periods = calculate_min_periods(
window, self.min_peri... | class _Window(PandasObject, ShallowMixin, SelectionMixin):
def calc(x):
x = np.concatenate((x, additional_nans))
if not isinstance(self.window, BaseIndexer):
min_periods = calculate_min_periods(
window, self.min... | pytest pandas/tests/window/test_base_indexer.py::test_rolling_forward_skewness |
pandas | 77 | def na_logical_op(x: np.ndarray, y, op):
assert not (is_bool_dtype(x.dtype) and is_bool_dtype(y.dtype))
x = ensure_object(x)
y = ensure_object(y)
result = libops.vec_binop(x, y, op)
else:
# let null fall thru
assert lib.is_scalar(y) | def na_logical_op(x: np.ndarray, y, op):
assert not (is_bool_dtype(x.dtype) and is_bool_dtype(y.dtype))
x = ensure_object(x)
y = ensure_object(y)
result = libops.vec_binop(x.ravel(), y.ravel(), op)
else:
# let null fall thru
assert lib.is_s... | pytest pandas/tests/arithmetic/test_array_ops.py::test_na_logical_op_2d |
pandas | 77 | def na_logical_op(x: np.ndarray, y, op):
f"and scalar of type [{typ}]"
)
return result
def logical_op( | def na_logical_op(x: np.ndarray, y, op):
f"and scalar of type [{typ}]"
)
return result.reshape(x.shape)
def logical_op( | pytest pandas/tests/arithmetic/test_array_ops.py::test_na_logical_op_2d |
matplotlib | 2 | default: :rc:`scatter.edgecolors`
- 'none': No patch boundary will be drawn.
- A color or sequence of colors.
For non-filled markers, the *edgecolors* kwarg is ignored and
forced to 'face' internally.
plotnonfinite : bool, default: False
Set to plot ... | default: :rc:`scatter.edgecolors`
- 'none': No patch boundary will be drawn.
- A color or sequence of colors.
For non-filled markers, *edgecolors* is ignored. Instead, the color
is determined like with 'face', i.e. from *c*, *colors*, or
*facecolors*.
... | pytest lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_unfilled |
matplotlib | 2 | default: :rc:`scatter.edgecolors`
path = marker_obj.get_path().transformed(
marker_obj.get_transform())
if not marker_obj.is_filled():
edgecolors = 'face'
if linewidths is None:
linewidths = rcParams['lines.linewidth']
elif np.iterable(line... | default: :rc:`scatter.edgecolors`
path = marker_obj.get_path().transformed(
marker_obj.get_transform())
if not marker_obj.is_filled():
if linewidths is None:
linewidths = rcParams['lines.linewidth']
elif np.iterable(linewidths): | pytest lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_unfilled |
matplotlib | 2 | default: :rc:`scatter.edgecolors`
collection = mcoll.PathCollection(
(path,), scales,
facecolors=colors,
edgecolors=edgecolors,
linewidths=linewidths,
offsets=offsets,
transOffset=kwargs.pop('transform', self.transD... | default: :rc:`scatter.edgecolors`
collection = mcoll.PathCollection(
(path,), scales,
facecolors=colors if marker_obj.is_filled() else 'none',
edgecolors=edgecolors if marker_obj.is_filled() else colors,
linewidths=linewidths,
offs... | pytest lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_unfilled |
pandas | 56 | class DataFrame(NDFrame):
scalar
"""
if takeable:
series = self._iget_item_cache(col)
return com.maybe_box_datetimelike(series._values[index])
series = self._get_item_cache(col)
engine = self.index._engine | class DataFrame(NDFrame):
scalar
"""
if takeable:
series = self._ixs(col, axis=1)
return series._values[index]
series = self._get_item_cache(col)
engine = self.index._engine | pytest pandas/tests/indexing/test_scalar.py::test_iat_dont_wrap_object_datetimelike |
youtube-dl | 27 | def parse_dfxp_time_expr(time_expr):
if mobj:
return float(mobj.group('time_offset'))
mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:\.\d+)?)$', time_expr)
if mobj:
return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3))
def srt_subtitles_timecode(seconds): | def parse_dfxp_time_expr(time_expr):
if mobj:
return float(mobj.group('time_offset'))
mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
if mobj:
return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
def srt_subtitles_timecod... | python -m unittest -q test.test_utils.TestUtil.test_parse_dfxp_time_expr |
fastapi | 4 | def get_openapi_path(
operation_parameters = get_openapi_operation_parameters(all_route_params)
parameters.extend(operation_parameters)
if parameters:
operation["parameters"] = parameters
if method in METHODS_WITH_BODY:
request_body_oai = g... | def get_openapi_path(
operation_parameters = get_openapi_operation_parameters(all_route_params)
parameters.extend(operation_parameters)
if parameters:
operation["parameters"] = list(
{param["name"]: param for param in parameters}.values()
... | pytest tests/test_param_in_path_and_dependency.py::test_reused_param |
matplotlib | 10 | class Axis(martist.Artist):
self._minor_tick_kw.update(kwtrans)
for tick in self.minorTicks:
tick._apply_params(**kwtrans)
# special-case label color to also apply to the offset text
if 'labelcolor' in kwtrans:
self.offsetText.s... | class Axis(martist.Artist):
self._minor_tick_kw.update(kwtrans)
for tick in self.minorTicks:
tick._apply_params(**kwtrans)
# labelOn and labelcolor also apply to the offset text.
if 'label1On' in kwtrans or 'label2On' in kwtrans:
... | pytest lib/matplotlib/tests/test_axes.py::test_offset_text_visible |
thefuck | 30 | def _search(stderr):
def match(command, settings):
return 'EDITOR' in os.environ and _search(command.stderr)
def get_new_command(command, settings): | def _search(stderr):
def match(command, settings):
if 'EDITOR' not in os.environ:
return False
m = _search(command.stderr)
return m and os.path.isfile(m.group('file'))
def get_new_command(command, settings): | pytest tests/rules/test_fix_file.py::test_not_file |
pandas | 165 | class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray)
def __add__(self, other):
other = lib.item_from_zerodim(other)
if isinstance(other, (ABCSeries, ABCDataFrame)):
return NotImplemented
# scalar others | class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray)
def __add__(self, other):
other = lib.item_from_zerodim(other)
if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)):
return NotImplemented
# scalar others | pytest pandas/tests/arithmetic/test_datetime64.py::TestDatetimeIndexArithmetic::test_dta_add_sub_index |
pandas | 165 | class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray)
def __sub__(self, other):
other = lib.item_from_zerodim(other)
if isinstance(other, (ABCSeries, ABCDataFrame)):
return NotImplemented
# scalar others | class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray)
def __sub__(self, other):
other = lib.item_from_zerodim(other)
if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)):
return NotImplemented
# scalar others | pytest pandas/tests/arithmetic/test_datetime64.py::TestDatetimeIndexArithmetic::test_dta_add_sub_index |
pandas | 165 | class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray)
return result
def __rsub__(self, other):
if is_datetime64_dtype(other) and is_timedelta64_dtype(self):
# ndarray[datetime64] cannot be subtracted from self, so
# we need to wrap in DatetimeArray... | class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray)
return result
def __rsub__(self, other):
if is_datetime64_any_dtype(other) and is_timedelta64_dtype(self):
# ndarray[datetime64] cannot be subtracted from self, so
# we need to wrap in DatetimeA... | pytest pandas/tests/arithmetic/test_datetime64.py::TestDatetimeIndexArithmetic::test_dta_add_sub_index |
pandas | 165 | class TestPeriodIndexArithmetic:
with pytest.raises(TypeError):
other - obj
class TestPeriodSeriesArithmetic:
def test_ops_series_timedelta(self): | class TestPeriodIndexArithmetic:
with pytest.raises(TypeError):
other - obj
# ---------------------------------------------------------------
# Unsorted
def test_parr_add_sub_index(self):
# Check that PeriodArray defers to Index on arithmetic ops
pi = pd.period_range("2... | pytest pandas/tests/arithmetic/test_datetime64.py::TestDatetimeIndexArithmetic::test_dta_add_sub_index |
pandas | 165 | class TestTimedelta64ArithmeticUnsorted:
tm.assert_index_equal(result1, result4)
tm.assert_index_equal(result2, result3)
class TestAddSubNaTMasking:
# TODO: parametrize over boxes | class TestTimedelta64ArithmeticUnsorted:
tm.assert_index_equal(result1, result4)
tm.assert_index_equal(result2, result3)
def test_tda_add_sub_index(self):
# Check that TimedeltaArray defers to Index on arithmetic ops
tdi = TimedeltaIndex(["1 days", pd.NaT, "2 days"])
tda = t... | pytest pandas/tests/arithmetic/test_datetime64.py::TestDatetimeIndexArithmetic::test_dta_add_sub_index |
luigi | 23 | class core(task.Config):
class WorkerSchedulerFactory(object):
def create_local_scheduler(self):
return scheduler.CentralPlannerScheduler()
def create_remote_scheduler(self, host, port):
return rpc.RemoteScheduler(host=host, port=port) | 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, host, port):
return rpc.RemoteScheduler(host=host, port=port) | pytest test/worker_external_task_test.py::WorkerExternalTaskTest::test_external_dependency_completes_later |
luigi | 23 | class scheduler(Config):
visualization_graph = parameter.Parameter(default="svg", config_path=dict(section='scheduler', name='visualization-graph'))
def fix_time(x):
# Backwards compatibility for a fix in Dec 2014. Prior to the fix, pickled state might store datetime objects | class scheduler(Config):
visualization_graph = parameter.Parameter(default="svg", config_path=dict(section='scheduler', name='visualization-graph'))
prune_on_get_work = parameter.BoolParameter(default=False)
def fix_time(x):
# Backwards compatibility for a fix in Dec 2014. Prior to the fix, pickled stat... | pytest test/worker_external_task_test.py::WorkerExternalTaskTest::test_external_dependency_completes_later |
luigi | 23 | class Worker(object):
def __init__(self, worker_id, last_active=None):
self.id = worker_id
self.reference = None # reference to the worker in the real world. (Currently a dict containing just the host)
self.last_active = last_active # seconds since epoch
self.started = time.time() ... | class Worker(object):
def __init__(self, worker_id, last_active=None):
self.id = worker_id
self.reference = None # reference to the worker in the real world. (Currently a dict containing just the host)
self.last_active = last_active or time.time() # seconds since epoch
self.started... | pytest test/worker_external_task_test.py::WorkerExternalTaskTest::test_external_dependency_completes_later |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.