buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class WorkerExternalTaskTest(unittest.TestCase): worker_disconnect_delay=3, disable_persist=3, disable_window=5, disable_fai...
class WorkerExternalTaskTest(unittest.TestCase): worker_disconnect_delay=3, disable_persist=3, disable_window=5, disable_fai...
class WorkerExternalTaskTest(unittest.TestCase): 'retry-external-tasks', False) is True original_get_work = self.scheduler.get_work def decorated_get_work(*args, **kwargs): ...
class WorkerExternalTaskTest(unittest.TestCase): 'retry-external-tasks', False) is True tempdir = tempfile.mkdtemp(prefix='luigi-test-') with patch('random.randint', return_value=0.1):
def getallmatchingheaders(self, name): lst.append(line) return lst def parse_headers(fp, _class=HTTPMessage): """Parses only RFC2822 headers from a file pointer. email Parser wants to see strings rather than bytes. But a TextIOWrapper around self.rfile would buffer too many bytes ...
def getallmatchingheaders(self, name): lst.append(line) return lst def _read_headers(fp): """Reads potential header lines into a list from a file pointer. Length of line is limited by _MAXLINE, and number of headers is limited by _MAXHEADERS. """ headers = [] while True...
def parse_headers(fp, _class=HTTPMessage): raise HTTPException("got more than %d headers" % _MAXHEADERS) if line in (b'\r\n', b'\n', b''): break hstring = b''.join(headers).decode('iso-8859-1') return email.parser.Parser(_class=_class).parsestr(hstring)
def parse_headers(fp, _class=HTTPMessage): raise HTTPException("got more than %d headers" % _MAXHEADERS) if line in (b'\r\n', b'\n', b''): break return headers def parse_headers(fp, _class=HTTPMessage): """Parses only RFC2822 headers from a file pointer. email Parser wants ...
def begin(self): if status != CONTINUE: break # skip the header from the 100 response while True: skip = self.fp.readline(_MAXLINE + 1) if len(skip) > _MAXLINE: raise LineTooLong("header line") skip =...
def begin(self): if status != CONTINUE: break # skip the header from the 100 response skipped_headers = _read_headers(self.fp) if self.debuglevel > 0: print("headers:", skipped_headers) del skipped_headers self.code = s...
def test_overflowing_header_line(self): resp = client.HTTPResponse(FakeSocket(body)) self.assertRaises(client.LineTooLong, resp.begin) def test_overflowing_chunked_line(self): body = ( 'HTTP/1.1 200 OK\r\n'
def test_overflowing_header_line(self): resp = client.HTTPResponse(FakeSocket(body)) self.assertRaises(client.LineTooLong, resp.begin) def test_overflowing_header_limit_after_100(self): body = ( 'HTTP/1.1 100 OK\r\n' 'r\n' * 32768 ) resp = client.HTTP...
def readline(self, limit): class OfflineTest(TestCase): def test_all(self): # Documented objects defined in the module should be in __all__ expected = {"responses"} # White-list documented dict() object # HTTPMessage, parse_headers(), and the HTTP status code constants are # intenti...
def readline(self, limit): class OfflineTest(TestCase): def test_all(self): # Documented objects defined in the module should be in __all__ expected = {"responses"} # Allowlist documented dict() object # HTTPMessage, parse_headers(), and the HTTP status code constants are # intentio...
class Index(IndexOpsMixin, PandasObject): "unicode", "mixed", ]: return self._invalid_indexer("label", key) elif kind in ["loc"] and is_integer(key): if not self.holds_integer(): return self._inv...
class Index(IndexOpsMixin, PandasObject): "unicode", "mixed", ]: self._invalid_indexer("label", key) elif kind in ["loc"] and is_integer(key): if not self.holds_integer(): self._invalid_indexer("...
class CategoricalIndex(Index, accessor.PandasDelegate): @Appender(_index_shared_docs["_convert_scalar_indexer"]) def _convert_scalar_indexer(self, key, kind=None): if self.categories._defer_to_indexing: return self.categories._convert_scalar_indexer(key, kind=kind) return super()._...
class CategoricalIndex(Index, accessor.PandasDelegate): @Appender(_index_shared_docs["_convert_scalar_indexer"]) def _convert_scalar_indexer(self, key, kind=None): if kind == "loc": try: return self.categories._convert_scalar_indexer(key, kind=kind) except TypeEr...
from pandas import ( Index, Interval, Series, Timestamp, ) from pandas.api.types import CategoricalDtype as CDT import pandas.util.testing as tm
from pandas import ( Index, Interval, Series, Timedelta, Timestamp, conftest, ) from pandas.api.types import CategoricalDtype as CDT import pandas.util.testing as tm
class TestCategoricalIndex: with pytest.raises(TypeError, match=msg): df.loc["d", "C"] = 10 def test_getitem_scalar(self): cats = Categorical([Timestamp("12-31-1999"), Timestamp("12-31-2000")])
class TestCategoricalIndex: with pytest.raises(TypeError, match=msg): df.loc["d", "C"] = 10 msg = ( r"cannot do label indexing on <class 'pandas\.core\.indexes\.category" r"\.CategoricalIndex'> with these indexers \[1\] of <class 'int'>" ) with pytest...
class TestCategoricalIndex: output = cur_index.map(mapper) # Order of categories in output can be different tm.assert_index_equal(expected, output)
class TestCategoricalIndex: output = cur_index.map(mapper) # Order of categories in output can be different tm.assert_index_equal(expected, output) @pytest.mark.parametrize( "idx_values", [ # python types [1, 2, 3], [-1, -2, -3], ...
class TestFloatIndexers: idxr(s)[3.0] # label based can be a TypeError or KeyError if s.index.inferred_type in ["string", "unicode", "mixed"]: error = KeyError msg = r"^3$" else:
class TestFloatIndexers: idxr(s)[3.0] # label based can be a TypeError or KeyError if s.index.inferred_type in { "categorical", "string", "unicode", "mixed", }: ...
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...
class WorkerProcess(multiprocessing_context.Process): self._variable_manager = variable_manager self._shared_loader_obj = shared_loader_obj def _save_stdin(self): self._new_stdin = os.devnull try:
class WorkerProcess(multiprocessing_context.Process): self._variable_manager = variable_manager self._shared_loader_obj = shared_loader_obj # NOTE: this works due to fork, if switching to threads this should change to per thread storage of temp files # clear var to ensure we only delete...
class WorkerProcess(multiprocessing_context.Process): except Exception: display.debug(u"WORKER EXCEPTION: %s" % to_text(e)) display.debug(u"WORKER TRACEBACK: %s" % to_text(traceback.format_exc())) display.debug("WORKER PROCESS EXITING")
class WorkerProcess(multiprocessing_context.Process): except Exception: display.debug(u"WORKER EXCEPTION: %s" % to_text(e)) display.debug(u"WORKER TRACEBACK: %s" % to_text(traceback.format_exc())) finally: self._clean_up() ...
class WorkerProcess(multiprocessing_context.Process): # ps.print_stats() # with open('worker_%06d.stats' % os.getpid(), 'w') as f: # f.write(s.getvalue())
class WorkerProcess(multiprocessing_context.Process): # ps.print_stats() # with open('worker_%06d.stats' % os.getpid(), 'w') as f: # f.write(s.getvalue()) def _clean_up(self): # NOTE: see note in init about forks # ensure we cleanup all temp files for this worker ...
class DataLoader: ''' def __init__(self): self._basedir = '.' self._FILE_CACHE = dict() self._tempfiles = set() # initialize the vault stuff with an empty password
class DataLoader: ''' def __init__(self): self._basedir = '.' # NOTE: not effective with forks as the main copy does not get updated. # avoids rereading files self._FILE_CACHE = dict() # NOTE: not thread safe, also issues with forks not returning data to main proc ...
class DataLoader: def _create_content_tempfile(self, content): ''' Create a tempfile containing defined content ''' fd, content_tempfile = tempfile.mkstemp() f = os.fdopen(fd, 'wb') content = to_bytes(content) try:
class DataLoader: def _create_content_tempfile(self, content): ''' Create a tempfile containing defined content ''' fd, content_tempfile = tempfile.mkstemp(dir=C.DEFAULT_LOCAL_TMP) f = os.fdopen(fd, 'wb') content = to_bytes(content) try:
class DataLoader: self._tempfiles.remove(file_path) def cleanup_all_tmp_files(self): for f in self._tempfiles: try: self.cleanup_tmp_file(f)
class DataLoader: self._tempfiles.remove(file_path) def cleanup_all_tmp_files(self): """ Removes all temporary files that DataLoader has created NOTE: not thread safe, forks also need special handling see __init__ for details. """ for f in self._tempfiles: ...
class VaultEditor: # Create a tempfile root, ext = os.path.splitext(os.path.realpath(filename)) fd, tmp_path = tempfile.mkstemp(suffix=ext) os.close(fd) cmd = self._editor_shell_command(tmp_path)
class VaultEditor: # Create a tempfile root, ext = os.path.splitext(os.path.realpath(filename)) fd, tmp_path = tempfile.mkstemp(suffix=ext, dir=C.DEFAULT_LOCAL_TMP) os.close(fd) cmd = self._editor_shell_command(tmp_path)
from youtube_dl.utils import ( DateRange, encodeFilename, find_xpath_attr, get_meta_content, orderedSet, parse_duration,
from youtube_dl.utils import ( DateRange, encodeFilename, find_xpath_attr, fix_xml_ampersands, get_meta_content, orderedSet, parse_duration,
class TestUtil(unittest.TestCase): self.assertEqual(parse_duration('9:12:43'), 33163) self.assertEqual(parse_duration('x:y'), None) if __name__ == '__main__': unittest.main()
class TestUtil(unittest.TestCase): self.assertEqual(parse_duration('9:12:43'), 33163) self.assertEqual(parse_duration('x:y'), None) def test_fix_xml_ampersands(self): self.assertEqual( fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a') self.assertEqual( fi...
import re from .common import InfoExtractor from ..utils import ( find_xpath_attr, fix_xml_all_ampersand, )
import re from .common import InfoExtractor from ..utils import ( find_xpath_attr, fix_xml_ampersands )
class ClipsyndicateIE(InfoExtractor): pdoc = self._download_xml( 'http://eplayer.clipsyndicate.com/osmf/playlist?%s' % flvars, video_id, u'Downloading video info', transform_source=fix_xml_all_ampersand) track_doc = pdoc.find('trackList/track') def find_para...
class ClipsyndicateIE(InfoExtractor): pdoc = self._download_xml( 'http://eplayer.clipsyndicate.com/osmf/playlist?%s' % flvars, video_id, u'Downloading video info', transform_source=fix_xml_ampersands) track_doc = pdoc.find('trackList/track') def find_param(na...
import re from .common import InfoExtractor from ..utils import ( fix_xml_all_ampersand, )
import re from .common import InfoExtractor from ..utils import ( fix_xml_ampersands, )
class MetacriticIE(InfoExtractor): webpage = self._download_webpage(url, video_id) # The xml is not well formatted, there are raw '&' info = self._download_xml('http://www.metacritic.com/video_data?video=' + video_id, video_id, 'Downloading info xml', transform_source=fix_xml_all_amp...
class MetacriticIE(InfoExtractor): webpage = self._download_webpage(url, video_id) # The xml is not well formatted, there are raw '&' info = self._download_xml('http://www.metacritic.com/video_data?video=' + video_id, video_id, 'Downloading info xml', transform_source=fix_xml_ampersa...
from .common import InfoExtractor from ..utils import ( compat_urllib_parse, ExtractorError, ) def _media_xml_tag(tag):
from .common import InfoExtractor from ..utils import ( compat_urllib_parse, ExtractorError, fix_xml_ampersands, ) def _media_xml_tag(tag):
class MTVServicesInfoExtractor(InfoExtractor): video_id = self._id_from_uri(uri) data = compat_urllib_parse.urlencode({'uri': uri}) def fix_ampersand(s): """ Fix unencoded ampersand in XML """ return s.replace(u'& ', '&amp; ') idoc = self._download_xml( ...
class MTVServicesInfoExtractor(InfoExtractor): video_id = self._id_from_uri(uri) data = compat_urllib_parse.urlencode({'uri': uri}) idoc = self._download_xml( self._FEED_URL + '?' + data, video_id, u'Downloading info', transform_source=fix_xml_ampersands) return ...
def month_by_name(name): return None def fix_xml_all_ampersand(xml_str): """Replace all the '&' by '&amp;' in XML""" return xml_str.replace(u'&', u'&amp;') def setproctitle(title):
def month_by_name(name): return None def fix_xml_ampersands(xml_str): """Replace all the '&' by '&amp;' in XML""" return re.sub( r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)', u'&amp;', xml_str) def setproctitle(title):
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)
class Call(Expr): def as_const(self, eval_ctx=None): eval_ctx = get_eval_context(self, eval_ctx) if eval_ctx.volatile: raise Impossible() obj = self.node.as_const(eval_ctx)
class Call(Expr): def as_const(self, eval_ctx=None): eval_ctx = get_eval_context(self, eval_ctx) if eval_ctx.volatile or eval_ctx.environment.sandboxed: raise Impossible() obj = self.node.as_const(eval_ctx)
""" import types import operator from jinja2.environment import Environment from jinja2.exceptions import SecurityError from jinja2._compat import string_types, PY2 #: maximum number of items a range may produce
""" import types import operator from collections import Mapping from jinja2.environment import Environment from jinja2.exceptions import SecurityError from jinja2._compat import string_types, text_type, PY2 from jinja2.utils import Markup has_format = False if hasattr(text_type, 'format'): from markupsafe import ...
#: unsafe generator attirbutes. UNSAFE_GENERATOR_ATTRIBUTES = set(['gi_frame', 'gi_code']) import warnings # make sure we don't warn in python 2.6 about stuff we don't care about
#: unsafe generator attirbutes. UNSAFE_GENERATOR_ATTRIBUTES = set(['gi_frame', 'gi_code']) #: unsafe attributes on coroutines UNSAFE_COROUTINE_ATTRIBUTES = set(['cr_frame', 'cr_code']) #: unsafe attributes on async generators UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = set(['ag_code', 'ag_frame']) import warnings # make su...
) def safe_range(*args): """A range that can't generate ranges with a length of more than MAX_RANGE items.
) class _MagicFormatMapping(Mapping): """This class implements a dummy wrapper to fix a bug in the Python standard library for string formatting. See http://bugs.python.org/issue13598 for information about why this is necessary. """ def __init__(self, args, kwargs): self._args = args...
def is_internal_attribute(obj, attr): elif isinstance(obj, types.GeneratorType): if attr in UNSAFE_GENERATOR_ATTRIBUTES: return True return attr.startswith('__')
def is_internal_attribute(obj, attr): elif isinstance(obj, types.GeneratorType): if attr in UNSAFE_GENERATOR_ATTRIBUTES: return True elif hasattr(types, 'CoroutineType') and isinstance(obj, types.CoroutineType): if attr in UNSAFE_COROUTINE_ATTRIBUTES: return True elif...
class SandboxedEnvironment(Environment): attributes or functions are safe to access. If the template tries to access insecure code a :exc:`SecurityError` is raised. However also other exceptions may occour during the rendering so the caller has to ensure that all exceptions are catched. """ sa...
class SandboxedEnvironment(Environment): attributes or functions are safe to access. If the template tries to access insecure code a :exc:`SecurityError` is raised. However also other exceptions may occur during the rendering so the caller has to ensure that all exceptions are caught. """ sand...
def unsafe_undefined(self, obj, attribute): obj.__class__.__name__ ), name=attribute, obj=obj, exc=SecurityError) def call(__self, __context, __obj, *args, **kwargs): """Call an object from sandboxed code.""" # the double prefixes are to avoid double keyword argument # e...
def unsafe_undefined(self, obj, attribute): obj.__class__.__name__ ), name=attribute, obj=obj, exc=SecurityError) def format_string(self, s, args, kwargs): """If a format call is detected, then this is routed through this method so that our safety sandbox can be used for it. ...
def is_safe_attribute(self, obj, attr, value): if not SandboxedEnvironment.is_safe_attribute(self, obj, attr, value): return False return not modifies_known_mutable(obj, attr)
def is_safe_attribute(self, obj, attr, value): if not SandboxedEnvironment.is_safe_attribute(self, obj, attr, value): return False return not modifies_known_mutable(obj, attr) if has_format: # This really is not a public API apparenlty. try: from _string import formatter_fi...
from jinja2 import Environment from jinja2.sandbox import SandboxedEnvironment, \ ImmutableSandboxedEnvironment, unsafe from jinja2 import Markup, escape from jinja2.exceptions import SecurityError, TemplateSyntaxError, \ TemplateRuntimeError
from jinja2 import Environment from jinja2.sandbox import SandboxedEnvironment, \ ImmutableSandboxedEnvironment, unsafe, has_format from jinja2 import Markup, escape from jinja2.exceptions import SecurityError, TemplateSyntaxError, \ TemplateRuntimeError
def disable_op(arg): pass else: assert False, 'expected runtime error'
def disable_op(arg): pass else: assert False, 'expected runtime error' @pytest.mark.sandbox @pytest.mark.skipif(not has_format, reason='No format support') class TestStringFormat(object): def test_basic_format_safety(self): env = SandboxedEnvironment() ...
def url_concat(url, args): >>> url_concat("http://example.com/foo?a=b", [("c", "d"), ("c", "d2")]) 'http://example.com/foo?a=b&c=d&c=d2' """ parsed_url = urlparse(url) if isinstance(args, dict): parsed_query = parse_qsl(parsed_url.query, keep_blank_values=True)
def url_concat(url, args): >>> url_concat("http://example.com/foo?a=b", [("c", "d"), ("c", "d2")]) 'http://example.com/foo?a=b&c=d&c=d2' """ if args is None: return url parsed_url = urlparse(url) if isinstance(args, dict): parsed_query = parse_qsl(parsed_url.query, keep_blank_val...
class TestUrlConcat(unittest.TestCase): ) self.assertEqual(url, "https://localhost/path?r=1&t=2") def test_url_concat_with_frag(self): url = url_concat( "https://localhost/path#tab",
class TestUrlConcat(unittest.TestCase): ) self.assertEqual(url, "https://localhost/path?r=1&t=2") def test_url_concat_none_params(self): url = url_concat( "https://localhost/path?r=1&t=2", None, ) self.assertEqual(url, "https://localhost/path?r=1&t=2"...
class XmlItemExporter(BaseItemExporter): elif is_listlike(serialized_value): for value in serialized_value: self._export_xml_field('value', value) else: self._xg_characters(serialized_value) self.xg.endElement(name) # Workaround for http://bugs.python...
class XmlItemExporter(BaseItemExporter): elif is_listlike(serialized_value): for value in serialized_value: self._export_xml_field('value', value) elif isinstance(serialized_value, six.text_type): self._xg_characters(serialized_value) else: sel...
class XmlItemExporterTest(BaseItemExporterTest): b'</items>' ) class JsonLinesItemExporterTest(BaseItemExporterTest):
class XmlItemExporterTest(BaseItemExporterTest): b'</items>' ) def test_nonstring_types_item(self): item = self._get_nonstring_types_item() self.assertExportResult(item, b'<?xml version="1.0" encoding="utf-8"?>\n' b'<items>' b'<item>' ...
from django.core.mail import EmailMultiAlternatives from django.template import loader from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from django.utils.text import capfirst from django.utils.translation import ugettext, ugettext_lazy as _ UserModel = get_user_model() ...
from django.core.mail import EmailMultiAlternatives from django.template import loader from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from django.utils.six import PY3 from django.utils.text import capfirst from django.utils.translation import ugettext, ugettext_lazy as...
class PasswordResetForm(forms.Form): that prevent inactive users and users with unusable passwords from resetting their password. """ active_users = UserModel._default_manager.filter(**{ '%s__iexact' % UserModel.get_email_field_name(): email, 'is_active': True, ...
class PasswordResetForm(forms.Form): that prevent inactive users and users with unusable passwords from resetting their password. """ email_field_name = UserModel.get_email_field_name() active_users = UserModel._default_manager.filter(**{ '%s__iexact' % email_field_na...
class PasswordResetForm(forms.Form): user. """ email = self.cleaned_data["email"] for user in self.get_users(email): if not domain_override: current_site = get_current_site(request)
class PasswordResetForm(forms.Form): user. """ email = self.cleaned_data["email"] email_field_name = UserModel.get_email_field_name() for user in self.get_users(email): if not domain_override: current_site = get_current_site(request)
class PasswordResetForm(forms.Form): domain = current_site.domain else: site_name = domain = domain_override context = { 'email': email, 'domain': domain, 'site_name': site_name, 'uid': urlsafe_base64...
class PasswordResetForm(forms.Form): domain = current_site.domain else: site_name = domain = domain_override user_email = getattr(user, email_field_name) context = { 'email': user_email, 'domain': domain, ...
class PasswordResetForm(forms.Form): context.update(extra_email_context) self.send_mail( subject_template_name, email_template_name, context, from_email, email, html_email_template_name=html_email_template_name, )
class PasswordResetForm(forms.Form): context.update(extra_email_context) self.send_mail( subject_template_name, email_template_name, context, from_email, user_email, html_email_template_name=html_email_template_name, )
class PasswordResetFormTest(TestDataMixin, TestCase): self.assertFalse(form.is_valid()) self.assertEqual(form['email'].errors, [_('Enter a valid email address.')]) def test_nonexistent_email(self): """ Test nonexistent email address. This should not fail because it would
class PasswordResetFormTest(TestDataMixin, TestCase): self.assertFalse(form.is_valid()) self.assertEqual(form['email'].errors, [_('Enter a valid email address.')]) def test_user_email_unicode_collision(self): User.objects.create_user('mike123', 'mike@example.org', 'test123') User.ob...
def str_repeat(arr, repeats): else: def rep(x, r): try: return bytes.__mul__(x, r) except TypeError:
def str_repeat(arr, repeats): else: def rep(x, r): if x is libmissing.NA: return x try: return bytes.__mul__(x, r) except TypeError:
class TestStringMethods: assert isinstance(rs, Series) tm.assert_series_equal(rs, xp) def test_match(self): # New match behavior introduced in 0.13 values = Series(["fooBAD__barBAD", np.nan, "foo"])
class TestStringMethods: assert isinstance(rs, Series) tm.assert_series_equal(rs, xp) def test_repeat_with_null(self): # GH: 31632 values = Series(["a", None], dtype="string") result = values.str.repeat([3, 4]) exp = Series(["aaa", None], dtype="string") tm.a...
class AnsibleModule(object): if k not in self.argument_spec: self.argument_spec[k] = v self._load_params() self._set_fallbacks()
class AnsibleModule(object): if k not in self.argument_spec: self.argument_spec[k] = v # Save parameter values that should never be logged self.no_log_values = set() self._load_params() self._set_fallbacks()
class AnsibleModule(object): print('\n{"failed": true, "msg": "Module alias error: %s"}' % to_native(e)) sys.exit(1) # Save parameter values that should never be logged self.no_log_values = set() self._handle_no_log_values() # check the locale as set by the curr...
class AnsibleModule(object): print('\n{"failed": true, "msg": "Module alias error: %s"}' % to_native(e)) sys.exit(1) self._handle_no_log_values() # check the locale as set by the current environment, and reset to
class AnsibleModule(object): param = self.params for (k, v) in spec.items(): default = v.get('default', None) if pre is True: # this prevents setting defaults on required items if default is not None and k not in param: para...
class AnsibleModule(object): param = self.params for (k, v) in spec.items(): default = v.get('default', None) # This prevents setting defaults on required items on the 1st run, # otherwise will set things without a default to None on the 2nd. if k not...
class AnsibleModule(object): else: fallback_args = item try: param[k] = fallback_strategy(*fallback_args, **fallback_kwargs) except AnsibleFallbackNotFound: continue def _load_params(self): '...
class AnsibleModule(object): else: fallback_args = item try: fallback_value = fallback_strategy(*fallback_args, **fallback_kwargs) except AnsibleFallbackNotFound: continue else: ...
Roger E. Masse """ from test.test_support import verbose, unlink import imageop, uu, os def main(use_rgbimg=1): # Create binary test files uu.decode(get_qualified_path('testrgb'+os.extsep+'uue'), 'test'+os.extsep+'rgb')
Roger E. Masse """ from test.test_support import verbose, unlink, run_unittest import imageop, uu, os, unittest SIZES = (1, 2, 3, 4) _VALUES = (1, 2, 2**10, 2**15-1, 2**15, 2**15+1, 2**31-2, 2**31-1) VALUES = tuple( -x for x in reversed(_VALUES) ) + (0,) + _VALUES AAAAA = "A" * 1024 class InputValidationTests(u...
def get_qualified_path(name): if os.path.exists(fullname): return fullname return name # rgbimg (unlike imgfile) is portable to platforms other than SGI. # So we prefer to use it. main(use_rgbimg=1)
def get_qualified_path(name): if os.path.exists(fullname): return fullname return name
from threading import local from django.conf import settings from django.core import signals from django.core.cache.backends.base import ( BaseCache, CacheKeyWarning, InvalidCacheBackendError, ) from django.utils.module_loading import import_string __all__ = [ 'cache', 'caches', 'DEFAULT_CACHE_ALIAS', 'Invalid...
from threading import local from django.conf import settings from django.core import signals from django.core.cache.backends.base import ( BaseCache, CacheKeyWarning, InvalidCacheBackendError, InvalidCacheKey, ) from django.utils.module_loading import import_string __all__ = [ 'cache', 'caches', 'DEFAULT_CACHE...
class CacheKeyWarning(RuntimeWarning): pass # Stub class to ensure not passing in a `timeout` argument results in # the default timeout DEFAULT_TIMEOUT = object()
class CacheKeyWarning(RuntimeWarning): pass class InvalidCacheKey(ValueError): pass # Stub class to ensure not passing in a `timeout` argument results in # the default timeout DEFAULT_TIMEOUT = object()
class BaseCache: backend. This encourages (but does not force) writing backend-portable cache code. """ if len(key) > MEMCACHE_MAX_KEY_LENGTH: warnings.warn( 'Cache key will cause errors if used with memcached: %r ' '(longer than %s)' % (key, M...
class BaseCache: backend. This encourages (but does not force) writing backend-portable cache code. """ for warning in memcache_key_warnings(key): warnings.warn(warning, CacheKeyWarning) def incr_version(self, key, delta=1, version=None): """
class BaseCache: def close(self, **kwargs): """Close the cache connection""" pass
class BaseCache: def close(self, **kwargs): """Close the cache connection""" pass def memcache_key_warnings(key): if len(key) > MEMCACHE_MAX_KEY_LENGTH: yield ( 'Cache key will cause errors if used with memcached: %r ' '(longer than %s)' % (key, MEMCACHE_MAX_KEY...
import pickle import re import time from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache from django.utils.functional import cached_property
import pickle import re import time from django.core.cache.backends.base import ( DEFAULT_TIMEOUT, BaseCache, InvalidCacheKey, memcache_key_warnings, ) from django.utils.functional import cached_property
class BaseMemcachedCache(BaseCache): def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_key(key, version=version) return self._cache.add(key, value, self.get_backend_timeout(timeout)) def get(self, key, default=None, version=None): key = self.make_key(key...
class BaseMemcachedCache(BaseCache): def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_key(key, version=version) self.validate_key(key) return self._cache.add(key, value, self.get_backend_timeout(timeout)) def get(self, key, default=None, version=None): ...
class BaseMemcachedCache(BaseCache): def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_key(key, version=version) if not self._cache.set(key, value, self.get_backend_timeout(timeout)): # make sure the key doesn't keep its old value in case of failure to se...
class BaseMemcachedCache(BaseCache): def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_key(key, version=version) self.validate_key(key) if not self._cache.set(key, value, self.get_backend_timeout(timeout)): # make sure the key doesn't keep its old...
class BaseMemcachedCache(BaseCache): def incr(self, key, delta=1, version=None): key = self.make_key(key, version=version) # memcached doesn't support a negative delta if delta < 0: return self._cache.decr(key, -delta)
class BaseMemcachedCache(BaseCache): def incr(self, key, delta=1, version=None): key = self.make_key(key, version=version) self.validate_key(key) # memcached doesn't support a negative delta if delta < 0: return self._cache.decr(key, -delta)
class BaseMemcachedCache(BaseCache): def decr(self, key, delta=1, version=None): key = self.make_key(key, version=version) # memcached doesn't support a negative delta if delta < 0: return self._cache.incr(key, -delta)
class BaseMemcachedCache(BaseCache): def decr(self, key, delta=1, version=None): key = self.make_key(key, version=version) self.validate_key(key) # memcached doesn't support a negative delta if delta < 0: return self._cache.incr(key, -delta)
class BaseMemcachedCache(BaseCache): original_keys = {} for key, value in data.items(): safe_key = self.make_key(key, version=version) safe_data[safe_key] = value original_keys[safe_key] = key failed_keys = self._cache.set_multi(safe_data, self.get_backend_tim...
class BaseMemcachedCache(BaseCache): original_keys = {} for key, value in data.items(): safe_key = self.make_key(key, version=version) self.validate_key(safe_key) safe_data[safe_key] = value original_keys[safe_key] = key failed_keys = self._cache.s...
class BaseMemcachedCache(BaseCache): def clear(self): self._cache.flush_all() class MemcachedCache(BaseMemcachedCache): "An implementation of a cache binding using python-memcached"
class BaseMemcachedCache(BaseCache): def clear(self): self._cache.flush_all() def validate_key(self, key): for warning in memcache_key_warnings(key): raise InvalidCacheKey(warning) class MemcachedCache(BaseMemcachedCache): "An implementation of a cache binding using python-mem...
from unittest import mock from django.conf import settings from django.core import management, signals from django.core.cache import ( DEFAULT_CACHE_ALIAS, CacheKeyWarning, cache, caches, ) from django.core.cache.utils import make_template_fragment_key from django.db import close_old_connections, connection, connec...
from unittest import mock from django.conf import settings from django.core import management, signals from django.core.cache import ( DEFAULT_CACHE_ALIAS, CacheKeyWarning, InvalidCacheKey, cache, caches, ) from django.core.cache.utils import make_template_fragment_key from django.db import close_old_connections, c...
class BaseCacheTests: def _perform_invalid_key_test(self, key, expected_warning): """ All the builtin backends (except memcached, see below) should warn on keys that would be refused by memcached. This encourages portable caching code without making it too difficult to use productio...
class BaseCacheTests: def _perform_invalid_key_test(self, key, expected_warning): """ All the builtin backends should warn (except memcached that should error) on keys that would be refused by memcached. This encourages portable caching code without making it too difficult to use pr...
class BaseMemcachedTests(BaseCacheTests): with self.settings(CACHES={'default': params}): self.assertEqual(cache._servers, ['server1.tld', 'server2:11211']) def test_invalid_key_characters(self): """ On memcached, we don't introduce a duplicate key validation ...
class BaseMemcachedTests(BaseCacheTests): with self.settings(CACHES={'default': params}): self.assertEqual(cache._servers, ['server1.tld', 'server2:11211']) def _perform_invalid_key_test(self, key, expected_warning): """ Whilst other backends merely warn, memcach...
class PyLibMCCacheTests(BaseMemcachedTests, TestCase): # libmemcached manages its own connections. should_disconnect_on_close = False # By default, pylibmc/libmemcached don't verify keys client-side and so # this test triggers a server-side bug that causes later tests to fail # (#19914). The `verif...
class PyLibMCCacheTests(BaseMemcachedTests, TestCase): # libmemcached manages its own connections. should_disconnect_on_close = False @override_settings(CACHES=caches_setting_for_tests( base=PyLibMCCache_params, exclude=memcached_excluded_caches,
class PKey(object): :raises: ``IOError`` -- if there was an error writing the file. """ with open(filename, "w") as f: os.chmod(filename, o600) self._write_private_key(f, key, format, password=password)
class PKey(object): :raises: ``IOError`` -- if there was an error writing the file. """ # Ensure that we create new key files directly with a user-only mode, # instead of opening, writing, then chmodding, which leaves us open to # CVE-2022-24302. # NOTE: O_TRUNC is a noo...
Some unit tests for public/private key objects. import unittest import os from binascii import hexlify from hashlib import md5
Some unit tests for public/private key objects. import unittest import os import stat from binascii import hexlify from hashlib import md5
from paramiko import ( SSHException, ) from paramiko.py3compat import StringIO, byte_chr, b, bytes, PY2 from cryptography.exceptions import UnsupportedAlgorithm from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateNumbers from mock import patch import pytest from .util import _support, is_low_entro...
from paramiko import ( SSHException, ) from paramiko.py3compat import StringIO, byte_chr, b, bytes, PY2 from paramiko.common import o600 from cryptography.exceptions import UnsupportedAlgorithm from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateNumbers from mock import patch, Mock import pytest f...
class KeyTest(unittest.TestCase): key1.load_certificate, _support("test_rsa.key-cert.pub"), )
class KeyTest(unittest.TestCase): key1.load_certificate, _support("test_rsa.key-cert.pub"), ) @patch("paramiko.pkey.os") def _test_keyfile_race(self, os_, exists): # Re: CVE-2022-24302 password = "television" newpassword = "radio" source = _suppor...
def capfirst(x): # Set up regular expressions re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.S) re_chars = re.compile(r'<.*?>|(.)', re.S) re_tag = re.compile(r'<(/)?(\S+?)(?:(\s*/)|\s.*?)?>', re.S) re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines re_camel_case = re.compile(r'(((?<=[a-z])[A...
def capfirst(x): # Set up regular expressions re_words = re.compile(r'<[^>]+?>|([^<>\s]+)', re.S) re_chars = re.compile(r'<[^>]+?>|(.)', re.S) re_tag = re.compile(r'<(/)?(\S+?)(?:(\s*/)|\s.*?)?>', re.S) re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines re_camel_case = re.compile(r'(((?<=[a-z])[A-Z])|...
class FunctionTests(SimpleTestCase): def test_truncate2(self): self.assertEqual( truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 4), '<p>one <a href="#">two - three <br>four …</a></p>', ) def test_truncate3(self): self.assertEqual( ...
class FunctionTests(SimpleTestCase): def test_truncate2(self): self.assertEqual( truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 4), '<p>one <a href="#">two - three …</a></p>', ) def test_truncate3(self): self.assertEqual( t...
class TestUtilsText(SimpleTestCase): # lazy strings are handled correctly self.assertEqual(text.Truncator(lazystr('The quick brown fox')).chars(10), 'The quick…') def test_truncate_words(self): truncator = text.Truncator('The quick brown fox jumped over the lazy dog.') self.assertEq...
class TestUtilsText(SimpleTestCase): # lazy strings are handled correctly self.assertEqual(text.Truncator(lazystr('The quick brown fox')).chars(10), 'The quick…') def test_truncate_chars_html(self): perf_test_values = [ (('</a' + '\t' * 50000) + '//>', None), ('&' * ...
class TestUtilsText(SimpleTestCase): truncator = text.Truncator('<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo est&aacute;?</i>') self.assertEqual('<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo…</i>', truncator.words(3, html=True)) truncator = text.Truncator('<p>I &lt;3 python, what about you?</p>') ...
class TestUtilsText(SimpleTestCase): truncator = text.Truncator('<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo est&aacute;?</i>') self.assertEqual('<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo…</i>', truncator.words(3, html=True)) truncator = text.Truncator('<p>I &lt;3 python, what about you?</p>') ...
##parameters=default_tab, obj=None, portal_tabs=[] ##title= ## from AccessControl import Unauthorized
##parameters=default_tab, obj=None, portal_tabs=[] ##title= ## from zExceptions import Forbidden if container.REQUEST['PUBLISHED'] is script: raise Forbidden('Script may not be published.') from AccessControl import Unauthorized
'self', which will cause the list to be sorted in place without a sort function. """ list_len = len(input_list)
'self', which will cause the list to be sorted in place without a sort function. """ from zExceptions import Forbidden if container.REQUEST['PUBLISHED'] is script: raise Forbidden('Script may not be published.') list_len = len(input_list)
##bind subpath=traverse_subpath ##parameters=qs=None, **kw ##title=Creates a query string based on existing string plus keyword arguments from Products.PythonScripts.standard import url_quote_plus L = []
##bind subpath=traverse_subpath ##parameters=qs=None, **kw ##title=Creates a query string based on existing string plus keyword arguments from zExceptions import Forbidden if container.REQUEST['PUBLISHED'] is script: raise Forbidden('Script may not be published.') from Products.PythonScripts.standard import url_quo...
##parameters=input_id return r"""
##parameters=input_id from zExceptions import Forbidden if container.REQUEST['PUBLISHED'] is script: raise Forbidden('Script may not be published.') return r"""
class TestUtil(unittest.TestCase): self.assertEqual(parse_duration('0s'), 0) self.assertEqual(parse_duration('01:02:03.05'), 3723.05) self.assertEqual(parse_duration('T30M38S'), 1838) def test_fix_xml_ampersands(self): self.assertEqual(
class TestUtil(unittest.TestCase): self.assertEqual(parse_duration('0s'), 0) self.assertEqual(parse_duration('01:02:03.05'), 3723.05) self.assertEqual(parse_duration('T30M38S'), 1838) self.assertEqual(parse_duration('5 s'), 5) self.assertEqual(parse_duration('3 min'), 180) ...
from ..compat import ( ) from ..utils import ( int_or_none, parse_filesize, )
from ..compat import ( ) from ..utils import ( int_or_none, parse_duration, parse_filesize, )
class MinhatecaIE(InfoExtractor): filesize_approx = parse_filesize(self._html_search_regex( r'<p class="fileSize">(.*?)</p>', webpage, 'file size approximation', fatal=False)) duration = int_or_none(self._html_search_regex( r'(?s)<p class="fileLeng[ht][th]">.*?([0-9]+...
class MinhatecaIE(InfoExtractor): filesize_approx = parse_filesize(self._html_search_regex( r'<p class="fileSize">(.*?)</p>', webpage, 'file size approximation', fatal=False)) duration = parse_duration(self._html_search_regex( r'(?s)<p class="fileLeng[ht][th]">.*?clas...
def parse_duration(s): m = re.match( r'''(?ix)T? (?: (?:(?P<hours>[0-9]+)\s*(?:[:h]|hours?)\s*)? (?P<mins>[0-9]+)\s*(?:[:m]|mins?|minutes?)\s* )? (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*(?:s|secs?|seconds?)?$''', s) if not m: retur...
def parse_duration(s): m = re.match( r'''(?ix)T? (?: (?P<only_mins>[0-9.]+)\s*(?:mins?|minutes?)\s*| (?P<only_hours>[0-9.]+)\s*(?:hours?)| (?: (?:(?P<hours>[0-9]+)\s*(?:[:h]|hours?)\s*)? (?P<mins>[0-9]+)\s*(?:[:m]|mins?|minutes?)\...
class Sequential(Model): first_layer = layer.layers[0] while isinstance(first_layer, (Model, Sequential)): first_layer = first_layer.layers[0] batch_shape = first_layer.batch_input_shape dtype = first_layer.dtype ...
class Sequential(Model): first_layer = layer.layers[0] while isinstance(first_layer, (Model, Sequential)): first_layer = first_layer.layers[0] if hasattr(first_layer, 'batch_input_shape'): batch_shape = first_layer.batc...
def test_sequential_deferred_build(): assert len(new_model.weights) == 4 if __name__ == '__main__': pytest.main([__file__])
def test_sequential_deferred_build(): assert len(new_model.weights) == 4 @keras_test def test_nested_sequential_deferred_build(): inner_model = keras.models.Sequential() inner_model.add(keras.layers.Dense(3)) inner_model.add(keras.layers.Dense(3)) model = keras.models.Sequential() model.add(i...
import os from shutil import rmtree import string import tempfile from typing import List, Optional, Union, cast import warnings import zipfile
import os from shutil import rmtree import string import tempfile from typing import Any, List, Optional, Union, cast import warnings import zipfile
from pandas._config.localization import ( # noqa:F401 ) import pandas._libs.testing as _testing from pandas._typing import FrameOrSeries from pandas.compat import _get_lzma_file, _import_lzma from pandas.core.dtypes.common import (
from pandas._config.localization import ( # noqa:F401 ) import pandas._libs.testing as _testing from pandas._typing import FilePathOrBuffer, FrameOrSeries from pandas.compat import _get_lzma_file, _import_lzma from pandas.core.dtypes.common import (
def reset_display_options(): pd.reset_option("^display.", silent=True) def round_trip_pickle(obj: FrameOrSeries, path: Optional[str] = None) -> FrameOrSeries: """ Pickle an object and then read it again. Parameters ---------- obj : pandas object The object to pickle and then re-read. ...
def reset_display_options(): pd.reset_option("^display.", silent=True) def round_trip_pickle( obj: Any, path: Optional[FilePathOrBuffer] = None ) -> FrameOrSeries: """ Pickle an object and then read it again. Parameters ---------- obj : any object The object to pickle and then re-...
def round_trip_pickle(obj: FrameOrSeries, path: Optional[str] = None) -> FrameOr pandas object The original object that was pickled and then re-read. """ if path is None: path = f"__{rands(10)}__.pickle" with ensure_clean(path) as path: pd.to_pickle(obj, path) return pd.r...
def round_trip_pickle(obj: FrameOrSeries, path: Optional[str] = None) -> FrameOr pandas object The original object that was pickled and then re-read. """ _path = path if _path is None: _path = f"__{rands(10)}__.pickle" with ensure_clean(_path) as path: pd.to_pickle(obj, _path...