buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
def __init__(self, password_mgr=None):
self.passwd = password_mgr
self.add_password = self.passwd.add_password
def http_error_auth_reqed(self, authreq, host, req, headers):
# host may be an authority (without userinfo) or a URL with an
# authority
# XXX could be multiple hea... | def __init__(self, password_mgr=None):
self.passwd = password_mgr
self.add_password = self.passwd.add_password
def _parse_realm(self, header):
# parse WWW-Authenticate header: accept multiple challenges per header
found_challenge = False
for mo in AbstractBasicAuthHandler.rx... |
def get_domain(value):
token, value = get_dot_atom(value)
except errors.HeaderParseError:
token, value = get_atom(value)
if leader is not None:
token[:0] = [leader]
domain.append(token) | def get_domain(value):
token, value = get_dot_atom(value)
except errors.HeaderParseError:
token, value = get_atom(value)
if value and value[0] == '@':
raise errors.HeaderParseError('Invalid Domain')
if leader is not None:
token[:0] = [leader]
domain.append(token) |
def getaddrspec(self):
aslist.append('@')
self.pos += 1
self.gotonext()
return EMPTYSTRING.join(aslist) + self.getdomain()
def getdomain(self):
"""Get the complete domain name from an address.""" | def getaddrspec(self):
aslist.append('@')
self.pos += 1
self.gotonext()
domain = self.getdomain()
if not domain:
# Invalid domain, return an empty address instead of returning a
# local part to denote failed parsing.
return EMPTYSTRING
... |
def getdomain(self):
elif self.field[self.pos] == '.':
self.pos += 1
sdlist.append('.')
elif self.field[self.pos] in self.atomends:
break
else: | def getdomain(self):
elif self.field[self.pos] == '.':
self.pos += 1
sdlist.append('.')
elif self.field[self.pos] == '@':
# bpo-34155: Don't parse domains with two `@` like
# `a@malicious.org@important.com`.
return E... |
def test_get_addr_spec_dot_atom(self):
self.assertEqual(addr_spec.domain, 'example.com')
self.assertEqual(addr_spec.addr_spec, 'star.a.star@example.com')
# get_obs_route
def test_get_obs_route_simple(self): | def test_get_addr_spec_dot_atom(self):
self.assertEqual(addr_spec.domain, 'example.com')
self.assertEqual(addr_spec.addr_spec, 'star.a.star@example.com')
def test_get_addr_spec_multiple_domains(self):
with self.assertRaises(errors.HeaderParseError):
parser.get_addr_spec('star@a.... |
def test_parseaddr_empty(self):
self.assertEqual(utils.parseaddr('<>'), ('', ''))
self.assertEqual(utils.formataddr(utils.parseaddr('<>')), '')
def test_noquote_dump(self):
self.assertEqual(
utils.formataddr(('A Silly Person', 'person@dom.ain')), | def test_parseaddr_empty(self):
self.assertEqual(utils.parseaddr('<>'), ('', ''))
self.assertEqual(utils.formataddr(utils.parseaddr('<>')), '')
def test_parseaddr_multiple_domains(self):
self.assertEqual(
utils.parseaddr('a@b@c'),
('', '')
)
self.asse... |
#!/usr/bin/env python
from __future__ import unicode_literals
| #!/usr/bin/env python
# coding: utf-8
from __future__ import unicode_literals
|
class TestYoutubeDL(unittest.TestCase):
'duration': 30,
'filesize': 10 * 1024,
'playlist_id': '42',
}
second = {
'id': '2', | class TestYoutubeDL(unittest.TestCase):
'duration': 30,
'filesize': 10 * 1024,
'playlist_id': '42',
'uploader': "變態妍字幕版 太妍 тест",
'creator': "тест ' 123 ' тест--",
}
second = {
'id': '2', |
class TestYoutubeDL(unittest.TestCase):
'description': 'foo',
'filesize': 5 * 1024,
'playlist_id': '43',
}
videos = [first, second]
| class TestYoutubeDL(unittest.TestCase):
'description': 'foo',
'filesize': 5 * 1024,
'playlist_id': '43',
'uploader': "тест 123",
}
videos = [first, second]
|
class TestYoutubeDL(unittest.TestCase):
res = get_videos(f)
self.assertEqual(res, ['1'])
def test_playlist_items_selection(self):
entries = [{
'id': compat_str(i), | class TestYoutubeDL(unittest.TestCase):
res = get_videos(f)
self.assertEqual(res, ['1'])
f = match_filter_func('uploader = "變態妍字幕版 太妍 тест"')
res = get_videos(f)
self.assertEqual(res, ['1'])
f = match_filter_func('uploader != "變態妍字幕版 太妍 тест"')
res = get_videos(... |
def _match_one(filter_part, dct):
\s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
(?:
(?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
(?P<strval>(?![0-9.])[a-z0-9A-Z]*)
)
\s*$ | def _match_one(filter_part, dct):
\s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
(?:
(?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
(?P<quote>["\'])(?P<quotedstrval>(?:\\.|(?!(?P=quote)|\\).)+?)(?P=quote)|
(?P<strval>(?![0-9.])[a-z0-9A-Z]*)
)
\s*$ |
def _match_one(filter_part, dct):
if m:
op = COMPARISON_OPERATORS[m.group('op')]
actual_value = dct.get(m.group('key'))
if (m.group('strval') is not None or
# If the original field is a string and matching comparisonvalue is
# a number we should respect the origin of ... | def _match_one(filter_part, dct):
if m:
op = COMPARISON_OPERATORS[m.group('op')]
actual_value = dct.get(m.group('key'))
if (m.group('quotedstrval') is not None or
m.group('strval') is not None or
# If the original field is a string and matching comparisonvalue is
... |
def _match_one(filter_part, dct):
if m.group('op') not in ('=', '!='):
raise ValueError(
'Operator %s does not support string values!' % m.group('op'))
comparison_value = m.group('strval') or m.group('intval')
else:
try:
com... | def _match_one(filter_part, dct):
if m.group('op') not in ('=', '!='):
raise ValueError(
'Operator %s does not support string values!' % m.group('op'))
comparison_value = m.group('quotedstrval') or m.group('strval') or m.group('intval')
quote = m.g... |
class Categorical(ExtensionArray, PandasObject):
code_values = code_values[null_mask | (code_values >= 0)]
return algorithms.isin(self.codes, code_values)
# The Series.cat accessor
| class Categorical(ExtensionArray, PandasObject):
code_values = code_values[null_mask | (code_values >= 0)]
return algorithms.isin(self.codes, code_values)
def replace(self, to_replace, value, inplace: bool = False):
"""
Replaces all instances of one value with another
Param... |
class CategoricalBlock(ExtensionBlock):
)
return result
# -----------------------------------------------------------------
# Constructor Helpers | class CategoricalBlock(ExtensionBlock):
)
return result
def replace(
self,
to_replace,
value,
inplace: bool = False,
filter=None,
regex: bool = False,
convert: bool = True,
):
inplace = validate_bool_kwarg(inplace, "inplace")
... |
def test_isin_cats():
tm.assert_numpy_array_equal(expected, result)
@pytest.mark.parametrize("empty", [[], pd.Series(), np.array([])])
def test_isin_empty(empty):
s = pd.Categorical(["a", "b"]) | def test_isin_cats():
tm.assert_numpy_array_equal(expected, result)
@pytest.mark.parametrize(
"to_replace, value, result",
[("b", "c", ["a", "c"]), ("c", "d", ["a", "b"]), ("b", None, ["a", None])],
)
def test_replace(to_replace, value, result):
# GH 26988
cat = pd.Categorical(["a", "b"])
expe... |
class TestDataFrameReplace:
expected = DataFrame(expected)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"df, to_replace, exp",
[ | class TestDataFrameReplace:
expected = DataFrame(expected)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"replace_dict, final_data",
[({"a": 1, "b": 1}, [[3, 3], [2, 2]]), ({"a": 1, "b": 2}, [[3, 1], [2, 3]])],
)
def test_categorical_replace_with_dict(sel... |
class TestSeriesReplace:
expected = pd.Series(numeric)
tm.assert_series_equal(expected, result, check_dtype=False)
def test_replace_with_no_overflowerror(self):
# GH 25616
# casts to object without Exception from OverflowError | class TestSeriesReplace:
expected = pd.Series(numeric)
tm.assert_series_equal(expected, result, check_dtype=False)
def test_replace_categorical_single(self):
# GH 26988
dti = pd.date_range("2016-01-01", periods=3, tz="US/Pacific")
s = pd.Series(dti)
c = s.astype("cat... |
def test_rules_names_list():
def test_update_settings():
settings = Settings({'key': 'val'})
new_settings = settings.update(key='new-val')
assert new_settings.key == 'new-val'
assert settings.key == 'val' | def test_rules_names_list():
def test_update_settings():
settings = Settings({'key': 'val'})
new_settings = settings.update(key='new-val', unset='unset-value')
assert new_settings.key == 'val'
assert new_settings.unset == 'unset-value'
assert settings.key == 'val' |
from tests.utils import Command
@pytest.mark.parametrize('override, old, new', [
({'key': 'val'}, {}, {'key': 'val'}),
({'key': 'new-val'}, {'key': 'val'}, {'key': 'new-val'})])
def test_wrap_settings(override, old, new):
fn = lambda _, settings: settings
assert wrap_settings(override)(fn)(None, Settin... | from tests.utils import Command
@pytest.mark.parametrize('override, old, new', [
({'key': 'val'}, {}, {'key': 'val'}),
({'key': 'new-val'}, {'key': 'val'}, {'key': 'val'}),
({'key': 'new-val', 'unset': 'unset'}, {'key': 'val'}, {'key': 'val', 'unset': 'unset'})])
def test_wrap_settings(override, old, new):... |
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) |
class DatabaseFeatures(BaseDatabaseFeatures):
supports_over_clause = True
supports_aggregate_filter_clause = True
supported_explain_formats = {'JSON', 'TEXT', 'XML', 'YAML'}
validates_explain_options = False # A query will error on invalid options.
@cached_property
def is_postgresql_9_5(self): | class DatabaseFeatures(BaseDatabaseFeatures):
supports_over_clause = True
supports_aggregate_filter_clause = True
supported_explain_formats = {'JSON', 'TEXT', 'XML', 'YAML'}
@cached_property
def is_postgresql_9_5(self): |
from django.db.backends.base.operations import BaseDatabaseOperations
class DatabaseOperations(BaseDatabaseOperations):
cast_char_field_without_max_length = 'varchar'
explain_prefix = 'EXPLAIN'
cast_data_types = {
'AutoField': 'integer',
'BigAutoField': 'bigint', | from django.db.backends.base.operations import BaseDatabaseOperations
class DatabaseOperations(BaseDatabaseOperations):
cast_char_field_without_max_length = 'varchar'
explain_prefix = 'EXPLAIN'
explain_options = frozenset(
[
"ANALYZE",
"BUFFERS",
"COSTS",
... |
class DatabaseOperations(BaseDatabaseOperations):
return start_, end_
def explain_query_prefix(self, format=None, **options):
prefix = super().explain_query_prefix(format)
extra = {}
if format:
extra['FORMAT'] = format
if options:
extra.update({
... | class DatabaseOperations(BaseDatabaseOperations):
return start_, end_
def explain_query_prefix(self, format=None, **options):
extra = {}
# Normalize options.
if options:
options = {
name.upper(): 'true' if value else 'false'
for name, valu... |
__all__ = ['Query', 'RawQuery']
# SQL comments are forbidden in column aliases.
FORBIDDEN_ALIAS_PATTERN = re.compile(r"['`\"\]\[;\s]|--|/\*|\*/")
def get_field_names_from_opts(opts):
return set(chain.from_iterable( | __all__ = ['Query', 'RawQuery']
# SQL comments are forbidden in column aliases.
FORBIDDEN_ALIAS_PATTERN = re.compile(r"['`\"\]\[;\s]|--|/\*|\*/")
# Inspired from
# https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
EXPLAIN_OPTIONS_PATTERN = re.compile(r"[\w\-]+")
def get_field_nam... |
class Query:
def explain(self, using, format=None, **options):
q = self.clone()
q.explain_query = True
q.explain_format = format
q.explain_options = options | class Query:
def explain(self, using, format=None, **options):
q = self.clone()
for option_name in options:
if (
not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name) or
"--" in option_name
):
raise ValueError("Invalid option name... |
class ExplainTests(TestCase):
@skipUnlessDBFeature('validates_explain_options')
def test_unknown_options(self):
with self.assertRaisesMessage(ValueError, 'Unknown options: test, test2'):
Tag.objects.all().explain(test=1, test2=1)
def test_unknown_format(self):
msg = 'DOES NOT E... | class ExplainTests(TestCase):
@skipUnlessDBFeature('validates_explain_options')
def test_unknown_options(self):
with self.assertRaisesMessage(ValueError, "Unknown options: TEST, TEST2"):
Tag.objects.all().explain(**{"TEST": 1, "TEST2": 1})
def test_unknown_format(self):
msg = '... |
class ExplainTests(TestCase):
option = '{} {}'.format(name.upper(), 'true' if value else 'false')
self.assertIn(option, captured_queries[0]['sql'])
@unittest.skipUnless(connection.vendor == 'mysql', 'MySQL specific')
def test_mysql_text_to_traditional(self):
# In... | class ExplainTests(TestCase):
option = '{} {}'.format(name.upper(), 'true' if value else 'false')
self.assertIn(option, captured_queries[0]['sql'])
def test_option_sql_injection(self):
qs = Tag.objects.filter(name="test")
options = {"SUMMARY true) SELECT 1; -... |
class AuthenticationForm(forms.Form):
if username is not None and password:
self.user_cache = authenticate(self.request, username=username, password=password)
if self.user_cache is None:
# An authentication backend may reject inactive users. Check
# if the... | class AuthenticationForm(forms.Form):
if username is not None and password:
self.user_cache = authenticate(self.request, username=username, password=password)
if self.user_cache is None:
raise forms.ValidationError(
self.error_messages['invalid_login']... |
class UserCreationFormTest(TestDataMixin, TestCase):
)
class AuthenticationFormTest(TestDataMixin, TestCase):
def test_invalid_username(self): | class UserCreationFormTest(TestDataMixin, TestCase):
)
# To verify that the login form rejects inactive users, use an authentication
# backend that allows them.
@override_settings(AUTHENTICATION_BACKENDS=['django.contrib.auth.backends.AllowAllUsersModelBackend'])
class AuthenticationFormTest(TestDataMixin, Te... |
class AuthenticationFormTest(TestDataMixin, TestCase):
self.assertFalse(form.is_valid())
self.assertEqual(form.non_field_errors(), [force_text(form.error_messages['inactive'])])
def test_login_failed(self):
signal_calls = []
| class AuthenticationFormTest(TestDataMixin, TestCase):
self.assertFalse(form.is_valid())
self.assertEqual(form.non_field_errors(), [force_text(form.error_messages['inactive'])])
# Use an authentication backend that rejects inactive users.
@override_settings(AUTHENTICATION_BACKENDS=['django.cont... |
class Task(object):
params_str = {}
params = dict(self.get_params())
for param_name, param_value in six.iteritems(self.param_kwargs):
if params[param_name].significant:
params_str[param_name] = params[param_name].serialize(param_value)
return params_str
| class Task(object):
params_str = {}
params = dict(self.get_params())
for param_name, param_value in six.iteritems(self.param_kwargs):
params_str[param_name] = params[param_name].serialize(param_value)
return params_str
|
class DummyTask(luigi.Task):
datehour_param = luigi.DateHourParameter()
timedelta_param = luigi.TimeDeltaParameter()
list_param = luigi.Parameter(is_list=True)
class TaskTest(unittest.TestCase): | class DummyTask(luigi.Task):
datehour_param = luigi.DateHourParameter()
timedelta_param = luigi.TimeDeltaParameter()
list_param = luigi.Parameter(is_list=True)
insignificant_param = luigi.Parameter(significant=False)
class TaskTest(unittest.TestCase): |
class TaskTest(unittest.TestCase):
date_param=datetime(2014, 9, 13).date(),
datehour_param=datetime(2014, 9, 13, 9),
timedelta_param=timedelta(44), # doesn't support seconds
list_param=['in', 'flames'])
original = DummyTask(**params)
other = DummyTask.fr... | class TaskTest(unittest.TestCase):
date_param=datetime(2014, 9, 13).date(),
datehour_param=datetime(2014, 9, 13, 9),
timedelta_param=timedelta(44), # doesn't support seconds
list_param=['in', 'flames'],
insignificant_param='test')
original = DummyTas... |
__all__ = [
def get_objs_combined_axis(
objs, intersect: bool = False, axis=0, sort: bool = True
) -> Index:
"""
Extract combined index: return intersection or union (depending on the | __all__ = [
def get_objs_combined_axis(
objs, intersect: bool = False, axis=0, sort: bool = True, copy: bool = False
) -> Index:
"""
Extract combined index: return intersection or union (depending on the |
def get_objs_combined_axis(
The axis to extract indexes from.
sort : bool, default True
Whether the result index should come out sorted or not.
Returns
-------
Index
"""
obs_idxes = [obj._get_axis(axis) for obj in objs]
return _get_combined_index(obs_idxes, intersect=interse... | def get_objs_combined_axis(
The axis to extract indexes from.
sort : bool, default True
Whether the result index should come out sorted or not.
copy : bool, default False
If True, return a copy of the combined index.
Returns
-------
Index
"""
obs_idxes = [obj._get_ax... |
def _get_distinct_objs(objs: List[Index]) -> List[Index]:
def _get_combined_index(
indexes: List[Index], intersect: bool = False, sort: bool = False
) -> Index:
"""
Return the union or intersection of indexes. | def _get_distinct_objs(objs: List[Index]) -> List[Index]:
def _get_combined_index(
indexes: List[Index],
intersect: bool = False,
sort: bool = False,
copy: bool = False,
) -> Index:
"""
Return the union or intersection of indexes. |
def _get_combined_index(
calculate the union.
sort : bool, default False
Whether the result index should come out sorted or not.
Returns
------- | def _get_combined_index(
calculate the union.
sort : bool, default False
Whether the result index should come out sorted or not.
copy : bool, default False
If True, return a copy of the combined index.
Returns
------- |
def _get_combined_index(
index = index.sort_values()
except TypeError:
pass
return index
| def _get_combined_index(
index = index.sort_values()
except TypeError:
pass
# GH 29879
if copy:
index = index.copy()
return index
|
class _Concatenator:
def _get_comb_axis(self, i: int) -> Index:
data_axis = self.objs[0]._get_block_manager_axis(i)
return get_objs_combined_axis(
self.objs, axis=data_axis, intersect=self.intersect, sort=self.sort
)
def _get_concat_axis(self) -> Index: | class _Concatenator:
def _get_comb_axis(self, i: int) -> Index:
data_axis = self.objs[0]._get_block_manager_axis(i)
return get_objs_combined_axis(
self.objs,
axis=data_axis,
intersect=self.intersect,
sort=self.sort,
copy=self.copy,
... |
def test_concat_sparse():
)
result = pd.concat([a, a], axis=1)
tm.assert_frame_equal(result, expected) | def test_concat_sparse():
)
result = pd.concat([a, a], axis=1)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("test_series", [True, False])
def test_concat_copy_index(test_series, axis):
# GH 29879
if test_series:
ser = Series([1, 2])
comb = concat([ser, ser], axi... |
def decode_raw(input_bytes,
name=None):
r"""Convert raw bytes from input tensor into numeric tensors.
The input tensor is interpreted as a sequence of bytes. These bytes are then
decoded as numbers in the format specified by `out_type`.
>>> tf.io.decode_raw(tf.constant("1"), tf.uint8)
<tf.Ten... | def decode_raw(input_bytes,
name=None):
r"""Convert raw bytes from input tensor into numeric tensors.
Every component of the input tensor is interpreted as a sequence of bytes.
These bytes are then decoded as numbers in the format specified by `out_type`.
>>> tf.io.decode_raw(tf.constant("1"), ... |
def decode_raw(input_bytes,
>>> tf.io.decode_raw(tf.constant(["1212"]), tf.uint16, fixed_length=4)
<tf.Tensor: shape=(1, 2), dtype=uint16, numpy=array([[12849, 12849]], ...
Note: There is currently a bug in `fixed_length` that can result in data loss:
>>> # truncated to length of type as it matches fixed_leng... | def decode_raw(input_bytes,
>>> tf.io.decode_raw(tf.constant(["1212"]), tf.uint16, fixed_length=4)
<tf.Tensor: shape=(1, 2), dtype=uint16, numpy=array([[12849, 12849]], ...
If the input value is larger than `fixed_length`, it is truncated:
>>> x=''.join([chr(1), chr(2), chr(3), chr(4)])
>>> tf.io.decode_raw... |
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 ... |
def test_apply_series_return_dataframe_groups():
["17661101"], index=pd.DatetimeIndex(["2015-02-24"], name="day"), name="userId"
)
tm.assert_series_equal(result, expected) | def test_apply_series_return_dataframe_groups():
["17661101"], index=pd.DatetimeIndex(["2015-02-24"], name="day"), name="userId"
)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("category", [False, True])
def test_apply_multi_level_name(category):
# https://github.com/pandas-dev... |
class _AxesBase(martist.Artist):
return
dL = self.dataLim
x0, x1 = map(x_trf.inverted().transform, dL.intervalx)
y0, y1 = map(y_trf.inverted().transform, dL.intervaly)
xr = 1.05 * (x1 - x0)
yr = 1.05 * (y1 - y0)
| class _AxesBase(martist.Artist):
return
dL = self.dataLim
x0, x1 = map(x_trf.transform, dL.intervalx)
y0, y1 = map(y_trf.transform, dL.intervaly)
xr = 1.05 * (x1 - x0)
yr = 1.05 * (y1 - y0)
|
def test_aspect_nonlinear_adjustable_datalim():
ax = fig.add_axes([.1, .1, .8, .8]) # Square.
ax.plot([.4, .6], [.4, .6]) # Set minpos to keep logit happy.
ax.set(xscale="log", xlim=(1, 10),
yscale="logit", ylim=(1/11, 1/1001),
aspect=1, adjustable="datalim")
ax.margins(0)
a... | def test_aspect_nonlinear_adjustable_datalim():
ax = fig.add_axes([.1, .1, .8, .8]) # Square.
ax.plot([.4, .6], [.4, .6]) # Set minpos to keep logit happy.
ax.set(xscale="log", xlim=(1, 100),
yscale="logit", ylim=(1 / 101, 1 / 11),
aspect=1, adjustable="datalim")
ax.margins(0)
... |
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-... |
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( |
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`.
|
class BlackTestCase(unittest.TestCase):
self.assertIn(one, cache)
self.assertIn(two, cache)
def test_no_cache_when_writeback_diff(self) -> None:
mode = black.FileMode()
with cache_dir() as workspace: | class BlackTestCase(unittest.TestCase):
self.assertIn(one, cache)
self.assertIn(two, cache)
@patch("black.ProcessPoolExecutor", autospec=True)
def test_works_in_mono_process_only_environment(self, mock_executor) -> None:
mock_executor.side_effect = OSError()
mode = black... |
def login():
login_user(form.user, remember=remember_me, authn_via=["password"])
after_this_request(_commit)
if not _security._want_json(request):
return redirect(get_post_login_redirect())
if _security._want_json(request):
if current_user.is_authenticated:
... | def login():
login_user(form.user, remember=remember_me, authn_via=["password"])
after_this_request(_commit)
if _security._want_json(request):
return base_render_json(form, include_auth_token=True)
return redirect(get_post_login_redirect())
if _security._want_json(reque... |
def change_password():
if form.validate_on_submit():
after_this_request(_commit)
change_user_password(current_user._get_current_object(), form.new_password.data)
if not _security._want_json(request):
do_flash(*get_message("PASSWORD_CHANGE"))
return redirect(
... | def change_password():
if form.validate_on_submit():
after_this_request(_commit)
change_user_password(current_user._get_current_object(), form.new_password.data)
if _security._want_json(request):
form.user = current_user
return base_render_json(form, include_auth_toke... |
def test_session_query(in_app_context):
assert response.status_code == 200
end_nqueries = get_num_queries(app.security.datastore)
assert current_nqueries is None or end_nqueries == (current_nqueries + 2) | def test_session_query(in_app_context):
assert response.status_code == 200
end_nqueries = get_num_queries(app.security.datastore)
assert current_nqueries is None or end_nqueries == (current_nqueries + 2)
@pytest.mark.changeable()
def test_no_get_auth_token(app, client):
# Test that GETs don't return a... |
if __name__ == "__main__":
if os.path.exists('/tmp/bar'):
shutil.rmtree('/tmp/bar')
luigi.run(['--task', 'examples.Foo', '--workers', '2', '--local-scheduler']) | if __name__ == "__main__":
if os.path.exists('/tmp/bar'):
shutil.rmtree('/tmp/bar')
luigi.run(['examples.Foo', '--workers', '2', '--local-scheduler']) |
def run(cmdline_args=None, main_task_cls=None,
:param use_dynamic_argparse:
:param local_scheduler:
"""
if use_dynamic_argparse:
interface = DynamicArgParseInterface()
else: | def run(cmdline_args=None, main_task_cls=None,
:param use_dynamic_argparse:
:param local_scheduler:
"""
if cmdline_args is None:
cmdline_args = sys.argv[1:]
if use_dynamic_argparse:
interface = DynamicArgParseInterface()
else: |
from helpers import unittest
import luigi
import luigi.date_interval
import luigi.notifications
from luigi.interface import core, Interface, WorkerSchedulerFactory
from luigi.worker import Worker
from mock import Mock
luigi.notifications.DEBUG = True
class InterfaceTest(unittest.TestCase):
def setUp(self):
... | from helpers import unittest
import luigi
import luigi.date_interval
import luigi.notifications
import sys
from luigi.interface import core, Interface, WorkerSchedulerFactory
from luigi.worker import Worker
from mock import Mock, patch
from helpers import LuigiTestCase
luigi.notifications.DEBUG = True
class Interfac... |
class InterfaceTest(unittest.TestCase):
self.worker_scheduler_factory = WorkerSchedulerFactory()
self.worker_scheduler_factory.create_worker = Mock(return_value=self.worker)
self.worker_scheduler_factory.create_local_scheduler = Mock()
class NoOpTask(luigi.Task):
param = lui... | class InterfaceTest(unittest.TestCase):
self.worker_scheduler_factory = WorkerSchedulerFactory()
self.worker_scheduler_factory.create_worker = Mock(return_value=self.worker)
self.worker_scheduler_factory.create_local_scheduler = Mock()
super(InterfaceTest, self).setUp()
class No... |
class InterfaceTest(unittest.TestCase):
self.assertFalse(self._run_interface())
def _run_interface(self):
return Interface.run([self.task_a, self.task_b], self.worker_scheduler_factory, {'no_lock': True})
| class InterfaceTest(unittest.TestCase):
self.assertFalse(self._run_interface())
def test_just_run_main_task_cls(self):
class MyTestTask(luigi.Task):
pass
class MyOtherTestTask(luigi.Task):
my_param = luigi.Parameter()
with patch.object(sys, 'argv', ['my_mo... |
class Selector(_ParselSelector, object_ref):
selectorlist_cls = SelectorList
def __init__(self, response=None, text=None, type=None, root=None, _root=None, **kwargs):
st = _st(response, type or self._default_type)
if _root is not None: | class Selector(_ParselSelector, object_ref):
selectorlist_cls = SelectorList
def __init__(self, response=None, text=None, type=None, root=None, _root=None, **kwargs):
if not(response is None or text is None):
raise ValueError('%s.__init__() received both response and text'
... |
class SelectorTestCase(unittest.TestCase):
sel.xpath('//p').extract_unquoted()
self.assertSubstring('Use .extract() instead', str(w[-1].message))
class DeprecatedXpathSelectorTest(unittest.TestCase):
| class SelectorTestCase(unittest.TestCase):
sel.xpath('//p').extract_unquoted()
self.assertSubstring('Use .extract() instead', str(w[-1].message))
def test_selector_bad_args(self):
with self.assertRaisesRegexp(ValueError, 'received both response and text'):
Selector(TextR... |
class SimpleTaskState(object):
self.re_enable(task)
# don't allow workers to override a scheduler disable
elif task.scheduler_disable_time is not None:
return
if new_status == FAILED and task.can_disable() and task.status != DISABLED: | class SimpleTaskState(object):
self.re_enable(task)
# don't allow workers to override a scheduler disable
elif task.scheduler_disable_time is not None and new_status != DISABLED:
return
if new_status == FAILED and task.can_disable() and task.status != DI... |
class CentralPlannerTest(unittest.TestCase):
self.setTime(101)
self.assertEqual(FAILED, self.sch.task_list('', '')['A']['status'])
def test_disable_by_worker(self):
self.sch.add_task(worker=WORKER, task_id='A', status=DISABLED)
self.assertEqual(len(self.sch.task_list('DISABLED', '')... | class CentralPlannerTest(unittest.TestCase):
self.setTime(101)
self.assertEqual(FAILED, self.sch.task_list('', '')['A']['status'])
def test_no_automatic_re_enable_after_manual_disable(self):
self.sch = CentralPlannerScheduler(disable_persist=100)
self.setTime(0)
self.sch.add... |
and Index.__new__.
These should not depend on core.internals.
"""
from typing import TYPE_CHECKING, Any, Optional, Sequence, Union, cast
import numpy as np | and Index.__new__.
These should not depend on core.internals.
"""
from collections import abc
from typing import TYPE_CHECKING, Any, Optional, Sequence, Union, cast
import numpy as np |
def sanitize_array(
# GH#16804
arr = np.arange(data.start, data.stop, data.step, dtype="int64")
subarr = _try_cast(arr, dtype, copy, raise_cast_failure)
else:
subarr = _try_cast(data, dtype, copy, raise_cast_failure)
| def sanitize_array(
# GH#16804
arr = np.arange(data.start, data.stop, data.step, dtype="int64")
subarr = _try_cast(arr, dtype, copy, raise_cast_failure)
elif isinstance(data, abc.Set):
raise TypeError("Set type is unordered")
else:
subarr = _try_cast(data, dtype, copy, ra... |
class TestDataFrameConstructorWithDatetimeTZ:
expected = DataFrame(array_dim2).astype("datetime64[ns, UTC]")
tm.assert_frame_equal(df, expected) | class TestDataFrameConstructorWithDatetimeTZ:
expected = DataFrame(array_dim2).astype("datetime64[ns, UTC]")
tm.assert_frame_equal(df, expected)
def test_construction_from_set_raises(self):
# https://github.com/pandas-dev/pandas/issues/32582
msg = "Set type is unordered"
wi... |
def test_startup_interactivehook_isolated_explicit(self):
@unittest.skipUnless(sys.platform == 'win32', "only supported on Windows")
class _pthFileTests(unittest.TestCase):
def _create_underpth_exe(self, lines):
temp_dir = tempfile.mkdtemp()
self.addCleanup(test.support.rmtree, temp_dir)
ex... | def test_startup_interactivehook_isolated_explicit(self):
@unittest.skipUnless(sys.platform == 'win32', "only supported on Windows")
class _pthFileTests(unittest.TestCase):
def _create_underpth_exe(self, lines, exe_pth=True):
import _winapi
temp_dir = tempfile.mkdtemp()
self.addCleanup(test... |
def test_underpth_file(self):
self.assertTrue(rc, "sys.path is incorrect")
if __name__ == "__main__":
unittest.main() | def test_underpth_file(self):
self.assertTrue(rc, "sys.path is incorrect")
def test_underpth_dll_file(self):
libpath = os.path.dirname(os.path.dirname(encodings.__file__))
exe_prefix = os.path.dirname(sys.executable)
exe_file = self._create_underpth_exe([
'fake-path-nam... |
def _make_ghost_gridspec_slots(fig, gs):
# this gridspec slot doesn't have an axis so we
# make a "ghost".
ax = fig.add_subplot(gs[nn])
ax.set_frame_on(False)
ax.set_xticks([])
ax.set_yticks([])
ax.set_facecolor((1, 0, 0, 0))
def _mak... | def _make_ghost_gridspec_slots(fig, gs):
# this gridspec slot doesn't have an axis so we
# make a "ghost".
ax = fig.add_subplot(gs[nn])
ax.set_visible(False)
def _make_layout_margins(ax, renderer, h_pad, w_pad): |
class FigureCanvasBase:
def inaxes(self, xy):
"""
Check if a point is in an axes.
Parameters
---------- | class FigureCanvasBase:
def inaxes(self, xy):
"""
Return the topmost visible `~.axes.Axes` containing the point *xy*.
Parameters
---------- |
class FigureCanvasBase:
Returns
-------
axes: topmost axes containing the point, or None if no axes.
"""
axes_list = [a for a in self.figure.get_axes()
if a.patch.contains_point(xy)]
if axes_list:
axes = cbook._topmost_artist(axes_list)... | class FigureCanvasBase:
Returns
-------
axes : `~matplotlib.axes.Axes` or None
The topmost visible axes containing the point, or None if no axes.
"""
axes_list = [a for a in self.figure.get_axes()
if a.patch.contains_point(xy) and a.get_visible()... |
def test_aspect_nonlinear_adjustable_datalim():
ax.apply_aspect()
assert ax.get_xlim() == pytest.approx([1*10**(1/2), 100/10**(1/2)])
assert ax.get_ylim() == (1 / 101, 1 / 11) | def test_aspect_nonlinear_adjustable_datalim():
ax.apply_aspect()
assert ax.get_xlim() == pytest.approx([1*10**(1/2), 100/10**(1/2)])
assert ax.get_ylim() == (1 / 101, 1 / 11)
def test_invisible_axes():
# invisible axes should not respond to events...
fig, ax = plt.subplots()
assert fig.canvas... |
from vyper.builtin_interfaces import ERC20, ERC721
from vyper.cli.utils import extract_file_interface_imports
from vyper.compiler import compile_code, compile_codes
from vyper.exceptions import InterfaceViolation, StructureException
def test_basic_extract_interface(): | from vyper.builtin_interfaces import ERC20, ERC721
from vyper.cli.utils import extract_file_interface_imports
from vyper.compiler import compile_code, compile_codes
from vyper.exceptions import ArgumentException, InterfaceViolation, StructureException
def test_basic_extract_interface(): |
def test():
assert erc20.balanceOf(sender) == 1000
def test_units_interface(w3, get_contract):
code = """
import balanceof as BalanceOf | def test():
assert erc20.balanceOf(sender) == 1000
# test data returned from external interface gets clamped
@pytest.mark.parametrize("typ", ("int128", "uint8"))
def test_external_interface_int_clampers(get_contract, assert_tx_failed, typ):
external_contract = f"""
@external
def ok() -> {typ}:
return 1
@... |
def _dynarray_make_setter(dst, src):
# for ABI-encoded dynamic data, we must loop to unpack, since
# the layout does not match our memory layout
should_loop = (
src.encoding in (Encoding.ABI, Encoding.JSON_ABI)
and src.typ.subtype.abi_type.is_dynamic()
)
... | def _dynarray_make_setter(dst, src):
# for ABI-encoded dynamic data, we must loop to unpack, since
# the layout does not match our memory layout
should_loop = src.encoding == Encoding.ABI and src.typ.subtype.abi_type.is_dynamic()
# if the subtype is dynamic, there might be a lot of
... |
def _get_element_ptr_tuplelike(parent, key):
ofst = 0 # offset from parent start
if parent.encoding in (Encoding.ABI, Encoding.JSON_ABI):
if parent.location == STORAGE:
raise CompilerPanic("storage variables should not be abi encoded") # pragma: notest
| def _get_element_ptr_tuplelike(parent, key):
ofst = 0 # offset from parent start
if parent.encoding == Encoding.ABI:
if parent.location == STORAGE:
raise CompilerPanic("storage variables should not be abi encoded") # pragma: notest
|
def _get_element_ptr_array(parent, key, array_bounds_check):
# NOTE: there are optimization rules for this when ix or bound is literal
ix = IRnode.from_list([clamp_op, ix, bound], typ=ix.typ)
if parent.encoding in (Encoding.ABI, Encoding.JSON_ABI):
if parent.location == STORAGE:
... | def _get_element_ptr_array(parent, key, array_bounds_check):
# NOTE: there are optimization rules for this when ix or bound is literal
ix = IRnode.from_list([clamp_op, ix, bound], typ=ix.typ)
if parent.encoding == Encoding.ABI:
if parent.location == STORAGE:
raise CompilerPanic(... |
def _freshname(name):
# returns True if t is ABI encoded and is a type that needs any kind of
# validation
def needs_clamp(t, encoding):
if encoding not in (Encoding.ABI, Encoding.JSON_ABI):
return False
if isinstance(t, (ByteArrayLike, DArrayType)):
if encoding == Encoding.JSON_ABI:
... | def _freshname(name):
# returns True if t is ABI encoded and is a type that needs any kind of
# validation
def needs_clamp(t, encoding):
if encoding == Encoding.VYPER:
return False
if encoding != Encoding.ABI:
raise CompilerPanic("unreachable") # pragma: notest
if isinstance(t, (ByteArrayLi... |
check_assign,
check_external_call,
dummy_node_for_type,
get_element_ptr,
)
from vyper.codegen.ir_node import Encoding, IRnode
from vyper.codegen.types import InterfaceType, TupleType, get_type_for_exact_size
from vyper.exceptions import StateAccessViolation, TypeCheckFailure
| check_assign,
check_external_call,
dummy_node_for_type,
make_setter,
needs_clamp,
)
from vyper.codegen.ir_node import Encoding, IRnode
from vyper.codegen.types import InterfaceType, TupleType, get_type_for_exact_size
from vyper.codegen.types.convert import new_type_to_old_type
from vyper.exceptions ... |
def _pack_arguments(contract_sig, args, context):
return buf, mstore_method_id + [encode_args], args_ofst, args_len
def _returndata_encoding(contract_sig):
if contract_sig.is_from_json:
return Encoding.JSON_ABI
return Encoding.ABI
def _unpack_returndata(buf, contract_sig, skip_contract_check, co... | def _pack_arguments(contract_sig, args, context):
return buf, mstore_method_id + [encode_args], args_ofst, args_len
def _unpack_returndata(buf, contract_sig, skip_contract_check, context, expr):
# expr.func._metadata["type"].return_type is more accurate
# than contract_sig.return_type in the case of JSON ... |
def _unpack_returndata(buf, contract_sig, skip_contract_check, context):
# revert when returndatasize is not in bounds
ret = []
# runtime: min_return_size <= returndatasize
# TODO move the -1 optimization to IR optimizer
if not skip_contract_check:
ret += [["assert", ["gt", "returndatasize",... | def _unpack_returndata(buf, contract_sig, skip_contract_check, context):
# revert when returndatasize is not in bounds
ret = []
# runtime: min_return_size <= returndatasize
if not skip_contract_check:
ret += [["assert", ["ge", "returndatasize", min_return_size]]]
encoding = Encoding.ABI
... |
def _external_call_helper(
buf, arg_packer, args_ofst, args_len = _pack_arguments(contract_sig, args_ir, context)
ret_unpacker, ret_ofst, ret_len = _unpack_returndata(
buf, contract_sig, skip_contract_check, context
)
sub += arg_packer | def _external_call_helper(
buf, arg_packer, args_ofst, args_len = _pack_arguments(contract_sig, args_ir, context)
ret_unpacker, ret_ofst, ret_len = _unpack_returndata(
buf, contract_sig, skip_contract_check, context, expr
)
sub += arg_packer |
def _external_call_helper(
if contract_sig.return_type is not None:
sub += ret_unpacker
ret = IRnode.from_list(
sub,
typ=contract_sig.return_type,
location=MEMORY,
# set the encoding to ABI here, downstream code will decode and add clampers.
encoding=_returndata_... | def _external_call_helper(
if contract_sig.return_type is not None:
sub += ret_unpacker
return IRnode.from_list(sub, typ=contract_sig.return_type, location=MEMORY)
def _get_special_kwargs(stmt_expr, context): |
import vyper.utils as util
from vyper.address_space import CALLDATA, DATA, MEMORY
from vyper.ast.signatures.function_signature import FunctionSignature, VariableRecord
from vyper.codegen.context import Context
from vyper.codegen.core import get_element_ptr, getpos, make_setter
from vyper.codegen.expr import Expr
from v... | import vyper.utils as util
from vyper.address_space import CALLDATA, DATA, MEMORY
from vyper.ast.signatures.function_signature import FunctionSignature, VariableRecord
from vyper.codegen.abi_encoder import abi_encoding_matches_vyper
from vyper.codegen.context import Context
from vyper.codegen.core import get_element_pt... |
def _register_function_args(context: Context, sig: FunctionSignature) -> List[IR
arg_ir = get_element_ptr(base_args_ofst, i)
if _should_decode(arg.typ):
# allocate a memory slot for it and copy
p = context.new_variable(arg.name, arg.typ, is_mutable=False)
dst = IRno... | def _register_function_args(context: Context, sig: FunctionSignature) -> List[IR
arg_ir = get_element_ptr(base_args_ofst, i)
if needs_clamp(arg.typ, Encoding.ABI):
# allocate a memory slot for it and copy
p = context.new_variable(arg.name, arg.typ, is_mutable=False)
... |
def _register_function_args(context: Context, sig: FunctionSignature) -> List[IR
copy_arg.source_pos = getpos(arg.ast_source)
ret.append(copy_arg)
else:
# leave it in place
context.vars[arg.name] = VariableRecord(
name=arg.name, | def _register_function_args(context: Context, sig: FunctionSignature) -> List[IR
copy_arg.source_pos = getpos(arg.ast_source)
ret.append(copy_arg)
else:
assert abi_encoding_matches_vyper(arg.typ)
# leave it in place
context.vars[arg.name] = VariableRec... |
class Encoding(Enum):
VYPER = auto()
# abi encoded, default for args/return values from external funcs
ABI = auto()
# abi encoded, same as ABI but no clamps for bytestrings
JSON_ABI = auto()
# future: packed
| class Encoding(Enum):
VYPER = auto()
# abi encoded, default for args/return values from external funcs
ABI = auto()
# future: packed
|
def new_type_to_old_type(typ: new.BasePrimitive) -> old.NodeType:
if isinstance(typ, new.DynamicArrayDefinition):
return old.DArrayType(new_type_to_old_type(typ.value_type), typ.length)
if isinstance(typ, new.TupleDefinition):
return old.TupleType(typ.value_type)
if isinstance(typ, new.Struc... | def new_type_to_old_type(typ: new.BasePrimitive) -> old.NodeType:
if isinstance(typ, new.DynamicArrayDefinition):
return old.DArrayType(new_type_to_old_type(typ.value_type), typ.length)
if isinstance(typ, new.TupleDefinition):
return old.TupleType([new_type_to_old_type(t) for t in typ.value_type... |
def test_version_exposed(self):
"version number does not match",
)
if __name__ == "__main__":
unittest.main() | def test_version_exposed(self):
"version number does not match",
)
def test_invalid_typecode(self):
s = b";\x2f\x7f"
with self.assertRaises(ValueError):
rencode.loads(s)
if __name__ == "__main__":
unittest.main() |
class SeriesGroupBy(GroupBy):
res, out = np.zeros(len(ri), dtype=out.dtype), res
res[ids[idx]] = out
return Series(res, index=ri, name=self._selection_name)
@Appender(Series.describe.__doc__)
def describe(self, **kwargs): | class SeriesGroupBy(GroupBy):
res, out = np.zeros(len(ri), dtype=out.dtype), res
res[ids[idx]] = out
result = Series(res, index=ri, name=self._selection_name)
return self._reindex_output(result, fill_value=0)
@Appender(Series.describe.__doc__)
def describe(self, **kwarg... |
class SeriesGroupBy(GroupBy):
minlength = ngroups or 0
out = np.bincount(ids[mask], minlength=minlength)
return Series(
out,
index=self.grouper.result_index,
name=self._selection_name,
dtype="int64",
)
def _apply_to_column_groupbys(se... | class SeriesGroupBy(GroupBy):
minlength = ngroups or 0
out = np.bincount(ids[mask], minlength=minlength)
result = Series(
out,
index=self.grouper.result_index,
name=self._selection_name,
dtype="int64",
)
return self._reindex_output... |
from pandas.core.dtypes.common import (
)
from pandas.core.dtypes.missing import isna, notna
from pandas.core import nanops
import pandas.core.algorithms as algorithms
from pandas.core.arrays import Categorical, try_cast_to_ea | from pandas.core.dtypes.common import (
)
from pandas.core.dtypes.missing import isna, notna
from pandas._typing import FrameOrSeries, Scalar
from pandas.core import nanops
import pandas.core.algorithms as algorithms
from pandas.core.arrays import Categorical, try_cast_to_ea |
class GroupBy(_GroupBy):
if isinstance(self.obj, Series):
result.name = self.obj.name
return result
@classmethod
def _add_numeric_operations(cls): | class GroupBy(_GroupBy):
if isinstance(self.obj, Series):
result.name = self.obj.name
return self._reindex_output(result, fill_value=0)
@classmethod
def _add_numeric_operations(cls): |
class GroupBy(_GroupBy):
if not self.observed and isinstance(result_index, CategoricalIndex):
out = out.reindex(result_index)
return out.sort_index() if self.sort else out
# dropna is truthy | class GroupBy(_GroupBy):
if not self.observed and isinstance(result_index, CategoricalIndex):
out = out.reindex(result_index)
out = self._reindex_output(out)
return out.sort_index() if self.sort else out
# dropna is truthy |
class GroupBy(_GroupBy):
mask = self._cumcount_array(ascending=False) < n
return self._selected_obj[mask]
def _reindex_output(self, output):
"""
If we have categorical groupers, then we might want to make sure that
we have a fully re-indexed output to the levels. This means ... | class GroupBy(_GroupBy):
mask = self._cumcount_array(ascending=False) < n
return self._selected_obj[mask]
def _reindex_output(
self, output: FrameOrSeries, fill_value: Scalar = np.NaN
) -> FrameOrSeries:
"""
If we have categorical groupers, then we might want to make sur... |
class GroupBy(_GroupBy):
Parameters
----------
output: Series or DataFrame
Object resulting from grouping and applying an operation.
Returns
------- | class GroupBy(_GroupBy):
Parameters
----------
output : Series or DataFrame
Object resulting from grouping and applying an operation.
fill_value : scalar, default np.NaN
Value to use for unobserved categories if self.observed is False.
Returns
--... |
class GroupBy(_GroupBy):
).sortlevel()
if self.as_index:
d = {self.obj._get_axis_name(self.axis): index, "copy": False}
return output.reindex(**d)
# GH 13204 | class GroupBy(_GroupBy):
).sortlevel()
if self.as_index:
d = {
self.obj._get_axis_name(self.axis): index,
"copy": False,
"fill_value": fill_value,
}
return output.reindex(**d)
# GH 13204 |
class GroupBy(_GroupBy):
output = output.drop(labels=list(g_names), axis=1)
# Set a temp index and reindex (possibly expanding)
output = output.set_index(self.grouper.result_index).reindex(index, copy=False)
# Reset in-axis grouper columns
# (using level numbers `g_nums` becaus... | class GroupBy(_GroupBy):
output = output.drop(labels=list(g_names), axis=1)
# Set a temp index and reindex (possibly expanding)
output = output.set_index(self.grouper.result_index).reindex(
index, copy=False, fill_value=fill_value
)
# Reset in-axis grouper columns
... |
def test_get_nonexistent_category():
{"var": [rows.iloc[-1]["var"]], "val": [rows.iloc[-1]["vau"]]}
)
) | def test_get_nonexistent_category():
{"var": [rows.iloc[-1]["var"]], "val": [rows.iloc[-1]["vau"]]}
)
)
def test_series_groupby_on_2_categoricals_unobserved(
reduction_func: str, observed: bool
):
# GH 17605
if reduction_func == "ngroup":
pytest.skip("ngroup is... |
from django.utils.encoding import force_bytes, force_str, force_text
from django.utils.functional import allow_lazy
from django.utils.six.moves.urllib.parse import (
quote, quote_plus, unquote, unquote_plus, urlencode as original_urlencode,
urlparse,
)
ETAG_MATCH = re.compile(r'(?:W/)?"((?:\\.|[^"])*)"')
MONT... | from django.utils.encoding import force_bytes, force_str, force_text
from django.utils.functional import allow_lazy
from django.utils.six.moves.urllib.parse import (
quote, quote_plus, unquote, unquote_plus, urlencode as original_urlencode,
)
if six.PY2:
from urlparse import (
ParseResult, SplitResult,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.