buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
class ItemTest(unittest.TestCase):
self.assertEqual(E(save='X')['save'], 'X')
self.assertEqual(E(load='X')['load'], 'X')
self.assertEqual(E.fields, {'save': {'default': 'C'},
'load': {'default': 'E'}})
def test_metaclass_multiple_inheritance_without_metaclass(self):
clas... | class ItemTest(unittest.TestCase):
self.assertEqual(E(save='X')['save'], 'X')
self.assertEqual(E(load='X')['load'], 'X')
self.assertEqual(E.fields, {'save': {'default': 'C'},
'load': {'default': 'E'}, 'update': {'default': 'C'}})
def test_metaclass_multiple_inheritance_without_m... |
class ItemTest(unittest.TestCase):
self.assertRaises(KeyError, D, not_allowed='value')
self.assertEqual(D(save='X')['save'], 'X')
self.assertEqual(D.fields, {'save': {'default': 'A'}})
# D class inverted
class E(C, B): pass
self.assertRaises(KeyError, E, not_allowed='v... | class ItemTest(unittest.TestCase):
self.assertRaises(KeyError, D, not_allowed='value')
self.assertEqual(D(save='X')['save'], 'X')
self.assertEqual(D.fields, {'save': {'default': 'A'},
'load': {'default': 'A'}})
# D class inverted
class E(C, B): pass
self.as... |
class TestSortedCorrectedCommandsSequence(object):
settings)
assert set(seq) == {CorrectedCommand('ls', priority=100),
CorrectedCommand('ls', side_effect, 300)} | class TestSortedCorrectedCommandsSequence(object):
settings)
assert set(seq) == {CorrectedCommand('ls', priority=100),
CorrectedCommand('ls', side_effect, 300)}
class TestCorrectedCommand(object):
def test_equality(self):
assert CorrectedCommand('ls', None,... |
from .logs import debug
Command = namedtuple('Command', ('script', 'stdout', 'stderr'))
CorrectedCommand = namedtuple('CorrectedCommand', ('script', 'side_effect', 'priority'))
Rule = namedtuple('Rule', ('name', 'match', 'get_new_command',
'enabled_by_default', 'side_effect',
... | from .logs import debug
Command = namedtuple('Command', ('script', 'stdout', 'stderr'))
Rule = namedtuple('Rule', ('name', 'match', 'get_new_command',
'enabled_by_default', 'side_effect',
'priority', 'requires_output'))
class CorrectedCommand(object):
def __i... |
class SortedCorrectedCommandsSequence(object):
return []
for command in self._commands:
if command.script != first.script or \
command.side_effect != first.side_effect:
return [first, command]
return [first]
def _remove_duplicates... | class SortedCorrectedCommandsSequence(object):
return []
for command in self._commands:
if command != first:
return [first, command]
return [first]
def _remove_duplicates(self, corrected_commands):
"""Removes low-priority duplicates."""
comma... |
class Block(PandasObject):
mask = missing.mask_missing(values, to_replace)
if not mask.any():
if inplace:
return [self]
return [self.copy()]
try:
blocks = self.putmask(mask, value, inplace=inplace)
# Note: it is _not_ the case th... | class Block(PandasObject):
mask = missing.mask_missing(values, to_replace)
try:
blocks = self.putmask(mask, value, inplace=inplace)
# Note: it is _not_ the case that self._can_hold_element(value) |
class TestDataFrameReplace:
)
with pytest.raises(TypeError, match=msg):
df.replace(lambda x: x.strip()) | class TestDataFrameReplace:
)
with pytest.raises(TypeError, match=msg):
df.replace(lambda x: x.strip())
@pytest.mark.parametrize("dtype", ["float", "float64", "int64", "Int64", "boolean"])
@pytest.mark.parametrize("value", [np.nan, pd.NA])
def test_replace_no_replacement_dtypes(... |
import OFS.interfaces
from AccessControl import safe_builtins
from Acquisition import aq_base
from MultiMapping import MultiMapping
from zExceptions import NotFound |
import OFS.interfaces
from AccessControl import safe_builtins
from AccessControl.SecurityManagement import getSecurityManager
from Acquisition import aq_base
from MultiMapping import MultiMapping
from zExceptions import NotFound |
def boboAwareZopeTraverse(object, path_items, econtext):
necessary (bobo-awareness).
"""
request = getattr(econtext, 'request', None)
path_items = list(path_items)
path_items.reverse()
while path_items:
name = path_items.pop()
if name == '_':
warnings.warn('Traversi... | def boboAwareZopeTraverse(object, path_items, econtext):
necessary (bobo-awareness).
"""
request = getattr(econtext, 'request', None)
validate = getSecurityManager().validate
path_items = list(path_items)
path_items.reverse()
while path_items:
name = path_items.pop()
if OFS... |
from chameleon.tales import NotExpr
from chameleon.tales import StringExpr
from AccessControl.ZopeGuards import guarded_apply
from AccessControl.ZopeGuards import guarded_getattr
from AccessControl.ZopeGuards import guarded_getitem | from chameleon.tales import NotExpr
from chameleon.tales import StringExpr
from AccessControl.SecurityManagement import getSecurityManager
from AccessControl.ZopeGuards import guarded_apply
from AccessControl.ZopeGuards import guarded_getattr
from AccessControl.ZopeGuards import guarded_getitem |
class BoboAwareZopeTraverse:
def traverse(cls, base, request, path_items):
"""See ``zope.app.pagetemplate.engine``."""
path_items = list(path_items)
path_items.reverse()
while path_items:
name = path_items.pop()
if name == '_':
warnings.warn... | class BoboAwareZopeTraverse:
def traverse(cls, base, request, path_items):
"""See ``zope.app.pagetemplate.engine``."""
validate = getSecurityManager().validate
path_items = list(path_items)
path_items.reverse()
while path_items:
name = path_items.pop()
... |
from AccessControl import safe_builtins
from zExceptions import NotFound
from zope.component.testing import PlacelessSetup
class EngineTestsBase(PlacelessSetup): | from AccessControl import safe_builtins
from zExceptions import NotFound
from zope.component.testing import PlacelessSetup
from zope.location.interfaces import LocationError
class EngineTestsBase(PlacelessSetup): |
def test_underscore_traversal(self):
with self.assertRaises(NotFound):
ec.evaluate("context/__class__")
with self.assertRaises(NotFound):
ec.evaluate("nocall: random/_itertools/repeat")
with self.assertRaises(NotFound):
ec.evaluate("random/_itertools/repeat/... | def test_underscore_traversal(self):
with self.assertRaises(NotFound):
ec.evaluate("context/__class__")
with self.assertRaises((NotFound, LocationError)):
ec.evaluate("nocall: random/_itertools/repeat")
with self.assertRaises((NotFound, LocationError)):
ec.e... |
DefaultUnicodeEncodingConflictResolver
from Products.PageTemplates.unicodeconflictresolver import \
PreferredCharsetResolver
from zExceptions import NotFound
from zope.component import provideUtility
from zope.traversing.adapters import DefaultTraversable
from .util import useChameleonEngine | DefaultUnicodeEncodingConflictResolver
from Products.PageTemplates.unicodeconflictresolver import \
PreferredCharsetResolver
from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
from zExceptions import NotFound
from zope.component import provideUtility
from zope.location.interfaces import Locati... |
class AqPageTemplate(Implicit, PageTemplate):
pass
class Folder(util.Base):
pass
| class AqPageTemplate(Implicit, PageTemplate):
pass
class AqZopePageTemplate(Implicit, ZopePageTemplate):
pass
class Folder(util.Base):
pass
|
def setUp(self):
self.folder = f = Folder()
f.laf = AqPageTemplate()
f.t = AqPageTemplate()
self.policy = UnitTestSecurityPolicy()
self.oldPolicy = SecurityManager.setSecurityPolicy(self.policy)
noSecurityManager() # Use the new policy. | def setUp(self):
self.folder = f = Folder()
f.laf = AqPageTemplate()
f.t = AqPageTemplate()
f.z = AqZopePageTemplate('testing')
self.policy = UnitTestSecurityPolicy()
self.oldPolicy = SecurityManager.setSecurityPolicy(self.policy)
noSecurityManager() # Use the ne... |
def test_underscore_traversal(self):
t()
t.write('<p tal:define="p nocall: random/_itertools/repeat"/>')
with self.assertRaises(NotFound):
t()
t.write('<p tal:content="random/_itertools/repeat/foobar"/>')
with self.assertRaises(NotFound):
t() | def test_underscore_traversal(self):
t()
t.write('<p tal:define="p nocall: random/_itertools/repeat"/>')
with self.assertRaises((NotFound, LocationError)):
t()
t.write('<p tal:content="random/_itertools/repeat/foobar"/>')
with self.assertRaises((NotFound, Locati... |
def to_categorical(y, num_classes=None):
"""
y = np.array(y, dtype='int')
input_shape = y.shape
y = y.ravel()
if not num_classes:
num_classes = np.max(y) + 1 | def to_categorical(y, num_classes=None):
"""
y = np.array(y, dtype='int')
input_shape = y.shape
if input_shape and input_shape[-1] == 1:
input_shape = tuple(input_shape[:-1])
y = y.ravel()
if not num_classes:
num_classes = np.max(y) + 1 |
from keras.utils import to_categorical
def test_to_categorical():
num_classes = 5
shapes = [(3,), (4, 3), (5, 4, 3)]
labels = [np.random.randint(0, num_classes, shape) for shape in shapes]
one_hots = [to_categorical(label, num_classes) for label in labels]
for label, one_hot in zip(labels, one_hots... | from keras.utils import to_categorical
def test_to_categorical():
num_classes = 5
shapes = [(3,), (4, 3), (5, 4, 3), (3, 1), (3, 2, 1)]
expected_shapes = [(3, num_classes),
(4, 3, num_classes),
(5, 4, 3, num_classes),
(3, num_classes)]
... |
class TupleParameter(ListParameter):
try:
# loop required to parse tuple of tuples
return tuple(tuple(x) for x in json.loads(x, object_pairs_hook=_FrozenOrderedDict))
except ValueError:
return literal_eval(x) # if this causes an error, let that error be raised.
cla... | class TupleParameter(ListParameter):
try:
# loop required to parse tuple of tuples
return tuple(tuple(x) for x in json.loads(x, object_pairs_hook=_FrozenOrderedDict))
except (ValueError, TypeError):
return tuple(literal_eval(x)) # if this causes an error, let that er... |
class TestTaskParameter(LuigiTestCase):
self.assertTrue(self.run_locally(['MainTask']))
class NewStyleParameters822Test(LuigiTestCase):
"""
I bet these tests created at 2015-03-08 are reduntant by now (Oct 2015). | class TestTaskParameter(LuigiTestCase):
self.assertTrue(self.run_locally(['MainTask']))
class TestSerializeTupleParameter(LuigiTestCase):
def testSerialize(self):
the_tuple = (1, 2, 3)
self.assertEqual(luigi.TupleParameter().parse(luigi.TupleParameter().serialize(the_tuple)), the_tuple)
... |
import securesystemslib.util
import six
import iso8601
# The Timestamp role does not have signed metadata about it; otherwise we
# would need an infinite regress of metadata. Therefore, we use some | import securesystemslib.util
import six
import iso8601
import requests.exceptions
# The Timestamp role does not have signed metadata about it; otherwise we
# would need an infinite regress of metadata. Therefore, we use some |
def _update_root_metadata(self, current_root_metadata):
None.
"""
# Retrieve the latest, remote root.json.
latest_root_metadata_file = self._get_metadata_file(
'root', 'root.json', DEFAULT_ROOT_UPPERLENGTH, None)
latest_root_metadata = securesystemslib.util.load_json_string(
late... | def _update_root_metadata(self, current_root_metadata):
None.
"""
def neither_403_nor_404(mirror_error):
if isinstance(mirror_error, requests.exceptions.HTTPError):
if mirror_error.response.status_code in {403, 404}:
return False
return True
# Temporarily set consistent... |
# to suspend execution for a specified amount of time. See
# theupdateframework/tuf/issue#338.
SLEEP_BEFORE_ROUND = None | # to suspend execution for a specified amount of time. See
# theupdateframework/tuf/issue#338.
SLEEP_BEFORE_ROUND = None
# Maximum number of root metadata file rotations we should perform in order to
# prevent a denial-of-service (DoS) attack.
MAX_NUMBER_ROOT_ROTATIONS = 2**5 |
def format_str(src_contents: str, line_length: int) -> FileContent:
return dst_contents
def lib2to3_parse(src_txt: str) -> Node:
"""Given a string with source, return the lib2to3 Node."""
grammar = pygram.python_grammar_no_print_statement
drv = driver.Driver(grammar, pytree.convert)
if src_txt[-1]... | def format_str(src_contents: str, line_length: int) -> FileContent:
return dst_contents
GRAMMARS = [
pygram.python_grammar_no_print_statement_no_exec_statement,
pygram.python_grammar_no_print_statement,
pygram.python_grammar_no_exec_statement,
pygram.python_grammar,
]
def lib2to3_parse(src_txt: ... |
def whitespace(leaf: Leaf) -> str: # noqa C901
):
return NO
elif prev.type in OPENING_BRACKETS:
return NO
| def whitespace(leaf: Leaf) -> str: # noqa C901
):
return NO
elif (
prevp.type == token.RIGHTSHIFT
and prevp.parent
and prevp.parent.type == syms.shift_expr
and prevp.prev_sibling
and prevp.prev_sibling.type == token.NAME
... |
def assert_equivalent(src: str, dst: str) -> None:
try:
src_ast = ast.parse(src)
except Exception as exc:
raise AssertionError(f"cannot parse source: {exc}") from None
try:
dst_ast = ast.parse(dst) | def assert_equivalent(src: str, dst: str) -> None:
try:
src_ast = ast.parse(src)
except Exception as exc:
major, minor = sys.version_info[:2]
raise AssertionError(
f"cannot use --safe with this file; failed to parse source file "
f"with Python {major}.{minor}'s bu... |
python_symbols = Symbols(python_grammar)
python_grammar_no_print_statement = python_grammar.copy()
del python_grammar_no_print_statement.keywords["print"]
pattern_grammar = driver.load_packaged_grammar("blib2to3", _PATTERN_GRAMMAR_FILE)
pattern_symbols = Symbols(pattern_grammar) | python_symbols = Symbols(python_grammar)
python_grammar_no_print_statement = python_grammar.copy()
del python_grammar_no_print_statement.keywords["print"]
python_grammar_no_exec_statement = python_grammar.copy()
del python_grammar_no_exec_statement.keywords["exec"]
python_grammar_no_print_statement_no_exec_statement ... |
def func_no_args():
for i in range(10):
print(i)
continue
return None
async def coroutine(arg):
"Single-line docstring. Multiline is harder to reformat."
async with some_connection() as conn:
await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', timeout=2) | def func_no_args():
for i in range(10):
print(i)
continue
exec("new-style exec", {}, {})
return None
async def coroutine(arg, exec=False):
"Single-line docstring. Multiline is harder to reformat."
async with some_connection() as conn:
await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', time... |
def func_no_args():
print(i)
continue
return None
async def coroutine(arg):
"Single-line docstring. Multiline is harder to reformat."
async with some_connection() as conn:
await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', timeout=2) | def func_no_args():
print(i)
continue
exec("new-style exec", {}, {})
return None
async def coroutine(arg, exec=False):
"Single-line docstring. Multiline is harder to reformat."
async with some_connection() as conn:
await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', ti... |
class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, line_length=ll)
def test_report(self) -> None:
report = black.Report()
out_lines = [] | class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, line_length=ll)
@patch("black.dump_to_file", dump_to_stderr)
def test_python2(self) -> None:
source, expected = read_data('python2')
actual = fs(source)
se... |
from youtube_dl.utils import (
limit_length,
escape_rfc3986,
escape_url,
)
| from youtube_dl.utils import (
limit_length,
escape_rfc3986,
escape_url,
js_to_json,
)
|
class TestUtil(unittest.TestCase):
)
self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
if __name__ == '__main__':
unittest.main() | class TestUtil(unittest.TestCase):
)
self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
def test_js_to_json(self):
inp = '''{
'clip':{'provider':'pseudo'}
}'''
self.assertEqual(js_to_json(inp), '''{
... |
class ExtractorError(Exception):
expected = True
if video_id is not None:
msg = video_id + ': ' + msg
if not expected:
msg = msg + u'; please report this issue on https://yt-dl.org/bug . Be sure to call youtube-dl with the --verbose flag and include its complete outpu... | class ExtractorError(Exception):
expected = True
if video_id is not None:
msg = video_id + ': ' + msg
if cause:
msg += u' (caused by %r)' % cause
if not expected:
msg = msg + u'; please report this issue on https://yt-dl.org/bug . Be sure to call y... |
def js_to_json(code):
([{,]\s*)
("[^"]*"|\'[^\']*\'|[a-z0-9A-Z]+)
(:\s*)
([0-9.]+|true|false|"[^"]*"|\'[^\']*\'|\[|\{)
''', fix_kv, code)
res = re.sub(r',(\s*\])', lambda m: m.group(1), res)
return res | def js_to_json(code):
([{,]\s*)
("[^"]*"|\'[^\']*\'|[a-z0-9A-Z]+)
(:\s*)
([0-9.]+|true|false|"[^"]*"|\'[^\']*\'|
(?=\[|\{)
)
''', fix_kv, code)
res = re.sub(r',(\s*\])', lambda m: m.group(1), res)
return res |
def array_equivalent(left, right, strict_nan=False):
if not isinstance(right_value, float) or not np.isnan(right_value):
return False
else:
if left_value != right_value:
return False
return True
| def array_equivalent(left, right, strict_nan=False):
if not isinstance(right_value, float) or not np.isnan(right_value):
return False
else:
if np.any(left_value != right_value):
return False
return True
|
def test_array_equivalent_str():
)
@pytest.mark.parametrize(
"dtype, na_value",
[ | def test_array_equivalent_str():
)
def test_array_equivalent_nested():
# reached in groupby aggregations, make sure we use np.any when checking
# if the comparison is truthy
left = np.array([np.array([50, 70, 90]), np.array([20, 30, 40])], dtype=object)
right = np.array([np.array([50, 70, 90]... |
ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
<p begin="3" dur="-1">Ignored, three</p>
</div>
</body>
</tt>'''
srt_data = '''1
00:00:00,000 --> 00:00:01,000
The following line contains Chinese characters and special symbols | ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
<p begin="3" dur="-1">Ignored, three</p>
</div>
</body>
</tt>'''.encode('utf-8')
srt_data = '''1
00:00:00,000 --> 00:00:01,000
The following line contains Chinese characters and ... |
Line
<p begin="0" end="1">The first line</p>
</div>
</body>
</tt>'''
srt_data = '''1
00:00:00,000 --> 00:00:01,000
The first line | Line
<p begin="0" end="1">The first line</p>
</div>
</body>
</tt>'''.encode('utf-8')
srt_data = '''1
00:00:00,000 --> 00:00:01,000
The first line |
The first line
<p style="s1" tts:textDecoration="underline" begin="00:00:09.56" id="p2" end="00:00:12.36"><span style="s2" tts:color="lime">inner<br /> </span>style</p>
</div>
</body>
</tt>'''
srt_data = '''1
00:00:02,080 --> 00:00:05,839
<font color="white" face="sansSerif" size="16">default style<... | The first line
<p style="s1" tts:textDecoration="underline" begin="00:00:09.56" id="p2" end="00:00:12.36"><span style="s2" tts:color="lime">inner<br /> </span>style</p>
</div>
</body>
</tt>'''.encode('utf-8')
srt_data = '''1
00:00:02,080 --> 00:00:05,839
<font color="white" face="sansSerif" size="16... |
part 3</font></u>
'''
self.assertEqual(dfxp2srt(dfxp_data_with_style), srt_data)
def test_cli_option(self):
self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), []) | part 3</font></u>
'''
self.assertEqual(dfxp2srt(dfxp_data_with_style), srt_data)
dfxp_data_non_utf8 = '''<?xml version="1.0" encoding="UTF-16"?>
<tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
<body>
<div xml:l... |
class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
dfxp_file = old_file
srt_file = subtitles_filename(filename, lang, 'srt')
with io.open(dfxp_file, 'rt', encoding='utf-8') as f:
srt_data = dfxp2srt(f.read())
with io.open(srt_file... | class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
dfxp_file = old_file
srt_file = subtitles_filename(filename, lang, 'srt')
with open(dfxp_file, 'rb') as f:
srt_data = dfxp2srt(f.read())
with io.open(srt_file, 'wt', encoding='utf... |
def srt_subtitles_timecode(seconds):
def dfxp2srt(dfxp_data):
LEGACY_NAMESPACES = (
('http://www.w3.org/ns/ttml', [
'http://www.w3.org/2004/11/ttaf1',
'http://www.w3.org/2006/04/ttaf1',
'http://www.w3.org/2006/10/ttaf1',
]),
('http://www.w3.org/ns/ttml#s... | def srt_subtitles_timecode(seconds):
def dfxp2srt(dfxp_data):
'''
@param dfxp_data A bytes-like object containing DFXP data
@returns A unicode object containing converted SRT data
'''
LEGACY_NAMESPACES = (
(b'http://www.w3.org/ns/ttml', [
b'http://www.w3.org/2004/11/ttaf1',
... |
def dfxp2srt(dfxp_data):
for ns in v:
dfxp_data = dfxp_data.replace(ns, k)
dfxp = compat_etree_fromstring(dfxp_data.encode('utf-8'))
out = []
paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall('.//p')
| def dfxp2srt(dfxp_data):
for ns in v:
dfxp_data = dfxp_data.replace(ns, k)
dfxp = compat_etree_fromstring(dfxp_data)
out = []
paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall('.//p')
|
class TestUtil(unittest.TestCase):
self.assertEqual(unescapeHTML('/'), '/')
self.assertEqual(unescapeHTML('é'), 'é')
self.assertEqual(unescapeHTML('�'), '�')
# HTML5 entities
self.assertEqual(unescapeHTML('.''), '.\'')
| class TestUtil(unittest.TestCase):
self.assertEqual(unescapeHTML('/'), '/')
self.assertEqual(unescapeHTML('é'), 'é')
self.assertEqual(unescapeHTML('�'), '�')
self.assertEqual(unescapeHTML('&a"'), '&a"')
# HTML5 entities
self.assertE... |
def unescapeHTML(s):
assert type(s) == compat_str
return re.sub(
r'&([^;]+;)', lambda m: _htmlentity_transform(m.group(1)), s)
def get_subprocess_encoding(): | def unescapeHTML(s):
assert type(s) == compat_str
return re.sub(
r'&([^&;]+;)', lambda m: _htmlentity_transform(m.group(1)), s)
def get_subprocess_encoding(): |
def get_user_roles(self, context, user_id, tenant_id=None):
not implementing them in hopes that the idea will die off.
"""
if tenant_id is None:
raise exception.NotImplemented(message='User roles not supported: '
'tenant ID required... | def get_user_roles(self, context, user_id, tenant_id=None):
not implementing them in hopes that the idea will die off.
"""
self.assert_admin(context)
if tenant_id is None:
raise exception.NotImplemented(message='User roles not supported: '
... |
def test_service_crud_requires_auth(self):
expected_status=401)
self.assertValidErrorResponse(r)
class XmlTestCase(RestfulTestCase, CoreApiTests):
xmlns = 'http://docs.openstack.org/identity/api/v2.0' | def test_service_crud_requires_auth(self):
expected_status=401)
self.assertValidErrorResponse(r)
def test_user_role_list_requires_auth(self):
"""User role list should 401 without an X-Auth-Token (bug 1006815)."""
# values here don't matter because we should 40... |
class TestUtil(unittest.TestCase):
self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
def test_strip_jsonp(self):
stripped... | class TestUtil(unittest.TestCase):
self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
self.assertEqual(parse_iso8601('2014-03-2... |
from __future__ import unicode_literals
import re
from .subtitles import SubtitlesInfoExtractor
from .common import ExtractorError
from ..utils import parse_iso8601 | from __future__ import unicode_literals
from .subtitles import SubtitlesInfoExtractor
from .common import ExtractorError
from ..utils import parse_iso8601 |
class DRTVIE(SubtitlesInfoExtractor):
}
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
video_id = mobj.group('id')
programcard = self._download_json(
'http://www.dr.dk/mu/programcard/expanded/%s' % video_id, video_id, 'Downloading video JSON') | class DRTVIE(SubtitlesInfoExtractor):
}
def _real_extract(self, url):
video_id = self._match_id(url)
programcard = self._download_json(
'http://www.dr.dk/mu/programcard/expanded/%s' % video_id, video_id, 'Downloading video JSON') |
class DRTVIE(SubtitlesInfoExtractor):
title = data['Title']
description = data['Description']
timestamp = parse_iso8601(data['CreatedTime'][:-5])
thumbnail = None
duration = None | class DRTVIE(SubtitlesInfoExtractor):
title = data['Title']
description = data['Description']
timestamp = parse_iso8601(data['CreatedTime'])
thumbnail = None
duration = None |
def parse_iso8601(date_str, delimiter='T'):
return None
m = re.search(
r'Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$',
date_str)
if not m:
timezone = datetime.timedelta() | def parse_iso8601(date_str, delimiter='T'):
return None
m = re.search(
r'(\.[0-9]+)?(?:Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
date_str)
if not m:
timezone = datetime.timedelta() |
def parse_iso8601(date_str, delimiter='T'):
timezone = datetime.timedelta(
hours=sign * int(m.group('hours')),
minutes=sign * int(m.group('minutes')))
date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
dt = datetime.datetime.strptime(date_str, date_format) - timez... | def parse_iso8601(date_str, delimiter='T'):
timezone = datetime.timedelta(
hours=sign * int(m.group('hours')),
minutes=sign * int(m.group('minutes')))
date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
dt = datetime.datetime.strptime(date_str, date_format) - timezo... |
from contextlib import contextmanager
import pytest
from mock import Mock
from thefuck.utils import wrap_settings, \
memoize, get_closest, get_all_executables, replace_argument, \
get_all_matched_commands, is_app, for_app, cache | import pytest
from mock import Mock
import six
from thefuck.utils import wrap_settings, \
memoize, get_closest, get_all_executables, replace_argument, \
get_all_matched_commands, is_app, for_app, cache |
class TestCache(object):
def shelve(self, mocker):
value = {}
@contextmanager
def _shelve(path):
yield value
mocker.patch('thefuck.utils.shelve.open', new_callable=lambda: _shelve)
return value
@pytest.fixture(autouse=True) | class TestCache(object):
def shelve(self, mocker):
value = {}
class _Shelve(object):
def __init__(self, path):
pass
def __setitem__(self, k, v):
value[k] = v
def __getitem__(self, k):
return value[k]
... |
class TestCache(object):
return fn
def test_with_blank_cache(self, shelve, fn):
assert shelve == {}
assert fn() == 'test'
assert shelve == {
'tests.test_utils.<function TestCache.fn.<locals>.fn ': {
'etag': '0', 'value': 'test'}}
def test_with_fille... | class TestCache(object):
return fn
@pytest.fixture
def key(self):
if six.PY3:
return 'tests.test_utils.<function TestCache.fn.<locals>.fn '
else:
return 'tests.test_utils.<function fn '
def test_with_blank_cache(self, shelve, fn, key):
assert shelve... |
from difflib import get_close_matches
from functools import wraps
import shelve
from decorator import decorator
import tempfile
import os | from difflib import get_close_matches
from functools import wraps
import shelve
from decorator import decorator
from contextlib import closing
import tempfile
import os |
def cache(*depends_on):
return fn(*args, **kwargs)
cache_path = os.path.join(tempfile.gettempdir(), '.thefuck-cache')
key = '{}.{}'.format(fn.__module__, repr(fn).split('at')[0])
etag = '.'.join(_get_mtime(name) for name in depends_on)
with shelve.open(cache_path) as db:
... | def cache(*depends_on):
return fn(*args, **kwargs)
cache_path = os.path.join(tempfile.gettempdir(), '.thefuck-cache')
# A bit obscure, but simplest way to generate unique key for
# functions and methods in python 2 and 3:
key = '{}.{}'.format(fn.__module__, repr(fn).split('a... |
def _parse_octet(cls, octet_str):
raise ValueError(msg % octet_str)
# Convert to integer (we know digits are legal)
octet_int = int(octet_str, 10)
# Any octets that look like they *might* be written in octal,
# and which don't look exactly the same in both octal and
#... | def _parse_octet(cls, octet_str):
raise ValueError(msg % octet_str)
# Convert to integer (we know digits are legal)
octet_int = int(octet_str, 10)
if octet_int > 255:
raise ValueError("Octet %d (> 255) not permitted" % octet_int)
return octet_int |
def pickle_test(self, addr):
y = pickle.loads(pickle.dumps(x, proto))
self.assertEqual(y, x)
class CommonTestMixin_v4(CommonTestMixin):
def test_leading_zeros(self):
self.assertInstancesEqual("000.000.000.000", "0.0.0.0")
self.assertInstancesEqual("192.168.000.001",... | def pickle_test(self, addr):
y = pickle.loads(pickle.dumps(x, proto))
self.assertEqual(y, x)
class CommonTestMixin_v4(CommonTestMixin):
def test_leading_zeros(self):
self.assertInstancesEqual("000.000.000.000", "0.0.0.0")
self.assertInstancesEqual("192.168.000.001"... |
def assertBadOctet(addr, octet):
assertBadOctet("1.2.3.4::", "4::")
assertBadOctet("1.a.2.3", "a")
def test_octal_decimal_ambiguity(self):
def assertBadOctet(addr, octet):
msg = "Ambiguous (octal/decimal) value in %r not permitted in %r"
with self.assertAddressError(... | def assertBadOctet(addr, octet):
assertBadOctet("1.2.3.4::", "4::")
assertBadOctet("1.a.2.3", "a")
def test_octet_length(self):
def assertBadOctet(addr, octet):
msg = "At most 3 characters permitted in %r in %r" |
def diff(arr, n: int, axis: int = 0):
dtype = arr.dtype
is_timedelta = False
if needs_i8_conversion(arr):
dtype = np.float64
arr = arr.view("i8") | def diff(arr, n: int, axis: int = 0):
dtype = arr.dtype
is_timedelta = False
is_bool = False
if needs_i8_conversion(arr):
dtype = np.float64
arr = arr.view("i8") |
def diff(arr, n: int, axis: int = 0):
elif is_bool_dtype(dtype):
dtype = np.object_
elif is_integer_dtype(dtype):
dtype = np.float64 | def diff(arr, n: int, axis: int = 0):
elif is_bool_dtype(dtype):
dtype = np.object_
is_bool = True
elif is_integer_dtype(dtype):
dtype = np.float64 |
def diff(arr, n: int, axis: int = 0):
result = res - lag
result[mask] = na
out_arr[res_indexer] = result
else:
out_arr[res_indexer] = arr[res_indexer] - arr[lag_indexer]
| def diff(arr, n: int, axis: int = 0):
result = res - lag
result[mask] = na
out_arr[res_indexer] = result
elif is_bool:
out_arr[res_indexer] = arr[res_indexer] ^ arr[lag_indexer]
else:
out_arr[res_indexer] = arr[res_indexer] - arr[lag_indexer]
|
from pandas import (
from pandas.api.types import is_scalar
from pandas.core.index import MultiIndex
from pandas.core.indexes.datetimes import Timestamp
import pandas.util.testing as tm
from pandas.util.testing import (
assert_almost_equal, | from pandas import (
from pandas.api.types import is_scalar
from pandas.core.index import MultiIndex
from pandas.core.indexes.datetimes import Timestamp
from pandas.core.indexes.timedeltas import TimedeltaIndex
import pandas.util.testing as tm
from pandas.util.testing import (
assert_almost_equal, |
class TestSeriesAnalytics:
result = s.cummax(skipna=False)
tm.assert_series_equal(expected, result)
def test_npdiff(self):
pytest.skip("skipping due to Series no longer being an ndarray")
# no longer works as the return type of np.diff is now nd.array | class TestSeriesAnalytics:
result = s.cummax(skipna=False)
tm.assert_series_equal(expected, result)
def test_np_diff(self):
pytest.skip("skipping due to Series no longer being an ndarray")
# no longer works as the return type of np.diff is now nd.array |
class TestSeriesAnalytics:
r = np.diff(s)
assert_series_equal(Series([nan, 0, 0, 0, nan]), r)
def _check_accum_op(self, name, datetime_series_, check_dtype=True):
func = getattr(np, name)
tm.assert_numpy_array_equal( | class TestSeriesAnalytics:
r = np.diff(s)
assert_series_equal(Series([nan, 0, 0, 0, nan]), r)
def test_int_diff(self):
# int dtype
a = 10000000000000000
b = a + 1
s = Series([a, b])
result = s.diff()
assert result[1] == 1
def test_tz_diff(self):... |
class TestTimeSeries(TestData):
)
tm.assert_index_equal(expected.index, result.index)
def test_diff(self):
# Just run the function
self.ts.diff()
# int dtype
a = 10000000000000000
b = a + 1
s = Series([a, b])
rs = s.diff()
assert rs[... | class TestTimeSeries(TestData):
)
tm.assert_index_equal(expected.index, result.index)
def test_pct_change(self):
rs = self.ts.pct_change(fill_method=None)
assert_series_equal(rs, self.ts / self.ts.shift(1) - 1) |
class DatabaseOperations(BaseDatabaseOperations):
return f"EXTRACT({lookup_type} FROM {sql})", params
def date_trunc_sql(self, lookup_type, sql, params, tzname=None):
sql, params = self._convert_field_to_tz(sql, params, tzname)
fields = {
"year": "%Y-01-01",
"mon... | class DatabaseOperations(BaseDatabaseOperations):
return f"EXTRACT({lookup_type} FROM {sql})", params
def date_trunc_sql(self, lookup_type, sql, params, tzname=None):
sql, params = self._convert_sql_to_tz(sql, params, tzname)
fields = {
"year": "%Y-01-01",
"month... |
class DatabaseOperations(BaseDatabaseOperations):
tzname, sign, offset = split_tzname_delta(tzname)
return f"{sign}{offset}" if offset else tzname
def _convert_field_to_tz(self, sql, params, tzname):
if tzname and settings.USE_TZ and self.connection.timezone_name != tzname:
retu... | class DatabaseOperations(BaseDatabaseOperations):
tzname, sign, offset = split_tzname_delta(tzname)
return f"{sign}{offset}" if offset else tzname
def _convert_sql_to_tz(self, sql, params, tzname):
if tzname and settings.USE_TZ and self.connection.timezone_name != tzname:
return... |
class DatabaseOperations(BaseDatabaseOperations):
return sql, params
def datetime_cast_date_sql(self, sql, params, tzname):
sql, params = self._convert_field_to_tz(sql, params, tzname)
return f"DATE({sql})", params
def datetime_cast_time_sql(self, sql, params, tzname):
sql, par... | class DatabaseOperations(BaseDatabaseOperations):
return sql, params
def datetime_cast_date_sql(self, sql, params, tzname):
sql, params = self._convert_sql_to_tz(sql, params, tzname)
return f"DATE({sql})", params
def datetime_cast_time_sql(self, sql, params, tzname):
sql, param... |
class DatabaseOperations(BaseDatabaseOperations):
return sql, params
def time_trunc_sql(self, lookup_type, sql, params, tzname=None):
sql, params = self._convert_field_to_tz(sql, params, tzname)
fields = {
"hour": "%H:00:00",
"minute": "%H:%i:00", | class DatabaseOperations(BaseDatabaseOperations):
return sql, params
def time_trunc_sql(self, lookup_type, sql, params, tzname=None):
sql, params = self._convert_sql_to_tz(sql, params, tzname)
fields = {
"hour": "%H:00:00",
"minute": "%H:%i:00", |
END;
return extract_sql, (*params, extract_param)
def date_trunc_sql(self, lookup_type, sql, params, tzname=None):
sql, params = self._convert_field_to_tz(sql, params, tzname)
# https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/ROUND-and-TRUNC-Date-Functions.html
t... | END;
return extract_sql, (*params, extract_param)
def date_trunc_sql(self, lookup_type, sql, params, tzname=None):
sql, params = self._convert_sql_to_tz(sql, params, tzname)
# https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/ROUND-and-TRUNC-Date-Functions.html
tru... |
END;
tzname, sign, offset = split_tzname_delta(tzname)
return f"{sign}{offset}" if offset else tzname
def _convert_field_to_tz(self, sql, params, tzname):
if not (settings.USE_TZ and tzname):
return sql, params
if not self._tzname_re.match(tzname): | END;
tzname, sign, offset = split_tzname_delta(tzname)
return f"{sign}{offset}" if offset else tzname
def _convert_sql_to_tz(self, sql, params, tzname):
if not (settings.USE_TZ and tzname):
return sql, params
if not self._tzname_re.match(tzname): |
END;
return sql, params
def datetime_cast_date_sql(self, sql, params, tzname):
sql, params = self._convert_field_to_tz(sql, params, tzname)
return f"TRUNC({sql})", params
def datetime_cast_time_sql(self, sql, params, tzname):
# Since `TimeField` values are stored as TIMESTAMP c... | END;
return sql, params
def datetime_cast_date_sql(self, sql, params, tzname):
sql, params = self._convert_sql_to_tz(sql, params, tzname)
return f"TRUNC({sql})", params
def datetime_cast_time_sql(self, sql, params, tzname):
# Since `TimeField` values are stored as TIMESTAMP cha... |
END;
)
def datetime_extract_sql(self, lookup_type, sql, params, tzname):
sql, params = self._convert_field_to_tz(sql, params, tzname)
return self.date_extract_sql(lookup_type, sql, params)
def datetime_trunc_sql(self, lookup_type, sql, params, tzname):
sql, params = self._conve... | END;
)
def datetime_extract_sql(self, lookup_type, sql, params, tzname):
sql, params = self._convert_sql_to_tz(sql, params, tzname)
return self.date_extract_sql(lookup_type, sql, params)
def datetime_trunc_sql(self, lookup_type, sql, params, tzname):
sql, params = self._convert... |
END;
# The implementation is similar to `datetime_trunc_sql` as both
# `DateTimeField` and `TimeField` are stored as TIMESTAMP where
# the date part of the later is ignored.
sql, params = self._convert_field_to_tz(sql, params, tzname)
trunc_param = None
if lookup_type == ... | END;
# The implementation is similar to `datetime_trunc_sql` as both
# `DateTimeField` and `TimeField` are stored as TIMESTAMP where
# the date part of the later is ignored.
sql, params = self._convert_sql_to_tz(sql, params, tzname)
trunc_param = None
if lookup_type == "h... |
from pandas.core.internals.construction import (
sanitize_index,
to_arrays,
)
from pandas.core.series import Series
from pandas.io.formats import console, format as fmt | from pandas.core.internals.construction import (
sanitize_index,
to_arrays,
)
from pandas.core.ops.missing import dispatch_fill_zeros
from pandas.core.series import Series
from pandas.io.formats import console, format as fmt |
class DataFrame(NDFrame):
# iterate over columns
return ops.dispatch_to_series(this, other, _arith_op)
else:
result = _arith_op(this.values, other.values)
return self._constructor(
result, index=new_index, columns=new_columns, copy=False
... | class DataFrame(NDFrame):
# iterate over columns
return ops.dispatch_to_series(this, other, _arith_op)
else:
with np.errstate(all="ignore"):
result = _arith_op(this.values, other.values)
result = dispatch_fill_zeros(func, this.values, other.values,... |
class TestNumericArithmeticUnsorted:
tm.assert_index_equal(index + index, 2 * index)
tm.assert_index_equal(index - index, 0 * index)
assert not (index - index).empty | class TestNumericArithmeticUnsorted:
tm.assert_index_equal(index + index, 2 * index)
tm.assert_index_equal(index - index, 0 * index)
assert not (index - index).empty
def test_fill_value_inf_masking():
# GH #27464 make sure we mask 0/1 with Inf and not NaN
df = pd.DataFrame({"A": [0, 1,... |
def generate_context(
context = OrderedDict([])
try:
with open(context_file) as file_handle:
obj = json.load(file_handle, object_pairs_hook=OrderedDict)
except ValueError as e:
# JSON decoding error. Let's throw a new exception that is more | def generate_context(
context = OrderedDict([])
try:
with open(context_file, encoding='utf-8') as file_handle:
obj = json.load(file_handle, object_pairs_hook=OrderedDict)
except ValueError as e:
# JSON decoding error. Let's throw a new exception that is more |
def test_default_context_replacement_in_generate_context():
assert generated_context == expected_context
@pytest.fixture
def template_context():
"""Fixture. Populates template content for future tests.""" | def test_default_context_replacement_in_generate_context():
assert generated_context == expected_context
def test_generate_context_decodes_non_ascii_chars():
"""Verify `generate_context` correctly decodes non-ascii chars."""
expected_context = {'non_ascii': OrderedDict([('full_name', 'éèà'),])}
gener... |
def gendata4():
data = [gendata1(), gendata2(), gendata4()]
class TestAudioop(unittest.TestCase):
| def gendata4():
data = [gendata1(), gendata2(), gendata4()]
INVALID_DATA = [
('abc', 0),
('abc', 2),
('abc', 4),
]
class TestAudioop(unittest.TestCase):
|
def test_negativelen(self):
self.assertRaises(audioop.error,
audioop.findmax, ''.join(chr(x) for x in range(256)), -2392392)
def test_main():
run_unittest(TestAudioop)
| def test_negativelen(self):
self.assertRaises(audioop.error,
audioop.findmax, ''.join(chr(x) for x in range(256)), -2392392)
def test_issue7673(self):
state = None
for data, size in INVALID_DATA:
size2 = size
self.assertRaises(audioop.error, audioop.getsa... |
# -*- 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
|
import salt.utils.json
import salt.utils.stringutils
import salt.utils.url
import salt.utils.yaml
from jinja2 import BaseLoader, Markup, TemplateNotFound, nodes
from jinja2.environment import TemplateModule
from jinja2.exceptions import TemplateRuntimeError
from jinja2.ext import Extension | import salt.utils.json
import salt.utils.stringutils
import salt.utils.url
import salt.utils.yaml
from jinja2 import BaseLoader, TemplateNotFound, nodes
from jinja2.environment import TemplateModule
from jinja2.exceptions import TemplateRuntimeError
from jinja2.ext import Extension |
from salt.utils.decorators.jinja import jinja_filter, jinja_global, jinja_test
from salt.utils.odict import OrderedDict
from salt.utils.versions import LooseVersion
log = logging.getLogger(__name__)
__all__ = ["SaltCacheLoader", "SerializerExtension"] | from salt.utils.decorators.jinja import jinja_filter, jinja_global, jinja_test
from salt.utils.odict import OrderedDict
from salt.utils.versions import LooseVersion
try:
from markupsafe import Markup
except ImportError:
# jinja < 3.1
from jinja2 import Markup
log = logging.getLogger(__name__)
__all__ = [... |
def method_call(obj, f_name, *f_args, **f_kwargs):
return getattr(obj, f_name, lambda *args, **kwargs: None)(*f_args, **f_kwargs)
@jinja2.contextfunction
def show_full_context(ctx):
return salt.utils.data.simple_types_filter(
{key: value for key, value in ctx.items()} | def method_call(obj, f_name, *f_args, **f_kwargs):
return getattr(obj, f_name, lambda *args, **kwargs: None)(*f_args, **f_kwargs)
try:
contextfunction = jinja2.contextfunction
except AttributeError:
contextfunction = jinja2.pass_context
@contextfunction
def show_full_context(ctx):
return salt.utils.... |
class Model(Container):
str(generator_output))
# build batch logs
batch_logs = {}
if isinstance(x, list):
batch_size = x[0].shape[0]
elif isinstance(x, dict):
... | class Model(Container):
str(generator_output))
# build batch logs
batch_logs = {}
if x is None or len(x) == 0:
# Handle data tensors support when no input given
# step-siz... |
class Model(Container):
outs = [outs]
outs_per_batch.append(outs)
if isinstance(x, list):
batch_size = x[0].shape[0]
elif isinstance(x, dict):
batch_size = list(x.values())[0].shape[0] | class Model(Container):
outs = [outs]
outs_per_batch.append(outs)
if x is None or len(x) == 0:
# Handle data tensors support when no input given
# step-size = 1 for data tensors
batch_size = 1
... |
def test_model_with_external_loss():
out = model.fit(None, None, epochs=1, batch_size=10)
out = model.fit(None, None, epochs=1, steps_per_epoch=1)
# test fit with validation data
with pytest.raises(ValueError):
out = model.fit(None, None, | def test_model_with_external_loss():
out = model.fit(None, None, epochs=1, batch_size=10)
out = model.fit(None, None, epochs=1, steps_per_epoch=1)
# define a generator to produce x=None and y=None
def data_tensors_generator():
while True:
yield (None, Non... |
class Sanic:
if _rn not in self.named_response_middleware:
self.named_response_middleware[_rn] = deque()
if middleware not in self.named_response_middleware[_rn]:
self.named_response_middleware[_rn].append(middleware)
# Decorator
def middl... | class Sanic:
if _rn not in self.named_response_middleware:
self.named_response_middleware[_rn] = deque()
if middleware not in self.named_response_middleware[_rn]:
self.named_response_middleware[_rn].appendleft(middleware)
# Decorator
def m... |
def test_several_bp_with_host(app):
def test_bp_middleware(app):
blueprint = Blueprint("test_middleware")
@blueprint.middleware("response")
async def process_response(request, response): | def test_several_bp_with_host(app):
def test_bp_middleware(app):
blueprint = Blueprint("test_bp_middleware")
@blueprint.middleware("response")
async def process_response(request, response): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.