buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
class ItemMeta(ABCMeta):
new_attrs['fields'] = fields
new_attrs['_class'] = _class
return super(ItemMeta, mcs).__new__(mcs, class_name, bases, new_attrs)
| class ItemMeta(ABCMeta):
new_attrs['fields'] = fields
new_attrs['_class'] = _class
if classcell is not None:
new_attrs['__classcell__'] = classcell
return super(ItemMeta, mcs).__new__(mcs, class_name, bases, new_attrs)
|
import unittest
from scrapy.item import Item, Field
import six
class ItemTest(unittest.TestCase):
| import sys
import unittest
import six
from scrapy.item import ABCMeta, Item, ItemMeta, Field
from tests import mock
PY36_PLUS = (sys.version_info.major >= 3) and (sys.version_info.minor >= 6)
class ItemTest(unittest.TestCase):
|
class ItemTest(unittest.TestCase):
self.assertNotEqual(item['name'], copied_item['name'])
if __name__ == "__main__":
unittest.main() | class ItemTest(unittest.TestCase):
self.assertNotEqual(item['name'], copied_item['name'])
class ItemMetaTest(unittest.TestCase):
def test_new_method_propagates_classcell(self):
new_mock = mock.Mock(side_effect=ABCMeta.__new__)
base = ItemMeta.__bases__[0]
with mock.patch.object(b... |
class TensorBoard(Callback):
tf.summary.image(mapped_weight_name, w_img)
if hasattr(layer, 'output'):
tf.summary.histogram('{}_out'.format(layer.name),
layer.output)
self.merged = tf.summary.merge_all()
... | class TensorBoard(Callback):
tf.summary.image(mapped_weight_name, w_img)
if hasattr(layer, 'output'):
if isinstance(layer.output, list):
for i, output in enumerate(layer.output):
tf.summary.histogram('{}_out... |
from keras import optimizers
from keras import initializers
from keras import callbacks
from keras.models import Sequential, Model
from keras.layers import Input, Dense, Dropout, add
from keras.layers.convolutional import Conv2D
from keras.layers.pooling import MaxPooling2D, GlobalAveragePooling2D
from keras.utils.test... | from keras import optimizers
from keras import initializers
from keras import callbacks
from keras.models import Sequential, Model
from keras.layers import Input, Dense, Dropout, add, dot, Lambda
from keras.layers.convolutional import Conv2D
from keras.layers.pooling import MaxPooling2D, GlobalAveragePooling1D, GlobalA... |
def test_TensorBoard_multi_input_output(tmpdir):
(X_train, y_train), (X_test, y_test) = get_test_data(
num_train=train_samples,
num_test=test_samples,
input_shape=(input_dim,),
classification=True,
num_classes=num_classes)
y_test = np_utils.to_categorical(y_test) | def test_TensorBoard_multi_input_output(tmpdir):
(X_train, y_train), (X_test, y_test) = get_test_data(
num_train=train_samples,
num_test=test_samples,
input_shape=(input_dim, input_dim),
classification=True,
num_classes=num_classes)
y_test = np_utils.to_categorical(y_test... |
def test_TensorBoard_multi_input_output(tmpdir):
i += 1
i = i % max_batch_index
inp1 = Input((input_dim,))
inp2 = Input((input_dim,))
inp = add([inp1, inp2])
hidden = Dense(num_hidden, activation='relu')(inp)
hidden = Dropout(0.1)(hidden)
output1 = Dense(num_classes, act... | def test_TensorBoard_multi_input_output(tmpdir):
i += 1
i = i % max_batch_index
inp1 = Input((input_dim, input_dim))
inp2 = Input((input_dim, input_dim))
inp_3d = add([inp1, inp2])
inp_2d = GlobalAveragePooling1D()(inp_3d)
inp_pair = Lambda(lambda x: x)([inp_3d, inp_2d]) # ... |
class Rolling(_Rolling_and_Expanding):
def _on(self):
if self.on is None:
return self.obj.index
elif isinstance(self.obj, ABCDataFrame) and self.on in self.obj.columns:
return Index(self.obj[self.on])
else: | class Rolling(_Rolling_and_Expanding):
def _on(self):
if self.on is None:
if self.axis == 0:
return self.obj.index
elif self.axis == 1:
return self.obj.columns
elif isinstance(self.obj, ABCDataFrame) and self.on in self.obj.columns:
... |
class TestRolling(Base):
result = pd.Series(arr).rolling(2).mean()
expected = pd.Series([np.nan, 2, np.nan, np.nan, 4])
tm.assert_series_equal(result, expected) | class TestRolling(Base):
result = pd.Series(arr).rolling(2).mean()
expected = pd.Series([np.nan, 2, np.nan, np.nan, 4])
tm.assert_series_equal(result, expected)
def test_rolling_datetime(self, axis_frame, tz_naive_fixture):
# GH-28192
tz = tz_naive_fixture
df = pd.Da... |
def __virtual__():
return __virtualname__
def _check_cb(cb_):
'''
If the callback is None or is not callable, return a lambda that returns | def __virtual__():
return __virtualname__
def _log_cmd(cmd):
if not isinstance(cmd, list):
return cmd.split()[0].strip()
return cmd[0].strip()
def _check_cb(cb_):
'''
If the callback is None or is not callable, return a lambda that returns |
def _run(cmd,
'Setting value to an empty string', bad_env_key)
env[bad_env_key] = ''
def _get_stripped(cmd):
# Return stripped command string copies to improve logging.
if isinstance(cmd, list):
return [x.strip() if isinstance(x, six.string_types) else x for x ... | def _run(cmd,
'Setting value to an empty string', bad_env_key)
env[bad_env_key] = ''
if output_loglevel is not None:
# Always log the shell commands at INFO unless quiet logging is
# requested. The command output is what will be controlled by the
# 'loglevel' param... |
def _run(cmd,
if output_loglevel != 'quiet':
log.error(
'Failed to decode stdout from command %s, non-decodable '
'characters have been replaced', cmd
)
try: | def _run(cmd,
if output_loglevel != 'quiet':
log.error(
'Failed to decode stdout from command %s, non-decodable '
'characters have been replaced', _log_cmd(cmd)
)
try: |
def _run(cmd,
if output_loglevel != 'quiet':
log.error(
'Failed to decode stderr from command %s, non-decodable '
'characters have been replaced', cmd
)
if rstrip: | def _run(cmd,
if output_loglevel != 'quiet':
log.error(
'Failed to decode stderr from command %s, non-decodable '
'characters have been replaced', _log_cmd(cmd)
)
if rstrip: |
def _run(cmd,
output_loglevel = LOG_LEVELS['error']
msg = (
'Command \'{0}\' failed with return code: {1}'.format(
cmd,
ret['retcode']
)
) | def _run(cmd,
output_loglevel = LOG_LEVELS['error']
msg = (
'Command \'{0}\' failed with return code: {1}'.format(
_log_cmd(cmd),
ret['retcode']
)
) |
def run(cmd,
lvl = LOG_LEVELS['error']
msg = (
'Command \'{0}\' failed with return code: {1}'.format(
cmd,
ret['retcode']
)
) | def run(cmd,
lvl = LOG_LEVELS['error']
msg = (
'Command \'{0}\' failed with return code: {1}'.format(
_log_cmd(cmd),
ret['retcode']
)
) |
class CMDMODTestCase(TestCase, LoaderModuleMockMixin):
cmdmod.run_chroot('/mnt', 'cmd', binds=['/var'])
self.assertEqual(mock_mount.call_count, 4)
self.assertEqual(mock_umount.call_count, 4) | class CMDMODTestCase(TestCase, LoaderModuleMockMixin):
cmdmod.run_chroot('/mnt', 'cmd', binds=['/var'])
self.assertEqual(mock_mount.call_count, 4)
self.assertEqual(mock_umount.call_count, 4)
def test_cve_2021_25284(self):
proc = MagicMock(
return_... |
def test_set_position():
assert a + shift_val == b
def test_get_rotation_string():
assert mpl.text.get_rotation('horizontal') == 0.
assert mpl.text.get_rotation('vertical') == 90. | def test_set_position():
assert a + shift_val == b
@pytest.mark.parametrize('text', ['', 'O'], ids=['empty', 'non-empty'])
def test_non_default_dpi(text):
fig, ax = plt.subplots()
t1 = ax.text(0.5, 0.5, text, ha='left', va='bottom')
fig.canvas.draw()
dpi = fig.dpi
bbox1 = t1.get_window_e... |
class Text(Artist):
#return _unit_box
if not self.get_visible():
return Bbox.unit()
if dpi is not None:
dpi_orig = self.figure.dpi
self.figure.dpi = dpi
if self.get_text() == '':
tx, ty = self._get_xy_display()
return Bbox.from_... | class Text(Artist):
#return _unit_box
if not self.get_visible():
return Bbox.unit()
if dpi is None:
dpi = self.figure.dpi
if self.get_text() == '':
with cbook._setattr_cm(self.figure, dpi=dpi):
tx, ty = self._get_xy_display()
... |
class Text(Artist):
if self._renderer is None:
raise RuntimeError('Cannot get window extent w/o renderer')
bbox, info, descent = self._get_layout(self._renderer)
x, y = self.get_unitless_position()
x, y = self.get_transform().transform((x, y))
bbox = bbox.translated(... | class Text(Artist):
if self._renderer is None:
raise RuntimeError('Cannot get window extent w/o renderer')
with cbook._setattr_cm(self.figure, dpi=dpi):
bbox, info, descent = self._get_layout(self._renderer)
x, y = self.get_unitless_position()
x, y = self... |
from pandas.core.dtypes.generic import ABCMultiIndex
from pandas.core.dtypes.missing import notna
from pandas.core.arrays import Categorical
from pandas.core.frame import DataFrame, _shared_docs
from pandas.core.indexes.base import Index
from pandas.core.reshape.concat import concat | from pandas.core.dtypes.generic import ABCMultiIndex
from pandas.core.dtypes.missing import notna
from pandas.core.arrays import Categorical
import pandas.core.common as com
from pandas.core.frame import DataFrame, _shared_docs
from pandas.core.indexes.base import Index
from pandas.core.reshape.concat import concat |
def melt(
else:
# Check that `id_vars` are in frame
id_vars = list(id_vars)
missing = Index(np.ravel(id_vars)).difference(cols)
if not missing.empty:
raise KeyError(
"The following 'id_vars' are not present" | def melt(
else:
# Check that `id_vars` are in frame
id_vars = list(id_vars)
missing = Index(com.flatten(id_vars)).difference(cols)
if not missing.empty:
raise KeyError(
"The following 'id_vars' are not present" |
def melt(
else:
value_vars = list(value_vars)
# Check that `value_vars` are in frame
missing = Index(np.ravel(value_vars)).difference(cols)
if not missing.empty:
raise KeyError(
"The following 'value_vars' are not present in" | def melt(
else:
value_vars = list(value_vars)
# Check that `value_vars` are in frame
missing = Index(com.flatten(value_vars)).difference(cols)
if not missing.empty:
raise KeyError(
"The following 'value_vars' are not present in" |
class TestMelt:
):
multi.melt(["A"], ["F"], col_level=0)
class TestLreshape:
def test_pairs(self): | class TestMelt:
):
multi.melt(["A"], ["F"], col_level=0)
def test_melt_mixed_int_str_id_vars(self):
# GH 29718
df = DataFrame({0: ["foo"], "a": ["bar"], "b": [1], "d": [2]})
result = melt(df, id_vars=[0, "a"], value_vars=["b", "d"])
expected = DataFrame(
... |
class AsyncClientMixin(object):
low["__user__"] = user
low["__tag__"] = tag
return self.low(fun, low, full_return=False)
def cmd_async(self, low):
""" | class AsyncClientMixin(object):
low["__user__"] = user
low["__tag__"] = tag
try:
return self.cmd_sync(low)
except salt.exceptions.EauthAuthenticationError as exc:
log.error(exc)
def cmd_async(self, low):
""" |
class ClearFuncs(TransportMethods):
"""
Send a master control function back to the wheel system
"""
# All wheel ops pass through eauth
auth_type, err_name, key, sensitive_load_keys = self._prep_auth_info(clear_load)
| class ClearFuncs(TransportMethods):
"""
Send a master control function back to the wheel system
"""
jid = clear_load.get("__jid__", salt.utils.jid.gen_jid(self.opts))
# All wheel ops pass through eauth
auth_type, err_name, key, sensitive_load_keys = self._prep_auth_info(c... |
class ClearFuncs(TransportMethods):
if error:
# Authentication error occurred: do not continue.
return {"error": error}
# Authorize | class ClearFuncs(TransportMethods):
if error:
# Authentication error occurred: do not continue.
data = {"error": error, "jid": jid}
self.event.fire_event(data, tagify([jid, "new"], "wheel"))
return {"error": error}
# Authorize |
class ClearFuncs(TransportMethods):
clear_load.get("kwarg", {}),
)
if not wheel_check:
return {
"error": {
"name": err_name,
"message": 'Authentication failure of type "{0}" occurred for '
... | class ClearFuncs(TransportMethods):
clear_load.get("kwarg", {}),
)
if not wheel_check:
err_data = {
"name": err_name,
"message": 'Authentication failure of type "{0}" occurred for '
"user {1}.".format(aut... |
class ClearFuncs(TransportMethods):
# Authorized. Do the job!
try:
jid = salt.utils.jid.gen_jid(self.opts)
fun = clear_load.pop("fun")
tag = tagify(jid, prefix="wheel")
data = { | class ClearFuncs(TransportMethods):
# Authorized. Do the job!
try:
fun = clear_load.pop("fun")
tag = tagify(jid, prefix="wheel")
data = { |
class WheelClient(
})
{'jid': '20131219224744416681', 'tag': 'salt/wheel/20131219224744416681'}
"""
fun = low.pop("fun")
return self.asynchronous(fun, low)
def cmd( | class WheelClient(
})
{'jid': '20131219224744416681', 'tag': 'salt/wheel/20131219224744416681'}
"""
fun = low.get("fun")
return self.asynchronous(fun, low)
def cmd( |
class NetapiClientTest(TestCase):
def test_wheel_async(self):
# Give this test a little breathing room
time.sleep(3)
low = {"client": "wheel_async", "fun": "key.list_all"}
low.update(self.eauth_creds)
ret = self.netapi.run(low)
self.assertIn("jid", ret)
self.... | class NetapiClientTest(TestCase):
def test_wheel_async(self):
# Give this test a little breathing room
time.sleep(3)
timeout = 60
opts = salt.config.master_config(
os.path.join(RUNTIME_VARS.TMP_CONF_DIR, "master")
)
with salt.utils.event.get_event("master"... |
def strip_tags(value):
value = force_text(value)
while '<' in value and '>' in value:
new_value = _strip_once(value)
if len(new_value) >= len(value):
# _strip_once was not able to detect more tags or length increased
# due to http://bugs.python.org/issue20288
... | def strip_tags(value):
value = force_text(value)
while '<' in value and '>' in value:
new_value = _strip_once(value)
if len(new_value) >= len(value) or value.count('<') == new_value.count('<'):
# _strip_once wasn't able to detect more tags, or line length increased.
# due... |
class TestUtilsHtml(SimpleTestCase):
# caused infinite loop on Pythons not patched with
# http://bugs.python.org/issue20288
('&gotcha&#;<>', '&gotcha&#;<>'),
)
for value, output in items:
self.check_output(f, value, output) | class TestUtilsHtml(SimpleTestCase):
# caused infinite loop on Pythons not patched with
# http://bugs.python.org/issue20288
('&gotcha&#;<>', '&gotcha&#;<>'),
('><!' + ('&' * 16000) + 'D', '><!' + ('&' * 16000) + 'D'),
('X<<<<br>br>br>br>X', 'XX'),
)
... |
class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray)
if is_datetime64_any_dtype(other) and is_timedelta64_dtype(self.dtype):
# ndarray[datetime64] cannot be subtracted from self, so
# we need to wrap in DatetimeArray/Index and flip the operation
if... | class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray)
if is_datetime64_any_dtype(other) and is_timedelta64_dtype(self.dtype):
# ndarray[datetime64] cannot be subtracted from self, so
# we need to wrap in DatetimeArray/Index and flip the operation
if... |
class TestTimedeltaArraylikeAddSubOps:
result = other + idx
tm.assert_equal(result, expected)
def test_td64arr_add_sub_timestamp(self, box_with_array):
# GH#11925
ts = Timestamp("2012-01-01")
# TODO: parametrize over types of datetime scalar?
tdi = timedelta_range("... | class TestTimedeltaArraylikeAddSubOps:
result = other + idx
tm.assert_equal(result, expected)
@pytest.mark.parametrize(
"ts",
[
Timestamp("2012-01-01"),
Timestamp("2012-01-01").to_pydatetime(),
Timestamp("2012-01-01").to_datetime64(),
],
... |
class URLValidator(RegexValidator):
r'\Z', re.IGNORECASE)
message = _('Enter a valid URL.')
schemes = ['http', 'https', 'ftp', 'ftps']
def __init__(self, schemes=None, **kwargs):
super().__init__(**kwargs) | class URLValidator(RegexValidator):
r'\Z', re.IGNORECASE)
message = _('Enter a valid URL.')
schemes = ['http', 'https', 'ftp', 'ftps']
unsafe_chars = frozenset('\t\r\n')
def __init__(self, schemes=None, **kwargs):
super().__init__(**kwargs) |
class URLValidator(RegexValidator):
def __call__(self, value):
if not isinstance(value, str):
raise ValidationError(self.message, code=self.code)
# Check if the scheme is valid.
scheme = value.split('://')[0].lower()
if scheme not in self.schemes: | class URLValidator(RegexValidator):
def __call__(self, value):
if not isinstance(value, str):
raise ValidationError(self.message, code=self.code)
if self.unsafe_chars.intersection(value):
raise ValidationError(self.message, code=self.code)
# Check if the scheme is val... |
TEST_DATA = [
(URLValidator(), None, ValidationError),
(URLValidator(), 56, ValidationError),
(URLValidator(), 'no_scheme', ValidationError),
# Trailing newlines not accepted
(URLValidator(), 'http://www.djangoproject.com/\n', ValidationError),
(URLValidator(), 'http://[::ffff:192.9.5.5]\n', Val... | TEST_DATA = [
(URLValidator(), None, ValidationError),
(URLValidator(), 56, ValidationError),
(URLValidator(), 'no_scheme', ValidationError),
# Newlines and tabs are not accepted.
(URLValidator(), 'http://www.djangoproject.com/\n', ValidationError),
(URLValidator(), 'http://[::ffff:192.9.5.5]\n'... |
class Index(IndexOpsMixin, PandasObject):
left_indexer = self.get_indexer(target, "pad", limit=limit)
right_indexer = self.get_indexer(target, "backfill", limit=limit)
target = np.asarray(target)
left_distances = abs(self.values[left_indexer] - target)
right_distances = abs(self... | class Index(IndexOpsMixin, PandasObject):
left_indexer = self.get_indexer(target, "pad", limit=limit)
right_indexer = self.get_indexer(target, "backfill", limit=limit)
left_distances = np.abs(self[left_indexer] - target)
right_distances = np.abs(self[right_indexer] - target)
op... |
class TestDataFrameIndexing:
actual = df.reindex(target, method="nearest", tolerance=[0.5, 0.01, 0.4, 0.1])
tm.assert_frame_equal(expected, actual)
def test_reindex_frame_add_nat(self):
rng = date_range("1/1/2000 00:00:00", periods=10, freq="10s")
df = DataFrame({"A": np.random.rand... | class TestDataFrameIndexing:
actual = df.reindex(target, method="nearest", tolerance=[0.5, 0.01, 0.4, 0.1])
tm.assert_frame_equal(expected, actual)
def test_reindex_nearest_tz(self, tz_aware_fixture):
# GH26683
tz = tz_aware_fixture
idx = pd.date_range("2019-01-01", periods=... |
class WorkerProcess(multiprocessing_context.Process):
self._variable_manager = variable_manager
self._shared_loader_obj = shared_loader_obj
def _save_stdin(self):
self._new_stdin = os.devnull
try: | class WorkerProcess(multiprocessing_context.Process):
self._variable_manager = variable_manager
self._shared_loader_obj = shared_loader_obj
# NOTE: this works due to fork, if switching to threads this should change to per thread storage of temp files
# clear var to ensure we only delete... |
class WorkerProcess(multiprocessing_context.Process):
except Exception:
display.debug(u"WORKER EXCEPTION: %s" % to_text(e))
display.debug(u"WORKER TRACEBACK: %s" % to_text(traceback.format_exc()))
display.debug("WORKER PROCESS EXITING")
| class WorkerProcess(multiprocessing_context.Process):
except Exception:
display.debug(u"WORKER EXCEPTION: %s" % to_text(e))
display.debug(u"WORKER TRACEBACK: %s" % to_text(traceback.format_exc()))
finally:
self._clean_up()
... |
class WorkerProcess(multiprocessing_context.Process):
# ps.print_stats()
# with open('worker_%06d.stats' % os.getpid(), 'w') as f:
# f.write(s.getvalue()) | class WorkerProcess(multiprocessing_context.Process):
# ps.print_stats()
# with open('worker_%06d.stats' % os.getpid(), 'w') as f:
# f.write(s.getvalue())
def _clean_up(self):
# NOTE: see note in init about forks
# ensure we cleanup all temp files for this worker
... |
class DataLoader:
'''
def __init__(self):
self._basedir = '.'
self._FILE_CACHE = dict()
self._tempfiles = set()
# initialize the vault stuff with an empty password | class DataLoader:
'''
def __init__(self):
self._basedir = '.'
# NOTE: not effective with forks as the main copy does not get updated.
# avoids rereading files
self._FILE_CACHE = dict()
# NOTE: not thread safe, also issues with forks not returning data to main proc
... |
class DataLoader:
def _create_content_tempfile(self, content):
''' Create a tempfile containing defined content '''
fd, content_tempfile = tempfile.mkstemp()
f = os.fdopen(fd, 'wb')
content = to_bytes(content)
try: | class DataLoader:
def _create_content_tempfile(self, content):
''' Create a tempfile containing defined content '''
fd, content_tempfile = tempfile.mkstemp(dir=C.DEFAULT_LOCAL_TMP)
f = os.fdopen(fd, 'wb')
content = to_bytes(content)
try: |
class DataLoader:
self._tempfiles.remove(file_path)
def cleanup_all_tmp_files(self):
for f in self._tempfiles:
try:
self.cleanup_tmp_file(f) | class DataLoader:
self._tempfiles.remove(file_path)
def cleanup_all_tmp_files(self):
"""
Removes all temporary files that DataLoader has created
NOTE: not thread safe, forks also need special handling see __init__ for details.
"""
for f in self._tempfiles:
... |
class VaultEditor:
# Create a tempfile
root, ext = os.path.splitext(os.path.realpath(filename))
fd, tmp_path = tempfile.mkstemp(suffix=ext)
os.close(fd)
cmd = self._editor_shell_command(tmp_path) | class VaultEditor:
# Create a tempfile
root, ext = os.path.splitext(os.path.realpath(filename))
fd, tmp_path = tempfile.mkstemp(suffix=ext, dir=C.DEFAULT_LOCAL_TMP)
os.close(fd)
cmd = self._editor_shell_command(tmp_path) |
from pandas.core.frame import DataFrame
from pandas.core.groupby import ops
from pandas.core.groupby.categorical import recode_for_groupby, recode_from_groupby
from pandas.core.indexes.api import CategoricalIndex, Index, MultiIndex
from pandas.core.series import Series
from pandas.io.formats.printing import pprint_thi... | from pandas.core.frame import DataFrame
from pandas.core.groupby import ops
from pandas.core.groupby.categorical import recode_for_groupby, recode_from_groupby
from pandas.core.indexes.api import CategoricalIndex, Index, MultiIndex
from pandas.core.indexes.base import InvalidIndexError
from pandas.core.series import Se... |
def get_grouper(
items = obj._data.items
try:
items.get_loc(key)
except (KeyError, TypeError):
# TypeError shows up here if we pass e.g. Int64Index
return False
| def get_grouper(
items = obj._data.items
try:
items.get_loc(key)
except (KeyError, TypeError, InvalidIndexError):
# TypeError shows up here if we pass e.g. Int64Index
return False
|
from pandas.core.arrays.datetimes import (
validate_tz_from_dtype,
)
import pandas.core.common as com
from pandas.core.indexes.base import Index, maybe_extract_name
from pandas.core.indexes.datetimelike import (
DatetimelikeDelegateMixin,
DatetimeTimedeltaMixin, | from pandas.core.arrays.datetimes import (
validate_tz_from_dtype,
)
import pandas.core.common as com
from pandas.core.indexes.base import Index, InvalidIndexError, maybe_extract_name
from pandas.core.indexes.datetimelike import (
DatetimelikeDelegateMixin,
DatetimeTimedeltaMixin, |
class DatetimeIndex(DatetimeTimedeltaMixin, DatetimeDelegateMixin):
Fast lookup of value from 1-dimensional ndarray. Only use this if you
know what you're doing
"""
if isinstance(key, (datetime, np.datetime64)):
return self.get_value_maybe_box(series, key) | class DatetimeIndex(DatetimeTimedeltaMixin, DatetimeDelegateMixin):
Fast lookup of value from 1-dimensional ndarray. Only use this if you
know what you're doing
"""
if not is_scalar(key):
raise InvalidIndexError(key)
if isinstance(key, (datetime, np.datetime64)):
... |
class DatetimeIndex(DatetimeTimedeltaMixin, DatetimeDelegateMixin):
-------
loc : int
"""
if is_valid_nat_for_dtype(key, self.dtype):
key = NaT
| class DatetimeIndex(DatetimeTimedeltaMixin, DatetimeDelegateMixin):
-------
loc : int
"""
if not is_scalar(key):
raise InvalidIndexError(key)
if is_valid_nat_for_dtype(key, self.dtype):
key = NaT
|
class MultiIndex(Index):
indexer = self._get_level_indexer(key, level=level)
new_index = maybe_mi_droplevels(indexer, [0], drop_level)
return indexer, new_index
except TypeError:
pass
if not any(isinstance(k, slice) for... | class MultiIndex(Index):
indexer = self._get_level_indexer(key, level=level)
new_index = maybe_mi_droplevels(indexer, [0], drop_level)
return indexer, new_index
except (TypeError, InvalidIndexError):
pass
if not any(isi... |
class Series(base.IndexOpsMixin, generic.NDFrame):
self[:] = value
else:
self.loc[key] = value
except TypeError as e:
if isinstance(key, tuple) and not isinstance(self.index, MultiIndex): | class Series(base.IndexOpsMixin, generic.NDFrame):
self[:] = value
else:
self.loc[key] = value
except InvalidIndexError:
# e.g. slice
self._set_with(key, value)
except TypeError as e:
if isinstance(key, tuple) and not isins... |
import pytz
import pandas as pd
from pandas import DatetimeIndex, Index, Timestamp, date_range, notna
import pandas._testing as tm
from pandas.tseries.offsets import BDay, CDay
| import pytz
import pandas as pd
from pandas import DatetimeIndex, Index, Timestamp, date_range, notna
import pandas._testing as tm
from pandas.core.indexes.base import InvalidIndexError
from pandas.tseries.offsets import BDay, CDay
|
class TestDatetimeIndex:
with pytest.raises(KeyError, match="'foobar'"):
idx.get_loc("foobar")
with pytest.raises(TypeError):
idx.get_loc(slice(2))
idx = pd.to_datetime(["2000-01-01", "2000-01-04"]) | class TestDatetimeIndex:
with pytest.raises(KeyError, match="'foobar'"):
idx.get_loc("foobar")
with pytest.raises(InvalidIndexError, match=r"slice\(None, 2, None\)"):
idx.get_loc(slice(2))
idx = pd.to_datetime(["2000-01-01", "2000-01-04"]) |
# -*- coding: utf-8 -*-
# The pam components have been modified to be salty and have been taken from
# the pam module under this licence:
# (c) 2007 Chris AtLee <chris@atlee.ca> | # The pam components have been modified to be salty and have been taken from
# the pam module under this licence:
# (c) 2007 Chris AtLee <chris@atlee.ca> |
authenticated against. This defaults to `login`
"""
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
from ctypes import ( | authenticated against. This defaults to `login`
"""
import logging
from ctypes import ( |
from ctypes import (
)
from ctypes.util import find_library
# Import Salt libs
import salt.utils.user
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin
log = logging.getLogger(__name__)
try: | from ctypes import (
)
from ctypes.util import find_library
import salt.utils.user
log = logging.getLogger(__name__)
try: |
class PamMessage(Structure):
]
def __repr__(self):
return "<PamMessage {0} '{1}'>".format(self.msg_style, self.msg)
class PamResponse(Structure): | class PamMessage(Structure):
]
def __repr__(self):
return "<PamMessage {} '{}'>".format(self.msg_style, self.msg)
class PamResponse(Structure): |
class PamResponse(Structure):
]
def __repr__(self):
return "<PamResponse {0} '{1}'>".format(self.resp_retcode, self.resp)
CONV_FUNC = CFUNCTYPE( | class PamResponse(Structure):
]
def __repr__(self):
return "<PamResponse {} '{}'>".format(self.resp_retcode, self.resp)
CONV_FUNC = CFUNCTYPE( |
def authenticate(username, password):
"""
service = __opts__.get("auth.pam.service", "login")
if isinstance(username, six.text_type):
username = username.encode(__salt_system_encoding__)
if isinstance(password, six.text_type):
password = password.encode(__salt_system_encoding__)
if ... | def authenticate(username, password):
"""
service = __opts__.get("auth.pam.service", "login")
if isinstance(username, str):
username = username.encode(__salt_system_encoding__)
if isinstance(password, str):
password = password.encode(__salt_system_encoding__)
if isinstance(service, ... |
def authenticate(username, password):
retval = PAM_AUTHENTICATE(handle, 0)
if retval == 0:
PAM_ACCT_MGMT(handle, 0)
PAM_END(handle, 0)
return retval == 0
| def authenticate(username, password):
retval = PAM_AUTHENTICATE(handle, 0)
if retval == 0:
retval = PAM_ACCT_MGMT(handle, 0)
PAM_END(handle, 0)
return retval == 0
|
Genshi Renderer for Salt
"""
# pylint: disable=import-error,no-name-in-module
try:
from genshi.template import MarkupTemplate
from genshi.template import NewTextTemplate
from genshi.template import OldTextTemplate
HAS_LIBS = True
except ImportError:
HAS_LIBS = False
# pylint: enable=import-error,n... | Genshi Renderer for Salt
"""
try:
from genshi.template import MarkupTemplate # pylint: disable=no-name-in-module
from genshi.template import NewTextTemplate # pylint: disable=no-name-in-module
from genshi.template import OldTextTemplate # pylint: disable=no-name-in-module
HAS_LIBS = True
except Imp... |
import time
import traceback
import math
from tornado.concurrent import TracebackFuture, is_future
from tornado.log import app_log, gen_log
from tornado.platform.auto import set_close_exec, Waker
from tornado import stack_context | import time
import traceback
import math
from tornado.concurrent import TracebackFuture, is_future, chain_future
from tornado.log import app_log, gen_log
from tornado.platform.auto import set_close_exec, Waker
from tornado import stack_context |
class IOLoop(Configurable):
from tornado.process import cpu_count
self._executor = ThreadPoolExecutor(max_workers=(cpu_count() * 5))
executor = self._executor
return executor.submit(func, *args)
def set_default_executor(self, executor):
"""Sets the defau... | class IOLoop(Configurable):
from tornado.process import cpu_count
self._executor = ThreadPoolExecutor(max_workers=(cpu_count() * 5))
executor = self._executor
c_future = executor.submit(func, *args)
# Concurrent Futures are not usable with await. Wrap this in ... |
class TestIOLoopFutures(AsyncTestCase):
event1 = threading.Event()
event2 = threading.Event()
def callback(self_event, other_event):
self_event.set()
time.sleep(0.01)
self.assertTrue(other_event.is_set())
return self_event
res = yield [
... | class TestIOLoopFutures(AsyncTestCase):
event1 = threading.Event()
event2 = threading.Event()
def sync_func(self_event, other_event):
self_event.set()
other_event.wait()
# Note that return value doesn't actually do anything,
# it is just passed th... |
def _create_instance(self, context, instance_type,
LOG.debug(_("Going to run %s instances...") % num_instances)
if create_instance_here:
instance = self.create_db_entry_for_new_instance(
context, instance_type, image, base_options, | def _create_instance(self, context, instance_type,
LOG.debug(_("Going to run %s instances...") % num_instances)
# Validate the correct devices have been specified
for bdm in block_device_mapping:
# NOTE(vish): For now, just make sure the volumes are accessible.
snapshot... |
class InstanceInvalidState(Invalid):
"%(method)s while the instance is in this state.")
class InstanceNotRunning(Invalid):
message = _("Instance %(instance_id)s is not running.")
| class InstanceInvalidState(Invalid):
"%(method)s while the instance is in this state.")
class InvalidBDM(Invalid):
message = _("Block Device Mapping is Invalid.")
class InvalidBDMSnapshot(InvalidBDM):
message = _("Block Device Mapping is Invalid: "
"failed to get snapshot %(i... |
import re
import inspect
__version__ = '0.8'
__author__ = 'Hsiaoming Yang <me@lepture.com>'
__all__ = [
'BlockGrammar', 'BlockLexer', | import re
import inspect
__version__ = '0.8.1'
__author__ = 'Hsiaoming Yang <me@lepture.com>'
__all__ = [
'BlockGrammar', 'BlockLexer', |
def _pure_pattern(regex):
def _keyify(key):
return _key_pattern.sub(' ', key.lower())
def escape(text, quote=False, smart_amp=True): | def _pure_pattern(regex):
def _keyify(key):
key = escape(key.lower(), quote=True)
return _key_pattern.sub(' ', key)
def escape(text, quote=False, smart_amp=True): |
class InlineGrammar(object):
inline_html = re.compile(
r'^(?:%s|%s|%s)' % (
r'<!--[\s\S]*?-->',
r'<(\w+%s)((?:%s)*?)\s*>([\s\S]*?)<\/\1>' % (_valid_end, _valid_attr),
r'<\w+%s(?:%s)*?\s*\/?>' % (_valid_end, _valid_attr),
)
) | class InlineGrammar(object):
inline_html = re.compile(
r'^(?:%s|%s|%s)' % (
r'<!--[\s\S]*?-->',
r'<(\w+%s)((?:%s)*?)\s*>([\s\S]*?)<\/\1>' % (
_valid_end, _valid_attr),
r'<\w+%s(?:%s)*?\s*\/?>' % (_valid_end, _valid_attr),
)
) |
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} |
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, |
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... |
class TestCrosstab:
result = pd.crosstab(s1, s2)
tm.assert_frame_equal(result, expected)
def test_crosstab_unsorted_order(self):
df = pd.DataFrame({"b": [3, 1, 2], "a": [5, 4, 6]}, index=["C", "A", "B"])
result = pd.crosstab(df.index, [df.b, df.a]) | class TestCrosstab:
result = pd.crosstab(s1, s2)
tm.assert_frame_equal(result, expected)
def test_crosstab_both_tuple_names(self):
# GH 18321
s1 = pd.Series(range(3), name=("a", "b"))
s2 = pd.Series(range(3), name=("c", "d"))
expected = pd.DataFrame(
np.... |
class HTTP1Connection(httputil.HTTPConnection):
self._chunking_output = (
start_line.method in ("POST", "PUT", "PATCH")
and "Content-Length" not in headers
and "Transfer-Encoding" not in headers
)
else:
assert isinstance(start_l... | class HTTP1Connection(httputil.HTTPConnection):
self._chunking_output = (
start_line.method in ("POST", "PUT", "PATCH")
and "Content-Length" not in headers
and (
"Transfer-Encoding" not in headers
or headers["Transfer-En... |
Transfer-Encoding: chunked
# don't either).
self.assertEqual(301, response.code)
def test_credentials_in_url(self):
url = self.get_url("/auth").replace("http://", "http://me:secret@")
response = self.fetch(url) | Transfer-Encoding: chunked
# don't either).
self.assertEqual(301, response.code)
def test_redirect_put_with_body(self):
response = self.fetch(
"/redirect?url=/put&status=307", method="PUT", body="hello"
)
self.assertEqual(response.body, b"Put body: hello")
d... |
class TestUtil(unittest.TestCase):
inp = '''{"foo":101}'''
self.assertEqual(js_to_json(inp), '''{"foo":101}''')
def test_js_to_json_edgecases(self):
on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"}) | class TestUtil(unittest.TestCase):
inp = '''{"foo":101}'''
self.assertEqual(js_to_json(inp), '''{"foo":101}''')
inp = '''{"duration": "00:01:07"}'''
self.assertEqual(js_to_json(inp), '''{"duration": "00:01:07"}''')
def test_js_to_json_edgecases(self):
on = js_to_json("{abc_... |
def js_to_json(code):
}.get(m.group(0), m.group(0)), v[1:-1])
INTEGER_TABLE = (
(r'^0[xX][0-9a-fA-F]+', 16),
(r'^0+[0-7]+', 8),
)
for regex, base in INTEGER_TABLE:
im = re.match(regex, v)
if im:
i = int(im.group(0), ba... | def js_to_json(code):
}.get(m.group(0), m.group(0)), v[1:-1])
INTEGER_TABLE = (
(r'^(0[xX][0-9a-fA-F]+)\s*:?$', 16),
(r'^(0+[0-7]+)\s*:?$', 8),
)
for regex, base in INTEGER_TABLE:
im = re.match(regex, v)
if im:
i = int... |
def generate_commands(vlan_id, to_set, to_remove):
if "vlan_id" in to_remove:
return ["no vlan {0}".format(vlan_id)]
for key, value in to_set.items():
if key == "vlan_id" or value is None:
continue
commands.append("{0} {1}".format(key, value))
for key in to_remove:
... | def generate_commands(vlan_id, to_set, to_remove):
if "vlan_id" in to_remove:
return ["no vlan {0}".format(vlan_id)]
for key in to_remove:
if key in to_set.keys():
continue
commands.append("no {0}".format(key))
for key, value in to_set.items():
if key == "vlan_i... |
class TestEosVlansModule(TestEosModule):
self.execute_show_command.return_value = []
set_module_args(dict(
config=[dict(
vlan_id=30,
name="thirty",
state="suspend"
)], state="replaced"
))
commands = ['vlan 30', 'name... | class TestEosVlansModule(TestEosModule):
self.execute_show_command.return_value = []
set_module_args(dict(
config=[dict(
vlan_id=10,
name="tenreplaced",
state="suspend"
)], state="replaced"
))
commands = ['vlan 10', ... |
class RangeIndex(Int64Index):
@Appender(_index_shared_docs["get_indexer"])
def get_indexer(self, target, method=None, limit=None, tolerance=None):
if not (method is None and tolerance is None and is_list_like(target)):
return super().get_indexer(target, method=method, tolerance=tolerance)
... | class RangeIndex(Int64Index):
@Appender(_index_shared_docs["get_indexer"])
def get_indexer(self, target, method=None, limit=None, tolerance=None):
if com.any_not_none(method, tolerance, limit) or not is_list_like(target):
return super().get_indexer(
target, method=method, to... |
class TestDataFrameIndexing(TestData):
assert mask[-5:].all()
assert not mask[:-5].any()
def test_set_dataframe_column_ns_dtype(self):
x = DataFrame([datetime.now(), datetime.now()])
assert x[0].dtype == np.dtype("M8[ns]") | class TestDataFrameIndexing(TestData):
assert mask[-5:].all()
assert not mask[:-5].any()
def test_reindex_limit(self):
# GH 28631
data = [["A", "A", "A"], ["B", "B", "B"], ["C", "C", "C"], ["D", "D", "D"]]
exp_data = [
["A", "A", "A"],
["B", "B", "B"]... |
class TestRangeIndex(Numeric):
expected = np.array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5], dtype=np.intp)
tm.assert_numpy_array_equal(indexer, expected)
def test_join_outer(self):
# join with Int64Index
other = Int64Index(np.arange(25, 14, -1)) | class TestRangeIndex(Numeric):
expected = np.array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5], dtype=np.intp)
tm.assert_numpy_array_equal(indexer, expected)
def test_get_indexer_limit(self):
# GH 28631
idx = RangeIndex(4)
target = RangeIndex(6)
result = idx.get_indexer(target, m... |
import functools
import http
from typing import Any, Awaitable, Callable, Iterable, Optional, Tuple, Union, cast
|
import functools
import hmac
import http
from typing import Any, Awaitable, Callable, Iterable, Optional, Tuple, Union, cast
|
def basic_auth_protocol_factory(
if credentials is not None:
if is_credentials(credentials):
async def check_credentials(username: str, password: str) -> bool:
return (username, password) == credentials
elif isinstance(credentials, Iterable):
credentials_li... | def basic_auth_protocol_factory(
if credentials is not None:
if is_credentials(credentials):
credentials_list = [cast(Credentials, credentials)]
elif isinstance(credentials, Iterable):
credentials_list = list(credentials)
if not all(is_credentials(item) for item ... |
async def check_credentials(username: str, password: str) -> bool:
)
return functools.partial(
create_protocol, realm=realm, check_credentials=check_credentials
) | async def check_credentials(username: str, password: str) -> bool:
)
return functools.partial(
create_protocol,
realm=realm,
check_credentials=check_credentials,
) |
import unittest
import urllib.error
| import hmac
import unittest
import urllib.error
|
def test_basic_auth_bad_multiple_credentials(self):
)
async def check_credentials(username, password):
return password == "iloveyou"
create_protocol_check_credentials = basic_auth_protocol_factory(
realm="auth-tests", | def test_basic_auth_bad_multiple_credentials(self):
)
async def check_credentials(username, password):
return hmac.compare_digest(password, "iloveyou")
create_protocol_check_credentials = basic_auth_protocol_factory(
realm="auth-tests", |
def test_basic_auth_unsupported_credentials_details(self):
self.assertEqual(raised.exception.read().decode(), "Unsupported credentials\n")
@with_server(create_protocol=create_protocol)
def test_basic_auth_invalid_credentials(self):
with self.assertRaises(InvalidStatusCode) as raised:
... | def test_basic_auth_unsupported_credentials_details(self):
self.assertEqual(raised.exception.read().decode(), "Unsupported credentials\n")
@with_server(create_protocol=create_protocol)
def test_basic_auth_invalid_username(self):
with self.assertRaises(InvalidStatusCode) as raised:
s... |
DEFAULT_LOG_PATH = get_config(p, DEFAULTS, 'log_path', 'ANSIB
DEFAULT_FORCE_HANDLERS = get_config(p, DEFAULTS, 'force_handlers', 'ANSIBLE_FORCE_HANDLERS', False, boolean=True)
DEFAULT_INVENTORY_IGNORE = get_config(p, DEFAULTS, 'inventory_ignore_extensions', 'ANSIBLE_INVENTORY_IGNORE', ["~", ".ori... | DEFAULT_LOG_PATH = get_config(p, DEFAULTS, 'log_path', 'ANSIB
DEFAULT_FORCE_HANDLERS = get_config(p, DEFAULTS, 'force_handlers', 'ANSIBLE_FORCE_HANDLERS', False, boolean=True)
DEFAULT_INVENTORY_IGNORE = get_config(p, DEFAULTS, 'inventory_ignore_extensions', 'ANSIBLE_INVENTORY_IGNORE', ["~", ".ori... |
class Templar:
loader=FileSystemLoader(self._basedir),
)
self.SINGLE_VAR = re.compile(r"^%s\s*(\w*)\s*%s$" % (self.environment.variable_start_string, self.environment.variable_end_string))
self.block_start = self.environment.block_start_string | class Templar:
loader=FileSystemLoader(self._basedir),
)
# the current rendering context under which the templar class is working
self.cur_context = None
self.SINGLE_VAR = re.compile(r"^%s\s*(\w*)\s*%s$" % (self.environment.variable_start_string, self.environment.variable_e... |
class Templar:
if instance is not None:
wantlist = kwargs.pop('wantlist', False)
from ansible.utils.listify import listify_lookup_plugin_terms
loop_terms = listify_lookup_plugin_terms(terms=args, templar=self, loader=self._loader, fail_on_undefined=True, convert_bare=False) | class Templar:
if instance is not None:
wantlist = kwargs.pop('wantlist', False)
allow_unsafe = kwargs.pop('allow_unsafe', C.DEFAULT_ALLOW_UNSAFE_LOOKUPS)
from ansible.utils.listify import listify_lookup_plugin_terms
loop_terms = listify_lookup_plugin_terms(term... |
class Templar:
raise AnsibleError("An unhandled exception occurred while running the lookup plugin '%s'. Error was a %s, original message: %s" % (name, type(e), e))
ran = None
if ran:
from ansible.vars.unsafe_proxy import UnsafeProxy, wrap_var
... | class Templar:
raise AnsibleError("An unhandled exception occurred while running the lookup plugin '%s'. Error was a %s, original message: %s" % (name, type(e), e))
ran = None
if ran and not allow_unsafe:
from ansible.vars.unsafe_proxy import UnsafeProxy,... |
class Templar:
else:
ran = wrap_var(ran)
return ran
else:
raise AnsibleError("lookup plugin (%s) not found" % name) | class Templar:
else:
ran = wrap_var(ran)
if self.cur_context:
self.cur_context.unsafe = True
return ran
else:
raise AnsibleError("lookup plugin (%s) not found" % name) |
class Templar:
jvars = AnsibleJ2Vars(self, t.globals)
new_context = t.new_context(jvars, shared=True)
rf = t.root_render_func(new_context)
try: | class Templar:
jvars = AnsibleJ2Vars(self, t.globals)
self.cur_context = new_context = t.new_context(jvars, shared=True)
rf = t.root_render_func(new_context)
try: |
Name: Max Speed, dtype: float64
if copy:
new_values = new_values.copy()
assert isinstance(self.index, PeriodIndex)
new_index = self.index.to_timestamp(freq=freq, how=how) # type: ignore
return self._constructor(new_values, index=new_index).__finalize__(
self, me... | Name: Max Speed, dtype: float64
if copy:
new_values = new_values.copy()
if not isinstance(self.index, PeriodIndex):
raise TypeError(f"unsupported Type {type(self.index).__name__}")
new_index = self.index.to_timestamp(freq=freq, how=how) # type: ignore
return sel... |
Name: Max Speed, dtype: float64
if copy:
new_values = new_values.copy()
assert isinstance(self.index, DatetimeIndex)
new_index = self.index.to_period(freq=freq) # type: ignore
return self._constructor(new_values, index=new_index).__finalize__(
self, method="to_p... | Name: Max Speed, dtype: float64
if copy:
new_values = new_values.copy()
if not isinstance(self.index, DatetimeIndex):
raise TypeError(f"unsupported Type {type(self.index).__name__}")
new_index = self.index.to_period(freq=freq) # type: ignore
return self._constru... |
import numpy as np
from pandas import (
DataFrame, | import numpy as np
import pytest
from pandas import (
DataFrame, |
class TestToPeriod:
expected = df.copy()
expected.columns = exp_idx
tm.assert_frame_equal(df.to_period(axis=1), expected) | class TestToPeriod:
expected = df.copy()
expected.columns = exp_idx
tm.assert_frame_equal(df.to_period(axis=1), expected)
def test_to_period_raises(self, indices):
# https://github.com/pandas-dev/pandas/issues/33327
index = indices
ser = Series(index=index, dtype=obj... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.