buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
class tqdm(object):
last_print_n = self.last_print_n
n = self.n
gui = self.gui
if gui: # pragma: no cover
plt = self.plt
ax = self.ax
xdata = self.xdata | class tqdm(object):
last_print_n = self.last_print_n
n = self.n
gui = self.gui
if gui: # pragma: no cover
plt = self.plt
ax = self.ax
xdata = self.xdata |
class tqdm(object):
delta_t = cur_t - last_print_t
if delta_t >= mininterval:
elapsed = cur_t - start_t
if gui: # pragma: no cover
# Inline due to multiple calls
total = self.t... | class tqdm(object):
delta_t = cur_t - last_print_t
if delta_t >= mininterval:
elapsed = cur_t - start_t
if gui: # pragma: no cover
# Inline due to multiple calls
total = self.... |
def test_format_meter():
" 10% 100/1000 [00:12<01:48, 8.33it/s]"
def test_all_defaults():
for i in tqdm(range(10)):
pass
import sys
sys.stderr.write('tests_tqdm.test_all_defaults ... ') | def test_format_meter():
" 10% 100/1000 [00:12<01:48, 8.33it/s]"
def test_si_format():
""" Test SI unit prefixes """
assert '9.00 ' in format_meter(1, 9, 1, unit_scale=True, unit='B')
assert '99.0 ' in format_meter(1, 99, 1, unit_scale=True)
assert '999 ' in format_meter(1, 999, 1, unit_scale... |
def test_update():
""" Test manual creation and updates """
our_file = StringIO()
progressbar = tqdm(total=2, file=our_file, miniters=1)
progressbar.update(2)
our_file.seek(0)
assert '| 2/2' in our_file.read() | def test_update():
""" Test manual creation and updates """
our_file = StringIO()
progressbar = tqdm(total=2, file=our_file, miniters=1)
assert len(progressbar) == 2
progressbar.update(2)
our_file.seek(0)
assert '| 2/2' in our_file.read() |
from pandas.core.dtypes.generic import (
)
from pandas.core.dtypes.missing import notna
from pandas.core import algorithms
from pandas.core.algorithms import unique
| from pandas.core.dtypes.generic import (
)
from pandas.core.dtypes.missing import notna
from pandas.arrays import IntegerArray
from pandas.core import algorithms
from pandas.core.algorithms import unique
|
def _convert_listlike_datetimes(
elif unit is not None:
if format is not None:
raise ValueError("cannot specify both format and unit")
arg = getattr(arg, "values", arg)
result, tz_parsed = tslib.array_with_unit_to_datetime(arg, unit, errors=errors)
if errors == "ignore":
... | def _convert_listlike_datetimes(
elif unit is not None:
if format is not None:
raise ValueError("cannot specify both format and unit")
arg = getattr(arg, "_values", arg)
# GH 30050 pass an ndarray to tslib.array_with_unit_to_datetime
# because it expects an ndarray argum... |
def test_should_cache_errors(unique_share, check_count, err_message):
with pytest.raises(AssertionError, match=err_message):
tools.should_cache(arg, unique_share, check_count) | def test_should_cache_errors(unique_share, check_count, err_message):
with pytest.raises(AssertionError, match=err_message):
tools.should_cache(arg, unique_share, check_count)
def test_nullable_integer_to_datetime():
# Test for #30050
ser = pd.Series([1, 2, None, 2 ** 61, None])
ser = ser.ast... |
from keystone import exception
from keystone import policy
from keystone import token
from keystone.common import manager
from keystone.common import wsgi
CONF = config.CONF
class Manager(manager.Manager):
"""Default pivot point for the Identity backend. | from keystone import exception
from keystone import policy
from keystone import token
from keystone.common import logging
from keystone.common import manager
from keystone.common import wsgi
CONF = config.CONF
LOG = logging.getLogger(__name__)
class Manager(manager.Manager):
"""Default pivot point for the Iden... |
def set_user_enabled(self, context, user_id, user):
return self.update_user(context, user_id, user)
def set_user_password(self, context, user_id, user):
return self.update_user(context, user_id, user)
def update_user_tenant(self, context, user_id, user):
"""Update the default tenant.""... | def set_user_enabled(self, context, user_id, user):
return self.update_user(context, user_id, user)
def set_user_password(self, context, user_id, user):
user_ref = self.update_user(context, user_id, user)
try:
for token_id in self.token_api.list_tokens(context, user_id):
... |
def delete_token(self, token_id):
return self.db.delete('token-%s' % token_id)
except KeyError:
raise exception.TokenNotFound(token_id=token_id) | def delete_token(self, token_id):
return self.db.delete('token-%s' % token_id)
except KeyError:
raise exception.TokenNotFound(token_id=token_id)
def list_tokens(self, user_id):
tokens = []
now = datetime.datetime.utcnow()
for token, user_ref in self.db.items(... |
def delete_token(self, token_id):
with session.begin():
session.delete(token_ref)
session.flush() | def delete_token(self, token_id):
with session.begin():
session.delete(token_ref)
session.flush()
def list_tokens(self, user_id):
session = self.get_session()
tokens = []
now = datetime.datetime.utcnow()
for token_ref in session.query(TokenModel)\
... |
def delete_token(self, token_id):
"""
raise exception.NotImplemented()
def _get_default_expire_time(self):
"""Determine when a token should expire based on the config.
| def delete_token(self, token_id):
"""
raise exception.NotImplemented()
def list_tokens(self, user_id):
"""Returns a list of current token_id's for a user
:param user_id: identity of the user
:type user_id: string
:returns: list of token_id's
"""
rai... |
def test_invalid_user_password(self):
username='blah',
password='blah')
def test_user_create_update_delete(self):
from keystoneclient import exceptions as client_exceptions
| def test_invalid_user_password(self):
username='blah',
password='blah')
def test_change_password_invalidates_token(self):
from keystoneclient import exceptions as client_exceptions
client = self.get_client(admin=True)
username = uuid.uui... |
def format_sizeof(num, suffix=''):
Number with Order of Magnitude SI unit postfix.
"""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if abs(num) < 1000.0:
if abs(num) < 100.0:
if abs(num) < 10.0:
return '{0:1.2f}'.format(num) + unit + suffix... | def format_sizeof(num, suffix=''):
Number with Order of Magnitude SI unit postfix.
"""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if abs(num) < 999.95:
if abs(num) < 99.95:
if abs(num) < 9.995:
return '{0:1.2f}'.format(num) + unit + suffi... |
class tqdm(object):
if ascii is None:
ascii = not _supports_unicode(file)
if gui: # pragma: no cover
try:
import matplotlib as mpl
import matplotlib.pyplot as plt | class tqdm(object):
if ascii is None:
ascii = not _supports_unicode(file)
if gui: # pragma: no cover
try:
import matplotlib as mpl
import matplotlib.pyplot as plt |
class tqdm(object):
self.unit_scale = unit_scale
self.gui = gui
if gui: # pragma: no cover
# Initialize the GUI display
if not disable:
file.write('Warning: GUI is experimental/alpha\n') | class tqdm(object):
self.unit_scale = unit_scale
self.gui = gui
if gui: # pragma: no cover
# Initialize the GUI display
if not disable:
file.write('Warning: GUI is experimental/alpha\n') |
class tqdm(object):
self.n = 0
def __len__(self):
return len(self.iterable)
def __iter__(self):
''' Backward-compatibility to use: for x in tqdm(iterable) ''' | class tqdm(object):
self.n = 0
def __len__(self):
return len(self.iterable) if self.iterable else self.total
def __iter__(self):
''' Backward-compatibility to use: for x in tqdm(iterable) ''' |
class tqdm(object):
last_print_n = self.last_print_n
n = self.n
gui = self.gui
if gui: # pragma: no cover
plt = self.plt
ax = self.ax
xdata = self.xdata | class tqdm(object):
last_print_n = self.last_print_n
n = self.n
gui = self.gui
if gui: # pragma: no cover
plt = self.plt
ax = self.ax
xdata = self.xdata |
class tqdm(object):
delta_t = cur_t - last_print_t
if delta_t >= mininterval:
elapsed = cur_t - start_t
if gui: # pragma: no cover
# Inline due to multiple calls
total = self.t... | class tqdm(object):
delta_t = cur_t - last_print_t
if delta_t >= mininterval:
elapsed = cur_t - start_t
if gui: # pragma: no cover
# Inline due to multiple calls
total = self.... |
def test_format_meter():
" 10% 100/1000 [00:12<01:48, 8.33it/s]"
def test_all_defaults():
for i in tqdm(range(10)):
pass
import sys
sys.stderr.write('tests_tqdm.test_all_defaults ... ') | def test_format_meter():
" 10% 100/1000 [00:12<01:48, 8.33it/s]"
def test_si_format():
""" Test SI unit prefixes """
assert '9.00 ' in format_meter(1, 9, 1, unit_scale=True, unit='B')
assert '99.0 ' in format_meter(1, 99, 1, unit_scale=True)
assert '999 ' in format_meter(1, 999, 1, unit_scale... |
def test_update():
""" Test manual creation and updates """
our_file = StringIO()
progressbar = tqdm(total=2, file=our_file, miniters=1)
progressbar.update(2)
our_file.seek(0)
assert '| 2/2' in our_file.read() | def test_update():
""" Test manual creation and updates """
our_file = StringIO()
progressbar = tqdm(total=2, file=our_file, miniters=1)
assert len(progressbar) == 2
progressbar.update(2)
our_file.seek(0)
assert '| 2/2' in our_file.read() |
def setup_remote_pydev_debug():
except:
LOG.exception(_(error_msg))
raise | def setup_remote_pydev_debug():
except:
LOG.exception(_(error_msg))
raise
class LimitingReader(object):
"""Reader to limit the size of an incoming request."""
def __init__(self, data, limit):
"""
:param data: Underlying data object
:param limit: maximum ... |
def register_cli_int(*args, **kw):
register_str('auth_admin_prefix', default='')
register_str('policy_file', default='policy.json')
register_str('policy_default_rule', default=None)
#ssl options
register_bool('enable', group='ssl', default=False) | def register_cli_int(*args, **kw):
register_str('auth_admin_prefix', default='')
register_str('policy_file', default='policy.json')
register_str('policy_default_rule', default=None)
#default max request size is 112k
register_int('max_request_body_size', default=114688)
#ssl options
register_bool('enable', group='ssl',... |
class Conflict(Error):
title = 'Conflict'
class UnexpectedError(Error):
"""An unexpected error prevented the server from fulfilling your request.
| class Conflict(Error):
title = 'Conflict'
class RequestTooLarge(Error):
"""Request is too large."""
code = 413
title = 'Request is too large.'
class UnexpectedError(Error):
"""An unexpected error prevented the server from fulfilling your request.
|
# License for the specific language governing permissions and limitations
# under the License.
from keystone.common import serializer
from keystone.common import wsgi
from keystone import config
from keystone import exception | # License for the specific language governing permissions and limitations
# under the License.
import webob.dec
from keystone.common import serializer
from keystone.common import utils
from keystone.common import wsgi
from keystone import config
from keystone import exception |
def process_request(self, request):
# Rewrites path to root if no path is given.
elif not request.environ['PATH_INFO']:
request.environ['PATH_INFO'] = '/' | def process_request(self, request):
# Rewrites path to root if no path is given.
elif not request.environ['PATH_INFO']:
request.environ['PATH_INFO'] = '/'
class RequestBodySizeLimiter(wsgi.Middleware):
"""Limit the size of an incoming request."""
def __init__(self, *args, **kwargs... |
from hashlib import sha1
import unittest
from paramiko import Transport, SecurityOptions, ServerInterface, RSAKey, DSSKey, \
SSHException, ChannelException, Packetizer
from paramiko import AUTH_FAILED, AUTH_SUCCESSFUL
from paramiko import OPEN_SUCCEEDED, OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
from paramiko.common... | from hashlib import sha1
import unittest
from paramiko import Transport, SecurityOptions, ServerInterface, RSAKey, DSSKey, \
SSHException, ChannelException, Packetizer, Channel
from paramiko import AUTH_FAILED, AUTH_SUCCESSFUL
from paramiko import OPEN_SUCCEEDED, OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
from parami... |
class NullServer (ServerInterface):
def check_global_request(self, kind, msg):
self._global_request = kind
return False
def check_channel_x11_request(self, channel, single_connection, auth_protocol, auth_cookie, screen_number):
self._x11_single_connection = single_connection | class NullServer (ServerInterface):
def check_global_request(self, kind, msg):
self._global_request = kind
# NOTE: for w/e reason, older impl of this returned False always, even
# tho that's only supposed to occur if the request cannot be served.
# For now, leaving that the default ... |
class TransportTest(unittest.TestCase):
# sendall() accepts a memoryview instance
chan.sendall(memoryview(data))
self.assertEqual(sfile.read(len(data)), data) | class TransportTest(unittest.TestCase):
# sendall() accepts a memoryview instance
chan.sendall(memoryview(data))
self.assertEqual(sfile.read(len(data)), data)
def test_server_rejects_open_channel_without_auth(self):
try:
self.setup_test_server(connect_kwargs=... |
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... |
from typing import (
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
cast, | from typing import (
Sequence,
Set,
Tuple,
TypeVar,
Union,
cast, |
class CannotSplit(Exception):
"""
class FormatError(Exception):
"""Base exception for `# fmt: on` and `# fmt: off` handling.
It holds the number of bytes of the prefix consumed before the format
control comment appeared.
"""
def __init__(self, consumed: int) -> None:
super().__init__... | class CannotSplit(Exception):
"""
class WriteBack(Enum):
NO = 0
YES = 1 |
class DebugVisitor(Visitor[T]):
out(f" {node.value!r}", fg="blue", bold=False)
@classmethod
def show(cls, code: str) -> None:
"""Pretty-print the lib2to3 AST of a given string of `code`.
Convenience method for debugging.
"""
v: DebugVisitor[None] = DebugVisitor()
... | class DebugVisitor(Visitor[T]):
out(f" {node.value!r}", fg="blue", bold=False)
@classmethod
def show(cls, code: Union[str, Leaf, Node]) -> None:
"""Pretty-print the lib2to3 AST of a given string of `code`.
Convenience method for debugging.
"""
v: DebugVisitor[None] ... |
class Line:
return bool(self.leaves or self.comments)
class UnformattedLines(Line):
"""Just like :class:`Line` but stores lines which aren't reformatted."""
def append(self, leaf: Leaf, preformatted: bool = True) -> None:
"""Just add a new `leaf` to the end of the lines.
The `preform... | class Line:
return bool(self.leaves or self.comments)
@dataclass
class EmptyLineTracker:
"""Provides a stateful method that returns the number of potential extra |
class EmptyLineTracker:
This is for separating `def`, `async def` and `class` with extra empty
lines (two on module-level).
"""
if isinstance(current_line, UnformattedLines):
return 0, 0
before, after = self._maybe_empty_lines(current_line)
before -= self.pre... | class EmptyLineTracker:
This is for separating `def`, `async def` and `class` with extra empty
lines (two on module-level).
"""
before, after = self._maybe_empty_lines(current_line)
before -= self.previous_after
self.previous_after = after |
class LineGenerator(Visitor[Line]):
current_line: Line = Factory(Line)
remove_u_prefix: bool = False
def line(self, indent: int = 0, type: Type[Line] = Line) -> Iterator[Line]:
"""Generate a line.
If the line is empty, only emit if it makes sense. | class LineGenerator(Visitor[Line]):
current_line: Line = Factory(Line)
remove_u_prefix: bool = False
def line(self, indent: int = 0) -> Iterator[Line]:
"""Generate a line.
If the line is empty, only emit if it makes sense. |
class LineGenerator(Visitor[Line]):
If any lines were generated, set up a new current_line.
"""
if not self.current_line:
if self.current_line.__class__ == type:
self.current_line.depth += indent
else:
self.current_line = type(depth=self.cu... | class LineGenerator(Visitor[Line]):
If any lines were generated, set up a new current_line.
"""
if not self.current_line:
self.current_line.depth += indent
return # Line is empty, don't emit. Creating a new one unnecessary.
complete_line = self.current_line
... |
class LineGenerator(Visitor[Line]):
yield from self.visit_default(leaf)
yield from self.line()
def visit_unformatted(self, node: LN) -> Iterator[Line]:
"""Used when file contained a `# fmt: off`."""
if isinstance(node, Node):
for child in node.children:
y... | class LineGenerator(Visitor[Line]):
yield from self.visit_default(leaf)
yield from self.line()
def visit_STANDALONE_COMMENT(self, leaf: Leaf) -> Iterator[Line]:
if not self.current_line.bracket_tracker.any_open_brackets():
yield from self.line()
yield from self.visit_def... |
def container_of(leaf: Leaf) -> LN:
if parent.children[0].prefix != same_prefix:
break
if parent.type in SURROUNDED_BY_BRACKETS:
break
| def container_of(leaf: Leaf) -> LN:
if parent.children[0].prefix != same_prefix:
break
if parent.type == syms.file_input:
break
if parent.type in SURROUNDED_BY_BRACKETS:
break
|
def generate_comments(leaf: LN) -> Iterator[Leaf]:
"""
for pc in list_comments(leaf.prefix, is_endmarker=leaf.type == token.ENDMARKER):
yield Leaf(pc.type, pc.value, prefix="\n" * pc.newlines)
if pc.value in FMT_ON:
raise FormatOn(pc.consumed)
if pc.value in FMT_OFF:
... | def generate_comments(leaf: LN) -> Iterator[Leaf]:
"""
for pc in list_comments(leaf.prefix, is_endmarker=leaf.type == token.ENDMARKER):
yield Leaf(pc.type, pc.value, prefix="\n" * pc.newlines)
@dataclass |
def split_line(
If `py36` is True, splitting may generate syntax that is only compatible
with Python 3.6 and later.
"""
if isinstance(line, UnformattedLines) or line.is_comment:
yield line
return
| def split_line(
If `py36` is True, splitting may generate syntax that is only compatible
with Python 3.6 and later.
"""
if line.is_comment:
yield line
return
|
def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
def normalize_fmt_off(node: Node) -> None:
"""Allow `# fmt: off`/`# fmt: on` within bracket pairs.
Ignores `# fmt: off` and `# fmt: on` outside of brackets.
Raises :exc:`SyntaxError` if no matching `# fmt: on` is found for a `# ... | def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
def normalize_fmt_off(node: Node) -> None:
"""Convert content between `# fmt: off`/`# fmt: on` into standalone comments."""
try_again = True
while try_again:
try_again = convert_one_fmt_off_pair(node)
def convert_one_fmt... |
def hide_fmt_off(node: Node) -> bool:
hidden_value = (
comment.value + "\n" + "".join(str(n) for n in ignored_nodes)
)
first_idx = None
for ignored in ignored_nodes:
index = ignored.remove() | def hide_fmt_off(node: Node) -> bool:
hidden_value = (
comment.value + "\n" + "".join(str(n) for n in ignored_nodes)
)
if hidden_value.endswith("\n"):
# That happens when one of the `ignored_nodes` ended with a NEWLINE
... |
def hide_fmt_off(node: Node) -> bool:
def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]:
container: Optional[LN] = container_of(leaf)
while container is not None:
for comment in list_comments(container.prefix, is_endmarker=False):
if comment.value in FMT_ON:
return | def hide_fmt_off(node: Node) -> bool:
def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]:
"""Starting from the container of `leaf`, generate all leaves until `# fmt: on`.
Stops at the end of the block.
"""
container: Optional[LN] = container_of(leaf)
while container is not None and container.... |
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_remove_empty_parentheses_after_class(self) -> None:
source, expected = read_data("class_blank_parenth... | 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_fmtonoff2(self) -> None:
source, expected = read_data("fmtonoff2")
actual = fs(source)
... |
class Scheduler(object):
for batch_task in self._state.get_batch_running_tasks(task.batch_id):
batch_task.expl = expl
if not (task.status in (RUNNING, BATCH_RUNNING) and status == PENDING) or new_deps:
# don't allow re-scheduling of task while it is running, it m... | class Scheduler(object):
for batch_task in self._state.get_batch_running_tasks(task.batch_id):
batch_task.expl = expl
if not (task.status in (RUNNING, BATCH_RUNNING) and (status not in (DONE, FAILED, RUNNING) or task.worker_running != worker_id)) or new_deps:
# d... |
class SchedulerApiTest(unittest.TestCase):
self.assertEqual(self.sch.get_work(worker='Y')['task_id'], 'C')
self.assertEqual(self.sch.get_work(worker='X')['task_id'], 'B')
def test_retry(self):
# Try to build A but fails, will retry after 100s
self.setTime(0) | class SchedulerApiTest(unittest.TestCase):
self.assertEqual(self.sch.get_work(worker='Y')['task_id'], 'C')
self.assertEqual(self.sch.get_work(worker='X')['task_id'], 'B')
def test_status_wont_override(self):
# Worker X is running A
# Worker Y wants to override the status to UNKNOWN ... |
def read_file(cls, file_path, config_name):
with open(file_path) as file_stream:
return file_stream.read()
def read_templates(
self,
filenames: List[str],
custom_template_directory: Optional[str] = None,
autoescape: bool = False,
) -> List[jinja2.Template]:
... | def read_file(cls, file_path, config_name):
with open(file_path) as file_stream:
return file_stream.read()
def read_template(self, filename: str) -> jinja2.Template:
"""Load a template file from disk.
This function will attempt to load the given template from the default Synaps... |
def read_templates(
template directory. If `custom_template_directory` is supplied, that directory
is tried first.
Files read are treated as Jinja templates. These templates are not rendered yet.
Args:
filenames: A list of template filenames to read. | def read_templates(
template directory. If `custom_template_directory` is supplied, that directory
is tried first.
Files read are treated as Jinja templates. The templates are not rendered yet
and have autoescape enabled.
Args:
filenames: A list of template filename... |
def read_templates(
custom_template_directory: A directory to try to look for the templates
before using the default Synapse template directory instead.
autoescape: Whether to autoescape variables before inserting them into the
template.
Raises:
... | def read_templates(
custom_template_directory: A directory to try to look for the templates
before using the default Synapse template directory instead.
Raises:
ConfigError: if the file's path is incorrect or otherwise cannot be read.
Returns:
A list... |
def read_templates(
search_directories.insert(0, custom_template_directory)
loader = jinja2.FileSystemLoader(search_directories)
env = jinja2.Environment(loader=loader, autoescape=autoescape)
# Update the environment with our custom filters
env.filters.update( | def read_templates(
search_directories.insert(0, custom_template_directory)
loader = jinja2.FileSystemLoader(search_directories)
env = jinja2.Environment(loader=loader, autoescape=jinja2.select_autoescape(),)
# Update the environment with our custom filters
env.filters.upda... |
def read_templates(
}
)
for filename in filenames:
# Load the template
template = env.get_template(filename)
templates.append(template)
return templates
def _format_ts_filter(value: int, format: str): | def read_templates(
}
)
# Load the templates
return [env.get_template(filename) for filename in filenames]
def _format_ts_filter(value: int, format: str): |
def read_config(self, config, **kwargs):
"recaptcha_siteverify_api",
"https://www.recaptcha.net/recaptcha/api/siteverify",
)
self.recaptcha_template = self.read_templates(
["recaptcha.html"], autoescape=True
)[0]
def generate_config_section(self, **kwargs... | def read_config(self, config, **kwargs):
"recaptcha_siteverify_api",
"https://www.recaptcha.net/recaptcha/api/siteverify",
)
self.recaptcha_template = self.read_template("recaptcha.html")
def generate_config_section(self, **kwargs):
return """\ |
def __init__(self, *args):
def read_config(self, config, **kwargs):
consent_config = config.get("user_consent")
self.terms_template = self.read_templates(["terms.html"], autoescape=True)[0]
if consent_config is None:
return | def __init__(self, *args):
def read_config(self, config, **kwargs):
consent_config = config.get("user_consent")
self.terms_template = self.read_template("terms.html")
if consent_config is None:
return |
def read_config(self, config, **kwargs):
self.session_lifetime = session_lifetime
# The success template used during fallback auth.
self.fallback_success_template = self.read_templates(
["auth_success.html"], autoescape=True
)[0]
def generate_config_section(self, genera... | def read_config(self, config, **kwargs):
self.session_lifetime = session_lifetime
# The success template used during fallback auth.
self.fallback_success_template = self.read_template("auth_success.html")
def generate_config_section(self, generate_secrets=False, **kwargs):
if gener... |
def make_unsubscribe_link(
def safe_markup(raw_html: str) -> jinja2.Markup:
return jinja2.Markup(
bleach.linkify(
bleach.clean( | def make_unsubscribe_link(
def safe_markup(raw_html: str) -> jinja2.Markup:
"""
Sanitise a raw HTML string to a set of allowed tags and attributes, and linkify any bare URLs.
Args
raw_html: Unsafe HTML.
Returns:
A Markup object ready to safely use in a Jinja template.
"""
ret... |
def safe_markup(raw_html: str) -> jinja2.Markup:
def safe_text(raw_text: str) -> jinja2.Markup:
"""
Process text: treat it as HTML but escape any tags (ie. just escape the
HTML) then linkify it.
"""
return jinja2.Markup(
bleach.linkify(bleach.clean(raw_text, tags=[], attributes={}, strip=Fa... | def safe_markup(raw_html: str) -> jinja2.Markup:
def safe_text(raw_text: str) -> jinja2.Markup:
"""
Sanitise text (escape any HTML tags), and then linkify any bare URLs.
Args
raw_text: Unsafe text which might include HTML markup.
Returns:
A Markup object ready to safely use in a Jinja... |
class WaitIterator(object):
self.current_index = self.current_future = None
self._running_future = None
self_ref = weakref.ref(self)
for future in futures:
future.add_done_callback(functools.partial( | class WaitIterator(object):
self.current_index = self.current_future = None
self._running_future = None
# Use a weak reference to self to avoid cycles that may delay
# garbage collection.
self_ref = weakref.ref(self)
for future in futures:
future.add_done_cal... |
class WaitIterator(object):
the inputs.
"""
self._running_future = TracebackFuture()
if self._finished:
self._return_result(self._finished.popleft()) | class WaitIterator(object):
the inputs.
"""
self._running_future = TracebackFuture()
# As long as there is an active _running_future, we must
# ensure that the WaitIterator is not GC'd (due to the
# use of weak references in __init__). Add a callback that
# refere... |
class WaitIteratorTest(AsyncTestCase):
self.assertEqual(g.current_index, 3, 'wrong index')
i += 1
if __name__ == '__main__':
unittest.main() | class WaitIteratorTest(AsyncTestCase):
self.assertEqual(g.current_index, 3, 'wrong index')
i += 1
@gen_test
def test_no_ref(self):
# In this usage, there is no direct hard reference to the
# WaitIterator itself, only the Future it returns. Since
# WaitIte... |
class TestDecompressionBomb:
with Image.open(TEST_FILE):
pass
def test_exception_ico(self):
with pytest.raises(Image.DecompressionBombError):
with Image.open("Tests/images/decompression_bomb.ico"): | class TestDecompressionBomb:
with Image.open(TEST_FILE):
pass
@pytest.mark.xfail(reason="different exception")
def test_exception_ico(self):
with pytest.raises(Image.DecompressionBombError):
with Image.open("Tests/images/decompression_bomb.ico"): |
def test_apng_syntax_errors():
exception = e
assert exception is None
with pytest.raises(SyntaxError):
with Image.open("Tests/images/apng/syntax_num_frames_high.png") as im:
im.seek(im.n_frames - 1)
im.load() | def test_apng_syntax_errors():
exception = e
assert exception is None
with pytest.raises(OSError):
with Image.open("Tests/images/apng/syntax_num_frames_high.png") as im:
im.seek(im.n_frames - 1)
im.load() |
from PIL import Image
from .helper import assert_image_equal_tofile
| from PIL import Image
import pytest
from .helper import assert_image_equal_tofile
|
def test_combined_larger_than_size():
with pytest.raises(OSError):
with Image.open("Tests/images/combined_larger_than_size.psd"):
pass | def test_combined_larger_than_size():
with pytest.raises(OSError):
with Image.open("Tests/images/combined_larger_than_size.psd"):
pass
@pytest.mark.parametrize(
"test_file,raises",
[
("Tests/images/timeout-1ee28a249896e05b83840ae8140622de8e648ba9.psd", Image.UnidentifiedImageErr... |
class TestFileTiff:
)
def test_string_dimension(self):
# Assert that an error is raised if one of the dimensions is a string
with pytest.raises(ValueError):
with Image.open("Tests/images/string_dimension.tiff"):
pass
@pytest.mark.skipif(not is_win32(), reason="Windo... | class TestFileTiff:
)
def test_string_dimension(self):
# Assert that an error is raised if one of the dimensions is a string
with pytest.raises(OSError):
with Image.open("Tests/images/string_dimension.tiff") as im:
im.load()
@pytest.mark.skipif(not is_win32(), reas... |
def _safe_read(fp, size):
:param fp: File handle. Must implement a <b>read</b> method.
:param size: Number of bytes to read.
:returns: A string containing up to <i>size</i> bytes of data.
"""
if size <= 0:
return b""
if size <= SAFEBLOCK:
return fp.read(size)
data = []
... | def _safe_read(fp, size):
:param fp: File handle. Must implement a <b>read</b> method.
:param size: Number of bytes to read.
:returns: A string containing <i>size</i> bytes of data.
Raises an OSError if the file is truncated and the read can not be completed
"""
if size <= 0:
return ... |
def _safe_read(fp, size):
break
data.append(block)
size -= len(block)
return b"".join(data)
class PyCodecState:
def __init__(self):
self.xsize = 0 | def _safe_read(fp, size):
break
data.append(block)
size -= len(block)
if sum(len(d) for d in data) < size:
raise OSError("Truncated File Read")
return b"".join(data)
class PyCodecState:
def __init__(self):
self.xsize = 0 |
class PsdImageFile(ImageFile.ImageFile):
end = self.fp.tell() + size
size = i32(read(4))
if size:
self.layers = _layerinfo(self.fp)
self.fp.seek(end)
self.n_frames = len(self.layers)
self.is_animated = self.n_frames > 1 | class PsdImageFile(ImageFile.ImageFile):
end = self.fp.tell() + size
size = i32(read(4))
if size:
_layer_data = io.BytesIO(ImageFile._safe_read(self.fp, size))
self.layers = _layerinfo(_layer_data, size)
self.fp.seek(end)
self.n_fra... |
class PsdImageFile(ImageFile.ImageFile):
finally:
self.__fp = None
def _layerinfo(file):
# read layerinfo block
layers = []
read = file.read
for i in range(abs(i16(read(2)))):
# bounding box
y0 = i32(read(4)) | class PsdImageFile(ImageFile.ImageFile):
finally:
self.__fp = None
def _layerinfo(fp, ct_bytes):
# read layerinfo block
layers = []
def read(size):
return ImageFile._safe_read(fp, size)
ct = i16(read(2))
# sanity check
if ct_bytes < (abs(ct) * 20):
raise S... |
def _layerinfo(file):
# image info
info = []
mode = []
types = list(range(i16(read(2))))
if len(types) > 4:
continue
| def _layerinfo(file):
# image info
info = []
mode = []
ct_types = i16(read(2))
types = list(range(ct_types))
if len(types) > 4:
continue
|
def _layerinfo(file):
size = i32(read(4)) # length of the extra data field
combined = 0
if size:
data_end = file.tell() + size
length = i32(read(4))
if length:
file.seek(length - 16, io.SEEK_CUR)
combined += length + 4
... | def _layerinfo(file):
size = i32(read(4)) # length of the extra data field
combined = 0
if size:
data_end = fp.tell() + size
length = i32(read(4))
if length:
fp.seek(length - 16, io.SEEK_CUR)
combined += length + 4
le... |
def _layerinfo(file):
name = read(length).decode("latin-1", "replace")
combined += length + 1
file.seek(data_end)
layers.append((name, mode, (x0, y0, x1, y1)))
# get tiles | def _layerinfo(file):
name = read(length).decode("latin-1", "replace")
combined += length + 1
fp.seek(data_end)
layers.append((name, mode, (x0, y0, x1, y1)))
# get tiles |
def _layerinfo(file):
for name, mode, bbox in layers:
tile = []
for m in mode:
t = _maketile(file, m, bbox, 1)
if t:
tile.extend(t)
layers[i] = name, mode, bbox, tile | def _layerinfo(file):
for name, mode, bbox in layers:
tile = []
for m in mode:
t = _maketile(fp, m, bbox, 1)
if t:
tile.extend(t)
layers[i] = name, mode, bbox, tile |
def ret10_slice() -> Bytes[10]:
assert c.ret10_slice() == b"A"
def test_slice_convert(get_contract):
# test slice of converting between bytes32 and Bytes
code = """ | def ret10_slice() -> Bytes[10]:
assert c.ret10_slice() == b"A"
def test_slice_equality(get_contract):
# test for equality with dirty bytes
code = """
@external
def assert_eq() -> bool:
dirty_bytes: String[4] = "abcd"
dirty_bytes = slice(dirty_bytes, 0, 3)
clean_bytes: String[4] = "abc"
ret... |
def test(a: uint256, b: String[50] = "foo") -> Bytes[100]:
assert c.test(12345, "bar")[-3:] == b"bar"
def test_string_equality(get_contract_with_gas_estimation):
code = """
_compA: String[100]
_compB: String[100]
@external
def equal_true() -> bool:
compA: String[100] = "The quick brown fox jumps over the... | def test(a: uint256, b: String[50] = "foo") -> Bytes[100]:
assert c.test(12345, "bar")[-3:] == b"bar"
string_equality_tests = [
(
100,
"The quick brown fox jumps over the lazy dog",
"The quick brown fox jumps over the lazy hog",
),
# check <= 32 codepath
(32, "abc", "abc\0"... |
def compare_var_storage_not_equal_false() -> bool:
assert c.storage_not_equal_true() is True
assert c.storage_not_equal_false() is False
a = "The quick brown fox jumps over the lazy dog"
b = "The quick brown fox jumps over the lazy hog"
assert c.string_compare_equal(a, a) is True
assert c.strin... | def compare_var_storage_not_equal_false() -> bool:
assert c.storage_not_equal_true() is True
assert c.storage_not_equal_false() is False
assert c.string_compare_equal(a, a) is True
assert c.string_compare_equal(a, b) is False
assert c.string_compare_not_equal(b, a) is True |
def copy_bytes(dst, src, length, length_bound):
with src.cache_when_complex("src") as (b1, src), length.cache_when_complex(
"copy_bytes_count"
) as (b2, length,), dst.cache_when_complex("dst") as (b3, dst):
# fast code for common case where num bytes is small
# TODO expand this for mor... | def copy_bytes(dst, src, length, length_bound):
with src.cache_when_complex("src") as (b1, src), length.cache_when_complex(
"copy_bytes_count"
) as (b2, length), dst.cache_when_complex("dst") as (b3, dst):
# fast code for common case where num bytes is small
# TODO expand this for more... |
from vyper.address_space import DATA, IMMUTABLES, MEMORY, STORAGE
from vyper.codegen import external_call, self_call
from vyper.codegen.core import (
LOAD,
bytes_data_ptr,
clamp_basetype,
ensure_in_memory,
get_dyn_array_count, | from vyper.address_space import DATA, IMMUTABLES, MEMORY, STORAGE
from vyper.codegen import external_call, self_call
from vyper.codegen.core import (
clamp_basetype,
ensure_in_memory,
get_dyn_array_count, |
def parse_Compare(self):
left = Expr(self.expr.left, self.context).ir_node
right = Expr(self.expr.right, self.context).ir_node
length_mismatch = left.typ.maxlen != right.typ.maxlen
left_over_32 = left.typ.maxlen > 32
right_over_32 = right.typ.maxlen > 32
... | def parse_Compare(self):
left = Expr(self.expr.left, self.context).ir_node
right = Expr(self.expr.right, self.context).ir_node
left_keccak = keccak256_helper(self.expr, left, self.context)
right_keccak = keccak256_helper(self.expr, right, self.context)
if op... |
from math import ceil
from vyper.codegen.core import ensure_in_memory
from vyper.codegen.ir_node import IRnode
from vyper.codegen.types import BaseType, ByteArrayLike, is_base_type
from vyper.exceptions import CompilerPanic | from math import ceil
from vyper.codegen.core import bytes_data_ptr, ensure_in_memory, get_bytearray_length
from vyper.codegen.ir_node import IRnode
from vyper.codegen.types import BaseType, ByteArrayLike, is_base_type
from vyper.exceptions import CompilerPanic |
def _gas_bound(num_words):
return SHA3_BASE + num_words * SHA3_PER_WORD
def keccak256_helper(expr, ir_arg, context):
sub = ir_arg # TODO get rid of useless variable
_check_byteslike(sub.typ, expr)
# Can hash literals
# TODO this is dead code.
if isinstance(sub, bytes):
return IRnode.... | def _gas_bound(num_words):
return SHA3_BASE + num_words * SHA3_PER_WORD
def keccak256_helper(expr, to_hash, context):
_check_byteslike(to_hash.typ, expr)
# Can hash literals
# TODO this is dead code.
if isinstance(to_hash, bytes):
return IRnode.from_list(bytes_to_int(keccak256(to_hash)), ... |
class EmptyLineTracker:
lines (two on module-level).
"""
before, after = self._maybe_empty_lines(current_line)
before -= self.previous_after
self.previous_after = after
self.previous_line = current_line
return before, after | class EmptyLineTracker:
lines (two on module-level).
"""
before, after = self._maybe_empty_lines(current_line)
before = (
# Black should not insert empty lines at the beginning
# of the file
0
if self.previous_line is None
else ... |
class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
def test_tab_comment_indentation(self) -> None:
contents_tab = "if 1:\n\tif 2:\n\t\tpass\n\t# comment\n\tpass\n"
contents_spc = "if 1:\n if 2:\n ... | class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
@patch("black.dump_to_file", dump_to_stderr)
def test_beginning_backslash(self) -> None:
source, expected = read_data("beginning_backslash")
actu... |
'transparent': (0, 0, 0, 0),
}
RGBA = re.compile(r'rgba\([ \n\r\t]*(.+?)[ \n\r\t]*\)')
RGB = re.compile(r'rgb\([ \n\r\t]*(.+?)[ \n\r\t]*\)')
HEX_RRGGBB = re.compile('#[0-9a-f]{6}')
HEX_RGB = re.compile('#[0-9a-f]{3}')
| 'transparent': (0, 0, 0, 0),
}
RGBA = re.compile(r'rgba\((.+?)\)')
RGB = re.compile(r'rgb\((.+?)\)')
HEX_RRGGBB = re.compile('#[0-9a-f]{6}')
HEX_RGB = re.compile('#[0-9a-f]{3}')
|
def color(string, opacity=1):
if match:
r, g, b, a = tuple(
float(i.strip(' %')) / 100 if '%' in i else float(i) / 255
for i in match.group(1).split(','))
return (r, g, b, a * 255 * opacity)
match = RGB.search(string)
if match:
r, g, b = tuple(
fl... | def color(string, opacity=1):
if match:
r, g, b, a = tuple(
float(i.strip(' %')) / 100 if '%' in i else float(i) / 255
for i in match.group(1).strip().split(','))
return (r, g, b, a * 255 * opacity)
match = RGB.search(string)
if match:
r, g, b = tuple(
... |
__all__ = [
def get_objs_combined_axis(
objs, intersect: bool = False, axis=0, sort: bool = True
) -> Index:
"""
Extract combined index: return intersection or union (depending on the | __all__ = [
def get_objs_combined_axis(
objs, intersect: bool = False, axis=0, sort: bool = True, copy: bool = False
) -> Index:
"""
Extract combined index: return intersection or union (depending on the |
def get_objs_combined_axis(
The axis to extract indexes from.
sort : bool, default True
Whether the result index should come out sorted or not.
Returns
-------
Index
"""
obs_idxes = [obj._get_axis(axis) for obj in objs]
return _get_combined_index(obs_idxes, intersect=interse... | def get_objs_combined_axis(
The axis to extract indexes from.
sort : bool, default True
Whether the result index should come out sorted or not.
copy : bool, default False
If True, return a copy of the combined index.
Returns
-------
Index
"""
obs_idxes = [obj._get_ax... |
def _get_distinct_objs(objs: List[Index]) -> List[Index]:
def _get_combined_index(
indexes: List[Index], intersect: bool = False, sort: bool = False
) -> Index:
"""
Return the union or intersection of indexes. | def _get_distinct_objs(objs: List[Index]) -> List[Index]:
def _get_combined_index(
indexes: List[Index],
intersect: bool = False,
sort: bool = False,
copy: bool = False,
) -> Index:
"""
Return the union or intersection of indexes. |
def _get_combined_index(
calculate the union.
sort : bool, default False
Whether the result index should come out sorted or not.
Returns
------- | def _get_combined_index(
calculate the union.
sort : bool, default False
Whether the result index should come out sorted or not.
copy : bool, default False
If True, return a copy of the combined index.
Returns
------- |
def _get_combined_index(
index = index.sort_values()
except TypeError:
pass
return index
| def _get_combined_index(
index = index.sort_values()
except TypeError:
pass
# GH 29879
if copy:
index = index.copy()
return index
|
class _Concatenator:
def _get_comb_axis(self, i: int) -> Index:
data_axis = self.objs[0]._get_block_manager_axis(i)
return get_objs_combined_axis(
self.objs, axis=data_axis, intersect=self.intersect, sort=self.sort
)
def _get_concat_axis(self) -> Index: | class _Concatenator:
def _get_comb_axis(self, i: int) -> Index:
data_axis = self.objs[0]._get_block_manager_axis(i)
return get_objs_combined_axis(
self.objs,
axis=data_axis,
intersect=self.intersect,
sort=self.sort,
copy=self.copy,
... |
def test_concat_sparse():
)
result = pd.concat([a, a], axis=1)
tm.assert_frame_equal(result, expected) | def test_concat_sparse():
)
result = pd.concat([a, a], axis=1)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("test_series", [True, False])
def test_concat_copy_index(test_series, axis):
# GH 29879
if test_series:
ser = Series([1, 2])
comb = concat([ser, ser], axi... |
class _AxesBase(martist.Artist):
return
dL = self.dataLim
x0, x1 = map(x_trf.inverted().transform, dL.intervalx)
y0, y1 = map(y_trf.inverted().transform, dL.intervaly)
xr = 1.05 * (x1 - x0)
yr = 1.05 * (y1 - y0)
| class _AxesBase(martist.Artist):
return
dL = self.dataLim
x0, x1 = map(x_trf.transform, dL.intervalx)
y0, y1 = map(y_trf.transform, dL.intervaly)
xr = 1.05 * (x1 - x0)
yr = 1.05 * (y1 - y0)
|
def test_aspect_nonlinear_adjustable_datalim():
ax = fig.add_axes([.1, .1, .8, .8]) # Square.
ax.plot([.4, .6], [.4, .6]) # Set minpos to keep logit happy.
ax.set(xscale="log", xlim=(1, 10),
yscale="logit", ylim=(1/11, 1/1001),
aspect=1, adjustable="datalim")
ax.margins(0)
a... | def test_aspect_nonlinear_adjustable_datalim():
ax = fig.add_axes([.1, .1, .8, .8]) # Square.
ax.plot([.4, .6], [.4, .6]) # Set minpos to keep logit happy.
ax.set(xscale="log", xlim=(1, 100),
yscale="logit", ylim=(1 / 101, 1 / 11),
aspect=1, adjustable="datalim")
ax.margins(0)
... |
def standardize_weights(y,
"""Performs sample weight validation and standardization.
Everything gets normalized to a single sample-wise (or timestep-wise)
weight array.
# Arguments
y: Numpy array of model targets to be weighted. | def standardize_weights(y,
"""Performs sample weight validation and standardization.
Everything gets normalized to a single sample-wise (or timestep-wise)
weight array. If both `sample_weights` and `class_weights` are provided,
the weights are multiplied together.
# Arguments
y: Numpy arra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.