buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
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: |
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):
self.schemes = schemes
def __call__(self, value):
# Check first if the scheme is valid
scheme = value.split('://')[0].lower()
if scheme not in self.schemes:
raise ValidationError(self.message, code=self.code) | class URLValidator(RegexValidator):
self.schemes = schemes
def __call__(self, value):
if isinstance(value, str) and self.unsafe_chars.intersection(value):
raise ValidationError(self.message, code=self.code)
# Check if the scheme is valid.
scheme = value.split('://')[... |
TEST_DATA = [
(URLValidator(EXTENDED_SCHEMES), 'git+ssh://git@github.com/example/hg-git.git', None),
(URLValidator(EXTENDED_SCHEMES), 'git://-invalid.com', ValidationError),
# Trailing newlines not accepted
(URLValidator(), 'http://www.djangoproject.com/\n', ValidationError),
(URLValidator(), 'http... | TEST_DATA = [
(URLValidator(EXTENDED_SCHEMES), 'git+ssh://git@github.com/example/hg-git.git', None),
(URLValidator(EXTENDED_SCHEMES), 'git://-invalid.com', ValidationError),
# Newlines and tabs are not accepted.
(URLValidator(), 'http://www.djangoproject.com/\n', ValidationError),
(URLValidator(), ... |
class Parser:
for date_unit in date_units:
try:
new_data = to_datetime(new_data, errors="raise", unit=date_unit)
except (ValueError, OverflowError):
continue
return new_data, True
return data, False | class Parser:
for date_unit in date_units:
try:
new_data = to_datetime(new_data, errors="raise", unit=date_unit)
except (ValueError, OverflowError, TypeError):
continue
return new_data, True
return data, False |
DataFrame\\.index values are different \\(100\\.0 %\\)
# GH 31615
result = pd.DataFrame([[nulls_fixture]]).to_json()
assert result == '{"0":{"0":null}}' | DataFrame\\.index values are different \\(100\\.0 %\\)
# GH 31615
result = pd.DataFrame([[nulls_fixture]]).to_json()
assert result == '{"0":{"0":null}}'
def test_readjson_bool_series(self):
# GH31464
result = read_json("[true, true, false]", typ="series")
expected = ... |
from warnings import warn
from lxml import etree
from lxml.etree import QName, XMLParser, XMLSyntaxError, parse
from .. import Name, Stream, String
from .. import __version__ as pikepdf_version
if sys.version_info < (3, 9): # pragma: no cover
from typing import Iterable, MutableMapping | from warnings import warn
from lxml import etree
from lxml.etree import QName, XMLSyntaxError
from .. import Name, Stream, String
from .. import __version__ as pikepdf_version
from .._xml import parse_xml
if sys.version_info < (3, 9): # pragma: no cover
from typing import Iterable, MutableMapping |
def _load_from(self, data: bytes) -> None:
data = XMP_EMPTY # on some platforms lxml chokes on empty documents
def basic_parser(xml):
return parse(BytesIO(xml))
def strip_illegal_bytes_parser(xml):
return parse(BytesIO(re_xml_illegal_bytes.sub(b'', xml)))
... | def _load_from(self, data: bytes) -> None:
data = XMP_EMPTY # on some platforms lxml chokes on empty documents
def basic_parser(xml):
return parse_xml(BytesIO(xml))
def strip_illegal_bytes_parser(xml):
return parse_xml(BytesIO(re_xml_illegal_bytes.sub(b'', xml)))
... |
def test_exception_undoes_edits(graph):
raise
m = graph.open_metadata()
assert m['dc:format'] != 'application/pdf-demo' | def test_exception_undoes_edits(graph):
raise
m = graph.open_metadata()
assert m['dc:format'] != 'application/pdf-demo'
def test_xxe(trivial, outdir):
secret = outdir / 'secret.txt'
secret.write_text("This is a secret")
trivial.Root.Metadata = Stream(
trivial,
b... |
def test_retry_method_not_in_whitelist(self):
retry = Retry()
with pytest.raises(ReadTimeoutError):
retry.increment(method='POST', error=error) | def test_retry_method_not_in_whitelist(self):
retry = Retry()
with pytest.raises(ReadTimeoutError):
retry.increment(method='POST', error=error)
def test_retry_default_remove_headers_on_redirect(self):
retry = Retry()
assert list(retry.remove_headers_on_redirect) == ['Au... |
def test_too_many_redirects(self):
except MaxRetryError:
pass
def test_raise_on_redirect(self):
http = PoolManager()
self.addCleanup(http.clear) | def test_too_many_redirects(self):
except MaxRetryError:
pass
def test_redirect_cross_host_remove_headers(self):
http = PoolManager()
self.addCleanup(http.clear)
r = http.request('GET', '%s/redirect' % self.base_url,
fields={'target': '%s/header... |
def urlopen(self, method, url, redirect=True, **kw):
kw['assert_same_host'] = False
kw['redirect'] = False
if 'headers' not in kw:
kw['headers'] = self.headers
if self.proxy is not None and u.scheme == "http":
response = conn.urlopen(method, url, **kw) | def urlopen(self, method, url, redirect=True, **kw):
kw['assert_same_host'] = False
kw['redirect'] = False
if 'headers' not in kw:
kw['headers'] = self.headers.copy()
if self.proxy is not None and u.scheme == "http":
response = conn.urlopen(method, url, **kw) |
def urlopen(self, method, url, redirect=True, **kw):
if not isinstance(retries, Retry):
retries = Retry.from_int(retries, redirect=redirect)
try:
retries = retries.increment(method, url, response=response, _pool=conn)
except MaxRetryError: | def urlopen(self, method, url, redirect=True, **kw):
if not isinstance(retries, Retry):
retries = Retry.from_int(retries, redirect=redirect)
# Strip headers marked as unsafe to forward to the redirected location.
# Check remove_headers_on_redirect to avoid a potential network call w... |
log = logging.getLogger(__name__)
# Data structure for representing the metadata of requests that result in a retry.
RequestHistory = namedtuple('RequestHistory', ["method", "url", "error",
"status", "redirect_location"]) |
log = logging.getLogger(__name__)
# Data structure for representing the metadata of requests that result in a retry.
RequestHistory = namedtuple('RequestHistory', ["method", "url", "error",
"status", "redirect_location"]) |
class Retry(object):
Whether to respect Retry-After header on status codes defined as
:attr:`Retry.RETRY_AFTER_STATUS_CODES` or not.
"""
DEFAULT_METHOD_WHITELIST = frozenset([ | class Retry(object):
Whether to respect Retry-After header on status codes defined as
:attr:`Retry.RETRY_AFTER_STATUS_CODES` or not.
:param iterable remove_headers_on_redirect:
Sequence of headers to remove from the request when a response
indicating a redirect is returned before fi... |
class Retry(object):
RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503])
#: Maximum backoff time.
BACKOFF_MAX = 120
def __init__(self, total=10, connect=None, read=None, redirect=None, status=None,
method_whitelist=DEFAULT_METHOD_WHITELIST, status_forcelist=None,
b... | class Retry(object):
RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503])
DEFAULT_REDIRECT_HEADERS_BLACKLIST = frozenset(['Authorization'])
#: Maximum backoff time.
BACKOFF_MAX = 120
def __init__(self, total=10, connect=None, read=None, redirect=None, status=None,
method_whitel... |
def __init__(self, total=10, connect=None, read=None, redirect=None, status=None
self.raise_on_status = raise_on_status
self.history = history or tuple()
self.respect_retry_after_header = respect_retry_after_header
def new(self, **kw):
params = dict( | def __init__(self, total=10, connect=None, read=None, redirect=None, status=None
self.raise_on_status = raise_on_status
self.history = history or tuple()
self.respect_retry_after_header = respect_retry_after_header
self.remove_headers_on_redirect = remove_headers_on_redirect
def new... |
def new(self, **kw):
raise_on_redirect=self.raise_on_redirect,
raise_on_status=self.raise_on_status,
history=self.history,
)
params.update(kw)
return type(self)(**params) | def new(self, **kw):
raise_on_redirect=self.raise_on_redirect,
raise_on_status=self.raise_on_status,
history=self.history,
remove_headers_on_redirect=self.remove_headers_on_redirect
)
params.update(kw)
return type(self)(**params) |
class Categorical(ExtensionArray, PandasObject):
)
raise ValueError(msg)
codes = np.asarray(codes) # #21767
if len(codes) and not is_integer_dtype(codes):
raise ValueError("codes need to be array-like integers")
| class Categorical(ExtensionArray, PandasObject):
)
raise ValueError(msg)
if is_extension_array_dtype(codes) and is_integer_dtype(codes):
# Avoid the implicit conversion of Int to object
if isna(codes).any():
raise ValueError("codes cannot contain ... |
class TestCategoricalConstructors:
with pytest.raises(ValueError, match=msg):
Categorical.from_codes([0, 1])
@pytest.mark.parametrize("dtype", [None, "category"])
def test_from_inferred_categories(self, dtype):
cats = ["a", "b"] | class TestCategoricalConstructors:
with pytest.raises(ValueError, match=msg):
Categorical.from_codes([0, 1])
def test_from_codes_with_nullable_int(self):
codes = pd.array([0, 1], dtype="Int64")
categories = ["a", "b"]
result = Categorical.from_codes(codes, categories=ca... |
class PdfParser:
whitespace_or_hex = br"[\000\011\012\014\015\0400-9a-fA-F]"
whitespace_optional = whitespace + b"*"
whitespace_mandatory = whitespace + b"+"
newline_only = br"[\r\n]+"
newline = whitespace_optional + newline_only + whitespace_optional
re_trailer_end = re.compile(
whitesp... | class PdfParser:
whitespace_or_hex = br"[\000\011\012\014\015\0400-9a-fA-F]"
whitespace_optional = whitespace + b"*"
whitespace_mandatory = whitespace + b"+"
whitespace_optional_no_nl = br"[\000\011\014\015\040]*" # no "\012" aka "\n"
newline_only = br"[\r\n]+"
newline = whitespace_optional_no_... |
jwplayer("mediaplayer").setup({"abouttext":"Visit Indie DB","aboutlink":"http:\/
_TEST_CASES = [
(
# https://github.com/rg3/youtube-dl/issues/13919
'float_duration',
'http://unknown/manifest.mpd',
[{
'manifest_url': ... | jwplayer("mediaplayer").setup({"abouttext":"Visit Indie DB","aboutlink":"http:\/
_TEST_CASES = [
(
# https://github.com/rg3/youtube-dl/issues/13919
# Also tests duplicate representation ids, see
# https://github.com/rg3/youtube-dl/issues/15111
... |
class InfoExtractor(object):
f['url'] = initialization_url
f['fragments'].append({location_key(initialization_url): initialization_url})
f['fragments'].extend(representation_ms_info['fragments'])
try:... | class InfoExtractor(object):
f['url'] = initialization_url
f['fragments'].append({location_key(initialization_url): initialization_url})
f['fragments'].extend(representation_ms_info['fragments'])
# Ac... |
def test_match(stderr, stdout):
def test_not_match():
assert not match(Command())
@pytest.mark.parametrize('before, after', [ | def test_match(stderr, stdout):
def test_not_match():
assert not match(Command())
assert not match(Command(script='sudo ls', stderr='Permission denied'))
@pytest.mark.parametrize('before, after', [ |
patterns = ['permission denied',
def match(command):
for pattern in patterns:
if pattern.lower() in command.stderr.lower()\
or pattern.lower() in command.stdout.lower(): | patterns = ['permission denied',
def match(command):
if command.script_parts and command.script_parts[0] == 'sudo':
return False
for pattern in patterns:
if pattern.lower() in command.stderr.lower()\
or pattern.lower() in command.stdout.lower(): |
class BaseGrouper:
pass
else:
raise
return self._aggregate_series_pure_python(obj, func)
def _aggregate_series_fast(self, obj, func):
func = self._is_builtin_func(func) | class BaseGrouper:
pass
else:
raise
except TypeError as err:
if "ndarray" in str(err):
# raised in libreduction if obj's values is no ndarray
pass
else:
raise
return self._aggregate_series... |
def test_array_ufunc_series_defer():
tm.assert_series_equal(r1, expected)
tm.assert_series_equal(r2, expected) | def test_array_ufunc_series_defer():
tm.assert_series_equal(r1, expected)
tm.assert_series_equal(r2, expected)
def test_groupby_agg():
# Ensure that the result of agg is inferred to be decimal dtype
# https://github.com/pandas-dev/pandas/issues/29141
data = make_data()[:5]
df = pd.DataFrame(... |
class Language(object):
kwargs = component_cfg.get(name, {})
kwargs.setdefault("batch_size", batch_size)
if not hasattr(pipe, "pipe"):
docs = _pipe(pipe, docs, kwargs)
else:
docs = pipe.pipe(docs, **kwargs)
for doc, gold in zip(docs... | class Language(object):
kwargs = component_cfg.get(name, {})
kwargs.setdefault("batch_size", batch_size)
if not hasattr(pipe, "pipe"):
docs = _pipe(docs, pipe, kwargs)
else:
docs = pipe.pipe(docs, **kwargs)
for doc, gold in zip(docs... |
def test_language_evaluate(nlp):
nlp.evaluate([text, gold])
def vector_modification_pipe(doc):
doc.vector += 1
return doc | def test_language_evaluate(nlp):
nlp.evaluate([text, gold])
def test_evaluate_no_pipe(nlp):
"""Test that docs are processed correctly within Language.pipe if the
component doesn't expose a .pipe method."""
def pipe(doc):
return doc
text = "hello world"
annots = {"cats": {"POSITIV... |
def check_data(self):
# If there are more documents available?
return self.check_node()
def get_data(self):
# Construct and return the next document.
if self.check_node(): | def check_data(self):
# If there are more documents available?
return self.check_node()
def check_state_key(self, key):
"""Block special attributes/methods from being set in a newly created
object, to prevent user-controlled methods from being called during
deserialization""... |
def construct_undefined(self, node):
SafeConstructor.construct_undefined)
class FullConstructor(SafeConstructor):
def construct_python_str(self, node):
return self.construct_scalar(node).encode('utf-8') | def construct_undefined(self, node):
SafeConstructor.construct_undefined)
class FullConstructor(SafeConstructor):
# 'extend' is blacklisted because it is used by
# construct_python_object_apply to add `listitems` to a newly generate
# python instance
def get_state_keys_blacklist(self):
... |
def make_python_instance(self, suffix, node,
else:
return cls(*args, **kwds)
def set_python_instance_state(self, instance, state):
if hasattr(instance, '__setstate__'):
instance.__setstate__(state)
else: | def make_python_instance(self, suffix, node,
else:
return cls(*args, **kwds)
def set_python_instance_state(self, instance, state, unsafe=False):
if hasattr(instance, '__setstate__'):
instance.__setstate__(state)
else: |
def set_python_instance_state(self, instance, state):
if isinstance(state, tuple) and len(state) == 2:
state, slotstate = state
if hasattr(instance, '__dict__'):
instance.__dict__.update(state)
elif state:
slotstate.update(state)
... | def set_python_instance_state(self, instance, state):
if isinstance(state, tuple) and len(state) == 2:
state, slotstate = state
if hasattr(instance, '__dict__'):
if not unsafe and state:
for key in state.keys():
self.che... |
def make_python_instance(self, suffix, node, args=None, kwds=None, newobj=False)
return super(UnsafeConstructor, self).make_python_instance(
suffix, node, args, kwds, newobj, unsafe=True)
UnsafeConstructor.add_multi_constructor(
u'tag:yaml.org,2002:python/object/apply:',
UnsafeConstructor.c... | def make_python_instance(self, suffix, node, args=None, kwds=None, newobj=False)
return super(UnsafeConstructor, self).make_python_instance(
suffix, node, args, kwds, newobj, unsafe=True)
def set_python_instance_state(self, instance, state):
return super(UnsafeConstructor, self).set_pyt... |
def check_data(self):
# If there are more documents available?
return self.check_node()
def get_data(self):
# Construct and return the next document.
if self.check_node(): | def check_data(self):
# If there are more documents available?
return self.check_node()
def check_state_key(self, key):
"""Block special attributes/methods from being set in a newly created
object, to prevent user-controlled methods from being called during
deserialization""... |
def construct_undefined(self, node):
SafeConstructor.construct_undefined)
class FullConstructor(SafeConstructor):
def construct_python_str(self, node):
return self.construct_scalar(node) | def construct_undefined(self, node):
SafeConstructor.construct_undefined)
class FullConstructor(SafeConstructor):
# 'extend' is blacklisted because it is used by
# construct_python_object_apply to add `listitems` to a newly generate
# python instance
def get_state_keys_blacklist(self):
... |
def make_python_instance(self, suffix, node,
else:
return cls(*args, **kwds)
def set_python_instance_state(self, instance, state):
if hasattr(instance, '__setstate__'):
instance.__setstate__(state)
else: | def make_python_instance(self, suffix, node,
else:
return cls(*args, **kwds)
def set_python_instance_state(self, instance, state, unsafe=False):
if hasattr(instance, '__setstate__'):
instance.__setstate__(state)
else: |
def set_python_instance_state(self, instance, state):
if isinstance(state, tuple) and len(state) == 2:
state, slotstate = state
if hasattr(instance, '__dict__'):
instance.__dict__.update(state)
elif state:
slotstate.update(state)
... | def set_python_instance_state(self, instance, state):
if isinstance(state, tuple) and len(state) == 2:
state, slotstate = state
if hasattr(instance, '__dict__'):
if not unsafe and state:
for key in state.keys():
self.che... |
def make_python_instance(self, suffix, node, args=None, kwds=None, newobj=False)
return super(UnsafeConstructor, self).make_python_instance(
suffix, node, args, kwds, newobj, unsafe=True)
UnsafeConstructor.add_multi_constructor(
'tag:yaml.org,2002:python/object/apply:',
UnsafeConstructor.co... | def make_python_instance(self, suffix, node, args=None, kwds=None, newobj=False)
return super(UnsafeConstructor, self).make_python_instance(
suffix, node, args, kwds, newobj, unsafe=True)
def set_python_instance_state(self, instance, state):
return super(UnsafeConstructor, self).set_pyt... |
def _make_objects():
global MyLoader, MyDumper, MyTestClass1, MyTestClass2, MyTestClass3, YAMLObject1, YAMLObject2, \
AnObject, AnInstance, AState, ACustomState, InitArgs, InitArgsWithState, \
NewArgs, NewArgsWithState, Reduce, ReduceWithState, Slots, MyInt, MyList, MyDict, \
... | def _make_objects():
global MyLoader, MyDumper, MyTestClass1, MyTestClass2, MyTestClass3, YAMLObject1, YAMLObject2, \
AnObject, AnInstance, AState, ACustomState, InitArgs, InitArgsWithState, \
NewArgs, NewArgsWithState, Reduce, ReduceWithState, Slots, MyInt, MyList, MyDict, \
... |
def tzname(self, dt):
def dst(self, dt):
return datetime.timedelta(0)
today = datetime.date.today()
def _load_code(expression): | def tzname(self, dt):
def dst(self, dt):
return datetime.timedelta(0)
class MyFullLoader(yaml.FullLoader):
def get_state_keys_blacklist(self):
return super(MyFullLoader, self).get_state_keys_blacklist() + ['^mymethod$', '^wrong_.*$']
today = datetime.date.today()
def _... |
def test_constructor_types(data_filename, code_filename, verbose=False):
test_constructor_types.unittest = ['.data', '.code']
if __name__ == '__main__':
import sys, test_constructor
sys.modules['test_constructor'] = sys.modules['__main__'] | def test_constructor_types(data_filename, code_filename, verbose=False):
test_constructor_types.unittest = ['.data', '.code']
def test_subclass_blacklist_types(data_filename, verbose=False):
_make_objects()
try:
yaml.load(open(data_filename, 'rb').read(), MyFullLoader)
except yaml.YAMLError as exc... |
def _make_objects():
global MyLoader, MyDumper, MyTestClass1, MyTestClass2, MyTestClass3, YAMLObject1, YAMLObject2, \
AnObject, AnInstance, AState, ACustomState, InitArgs, InitArgsWithState, \
NewArgs, NewArgsWithState, Reduce, ReduceWithState, Slots, MyInt, MyList, MyDict, \
... | def _make_objects():
global MyLoader, MyDumper, MyTestClass1, MyTestClass2, MyTestClass3, YAMLObject1, YAMLObject2, \
AnObject, AnInstance, AState, ACustomState, InitArgs, InitArgsWithState, \
NewArgs, NewArgsWithState, Reduce, ReduceWithState, Slots, MyInt, MyList, MyDict, \
... |
def tzname(self, dt):
def dst(self, dt):
return datetime.timedelta(0)
today = datetime.date.today()
def _load_code(expression): | def tzname(self, dt):
def dst(self, dt):
return datetime.timedelta(0)
class MyFullLoader(yaml.FullLoader):
def get_state_keys_blacklist(self):
return super().get_state_keys_blacklist() + ['^mymethod$', '^wrong_.*$']
today = datetime.date.today()
def _load_code(expressi... |
def test_constructor_types(data_filename, code_filename, verbose=False):
test_constructor_types.unittest = ['.data', '.code']
if __name__ == '__main__':
import sys, test_constructor
sys.modules['test_constructor'] = sys.modules['__main__'] | def test_constructor_types(data_filename, code_filename, verbose=False):
test_constructor_types.unittest = ['.data', '.code']
def test_subclass_blacklist_types(data_filename, verbose=False):
_make_objects()
try:
yaml.load(open(data_filename, 'rb').read(), MyFullLoader)
except yaml.YAMLError as exc... |
class Categorical(ExtensionArray, PandasObject):
good = self._codes != -1
if not good.all():
if skipna:
pointer = self._codes[good].min()
else:
return np.nan | class Categorical(ExtensionArray, PandasObject):
good = self._codes != -1
if not good.all():
if skipna and good.any():
pointer = self._codes[good].min()
else:
return np.nan |
class Categorical(ExtensionArray, PandasObject):
good = self._codes != -1
if not good.all():
if skipna:
pointer = self._codes[good].max()
else:
return np.nan | class Categorical(ExtensionArray, PandasObject):
good = self._codes != -1
if not good.all():
if skipna and good.any():
pointer = self._codes[good].max()
else:
return np.nan |
class TestCategoricalAnalytics:
assert _min == 2
assert _max == 1
@pytest.mark.parametrize("method", ["min", "max"])
def test_deprecate_numeric_only_min_max(self, method):
# GH 25303 | class TestCategoricalAnalytics:
assert _min == 2
assert _max == 1
@pytest.mark.parametrize("function", ["min", "max"])
@pytest.mark.parametrize("skipna", [True, False])
def test_min_max_only_nan(self, function, skipna):
# https://github.com/pandas-dev/pandas/issues/33450
... |
from pandas._libs.lib import infer_dtype
from pandas.core.dtypes.common import (
_NS_DTYPE,
ensure_int64,
is_categorical_dtype,
is_datetime64_dtype,
is_datetime64tz_dtype, | from pandas._libs.lib import infer_dtype
from pandas.core.dtypes.common import (
_NS_DTYPE,
ensure_int64,
is_bool_dtype,
is_categorical_dtype,
is_datetime64_dtype,
is_datetime64tz_dtype, |
def _bins_to_cuts(
def _coerce_to_type(x):
"""
if the passed data is of datetime/timedelta type,
this method converts it to numeric so that cut method can
handle it
"""
dtype = None | def _bins_to_cuts(
def _coerce_to_type(x):
"""
if the passed data is of datetime/timedelta or bool type,
this method converts it to numeric so that cut or qcut method can
handle it
"""
dtype = None |
def _coerce_to_type(x):
elif is_timedelta64_dtype(x):
x = to_timedelta(x)
dtype = np.dtype("timedelta64[ns]")
if dtype is not None:
# GH 19768: force NaT to NaN during integer conversion | def _coerce_to_type(x):
elif is_timedelta64_dtype(x):
x = to_timedelta(x)
dtype = np.dtype("timedelta64[ns]")
elif is_bool_dtype(x):
# GH 20303
x = x.astype(np.int64)
if dtype is not None:
# GH 19768: force NaT to NaN during integer conversion |
def test_timedelta_cut_roundtrip():
["0 days 23:57:07.200000", "2 days 00:00:00", "3 days 00:00:00"]
)
tm.assert_index_equal(result_bins, expected_bins) | def test_timedelta_cut_roundtrip():
["0 days 23:57:07.200000", "2 days 00:00:00", "3 days 00:00:00"]
)
tm.assert_index_equal(result_bins, expected_bins)
@pytest.mark.parametrize("bins", [6, 7])
@pytest.mark.parametrize(
"box, compare",
[
(Series, tm.assert_series_equal),
(np.ar... |
def test_date_like_qcut_bins(arg, expected_bins):
ser = Series(arg)
result, result_bins = qcut(ser, 2, retbins=True)
tm.assert_index_equal(result_bins, expected_bins) | def test_date_like_qcut_bins(arg, expected_bins):
ser = Series(arg)
result, result_bins = qcut(ser, 2, retbins=True)
tm.assert_index_equal(result_bins, expected_bins)
@pytest.mark.parametrize("bins", [6, 7])
@pytest.mark.parametrize(
"box, compare",
[
(Series, tm.assert_series_equal),
... |
from django.contrib.postgres.fields import ArrayField, JSONField
from django.db.models.aggregates import Aggregate
from .mixins import OrderableAggMixin | from django.contrib.postgres.fields import ArrayField, JSONField
from django.db.models import Value
from django.db.models.aggregates import Aggregate
from .mixins import OrderableAggMixin |
class JSONBAgg(Aggregate):
class StringAgg(OrderableAggMixin, Aggregate):
function = 'STRING_AGG'
template = "%(function)s(%(distinct)s%(expressions)s, '%(delimiter)s'%(ordering)s)"
allow_distinct = True
def __init__(self, expression, delimiter, **extra):
super().__init__(expression, delimiter... | class JSONBAgg(Aggregate):
class StringAgg(OrderableAggMixin, Aggregate):
function = 'STRING_AGG'
template = '%(function)s(%(distinct)s%(expressions)s %(ordering)s)'
allow_distinct = True
def __init__(self, expression, delimiter, **extra):
delimiter_expr = Value(str(delimiter))
super()... |
from django.db.models.expressions import F, OrderBy
class OrderableAggMixin:
def __init__(self, expression, ordering=(), **extra):
if not isinstance(ordering, (list, tuple)):
ordering = [ordering]
ordering = ordering or [] | from django.db.models.expressions import F, OrderBy
class OrderableAggMixin:
def __init__(self, *expressions, ordering=(), **extra):
if not isinstance(ordering, (list, tuple)):
ordering = [ordering]
ordering = ordering or [] |
class OrderableAggMixin:
(OrderBy(F(o[1:]), descending=True) if isinstance(o, str) and o[0] == '-' else o)
for o in ordering
)
super().__init__(expression, **extra)
self.ordering = self._parse_expressions(*ordering)
def resolve_expression(self, *args, **kwargs): | class OrderableAggMixin:
(OrderBy(F(o[1:]), descending=True) if isinstance(o, str) and o[0] == '-' else o)
for o in ordering
)
super().__init__(*expressions, **extra)
self.ordering = self._parse_expressions(*ordering)
def resolve_expression(self, *args, **kwargs): |
class TestGeneralAggregate(PostgreSQLTestCase):
with self.assertRaises(TypeError):
AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field'))
def test_string_agg_charfield(self):
values = AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field', delimiter=';'))... | class TestGeneralAggregate(PostgreSQLTestCase):
with self.assertRaises(TypeError):
AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field'))
def test_string_agg_delimiter_escaping(self):
values = AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field', delimi... |
def test_mapping_file(self):
self._test_mapping_file_plain()
def _test_mapping_file_plain(self):
unichrs = lambda s: ''.join(map(chr, map(eval, s.split('+'))))
urt_wa = {}
with self.open_mapping_file() as f:
for line in f:
if not line:
... | def test_mapping_file(self):
self._test_mapping_file_plain()
def _test_mapping_file_plain(self):
def unichrs(s):
return ''.join(chr(int(x, 16)) for x in s.split('+'))
urt_wa = {}
with self.open_mapping_file() as f:
for line in f:
if not ... |
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 ansible.parsing.dataloader import DataLoader
from ansible.release import __version__
from ansible.utils.path import unfrackpath
from ansible.utils.vars import load_extra_vars, load_options_vars
from ansible.vars.manager import VariableManager
from ansible.parsing.vault import PromptVaultSecret, get_file_vault_secr... | from ansible.parsing.dataloader import DataLoader
from ansible.release import __version__
from ansible.utils.path import unfrackpath
from ansible.utils.vars import load_extra_vars, load_options_vars
from ansible.utils.unsafe_proxy import AnsibleUnsafeBytes
from ansible.vars.manager import VariableManager
from ansible.p... |
class CLI(with_metaclass(ABCMeta, object)):
except EOFError:
pass
return (sshpass, becomepass)
def normalize_become_options(self): | class CLI(with_metaclass(ABCMeta, object)):
except EOFError:
pass
# we 'wrap' the passwords to prevent templating as
# they can contain special chars and trigger it incorrectly
if sshpass:
sshpass = AnsibleUnsafeBytes(sshpass)
if becomepass:
b... |
__metaclass__ = type
from collections import Mapping, MutableSequence, Set
from ansible.module_utils.six import string_types, text_type
from ansible.module_utils._text import to_text
| __metaclass__ = type
from collections import Mapping, MutableSequence, Set
from ansible.module_utils.six import string_types, text_type, binary_type
from ansible.module_utils._text import to_text
|
class AnsibleUnsafeText(text_type, AnsibleUnsafe):
pass
class UnsafeProxy(object):
def __new__(cls, obj, *args, **kwargs):
# In our usage we should only receive unicode strings.
# This conditional and conversion exists to sanity check the values
# we're given but we may want to take it... | class AnsibleUnsafeText(text_type, AnsibleUnsafe):
pass
class AnsibleUnsafeBytes(binary_type, AnsibleUnsafe):
pass
class UnsafeProxy(object):
def __new__(cls, obj, *args, **kwargs):
if isinstance(obj, AnsibleUnsafe):
# Already marked unsafe
return obj
# In our us... |
from thefuck.rules.ls_lah import match, get_new_command
def test_match():
assert match(Mock(script='ls file.py'), None)
assert match(Mock(script='ls /opt'), None)
assert not match(Mock(script='ls -lah /opt'), None)
def test_get_new_command(): | from thefuck.rules.ls_lah import match, get_new_command
def test_match():
assert match(Mock(script='ls'), None)
assert match(Mock(script='ls file.py'), None)
assert match(Mock(script='ls /opt'), None)
assert not match(Mock(script='ls -lah /opt'), None)
assert not match(Mock(script='pacman -S binut... |
def match(command, settings):
return 'ls' in command.script and not ('ls -' in command.script)
def get_new_command(command, settings): | def match(command, settings):
return (command.script == 'ls'
or command.script.startswith('ls ')
and not ('ls -' in command.script))
def get_new_command(command, settings): |
def get_write_function(output):
stderr.write(s)
elif isinstance(output, (pycompat.PathLike, str)):
def write(s):
with open(output_path, 'a') as output_file:
output_file.write(s)
else:
assert isinstance(output, utils.WritableStream) | def get_write_function(output):
stderr.write(s)
elif isinstance(output, (pycompat.PathLike, str)):
def write(s):
with open(output, 'a') as output_file:
output_file.write(s)
else:
assert isinstance(output, utils.WritableStream) |
import abc
from python_toolbox import caching
from python_toolbox import sys_tools
import pysnooper
| import abc
from python_toolbox import caching
from python_toolbox import sys_tools
from python_toolbox import temp_file_tools
import pysnooper
|
def test_method_and_prefix():
),
prefix='ZZZ'
) | def test_method_and_prefix():
),
prefix='ZZZ'
)
def test_file_output():
with temp_file_tools.create_temp_folder(prefix='pysnooper') as folder:
path = folder / 'foo.log'
@pysnooper.snoop(str(path))
def my_function(foo):
x = 7
y = 8
ret... |
from django.utils.translation import gettext, gettext_lazy as _
UserModel = get_user_model()
class ReadOnlyPasswordHashWidget(forms.Widget):
template_name = 'auth/widgets/read_only_password_hash.html'
read_only = True | from django.utils.translation import gettext, gettext_lazy as _
UserModel = get_user_model()
def _unicode_ci_compare(s1, s2):
"""
Perform case-insensitive comparison of two identifiers, using the
recommended algorithm from Unicode Technical Report 36, section
2.11.2(B)(2).
"""
return unicodeda... |
class PasswordResetForm(forms.Form):
that prevent inactive users and users with unusable passwords from
resetting their password.
"""
active_users = UserModel._default_manager.filter(**{
'%s__iexact' % UserModel.get_email_field_name(): email,
'is_active': True,
... | class PasswordResetForm(forms.Form):
that prevent inactive users and users with unusable passwords from
resetting their password.
"""
email_field_name = UserModel.get_email_field_name()
active_users = UserModel._default_manager.filter(**{
'%s__iexact' % email_field_na... |
class PasswordResetForm(forms.Form):
user.
"""
email = self.cleaned_data["email"]
for user in self.get_users(email):
if not domain_override:
current_site = get_current_site(request) | class PasswordResetForm(forms.Form):
user.
"""
email = self.cleaned_data["email"]
email_field_name = UserModel.get_email_field_name()
for user in self.get_users(email):
if not domain_override:
current_site = get_current_site(request) |
class PasswordResetForm(forms.Form):
domain = current_site.domain
else:
site_name = domain = domain_override
context = {
'email': email,
'domain': domain,
'site_name': site_name,
'uid': urlsafe_base64... | class PasswordResetForm(forms.Form):
domain = current_site.domain
else:
site_name = domain = domain_override
user_email = getattr(user, email_field_name)
context = {
'email': user_email,
'domain': domain,
... |
class PasswordResetForm(forms.Form):
}
self.send_mail(
subject_template_name, email_template_name, context, from_email,
email, html_email_template_name=html_email_template_name,
)
| class PasswordResetForm(forms.Form):
}
self.send_mail(
subject_template_name, email_template_name, context, from_email,
user_email, html_email_template_name=html_email_template_name,
)
|
class PasswordResetFormTest(TestDataMixin, TestCase):
self.assertFalse(form.is_valid())
self.assertEqual(form['email'].errors, [_('Enter a valid email address.')])
def test_nonexistent_email(self):
"""
Test nonexistent email address. This should not fail because it would | class PasswordResetFormTest(TestDataMixin, TestCase):
self.assertFalse(form.is_valid())
self.assertEqual(form['email'].errors, [_('Enter a valid email address.')])
def test_user_email_unicode_collision(self):
User.objects.create_user('mike123', 'mike@example.org', 'test123')
User.ob... |
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... |
def test_threading():
@with_setup(pretest, posttest)
def test_bool():
"""Test boolean cast"""
def internal(our_file, disable):
with tqdm(total=10, file=our_file, disable=disable) as t:
assert t
with tqdm(total=0, file=our_file, disable=disable) as t:
assert not t
... | def test_threading():
@with_setup(pretest, posttest)
def test_bool():
"""Test boolean cast"""
def internal(our_file, disable):
with trange(10, file=our_file, disable=disable) as t:
assert t
with trange(0, file=our_file, disable=disable) as t:
assert not t
def ge... |
class LocalFileSystem(FileSystem):
raise RuntimeError('Destination exists: %s' % new_path)
d = os.path.dirname(new_path)
if d and not os.path.exists(d):
self.fs.mkdir(d)
os.rename(old_path, new_path)
| class LocalFileSystem(FileSystem):
raise RuntimeError('Destination exists: %s' % new_path)
d = os.path.dirname(new_path)
if d and not os.path.exists(d):
self.mkdir(d)
os.rename(old_path, new_path)
|
class FileSystemTest(unittest.TestCase):
pass
self.assertTrue([self.path + '/file'], list(self.fs.listdir(self.path + '/')))
class TestImportFile(unittest.TestCase):
| class FileSystemTest(unittest.TestCase):
pass
self.assertTrue([self.path + '/file'], list(self.fs.listdir(self.path + '/')))
def test_move_to_new_dir(self):
# Regression test for a bug in LocalFileSystem.move
src = os.path.join(self.path, 'src.txt')
dest = os.path.join(s... |
from tornado.concurrent import Future
from tornado import gen
from tornado.httpclient import HTTPError, HTTPRequest
from tornado.log import gen_log, app_log
from tornado.testing import AsyncHTTPTestCase, gen_test, bind_unused_port, ExpectLog
from tornado.test.util import unittest, skipBefore35, exec_test
from tornado.w... | from tornado.concurrent import Future
from tornado import gen
from tornado.httpclient import HTTPError, HTTPRequest
from tornado.log import gen_log, app_log
from tornado.template import DictLoader
from tornado.testing import AsyncHTTPTestCase, gen_test, bind_unused_port, ExpectLog
from tornado.test.util import unittest... |
class CoroutineOnMessageHandler(TestWebSocketHandler):
self.write_message(message)
class WebSocketBaseTestCase(AsyncHTTPTestCase):
@gen.coroutine
def ws_connect(self, path, **kwargs): | class CoroutineOnMessageHandler(TestWebSocketHandler):
self.write_message(message)
class RenderMessageHandler(TestWebSocketHandler):
def on_message(self, message):
self.write_message(self.render_string('message.html', message=message))
class WebSocketBaseTestCase(AsyncHTTPTestCase):
@gen.cor... |
class WebSocketTest(WebSocketBaseTestCase):
dict(close_future=self.close_future)),
('/coroutine', CoroutineOnMessageHandler,
dict(close_future=self.close_future)),
])
def test_http_request(self):
# WS server, HTTP client. | class WebSocketTest(WebSocketBaseTestCase):
dict(close_future=self.close_future)),
('/coroutine', CoroutineOnMessageHandler,
dict(close_future=self.close_future)),
('/render', RenderMessageHandler,
dict(close_future=self.close_future)),
], template_... |
class WebSocketTest(WebSocketBaseTestCase):
self.assertEqual(response, u'hello \u00e9')
yield self.close(ws)
@gen_test
def test_error_in_on_message(self):
ws = yield self.ws_connect('/error_in_on_message') | class WebSocketTest(WebSocketBaseTestCase):
self.assertEqual(response, u'hello \u00e9')
yield self.close(ws)
@gen_test
def test_render_message(self):
ws = yield self.ws_connect('/render')
ws.write_message('hello')
response = yield ws.read_message()
self.assertEqu... |
class RequestHandler(object):
self._log()
self._finished = True
self.on_finish()
# Break up a reference cycle between this handler and the
# _ui_module closures to allow for faster GC on CPython.
self.ui = None | class RequestHandler(object):
self._log()
self._finished = True
self.on_finish()
self._break_cycles()
def _break_cycles(self):
# Break up a reference cycle between this handler and the
# _ui_module closures to allow for faster GC on CPython.
self.ui = None |
class WebSocketHandler(tornado.web.RequestHandler):
if not self._on_close_called:
self._on_close_called = True
self.on_close()
def send_error(self, *args, **kwargs):
if self.stream is None: | class WebSocketHandler(tornado.web.RequestHandler):
if not self._on_close_called:
self._on_close_called = True
self.on_close()
self._break_cycles()
def _break_cycles(self):
# WebSocketHandlers call finish() early, but we don't want to
# break up reference... |
def test_overrun(self):
for file in [
"fli_overrun.bin",
"sgi_overrun.bin",
"pcx_overrun.bin",
"pcx_overrun2.bin",
]: | def test_overrun(self):
for file in [
"fli_overrun.bin",
"sgi_overrun.bin",
"sgi_overrun_expandrow.bin",
"sgi_overrun_expandrow2.bin",
"pcx_overrun.bin",
"pcx_overrun2.bin",
]: |
def test_match(stderr):
def test_get_new_command(stderr):
assert get_new_command(Command('git push', stderr=stderr))\
== "git push --set-upstream origin master"
assert get_new_command(Command('git push --quiet', stderr=stderr))\
== "git push --set-upstream origin master --quiet" | def test_match(stderr):
def test_get_new_command(stderr):
assert get_new_command(Command('git push', stderr=stderr))\
== "git push --set-upstream origin master"
assert get_new_command(Command('git push -u origin', stderr=stderr))\
== "git push --set-upstream origin master"
assert get_new_com... |
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
... |
class Progbar(object):
info = ' - %.0fs' % (now - self.start)
if self.verbose == 1:
if (not force and (now - self.last_update) < self.interval and
current < self.target):
return
prev_total_width = self.total_width | class Progbar(object):
info = ' - %.0fs' % (now - self.start)
if self.verbose == 1:
if (not force and (now - self.last_update) < self.interval and
(self.target is not None and current < self.target)):
return
prev_total_width = self.total_width |
from keras import regularizers
def test_progbar():
n = 2
input_arr = np.random.random((n, n, n))
bar = Progbar(n)
for i, arr in enumerate(input_arr):
bar.update(i, list(arr))
| from keras import regularizers
def test_progbar():
n = 2
input_arr = np.random.random((n, n, n))
bar = Progbar(n)
for i, arr in enumerate(input_arr):
bar.update(i, list(arr))
bar = Progbar(None)
for i, arr in enumerate(input_arr):
bar.update(i, list(arr))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.