buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
def _create_atom(self, extensions=True):
# Atom requires a name. Skip elements without.
if not a.get('name'):
continue
author = etree.SubElement(feed, 'author')
name = etree.SubElement(author, 'name')
name.text = a.get('name')
if a.... | def _create_atom(self, extensions=True):
# Atom requires a name. Skip elements without.
if not a.get('name'):
continue
author = xml_elem('author', feed)
name = xml_elem('name', author)
name.text = a.get('name')
if a.get('email'):
... |
def _create_atom(self, extensions=True):
link.attrib['length'] = l['length']
for c in self.__atom_category or []:
cat = etree.SubElement(feed, 'category', term=c['term'])
if c.get('scheme'):
cat.attrib['scheme'] = c['scheme']
if c.get('label')... | def _create_atom(self, extensions=True):
link.attrib['length'] = l['length']
for c in self.__atom_category or []:
cat = xml_elem('category', feed, term=c['term'])
if c.get('scheme'):
cat.attrib['scheme'] = c['scheme']
if c.get('label'): |
def _create_atom(self, extensions=True):
# Atom requires a name. Skip elements without.
if not c.get('name'):
continue
contrib = etree.SubElement(feed, 'contributor')
name = etree.SubElement(contrib, 'name')
name.text = c.get('name')
... | def _create_atom(self, extensions=True):
# Atom requires a name. Skip elements without.
if not c.get('name'):
continue
contrib = xml_elem('contributor', feed)
name = xml_elem('name', contrib)
name.text = c.get('name')
if c.get('emai... |
def _create_atom(self, extensions=True):
generator.attrib['version'] = self.__atom_generator['version']
if self.__atom_icon:
icon = etree.SubElement(feed, 'icon')
icon.text = self.__atom_icon
if self.__atom_logo:
logo = etree.SubElement(feed, 'logo')... | def _create_atom(self, extensions=True):
generator.attrib['version'] = self.__atom_generator['version']
if self.__atom_icon:
icon = xml_elem('icon', feed)
icon.text = self.__atom_icon
if self.__atom_logo:
logo = xml_elem('logo', feed)
log... |
def _create_rss(self, extensions=True):
nsmap.update({'atom': 'http://www.w3.org/2005/Atom',
'content': 'http://purl.org/rss/1.0/modules/content/'})
feed = etree.Element('rss', version='2.0', nsmap=nsmap)
channel = etree.SubElement(feed, 'channel')
if not (self.__... | def _create_rss(self, extensions=True):
nsmap.update({'atom': 'http://www.w3.org/2005/Atom',
'content': 'http://purl.org/rss/1.0/modules/content/'})
feed = xml_elem('rss', version='2.0', nsmap=nsmap)
channel = xml_elem('channel', feed)
if not (self.__rss_title and... |
def _create_rss(self, extensions=True):
([] if self.__rss_description else ['description'])
missing = ', '.join(missing)
raise ValueError('Required fields not set (%s)' % missing)
title = etree.SubElement(channel, 'title')
title.text = self.__rss_title
... | def _create_rss(self, extensions=True):
([] if self.__rss_description else ['description'])
missing = ', '.join(missing)
raise ValueError('Required fields not set (%s)' % missing)
title = xml_elem('title', channel)
title.text = self.__rss_title
link ... |
def _create_rss(self, extensions=True):
break
if self.__rss_category:
for cat in self.__rss_category:
category = etree.SubElement(channel, 'category')
category.text = cat['value']
if cat.get('domain'):
category.attri... | def _create_rss(self, extensions=True):
break
if self.__rss_category:
for cat in self.__rss_category:
category = xml_elem('category', channel)
category.text = cat['value']
if cat.get('domain'):
category.attrib['domai... |
def _create_rss(self, extensions=True):
'registerProcedure')
cloud.attrib['protocol'] = self.__rss_cloud.get('protocol')
if self.__rss_copyright:
copyright = etree.SubElement(channel, 'copyright')
copyright.text = self.__rss_copyright
if self.__rss... | def _create_rss(self, extensions=True):
'registerProcedure')
cloud.attrib['protocol'] = self.__rss_cloud.get('protocol')
if self.__rss_copyright:
copyright = xml_elem('copyright', channel)
copyright.text = self.__rss_copyright
if self.__rss_docs:
... |
'''
import locale
import sys
def ensure_format(val, allowed, required, allowed_values=None, defaults=None): | '''
import locale
import sys
import lxml # nosec - we configure a safe parser below
# Configure a safe parser which does not allow XML entity expansion
parser = lxml.etree.XMLParser(
attribute_defaults=False,
dtd_validation=False,
load_dtd=False,
no_network=True,
recover=False,... |
class EventCollection(LineCollection):
.. plot:: gallery/lines_bars_and_markers/eventcollection_demo.py
"""
segment = (lineoffset + linelength / 2.,
lineoffset - linelength / 2.)
if positions is None or len(positions) == 0:
segments = []
elif hasa... | class EventCollection(LineCollection):
.. plot:: gallery/lines_bars_and_markers/eventcollection_demo.py
"""
if positions is None:
raise ValueError('positions must be an array-like object')
# Force a copy of positions
positions = np.array(positions, copy=True)
... |
def test_pathcollection_legend_elements():
ax.add_artist(l)
fig.canvas.draw() | def test_pathcollection_legend_elements():
ax.add_artist(l)
fig.canvas.draw()
def test_EventCollection_nosort():
# Check that EventCollection doesn't modify input in place
arr = np.array([3, 2, 1, 10])
coll = EventCollection(arr)
np.testing.assert_array_equal(arr, np.array([3, 2, 1, 10])) |
def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
check_lpar = False
for index, child in enumerate(list(node.children)):
if check_lpar:
if child.type == syms.atom:
if maybe_make_parens_invisible_in_atom(child, parent=node): | def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
check_lpar = False
for index, child in enumerate(list(node.children)):
# Add parentheses around long tuple unpacking in assignments.
if (
index == 0
and isinstance(child, Node)
and ch... |
def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
lpar = Leaf(token.LPAR, "")
rpar = Leaf(token.RPAR, "")
index = child.remove() or 0
node.insert_child(index, Node(syms.atom, [lpar, child, rpar]))
check_lpar = isinstance(... | def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
lpar = Leaf(token.LPAR, "")
rpar = Leaf(token.RPAR, "")
index = child.remove() or 0
prefix = child.prefix
child.prefix = ""
new_child = Node(syms.at... |
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_tuple_assign(self) -> None:
source, expected = read_data("tupleassign")
actual = fs(source)... |
b 2""",
# datetime64tz is handled correctly in agg_series,
# so is excluded here.
# return the same type (Series) as our caller
cls = dtype.construct_array_type()
result = try_cast_to_ea(cls, result, dtype=dtype)
elif numeric... | b 2""",
# datetime64tz is handled correctly in agg_series,
# so is excluded here.
if len(result) and isinstance(result[0], dtype.type):
cls = dtype.construct_array_type()
result = try_cast_to_ea(cls, result, dtype=dtype)
... |
class BaseGrouper:
if mask.any():
result = result.astype("float64")
result[mask] = np.nan
if kind == "aggregate" and self._filter_empty_groups and not counts.all():
assert result.ndim != 2 | class BaseGrouper:
if mask.any():
result = result.astype("float64")
result[mask] = np.nan
elif (
how == "add"
and is_integer_dtype(orig_values.dtype)
and is_extension_array_dtype(orig_values.dtype)
):
# We need t... |
def test_aggregate_mixed_types():
tm.assert_frame_equal(result, expected)
class TestLambdaMangling:
def test_basic(self):
df = pd.DataFrame({"A": [0, 0, 1, 1], "B": [1, 2, 3, 4]}) | def test_aggregate_mixed_types():
tm.assert_frame_equal(result, expected)
@pytest.mark.xfail(reason="Not implemented.")
def test_aggregate_udf_na_extension_type():
# https://github.com/pandas-dev/pandas/pull/31359
# This is currently failing to cast back to Int64Dtype.
# The presence of the NA causes ... |
def test_series_groupby_categorical_aggregation_getitem():
result = groups["foo"].agg("mean")
expected = groups.agg("mean")["foo"]
tm.assert_series_equal(result, expected) | def test_series_groupby_categorical_aggregation_getitem():
result = groups["foo"].agg("mean")
expected = groups.agg("mean")["foo"]
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize(
"func, expected_values",
[(pd.Series.nunique, [1, 1, 2]), (pd.Series.count, [1, 2, 2])],
)
def test_... |
def test_resample_integerarray():
result = ts.resample("3T").mean()
expected = Series(
[1, 4, 7], index=pd.date_range("1/1/2000", periods=3, freq="3T"), dtype="Int64"
)
tm.assert_series_equal(result, expected)
| def test_resample_integerarray():
result = ts.resample("3T").mean()
expected = Series(
[1, 4, 7],
index=pd.date_range("1/1/2000", periods=3, freq="3T"),
dtype="float64",
)
tm.assert_series_equal(result, expected)
|
def test_resample_categorical_data_with_timedeltaindex():
index=pd.to_timedelta([0, 10], unit="s"),
)
expected = expected.reindex(["Group_obj", "Group"], axis=1)
expected["Group"] = expected["Group_obj"].astype("category")
tm.assert_frame_equal(result, expected)
| def test_resample_categorical_data_with_timedeltaindex():
index=pd.to_timedelta([0, 10], unit="s"),
)
expected = expected.reindex(["Group_obj", "Group"], axis=1)
expected["Group"] = expected["Group_obj"]
tm.assert_frame_equal(result, expected)
|
class Language(object):
"""
if name not in self.pipe_names:
raise ValueError(Errors.E001.format(name=name, opts=self.pipe_names))
if ENABLE_PIPELINE_ANALYSIS:
analyze_all_pipes(self.pipeline)
return self.pipeline.pop(self.pipe_names.index(name))
def __call__(... | class Language(object):
"""
if name not in self.pipe_names:
raise ValueError(Errors.E001.format(name=name, opts=self.pipe_names))
removed = self.pipeline.pop(self.pipe_names.index(name))
if ENABLE_PIPELINE_ANALYSIS:
analyze_all_pipes(self.pipeline)
return ... |
def test_analysis_validate_attrs_valid():
def test_analysis_validate_attrs_invalid(attr):
with pytest.raises(ValueError):
validate_attrs([attr]) | def test_analysis_validate_attrs_valid():
def test_analysis_validate_attrs_invalid(attr):
with pytest.raises(ValueError):
validate_attrs([attr])
def test_analysis_validate_attrs_remove_pipe():
"""Test that attributes are validated correctly on remove."""
spacy.language.ENABLE_PIPELINE_ANALYSIS = T... |
def in_top_k(predictions, targets, k):
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1),
padding='valid', data_format=None):
data_format = normalize_data_format(data_format)
x = _preprocess_conv2d_input(x, data_format) | def in_top_k(predictions, targets, k):
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1),
padding='valid', data_format=None, dilation_rate=(1, 1)):
data_format = normalize_data_format(data_format)
x = _preprocess_conv2d_input(x, data_format) |
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1),
False,
padding,
padding],
output_shape=output_shape)
return _postprocess_conv2d_output(x, data_format)
| def conv2d_transpose(x, kernel, output_shape, strides=(1, 1),
False,
padding,
padding],
output_shape=output_shape,
dilation=dilation_rate)
return _postprocess_conv2d_output(x, data_format)
|
def _preprocess_conv1d_input(x, data_format):
return x, tf_data_format
def _preprocess_conv2d_input(x, data_format):
"""Transpose and cast the input before the conv2d.
# Arguments
x: input tensor.
data_format: string, `"channels_last"` or `"channels_first"`.
# Returns
A tenso... | def _preprocess_conv1d_input(x, data_format):
return x, tf_data_format
def _preprocess_conv2d_input(x, data_format, force_transpose=False):
"""Transpose and cast the input before the conv2d.
# Arguments
x: input tensor.
data_format: string, `"channels_last"` or `"channels_first"`.
... |
def _preprocess_conv2d_input(x, data_format):
x = tf.cast(x, 'float32')
tf_data_format = 'NHWC'
if data_format == 'channels_first':
if not _has_nchw_support():
x = tf.transpose(x, (0, 2, 3, 1)) # NCHW -> NHWC
else:
tf_data_format = 'NCHW' | def _preprocess_conv2d_input(x, data_format):
x = tf.cast(x, 'float32')
tf_data_format = 'NHWC'
if data_format == 'channels_first':
if not _has_nchw_support() or force_transpose:
x = tf.transpose(x, (0, 2, 3, 1)) # NCHW -> NHWC
else:
tf_data_format = 'NCHW' |
def conv2d(x, kernel, strides=(1, 1), padding='valid',
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1),
padding='valid', data_format=None):
"""2D deconvolution (i.e. transposed convolution).
# Arguments | def conv2d(x, kernel, strides=(1, 1), padding='valid',
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1),
padding='valid', data_format=None, dilation_rate=(1, 1)):
"""2D deconvolution (i.e. transposed convolution).
# Arguments |
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1),
data_format: string, `"channels_last"` or `"channels_first"`.
Whether to use Theano or TensorFlow/CNTK data format
for inputs/kernels/outputs.
# Returns
A tensor, result of transposed 2D convolution. | def conv2d_transpose(x, kernel, output_shape, strides=(1, 1),
data_format: string, `"channels_last"` or `"channels_first"`.
Whether to use Theano or TensorFlow/CNTK data format
for inputs/kernels/outputs.
dilation_rate: tuple of 2 integers.
# Returns
A tensor, result... |
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1),
if isinstance(output_shape, (tuple, list)):
output_shape = tf.stack(output_shape)
x, tf_data_format = _preprocess_conv2d_input(x, data_format)
if data_format == 'channels_first' and tf_data_format == 'NHWC':
output_shape = (outp... | def conv2d_transpose(x, kernel, output_shape, strides=(1, 1),
if isinstance(output_shape, (tuple, list)):
output_shape = tf.stack(output_shape)
# tf.nn.atrous_conv2d_transpose input only supports NHWC format
if data_format == 'channels_first' and dilation_rate != (1, 1):
force_transpose = T... |
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1),
else:
strides = (1, 1) + strides
x = tf.nn.conv2d_transpose(x, kernel, output_shape, strides,
padding=padding,
data_format=tf_data_format)
if data_format == 'channels_first' a... | def conv2d_transpose(x, kernel, output_shape, strides=(1, 1),
else:
strides = (1, 1) + strides
if dilation_rate == (1, 1):
x = tf.nn.conv2d_transpose(x, kernel, output_shape, strides,
padding=padding,
data_format=tf_data_form... |
def conv2d(x, kernel, strides=(1, 1), padding='valid',
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1),
padding='valid', data_format=None):
"""2D deconvolution (transposed convolution).
# Arguments | def conv2d(x, kernel, strides=(1, 1), padding='valid',
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1),
padding='valid', data_format=None, dilation_rate=(1, 1)):
"""2D deconvolution (transposed convolution).
# Arguments |
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1),
padding: string, "same" or "valid".
data_format: "channels_last" or "channels_first".
Whether to use Theano or TensorFlow data format
in inputs/kernels/outputs.
# Raises
ValueError: if using an even kernel siz... | def conv2d_transpose(x, kernel, output_shape, strides=(1, 1),
padding: string, "same" or "valid".
data_format: "channels_last" or "channels_first".
Whether to use Theano or TensorFlow data format
in inputs/kernels/outputs.
dilation_rate: tuple of 2 integers.
# Raises... |
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1),
kshp=kernel_shape,
subsample=strides,
border_mode=th_padding,
... | def conv2d_transpose(x, kernel, output_shape, strides=(1, 1),
kshp=kernel_shape,
subsample=strides,
border_mode=th_padding,
... |
class Conv2DTranspose(Conv2D):
padding='valid',
output_padding=None,
data_format=None,
activation=None,
use_bias=True,
kernel_initializer='glorot_uniform', | class Conv2DTranspose(Conv2D):
padding='valid',
output_padding=None,
data_format=None,
dilation_rate=(1, 1),
activation=None,
use_bias=True,
kernel_initializer='glorot_uniform', |
class Conv2DTranspose(Conv2D):
strides=strides,
padding=padding,
data_format=data_format,
activation=activation,
use_bias=use_bias,
kernel_initializer=kernel_initializer, | class Conv2DTranspose(Conv2D):
strides=strides,
padding=padding,
data_format=data_format,
dilation_rate=dilation_rate,
activation=activation,
use_bias=use_bias,
kernel_initializer=kernel_initializer, |
class Conv2DTranspose(Conv2D):
out_height = conv_utils.deconv_length(height,
stride_h, kernel_h,
self.padding,
out_pad_h)
out_width = conv_utils.deconv_length(width,
... | class Conv2DTranspose(Conv2D):
out_height = conv_utils.deconv_length(height,
stride_h, kernel_h,
self.padding,
out_pad_h,
self.d... |
class Conv2DTranspose(Conv2D):
output_shape,
self.strides,
padding=self.padding,
data_format=self.data_format)
if self.use_bias:
outputs = K.bias_add( | class Conv2DTranspose(Conv2D):
output_shape,
self.strides,
padding=self.padding,
data_format=self.data_format,
dilation_rate=self.dilation_rate)
if self.use_bias:
outputs = K.bias_add( |
class Conv2DTranspose(Conv2D):
stride_h,
kernel_h,
self.padding,
out_pad_h)
output_shape... | class Conv2DTranspose(Conv2D):
stride_h,
kernel_h,
self.padding,
out_pad_h,
... |
def conv_input_length(output_length, filter_size, padding, stride):
return (output_length - 1) * stride - 2 * pad + filter_size
def deconv_length(dim_size, stride_size, kernel_size, padding, output_padding):
"""Determines output length of a transposed convolution given input length.
# Arguments | def conv_input_length(output_length, filter_size, padding, stride):
return (output_length - 1) * stride - 2 * pad + filter_size
def deconv_length(dim_size, stride_size, kernel_size, padding,
output_padding, dilation=1):
"""Determines output length of a transposed convolution given input leng... |
def deconv_length(dim_size, stride_size, kernel_size, padding, output_padding):
padding: One of `"same"`, `"valid"`, `"full"`.
output_padding: Integer, amount of padding along the output dimension,
Can be set to `None` in which case the output length is inferred.
# Returns
The o... | def deconv_length(dim_size, stride_size, kernel_size, padding, output_padding):
padding: One of `"same"`, `"valid"`, `"full"`.
output_padding: Integer, amount of padding along the output dimension,
Can be set to `None` in which case the output length is inferred.
dilation: dilation r... |
def deconv_length(dim_size, stride_size, kernel_size, padding, output_padding):
if dim_size is None:
return None
# Infer length if output padding is None, else compute the exact length
if output_padding is None:
if padding == 'valid': | def deconv_length(dim_size, stride_size, kernel_size, padding, output_padding):
if dim_size is None:
return None
# Get the dilated kernel size
kernel_size = kernel_size + (kernel_size - 1) * (dilation - 1)
# Infer length if output padding is None, else compute the exact length
if output_pa... |
def test_convolution_2d_channels_last():
@keras_test
@pytest.mark.skipif((K.backend() == 'cntk'),
reason="cntk only supports dilated conv on GPU")
def test_convolution_2d_dilation():
num_samples = 2
filters = 2 | def test_convolution_2d_channels_last():
@keras_test
@pytest.mark.skipif((K.backend() == 'cntk'),
reason='cntk only supports dilated conv on GPU')
def test_convolution_2d_dilation():
num_samples = 2
filters = 2 |
def test_conv2d_transpose(padding, out_padding, strides):
fixed_batch_size=True)
@keras_test
def test_conv2d_transpose_channels_first():
num_samples = 2 | def test_conv2d_transpose(padding, out_padding, strides):
fixed_batch_size=True)
@keras_test
@pytest.mark.skipif((K.backend() == 'cntk'),
reason='cntk only supports dilated conv transpose on GPU')
def test_conv2d_transpose_dilation():
layer_test(convolutional.Conv2DTranspose,
... |
MSG_USERAUTH_INFO_REQUEST, MSG_USERAUTH_INFO_RESPONSE = range(60, 62)
MSG_USERAUTH_GSSAPI_RESPONSE, MSG_USERAUTH_GSSAPI_TOKEN = range(60, 62)
MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE, MSG_USERAUTH_GSSAPI_ERROR,\
MSG_USERAUTH_GSSAPI_ERRTOK, MSG_USERAUTH_GSSAPI_MIC = range(63, 67)
MSG_GLOBAL_REQUEST, MSG_REQUEST_SUCCESS... | MSG_USERAUTH_INFO_REQUEST, MSG_USERAUTH_INFO_RESPONSE = range(60, 62)
MSG_USERAUTH_GSSAPI_RESPONSE, MSG_USERAUTH_GSSAPI_TOKEN = range(60, 62)
MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE, MSG_USERAUTH_GSSAPI_ERROR,\
MSG_USERAUTH_GSSAPI_ERRTOK, MSG_USERAUTH_GSSAPI_MIC = range(63, 67)
HIGHEST_USERAUTH_MESSAGE_ID = 79
MSG_GL... |
from paramiko.common import (
MSG_CHANNEL_FAILURE, MSG_CHANNEL_DATA, MSG_CHANNEL_EXTENDED_DATA,
MSG_CHANNEL_WINDOW_ADJUST, MSG_CHANNEL_REQUEST, MSG_CHANNEL_EOF,
MSG_CHANNEL_CLOSE, MIN_WINDOW_SIZE, MIN_PACKET_SIZE, MAX_WINDOW_SIZE,
DEFAULT_WINDOW_SIZE, DEFAULT_MAX_PACKET_SIZE,
)
from paramiko.compress im... | from paramiko.common import (
MSG_CHANNEL_FAILURE, MSG_CHANNEL_DATA, MSG_CHANNEL_EXTENDED_DATA,
MSG_CHANNEL_WINDOW_ADJUST, MSG_CHANNEL_REQUEST, MSG_CHANNEL_EOF,
MSG_CHANNEL_CLOSE, MIN_WINDOW_SIZE, MIN_PACKET_SIZE, MAX_WINDOW_SIZE,
DEFAULT_WINDOW_SIZE, DEFAULT_MAX_PACKET_SIZE, HIGHEST_USERAUTH_MESSAGE_ID... |
class Transport(threading.Thread, ClosingContextManager):
max_packet_size = self.default_max_packet_size
return clamp_value(MIN_PACKET_SIZE, max_packet_size, MAX_WINDOW_SIZE)
def run(self):
# (use the exposed "run" method, because if we specify a thread target | class Transport(threading.Thread, ClosingContextManager):
max_packet_size = self.default_max_packet_size
return clamp_value(MIN_PACKET_SIZE, max_packet_size, MAX_WINDOW_SIZE)
def _ensure_authed(self, ptype, message):
"""
Checks message type against current auth state.
I... |
class Transport(threading.Thread, ClosingContextManager):
continue
if ptype in self._handler_table:
self._handler_table[ptype](self, m)
elif ptype in self._channel_handler_table:
chanid = m.get_int()
... | class Transport(threading.Thread, ClosingContextManager):
continue
if ptype in self._handler_table:
error_msg = self._ensure_authed(ptype, m)
if error_msg:
self._send_message(error_msg)
... |
def main():
'error message')
parser.add_argument('--log-file',
default='/tmp/{prog_name}.log'.format(
prog_name=prog_name),
help='log file pathname')
| def main():
'error message')
parser.add_argument('--log-file',
default='{prog_name}.log'.format(
prog_name=prog_name),
help='log file pathname')
|
def parse(validator_string, validators=None):
validators = validators or val.DefaultValidators
try:
tree = ast.parse(validator_string, mode='eval')
# evaluate with access to a limited global scope only |
def parse(validator_string, validators=None):
validators = validators or val.DefaultValidators
if validator_string:
for validator in validators.keys():
if validator_string.startswith(validator):
break
else:
raise SyntaxError(
'Invalid sch... |
def ct_lt_u32(val_a, val_b):
return (val_a^((val_a^val_b)|(((val_a-val_b)&0xffffffff)^val_b)))>>31
def ct_gt_u32(val_a, val_b):
"""
Return 1 if val_a > val_b, 0 otherwise. Constant time. | def ct_lt_u32(val_a, val_b):
return (val_a^((val_a^val_b)|(((val_a-val_b)&0xffffffff)^val_b)))>>31
def ct_gt_u32(val_a, val_b):
"""
Return 1 if val_a > val_b, 0 otherwise. Constant time. |
def ct_gt_u32(val_a, val_b):
"""
return ct_lt_u32(val_b, val_a)
def ct_le_u32(val_a, val_b):
"""
Return 1 if val_a <= val_b, 0 otherwise. Constant time. | def ct_gt_u32(val_a, val_b):
"""
return ct_lt_u32(val_b, val_a)
def ct_le_u32(val_a, val_b):
"""
Return 1 if val_a <= val_b, 0 otherwise. Constant time. |
def ct_le_u32(val_a, val_b):
"""
return 1 ^ ct_gt_u32(val_a, val_b)
def ct_lsb_prop_u8(val):
"""Propagate LSB to all 8 bits of the returned byte. Constant time."""
val &= 0x01
val |= val << 1
val |= val << 2
val |= val << 4
return val
def ct_isnonzero_u32(val):
"""
Returns 1 if... | def ct_le_u32(val_a, val_b):
"""
return 1 ^ ct_gt_u32(val_a, val_b)
def ct_lsb_prop_u8(val):
"""Propagate LSB to all 8 bits of the returned int. Constant time."""
val &= 0x01
val |= val << 1
val |= val << 2
val |= val << 4
return val
def ct_lsb_prop_u16(val):
"""Propagate LSB to ... |
def ct_isnonzero_u32(val):
val &= 0xffffffff
return (val|(-val&0xffffffff)) >> 31
def ct_neq_u32(val_a, val_b):
"""
Return 1 if val_a != val_b, 0 otherwise. Constant time. | def ct_isnonzero_u32(val):
val &= 0xffffffff
return (val|(-val&0xffffffff)) >> 31
def ct_neq_u32(val_a, val_b):
"""
Return 1 if val_a != val_b, 0 otherwise. Constant time. |
def parsePEMKey(s, private=False, public=False, passwordCallback=None,
def _parseKeyHelper(key, private, public):
if private:
if not key.hasPrivateKey():
raise SyntaxError("Not a private key!")
if public:
return _createPublicKey(key)
if private:
if hasattr(key, "d"):
... | def parsePEMKey(s, private=False, public=False, passwordCallback=None,
def _parseKeyHelper(key, private, public):
if private and not key.hasPrivateKey():
raise SyntaxError("Not a private key!")
if public:
return _createPublicKey(key)
if private:
if cryptomath.m2cryptoLoaded:
... |
from .rsakey import *
from .python_rsakey import Python_RSAKey
from .compat import compatAscii2Bytes
#copied from M2Crypto.util.py, so when we load the local copy of m2
#we can still use it | from .rsakey import *
from .python_rsakey import Python_RSAKey
from .compat import compatAscii2Bytes
import sys
#copied from M2Crypto.util.py, so when we load the local copy of m2
#we can still use it |
def _rawPrivateKeyOp(self, message):
ciphertext = bytesToNumber(bytearray(string))
return ciphertext
def _rawPublicKeyOp(self, ciphertext):
data = numberToByteArray(ciphertext, numBytes(self.n))
string = m2.rsa_public_decrypt(self.rsa, bytes(data), | def _rawPrivateKeyOp(self, message):
ciphertext = bytesToNumber(bytearray(string))
return ciphertext
def _raw_private_key_op_bytes(self, message):
return bytearray(m2.rsa_private_encrypt(self.rsa, bytes(message),
m2.no_padd... |
def _rawPublicKeyOp(self, ciphertext):
message = bytesToNumber(bytearray(string))
return message
def acceptsPassword(self): return True
def write(self, password=None): | def _rawPublicKeyOp(self, ciphertext):
message = bytesToNumber(bytearray(string))
return message
def _raw_public_key_op_bytes(self, ciphertext):
return bytearray(m2.rsa_public_decrypt(self.rsa, bytes(ciphertext),
m2.no_paddi... |
def f():pass
key._hasPrivateKey = False
else:
raise SyntaxError()
return key
finally:
m2.bio_free(bio) | def f():pass
key._hasPrivateKey = False
else:
raise SyntaxError()
if key._hasPrivateKey:
if sys.version_info < (3, 0):
b64_key = str(key.write())
else:
... |
def parsePEM(s, passwordCallback=None):
elif pemSniff(s, "EC PRIVATE KEY"):
bytes = dePem(s, "EC PRIVATE KEY")
return Python_Key._parse_ecc_ssleay(bytes)
else:
raise SyntaxError("Not a PEM private key file")
@staticmethod
def _parse_pkcs8(bytes):
pars... | def parsePEM(s, passwordCallback=None):
elif pemSniff(s, "EC PRIVATE KEY"):
bytes = dePem(s, "EC PRIVATE KEY")
return Python_Key._parse_ecc_ssleay(bytes)
elif pemSniff(s, "PUBLIC KEY"):
bytes = dePem(s, "PUBLIC KEY")
return Python_Key._parse_public_key(byt... |
from . import tlshashlib as hashlib
from ..errors import MaskTooLongError, MessageTooLongError, EncodingError, \
InvalidSignature, UnknownRSAType
class RSAKey(object): | from . import tlshashlib as hashlib
from ..errors import MaskTooLongError, MessageTooLongError, EncodingError, \
InvalidSignature, UnknownRSAType
from .constanttime import ct_isnonzero_u32, ct_neq_u32, ct_lsb_prop_u8, \
ct_lsb_prop_u16, ct_lt_u32
class RSAKey(object): |
def __init__(self, n=0, e=0, key_type="rsa"):
self.e = e
# pylint: enable=invalid-name
self.key_type = key_type
raise NotImplementedError()
def __len__(self): | def __init__(self, n=0, e=0, key_type="rsa"):
self.e = e
# pylint: enable=invalid-name
self.key_type = key_type
self._key_hash = None
raise NotImplementedError()
def __len__(self): |
def RSASSA_PSS_sign(self, mHash, hAlg, sLen=0):
:type sLen: int
:param sLen: length of salt"""
EM = self.EMSA_PSS_encode(mHash, numBits(self.n) - 1, hAlg, sLen)
m = bytesToNumber(EM)
if m >= self.n:
raise MessageTooLongError("Encode output too long")
s = self.... | def RSASSA_PSS_sign(self, mHash, hAlg, sLen=0):
:type sLen: int
:param sLen: length of salt"""
EM = self.EMSA_PSS_encode(mHash, numBits(self.n) - 1, hAlg, sLen)
try:
ret = self._raw_private_key_op_bytes(EM)
except ValueError:
raise MessageTooLongError("Enc... |
def RSASSA_PSS_verify(self, mHash, S, hAlg, sLen=0):
:type sLen: int
:param sLen: Length of salt
"""
if len(bytearray(S)) != len(numberToByteArray(self.n)):
raise InvalidSignature("Invalid signature")
s = bytesToNumber(S)
m = self._rawPublicKeyOp(s)
EM... | def RSASSA_PSS_verify(self, mHash, S, hAlg, sLen=0):
:type sLen: int
:param sLen: Length of salt
"""
try:
EM = self._raw_public_key_op_bytes(S)
except ValueError:
raise InvalidSignature("Invalid signature")
result = self.EMSA_PSS_verify(mHash, EM, ... |
def _raw_pkcs1_sign(self, bytes):
if not self.hasPrivateKey():
raise AssertionError()
paddedBytes = self._addPKCS1Padding(bytes, 1)
m = bytesToNumber(paddedBytes)
if m >= self.n:
raise ValueError()
c = self._rawPrivateKeyOp(m)
sigBytes = numberToBy... | def _raw_pkcs1_sign(self, bytes):
if not self.hasPrivateKey():
raise AssertionError()
paddedBytes = self._addPKCS1Padding(bytes, 1)
return self._raw_private_key_op_bytes(paddedBytes)
def sign(self, bytes, padding='pkcs1', hashAlg=None, saltLen=None):
"""Sign the passed-i... |
def sign(self, bytes, padding='pkcs1', hashAlg=None, saltLen=None):
def _raw_pkcs1_verify(self, sigBytes, bytes):
"""Perform verification operation on raw PKCS#1 padded signature"""
if len(sigBytes) != numBytes(self.n):
return False
paddedBytes = self._addPKCS1Padding(bytes, 1)
... | def sign(self, bytes, padding='pkcs1', hashAlg=None, saltLen=None):
def _raw_pkcs1_verify(self, sigBytes, bytes):
"""Perform verification operation on raw PKCS#1 padded signature"""
try:
checkBytes = self._raw_public_key_op_bytes(sigBytes)
except ValueError:
return F... |
def encrypt(self, bytes):
:returns: A PKCS1 encryption of the passed-in data.
"""
paddedBytes = self._addPKCS1Padding(bytes, 2)
m = bytesToNumber(paddedBytes)
if m >= self.n:
raise ValueError()
c = self._rawPublicKeyOp(m)
encBytes = numberToByteArray(c... | def encrypt(self, bytes):
:returns: A PKCS1 encryption of the passed-in data.
"""
paddedBytes = self._addPKCS1Padding(bytes, 2)
return self._raw_public_key_op_bytes(paddedBytes)
def _dec_prf(self, key, label, out_len):
"""PRF for deterministic implicit rejection in the RSA d... |
def _rawPrivateKeyOp(self, message):
def _rawPublicKeyOp(self, ciphertext):
raise NotImplementedError()
def acceptsPassword(self):
"""Return True if the write() method accepts a password for use
in encrypting the private key. | def _rawPrivateKeyOp(self, message):
def _rawPublicKeyOp(self, ciphertext):
raise NotImplementedError()
def _raw_private_key_op_bytes(self, message):
n = self.n
if len(message) != numBytes(n):
raise ValueError("Message has incorrect length for the key size")
m_int = ... |
from tlslite.utils.constanttime import ct_lt_u32, ct_gt_u32, ct_le_u32, \
ct_lsb_prop_u8, ct_isnonzero_u32, ct_neq_u32, ct_eq_u32, \
ct_check_cbc_mac_and_pad, ct_compare_digest
from hypothesis import given, example
import hypothesis.strategies as st |
from tlslite.utils.constanttime import ct_lt_u32, ct_gt_u32, ct_le_u32, \
ct_lsb_prop_u8, ct_isnonzero_u32, ct_neq_u32, ct_eq_u32, \
ct_check_cbc_mac_and_pad, ct_compare_digest, ct_lsb_prop_u16
from hypothesis import given, example
import hypothesis.strategies as st |
def test_ct_lsb_prop_u8(self, i):
self.assertEqual(((i & 0x1) == 1), (ct_lsb_prop_u8(i) == 0xff))
self.assertEqual(((i & 0x1) == 0), (ct_lsb_prop_u8(i) == 0x00))
@given(i=st.integers(0,2**32 - 1))
@example(i=0)
def test_ct_isnonzero_u32(self, i): | def test_ct_lsb_prop_u8(self, i):
self.assertEqual(((i & 0x1) == 1), (ct_lsb_prop_u8(i) == 0xff))
self.assertEqual(((i & 0x1) == 0), (ct_lsb_prop_u8(i) == 0x00))
@given(i=st.integers(0, 2**16-1))
@example(i=0)
@example(i=255)
@example(i=2**16-1)
def test_ct_lsb_prop_u16(self, i):
... |
from tlslite.utils.python_rsakey import Python_RSAKey
from tlslite.utils.cryptomath import *
from tlslite.errors import *
try:
import mock
from mock import call | from tlslite.utils.python_rsakey import Python_RSAKey
from tlslite.utils.cryptomath import *
from tlslite.errors import *
from tlslite.utils.keyfactory import parsePEMKey
from tlslite.utils.compat import a2b_hex, remove_whitespace
try:
import mock
from mock import call |
def test_addPKCS1Prefix(self):
self.assertEqual(RSAKey.addPKCS1Prefix(data, 'sha1'), bytearray(
b'0!0\t\x06\x05+\x0e\x03\x02\x1a\x05\x00\x04\x14' +
b' sha-1 hash of data ')) | def test_addPKCS1Prefix(self):
self.assertEqual(RSAKey.addPKCS1Prefix(data, 'sha1'), bytearray(
b'0!0\t\x06\x05+\x0e\x03\x02\x1a\x05\x00\x04\x14' +
b' sha-1 hash of data '))
class TestRSADecrypt(unittest.TestCase):
@classmethod
def setUpClass(cls):
priv_key = """
-----B... |
class TestYoutubeDL(unittest.TestCase):
'ext': 'mp4',
'width': None,
'height': 1080,
}
def fname(templ): | class TestYoutubeDL(unittest.TestCase):
'ext': 'mp4',
'width': None,
'height': 1080,
'title1': '$PATH',
'title2': '%PATH%',
}
def fname(templ): |
class TestYoutubeDL(unittest.TestCase):
self.assertEqual(fname('%(height)0 6d.%(ext)s'), ' 01080.mp4')
self.assertEqual(fname('%(height)0 6d.%(ext)s'), ' 01080.mp4')
self.assertEqual(fname('%(height) 0 6d.%(ext)s'), ' 01080.mp4')
self.assertEqual(fname('%%(height)06d.%(ext)s'), '%(... | class TestYoutubeDL(unittest.TestCase):
self.assertEqual(fname('%(height)0 6d.%(ext)s'), ' 01080.mp4')
self.assertEqual(fname('%(height)0 6d.%(ext)s'), ' 01080.mp4')
self.assertEqual(fname('%(height) 0 6d.%(ext)s'), ' 01080.mp4')
self.assertEqual(fname('%%'), '%')
self.asse... |
import re
import shutil
import subprocess
import socket
import sys
import time
import tokenize | import re
import shutil
import subprocess
import socket
import string
import sys
import time
import tokenize |
class YoutubeDL(object):
FORMAT_RE.format(numeric_field),
r'%({0})s'.format(numeric_field), outtmpl)
filename = expand_path(outtmpl % template_dict)
# Temporary fix for #4787
# 'Treat' all problem characters by passing filename through... | class YoutubeDL(object):
FORMAT_RE.format(numeric_field),
r'%({0})s'.format(numeric_field), outtmpl)
# expand_path translates '%%' into '%' and '$$' into '$'
# correspondingly that is not what we want since we need to keep
# '%%' intac... |
from .helper import on_ci
"Tests/images/crash_1.tif",
"Tests/images/crash_2.tif",
"Tests/images/crash-2020-10-test.tif",
],
)
@pytest.mark.filterwarnings("ignore:Possibly corrupt EXIF data") | from .helper import on_ci
"Tests/images/crash_1.tif",
"Tests/images/crash_2.tif",
"Tests/images/crash-2020-10-test.tif",
"Tests/images/crash-1152ec2d1a1a71395b6f2ce6721c38924d025bf3.tif",
"Tests/images/crash-0e16d3bfb83be87356d026d66919deaefca44dac.tif",
],
)
@pytest.mark.fil... |
import pytest
import warnings
from mock import Mock, patch
from thefuck.utils import default_settings, \
memoize, get_closest, get_all_executables, replace_argument, \
get_all_matched_commands, is_app, for_app, cache, \ |
import pytest
import warnings
from mock import Mock, call, patch
from thefuck.utils import default_settings, \
memoize, get_closest, get_all_executables, replace_argument, \
get_all_matched_commands, is_app, for_app, cache, \ |
def test_get_all_executables():
assert 'fuck' not in all_callables
@pytest.mark.parametrize('args, result', [
(('apt-get instol vim', 'instol', 'install'), 'apt-get install vim'),
(('git brnch', 'brnch', 'branch'), 'git branch')]) | def test_get_all_executables():
assert 'fuck' not in all_callables
@pytest.fixture
def os_environ_pathsep(monkeypatch, path, pathsep):
env = {'PATH': path}
monkeypatch.setattr('os.environ', env)
monkeypatch.setattr('os.pathsep', pathsep)
return env
@pytest.mark.usefixtures('no_memoize', 'os_envi... |
def get_all_executables():
tf_entry_points = ['thefuck', 'fuck']
bins = [exe.name.decode('utf8') if six.PY2 else exe.name
for path in os.environ.get('PATH', '').split(':')
for exe in _safe(lambda: list(Path(path).iterdir()), [])
if not _safe(exe.is_dir, True)
and... | def get_all_executables():
tf_entry_points = ['thefuck', 'fuck']
bins = [exe.name.decode('utf8') if six.PY2 else exe.name
for path in os.environ.get('PATH', '').split(os.pathsep)
for exe in _safe(lambda: list(Path(path).iterdir()), [])
if not _safe(exe.is_dir, True)
... |
def verify_collections(collections, search_paths, apis, validate_certs, ignore_e
for search_path in search_paths:
b_search_path = to_bytes(os.path.join(search_path, namespace, name), errors='surrogate_or_strict')
if os.path.isdir(b_search_path):
... | def verify_collections(collections, search_paths, apis, validate_certs, ignore_e
for search_path in search_paths:
b_search_path = to_bytes(os.path.join(search_path, namespace, name), errors='surrogate_or_strict')
if os.path.isdir(b_search_path):
... |
def test_verify_identical(monkeypatch, mock_collection, manifest_info, files_man
assert mock_debug.call_args_list[-1][0][0] == success_msg
@patch.object(collection.CollectionRequirement, 'verify')
def test_verify_collections_not_installed(mock_verify, mock_collection, monkeypatch):
namespace = 'ansibl... | def test_verify_identical(monkeypatch, mock_collection, manifest_info, files_man
assert mock_debug.call_args_list[-1][0][0] == success_msg
@patch.object(os.path, 'isdir', return_value=True)
def test_verify_collections_no_version(mock_isdir, mock_collection, monkeypatch):
namespace = 'ansible_namespace... |
def test_verify_collections_not_installed_ignore_errors(mock_verify, mock_collec
@patch.object(os.path, 'isdir', return_value=True)
@patch.object(collection.CollectionRequirement, 'verify')
def test_verify_collections_no_remote(mock_verify, mock_isdir, mock_collection):
namespace = 'ansible_namespace'
name = '... | def test_verify_collections_not_installed_ignore_errors(mock_verify, mock_collec
@patch.object(os.path, 'isdir', return_value=True)
@patch.object(collection.CollectionRequirement, 'verify')
def test_verify_collections_no_remote(mock_verify, mock_isdir, mock_collection, monkeypatch):
namespace = 'ansible_namespace'... |
def test_verify_collections_no_remote(mock_verify, mock_isdir, mock_collection):
@patch.object(os.path, 'isdir', return_value=True)
@patch.object(collection.CollectionRequirement, 'verify')
def test_verify_collections_no_remote_ignore_errors(mock_verify, mock_isdir, mock_collection):
namespace = 'ansible_namespace... | def test_verify_collections_no_remote(mock_verify, mock_isdir, mock_collection):
@patch.object(os.path, 'isdir', return_value=True)
@patch.object(collection.CollectionRequirement, 'verify')
def test_verify_collections_no_remote_ignore_errors(mock_verify, mock_isdir, mock_collection, monkeypatch):
namespace = 'ansi... |
def test_verify_collections_url(monkeypatch):
assert err.value.message == msg
@patch.object(os.path, 'isfile', return_value=False)
@patch.object(os.path, 'isdir', return_value=True)
@patch.object(collection.CollectionRequirement, 'verify')
def test_verify_collections_name(mock_verify, mock_isdir, mock_isfile, moc... | def test_verify_collections_url(monkeypatch):
assert err.value.message == msg
@patch.object(os.path, 'isdir', return_value=True)
@patch.object(collection.CollectionRequirement, 'verify')
def test_verify_collections_name(mock_verify, mock_isdir, mock_collection, monkeypatch):
local_collection = mock_collection... |
from keystone import catalog
from keystone.common import logging
from keystone.common import utils
from keystone.common import wsgi
from keystone import exception
from keystone import identity |
from keystone import catalog
from keystone.common import logging
from keystone.common import wsgi
from keystone import exception
from keystone import identity |
def authenticate(self, context, auth=None):
if not user_ref.get('enabled', True):
LOG.warning('User %s is disabled' % user_id)
raise exception.Unauthorized()
except AssertionError as e:
raise exception.Unauthorized(e.message)
| def authenticate(self, context, auth=None):
if not user_ref.get('enabled', True):
LOG.warning('User %s is disabled' % user_id)
raise exception.Unauthorized()
# If the tenant is disabled don't allow them to authenticate
if tenant_re... |
def authenticate(self, context, auth=None):
tenant_ref = None
metadata_ref = {}
catalog_ref = {}
token_ref = self.token_api.create_token(
context, token_id, dict(id=token_id, | def authenticate(self, context, auth=None):
tenant_ref = None
metadata_ref = {}
catalog_ref = {}
except exception.MetadataNotFound:
metadata_ref = {}
catalog_ref = {}
# If the tenant is disabled don't allow them to ... |
def test_authenticate_no_username(self):
self.get_client,
user_ref)
# FIXME(ja): this test should require the "keystone:admin" roled
# (probably the role set via --keystone_admin_role flag)
# FIXME(ja): add a test that admin endpoint is only se... | def test_authenticate_no_username(self):
self.get_client,
user_ref)
def test_authenticate_disabled_tenant(self):
from keystoneclient import exceptions as client_exceptions
admin_client = self.get_client(admin=True)
tenant = {
... |
from ansible.release import __version__
from ansible.utils.collection_loader import set_collection_playbook_paths
from ansible.utils.display import Display
from ansible.utils.path import unfrackpath
from ansible.vars.manager import VariableManager
| from ansible.release import __version__
from ansible.utils.collection_loader import set_collection_playbook_paths
from ansible.utils.display import Display
from ansible.utils.path import unfrackpath
from ansible.utils.unsafe_proxy import AnsibleUnsafeBytes
from ansible.vars.manager import VariableManager
|
class CLI(with_metaclass(ABCMeta, object)):
except EOFError:
pass
return (sshpass, becomepass)
def validate_conflicts(self, op, vault_opts=False, runas_opts=False, fork_opts=False, vault_rekey_opts=False): | class CLI(with_metaclass(ABCMeta, object)):
except EOFError:
pass
# we 'wrap' the passwords to prevent templating as
# they can contain special chars and trigger it incorrectly
if sshpass:
sshpass = AnsibleUnsafeBytes(sshpass)
if becomepass:
b... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.module_utils.six import string_types, text_type
from ansible.module_utils._text import to_text
from ansible.module_utils.common._collections_compat import Mapping, MutableSequence, Set
| from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.module_utils.six import string_types, text_type, binary_type
from ansible.module_utils._text import to_text
from ansible.module_utils.common._collections_compat import Mapping, MutableSequence, Set
|
class AnsibleUnsafeText(text_type, AnsibleUnsafe):
pass
class UnsafeProxy(object):
def __new__(cls, obj, *args, **kwargs):
# In our usage we should only receive unicode strings.
# This conditional and conversion exists to sanity check the values
# we're given but we may want to take it... | class AnsibleUnsafeText(text_type, AnsibleUnsafe):
pass
class AnsibleUnsafeBytes(binary_type, AnsibleUnsafe):
pass
class UnsafeProxy(object):
def __new__(cls, obj, *args, **kwargs):
# In our usage we should only receive unicode strings.
# This conditional and conversion exists to sanity ... |
class EmptyLineTracker:
# Don't insert empty lines between decorators.
return 0, 0
newlines = 2
if current_line.depth:
newlines -= 1 | class EmptyLineTracker:
# Don't insert empty lines between decorators.
return 0, 0
if is_decorator and self.previous_line and self.previous_line.is_comment:
# Don't insert empty lines between decorator comments.
return 0, 0
newlin... |
class BlackTestCase(unittest.TestCase):
)
self.assertEqual(result.exit_code, 1)
if __name__ == "__main__":
unittest.main() | class BlackTestCase(unittest.TestCase):
)
self.assertEqual(result.exit_code, 1)
@patch("black.dump_to_file", dump_to_stderr)
def test_comment_in_decorator(self) -> None:
source, expected = read_data("comments6")
actual = fs(source)
self.assertFormatEqual(expected... |
def url_has_any_extension(url, extensions):
def _safe_ParseResult(parts, encoding='utf8', path_encoding='utf8'):
return (
to_native_str(parts.scheme),
to_native_str(parts.netloc.encode('idna')),
# default encoding for path component SHOULD be UTF-8
quote(to_bytes(parts.path, path_... | def url_has_any_extension(url, extensions):
def _safe_ParseResult(parts, encoding='utf8', path_encoding='utf8'):
# IDNA encoding can fail for too long labels (>63 characters)
# or missing labels (e.g. http://.example.com)
try:
netloc = parts.netloc.encode('idna')
except UnicodeError:
n... |
class CanonicalizeUrlTest(unittest.TestCase):
# without encoding, already canonicalized URL is canonicalized identically
self.assertEqual(canonicalize_url(canonicalized), canonicalized)
class AddHttpIfNoScheme(unittest.TestCase):
| class CanonicalizeUrlTest(unittest.TestCase):
# without encoding, already canonicalized URL is canonicalized identically
self.assertEqual(canonicalize_url(canonicalized), canonicalized)
def test_canonicalize_url_idna_exceptions(self):
# missing DNS label
self.assertEqual(
... |
class PolarAxes(Axes):
@cbook._delete_parameter("3.3", "args")
@cbook._delete_parameter("3.3", "kwargs")
def draw(self, renderer, *args, **kwargs):
thetamin, thetamax = np.rad2deg(self._realViewLim.intervalx)
if thetamin > thetamax:
thetamin, thetamax = thetamax, thetamin | class PolarAxes(Axes):
@cbook._delete_parameter("3.3", "args")
@cbook._delete_parameter("3.3", "kwargs")
def draw(self, renderer, *args, **kwargs):
self._unstale_viewLim()
thetamin, thetamax = np.rad2deg(self._realViewLim.intervalx)
if thetamin > thetamax:
thetamin, theta... |
def test_polar_invertedylim():
def test_polar_invertedylim_rorigin():
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)
ax.set_ylim(2, 0)
ax.set_rorigin(3)
| def test_polar_invertedylim():
def test_polar_invertedylim_rorigin():
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)
ax.yaxis.set_inverted(True)
# Set the rlims to inverted (2, 0) without calling set_rlim, to check that
# viewlims are correctly unstaled before draw()ing.
... |
import json
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db.models.deletion import CASCADE
from django.urls import reverse
from django.urls.exceptions import NoReverseMatch | import json
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
from django.db.models.deletion import CASCADE
from django.urls import reverse
from django.urls.exceptions import NoReverseMatch |
class AdminEmailInputWidget(forms.EmailInput):
class AdminURLFieldWidget(forms.URLInput):
template_name = 'admin/widgets/url.html'
def __init__(self, attrs=None):
super().__init__(attrs={'class': 'vURLField', **(attrs or {})})
def get_context(self, name, value, attrs):
context = super().ge... | class AdminEmailInputWidget(forms.EmailInput):
class AdminURLFieldWidget(forms.URLInput):
template_name = 'admin/widgets/url.html'
def __init__(self, attrs=None, validator_class=URLValidator):
super().__init__(attrs={'class': 'vURLField', **(attrs or {})})
self.validator = validator_class()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.