buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
class TestAsOfMerge:
)
assert_frame_equal(result, expected) | class TestAsOfMerge:
)
assert_frame_equal(result, expected)
def test_int_type_tolerance(self, any_int_dtype):
# GH #28870
left = pd.DataFrame({"a": [0, 10, 20], "left_val": [1, 2, 3]})
right = pd.DataFrame({"a": [5, 15, 25], "right_val": [1, 2, 3]})
left["a"] = lef... |
class URLValidator(RegexValidator):
ul = '\u00a1-\uffff' # unicode letters range (must not be a raw string)
# IP patterns
ipv4_re = r'(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}'
ipv6_re = r'\[[0-9a-f:\.]+\]' # (simple regex, validated later)
# Host patterns | class URLValidator(RegexValidator):
ul = '\u00a1-\uffff' # unicode letters range (must not be a raw string)
# IP patterns
ipv4_re = r'(?:0|25[0-5]|2[0-4]\d|1\d?\d?|[1-9]\d?)(?:\.(?:0|25[0-5]|2[0-4]\d|1\d?\d?|[1-9]\d?)){3}'
ipv6_re = r'\[[0-9a-f:\.]+\]' # (simple regex, validated later)
# Host pa... |
def validate_ipv4_address(value):
ipaddress.IPv4Address(value)
except ValueError:
raise ValidationError(_('Enter a valid IPv4 address.'), code='invalid')
def validate_ipv6_address(value): | def validate_ipv4_address(value):
ipaddress.IPv4Address(value)
except ValueError:
raise ValidationError(_('Enter a valid IPv4 address.'), code='invalid')
else:
# Leading zeros are forbidden to avoid ambiguity with the octal
# notation. This restriction is included in Python 3.9.5... |
TEST_DATA = [
(validate_ipv4_address, '1.1.1.1\n', ValidationError),
(validate_ipv4_address, '٧.2٥.3٣.243', ValidationError),
# validate_ipv6_address uses django.utils.ipv6, which
# is tested in much greater detail in its own testcase
(validate_ipv6_address, 'fe80::1', None), | TEST_DATA = [
(validate_ipv4_address, '1.1.1.1\n', ValidationError),
(validate_ipv4_address, '٧.2٥.3٣.243', ValidationError),
# Leading zeros are forbidden to avoid ambiguity with the octal notation.
(validate_ipv4_address, '000.000.000.000', ValidationError),
(validate_ipv4_address, '016.016.016.0... |
TEST_DATA = [
(validate_ipv46_address, '::zzz', ValidationError),
(validate_ipv46_address, '12345::', ValidationError),
(validate_comma_separated_integer_list, '1', None),
(validate_comma_separated_integer_list, '12', None),
(validate_comma_separated_integer_list, '1,2', None), | TEST_DATA = [
(validate_ipv46_address, '::zzz', ValidationError),
(validate_ipv46_address, '12345::', ValidationError),
# Leading zeros are forbidden to avoid ambiguity with the octal notation.
(validate_ipv46_address, '000.000.000.000', ValidationError),
(validate_ipv46_address, '016.016.016.016',... |
class SeriesGroupBy(GroupBy):
val = self.obj._internal_get_values()
# GH 27951
# temporary fix while we wait for NumPy bug 12629 to be fixed
val[isna(val)] = np.datetime64("NaT")
try:
sorter = np.lexsort((val, ids))
except TypeError: # catches object dtype... | class SeriesGroupBy(GroupBy):
val = self.obj._internal_get_values()
codes, _ = algorithms.factorize(val, sort=False)
sorter = np.lexsort((codes, ids))
codes = codes[sorter]
ids = ids[sorter]
# group boundaries are where group ids change
# unique observations ar... |
def test_frame_describe_unstacked_format():
@pytest.mark.parametrize("dropna", [False, True])
def test_series_groupby_nunique(n, m, sort, dropna):
def check_nunique(df, keys, as_index=True):
gr = df.groupby(keys, as_index=as_index, sort=sort)
left = gr["julie"].nunique(dropna=dropna)
| def test_frame_describe_unstacked_format():
@pytest.mark.parametrize("dropna", [False, True])
def test_series_groupby_nunique(n, m, sort, dropna):
def check_nunique(df, keys, as_index=True):
original_df = df.copy()
gr = df.groupby(keys, as_index=as_index, sort=sort)
left = gr["julie"].nuniqu... |
def test_series_groupby_nunique(n, m, sort, dropna):
right = right.reset_index(drop=True)
tm.assert_series_equal(left, right, check_names=False)
days = date_range("2015-08-23", periods=10)
| def test_series_groupby_nunique(n, m, sort, dropna):
right = right.reset_index(drop=True)
tm.assert_series_equal(left, right, check_names=False)
tm.assert_frame_equal(df, original_df)
days = date_range("2015-08-23", periods=10)
|
all about the internals of models in order to get the information it needs.
"""
import difflib
import functools
from collections import Counter, OrderedDict, namedtuple
from collections.abc import Iterator, Mapping
from itertools import chain, count, product | all about the internals of models in order to get the information it needs.
"""
import difflib
import functools
import re
from collections import Counter, OrderedDict, namedtuple
from collections.abc import Iterator, Mapping
from itertools import chain, count, product |
from django.utils.tree import Node
__all__ = ['Query', 'RawQuery']
def get_field_names_from_opts(opts):
return set(chain.from_iterable( | from django.utils.tree import Node
__all__ = ['Query', 'RawQuery']
# Quotation marks ('"`[]), whitespace characters, semicolons, or inline
# SQL comments are forbidden in column aliases.
FORBIDDEN_ALIAS_PATTERN = re.compile(r"['`\"\]\[;\s]|--|/\*|\*/")
def get_field_names_from_opts(opts):
return set(chain.from_... |
class Query:
alias = seen[int_model] = join_info.joins[-1]
return alias or seen[None]
def add_annotation(self, annotation, alias, is_summary=False):
"""Add a single annotation expression to the Query."""
annotation = annotation.resolve_expression(self, allow_joins=True, reuse=No... | class Query:
alias = seen[int_model] = join_info.joins[-1]
return alias or seen[None]
def check_alias(self, alias):
if FORBIDDEN_ALIAS_PATTERN.search(alias):
raise ValueError(
"Column aliases cannot contain whitespace characters, quotation marks, "
... |
class Query:
else:
param_iter = iter([])
for name, entry in select.items():
entry = str(entry)
entry_params = []
pos = entry.find("%s") | class Query:
else:
param_iter = iter([])
for name, entry in select.items():
self.check_alias(name)
entry = str(entry)
entry_params = []
pos = entry.find("%s") |
class AggregateTestCase(TestCase):
Book.objects.aggregate(is_book=True)
with self.assertRaisesMessage(TypeError, msg % ', '.join([str(FloatField()), 'True'])):
Book.objects.aggregate(FloatField(), Avg('price'), is_book=True) | class AggregateTestCase(TestCase):
Book.objects.aggregate(is_book=True)
with self.assertRaisesMessage(TypeError, msg % ', '.join([str(FloatField()), 'True'])):
Book.objects.aggregate(FloatField(), Avg('price'), is_book=True)
def test_alias_sql_injection(self):
crafted_alias ... |
class NonAggregateAnnotationTestCase(TestCase):
total_books=Subquery(long_books_qs, output_field=IntegerField()),
).values('name')
self.assertCountEqual(publisher_books_qs, [{'name': 'Sams'}, {'name': 'Morgan Kaufmann'}]) | class NonAggregateAnnotationTestCase(TestCase):
total_books=Subquery(long_books_qs, output_field=IntegerField()),
).values('name')
self.assertCountEqual(publisher_books_qs, [{'name': 'Sams'}, {'name': 'Morgan Kaufmann'}])
def test_alias_sql_injection(self):
crafted_alias = """in... |
class ValuesExpressionsTests(TestCase):
[{'salary': 10}, {'salary': 20}, {'salary': 30}],
)
def test_values_expression_group_by(self):
# values() applies annotate() first, so values selected are grouped by
# id, not firstname. | class ValuesExpressionsTests(TestCase):
[{'salary': 10}, {'salary': 20}, {'salary': 30}],
)
def test_values_expression_alias_sql_injection(self):
crafted_alias = """injected_name" from "expressions_company"; --"""
msg = (
"Column aliases cannot contain whitespace cha... |
class Queries5Tests(TestCase):
'bar %s'
)
class SelectRelatedTests(TestCase):
def test_tickets_3045_3288(self): | class Queries5Tests(TestCase):
'bar %s'
)
def test_extra_select_alias_sql_injection(self):
crafted_alias = """injected_name" from "queries_note"; --"""
msg = (
"Column aliases cannot contain whitespace characters, quotation marks, "
"semicolons, or SQL co... |
from django.db import models
from django.http import Http404
from django.template.engine import Engine
from django.urls import get_mod_func, get_resolver, get_urlconf
from django.utils.decorators import method_decorator
from django.utils.inspect import (
func_accepts_kwargs, func_accepts_var_args, get_func_full_arg... | from django.db import models
from django.http import Http404
from django.template.engine import Engine
from django.urls import get_mod_func, get_resolver, get_urlconf
from django.utils._os import safe_join
from django.utils.decorators import method_decorator
from django.utils.inspect import (
func_accepts_kwargs, f... |
class TemplateDetailView(BaseAdminDocsView):
else:
# This doesn't account for template loaders (#24128).
for index, directory in enumerate(default_engine.dirs):
template_file = Path(directory) / template
if template_file.exists():
templ... | class TemplateDetailView(BaseAdminDocsView):
else:
# This doesn't account for template loaders (#24128).
for index, directory in enumerate(default_engine.dirs):
template_file = Path(safe_join(directory, template))
if template_file.exists():
... |
class AdminDocViewTests(TestDataMixin, AdminDocsTestCase):
self.assertContains(response, 'View documentation')
@override_settings(TEMPLATES=[{
'NAME': 'ONE',
'BACKEND': 'django.template.backends.django.DjangoTemplates', | class AdminDocViewTests(TestDataMixin, AdminDocsTestCase):
self.assertContains(response, 'View documentation')
@unittest.skipUnless(utils.docutils_is_available, 'no docutils installed.')
class AdminDocViewDefaultEngineOnly(TestDataMixin, AdminDocsTestCase):
def setUp(self):
self.client.force_logi... |
from ansible.galaxy.role import GalaxyRole
from ansible.galaxy.token import BasicAuthToken, GalaxyToken, KeycloakToken, NoTokenSentinel
from ansible.module_utils.ansible_release import __version__ as ansible_version
from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.parsing.yaml.loader imp... | from ansible.galaxy.role import GalaxyRole
from ansible.galaxy.token import BasicAuthToken, GalaxyToken, KeycloakToken, NoTokenSentinel
from ansible.module_utils.ansible_release import __version__ as ansible_version
from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.module_utils import six... |
class GalaxyCLI(CLI):
else:
requirements = []
for collection_input in collections:
name, dummy, requirement = collection_input.partition(':')
requirements.append((name, requirement or '*', None))
output_path = GalaxyCLI._re... | class GalaxyCLI(CLI):
else:
requirements = []
for collection_input in collections:
requirement = None
if os.path.isfile(to_bytes(collection_input, errors='surrogate_or_strict')) or \
urlparse(collection_input... |
def _get_collection_info(dep_map, existing_collections, collection, requirement,
if os.path.isfile(to_bytes(collection, errors='surrogate_or_strict')):
display.vvvv("Collection requirement '%s' is a tar artifact" % to_text(collection))
b_tar_path = to_bytes(collection, errors='surrogate_or_strict')
... | def _get_collection_info(dep_map, existing_collections, collection, requirement,
if os.path.isfile(to_bytes(collection, errors='surrogate_or_strict')):
display.vvvv("Collection requirement '%s' is a tar artifact" % to_text(collection))
b_tar_path = to_bytes(collection, errors='surrogate_or_strict')
... |
def test_collection_install_in_collection_dir(collection_install, monkeypatch):
assert mock_install.call_args[0][7] is False
def test_collection_install_name_and_requirements_fail(collection_install):
test_path = collection_install[2]
expected = 'The positional collection_name arg and --requirements-file ... | def test_collection_install_in_collection_dir(collection_install, monkeypatch):
assert mock_install.call_args[0][7] is False
def test_collection_install_with_url(collection_install):
mock_install, dummy, output_dir = collection_install
galaxy_args = ['ansible-galaxy', 'collection', 'install', 'https://fo... |
class PlayBook(object):
basedir = self.inventory.basedir()
filename = "%s.retry" % os.path.basename(self.filename)
filename = filename.replace(".yml","")
if not os.path.exists('/var/tmp/ansible'):
try:
os.makedirs('/var/tmp/ansible')
except:
... | class PlayBook(object):
basedir = self.inventory.basedir()
filename = "%s.retry" % os.path.basename(self.filename)
filename = filename.replace(".yml","")
filename = os.path.join(os.path.expandvars('$HOME/'), filename)
try:
fd = open(filename, 'w') |
def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='',
# sign
sign = ''
if isinstance(number, Decimal):
str_number = '{:f}'.format(number)
else:
str_number = six.text_type(number)
if str_number[0] == '-': | def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='',
# sign
sign = ''
if isinstance(number, Decimal):
# Format values with more than 200 digits (an arbitrary cutoff) using
# scientific notation to avoid high memory usage in {:f}'.format().
_, digits, exponen... |
class TestNumberFormat(TestCase):
self.assertEqual(nformat(Decimal('1234'), '.', grouping=2, thousand_sep=',', force_grouping=True), '12,34')
self.assertEqual(nformat(Decimal('-1234.33'), '.', decimal_pos=1), '-1234.3')
self.assertEqual(nformat(Decimal('0.00000001'), '.', decimal_pos=8), '0.0000... | class TestNumberFormat(TestCase):
self.assertEqual(nformat(Decimal('1234'), '.', grouping=2, thousand_sep=',', force_grouping=True), '12,34')
self.assertEqual(nformat(Decimal('-1234.33'), '.', decimal_pos=1), '-1234.3')
self.assertEqual(nformat(Decimal('0.00000001'), '.', decimal_pos=8), '0.0000... |
def Ghostscript(tile, size, fp, scale=1):
import tempfile, os, subprocess
outfile = tempfile.mktemp()
infile = tempfile.mktemp()
with open(infile, 'wb') as f:
fp.seek(offset) | def Ghostscript(tile, size, fp, scale=1):
import tempfile, os, subprocess
out_fd, outfile = tempfile.mkstemp()
os.close(out_fd)
in_fd, infile = tempfile.mkstemp()
os.close(in_fd)
with open(infile, 'wb') as f:
fp.seek(offset) |
class Image:
self.readonly = 0
def _dump(self, file=None, format=None):
import tempfile
if not file:
file = tempfile.mktemp()
self.load()
if not format or format == "PPM":
self.im.save_ppm(file)
else:
file = file + "." + format
... | class Image:
self.readonly = 0
def _dump(self, file=None, format=None):
import tempfile, os
if not file:
f, file = tempfile.mkstemp(format or '')
os.close(f)
self.load()
if not format or format == "PPM":
self.im.save_ppm(file)... |
class IptcImageFile(ImageFile.ImageFile):
self.fp.seek(offset)
# Copy image data to temporary file
outfile = tempfile.mktemp()
o = open(outfile, "wb")
if encoding == "raw":
# To simplify access to the extracted file,
# prepend a PPM header | class IptcImageFile(ImageFile.ImageFile):
self.fp.seek(offset)
# Copy image data to temporary file
o_fd, outfile = tempfile.mkstemp(text=False)
o = os.fdopen(o_fd)
if encoding == "raw":
# To simplify access to the extracted file,
# prepend a PPM header |
class JpegImageFile(ImageFile.ImageFile):
# ALTERNATIVE: handle JPEGs via the IJG command line utilities
import tempfile, os
file = tempfile.mktemp()
os.system("djpeg %s >%s" % (self.filename, file))
try:
self.im = Image.core.open_ppm(file)
finally:
... | class JpegImageFile(ImageFile.ImageFile):
# ALTERNATIVE: handle JPEGs via the IJG command line utilities
import tempfile, os
f, path = tempfile.mkstemp()
os.close(f)
if os.path.exists(self.filename):
os.system("djpeg '%s' >'%s'" % (self.filename, path))
else:... |
def _add_margins(
row_names = result.index.names
try:
for dtype in set(result.dtypes):
cols = result.select_dtypes([dtype]).columns
margin_dummy[cols] = margin_dummy[cols].astype(dtype)
result = result.append(margin_dummy)
except TypeError:
| def _add_margins(
row_names = result.index.names
try:
# check the result column and leave floats
for dtype in set(result.dtypes):
cols = result.select_dtypes([dtype]).columns
margin_dummy[cols] = margin_dummy[cols].apply(
maybe_downcast_to_dtype, args=(dt... |
class TestPivotTable:
table = df.pivot_table("x", "y", "z", dropna=observed, margins=True)
tm.assert_frame_equal(table, expected)
def test_pivot_with_categorical(self, observed, ordered_fixture):
# gh-21370
idx = [np.nan, "low", "high", "low", np.nan] | class TestPivotTable:
table = df.pivot_table("x", "y", "z", dropna=observed, margins=True)
tm.assert_frame_equal(table, expected)
def test_margins_casted_to_float(self, observed):
# GH 24893
df = pd.DataFrame(
{
"A": [2, 4, 6, 8],
"B": [1,... |
def test_load_blp2_dxt1():
def test_load_blp2_dxt1a():
with Image.open("Tests/images/blp/blp2_dxt1a.blp") as im:
assert_image_equal_tofile(im, "Tests/images/blp/blp2_dxt1a.png") | def test_load_blp2_dxt1():
def test_load_blp2_dxt1a():
with Image.open("Tests/images/blp/blp2_dxt1a.blp") as im:
assert_image_equal_tofile(im, "Tests/images/blp/blp2_dxt1a.png")
@pytest.mark.parametrize(
"test_file",
[
"Tests/images/timeout-060745d3f534ad6e4128c51d336ea5489182c69d.blp",
... |
class _BLPBaseDecoder(ImageFile.PyDecoder):
raise OSError("Truncated Blp file") from e
return 0, 0
def _read_palette(self):
ret = []
for i in range(256):
try:
b, g, r, a = struct.unpack("<4B", self.fd.read(4))
except struct.error:
... | class _BLPBaseDecoder(ImageFile.PyDecoder):
raise OSError("Truncated Blp file") from e
return 0, 0
def _safe_read(self, length):
return ImageFile._safe_read(self.fd, length)
def _read_palette(self):
ret = []
for i in range(256):
try:
b, g... |
class BLP1Decoder(_BLPBaseDecoder):
if self._blp_encoding in (4, 5):
data = bytearray()
palette = self._read_palette()
_data = BytesIO(self.fd.read(self._blp_lengths[0]))
while True:
try:
(offset,) = ... | class BLP1Decoder(_BLPBaseDecoder):
if self._blp_encoding in (4, 5):
data = bytearray()
palette = self._read_palette()
_data = BytesIO(self._safe_read(self._blp_lengths[0]))
while True:
try:
(offset,)... |
class BLP1Decoder(_BLPBaseDecoder):
def _decode_jpeg_stream(self):
from PIL.JpegImagePlugin import JpegImageFile
(jpeg_header_size,) = struct.unpack("<I", self.fd.read(4))
jpeg_header = self.fd.read(jpeg_header_size)
self.fd.read(self._blp_offsets[0] - self.fd.tell()) # What IS thi... | class BLP1Decoder(_BLPBaseDecoder):
def _decode_jpeg_stream(self):
from PIL.JpegImagePlugin import JpegImageFile
(jpeg_header_size,) = struct.unpack("<I", self._safe_read(4))
jpeg_header = self._safe_read(jpeg_header_size)
self._safe_read(self._blp_offsets[0] - self.fd.tell()) # Wh... |
class BLP2Decoder(_BLPBaseDecoder):
# Uncompressed or DirectX compression
if self._blp_encoding == BLP_ENCODING_UNCOMPRESSED:
_data = BytesIO(self.fd.read(self._blp_lengths[0]))
while True:
try:
(offset,) = struct.unpac... | class BLP2Decoder(_BLPBaseDecoder):
# Uncompressed or DirectX compression
if self._blp_encoding == BLP_ENCODING_UNCOMPRESSED:
_data = BytesIO(self._safe_read(self._blp_lengths[0]))
while True:
try:
(offset,) = struct.un... |
class BLP2Decoder(_BLPBaseDecoder):
linesize = (self.size[0] + 3) // 4 * 8
for yb in range((self.size[1] + 3) // 4):
for d in decode_dxt1(
self.fd.read(linesize), alpha=bool(self._blp_alpha_depth)
):
... | class BLP2Decoder(_BLPBaseDecoder):
linesize = (self.size[0] + 3) // 4 * 8
for yb in range((self.size[1] + 3) // 4):
for d in decode_dxt1(
self._safe_read(linesize), alpha=bool(self._blp_alpha_depth)
):
... |
class ReduceLROnPlateau(Callback):
monitored has stopped increasing; in `auto`
mode, the direction is automatically inferred
from the name of the monitored quantity.
epsilon: threshold for measuring the new optimum,
to only focus on significant changes.
co... | class ReduceLROnPlateau(Callback):
monitored has stopped increasing; in `auto`
mode, the direction is automatically inferred
from the name of the monitored quantity.
min_delta: threshold for measuring the new optimum,
to only focus on significant changes.
... |
class ReduceLROnPlateau(Callback):
"""
def __init__(self, monitor='val_loss', factor=0.1, patience=10,
verbose=0, mode='auto', epsilon=1e-4, cooldown=0, min_lr=0):
super(ReduceLROnPlateau, self).__init__()
self.monitor = monitor
if factor >= 1.0:
raise Valu... | class ReduceLROnPlateau(Callback):
"""
def __init__(self, monitor='val_loss', factor=0.1, patience=10,
verbose=0, mode='auto', min_delta=1e-4, cooldown=0, min_lr=0,
**kwargs):
super(ReduceLROnPlateau, self).__init__()
self.monitor = monitor
if factor >... |
class ReduceLROnPlateau(Callback):
self.mode = 'auto'
if (self.mode == 'min' or
(self.mode == 'auto' and 'acc' not in self.monitor)):
self.monitor_op = lambda a, b: np.less(a, b - self.epsilon)
self.best = np.Inf
else:
self.monitor_op = lambda a... | class ReduceLROnPlateau(Callback):
self.mode = 'auto'
if (self.mode == 'min' or
(self.mode == 'auto' and 'acc' not in self.monitor)):
self.monitor_op = lambda a, b: np.less(a, b - self.min_delta)
self.best = np.Inf
else:
self.monitor_op = lambda... |
class ReduceLROnPlateau(Callback):
self.best = current
self.wait = 0
elif not self.in_cooldown():
if self.wait >= self.patience:
old_lr = float(K.get_value(self.model.optimizer.lr))
if old_lr > self.min_lr: | class ReduceLROnPlateau(Callback):
self.best = current
self.wait = 0
elif not self.in_cooldown():
self.wait += 1
if self.wait >= self.patience:
old_lr = float(K.get_value(self.model.optimizer.lr))
if old_... |
class ReduceLROnPlateau(Callback):
'rate to %s.' % (epoch + 1, new_lr))
self.cooldown_counter = self.cooldown
self.wait = 0
self.wait += 1
def in_cooldown(self):
return self.cooldown_counter > 0 | class ReduceLROnPlateau(Callback):
'rate to %s.' % (epoch + 1, new_lr))
self.cooldown_counter = self.cooldown
self.wait = 0
def in_cooldown(self):
return self.cooldown_counter > 0 |
def test_ReduceLROnPlateau():
model = make_model()
# This should reduce the LR after the first epoch (due to high epsilon).
cbks = [callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.1, epsilon=10, patience=1, cooldown=5)]
model.fit(X_train, y_train, batch_size=batch_size,
validatio... | def test_ReduceLROnPlateau():
model = make_model()
# This should reduce the LR after the first epoch (due to high epsilon).
cbks = [callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.1, min_delta=10, patience=1, cooldown=5)]
model.fit(X_train, y_train, batch_size=batch_size,
validat... |
def test_osx_proxy_bypass(self):
bypass = {'exclude_simple': True, 'exceptions': []}
self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass))
def test_basic_auth(self, quote_char='"'):
opener = OpenerDirector()
password_manager = MockPasswordManager()
auth_handler = url... | def test_osx_proxy_bypass(self):
bypass = {'exclude_simple': True, 'exceptions': []}
self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass))
def check_basic_auth(self, headers, realm):
with self.subTest(realm=realm, headers=headers):
opener = OpenerDirector()
p... |
class AbstractBasicAuthHandler:
# allow for double- and single-quoted realm values
# (single quotes are a violation of the RFC, but appear in the wild)
rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'
'realm=(["\']?)([^"\']*)\\2', re.I)
# XXX could pre-emptively send auth info alrea... | class AbstractBasicAuthHandler:
# allow for double- and single-quoted realm values
# (single quotes are a violation of the RFC, but appear in the wild)
rx = re.compile('(?:^|,)' # start of the string or ','
'[ \t]*' # optional whitespaces
'([^ \t]+)' # scheme li... |
def __init__(self, password_mgr=None):
self.passwd = password_mgr
self.add_password = self.passwd.add_password
def http_error_auth_reqed(self, authreq, host, req, headers):
# host may be an authority (without userinfo) or a URL with an
# authority
# XXX could be multiple hea... | def __init__(self, password_mgr=None):
self.passwd = password_mgr
self.add_password = self.passwd.add_password
def _parse_realm(self, header):
# parse WWW-Authenticate header: accept multiple challenges per header
found_challenge = False
for mo in AbstractBasicAuthHandler.rx... |
def test_apply_index(cls, n):
ser = pd.Series(rng)
res = rng + offset
res_v2 = offset.apply_index(rng)
assert (res == res_v2).all()
assert res[0] == rng[0] + offset | def test_apply_index(cls, n):
ser = pd.Series(rng)
res = rng + offset
assert res.freq is None # not retained
res_v2 = offset.apply_index(rng)
assert (res == res_v2).all()
assert res[0] == rng[0] + offset |
class MonthOffset(SingleConstructorOffset):
@apply_index_wraps
def apply_index(self, i):
shifted = liboffsets.shift_months(i.asi8, self.n, self._day_opt)
# TODO: going through __new__ raises on call to _validate_frequency;
# are we passing incorrect freq?
return type(i)._simple_... | class MonthOffset(SingleConstructorOffset):
@apply_index_wraps
def apply_index(self, i):
shifted = liboffsets.shift_months(i.asi8, self.n, self._day_opt)
return type(i)._simple_new(shifted, dtype=i.dtype)
class MonthEnd(MonthOffset): |
class QuarterOffset(DateOffset):
shifted = liboffsets.shift_quarters(
dtindex.asi8, self.n, self.startingMonth, self._day_opt
)
# TODO: going through __new__ raises on call to _validate_frequency;
# are we passing incorrect freq?
return type(dtindex)._simple_new(
... | class QuarterOffset(DateOffset):
shifted = liboffsets.shift_quarters(
dtindex.asi8, self.n, self.startingMonth, self._day_opt
)
return type(dtindex)._simple_new(shifted, dtype=dtindex.dtype)
class BQuarterEnd(QuarterOffset): |
class YearOffset(DateOffset):
shifted = liboffsets.shift_quarters(
dtindex.asi8, self.n, self.month, self._day_opt, modby=12
)
# TODO: going through __new__ raises on call to _validate_frequency;
# are we passing incorrect freq?
return type(dtindex)._simple_new(
... | class YearOffset(DateOffset):
shifted = liboffsets.shift_quarters(
dtindex.asi8, self.n, self.month, self._day_opt, modby=12
)
return type(dtindex)._simple_new(shifted, dtype=dtindex.dtype)
def is_on_offset(self, dt: datetime) -> bool:
if self.normalize and not _is_norma... |
from pandas.core.dtypes.common import (
is_list_like,
is_object_dtype,
is_scalar,
)
from pandas.core.dtypes.dtypes import register_extension_dtype
from pandas.core.dtypes.missing import isna | from pandas.core.dtypes.common import (
is_list_like,
is_object_dtype,
is_scalar,
pandas_dtype,
)
from pandas.core.dtypes.dtypes import register_extension_dtype
from pandas.core.dtypes.missing import isna |
class IntegerArray(BaseMaskedArray):
if incompatible type with an IntegerDtype, equivalent of same_kind
casting
"""
# if we are astyping to an existing IntegerDtype we can fastpath
if isinstance(dtype, _IntegerDtype):
result = self._data.astype(dtype.numpy_dt... | class IntegerArray(BaseMaskedArray):
if incompatible type with an IntegerDtype, equivalent of same_kind
casting
"""
from pandas.core.arrays.boolean import BooleanArray, BooleanDtype
dtype = pandas_dtype(dtype)
# if we are astyping to an existing IntegerDtype we ... |
class TestCasting:
tm.assert_numpy_array_equal(a.astype(str), expected)
tm.assert_numpy_array_equal(a.astype("str"), expected)
def test_frame_repr(data_missing):
| class TestCasting:
tm.assert_numpy_array_equal(a.astype(str), expected)
tm.assert_numpy_array_equal(a.astype("str"), expected)
def test_astype_boolean(self):
# https://github.com/pandas-dev/pandas/issues/31102
a = pd.array([1, 0, -1, 2, None], dtype="Int64")
result = a.astyp... |
The `pillar_roots` wheel module is used to manage files under the pillar roots
directories on the master server.
"""
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
# Import salt libs
import salt.utils.files
import salt.utils.path
# Import 3rd-party libs
from ... | The `pillar_roots` wheel module is used to manage files under the pillar roots
directories on the master server.
"""
from __future__ import absolute_import, print_function, unicode_literals
import os
import salt.utils.files
import salt.utils.path
import salt.utils.verify
from salt.ext import six
|
def write(data, path, saltenv="base", index=0):
return (
"The path passed in {0} is not relative to the environment " "{1}"
).format(path, saltenv)
dest = os.path.join(__opts__["pillar_roots"][saltenv][index], path)
dest_dir = os.path.dirname(dest)
if not os.path.isdir(dest_dir): | def write(data, path, saltenv="base", index=0):
return (
"The path passed in {0} is not relative to the environment " "{1}"
).format(path, saltenv)
roots_dir = __opts__["pillar_roots"][saltenv][index]
dest = os.path.join(roots_dir, path)
if not salt.utils.verify.clean_path(roots_... |
import pytest
import os
from thefuck.rules.fix_file import match, get_new_command
from tests.utils import Command
# (script, file, line, col (or None), stdout, stderr) | import pytest
import os
from thefuck.rules.fix_file import match, get_new_command
from tests.utils import Command
from thefuck.types import Settings
# (script, file, line, col (or None), stdout, stderr) |
awk: ./a:2: BEGIN { print "Hello, world!" + }
awk: ./a:2: ^ syntax error
"""),
('llc a.ll', 'a.ll', 1, None, '',
"""
llc: a.ll:1:1: error: expected top-level entity
+
^
"""),
('go build a.go', 'a.go', 1, None, '',
"""
can't load package:
a.go:1:1: expected 'package', found '+'
"""),
(... | awk: ./a:2: BEGIN { print "Hello, world!" + }
awk: ./a:2: ^ syntax error
"""),
('llc a.ll', 'a.ll', 1, 2, '',
"""
llc: a.ll:1:2: error: expected top-level entity
+
^
"""),
('go build a.go', 'a.go', 1, 2, '',
"""
can't load package:
a.go:1:2: expected 'package', found '+'
"""),
('make'... |
def test_not_file(mocker, monkeypatch, test):
def test_get_new_command(mocker, monkeypatch, test):
mocker.patch('os.path.isfile', return_value=True)
monkeypatch.setenv('EDITOR', 'dummy_editor')
cmd = Command(script=test[0], stdout=test[4], stderr=test[5])
assert (get_new_command(cmd, None) ==
'd... | def test_not_file(mocker, monkeypatch, test):
def test_get_new_command(mocker, monkeypatch, test):
mocker.patch('os.path.isfile', return_value=True)
monkeypatch.setenv('EDITOR', 'dummy_editor')
cmd = Command(script=test[0], stdout=test[4], stderr=test[5])
#assert (get_new_command(cmd, Settings({})) ==
... |
import re
import os
from thefuck.utils import memoize
from thefuck import shells
patterns = (
# js, node:
'^ at {file}:{line}:{col}', | import re
import os
from thefuck.utils import memoize, wrap_settings
from thefuck import shells
# order is important: only the first match is considered
patterns = (
# js, node:
'^ at {file}:{line}:{col}', |
patterns = (
# lua:
'^lua: {file}:{line}:',
# fish:
'^{file} \(line {line}\):',
# bash, sh, ssh:
'^{file}: line {line}: ',
# ghc, make, ruby, zsh:
'^{file}:{line}:',
# cargo, clang, gcc, go, pep8, rustc:
'^{file}:{line}:{col}',
# pe... | patterns = (
# lua:
'^lua: {file}:{line}:',
# fish:
'^{file} \\(line {line}\\):',
# bash, sh, ssh:
'^{file}: line {line}: ',
# cargo, clang, gcc, go, pep8, rustc:
'^{file}:{line}:{col}',
# ghc, make, ruby, zsh:
'^{file}:{line}:',
# ... |
def match(command, settings):
return _search(command.stderr) or _search(command.stdout)
def get_new_command(command, settings):
m = _search(command.stderr) or _search(command.stdout)
# Note: there does not seem to be a standard for columns, so they are just
# ignored for now
editor_call = '{} {} ... | def match(command, settings):
return _search(command.stderr) or _search(command.stdout)
@wrap_settings({'fixlinecmd': '{editor} {file} +{line}',
'fixcolcmd': None})
def get_new_command(command, settings):
m = _search(command.stderr) or _search(command.stdout)
# Note: there does not seem t... |
def do_setup():
'gunicorn>=19.5.0, <20.0',
'iso8601>=0.1.12',
'json-merge-patch==0.2',
'jinja2>=2.7.3, <=2.10.0',
'markdown>=2.5.2, <3.0',
'pandas>=0.17.1, <1.0.0',
'pendulum==1.4.4', | def do_setup():
'gunicorn>=19.5.0, <20.0',
'iso8601>=0.1.12',
'json-merge-patch==0.2',
'jinja2>=2.10.1, <2.11.0',
'markdown>=2.5.2, <3.0',
'pandas>=0.17.1, <1.0.0',
'pendulum==1.4.4', |
def __virtual__():
return __virtualname__
def _check_cb(cb_):
'''
If the callback is None or is not callable, return a lambda that returns | def __virtual__():
return __virtualname__
def _log_cmd(cmd):
if not isinstance(cmd, list):
return cmd.split()[0].strip()
return cmd[0].strip()
def _check_cb(cb_):
'''
If the callback is None or is not callable, return a lambda that returns |
def _run(cmd,
'Setting value to an empty string', bad_env_key)
env[bad_env_key] = ''
def _get_stripped(cmd):
# Return stripped command string copies to improve logging.
if isinstance(cmd, list):
return [x.strip() if isinstance(x, six.string_types) else x for x ... | def _run(cmd,
'Setting value to an empty string', bad_env_key)
env[bad_env_key] = ''
if output_loglevel is not None:
# Always log the shell commands at INFO unless quiet logging is
# requested. The command output is what will be controlled by the
# 'loglevel' param... |
def _run(cmd,
if output_loglevel != 'quiet':
log.error(
'Failed to decode stdout from command %s, non-decodable '
'characters have been replaced', cmd
)
try: | def _run(cmd,
if output_loglevel != 'quiet':
log.error(
'Failed to decode stdout from command %s, non-decodable '
'characters have been replaced', _log_cmd(cmd)
)
try: |
def _run(cmd,
if output_loglevel != 'quiet':
log.error(
'Failed to decode stderr from command %s, non-decodable '
'characters have been replaced', cmd
)
if rstrip: | def _run(cmd,
if output_loglevel != 'quiet':
log.error(
'Failed to decode stderr from command %s, non-decodable '
'characters have been replaced', _log_cmd(cmd)
)
if rstrip: |
def _run(cmd,
output_loglevel = LOG_LEVELS['error']
msg = (
'Command \'{0}\' failed with return code: {1}'.format(
cmd,
ret['retcode']
)
) | def _run(cmd,
output_loglevel = LOG_LEVELS['error']
msg = (
'Command \'{0}\' failed with return code: {1}'.format(
_log_cmd(cmd),
ret['retcode']
)
) |
def run(cmd,
lvl = LOG_LEVELS['error']
msg = (
'Command \'{0}\' failed with return code: {1}'.format(
cmd,
ret['retcode']
)
) | def run(cmd,
lvl = LOG_LEVELS['error']
msg = (
'Command \'{0}\' failed with return code: {1}'.format(
_log_cmd(cmd),
ret['retcode']
)
) |
class CMDMODTestCase(TestCase, LoaderModuleMockMixin):
cmdmod.run_chroot('/mnt', 'cmd', binds=['/var'])
self.assertEqual(mock_mount.call_count, 4)
self.assertEqual(mock_umount.call_count, 4) | class CMDMODTestCase(TestCase, LoaderModuleMockMixin):
cmdmod.run_chroot('/mnt', 'cmd', binds=['/var'])
self.assertEqual(mock_mount.call_count, 4)
self.assertEqual(mock_umount.call_count, 4)
def test_cve_2021_25284(self):
proc = MagicMock(
return_... |
def test_side_effect(zip_error, script):
@pytest.mark.parametrize('script,fixed', [
('unzip foo', 'unzip foo -d foo'),
('unzip foo.zip', 'unzip foo.zip -d foo')])
def test_get_new_command(zip_error, script, fixed):
assert get_new_command(Command(script=script)) == fixed | def test_side_effect(zip_error, script):
@pytest.mark.parametrize('script,fixed', [
('unzip foo', 'unzip foo -d foo'),
(R"unzip foo\ bar.zip", R"unzip foo\ bar.zip -d 'foo bar'"),
(R"unzip 'foo bar.zip'", R"unzip 'foo bar.zip' -d 'foo bar'"),
('unzip foo.zip', 'unzip foo.zip -d foo')])
def test_get_new... |
import os
import zipfile
from thefuck.utils import for_app
def _is_bad_zip(file): | import os
import zipfile
from thefuck.utils import for_app
from thefuck.shells import quote
def _is_bad_zip(file): |
def _zip_file(command):
# unzip [-flags] file[.zip] [file(s) ...] [-x file(s) ...]
# ^ ^ files to unzip from the archive
# archive to unzip
for c in command.script.split()[1:]:
if not c.startswith('-'):
if c.endswith('.zip'):
ret... | def _zip_file(command):
# unzip [-flags] file[.zip] [file(s) ...] [-x file(s) ...]
# ^ ^ files to unzip from the archive
# archive to unzip
for c in command.split_script[1:]:
if not c.startswith('-'):
if c.endswith('.zip'):
retur... |
def match(command):
def get_new_command(command):
return '{} -d {}'.format(command.script, _zip_file(command)[:-4])
def side_effect(old_cmd, command): | def match(command):
def get_new_command(command):
return '{} -d {}'.format(command.script, quote(_zip_file(command)[:-4]))
def side_effect(old_cmd, command): |
def _find_module_utils(module_name, b_module_data, module_path, module_args, tas
# FUTURE: smuggle this back as a dict instead of serializing here; the connection plugin may need to modify it
module_json = json.dumps(exec_manifest)
b_module_data = exec_wrapper.replace(b"$json_raw = ''", b"$json... | def _find_module_utils(module_name, b_module_data, module_path, module_args, tas
# FUTURE: smuggle this back as a dict instead of serializing here; the connection plugin may need to modify it
module_json = json.dumps(exec_manifest)
# delimit the payload JSON from the wrapper to keep sensitive c... |
class ActionModule(ActionBase):
exec_data = None
# WinRM requires a special wrapper to work with environment variables
if self._connection.transport == "winrm":
pay = self._connection._create_raw_wrapper_payload(script_cmd,
... | class ActionModule(ActionBase):
exec_data = None
# WinRM requires a special wrapper to work with environment variables
if self._connection.transport == "winrm":
pay = self._connection._create_raw_wrapper_payload(script_cmd, env_dict)
exec_data = to_byt... |
import traceback
import json
import tempfile
import subprocess
HAVE_KERBEROS = False
try: | import traceback
import json
import tempfile
import subprocess
import xml.etree.ElementTree as ET
HAVE_KERBEROS = False
try: |
class Connection(ConnectionBase):
return (result.status_code, result.std_out, result.std_err)
def is_clixml(self, value):
return value.startswith(b"#< CLIXML")
# hacky way to get just stdout- not always sure of doc framing here, so use with care
def parse_clixml_stream(self, clixml_doc, st... | class Connection(ConnectionBase):
return (result.status_code, result.std_out, result.std_err)
def is_clixml(self, value):
return value.startswith(b"#< CLIXML\r\n")
# hacky way to get just stdout- not always sure of doc framing here, so use with care
def parse_clixml_stream(self, clixml_doc... |
import base64
import os
import re
import shlex
from ansible.errors import AnsibleError
from ansible.module_utils._text import to_native, to_text | import base64
import os
import re
import shlex
import pkgutil
from ansible.errors import AnsibleError
from ansible.module_utils._text import to_native, to_text |
begin {
# stream JSON including become_pw, ps_module_payload, bin_module_payload, become_payload, write_payload_path, preserve directives
# exec runspace, capture output, cleanup, return module output
# NB: do not adjust the following line- it is replaced when doing non-streamed module output
$json_raw... | begin {
# stream JSON including become_pw, ps_module_payload, bin_module_payload, become_payload, write_payload_path, preserve directives
# exec runspace, capture output, cleanup, return module output
# only init and stream in $json_raw if it wasn't set by the enclosing scope
if (-not $(Get-Variable "j... |
class ShellModule(ShellBase):
return self._encode_script(script)
def build_module_command(self, env_string, shebang, cmd, arg_path=None):
# pipelining bypass
if cmd == '':
return '-'
# non-pipelining
| class ShellModule(ShellBase):
return self._encode_script(script)
def build_module_command(self, env_string, shebang, cmd, arg_path=None):
bootstrap_wrapper = pkgutil.get_data("ansible.executor.powershell", "bootstrap_wrapper.ps1")
# pipelining bypass
if cmd == '':
retur... |
class ShellModule(ShellBase):
cmd_parts = list(map(to_text, cmd_parts))
if shebang and shebang.lower() == '#!powershell':
if not self._unquote(cmd_parts[0]).lower().endswith('.ps1'):
cmd_parts[0] = '"%s.ps1"' % self._unquote(cmd_parts[0])
cmd_parts.insert(0, '&')
... | class ShellModule(ShellBase):
cmd_parts = list(map(to_text, cmd_parts))
if shebang and shebang.lower() == '#!powershell':
if not self._unquote(cmd_parts[0]).lower().endswith('.ps1'):
# we're running a module via the bootstrap wrapper
cmd_parts[0] = '"%s.ps1"' ... |
def configure():
register_cli_str('pydev-debug-host', default=None)
register_cli_int('pydev-debug-port', default=None)
register_str('admin_token', default='ADMIN')
register_str('bind_host', default='0.0.0.0')
register_int('compute_port', default=8774)
register_int('admin_port', default=35357) | def configure():
register_cli_str('pydev-debug-host', default=None)
register_cli_int('pydev-debug-port', default=None)
register_str('admin_token', secret=True, default='ADMIN')
register_str('bind_host', default='0.0.0.0')
register_int('compute_port', default=8774)
register_int('admin_port', def... |
def configure():
# ldap
register_str('url', group='ldap', default='ldap://localhost')
register_str('user', group='ldap', default=None)
register_str('password', group='ldap', default=None)
register_str('suffix', group='ldap', default='cn=example,cn=com')
register_bool('use_dumb_member', group='ld... | def configure():
# ldap
register_str('url', group='ldap', default='ldap://localhost')
register_str('user', group='ldap', default=None)
register_str('password', group='ldap', secret=True, default=None)
register_str('suffix', group='ldap', default='cn=example,cn=com')
register_bool('use_dumb_membe... |
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])) |
from django.utils.safestring import SafeData, SafeText, mark_safe
from django.utils.text import normalize_newlines
# Configuration for urlize() function.
TRAILING_PUNCTUATION_RE = re.compile(
'^' # Beginning of word
'(.*?)' # The URL in word
'([.,:;!]+)' # Allowed non-wrapping, trailing pu... | from django.utils.safestring import SafeData, SafeText, mark_safe
from django.utils.text import normalize_newlines
# Configuration for urlize() function.
TRAILING_PUNCTUATION_CHARS = '.,:;!'
WRAPPING_PUNCTUATION = [('(', ')'), ('<', '>'), ('[', ']'), ('<', '>'), ('"', '"'), ('\'', '\'')]
# List of possible stri... |
unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)')
word_split_re = re.compile(r'''([\s<>"']+)''')
simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE)
simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$', re.IGNORECASE)
simple_email_re = re.compile(r'^\S+@\S+\.\... | unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)')
word_split_re = re.compile(r'''([\s<>"']+)''')
simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE)
simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$', re.IGNORECASE)
_html_escapes = {
ord('&'): '&', |
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
trimmed_something = False
# Trim trailing punctuation.
match = TRAILING_PUNCTUATION_RE.match(middle)
if match:
middle = match.group(1)
trail = match.group(2) + trail
... | def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
trimmed_something = False
# Trim trailing punctuation.
stripped = middle.rstrip(TRAILING_PUNCTUATION_CHARS)
if middle != stripped:
trail = middle[len(stripped):] + trail
... |
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
trimmed_something = True
return lead, middle, trail
words = word_split_re.split(str(text))
for i, word in enumerate(words):
if '.' in word or '@' in word or ':' in word: | def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
trimmed_something = True
return lead, middle, trail
def is_email_simple(value):
"""Return True if value looks like an email address."""
# An @ must be in the middle of the value.
if '@' not ... |
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
elif simple_url_2_re.match(middle):
middle, middle_unescaped, trail = unescape(middle, trail)
url = smart_urlquote('http://%s' % middle_unescaped)
elif ':' not in middle and simple_email_re.m... | def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
elif simple_url_2_re.match(middle):
middle, middle_unescaped, trail = unescape(middle, trail)
url = smart_urlquote('http://%s' % middle_unescaped)
elif ':' not in middle and is_email_simple(m... |
class TestUtilsHtml(SimpleTestCase):
for value, output in tests:
with self.subTest(value=value):
self.assertEqual(urlize(value), output) | class TestUtilsHtml(SimpleTestCase):
for value, output in tests:
with self.subTest(value=value):
self.assertEqual(urlize(value), output)
def test_urlize_unchanged_inputs(self):
tests = (
('a' + '@a' * 50000) + 'a', # simple_email_re catastrophic test
... |
DEFAULT_FORCE_HANDLERS = get_config(p, DEFAULTS, 'force_handlers', 'ANSIBLE_F
DEFAULT_INVENTORY_IGNORE = get_config(p, DEFAULTS, 'inventory_ignore_extensions', 'ANSIBLE_INVENTORY_IGNORE', ["~", ".orig", ".bak", ".ini", ".cfg", ".retry", ".pyc", ".pyo"], islist=True)
DEFAULT_VAR_COMPRESSION_LEVEL = get_config(p, DEF... | DEFAULT_FORCE_HANDLERS = get_config(p, DEFAULTS, 'force_handlers', 'ANSIBLE_F
DEFAULT_INVENTORY_IGNORE = get_config(p, DEFAULTS, 'inventory_ignore_extensions', 'ANSIBLE_INVENTORY_IGNORE', ["~", ".orig", ".bak", ".ini", ".cfg", ".retry", ".pyc", ".pyo"], islist=True)
DEFAULT_VAR_COMPRESSION_LEVEL = get_config(p, DEF... |
class Templar:
loader=FileSystemLoader(self._basedir),
)
self.SINGLE_VAR = re.compile(r"^%s\s*(\w*)\s*%s$" % (self.environment.variable_start_string, self.environment.variable_end_string))
self.block_start = self.environment.block_start_string | class Templar:
loader=FileSystemLoader(self._basedir),
)
# the current rendering context under which the templar class is working
self.cur_context = None
self.SINGLE_VAR = re.compile(r"^%s\s*(\w*)\s*%s$" % (self.environment.variable_start_string, self.environment.variable_e... |
class Templar:
if instance is not None:
wantlist = kwargs.pop('wantlist', False)
from ansible.utils.listify import listify_lookup_plugin_terms
loop_terms = listify_lookup_plugin_terms(terms=args, templar=self, loader=self._loader, fail_on_undefined=True, convert_bare=False) | class Templar:
if instance is not None:
wantlist = kwargs.pop('wantlist', False)
allow_unsafe = kwargs.pop('allow_unsafe', C.DEFAULT_ALLOW_UNSAFE_LOOKUPS)
from ansible.utils.listify import listify_lookup_plugin_terms
loop_terms = listify_lookup_plugin_terms(term... |
class Templar:
raise AnsibleError("An unhandled exception occurred while running the lookup plugin '%s'. Error was a %s, original message: %s" % (name, type(e), e))
ran = None
if ran:
from ansible.vars.unsafe_proxy import UnsafeProxy, wrap_var
... | class Templar:
raise AnsibleError("An unhandled exception occurred while running the lookup plugin '%s'. Error was a %s, original message: %s" % (name, type(e), e))
ran = None
if ran and not allow_unsafe:
from ansible.vars.unsafe_proxy import UnsafeProxy,... |
class Templar:
else:
ran = wrap_var(ran)
return ran
else:
raise AnsibleError("lookup plugin (%s) not found" % name) | class Templar:
else:
ran = wrap_var(ran)
if self.cur_context:
self.cur_context.unsafe = True
return ran
else:
raise AnsibleError("lookup plugin (%s) not found" % name) |
class Templar:
jvars = AnsibleJ2Vars(self, t.globals)
new_context = t.new_context(jvars, shared=True)
rf = t.root_render_func(new_context)
try: | class Templar:
jvars = AnsibleJ2Vars(self, t.globals)
self.cur_context = new_context = t.new_context(jvars, shared=True)
rf = t.root_render_func(new_context)
try: |
class Functional(training_lib.Model):
than with subclassed `Model`s, specifically:
- Model cloning (`keras.models.clone`)
- Serialization (`model.get_config()/from_config`, `model.to_json()/to_yaml()`
- Whole-model saving (`model.save()`)
A `Functional` model can be instantiated by passing two arguments to | class Functional(training_lib.Model):
than with subclassed `Model`s, specifically:
- Model cloning (`keras.models.clone`)
- Serialization (`model.get_config()/from_config`, `model.to_json()`
- Whole-model saving (`model.save()`)
A `Functional` model can be instantiated by passing two arguments to |
from tensorflow.python.platform import test
from tensorflow.python.training.tracking.util import Checkpoint
try:
import yaml # pylint:disable=g-import-not-at-top
except ImportError:
yaml = None
class NetworkConstructionTest(keras_parameterized.TestCase):
| from tensorflow.python.platform import test
from tensorflow.python.training.tracking.util import Checkpoint
class NetworkConstructionTest(keras_parameterized.TestCase):
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.