buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class WaitIterator(object): self.current_index = self.current_future = None self._running_future = None self_ref = weakref.ref(self) for future in futures: future.add_done_callback(functools.partial(
class WaitIterator(object): self.current_index = self.current_future = None self._running_future = None # Use a weak reference to self to avoid cycles that may delay # garbage collection. self_ref = weakref.ref(self) for future in futures: future.add_done_cal...
class WaitIterator(object): the inputs. """ self._running_future = TracebackFuture() if self._finished: self._return_result(self._finished.popleft())
class WaitIterator(object): the inputs. """ self._running_future = TracebackFuture() # As long as there is an active _running_future, we must # ensure that the WaitIterator is not GC'd (due to the # use of weak references in __init__). Add a callback that # refere...
class WaitIteratorTest(AsyncTestCase): self.assertEqual(g.current_index, 3, 'wrong index') i += 1 if __name__ == '__main__': unittest.main()
class WaitIteratorTest(AsyncTestCase): self.assertEqual(g.current_index, 3, 'wrong index') i += 1 @gen_test def test_no_ref(self): # In this usage, there is no direct hard reference to the # WaitIterator itself, only the Future it returns. Since # WaitIte...
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): algorithm, empty, algostr, rounds, data = encoded.split('$', 4) return int(rounds) != self.rounds class BCryptPasswordHasher(BCryptSHA256PasswordHasher): """
class BCryptSHA256PasswordHasher(BasePasswordHasher): algorithm, empty, algostr, rounds, data = encoded.split('$', 4) return int(rounds) != self.rounds def harden_runtime(self, password, encoded): _, data = encoded.split('$', 1) salt = data[:29] # Length of the salt in bcrypt. ...
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): finally: hasher.rounds = old_rounds def test_unusable(self): encoded = make_password(None) self.assertEqual(len(encoded), len(UNUSABLE_PASSWORD_PREFIX) + UNUSABLE_PASSWORD_SUFFIX_LENGTH)
class TestUtilsHashPass(SimpleTestCase): finally: hasher.rounds = old_rounds @skipUnless(bcrypt, "bcrypt not installed") def test_bcrypt_harden_runtime(self): hasher = get_hasher('bcrypt') self.assertEqual('bcrypt', hasher.algorithm) with mock.patch.object(hasher, '...
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...
def gendata4(): data = [gendata1(), gendata2(), gendata4()] class TestAudioop(unittest.TestCase):
def gendata4(): data = [gendata1(), gendata2(), gendata4()] INVALID_DATA = [ ('abc', 0), ('abc', 2), ('abc', 4), ] class TestAudioop(unittest.TestCase):
def test_negativelen(self): self.assertRaises(audioop.error, audioop.findmax, ''.join(chr(x) for x in range(256)), -2392392) def test_main(): run_unittest(TestAudioop)
def test_negativelen(self): self.assertRaises(audioop.error, audioop.findmax, ''.join(chr(x) for x in range(256)), -2392392) def test_issue7673(self): state = None for data, size in INVALID_DATA: size2 = size self.assertRaises(audioop.error, audioop.getsa...
setup( name='sopel_plugins.channelmgnt', version='1.0.2', description='Channelmgnt plugin for Sopel', long_description=readme, long_description_content_type='text/markdown', # This is important!
setup( name='sopel_plugins.channelmgnt', version='1.0.3', description='Channelmgnt plugin for Sopel', long_description=readme, long_description_content_type='text/markdown', # This is important!
def makemodechange(bot, trigger, mode, isusermode=False, isbqmode=False, selfsaf bot.say('Attempting to OP...') bot.say('op ' + trigger.sender, 'ChanServ') time.sleep(1) if isusermode and not trigger.group(2): bot.write(['MODE', trigger.sender, mode, trigger.nick]...
def makemodechange(bot, trigger, mode, isusermode=False, isbqmode=False, selfsaf bot.say('Attempting to OP...') bot.say('op ' + trigger.sender, 'ChanServ') time.sleep(1) if isusermode and not trigger.group(2) and selfsafe: bot.write(['MODE', trigger.sender, mode, ...
def default_urlconf(request): var s = link.getElementsByTagName('span')[0]; var uarr = String.fromCharCode(0x25b6); var darr = String.fromCharCode(0x25bc); s.innerHTML = s.innerHTML == uarr ? darr : uarr; return false; } function switchPastebinFriendly(link) { s1 = "Switch to...
def default_urlconf(request): var s = link.getElementsByTagName('span')[0]; var uarr = String.fromCharCode(0x25b6); var darr = String.fromCharCode(0x25bc); s.textContent = s.textContent == uarr ? darr : uarr; return false; } function switchPastebinFriendly(link) { s1 = "Switc...
from django.utils.encoding import python_2_unicode_compatible class Section(models.Model): """ A simple section that links to articles, to test linking to related items
from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Section(models.Model): """ A simple section that links to articles, to test linking to related items
class Section(models.Model): """ name = models.CharField(max_length=100) @property def name_property(self): """
class Section(models.Model): """ name = models.CharField(max_length=100) def __str__(self): return self.name @property def name_property(self): """
def test_list_editable_popups(self): """ list_editable foreign keys have add/change popups. """ s1 = Section.objects.create(name='Test section') Article.objects.create( content='<p>Middle content</p>', date=datetime.datetime(2008, 3, 18, 11, 54, 58), ...
def test_list_editable_popups(self): """ list_editable foreign keys have add/change popups. """ from selenium.webdriver.support.ui import Select s1 = Section.objects.create(name='Test section') Article.objects.create( title='foo', content='<p>Middl...
def test_list_editable_popups(self): self.wait_for_popup() self.selenium.switch_to.window(self.selenium.window_handles[-1]) self.wait_for_text('#content h1', 'Change section') self.selenium.close() self.selenium.switch_to.window(self.selenium.window_handles[0]) # Add pop...
def test_list_editable_popups(self): self.wait_for_popup() self.selenium.switch_to.window(self.selenium.window_handles[-1]) self.wait_for_text('#content h1', 'Change section') name_input = self.selenium.find_element_by_id('id_name') name_input.clear() name_input.send_keys...
class ErrorInAsyncOpenHandler(TestWebSocketHandler): raise Exception("boom") class WebSocketBaseTestCase(AsyncHTTPTestCase): @gen.coroutine def ws_connect(self, path, **kwargs):
class ErrorInAsyncOpenHandler(TestWebSocketHandler): raise Exception("boom") class NoDelayHandler(TestWebSocketHandler): def open(self): self.set_nodelay(True) self.write_message("hello") class WebSocketBaseTestCase(AsyncHTTPTestCase): @gen.coroutine def ws_connect(self, path, **...
class WebSocketTest(WebSocketBaseTestCase): ), ("/error_in_open", ErrorInOpenHandler), ("/error_in_async_open", ErrorInAsyncOpenHandler), ], template_loader=DictLoader({"message.html": "<b>{{ message }}</b>"}), )
class WebSocketTest(WebSocketBaseTestCase): ), ("/error_in_open", ErrorInOpenHandler), ("/error_in_async_open", ErrorInAsyncOpenHandler), ("/nodelay", NoDelayHandler), ], template_loader=DictLoader({"message.html": "<b>{{ message }}...
class WebSocketTest(WebSocketBaseTestCase): res = yield ws.read_message() self.assertIsNone(res) class NativeCoroutineOnMessageHandler(TestWebSocketHandler): def initialize(self, **kwargs):
class WebSocketTest(WebSocketBaseTestCase): res = yield ws.read_message() self.assertIsNone(res) @gen_test def test_nodelay(self): ws = yield self.ws_connect("/nodelay") res = yield ws.read_message() self.assertEqual(res, "hello") class NativeCoroutineOnMessageHand...
class WebSocketHandler(tornado.web.RequestHandler): .. versionadded:: 3.1 """ assert self.stream is not None self.stream.set_nodelay(value) def on_connection_close(self) -> None: if self.ws_connection:
class WebSocketHandler(tornado.web.RequestHandler): .. versionadded:: 3.1 """ assert self.ws_connection is not None self.ws_connection.set_nodelay(value) def on_connection_close(self) -> None: if self.ws_connection:
class WebSocketProtocol(abc.ABC): async def _receive_frame_loop(self) -> None: raise NotImplementedError() class _PerMessageDeflateCompressor(object): def __init__(
class WebSocketProtocol(abc.ABC): async def _receive_frame_loop(self) -> None: raise NotImplementedError() @abc.abstractmethod def set_nodelay(self, x: bool) -> None: raise NotImplementedError() class _PerMessageDeflateCompressor(object): def __init__(
class WebSocketProtocol13(WebSocketProtocol): self.write_ping(b"") self.last_ping = now class WebSocketClientConnection(simple_httpclient._HTTPConnection): """WebSocket client connection.
class WebSocketProtocol13(WebSocketProtocol): self.write_ping(b"") self.last_ping = now def set_nodelay(self, x: bool) -> None: self.stream.set_nodelay(x) class WebSocketClientConnection(simple_httpclient._HTTPConnection): """WebSocket client connection.
class DatabaseOperations(BaseDatabaseOperations): return f"EXTRACT({lookup_type} FROM {sql})", params def date_trunc_sql(self, lookup_type, sql, params, tzname=None): sql, params = self._convert_field_to_tz(sql, params, tzname) fields = { "year": "%Y-01-01", "mon...
class DatabaseOperations(BaseDatabaseOperations): return f"EXTRACT({lookup_type} FROM {sql})", params def date_trunc_sql(self, lookup_type, sql, params, tzname=None): sql, params = self._convert_sql_to_tz(sql, params, tzname) fields = { "year": "%Y-01-01", "month...
class DatabaseOperations(BaseDatabaseOperations): tzname, sign, offset = split_tzname_delta(tzname) return f"{sign}{offset}" if offset else tzname def _convert_field_to_tz(self, sql, params, tzname): if tzname and settings.USE_TZ and self.connection.timezone_name != tzname: retu...
class DatabaseOperations(BaseDatabaseOperations): tzname, sign, offset = split_tzname_delta(tzname) return f"{sign}{offset}" if offset else tzname def _convert_sql_to_tz(self, sql, params, tzname): if tzname and settings.USE_TZ and self.connection.timezone_name != tzname: return...
class DatabaseOperations(BaseDatabaseOperations): return sql, params def datetime_cast_date_sql(self, sql, params, tzname): sql, params = self._convert_field_to_tz(sql, params, tzname) return f"DATE({sql})", params def datetime_cast_time_sql(self, sql, params, tzname): sql, par...
class DatabaseOperations(BaseDatabaseOperations): return sql, params def datetime_cast_date_sql(self, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) return f"DATE({sql})", params def datetime_cast_time_sql(self, sql, params, tzname): sql, param...
class DatabaseOperations(BaseDatabaseOperations): return sql, params def time_trunc_sql(self, lookup_type, sql, params, tzname=None): sql, params = self._convert_field_to_tz(sql, params, tzname) fields = { "hour": "%H:00:00", "minute": "%H:%i:00",
class DatabaseOperations(BaseDatabaseOperations): return sql, params def time_trunc_sql(self, lookup_type, sql, params, tzname=None): sql, params = self._convert_sql_to_tz(sql, params, tzname) fields = { "hour": "%H:00:00", "minute": "%H:%i:00",
END; return extract_sql, (*params, extract_param) def date_trunc_sql(self, lookup_type, sql, params, tzname=None): sql, params = self._convert_field_to_tz(sql, params, tzname) # https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/ROUND-and-TRUNC-Date-Functions.html t...
END; return extract_sql, (*params, extract_param) def date_trunc_sql(self, lookup_type, sql, params, tzname=None): sql, params = self._convert_sql_to_tz(sql, params, tzname) # https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/ROUND-and-TRUNC-Date-Functions.html tru...
END; tzname, sign, offset = split_tzname_delta(tzname) return f"{sign}{offset}" if offset else tzname def _convert_field_to_tz(self, sql, params, tzname): if not (settings.USE_TZ and tzname): return sql, params if not self._tzname_re.match(tzname):
END; tzname, sign, offset = split_tzname_delta(tzname) return f"{sign}{offset}" if offset else tzname def _convert_sql_to_tz(self, sql, params, tzname): if not (settings.USE_TZ and tzname): return sql, params if not self._tzname_re.match(tzname):
END; return sql, params def datetime_cast_date_sql(self, sql, params, tzname): sql, params = self._convert_field_to_tz(sql, params, tzname) return f"TRUNC({sql})", params def datetime_cast_time_sql(self, sql, params, tzname): # Since `TimeField` values are stored as TIMESTAMP c...
END; return sql, params def datetime_cast_date_sql(self, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) return f"TRUNC({sql})", params def datetime_cast_time_sql(self, sql, params, tzname): # Since `TimeField` values are stored as TIMESTAMP cha...
END; ) def datetime_extract_sql(self, lookup_type, sql, params, tzname): sql, params = self._convert_field_to_tz(sql, params, tzname) return self.date_extract_sql(lookup_type, sql, params) def datetime_trunc_sql(self, lookup_type, sql, params, tzname): sql, params = self._conve...
END; ) def datetime_extract_sql(self, lookup_type, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) return self.date_extract_sql(lookup_type, sql, params) def datetime_trunc_sql(self, lookup_type, sql, params, tzname): sql, params = self._convert...
END; # The implementation is similar to `datetime_trunc_sql` as both # `DateTimeField` and `TimeField` are stored as TIMESTAMP where # the date part of the later is ignored. sql, params = self._convert_field_to_tz(sql, params, tzname) trunc_param = None if lookup_type == ...
END; # The implementation is similar to `datetime_trunc_sql` as both # `DateTimeField` and `TimeField` are stored as TIMESTAMP where # the date part of the later is ignored. sql, params = self._convert_sql_to_tz(sql, params, tzname) trunc_param = None if lookup_type == "h...
class SSHClient(object): # Salt API should never offer a custom roster! self.opts["__disable_custom_roster"] = disable_custom_roster def _prep_ssh( self, tgt, fun, arg=(), timeout=None, tgt_type="glob", kwarg=None, **kwargs ): """ Prepare the arguments """ ...
class SSHClient(object): # Salt API should never offer a custom roster! self.opts["__disable_custom_roster"] = disable_custom_roster def sanitize_kwargs(self, kwargs): roster_vals = [ ("host", str), ("ssh_user", str), ("ssh_passwd", str), ("ss...
class NetapiSSHClientAuthTest(SSHCase): except AssertionError: self.mod_case.run_function("user.delete", [self.USERA], remove=True) self.skipTest("Could not add user or password, skipping test") def tearDown(self): del self.netapi self.mod_case.run_function("user.del...
class NetapiSSHClientAuthTest(SSHCase): except AssertionError: self.mod_case.run_function("user.delete", [self.USERA], remove=True) self.skipTest("Could not add user or password, skipping test") self.expfile = os.path.join(RUNTIME_VARS.TMP, "exploited") def tearDown(self): ...
class NetapiSSHClientAuthTest(SSHCase): ret = self.netapi.run(low) assert "localhost" in ret assert ret["localhost"]["return"] is True
class NetapiSSHClientAuthTest(SSHCase): ret = self.netapi.run(low) assert "localhost" in ret assert ret["localhost"]["return"] is True def test_ssh_cve_2021_3197_a(self): assert not os.path.exists(self.expfile) low = { "eauth": "auto", "username": sel...
class TestYoutubeChapters(unittest.TestCase): for description, duration, expected_chapters in self._TEST_CASES: ie = YoutubeIE() expect_value( self, ie._extract_chapters(description, duration), expected_chapters, None)
class TestYoutubeChapters(unittest.TestCase): for description, duration, expected_chapters in self._TEST_CASES: ie = YoutubeIE() expect_value( self, ie._extract_chapters_from_description(description, duration), expected_chapters, None)
class YoutubeIE(YoutubeBaseInfoExtractor): video_id = mobj.group(2) return video_id @staticmethod def _extract_chapters(description, duration): if not description: return None chapter_lines = re.findall(
class YoutubeIE(YoutubeBaseInfoExtractor): video_id = mobj.group(2) return video_id def _extract_chapters_from_json(self, webpage, video_id, duration): if not webpage: return player = self._parse_json( self._search_regex( r'RELATED_PLAYER_ARGS...
class YoutubeIE(YoutubeBaseInfoExtractor): }) return chapters def _real_extract(self, url): url, smuggled_data = unsmuggle_url(url, {})
class YoutubeIE(YoutubeBaseInfoExtractor): }) return chapters def _extract_chapters(self, webpage, description, video_id, duration): return (self._extract_chapters_from_json(webpage, video_id, duration) or self._extract_chapters_from_description(description, duration)) ...
class YoutubeIE(YoutubeBaseInfoExtractor): errnote='Unable to download video annotations', fatal=False, data=urlencode_postdata({xsrf_field_name: xsrf_token})) chapters = self._extract_chapters(description_original, video_duration) # Look for the DASH manifest ...
class YoutubeIE(YoutubeBaseInfoExtractor): errnote='Unable to download video annotations', fatal=False, data=urlencode_postdata({xsrf_field_name: xsrf_token})) chapters = self._extract_chapters(video_webpage, description_original, video_id, video_duration) # Loo...
def __init__(self, ValueError: if `input_signature` is not None and the `python_function`'s argspec has keyword arguments. """ self._lock = threading.Lock() self._python_function = python_function self._function_spec = function_lib.FunctionSpec.from_function_and_signature( python_f...
def __init__(self, ValueError: if `input_signature` is not None and the `python_function`'s argspec has keyword arguments. """ self._lock = threading.RLock() self._python_function = python_function self._function_spec = function_lib.FunctionSpec.from_function_and_signature( python_...
def __getstate__(self): def __setstate__(self, state): """Restore from pickled state.""" self.__dict__ = state self._lock = threading.Lock() self._descriptor_cache = weakref.WeakKeyDictionary() self._key_for_call_stats = self._get_key_for_call_stats()
def __getstate__(self): def __setstate__(self, state): """Restore from pickled state.""" self.__dict__ = state self._lock = threading.RLock() self._descriptor_cache = weakref.WeakKeyDictionary() self._key_for_call_stats = self._get_key_for_call_stats()
from six.moves import range from tensorflow.python.autograph.core import converter from tensorflow.python.eager import def_function from tensorflow.python.eager import lift_to_graph from tensorflow.python.framework import constant_op
from six.moves import range from tensorflow.python.autograph.core import converter from tensorflow.python.eager import backprop from tensorflow.python.eager import def_function from tensorflow.python.eager import lift_to_graph from tensorflow.python.framework import constant_op
from tensorflow.python.framework import test_util from tensorflow.python.module import module from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import random_ops
from tensorflow.python.framework import test_util from tensorflow.python.module import module from tensorflow.python.ops import array_ops from tensorflow.python.ops import cond_v2 from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import random_ops
def testDouble(self, a): self.assertAllEqual(obj2.testDouble.experimental_get_tracing_count(), 3) self.assertAllEqual(obj1.testDouble.experimental_get_tracing_count(), 2) if __name__ == '__main__': ops.enable_eager_execution()
def testDouble(self, a): self.assertAllEqual(obj2.testDouble.experimental_get_tracing_count(), 3) self.assertAllEqual(obj1.testDouble.experimental_get_tracing_count(), 2) def test_recursive_tf_function(self): @def_function.function def recursive_fn(n): if n > 0: return recursive_fn(n -...
def __init__(self, if self.input_signature is not None: self._hashable_input_signature = hash(self.flat_input_signature) self._lock = threading.Lock() # _descriptor_cache is a of instance of a class to an instance-specific # `Function`, used to make sure defun-decorated methods create different ...
def __init__(self, if self.input_signature is not None: self._hashable_input_signature = hash(self.flat_input_signature) self._lock = threading.RLock() # _descriptor_cache is a of instance of a class to an instance-specific # `Function`, used to make sure defun-decorated methods create different ...
class Tracer: self.target_codes = set() self.target_frames = set() self.thread_local = threading.local() self.custom_repr = custom_repr def __call__(self, function):
class Tracer: self.target_codes = set() self.target_frames = set() self.thread_local = threading.local() if len(custom_repr) == 2 and not all(isinstance(x, pycompat.collections_abc.Iterable) for x in custom_repr): custom_repr = (custom_repr,) sel...
def test_custom_repr(): ) ) def test_disable(): string_io = io.StringIO()
def test_custom_repr(): ) ) def test_custom_repr_single(): string_io = io.StringIO() @pysnooper.snoop(string_io, custom_repr=(list, lambda l: 'foofoo!')) def sum_to_x(x): l = list(range(x)) return 7 result = sum_to_x(10000) output = string_io.getvalue() assert_out...
def __str__(self): class Application: SOCKTYPES = { "tcp": socket.SOCK_STREAM, "udp": socket.SOCK_DGRAM,
def __str__(self): class Application: MAX_LENGTH = 128 * 1024 SOCKTYPES = { "tcp": socket.SOCK_STREAM, "udp": socket.SOCK_DGRAM,
def __call__(self, env, start_response): try: length = int(env["CONTENT_LENGTH"]) except AttributeError: length = -1 try: pr = codec.decode(env["wsgi.input"].read(length)) except codec.ParsingError as e:
def __call__(self, env, start_response): try: length = int(env["CONTENT_LENGTH"]) except AttributeError: raise HTTPException(411, "Length required.") if length < 0: raise HTTPException(411, "Length required.") if length > se...
from youtube_dl.utils import ( unified_strdate, unsmuggle_url, url_basename, xpath_with_ns, )
from youtube_dl.utils import ( unified_strdate, unsmuggle_url, url_basename, urlencode_postdata, xpath_with_ns, )
class TestUtil(unittest.TestCase): bam''') self.assertEqual(read_batch_urls(f), [u'foo', u'bar', u'baz', u'bam']) if __name__ == '__main__': unittest.main()
class TestUtil(unittest.TestCase): bam''') self.assertEqual(read_batch_urls(f), [u'foo', u'bar', u'baz', u'bam']) def test_urlencode_postdata(self): data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'}) self.assertTrue(isinstance(data, bytes)) if __name__ =...
from ..utils import ( compat_urllib_error, compat_urllib_parse, compat_urllib_request, ExtractorError, )
from ..utils import ( compat_urllib_error, compat_urllib_parse, compat_urllib_request, urlencode_postdata, ExtractorError, )
class FacebookIE(InfoExtractor): login_page_req = compat_urllib_request.Request(self._LOGIN_URL) login_page_req.add_header('Cookie', 'locale=en_US') self.report_login() login_page = self._download_webpage(login_page_req, None, note=False, errnote='Unable to download login pa...
class FacebookIE(InfoExtractor): login_page_req = compat_urllib_request.Request(self._LOGIN_URL) login_page_req.add_header('Cookie', 'locale=en_US') login_page = self._download_webpage(login_page_req, None, note='Downloading login page', errnote='Unable to download login...
class FacebookIE(InfoExtractor): 'timezone': '-60', 'trynum': '1', } request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(login_form)) request.add_header('Content-Type', 'application/x-www-form-urlencoded') try: lo...
class FacebookIE(InfoExtractor): 'timezone': '-60', 'trynum': '1', } request = compat_urllib_request.Request(self._LOGIN_URL, urlencode_postdata(login_form)) request.add_header('Content-Type', 'application/x-www-form-urlencoded') try: login_results...
def read_batch_urls(batch_fd): with contextlib.closing(batch_fd) as fd: return [url for url in map(fixup, fd) if url]
def read_batch_urls(batch_fd): with contextlib.closing(batch_fd) as fd: return [url for url in map(fixup, fd) if url] def urlencode_postdata(*args, **kargs): return compat_urllib_parse.urlencode(*args, **kargs).encode('ascii')
def test_urlsplit_normalization(self): urllib.parse.urlsplit('http://\u30d5\u309a\ufe1380') for scheme in ["http", "https", "ftp"]: for c in denorm_chars: url = "{}://netloc{}false.netloc/path".format(scheme, c) with self.subTest(url=url, char='{:04X}'.fo...
def test_urlsplit_normalization(self): urllib.parse.urlsplit('http://\u30d5\u309a\ufe1380') for scheme in ["http", "https", "ftp"]: for netloc in ["netloc{}false.netloc", "n{}user@netloc"]: for c in denorm_chars: url = "{}://{}/path".format(scheme, ne...
def _checknetloc(netloc): # looking for characters like \u2100 that expand to 'a/c' # IDNA uses NFKC equivalence, so normalize for this check import unicodedata n = netloc.rpartition('@')[2] # ignore anything to the left of '@' n = n.replace(':', '') # ignore characters already included n...
def _checknetloc(netloc): # looking for characters like \u2100 that expand to 'a/c' # IDNA uses NFKC equivalence, so normalize for this check import unicodedata n = netloc.replace('@', '') # ignore characters already included n = n.replace(':', '') # but not the surrounding text n = n.r...
def parse_yaml_query(yaml_content): On success, the processed MLQuery object. """ logger.debug("Attempting to parse YAML content:\n%s" % yaml_content) return parse_query(yaml.load(yaml_content)) def parse_json_query(json_content):
def parse_yaml_query(yaml_content): On success, the processed MLQuery object. """ logger.debug("Attempting to parse YAML content:\n%s" % yaml_content) return parse_query(yaml.safe_load(yaml_content)) def parse_json_query(json_content):
class Worker(object): Structure for tracking worker activity and keeping their references. """ def __init__(self, worker_id, last_active=None): self.id = worker_id self.reference = None # reference to the worker in the real world. (Currently a dict containing just the host) self.la...
class Worker(object): Structure for tracking worker activity and keeping their references. """ def __init__(self, worker_id, last_active=time.time()): self.id = worker_id self.reference = None # reference to the worker in the real world. (Currently a dict containing just the host) ...
class SchedulerTest(unittest.TestCase): cps = reload_from_disk(cps=cps) # This time without deleting self.assertEqual(cps.get_work(worker='D')['task_id'], '4') if __name__ == '__main__': unittest.main()
class SchedulerTest(unittest.TestCase): cps = reload_from_disk(cps=cps) # This time without deleting self.assertEqual(cps.get_work(worker='D')['task_id'], '4') def test_worker_prune_after_init(self): worker = luigi.scheduler.Worker(123) class TmpCfg: def __init...
class Spider(object_ref): crawler.signals.connect(self.close, signals.spider_closed) def start_requests(self): if self.make_requests_from_url is not Spider.make_requests_from_url: warnings.warn( "Spider.make_requests_from_url method is deprecated; " "it w...
class Spider(object_ref): crawler.signals.connect(self.close, signals.spider_closed) def start_requests(self): cls = self.__class__ if cls.make_requests_from_url is not Spider.make_requests_from_url: warnings.warn( "Spider.make_requests_from_url method is depreca...
Sitemap: /sitemap-relative-url.xml 'http://www.example.com/sitemap-relative-url.xml']) class BaseSpiderDeprecationTest(unittest.TestCase): def test_basespider_is_deprecated(self): with warnings.catch_warnings(record=True) as w:
Sitemap: /sitemap-relative-url.xml 'http://www.example.com/sitemap-relative-url.xml']) class DeprecationTest(unittest.TestCase): def test_basespider_is_deprecated(self): with warnings.catch_warnings(record=True) as w:
class BaseSpiderDeprecationTest(unittest.TestCase): assert isinstance(CrawlSpider(name='foo'), Spider) assert isinstance(CrawlSpider(name='foo'), BaseSpider) if __name__ == '__main__': unittest.main()
class BaseSpiderDeprecationTest(unittest.TestCase): assert isinstance(CrawlSpider(name='foo'), Spider) assert isinstance(CrawlSpider(name='foo'), BaseSpider) def test_make_requests_from_url_deprecated(self): class MySpider4(Spider): name = 'spider1' start_urls = ['ht...
pjoin = os.path.join # Constants #----------------------------------------------------------------------------- bundled_version = (4, 3, 1) vs = '%i.%i.%i' % bundled_version libzmq = "zeromq-%s.tar.gz" % vs libzmq_url = "https://github.com/zeromq/libzmq/releases/download/v{vs}/{libzmq}".format( vs=vs, libzmq=l...
pjoin = os.path.join # Constants #----------------------------------------------------------------------------- bundled_version = (4, 3, 2) vs = '%i.%i.%i' % bundled_version libzmq = "zeromq-%s.tar.gz" % vs libzmq_url = "https://github.com/zeromq/libzmq/releases/download/v{vs}/{libzmq}".format( vs=vs, libzmq=l...
class DataFrame(NDFrame): ) return result def transpose(self, *args, **kwargs): """ Transpose index and columns.
class DataFrame(NDFrame): ) return result def transpose(self, *args, copy: bool = False): """ Transpose index and columns.
class DataFrame(NDFrame): Parameters ---------- *args, **kwargs Additional arguments and keywords have no effect but might be accepted for compatibility with numpy. Returns -------
class DataFrame(NDFrame): Parameters ---------- *args : tuple, optional Accepted for compatibility with NumPy. copy : bool, default False Whether to copy the data after transposing, even for DataFrames with a single dtype. Note that a cop...
class DataFrame(NDFrame): dtype: object """ nv.validate_transpose(args, dict()) return super().transpose(1, 0, **kwargs) T = property(transpose)
class DataFrame(NDFrame): dtype: object """ nv.validate_transpose(args, dict()) # construct the args dtypes = list(self.dtypes) if self._is_homogeneous_type and dtypes and is_extension_array_dtype(dtypes[0]): # We have EAs with the same dtype. We can preserve...
class NDFrame(PandasObject, SelectionMixin): self._data.set_axis(axis, labels) self._clear_item_cache() def transpose(self, *args, **kwargs): """ Permute the dimensions of the %(klass)s Parameters ---------- args : %(args_transpose)s copy : bool, def...
class NDFrame(PandasObject, SelectionMixin): self._data.set_axis(axis, labels) self._clear_item_cache() def swapaxes(self, axis1, axis2, copy=True): """ Interchange axes and swap values axes appropriately.
def box_df_fail(request): return request.param @pytest.fixture( params=[ (pd.Index, False), (pd.Series, False), (pd.DataFrame, False), pytest.param((pd.DataFrame, True), marks=pytest.mark.xfail), (tm.to_array, False), ], ids=id_func, ) def box_transpose_fail(req...
def box_df_fail(request): return request.param @pytest.fixture(params=[pd.Index, pd.Series, pd.DataFrame, tm.to_array], ids=id_func) def box_with_array(request): """
class TestPeriodIndexArithmetic: rng -= pd.offsets.MonthEnd(5) tm.assert_index_equal(rng, expected) def test_pi_add_offset_n_gt1(self, box_transpose_fail): # GH#23215 # add offset to PeriodIndex with freq.n > 1 box, transpose = box_transpose_fail per = pd.Period("20...
class TestPeriodIndexArithmetic: rng -= pd.offsets.MonthEnd(5) tm.assert_index_equal(rng, expected) @pytest.mark.parametrize("transpose", [True, False]) def test_pi_add_offset_n_gt1(self, box_with_array, transpose): # GH#23215 # add offset to PeriodIndex with freq.n > 1 ...
class TestPeriodIndexArithmetic: with pytest.raises(IncompatibleFrequency, match=msg): rng -= other def test_parr_add_sub_td64_nat(self, box_transpose_fail): # GH#23320 special handling for timedelta64("NaT") box, transpose = box_transpose_fail pi = pd.period_range("199...
class TestPeriodIndexArithmetic: with pytest.raises(IncompatibleFrequency, match=msg): rng -= other @pytest.mark.parametrize("transpose", [True, False]) def test_parr_add_sub_td64_nat(self, box_with_array, transpose): # GH#23320 special handling for timedelta64("NaT") pi = p...
class TestPeriodIndexArithmetic: TimedeltaArray._from_sequence(["NaT"] * 9), ], ) def test_parr_add_sub_tdt64_nat_array(self, box_df_fail, other): # FIXME: DataFrame fails because when when operating column-wise # timedelta64 entries become NaT and are treated like datetimes...
class TestPeriodIndexArithmetic: TimedeltaArray._from_sequence(["NaT"] * 9), ], ) def test_parr_add_sub_tdt64_nat_array(self, box_with_array, other): pi = pd.period_range("1994-04-01", periods=9, freq="19D") expected = pd.PeriodIndex(["NaT"] * 9, freq="19D") obj = tm...
class BaseReshapingTests(BaseExtensionTests): # Check that we have a view, not a copy result[0] = result[1] assert data[0] == data[1]
class BaseReshapingTests(BaseExtensionTests): # Check that we have a view, not a copy result[0] = result[1] assert data[0] == data[1] def test_transpose(self, data): df = pd.DataFrame({"A": data[:4], "B": data[:4]}, index=["a", "b", "c", "d"]) result = df.T expected ...
class TestReshaping(BaseJSON, base.BaseReshapingTests): # this matches otherwise return super().test_unstack(data, index) class TestGetitem(BaseJSON, base.BaseGetitemTests): pass
class TestReshaping(BaseJSON, base.BaseReshapingTests): # this matches otherwise return super().test_unstack(data, index) @pytest.mark.xfail(reason="Inconsistent sizes.") def test_transpose(self, data): super().test_transpose(data) class TestGetitem(BaseJSON, base.BaseGetitemTests): ...
class TestReshaping(BaseNumPyTests, base.BaseReshapingTests): # Fails creating expected super().test_merge_on_extension_array_duplicates(data) class TestSetitem(BaseNumPyTests, base.BaseSetitemTests): @skip_nested
class TestReshaping(BaseNumPyTests, base.BaseReshapingTests): # Fails creating expected super().test_merge_on_extension_array_duplicates(data) @skip_nested def test_transpose(self, data): super().test_transpose(data) class TestSetitem(BaseNumPyTests, base.BaseSetitemTests): @skip_...
def top_k_categorical_accuracy(y_true, y_pred, k=5): def sparse_top_k_categorical_accuracy(y_true, y_pred, k=5): return K.mean(K.in_top_k(y_pred, K.cast(K.max(y_true, axis=-1), 'int32'), k), axis=-1)
def top_k_categorical_accuracy(y_true, y_pred, k=5): def sparse_top_k_categorical_accuracy(y_true, y_pred, k=5): # If the shape of y_true is (num_samples, 1), flatten to (num_samples,) return K.mean(K.in_top_k(y_pred, K.cast(K.flatten(y_true), 'int32'), k), axis=-1)
def test_top_k_categorical_accuracy(): @pytest.mark.skipif((K.backend() == 'cntk'), reason='CNTK backend does not support top_k yet') def test_sparse_top_k_categorical_accuracy(): y_pred = K.variable(np.array([[0.3, 0.2, 0.1], [0.1, 0.2, 0.7]])) y_true = K.variable(np.array([[1], [0]])) ...
def test_top_k_categorical_accuracy(): @pytest.mark.skipif((K.backend() == 'cntk'), reason='CNTK backend does not support top_k yet') @pytest.mark.parametrize('y_pred, y_true', [ # Test correctness if the shape of y_true is (num_samples, 1) (np.array([[0.3, 0.2, 0.1], [0.1, 0.2, 0.7]]), np....
def main(): 'error message') parser.add_argument('--log-file', default='/tmp/{prog_name}.log'.format( prog_name=prog_name), help='log file pathname')
def main(): 'error message') parser.add_argument('--log-file', default='{prog_name}.log'.format( prog_name=prog_name), help='log file pathname')
def authenticate(self, context, auth=None): if not user_ref.get('enabled', True): LOG.warning('User %s is disabled' % user_id) raise exception.Unauthorized() except AssertionError as e: raise exception.Unauthorized(e.message)
def authenticate(self, context, auth=None): if not user_ref.get('enabled', True): LOG.warning('User %s is disabled' % user_id) raise exception.Unauthorized() # If the tenant is disabled don't allow them to authenticate if tenant_re...
def authenticate(self, context, auth=None): tenant_ref = self.identity_api.get_tenant(context=context, tenant_id=tenant_id) if tenant_ref: metadata_ref = self.identity_api.get_metadata( context=context...
def authenticate(self, context, auth=None): tenant_ref = self.identity_api.get_tenant(context=context, tenant_id=tenant_id) # If the tenant is disabled don't allow them to authenticate if tenant_ref and not tenant_ref.get('enabl...
def test_authenticate_no_username(self): self.get_client, user_ref) # FIXME(ja): this test should require the "keystone:admin" roled # (probably the role set via --keystone_admin_role flag) # FIXME(ja): add a test that admin endpoint is only se...
def test_authenticate_no_username(self): self.get_client, user_ref) def test_authenticate_disabled_tenant(self): from keystoneclient import exceptions as client_exceptions admin_client = self.get_client(admin=True) tenant = { ...
from pandas.core.algorithms import ( ) from pandas.core.base import NoNewAttributesMixin, PandasObject, _shared_docs import pandas.core.common as com from pandas.core.construction import extract_array, sanitize_array from pandas.core.missing import interpolate_2d from pandas.core.sorting import nargsort
from pandas.core.algorithms import ( ) from pandas.core.base import NoNewAttributesMixin, PandasObject, _shared_docs import pandas.core.common as com from pandas.core.construction import array, extract_array, sanitize_array from pandas.core.missing import interpolate_2d from pandas.core.sorting import nargsort
class Categorical(ExtensionArray, PandasObject): if dtype == self.dtype: return self return self._set_dtype(dtype) if is_integer_dtype(dtype) and self.isna().any(): msg = "Cannot convert float NaN to integer" raise ValueError(msg)
class Categorical(ExtensionArray, PandasObject): if dtype == self.dtype: return self return self._set_dtype(dtype) if is_extension_array_dtype(dtype): return array(self, dtype=dtype, copy=copy) # type: ignore # GH 28770 if is_integer_dtype(dtype) and ...
class TestCasting(base.BaseCastingTests): with pytest.raises((ValueError, TypeError), match=msg): s.astype(int) class TestArithmeticOps(base.BaseArithmeticOpsTests): def test_arith_series_with_scalar(self, data, all_arithmetic_operators):
class TestCasting(base.BaseCastingTests): with pytest.raises((ValueError, TypeError), match=msg): s.astype(int) @pytest.mark.parametrize( "expected", [ pd.Series(["2019", "2020"], dtype="datetime64[ns, UTC]"), pd.Series([0, 0], dtype="timedelta64[ns]"), ...
def test_merge_equal_cat_dtypes2(): tm.assert_frame_equal(result, expected, check_categorical=False) def test_merge_multiindex_columns(): # Issue #28518 # Verify that merging two dataframes give the expected labels
def test_merge_equal_cat_dtypes2(): tm.assert_frame_equal(result, expected, check_categorical=False) def test_merge_on_cat_and_ext_array(): # GH 28668 right = DataFrame( {"a": Series([pd.Interval(0, 1), pd.Interval(1, 2)], dtype="interval")} ) left = right.copy() left["a"] = left["a"]....
'transparent': (0, 0, 0, 0), } RGBA = re.compile(r'rgba\([ \n\r\t]*(.+?)[ \n\r\t]*\)') RGB = re.compile(r'rgb\([ \n\r\t]*(.+?)[ \n\r\t]*\)') HEX_RRGGBB = re.compile('#[0-9a-f]{6}') HEX_RGB = re.compile('#[0-9a-f]{3}')
'transparent': (0, 0, 0, 0), } RGBA = re.compile(r'rgba\((.+?)\)') RGB = re.compile(r'rgb\((.+?)\)') HEX_RRGGBB = re.compile('#[0-9a-f]{6}') HEX_RGB = re.compile('#[0-9a-f]{3}')
def color(string, opacity=1): if match: r, g, b, a = tuple( float(i.strip(' %')) / 100 if '%' in i else float(i) / 255 for i in match.group(1).split(',')) return (r, g, b, a * 255 * opacity) match = RGB.search(string) if match: r, g, b = tuple( fl...
def color(string, opacity=1): if match: r, g, b, a = tuple( float(i.strip(' %')) / 100 if '%' in i else float(i) / 255 for i in match.group(1).strip().split(',')) return (r, g, b, a * 255 * opacity) match = RGB.search(string) if match: r, g, b = tuple( ...
HOST = test_support.HOST CERTFILE = None SVN_PYTHON_ORG_ROOT_CERT = None def handle_error(prefix): exc_format = ' '.join(traceback.format_exception(*sys.exc_info()))
HOST = test_support.HOST CERTFILE = None SVN_PYTHON_ORG_ROOT_CERT = None NULLBYTECERT = None def handle_error(prefix): exc_format = ' '.join(traceback.format_exception(*sys.exc_info()))
def test_parse_cert(self): ('DNS', 'projects.forum.nokia.com')) ) def test_DER_to_PEM(self): with open(SVN_PYTHON_ORG_ROOT_CERT, 'r') as f: pem = f.read()
def test_parse_cert(self): ('DNS', 'projects.forum.nokia.com')) ) def test_parse_cert_CVE_2013_4238(self): p = ssl._ssl._test_decode_cert(NULLBYTECERT) if test_support.verbose: sys.stdout.write("\n" + pprint.pformat(p) + "\n") su...
def test_default_ciphers(self): def test_main(verbose=False): global CERTFILE, SVN_PYTHON_ORG_ROOT_CERT, NOKIACERT CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir, "keycert.pem") SVN_PYTHON_ORG_ROOT_CERT = os.path.join(
def test_default_ciphers(self): def test_main(verbose=False): global CERTFILE, SVN_PYTHON_ORG_ROOT_CERT, NOKIACERT, NULLBYTECERT CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir, "keycert.pem") SVN_PYTHON_ORG_ROOT_CERT = os.path.join(