buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
def test_handle_write_no_notify_after_flush(self):
inst.total_outbufs_len = len(inst.outbufs[0])
inst.adj.send_bytes = 1
inst.adj.outbuf_high_watermark = 2
sock.send = lambda x: False
inst.will_close = False
inst.last_activity = 0
result = inst.handle_write() | def test_handle_write_no_notify_after_flush(self):
inst.total_outbufs_len = len(inst.outbufs[0])
inst.adj.send_bytes = 1
inst.adj.outbuf_high_watermark = 2
sock.send = lambda x, do_close=True: False
inst.will_close = False
inst.last_activity = 0
result = inst.hand... |
def get(self, numbytes):
buf = DummyHugeOutbuffer()
inst.outbufs = [buf]
inst.send = lambda *arg: 0
result = inst._flush_some()
# we are testing that _flush_some doesn't raise an OverflowError
# when one of its outbufs has a __len__ that returns gt sys.maxint | def get(self, numbytes):
buf = DummyHugeOutbuffer()
inst.outbufs = [buf]
inst.send = lambda *arg, do_close: 0
result = inst._flush_some()
# we are testing that _flush_some doesn't raise an OverflowError
# when one of its outbufs has a __len__ that returns gt sys.maxint |
class Bidirectional(Wrapper):
return self.forward_layer.updates + self.backward_layer.updates
return []
@property
def losses(self):
if hasattr(self.forward_layer, 'losses'):
return self.forward_layer.losses + self.backward_layer.losses
return []
@property
... | class Bidirectional(Wrapper):
return self.forward_layer.updates + self.backward_layer.updates
return []
def get_updates_for(self, inputs=None):
forward_updates = self.forward_layer.get_updates_for(inputs)
backward_updates = self.backward_layer.get_updates_for(inputs)
ret... |
def test_Bidirectional_trainable():
assert len(layer.trainable_weights) == 6
if __name__ == '__main__':
pytest.main([__file__]) | def test_Bidirectional_trainable():
assert len(layer.trainable_weights) == 6
@keras_test
def test_Bidirectional_updates():
x = Input(shape=(3, 2))
layer = wrappers.Bidirectional(layers.SimpleRNN(3))
assert len(layer.updates) == 0
assert len(layer.get_updates_for(None)) == 0
assert len(layer.ge... |
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(
)
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, str) else x for x in cmd]
elif isinstance(cmd, str):
return cmd.strip()
... | def _run(
)
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' parameter.
msg = "Executing command {}{}{} {}{}in director... |
def _run(
log.error(
"Failed to decode stdout from command %s, non-decodable "
"characters have been replaced",
cmd,
)
try: | def _run(
log.error(
"Failed to decode stdout from command %s, non-decodable "
"characters have been replaced",
_log_cmd(cmd),
)
try: |
def _run(
log.error(
"Failed to decode stderr from command %s, non-decodable "
"characters have been replaced",
cmd,
)
if rstrip: | def _run(
log.error(
"Failed to decode stderr from command %s, non-decodable "
"characters have been replaced",
_log_cmd(cmd),
)
if rstrip: |
def _run(
if not ignore_retcode and ret["retcode"] != 0:
if output_loglevel < LOG_LEVELS["error"]:
output_loglevel = LOG_LEVELS["error"]
msg = "Command '{}' failed with return code: {}".format(cmd, ret["retcode"])
log.error(log_callback(msg))
if ret["s... | def _run(
if not ignore_retcode and ret["retcode"] != 0:
if output_loglevel < LOG_LEVELS["error"]:
output_loglevel = LOG_LEVELS["error"]
msg = "Command '{}' failed with return code: {}".format(_log_cmd(cmd), ret["retcode"])
log.error(log_callback(msg))
... |
def run(
if not ignore_retcode and ret["retcode"] != 0:
if lvl < LOG_LEVELS["error"]:
lvl = LOG_LEVELS["error"]
msg = "Command '{}' failed with return code: {}".format(cmd, ret["retcode"])
log.error(log_callback(msg))
if raise_err:
... | def run(
if not ignore_retcode and ret["retcode"] != 0:
if lvl < LOG_LEVELS["error"]:
lvl = LOG_LEVELS["error"]
msg = "Command '{}' failed with return code: {}".format(_log_cmd(cmd), ret["retcode"])
log.error(log_callback(msg))
if raise_err:
... |
class CMDMODTestCase(TestCase, LoaderModuleMockMixin):
umask=None,
use_vt=False,
) | class CMDMODTestCase(TestCase, LoaderModuleMockMixin):
umask=None,
use_vt=False,
)
def test_cve_2021_25284(self):
proc = MagicMock(
return_value=MockTimedProc(
stdout=b"foo",
stderr=b"wtf",
returncode=2
... |
options:
description:
- Whether to disable the GPG checking of signatures of packages being
installed. Has an effect only if state is I(present) or I(latest).
type: bool
default: 'no'
| options:
description:
- Whether to disable the GPG checking of signatures of packages being
installed. Has an effect only if state is I(present) or I(latest).
- This setting affects packages installed from a repository as well as
"local" packages installed from the filesystem or a URL.
... |
class DnfModule(YumDnf):
results=[],
)
if self.download_only:
for package in self.base.transaction.install_set:
response['results'].append("Downloaded: {0}".format(package)) | class DnfModule(YumDnf):
results=[],
)
# Validate GPG. This is NOT done in dnf.Base (it's done in the
# upstream CLI subclass of dnf.Base)
if not self.disable_gpg_check:
for package in self.base.transaction.... |
class HttpRequest(object):
"""Return the HTTP host using the environment or request headers."""
host = self._get_raw_host()
# There is no hostname validation when DEBUG=True
if settings.DEBUG:
return host
domain, port = split_domain_port(host)
if domain and ... | class HttpRequest(object):
"""Return the HTTP host using the environment or request headers."""
host = self._get_raw_host()
# Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True.
allowed_hosts = settings.ALLOWED_HOSTS
if settings.DEBUG and not allowed_hosts:
... |
class CsrfViewMiddlewareTest(SimpleTestCase):
self.assertEqual(len(csrf_cookie.value), CSRF_TOKEN_LENGTH)
self._check_token_present(resp, csrf_id=csrf_cookie.value)
@override_settings(DEBUG=True)
def test_https_bad_referer(self):
"""
Test that a POST HTTPS request with a bad ref... | class CsrfViewMiddlewareTest(SimpleTestCase):
self.assertEqual(len(csrf_cookie.value), CSRF_TOKEN_LENGTH)
self._check_token_present(resp, csrf_id=csrf_cookie.value)
@override_settings(DEBUG=True, ALLOWED_HOSTS=['www.example.com'])
def test_https_bad_referer(self):
"""
Test that ... |
class HostValidationTests(SimpleTestCase):
self.assertEqual(request.get_port(), '8080')
@override_settings(DEBUG=True, ALLOWED_HOSTS=[])
def test_host_validation_disabled_in_debug_mode(self):
"""If ALLOWED_HOSTS is empty and DEBUG is True, all hosts pass."""
request = HttpRequest()
... | class HostValidationTests(SimpleTestCase):
self.assertEqual(request.get_port(), '8080')
@override_settings(DEBUG=True, ALLOWED_HOSTS=[])
def test_host_validation_in_debug_mode(self):
"""
If ALLOWED_HOSTS is empty and DEBUG is True, variants of localhost are
allowed.
"""
... |
def get_file(fname,
Path to the downloaded file
""" # noqa
if cache_dir is None:
cache_dir = os.path.join(os.path.expanduser('~'), '.keras')
if md5_hash is not None and file_hash is None:
file_hash = md5_hash
hash_algorithm = 'md5' | def get_file(fname,
Path to the downloaded file
""" # noqa
if cache_dir is None:
if 'KERAS_HOME' in os.environ:
cache_dir = os.environ.get('KERAS_HOME')
else:
cache_dir = os.path.join(os.path.expanduser('~'), '.keras')
if md5_hash is not None and file_hash is... |
import time
import sys
import tarfile
import threading
import zipfile
from itertools import cycle
import multiprocessing as mp | import time
import sys
import tarfile
import threading
import shutil
import zipfile
from itertools import cycle
import multiprocessing as mp |
import pytest
import six
from six.moves.urllib.parse import urljoin
from six.moves.urllib.request import pathname2url
from flaky import flaky
| import pytest
import six
from six.moves.urllib.parse import urljoin
from six.moves.urllib.request import pathname2url
from six.moves import reload_module
from flaky import flaky
|
def test_data_utils(in_tmpdir):
origin = urljoin('file://', pathname2url(os.path.abspath('test.tar.gz')))
path = get_file(dirname, origin, untar=True)
filepath = path + '.tar.gz'
hashval_sha256 = _hash_file(filepath) | def test_data_utils(in_tmpdir):
origin = urljoin('file://', pathname2url(os.path.abspath('test.tar.gz')))
path = get_file(dirname, origin, untar=True)
filepath = path + '.tar.gz'
data_keras_home = os.path.dirname(os.path.dirname(os.path.abspath(filepath)))
assert data_keras_home == os.path.dirname... |
def test_data_utils(in_tmpdir):
assert validate_file(path, hashval_md5)
os.remove(path)
os.remove('test.txt')
os.remove('test.zip')
| def test_data_utils(in_tmpdir):
assert validate_file(path, hashval_md5)
os.remove(path)
os.remove(os.path.join(os.path.dirname(path), 'test.txt'))
os.remove('test.txt')
os.remove('test.zip')
|
def localpkgs(directory):
cache[name] = {'path': fn, 'size': st.st_size, 'device': st.st_dev}
return cache
def parseArgs():
usage = _("""
Reposync is used to synchronize a remote yum repository to a local | def localpkgs(directory):
cache[name] = {'path': fn, 'size': st.st_size, 'device': st.st_dev}
return cache
def is_subpath(path, root):
root = os.path.realpath(root)
path = os.path.realpath(os.path.join(root, path))
# join() is used below to ensure root ends with a slash
return path.star... |
def parseArgs():
parser.add_option("", "--download-metadata", dest="downloadmd",
default=False, action="store_true",
help=_("download all the non-default metadata"))
(opts, args) = parser.parse_args()
return (opts, args)
| def parseArgs():
parser.add_option("", "--download-metadata", dest="downloadmd",
default=False, action="store_true",
help=_("download all the non-default metadata"))
parser.add_option("", "--allow-path-traversal", default=False,
action="store_true",
help=_("Allow packages stored ... |
def main():
else:
local_repo_path = opts.destdir + '/' + repo.id
if opts.delete and os.path.exists(local_repo_path):
current_pkgs = localpkgs(local_repo_path)
| def main():
else:
local_repo_path = opts.destdir + '/' + repo.id
# Ensure we don't traverse out of local_repo_path by dropping any
# packages whose remote_path is absolute or contains up-level
# references (unless explicitly allowed).
# See RHBZ#1600221 for details.
... |
class TimedeltaIndex(
this, other = self, other
if this._can_fast_union(other):
return this._fast_union(other)
else:
result = Index._union(this, other, sort=sort)
if isinstance(result, TimedeltaIndex): | class TimedeltaIndex(
this, other = self, other
if this._can_fast_union(other):
return this._fast_union(other, sort=sort)
else:
result = Index._union(this, other, sort=sort)
if isinstance(result, TimedeltaIndex): |
class TimedeltaIndex(
result._set_freq("infer")
return result
def _fast_union(self, other):
if len(other) == 0:
return self.view(type(self))
| class TimedeltaIndex(
result._set_freq("infer")
return result
def _fast_union(self, other, sort=None):
if len(other) == 0:
return self.view(type(self))
|
class TimedeltaIndex(
# to make our life easier, "sort" the two ranges
if self[0] <= other[0]:
left, right = self, other
else:
left, right = other, self
| class TimedeltaIndex(
# to make our life easier, "sort" the two ranges
if self[0] <= other[0]:
left, right = self, other
elif sort is False:
# TDIs are not in the "correct" order and we don't want
# to sort but want to remove overlaps
left, right ... |
class TestTimedeltaIndex:
i1.union(i2) # Works
i2.union(i1) # Fails with "AttributeError: can't set attribute"
def test_union_coverage(self):
idx = TimedeltaIndex(["3d", "1d", "2d"]) | class TestTimedeltaIndex:
i1.union(i2) # Works
i2.union(i1) # Fails with "AttributeError: can't set attribute"
def test_union_sort_false(self):
tdi = timedelta_range("1day", periods=5)
left = tdi[3:]
right = tdi[:3]
# Check that we are testing the desired code pa... |
class Path:
if not args:
return Path(np.empty([0, 2], dtype=np.float32))
vertices = np.concatenate([x.vertices for x in args])
codes = np.empty(len(vertices), dtype=cls.code_type)
i = 0 | class Path:
if not args:
return Path(np.empty([0, 2], dtype=np.float32))
# concatenate paths
vertices = np.concatenate([x.vertices for x in args])
codes = np.empty(len(vertices), dtype=cls.code_type)
i = 0 |
class Path:
codes[i:i + len(path.codes)] = path.codes
i += len(path.vertices)
return cls(vertices, codes)
def __repr__(self): | class Path:
codes[i:i + len(path.codes)] = path.codes
i += len(path.vertices)
# remove internal STOP's, replace kinal stop if present
last_vert = None
if codes.size > 0 and codes[-1] == cls.STOP:
last_vert = vertices[-1]
vertices = vertices[codes ... |
def test_make_compound_path_empty():
assert r.vertices.shape == (0, 2)
@image_comparison(['xkcd.png'], remove_text=True)
def test_xkcd():
np.random.seed(0) | def test_make_compound_path_empty():
assert r.vertices.shape == (0, 2)
def test_make_compound_path_stops():
zero = [0, 0]
paths = 3*[Path([zero, zero], [Path.MOVETO, Path.STOP])]
compound_path = Path.make_compound_path(*paths)
assert np.sum(compound_path.codes == Path.STOP) == 1
@image_compariso... |
def _partition_tasks(worker):
set_tasks["completed"] = {task for (task, status, ext) in task_history if status == 'DONE' and task in pending_tasks}
set_tasks["already_done"] = {task for (task, status, ext) in task_history
if status == 'DONE' and task not in pending_tasks and tas... | def _partition_tasks(worker):
set_tasks["completed"] = {task for (task, status, ext) in task_history if status == 'DONE' and task in pending_tasks}
set_tasks["already_done"] = {task for (task, status, ext) in task_history
if status == 'DONE' and task not in pending_tasks and tas... |
def _depth_first_search(set_tasks, current_task, visited):
for task in current_task._requires():
if task not in visited:
_depth_first_search(set_tasks, task, visited)
if task in set_tasks["failed"] or task in set_tasks["upstream_failure"]:
set_tasks["upstr... | def _depth_first_search(set_tasks, current_task, visited):
for task in current_task._requires():
if task not in visited:
_depth_first_search(set_tasks, task, visited)
if task in set_tasks["ever_failed"] or task in set_tasks["upstream_failure"]:
set_tasks["... |
def _get_comments(group_tasks):
_ORDERED_STATUSES = (
"already_done",
"completed",
"failed",
"scheduling_error",
"still_pending", | def _get_comments(group_tasks):
_ORDERED_STATUSES = (
"already_done",
"completed",
"ever_failed",
"failed",
"scheduling_error",
"still_pending", |
def _summary_format(set_tasks, worker):
str_output += 'Did not run any tasks'
smiley = ""
reason = ""
if set_tasks["failed"]:
smiley = ":("
reason = "there were failed tasks"
if set_tasks["scheduling_error"]:
reason += " and tasks whose scheduling failed"
elif... | def _summary_format(set_tasks, worker):
str_output += 'Did not run any tasks'
smiley = ""
reason = ""
if set_tasks["ever_failed"]:
if not set_tasks["failed"]:
smiley = ":)"
reason = "there were failed tasks but they all suceeded in a retry"
else:
s... |
class ExecutionSummaryTest(LuigiTestCase):
self.assertIn('Luigi Execution Summary', s)
self.assertNotIn('00:00:00', s)
self.assertNotIn('\n\n\n', s) | class ExecutionSummaryTest(LuigiTestCase):
self.assertIn('Luigi Execution Summary', s)
self.assertNotIn('00:00:00', s)
self.assertNotIn('\n\n\n', s)
"""
Test that a task once crashing and then succeeding should be counted as no failure.
"""
def test_status_with_task_retry(self):... |
class RetcodesTest(LuigiTestCase):
with mock.patch('luigi.scheduler.Scheduler.add_task', new_func):
self.run_and_expect('RequiringTask', 0)
self.run_and_expect('RequiringTask --retcode-not-run 5', 5) | class RetcodesTest(LuigiTestCase):
with mock.patch('luigi.scheduler.Scheduler.add_task', new_func):
self.run_and_expect('RequiringTask', 0)
self.run_and_expect('RequiringTask --retcode-not-run 5', 5)
"""
Test that a task once crashing and then succeeding should be counted as no ... |
class TestUtil(unittest.TestCase):
self.assertEqual(urljoin('http://foo.de/', ''), None)
self.assertEqual(urljoin('http://foo.de/', ['foobar']), None)
self.assertEqual(urljoin('http://foo.de/a/b/c.txt', '.././../d.txt'), 'http://foo.de/d.txt')
def test_url_or_none(self):
self.assert... | class TestUtil(unittest.TestCase):
self.assertEqual(urljoin('http://foo.de/', ''), None)
self.assertEqual(urljoin('http://foo.de/', ['foobar']), None)
self.assertEqual(urljoin('http://foo.de/a/b/c.txt', '.././../d.txt'), 'http://foo.de/d.txt')
self.assertEqual(urljoin('http://foo.de/a/b/... |
def urljoin(base, path):
path = path.decode('utf-8')
if not isinstance(path, compat_str) or not path:
return None
if re.match(r'^(?:https?:)?//', path):
return path
if isinstance(base, bytes):
base = base.decode('utf-8') | def urljoin(base, path):
path = path.decode('utf-8')
if not isinstance(path, compat_str) or not path:
return None
if re.match(r'^(?:[a-zA-Z][a-zA-Z0-9+-.]*:)?//', path):
return path
if isinstance(base, bytes):
base = base.decode('utf-8') |
def test_getproxies_environment_keep_no_proxies(self):
self.assertTrue(urllib.request.proxy_bypass_environment('anotherdomain.com:8888'))
self.assertTrue(urllib.request.proxy_bypass_environment('newdomain.com:1234'))
def test_proxy_bypass_environment_host_match(self):
bypass = urllib.reques... | def test_getproxies_environment_keep_no_proxies(self):
self.assertTrue(urllib.request.proxy_bypass_environment('anotherdomain.com:8888'))
self.assertTrue(urllib.request.proxy_bypass_environment('newdomain.com:1234'))
def test_proxy_cgi_ignore(self):
try:
self.env.set('HTTP_PROXY... |
def getproxies_environment():
name = name.lower()
if value and name[-6:] == '_proxy':
proxies[name[:-6]] = value
for name, value in os.environ.items():
if name[-6:] == '_proxy':
name = name.lower() | def getproxies_environment():
name = name.lower()
if value and name[-6:] == '_proxy':
proxies[name[:-6]] = value
# CVE-2016-1000110 - If we are running as CGI script, forget HTTP_PROXY
# (non-all-lowercase) as it may be set from the web server by a "Proxy:"
# header from the clie... |
def shortDescription(self):
return """%s .decrypt() output of .encrypt() should not be garbled""" % (self.module_name,)
def runTest(self):
for mode in (self.module.MODE_ECB, self.module.MODE_CBC, self.module.MODE_CFB, self.module.MODE_OFB, self.module.MODE_OPENPGP):
encryption_cipher = ... | def shortDescription(self):
return """%s .decrypt() output of .encrypt() should not be garbled""" % (self.module_name,)
def runTest(self):
## ECB mode
mode = self.module.MODE_ECB
encryption_cipher = self.module.new(a2b_hex(self.key), mode)
ciphertext = encryption_cipher.enc... |
def read_json(
dtype = True
if convert_axes is None and orient != "table":
convert_axes = True
compression = _infer_compression(path_or_buf, compression)
filepath_or_buffer, _, compression, should_close = get_filepath_or_buffer( | def read_json(
dtype = True
if convert_axes is None and orient != "table":
convert_axes = True
if encoding is None:
encoding = "utf-8"
compression = _infer_compression(path_or_buf, compression)
filepath_or_buffer, _, compression, should_close = get_filepath_or_buffer( |
def test_readjson_chunks_multiple_empty_lines(chunksize):
tm.assert_frame_equal(
orig, test, obj="chunksize: {chunksize}".format(chunksize=chunksize)
) | def test_readjson_chunks_multiple_empty_lines(chunksize):
tm.assert_frame_equal(
orig, test, obj="chunksize: {chunksize}".format(chunksize=chunksize)
)
def test_readjson_unicode(monkeypatch):
with tm.ensure_clean("test.json") as path:
monkeypatch.setattr("_bootlocale.getpreferredencoding",... |
from AccessControl import ClassSecurityInfo, Unauthorized
from Products.CMFPlone.PloneBaseTool import PloneBaseTool
from Products.CMFPlone.PloneTool import EMAIL_RE
# - remove '1', 'l', and 'I' to avoid confusion
# - remove '0', 'O', and 'Q' to avoid confusion
# - remove vowels to avoid spelling words | from AccessControl import ClassSecurityInfo, Unauthorized
from Products.CMFPlone.PloneBaseTool import PloneBaseTool
from Products.CMFPlone.PloneTool import EMAIL_RE
from Products.PluggableAuthService.interfaces.authservice \
import IPluggableAuthService
# - remove '1', 'l', and 'I' to avoid confusion
# - remo... |
class RegistrationTool(PloneBaseTool, BaseTool):
return self.mail_password_response( self, self.REQUEST )
RegistrationTool.__doc__ = BaseTool.__doc__
| class RegistrationTool(PloneBaseTool, BaseTool):
return self.mail_password_response( self, self.REQUEST )
def isMemberIdAllowed(self, id):
if len(id) < 1 or id == 'Anonymous User':
return 0
if not self._ALLOWED_MEMBER_ID_PATTERN.match( id ):
return 0
pas = ... |
class TestRegistrationTool(PloneTestCase.PloneTestCase):
def afterSetUp(self):
self.registration = self.portal.portal_registration
def testJoinCreatesUser(self):
self.registration.addMember(member_id, 'secret', | class TestRegistrationTool(PloneTestCase.PloneTestCase):
def afterSetUp(self):
self.registration = self.portal.portal_registration
self.portal.acl_users.userFolderAddUser("userid", "password",
(), (), ())
self.portal.acl_users._doAddGroup("groupid", ())
def testJoinCrea... |
class TestRegistrationTool(PloneTestCase.PloneTestCase):
def testInvalidCMFDefaultEmailFailsValidation(self):
# http://dev.plone.org/plone/ticket/3910
self.failIf(self.registration.isValidEmail('bogus@127.0.0.1'))
class TestPasswordGeneration(PloneTestCase.PloneTestCase):
| class TestRegistrationTool(PloneTestCase.PloneTestCase):
def testInvalidCMFDefaultEmailFailsValidation(self):
# http://dev.plone.org/plone/ticket/3910
self.failIf(self.registration.isValidEmail('bogus@127.0.0.1'))
def testNewIdAllowed(self):
self.assertEqual(self.registration.isMemberId... |
from django.contrib.gis.db.models.fields import (
ExtentField, GeometryCollectionField, GeometryField, LineStringField,
)
from django.db.models.aggregates import Aggregate
from django.utils.functional import cached_property
| from django.contrib.gis.db.models.fields import (
ExtentField, GeometryCollectionField, GeometryField, LineStringField,
)
from django.db.models import Value
from django.db.models.aggregates import Aggregate
from django.utils.functional import cached_property
|
class GeoAggregate(Aggregate):
)
def as_oracle(self, compiler, connection, **extra_context):
tolerance = self.extra.get('tolerance') or getattr(self, 'tolerance', 0.05)
template = None if self.is_extent else '%(function)s(SDOAGGRTYPE(%(expressions)s,%(tolerance)s))'
return self.as_s... | class GeoAggregate(Aggregate):
)
def as_oracle(self, compiler, connection, **extra_context):
if not self.is_extent:
tolerance = self.extra.get('tolerance') or getattr(self, 'tolerance', 0.05)
clone = self.copy()
clone.set_source_expressions([
*sel... |
class OracleToleranceMixin:
tolerance = 0.05
def as_oracle(self, compiler, connection, **extra_context):
tol = self.extra.get('tolerance', self.tolerance)
return self.as_sql(
compiler, connection,
template="%%(function)s(%%(expressions)s, %s)" % tol,
**extra_... | class OracleToleranceMixin:
tolerance = 0.05
def as_oracle(self, compiler, connection, **extra_context):
tolerance = Value(self._handle_param(
self.extra.get('tolerance', self.tolerance),
'tolerance',
NUMERIC_TYPES,
))
clone = self.copy()
clon... |
class DistanceFunctionsTests(FuncTestMixin, TestCase):
).filter(d=D(m=1))
self.assertTrue(qs.exists())
@skipIfDBFeature("supports_distance_geodetic")
@skipUnlessDBFeature("has_Distance_function")
def test_distance_function_raw_result_d_lookup(self): | class DistanceFunctionsTests(FuncTestMixin, TestCase):
).filter(d=D(m=1))
self.assertTrue(qs.exists())
@unittest.skipUnless(
connection.vendor == 'oracle',
'Oracle supports tolerance paremeter.',
)
def test_distance_function_tolerance_escaping(self):
qs = Interstate.... |
from django.contrib.gis.geos import (
MultiPoint, MultiPolygon, Point, Polygon, fromstr,
)
from django.core.management import call_command
from django.db import NotSupportedError, connection
from django.test import TestCase, skipUnlessDBFeature
from ..utils import ( | from django.contrib.gis.geos import (
MultiPoint, MultiPolygon, Point, Polygon, fromstr,
)
from django.core.management import call_command
from django.db import DatabaseError, NotSupportedError, connection
from django.test import TestCase, skipUnlessDBFeature
from ..utils import ( |
class GeoQuerySetTest(TestCase):
qs = City.objects.filter(name='NotACity')
self.assertIsNone(qs.aggregate(Union('point'))['point__union'])
def test_within_subquery(self):
"""
Using a queryset inside a geo lookup is working (using a subquery) | class GeoQuerySetTest(TestCase):
qs = City.objects.filter(name='NotACity')
self.assertIsNone(qs.aggregate(Union('point'))['point__union'])
@unittest.skipUnless(
connection.vendor == 'oracle',
'Oracle supports tolerance paremeter.',
)
def test_unionagg_tolerance(self):
... |
def _convert_by(by):
@Substitution("\ndata : DataFrame")
@Appender(_shared_docs["pivot"], indents=1)
def pivot(data: "DataFrame", index=None, columns=None, values=None) -> "DataFrame":
if values is None:
cols = [columns] if index is None else [index, columns]
append = index is None | def _convert_by(by):
@Substitution("\ndata : DataFrame")
@Appender(_shared_docs["pivot"], indents=1)
def pivot(data: "DataFrame", index=None, columns=None, values=None) -> "DataFrame":
if columns is None:
raise TypeError("pivot() missing 1 required argument: 'columns'")
if values is None:
cols ... |
class TestPivotTable:
expected = DataFrame(data=data, index=index, columns=columns, dtype="object")
tm.assert_frame_equal(result, expected)
@pytest.mark.xfail(
reason="MultiIndexed unstack with tuple names fails with KeyError GH#19966"
) | class TestPivotTable:
expected = DataFrame(data=data, index=index, columns=columns, dtype="object")
tm.assert_frame_equal(result, expected)
def test_pivot_columns_none_raise_error(self):
# GH 30924
df = pd.DataFrame(
{"col1": ["a", "b", "c"], "col2": [1, 2, 3], "col3": [... |
def test_register(self):
# Test registering a viewer that is not a class
ImageShow.register("not a class")
def test_show(self):
class TestViewer:
methodCalled = False | def test_register(self):
# Test registering a viewer that is not a class
ImageShow.register("not a class")
# Restore original state
ImageShow._viewers.pop()
def test_show(self):
class TestViewer:
methodCalled = False |
def show(self, image, title=None, **options):
self.assertTrue(ImageShow.show(im))
self.assertTrue(viewer.methodCalled)
def test_viewer(self):
viewer = ImageShow.Viewer()
| def show(self, image, title=None, **options):
self.assertTrue(ImageShow.show(im))
self.assertTrue(viewer.methodCalled)
# Restore original state
ImageShow._viewers.pop(0)
def test_viewer(self):
viewer = ImageShow.Viewer()
|
def test_viewer(self):
self.assertRaises(NotImplementedError, viewer.get_command, None)
if __name__ == '__main__':
unittest.main() | def test_viewer(self):
self.assertRaises(NotImplementedError, viewer.get_command, None)
def test_viewers(self):
for viewer in ImageShow._viewers:
viewer.get_command('test.jpg')
if __name__ == '__main__':
unittest.main() |
from PIL import Image
import os
import sys
if sys.version_info.major >= 3:
from shlex import quote | from PIL import Image
import os
import sys
import subprocess
import tempfile
if sys.version_info.major >= 3:
from shlex import quote |
def get_command(self, file, **options):
quote(file))
return command
register(MacViewer)
else: | def get_command(self, file, **options):
quote(file))
return command
def show_file(self, file, **options):
"""Display given file"""
f, path = tempfile.mkstemp()
f.write(file)
f.close()
... |
class UnixViewer(Viewer):
format = "PNG"
options = {'compress_level': 1}
def show_file(self, file, **options):
command, executable = self.get_command_ex(file, **options)
command = "(%s %s; rm -f %s)&" % (command, quote(file),
... | class UnixViewer(Viewer):
format = "PNG"
options = {'compress_level': 1}
def get_command(self, file, **options):
command = self.get_command_ex(file, **options)[0]
return "(%s %s; rm -f %s)&" % (command, quote(file), quote(file))
def show_file(self, file, **optio... |
import base64
import binascii
import hashlib
import importlib
from collections import OrderedDict
from django.conf import settings | import base64
import binascii
import hashlib
import importlib
import warnings
from collections import OrderedDict
from django.conf import settings |
def check_password(password, encoded, setter=None, preferred='default'):
preferred = get_hasher(preferred)
hasher = identify_hasher(encoded)
must_update = hasher.algorithm != preferred.algorithm
if not must_update:
must_update = preferred.must_update(encoded)
is_correct = hasher.verify(pass... | def check_password(password, encoded, setter=None, preferred='default'):
preferred = get_hasher(preferred)
hasher = identify_hasher(encoded)
hasher_changed = hasher.algorithm != preferred.algorithm
must_update = hasher_changed or preferred.must_update(encoded)
is_correct = hasher.verify(password, e... |
class BasePasswordHasher(object):
def must_update(self, encoded):
return False
class PBKDF2PasswordHasher(BasePasswordHasher):
""" | class BasePasswordHasher(object):
def must_update(self, encoded):
return False
def harden_runtime(self, password, encoded):
"""
Bridge the runtime gap between the work factor supplied in `encoded`
and the work factor suggested by this hasher.
Taking PBKDF2 as an example... |
class PBKDF2PasswordHasher(BasePasswordHasher):
algorithm, iterations, salt, hash = encoded.split('$', 3)
return int(iterations) != self.iterations
class PBKDF2SHA1PasswordHasher(PBKDF2PasswordHasher):
""" | class PBKDF2PasswordHasher(BasePasswordHasher):
algorithm, iterations, salt, hash = encoded.split('$', 3)
return int(iterations) != self.iterations
def harden_runtime(self, password, encoded):
algorithm, iterations, salt, hash = encoded.split('$', 3)
extra_iterations = self.iteratio... |
class BCryptSHA256PasswordHasher(BasePasswordHasher):
def verify(self, password, encoded):
algorithm, data = encoded.split('$', 1)
assert algorithm == self.algorithm
bcrypt = self._load_library()
# Hash the password prior to using bcrypt to prevent password truncation
# Se... | class BCryptSHA256PasswordHasher(BasePasswordHasher):
def verify(self, password, encoded):
algorithm, data = encoded.split('$', 1)
assert algorithm == self.algorithm
encoded_2 = self.encode(password, force_bytes(data))
return constant_time_compare(encoded, encoded_2)
def safe_su... |
class BCryptSHA256PasswordHasher(BasePasswordHasher):
(_('checksum'), mask_hash(checksum)),
])
class BCryptPasswordHasher(BCryptSHA256PasswordHasher):
""" | class BCryptSHA256PasswordHasher(BasePasswordHasher):
(_('checksum'), mask_hash(checksum)),
])
def harden_runtime(self, password, encoded):
_, data = encoded.split('$', 1)
salt = data[:29] # Length of the salt in bcrypt.
rounds = data.split('$')[2]
# work factor... |
class SHA1PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(hash)),
])
class MD5PasswordHasher(BasePasswordHasher):
""" | class SHA1PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(hash)),
])
def harden_runtime(self, password, encoded):
pass
class MD5PasswordHasher(BasePasswordHasher):
""" |
class MD5PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(hash)),
])
class UnsaltedSHA1PasswordHasher(BasePasswordHasher):
""" | class MD5PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(hash)),
])
def harden_runtime(self, password, encoded):
pass
class UnsaltedSHA1PasswordHasher(BasePasswordHasher):
""" |
class UnsaltedSHA1PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(hash)),
])
class UnsaltedMD5PasswordHasher(BasePasswordHasher):
""" | class UnsaltedSHA1PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(hash)),
])
def harden_runtime(self, password, encoded):
pass
class UnsaltedMD5PasswordHasher(BasePasswordHasher):
""" |
class UnsaltedMD5PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(encoded, show=3)),
])
class CryptPasswordHasher(BasePasswordHasher):
""" | class UnsaltedMD5PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(encoded, show=3)),
])
def harden_runtime(self, password, encoded):
pass
class CryptPasswordHasher(BasePasswordHasher):
""" |
class CryptPasswordHasher(BasePasswordHasher):
(_('salt'), salt),
(_('hash'), mask_hash(data, show=3)),
]) | class CryptPasswordHasher(BasePasswordHasher):
(_('salt'), salt),
(_('hash'), mask_hash(data, show=3)),
])
def harden_runtime(self, password, encoded):
pass |
from django.contrib.auth.hashers import (
check_password, get_hasher, identify_hasher, is_password_usable,
make_password,
)
from django.test import SimpleTestCase
from django.test.utils import override_settings
from django.utils import six
try:
import crypt | from django.contrib.auth.hashers import (
check_password, get_hasher, identify_hasher, is_password_usable,
make_password,
)
from django.test import SimpleTestCase, mock
from django.test.utils import override_settings
from django.utils import six
from django.utils.encoding import force_bytes
try:
import cry... |
class TestUtilsHashPass(SimpleTestCase):
self.assertTrue(check_password('', blank_encoded))
self.assertFalse(check_password(' ', blank_encoded))
def test_unusable(self):
encoded = make_password(None)
self.assertEqual(len(encoded), len(UNUSABLE_PASSWORD_PREFIX) + UNUSABLE_PASSWORD_SU... | class TestUtilsHashPass(SimpleTestCase):
self.assertTrue(check_password('', blank_encoded))
self.assertFalse(check_password(' ', blank_encoded))
@skipUnless(bcrypt, "bcrypt not installed")
def test_bcrypt_harden_runtime(self):
hasher = get_hasher('bcrypt')
self.assertEqual('bcry... |
class TestUtilsHashPass(SimpleTestCase):
finally:
hasher.iterations = old_iterations
def test_pbkdf2_upgrade_new_hasher(self):
hasher = get_hasher('default')
self.assertEqual('pbkdf2_sha256', hasher.algorithm) | class TestUtilsHashPass(SimpleTestCase):
finally:
hasher.iterations = old_iterations
def test_pbkdf2_harden_runtime(self):
hasher = get_hasher('default')
self.assertEqual('pbkdf2_sha256', hasher.algorithm)
with mock.patch.object(hasher, 'iterations', 1):
enc... |
class TestUtilsHashPass(SimpleTestCase):
self.assertTrue(check_password('letmein', encoded, setter))
self.assertTrue(state['upgraded'])
def test_load_library_no_algorithm(self):
with self.assertRaises(ValueError) as e:
BasePasswordHasher()._load_library() | class TestUtilsHashPass(SimpleTestCase):
self.assertTrue(check_password('letmein', encoded, setter))
self.assertTrue(state['upgraded'])
def test_check_password_calls_harden_runtime(self):
hasher = get_hasher('default')
encoded = make_password('letmein')
with mock.pa... |
class Connection(object):
self.user = user
self.password = password
self.private_key_file = private_key_file
self.HASHED_KEY_MAGIC = "|1|"
def connect(self): | class Connection(object):
self.user = user
self.password = password
self.private_key_file = private_key_file
self.cp_dir = utils.prepare_writeable_dir('$HOME/.ansible/cp',mode=0700)
self.HASHED_KEY_MAGIC = "|1|"
def connect(self): |
class Connection(object):
else:
self.common_args += ["-o", "ControlMaster=auto",
"-o", "ControlPersist=60s",
"-o", "ControlPath=/tmp/ansible-ssh-%h-%p-%r"]
if not C.HOST_KEY_CHECKING:
self.common_args += ["-o", "S... | class Connection(object):
else:
self.common_args += ["-o", "ControlMaster=auto",
"-o", "ControlPersist=60s",
"-o", "ControlPath=%s/ansible-ssh-%%h-%%p-%%r" % self.cp_dir]
cp_in_use = False
cp_path_set = False
... |
def is_executable(path):
or stat.S_IXGRP & os.stat(path)[stat.ST_MODE]
or stat.S_IXOTH & os.stat(path)[stat.ST_MODE])
def prepare_writeable_dir(tree):
''' make sure a directory exists and is writeable '''
if tree != '/':
tree = os.path.realpath(os.path.expanduser(tree))
if ... | def is_executable(path):
or stat.S_IXGRP & os.stat(path)[stat.ST_MODE]
or stat.S_IXOTH & os.stat(path)[stat.ST_MODE])
def unfrackpath(path):
'''
returns a path that is free of symlinks, environment
variables, relative path traversals and symbols (~)
example:
'$HOME/../../va... |
Wild 185.0
result = coerce_to_dtypes(result, self.dtypes)
if constructor is not None:
result = Series(result, index=labels)
return result
def nunique(self, axis=0, dropna=True) -> Series: | Wild 185.0
result = coerce_to_dtypes(result, self.dtypes)
if constructor is not None:
result = self._constructor_sliced(result, index=labels)
return result
def nunique(self, axis=0, dropna=True) -> Series: |
class TestDataFrameSubclassing:
result = df.apply(lambda x: [1, 2, 3], axis=1)
assert not isinstance(result, tm.SubclassedDataFrame)
tm.assert_series_equal(result, expected) | class TestDataFrameSubclassing:
result = df.apply(lambda x: [1, 2, 3], axis=1)
assert not isinstance(result, tm.SubclassedDataFrame)
tm.assert_series_equal(result, expected)
def test_subclassed_numeric_reductions(self, all_numeric_reductions):
# GH 25596
df = tm.SubclassedD... |
class CollectionRequirement:
requirement = req
op = operator.eq
# In the case we are checking a new requirement on a base requirement (parent != None) we can't accept
# version as '*' (unknown version) unless the requirement is also '*'.
i... | class CollectionRequirement:
requirement = req
op = operator.eq
# In the case we are checking a new requirement on a base requirement (parent != None) we can't accept
# version as '*' (unknown version) unless the requirement is also '*'.
if parent and... |
class CollectionRequirement:
manifest = info['manifest_file']['collection_info']
namespace = manifest['namespace']
name = manifest['name']
version = manifest['version']
dependencies = manifest['dependencies']
else:
display.warning("Collecti... | class CollectionRequirement:
manifest = info['manifest_file']['collection_info']
namespace = manifest['namespace']
name = manifest['name']
version = to_text(manifest['version'], errors='surrogate_or_strict')
if not hasattr(LooseVersion(version), 'version'):
... |
def _get_collection_info(dep_map, existing_collections, collection, requirement,
existing = [c for c in existing_collections if to_text(c) == to_text(collection_info)]
if existing and not collection_info.force:
# Test that the installed collection fits the requirement
existing[0].add_requirement... | def _get_collection_info(dep_map, existing_collections, collection, requirement,
existing = [c for c in existing_collections if to_text(c) == to_text(collection_info)]
if existing and not collection_info.force:
# Test that the installed collection fits the requirement
existing[0].add_requirement... |
def test_build_requirement_from_path(collection_artifact):
assert actual.dependencies == {}
def test_build_requirement_from_path_with_manifest(collection_artifact):
manifest_path = os.path.join(collection_artifact[0], b'MANIFEST.json')
manifest_value = json.dumps({
'collection_info': {
... | def test_build_requirement_from_path(collection_artifact):
assert actual.dependencies == {}
@pytest.mark.parametrize('version', ['1.1.1', 1.1, 1])
def test_build_requirement_from_path_with_manifest(version, collection_artifact):
manifest_path = os.path.join(collection_artifact[0], b'MANIFEST.json')
manife... |
def test_build_requirement_from_path_with_manifest(collection_artifact):
assert actual.b_path == collection_artifact[0]
assert actual.api is None
assert actual.skip is True
assert actual.versions == set([u'1.1.1'])
assert actual.latest_version == u'1.1.1'
assert actual.dependencies == {'ansible_... | def test_build_requirement_from_path_with_manifest(collection_artifact):
assert actual.b_path == collection_artifact[0]
assert actual.api is None
assert actual.skip is True
assert actual.versions == set([to_text(version)])
assert actual.latest_version == to_text(version)
assert actual.dependenci... |
def test_build_requirement_from_path_invalid_manifest(collection_artifact):
collection.CollectionRequirement.from_path(collection_artifact[0], True)
def test_build_requirement_from_tar(collection_artifact):
actual = collection.CollectionRequirement.from_tar(collection_artifact[1], True, True)
| def test_build_requirement_from_path_invalid_manifest(collection_artifact):
collection.CollectionRequirement.from_path(collection_artifact[0], True)
def test_build_requirement_from_path_no_version(collection_artifact, monkeypatch):
manifest_path = os.path.join(collection_artifact[0], b'MANIFEST.json')
... |
def test_add_collection_requirements(versions, requirement, expected_filter, exp
assert req.latest_version == expected_latest
def test_add_collection_requirement_to_unknown_installed_version():
req = collection.CollectionRequirement('namespace', 'name', None, 'https://galaxy.com', ['*'], '*', False,
... | def test_add_collection_requirements(versions, requirement, expected_filter, exp
assert req.latest_version == expected_latest
def test_add_collection_requirement_to_unknown_installed_version(monkeypatch):
mock_display = MagicMock()
monkeypatch.setattr(Display, 'display', mock_display)
req = collectio... |
from tensorflow.python.ops import functional_ops
from tensorflow.python.ops import ctc_ops as ctc
from .common import floatx, epsilon, image_data_format
import functools
import threading
| from tensorflow.python.ops import functional_ops
from tensorflow.python.ops import ctc_ops as ctc
from .common import floatx, epsilon, image_data_format
import sys
import functools
import threading
|
def update(x, new_x):
# Returns
The variable `x` updated.
"""
return tf_state_ops.assign(x, new_x)
@symbolic | def update(x, new_x):
# Returns
The variable `x` updated.
"""
op = tf_state_ops.assign(x, new_x)
with tf.control_dependencies([op]):
return tf.identity(x)
@symbolic |
def update_add(x, increment):
# Returns
The variable `x` updated.
"""
return tf_state_ops.assign_add(x, increment)
@symbolic | def update_add(x, increment):
# Returns
The variable `x` updated.
"""
op = tf_state_ops.assign_add(x, increment)
with tf.control_dependencies([op]):
return tf.identity(x)
@symbolic |
def update_sub(x, decrement):
# Returns
The variable `x` updated.
"""
return tf_state_ops.assign_sub(x, decrement)
@symbolic | def update_sub(x, decrement):
# Returns
The variable `x` updated.
"""
op = tf_state_ops.assign_sub(x, decrement)
with tf.control_dependencies([op]):
return tf.identity(x)
@symbolic |
def get_variable_shape(x):
return int_shape(x)
def print_tensor(x, message=''):
"""Prints `message` and the tensor value when evaluated.
| def get_variable_shape(x):
return int_shape(x)
@symbolic
def print_tensor(x, message=''):
"""Prints `message` and the tensor value when evaluated.
|
def print_tensor(x, message=''):
# Returns
The same tensor `x`, unchanged.
"""
# TODO
return tf.Print(x, [x], message)
# GRAPH MANIPULATION | def print_tensor(x, message=''):
# Returns
The same tensor `x`, unchanged.
"""
op = tf.print(message, x, output_stream=sys.stdout)
with tf.control_dependencies([op]):
return tf.identity(x)
# GRAPH MANIPULATION |
def get_variable_shape(x):
def print_tensor(x, message=''):
"""Print the message and the tensor when evaluated and return the same
tensor.
"""
p_op = Print(message)
return p_op(x) | def get_variable_shape(x):
def print_tensor(x, message=''):
"""Print the message & the tensor when evaluated & return the same tensor.
"""
p_op = Print(message)
return p_op(x) |
class RandomNormal(Initializer):
self.seed = seed
def __call__(self, shape, dtype=None):
return K.random_normal(shape, self.mean, self.stddev,
dtype=dtype, seed=self.seed)
def get_config(self):
return { | class RandomNormal(Initializer):
self.seed = seed
def __call__(self, shape, dtype=None):
x = K.random_normal(shape, self.mean, self.stddev,
dtype=dtype, seed=self.seed)
if self.seed is not None:
self.seed += 1
return x
def get_config(self... |
class RandomUniform(Initializer):
self.seed = seed
def __call__(self, shape, dtype=None):
return K.random_uniform(shape, self.minval, self.maxval,
dtype=dtype, seed=self.seed)
def get_config(self):
return { | class RandomUniform(Initializer):
self.seed = seed
def __call__(self, shape, dtype=None):
x = K.random_uniform(shape, self.minval, self.maxval,
dtype=dtype, seed=self.seed)
if self.seed is not None:
self.seed += 1
return x
def get_config... |
class TruncatedNormal(Initializer):
self.seed = seed
def __call__(self, shape, dtype=None):
return K.truncated_normal(shape, self.mean, self.stddev,
dtype=dtype, seed=self.seed)
def get_config(self):
return { | class TruncatedNormal(Initializer):
self.seed = seed
def __call__(self, shape, dtype=None):
x = K.truncated_normal(shape, self.mean, self.stddev,
dtype=dtype, seed=self.seed)
if self.seed is not None:
self.seed += 1
return x
def get_co... |
class VarianceScaling(Initializer):
if self.distribution == 'normal':
# 0.879... = scipy.stats.truncnorm.std(a=-2, b=2, loc=0., scale=1.)
stddev = np.sqrt(scale) / .87962566103423978
return K.truncated_normal(shape, 0., stddev,
dtype=dtyp... | class VarianceScaling(Initializer):
if self.distribution == 'normal':
# 0.879... = scipy.stats.truncnorm.std(a=-2, b=2, loc=0., scale=1.)
stddev = np.sqrt(scale) / .87962566103423978
x = K.truncated_normal(shape, 0., stddev,
dtype=dtype, see... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.