buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
class YoutubeDL(object):
else:
filter_parts.append(string)
def _parse_format_selection(tokens, endwith=[]):
selectors = []
current_selector = None
for type, string, start, _, _ in tokens: | class YoutubeDL(object):
else:
filter_parts.append(string)
def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False):
selectors = []
current_selector = None
for type, string, start, _, _ in tokens: |
class YoutubeDL(object):
elif type in [tokenize.NAME, tokenize.NUMBER]:
current_selector = FormatSelector(SINGLE, string, [])
elif type == tokenize.OP:
if string in endwith:
break
elif string == ')':
... | class YoutubeDL(object):
elif type in [tokenize.NAME, tokenize.NUMBER]:
current_selector = FormatSelector(SINGLE, string, [])
elif type == tokenize.OP:
if string == ')':
if not inside_group:
# ')'... |
class YoutubeDL(object):
elif string == '(':
if current_selector:
raise syntax_error('Unexpected "("', start)
current_selector = FormatSelector(GROUP, _parse_format_selection(tokens, [')']), [])
elif stri... | class YoutubeDL(object):
elif string == '(':
if current_selector:
raise syntax_error('Unexpected "("', start)
group = _parse_format_selection(tokens, inside_group=True)
current_selector = FormatSelect... |
from youtube_dl.utils import (
shell_quote,
smuggle_url,
str_to_int,
timeconvert,
unescapeHTML,
unified_strdate, | from youtube_dl.utils import (
shell_quote,
smuggle_url,
str_to_int,
struct_unpack,
timeconvert,
unescapeHTML,
unified_strdate, |
class TestUtil(unittest.TestCase):
testPL(5, 2, (2, 99), [2, 3, 4])
testPL(5, 2, (20, 99), [])
if __name__ == '__main__':
unittest.main() | class TestUtil(unittest.TestCase):
testPL(5, 2, (2, 99), [2, 3, 4])
testPL(5, 2, (20, 99), [])
def test_struct_unpack(self):
self.assertEqual(struct_unpack(u'!B', b'\x00'), (0,))
if __name__ == '__main__':
unittest.main() |
import base64
import io
import itertools
import os
from struct import unpack, pack
import time
import xml.etree.ElementTree as etree
from .common import FileDownloader
from .http import HttpFD
from ..utils import (
compat_urllib_request,
compat_urlparse,
format_bytes, | import base64
import io
import itertools
import os
import time
import xml.etree.ElementTree as etree
from .common import FileDownloader
from .http import HttpFD
from ..utils import (
struct_pack,
struct_unpack,
compat_urllib_request,
compat_urlparse,
format_bytes, |
class FlvReader(io.BytesIO):
# Utility functions for reading numbers and strings
def read_unsigned_long_long(self):
return unpack('!Q', self.read(8))[0]
def read_unsigned_int(self):
return unpack('!I', self.read(4))[0]
def read_unsigned_char(self):
return unpack('!B', self.rea... | class FlvReader(io.BytesIO):
# Utility functions for reading numbers and strings
def read_unsigned_long_long(self):
return struct_unpack('!Q', self.read(8))[0]
def read_unsigned_int(self):
return struct_unpack('!I', self.read(4))[0]
def read_unsigned_char(self):
return struct_... |
def write_flv_header(stream, metadata):
# Script data
stream.write(b'\x12')
# Size of the metadata with 3 bytes
stream.write(pack('!L', len(metadata))[1:])
stream.write(b'\x00\x00\x00\x00\x00\x00\x00')
stream.write(metadata)
# Magic numbers extracted from the output files produced by AdobeHD... | def write_flv_header(stream, metadata):
# Script data
stream.write(b'\x12')
# Size of the metadata with 3 bytes
stream.write(struct_pack('!L', len(metadata))[1:])
stream.write(b'\x00\x00\x00\x00\x00\x00\x00')
stream.write(metadata)
# Magic numbers extracted from the output files produced by ... |
import platform
import re
import ssl
import socket
import subprocess
import sys
import traceback | import platform
import re
import ssl
import socket
import struct
import subprocess
import sys
import traceback |
def uppercase_escape(s):
return re.sub(
r'\\U([0-9a-fA-F]{8})',
lambda m: compat_chr(int(m.group(1), base=16)), s) | def uppercase_escape(s):
return re.sub(
r'\\U([0-9a-fA-F]{8})',
lambda m: compat_chr(int(m.group(1), base=16)), s)
try:
struct.pack(u'!I', 0)
except TypeError:
# In Python 2.6 (and some 2.7 versions), struct requires a bytes argument
def struct_pack(spec, *args):
if isinstance(s... |
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 _add_margins(
row_names = result.index.names
try:
for dtype in set(result.dtypes):
cols = result.select_dtypes([dtype]).columns
margin_dummy[cols] = margin_dummy[cols].astype(dtype)
result = result.append(margin_dummy)
except TypeError:
| def _add_margins(
row_names = result.index.names
try:
# check the result column and leave floats
for dtype in set(result.dtypes):
cols = result.select_dtypes([dtype]).columns
margin_dummy[cols] = margin_dummy[cols].apply(
maybe_downcast_to_dtype, args=(dt... |
class TestPivotTable:
table = df.pivot_table("x", "y", "z", dropna=observed, margins=True)
tm.assert_frame_equal(table, expected)
def test_pivot_with_categorical(self, observed, ordered_fixture):
# gh-21370
idx = [np.nan, "low", "high", "low", np.nan] | class TestPivotTable:
table = df.pivot_table("x", "y", "z", dropna=observed, margins=True)
tm.assert_frame_equal(table, expected)
def test_margins_casted_to_float(self, observed):
# GH 24893
df = pd.DataFrame(
{
"A": [2, 4, 6, 8],
"B": [1,... |
def _period_array_cmp(cls, op):
@unpack_zerodim_and_defer(opname)
def wrapper(self, other):
ordinal_op = getattr(self.asi8, opname)
if isinstance(other, str):
try: | def _period_array_cmp(cls, op):
@unpack_zerodim_and_defer(opname)
def wrapper(self, other):
if isinstance(other, str):
try: |
def _period_array_cmp(cls, op):
except ValueError:
# string that can't be parsed as Period
return invalid_comparison(self, other, op)
elif isinstance(other, int):
# TODO: sure we want to allow this? we dont for DTA/TDA
# 2 tests rely on this
... | def _period_array_cmp(cls, op):
except ValueError:
# string that can't be parsed as Period
return invalid_comparison(self, other, op)
if isinstance(other, self._recognized_scalars) or other is NaT:
other = self._scalar_type(other) |
class TestPeriodArrayLikeComparisons:
class TestPeriodIndexComparisons:
# TODO: parameterize over boxes
@pytest.mark.parametrize("other", ["2017", 2017])
def test_eq(self, other):
idx = PeriodIndex(["2017", "2017", "2018"], freq="D")
expected = np.array([True, True, False]) | class TestPeriodArrayLikeComparisons:
class TestPeriodIndexComparisons:
# TODO: parameterize over boxes
@pytest.mark.parametrize("other", ["2017", pd.Period("2017", freq="D")])
def test_eq(self, other):
idx = PeriodIndex(["2017", "2017", "2018"], freq="D")
expected = np.array([True, True, F... |
class TestPeriodIndexComparisons:
tm.assert_numpy_array_equal(result, expected)
def test_pi_cmp_period(self):
idx = period_range("2007-01", periods=20, freq="M")
| class TestPeriodIndexComparisons:
tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize(
"other",
[
2017,
[2017, 2017, 2017],
np.array([2017, 2017, 2017]),
np.array([2017, 2017, 2017], dtype=object),
pd.Index([201... |
class TestPeriodIndex(DatetimeLike):
ts = Series(np.random.randn(len(idx)), index=idx)
result = ts[2007]
expected = ts[idx == 2007]
tm.assert_series_equal(result, expected)
def test_index_unique(self): | class TestPeriodIndex(DatetimeLike):
ts = Series(np.random.randn(len(idx)), index=idx)
result = ts[2007]
expected = ts[idx == "2007"]
tm.assert_series_equal(result, expected)
def test_index_unique(self): |
from django.db import models
from django.http import Http404
from django.template.engine import Engine
from django.urls import get_mod_func, get_resolver, get_urlconf
from django.utils.decorators import method_decorator
from django.utils.functional import cached_property
from django.utils.inspect import ( | from django.db import models
from django.http import Http404
from django.template.engine import Engine
from django.urls import get_mod_func, get_resolver, get_urlconf
from django.utils._os import safe_join
from django.utils.decorators import method_decorator
from django.utils.functional import cached_property
from djan... |
class TemplateDetailView(BaseAdminDocsView):
else:
# This doesn't account for template loaders (#24128).
for index, directory in enumerate(default_engine.dirs):
template_file = Path(directory) / template
if template_file.exists():
templ... | class TemplateDetailView(BaseAdminDocsView):
else:
# This doesn't account for template loaders (#24128).
for index, directory in enumerate(default_engine.dirs):
template_file = Path(safe_join(directory, template))
if template_file.exists():
... |
class AdminDocViewTests(TestDataMixin, AdminDocsTestCase):
self.assertEqual(response.status_code, 200)
@override_settings(TEMPLATES=[{
'NAME': 'ONE',
'BACKEND': 'django.template.backends.django.DjangoTemplates', | class AdminDocViewTests(TestDataMixin, AdminDocsTestCase):
self.assertEqual(response.status_code, 200)
@unittest.skipUnless(utils.docutils_is_available, 'no docutils installed.')
class AdminDocViewDefaultEngineOnly(TestDataMixin, AdminDocsTestCase):
def setUp(self):
self.client.force_login(se... |
def _unstack_multiple(data, clocs, fill_value=None):
index = data.index
clocs = [index._get_level_number(i) for i in clocs]
rlocs = [i for i in range(index.nlevels) if i not in clocs] | def _unstack_multiple(data, clocs, fill_value=None):
index = data.index
# GH 19966 Make sure if MultiIndexed index has tuple name, they will be
# recognised as a whole
if clocs in index.names:
clocs = [clocs]
clocs = [index._get_level_number(i) for i in clocs]
rlocs = [i for i in rang... |
class TestDataFrameReshape:
)
tm.assert_frame_equal(result, expected)
def test_unstack_preserve_dtypes(self):
# Checks fix for #11847
df = pd.DataFrame( | class TestDataFrameReshape:
)
tm.assert_frame_equal(result, expected)
def test_unstack_tuplename_in_multiindex(self):
# GH 19966
idx = pd.MultiIndex.from_product(
[["a", "b", "c"], [1, 2, 3]], names=[("A", "a"), ("B", "b")]
)
df = pd.DataFrame({"d": [1] *... |
import pytest
import pandas.util._test_decorators as td
import pandas as pd
from pandas import DataFrame, MultiIndex, Series
import pandas._testing as tm
| import pytest
import pandas.util._test_decorators as td
import pandas as pd
from pandas import DataFrame, Series
import pandas._testing as tm
|
class TestSeriesAnalytics:
assert s.is_monotonic is False
assert s.is_monotonic_decreasing is True
def test_unstack(self):
index = MultiIndex(
levels=[["bar", "foo"], ["one", "three", "two"]],
codes=[[1, 1, 0, 0], [0, 1, 0, 2]],
)
s = Series(np.aran... | class TestSeriesAnalytics:
assert s.is_monotonic is False
assert s.is_monotonic_decreasing is True
@pytest.mark.parametrize("func", [np.any, np.all])
@pytest.mark.parametrize("kwargs", [dict(keepdims=True), dict(out=object())])
@td.skip_if_np_lt("1.15") |
from __future__ import absolute_import
import datetime
import logging
import os | from __future__ import absolute_import
import re
import datetime
import logging
import os |
class ConnectionError(Exception):
# (ie test_recent_date is failing) update it to ~6 months before the current date.
RECENT_DATE = datetime.date(2019, 1, 1)
class DummyConnection(object):
"""Used to detect a failed ConnectionCls import.""" | class ConnectionError(Exception):
# (ie test_recent_date is failing) update it to ~6 months before the current date.
RECENT_DATE = datetime.date(2019, 1, 1)
_CONTAINS_CONTROL_CHAR_RE = re.compile(r"[^-!#$%&'*+.^_`|~0-9a-zA-Z]")
class DummyConnection(object):
"""Used to detect a failed ConnectionCls import.""" |
def connect(self):
conn = self._new_conn()
self._prepare_conn(conn)
def request_chunked(self, method, url, body=None, headers=None):
"""
Alternative to the common request method, which sends the | def connect(self):
conn = self._new_conn()
self._prepare_conn(conn)
def putrequest(self, method, url, *args, **kwargs):
"""Send a request to the server"""
match = _CONTAINS_CONTROL_CHAR_RE.search(method)
if match:
raise ValueError(
"Method cannot ... |
def test_dns_error(self):
with pytest.raises(MaxRetryError):
pool.request("GET", "/test", retries=2)
def test_percent_encode_invalid_target_chars(self):
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.request("GET", "/echo_params?q=\r&k=\n \n") | def test_dns_error(self):
with pytest.raises(MaxRetryError):
pool.request("GET", "/test", retries=2)
@pytest.mark.parametrize("char", [" ", "\r", "\n", "\x00"])
def test_invalid_method_not_allowed(self, char):
with pytest.raises(ValueError):
with HTTPConnectionPo... |
def bar(foo: Foo):
# fails due to returndatasize being nonzero but also lt 64
assert_tx_failed(lambda: c.bar(bad_1.address))
c.bar(bad_2.address) | def bar(foo: Foo):
# fails due to returndatasize being nonzero but also lt 64
assert_tx_failed(lambda: c.bar(bad_1.address))
c.bar(bad_2.address)
def test_contract_address_evaluation(get_contract):
callee_code = """
# implements: Foo
interface Counter:
def increment_counter(): nonpayable
@extern... |
def _extcodesize_check(address):
return ["assert", ["extcodesize", address]]
def ir_for_external_call(call_expr, context):
from vyper.codegen.expr import Expr # TODO rethink this circular import
contract_address = Expr.parse_value_expr(call_expr.func.value, context)
call_kwargs = _parse_kwargs(call_... | def _extcodesize_check(address):
return ["assert", ["extcodesize", address]]
def _external_call_helper(contract_address, args_ir, call_kwargs, call_expr, context):
# expr.func._metadata["type"].return_type is more accurate
# than fn_sig.return_type in the case of JSON interfaces.
fn_type = call_expr.f... |
def ir_for_external_call(call_expr, context):
ret.append(ret_unpacker)
return IRnode.from_list(ret, typ=return_t, location=MEMORY) | def ir_for_external_call(call_expr, context):
ret.append(ret_unpacker)
return IRnode.from_list(ret, typ=return_t, location=MEMORY)
def ir_for_external_call(call_expr, context):
from vyper.codegen.expr import Expr # TODO rethink this circular import
contract_address = Expr.parse_value_expr(call_... |
from django.utils.text import normalize_newlines
from .html_parser import HTMLParseError, HTMLParser
# Configuration for urlize() function.
TRAILING_PUNCTUATION_RE = re.compile(
'^' # Beginning of word
'(.*?)' # The URL in word
'([.,:;!]+)' # Allowed non-wrapping, trailing punctuation
... | from django.utils.text import normalize_newlines
from .html_parser import HTMLParseError, HTMLParser
# Configuration for urlize() function.
TRAILING_PUNCTUATION_CHARS = '.,:;!'
WRAPPING_PUNCTUATION = [('(', ')'), ('<', '>'), ('[', ']'), ('<', '>'), ('"', '"'), ('\'', '\'')]
# List of possible strings used for b... |
unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)')
word_split_re = re.compile(r'''([\s<>"']+)''')
simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE)
simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$', re.IGNORECASE)
simple_email_re = re.compile(r'^\S+@\S+\.\... | unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)')
word_split_re = re.compile(r'''([\s<>"']+)''')
simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE)
simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$', re.IGNORECASE)
@keep_lazy(str, SafeText) |
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
trimmed_something = False
# Trim trailing punctuation.
match = TRAILING_PUNCTUATION_RE.match(middle)
if match:
middle = match.group(1)
trail = match.group(2) + trail
... | def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
trimmed_something = False
# Trim trailing punctuation.
stripped = middle.rstrip(TRAILING_PUNCTUATION_CHARS)
if middle != stripped:
trail = middle[len(stripped):] + trail
... |
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
trimmed_something = True
return lead, middle, trail
words = word_split_re.split(force_text(text))
for i, word in enumerate(words):
if '.' in word or '@' in word or ':' in word: | def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
trimmed_something = True
return lead, middle, trail
def is_email_simple(value):
"""Return True if value looks like an email address."""
# An @ must be in the middle of the value.
if '@' not ... |
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
elif simple_url_2_re.match(middle):
middle, middle_unescaped, trail = unescape(middle, trail)
url = smart_urlquote('http://%s' % middle_unescaped)
elif ':' not in middle and simple_email_re.m... | def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
elif simple_url_2_re.match(middle):
middle, middle_unescaped, trail = unescape(middle, trail)
url = smart_urlquote('http://%s' % middle_unescaped)
elif ':' not in middle and is_email_simple(m... |
from django.test import SimpleTestCase
from django.utils.functional import lazystr
from django.utils.html import (
conditional_escape, escape, escapejs, format_html, html_safe, linebreaks,
smart_urlquote, strip_spaces_between_tags, strip_tags,
)
from django.utils.safestring import mark_safe
| from django.test import SimpleTestCase
from django.utils.functional import lazystr
from django.utils.html import (
conditional_escape, escape, escapejs, format_html, html_safe, linebreaks,
smart_urlquote, strip_spaces_between_tags, strip_tags, urlize,
)
from django.utils.safestring import mark_safe
|
class TestUtilsHtml(SimpleTestCase):
@html_safe
class HtmlClass:
pass | class TestUtilsHtml(SimpleTestCase):
@html_safe
class HtmlClass:
pass
def test_urlize_unchanged_inputs(self):
tests = (
('a' + '@a' * 50000) + 'a', # simple_email_re catastrophic test
('a' + '.' * 1000000) + 'a', # trailing_punctuation catas... |
import sys
import os
import platform
import math
import binascii |
import sys
import os
import re
import platform
import math
import binascii |
def formatExceptionTrace(e):
"""Return exception information formatted as string"""
return str(e)
else:
# Python 2.6 requires strings instead of bytearrays in a couple places,
# so we define this function so it does the conversion if needed. | def formatExceptionTrace(e):
"""Return exception information formatted as string"""
return str(e)
def remove_whitespace(text):
"""Removes all whitespace from passed in string"""
return re.sub(r"\s+", "", text, flags=re.UNICODE)
else:
# Python 2.6 requires strings instead of byt... |
def formatExceptionTrace(e):
if sys.version_info < (2, 7) or sys.version_info < (2, 7, 4) \
or platform.system() == 'Java':
def compat26Str(x): return str(x)
else:
def compat26Str(x): return x
def compatAscii2Bytes(val):
"""Convert ASCII string to bytes."""
retur... | def formatExceptionTrace(e):
if sys.version_info < (2, 7) or sys.version_info < (2, 7, 4) \
or platform.system() == 'Java':
def compat26Str(x): return str(x)
def remove_whitespace(text):
"""Removes all whitespace from passed in string"""
return re.sub(r"\s+", "",... |
def ct_lt_u32(val_a, val_b):
return (val_a^((val_a^val_b)|(((val_a-val_b)&0xffffffff)^val_b)))>>31
def ct_gt_u32(val_a, val_b):
"""
Return 1 if val_a > val_b, 0 otherwise. Constant time. | def ct_lt_u32(val_a, val_b):
return (val_a^((val_a^val_b)|(((val_a-val_b)&0xffffffff)^val_b)))>>31
def ct_gt_u32(val_a, val_b):
"""
Return 1 if val_a > val_b, 0 otherwise. Constant time. |
def ct_gt_u32(val_a, val_b):
"""
return ct_lt_u32(val_b, val_a)
def ct_le_u32(val_a, val_b):
"""
Return 1 if val_a <= val_b, 0 otherwise. Constant time. | def ct_gt_u32(val_a, val_b):
"""
return ct_lt_u32(val_b, val_a)
def ct_le_u32(val_a, val_b):
"""
Return 1 if val_a <= val_b, 0 otherwise. Constant time. |
def ct_le_u32(val_a, val_b):
"""
return 1 ^ ct_gt_u32(val_a, val_b)
def ct_lsb_prop_u8(val):
"""Propagate LSB to all 8 bits of the returned byte. Constant time."""
val &= 0x01
val |= val << 1
val |= val << 2
val |= val << 4
return val
def ct_isnonzero_u32(val):
"""
Returns 1 if... | def ct_le_u32(val_a, val_b):
"""
return 1 ^ ct_gt_u32(val_a, val_b)
def ct_lsb_prop_u8(val):
"""Propagate LSB to all 8 bits of the returned int. Constant time."""
val &= 0x01
val |= val << 1
val |= val << 2
val |= val << 4
return val
def ct_lsb_prop_u16(val):
"""Propagate LSB to ... |
def ct_isnonzero_u32(val):
val &= 0xffffffff
return (val|(-val&0xffffffff)) >> 31
def ct_neq_u32(val_a, val_b):
"""
Return 1 if val_a != val_b, 0 otherwise. Constant time. | def ct_isnonzero_u32(val):
val &= 0xffffffff
return (val|(-val&0xffffffff)) >> 31
def ct_neq_u32(val_a, val_b):
"""
Return 1 if val_a != val_b, 0 otherwise. Constant time. |
def parsePEMKey(s, private=False, public=False, passwordCallback=None,
def _parseKeyHelper(key, private, public):
if private:
if not key.hasPrivateKey():
raise SyntaxError("Not a private key!")
if public:
return _createPublicKey(key)
if private:
if hasattr(key, "d"):
... | def parsePEMKey(s, private=False, public=False, passwordCallback=None,
def _parseKeyHelper(key, private, public):
if private and not key.hasPrivateKey():
raise SyntaxError("Not a private key!")
if public:
return _createPublicKey(key)
if private:
if cryptomath.m2cryptoLoaded:
... |
from .rsakey import *
from .python_rsakey import Python_RSAKey
from .compat import compatAscii2Bytes
#copied from M2Crypto.util.py, so when we load the local copy of m2
#we can still use it | from .rsakey import *
from .python_rsakey import Python_RSAKey
from .compat import compatAscii2Bytes
import sys
#copied from M2Crypto.util.py, so when we load the local copy of m2
#we can still use it |
def _rawPrivateKeyOp(self, m):
c = bytesToNumber(bytearray(s))
return c
def _rawPublicKeyOp(self, c):
b = numberToByteArray(c, numBytes(self.n))
s = m2.rsa_public_decrypt(self.rsa, bytes(b), m2.no_padding)
m = bytesToNumber(bytearray(s))
r... | def _rawPrivateKeyOp(self, m):
c = bytesToNumber(bytearray(s))
return c
def _raw_private_key_op_bytes(self, message):
return bytearray(m2.rsa_private_encrypt(self.rsa, bytes(message),
m2.no_padding))
def _rawPublic... |
def f():pass
key._hasPrivateKey = False
else:
raise SyntaxError()
return key
finally:
m2.bio_free(bio) | def f():pass
key._hasPrivateKey = False
else:
raise SyntaxError()
if key._hasPrivateKey:
if sys.version_info < (3, 0):
b64_key = str(key.write())
else:
... |
def generate(bits):
return key
generate = staticmethod(generate)
def parsePEM(s, passwordCallback=None):
"""Parse a string containing a PEM-encoded <privateKey>."""
if pemSniff(s, "PRIVATE KEY"):
bytes = dePem(s, "PRIVATE KEY")
return Python_RSAKey._parsePKCS8(b... | def generate(bits):
return key
generate = staticmethod(generate)
@staticmethod
def parsePEM(s, passwordCallback=None):
"""Parse a string containing a PEM-encoded <privateKey>."""
from .python_key import Python_Key
return Python_Key.parsePEM(s, passwordCallback) |
from . import tlshashlib as hashlib
from ..errors import MaskTooLongError, MessageTooLongError, EncodingError, \
InvalidSignature, UnknownRSAType
class RSAKey(object): | from . import tlshashlib as hashlib
from ..errors import MaskTooLongError, MessageTooLongError, EncodingError, \
InvalidSignature, UnknownRSAType
from .constanttime import ct_isnonzero_u32, ct_neq_u32, ct_lsb_prop_u8, \
ct_lsb_prop_u16, ct_lt_u32
class RSAKey(object): |
def __init__(self, n=0, e=0):
:type e: int
:param e: RSA public exponent.
"""
raise NotImplementedError()
def __len__(self): | def __init__(self, n=0, e=0):
:type e: int
:param e: RSA public exponent.
"""
self._key_hash = None
raise NotImplementedError()
def __len__(self): |
def RSASSA_PSS_sign(self, mHash, hAlg, sLen=0):
:type sLen: int
:param sLen: length of salt"""
EM = self.EMSA_PSS_encode(mHash, numBits(self.n) - 1, hAlg, sLen)
m = bytesToNumber(EM)
if m >= self.n:
raise MessageTooLongError("Encode output too long")
s = self.... | def RSASSA_PSS_sign(self, mHash, hAlg, sLen=0):
:type sLen: int
:param sLen: length of salt"""
EM = self.EMSA_PSS_encode(mHash, numBits(self.n) - 1, hAlg, sLen)
try:
ret = self._raw_private_key_op_bytes(EM)
except ValueError:
raise MessageTooLongError("Enc... |
def RSASSA_PSS_verify(self, mHash, S, hAlg, sLen=0):
:type sLen: int
:param sLen: Length of salt
"""
if len(bytearray(S)) != len(numberToByteArray(self.n)):
raise InvalidSignature("Invalid signature")
s = bytesToNumber(S)
m = self._rawPublicKeyOp(s)
EM... | def RSASSA_PSS_verify(self, mHash, S, hAlg, sLen=0):
:type sLen: int
:param sLen: Length of salt
"""
try:
EM = self._raw_public_key_op_bytes(S)
except ValueError:
raise InvalidSignature("Invalid signature")
result = self.EMSA_PSS_verify(mHash, EM, ... |
def _raw_pkcs1_sign(self, bytes):
if not self.hasPrivateKey():
raise AssertionError()
paddedBytes = self._addPKCS1Padding(bytes, 1)
m = bytesToNumber(paddedBytes)
if m >= self.n:
raise ValueError()
c = self._rawPrivateKeyOp(m)
sigBytes = numberToBy... | def _raw_pkcs1_sign(self, bytes):
if not self.hasPrivateKey():
raise AssertionError()
paddedBytes = self._addPKCS1Padding(bytes, 1)
return self._raw_private_key_op_bytes(paddedBytes)
def sign(self, bytes, padding='pkcs1', hashAlg=None, saltLen=None):
"""Sign the passed-i... |
def sign(self, bytes, padding='pkcs1', hashAlg=None, saltLen=None):
def _raw_pkcs1_verify(self, sigBytes, bytes):
"""Perform verification operation on raw PKCS#1 padded signature"""
if len(sigBytes) != numBytes(self.n):
return False
paddedBytes = self._addPKCS1Padding(bytes, 1)
... | def sign(self, bytes, padding='pkcs1', hashAlg=None, saltLen=None):
def _raw_pkcs1_verify(self, sigBytes, bytes):
"""Perform verification operation on raw PKCS#1 padded signature"""
try:
checkBytes = self._raw_public_key_op_bytes(sigBytes)
except ValueError:
return F... |
def encrypt(self, bytes):
:returns: A PKCS1 encryption of the passed-in data.
"""
paddedBytes = self._addPKCS1Padding(bytes, 2)
m = bytesToNumber(paddedBytes)
if m >= self.n:
raise ValueError()
c = self._rawPublicKeyOp(m)
encBytes = numberToByteArray(c... | def encrypt(self, bytes):
:returns: A PKCS1 encryption of the passed-in data.
"""
paddedBytes = self._addPKCS1Padding(bytes, 2)
return self._raw_public_key_op_bytes(paddedBytes)
def _dec_prf(self, key, label, out_len):
"""PRF for deterministic implicit rejection in the RSA d... |
def _rawPrivateKeyOp(self, m):
def _rawPublicKeyOp(self, c):
raise NotImplementedError()
def acceptsPassword(self):
"""Return True if the write() method accepts a password for use
in encrypting the private key. | def _rawPrivateKeyOp(self, m):
def _rawPublicKeyOp(self, c):
raise NotImplementedError()
def _raw_private_key_op_bytes(self, message):
n = self.n
if len(message) != numBytes(n):
raise ValueError("Message has incorrect length for the key size")
m_int = bytesToNumber(m... |
from tlslite.utils.constanttime import ct_lt_u32, ct_gt_u32, ct_le_u32, \
ct_lsb_prop_u8, ct_isnonzero_u32, ct_neq_u32, ct_eq_u32, \
ct_check_cbc_mac_and_pad, ct_compare_digest
from hypothesis import given, example
import hypothesis.strategies as st |
from tlslite.utils.constanttime import ct_lt_u32, ct_gt_u32, ct_le_u32, \
ct_lsb_prop_u8, ct_isnonzero_u32, ct_neq_u32, ct_eq_u32, \
ct_check_cbc_mac_and_pad, ct_compare_digest, ct_lsb_prop_u16
from hypothesis import given, example
import hypothesis.strategies as st |
def test_ct_lsb_prop_u8(self, i):
self.assertEqual(((i & 0x1) == 1), (ct_lsb_prop_u8(i) == 0xff))
self.assertEqual(((i & 0x1) == 0), (ct_lsb_prop_u8(i) == 0x00))
@given(i=st.integers(0,2**32 - 1))
@example(i=0)
def test_ct_isnonzero_u32(self, i): | def test_ct_lsb_prop_u8(self, i):
self.assertEqual(((i & 0x1) == 1), (ct_lsb_prop_u8(i) == 0xff))
self.assertEqual(((i & 0x1) == 0), (ct_lsb_prop_u8(i) == 0x00))
@given(i=st.integers(0, 2**16-1))
@example(i=0)
@example(i=255)
@example(i=2**16-1)
def test_ct_lsb_prop_u16(self, i):
... |
from tlslite.utils.python_rsakey import Python_RSAKey
from tlslite.utils.cryptomath import *
from tlslite.errors import *
try:
import mock
from mock import call | from tlslite.utils.python_rsakey import Python_RSAKey
from tlslite.utils.cryptomath import *
from tlslite.errors import *
from tlslite.utils.keyfactory import parsePEMKey
from tlslite.utils.compat import a2b_hex, remove_whitespace
try:
import mock
from mock import call |
def test_addPKCS1Prefix(self):
self.assertEqual(RSAKey.addPKCS1Prefix(data, 'sha1'), bytearray(
b'0!0\t\x06\x05+\x0e\x03\x02\x1a\x05\x00\x04\x14' +
b' sha-1 hash of data ')) | def test_addPKCS1Prefix(self):
self.assertEqual(RSAKey.addPKCS1Prefix(data, 'sha1'), bytearray(
b'0!0\t\x06\x05+\x0e\x03\x02\x1a\x05\x00\x04\x14' +
b' sha-1 hash of data '))
class TestRSADecrypt(unittest.TestCase):
@classmethod
def setUpClass(cls):
priv_key = """
-----B... |
class XMLRPCHandlerTests(unittest.TestCase):
self.assertEqual(params[11], {'k': [1, {}]})
class TraverseTests(unittest.TestCase):
def test_underscore(self):
from supervisor import xmlrpc
self.assertRaises(xmlrpc.RPCError, xmlrpc.traverse, None, '_', None)
def test_notfound(self):
... | class XMLRPCHandlerTests(unittest.TestCase):
self.assertEqual(params[11], {'k': [1, {}]})
class TraverseTests(unittest.TestCase):
def test_security_disallows_underscore_methods(self):
from supervisor import xmlrpc
class Root:
pass
class A:
def _danger(self):
... |
class supervisor_xmlrpc_handler(xmlrpc_handler):
return traverse(self.rpcinterface, method, params)
def traverse(ob, method, params):
path = method.split('.')
for name in path:
if name.startswith('_'):
# security (don't allow things that start with an underscore to
# be ... | class supervisor_xmlrpc_handler(xmlrpc_handler):
return traverse(self.rpcinterface, method, params)
def traverse(ob, method, params):
dotted_parts = method.split('.')
# security (CVE-2017-11610, don't allow object traversal)
if len(dotted_parts) != 2:
raise RPCError(Faults.UNKNOWN_METHOD)
... |
# -*- coding: utf-8 -*-
# The pam components have been modified to be salty and have been taken from
# the pam module under this licence:
# (c) 2007 Chris AtLee <chris@atlee.ca> | # The pam components have been modified to be salty and have been taken from
# the pam module under this licence:
# (c) 2007 Chris AtLee <chris@atlee.ca> |
authenticated against. This defaults to `login`
"""
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
from ctypes import ( | authenticated against. This defaults to `login`
"""
import logging
from ctypes import ( |
from ctypes import (
)
from ctypes.util import find_library
# Import Salt libs
import salt.utils.user
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin
log = logging.getLogger(__name__)
try: | from ctypes import (
)
from ctypes.util import find_library
import salt.utils.user
log = logging.getLogger(__name__)
try: |
class PamMessage(Structure):
]
def __repr__(self):
return "<PamMessage {0} '{1}'>".format(self.msg_style, self.msg)
class PamResponse(Structure): | class PamMessage(Structure):
]
def __repr__(self):
return "<PamMessage {} '{}'>".format(self.msg_style, self.msg)
class PamResponse(Structure): |
class PamResponse(Structure):
]
def __repr__(self):
return "<PamResponse {0} '{1}'>".format(self.resp_retcode, self.resp)
CONV_FUNC = CFUNCTYPE( | class PamResponse(Structure):
]
def __repr__(self):
return "<PamResponse {} '{}'>".format(self.resp_retcode, self.resp)
CONV_FUNC = CFUNCTYPE( |
def authenticate(username, password):
"""
service = __opts__.get("auth.pam.service", "login")
if isinstance(username, six.text_type):
username = username.encode(__salt_system_encoding__)
if isinstance(password, six.text_type):
password = password.encode(__salt_system_encoding__)
if ... | def authenticate(username, password):
"""
service = __opts__.get("auth.pam.service", "login")
if isinstance(username, str):
username = username.encode(__salt_system_encoding__)
if isinstance(password, str):
password = password.encode(__salt_system_encoding__)
if isinstance(service, ... |
def authenticate(username, password):
retval = PAM_AUTHENTICATE(handle, 0)
if retval == 0:
PAM_ACCT_MGMT(handle, 0)
PAM_END(handle, 0)
return retval == 0
| def authenticate(username, password):
retval = PAM_AUTHENTICATE(handle, 0)
if retval == 0:
retval = PAM_ACCT_MGMT(handle, 0)
PAM_END(handle, 0)
return retval == 0
|
Genshi Renderer for Salt
"""
# pylint: disable=import-error,no-name-in-module
try:
from genshi.template import MarkupTemplate
from genshi.template import NewTextTemplate
from genshi.template import OldTextTemplate
HAS_LIBS = True
except ImportError:
HAS_LIBS = False
# pylint: enable=import-error,n... | Genshi Renderer for Salt
"""
try:
from genshi.template import MarkupTemplate # pylint: disable=no-name-in-module
from genshi.template import NewTextTemplate # pylint: disable=no-name-in-module
from genshi.template import OldTextTemplate # pylint: disable=no-name-in-module
HAS_LIBS = True
except Imp... |
class Series(base.IndexOpsMixin, generic.NDFrame):
indexer = self.index.get_indexer_for(key)
return self.iloc[indexer]
else:
return self._get_values(key)
if isinstance(key, (list, tuple)):
# TODO: de-dup with tuple case handled above? | class Series(base.IndexOpsMixin, generic.NDFrame):
indexer = self.index.get_indexer_for(key)
return self.iloc[indexer]
else:
return self.iloc[key]
if isinstance(key, (list, tuple)):
# TODO: de-dup with tuple case handled above? |
class TestFancy:
idxr = idxr(obj)
nd3 = np.random.randint(5, size=(2, 2, 2))
msg = (
r"Buffer has wrong number of dimensions \(expected 1, "
r"got 3\)|"
"Cannot index with multidimensional key|"
r"Wrong number of dimensions. values.ndim != ndim \[... | class TestFancy:
idxr = idxr(obj)
nd3 = np.random.randint(5, size=(2, 2, 2))
msg = "|".join(
[
r"Buffer has wrong number of dimensions \(expected 1, got 3\)",
"Cannot index with multidimensional key",
r"Wrong number of dimensions. valu... |
class ReduceLROnPlateau(Callback):
monitored has stopped increasing; in `auto`
mode, the direction is automatically inferred
from the name of the monitored quantity.
epsilon: threshold for measuring the new optimum,
to only focus on significant changes.
co... | class ReduceLROnPlateau(Callback):
monitored has stopped increasing; in `auto`
mode, the direction is automatically inferred
from the name of the monitored quantity.
min_delta: threshold for measuring the new optimum,
to only focus on significant changes.
... |
class ReduceLROnPlateau(Callback):
"""
def __init__(self, monitor='val_loss', factor=0.1, patience=10,
verbose=0, mode='auto', epsilon=1e-4, cooldown=0, min_lr=0):
super(ReduceLROnPlateau, self).__init__()
self.monitor = monitor
if factor >= 1.0:
raise Valu... | class ReduceLROnPlateau(Callback):
"""
def __init__(self, monitor='val_loss', factor=0.1, patience=10,
verbose=0, mode='auto', min_delta=1e-4, cooldown=0, min_lr=0,
**kwargs):
super(ReduceLROnPlateau, self).__init__()
self.monitor = monitor
if factor >... |
class ReduceLROnPlateau(Callback):
self.mode = 'auto'
if (self.mode == 'min' or
(self.mode == 'auto' and 'acc' not in self.monitor)):
self.monitor_op = lambda a, b: np.less(a, b - self.epsilon)
self.best = np.Inf
else:
self.monitor_op = lambda a... | class ReduceLROnPlateau(Callback):
self.mode = 'auto'
if (self.mode == 'min' or
(self.mode == 'auto' and 'acc' not in self.monitor)):
self.monitor_op = lambda a, b: np.less(a, b - self.min_delta)
self.best = np.Inf
else:
self.monitor_op = lambda... |
class ReduceLROnPlateau(Callback):
self.best = current
self.wait = 0
elif not self.in_cooldown():
if self.wait >= self.patience:
old_lr = float(K.get_value(self.model.optimizer.lr))
if old_lr > self.min_lr: | class ReduceLROnPlateau(Callback):
self.best = current
self.wait = 0
elif not self.in_cooldown():
self.wait += 1
if self.wait >= self.patience:
old_lr = float(K.get_value(self.model.optimizer.lr))
if old_... |
class ReduceLROnPlateau(Callback):
'rate to %s.' % (epoch + 1, new_lr))
self.cooldown_counter = self.cooldown
self.wait = 0
self.wait += 1
def in_cooldown(self):
return self.cooldown_counter > 0 | class ReduceLROnPlateau(Callback):
'rate to %s.' % (epoch + 1, new_lr))
self.cooldown_counter = self.cooldown
self.wait = 0
def in_cooldown(self):
return self.cooldown_counter > 0 |
def test_ReduceLROnPlateau():
model = make_model()
# This should reduce the LR after the first epoch (due to high epsilon).
cbks = [callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.1, epsilon=10, patience=1, cooldown=5)]
model.fit(X_train, y_train, batch_size=batch_size,
validatio... | def test_ReduceLROnPlateau():
model = make_model()
# This should reduce the LR after the first epoch (due to high epsilon).
cbks = [callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.1, min_delta=10, patience=1, cooldown=5)]
model.fit(X_train, y_train, batch_size=batch_size,
validat... |
class MinimumLengthValidator:
) % {'min_length': self.min_length}
class UserAttributeSimilarityValidator:
"""
Validate whether the password is sufficiently different from the user's | class MinimumLengthValidator:
) % {'min_length': self.min_length}
def exceeds_maximum_length_ratio(password, max_similarity, value):
"""
Test that value is within a reasonable range of password.
The following ratio calculations are based on testing SequenceMatcher like
this:
for i in ran... |
class UserAttributeSimilarityValidator:
def __init__(self, user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7):
self.user_attributes = user_attributes
self.max_similarity = max_similarity
def validate(self, password, user=None):
if not user:
return
for att... | class UserAttributeSimilarityValidator:
def __init__(self, user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7):
self.user_attributes = user_attributes
if max_similarity < 0.1:
raise ValueError('max_similarity must be at least 0.1')
self.max_similarity = max_similarity
... |
class UserAttributeSimilarityValidatorTest(TestCase):
max_similarity=1,
).validate(user.first_name, user=user)
self.assertEqual(cm.exception.messages, [expected_error % "first name"])
# max_similarity=0 rejects all passwords.
with self.assertRaises(ValidationError) as... | class UserAttributeSimilarityValidatorTest(TestCase):
max_similarity=1,
).validate(user.first_name, user=user)
self.assertEqual(cm.exception.messages, [expected_error % "first name"])
# Very low max_similarity is rejected.
msg = 'max_similarity must be at least 0.1'
... |
def format_file_in_place(
with open(src, "w", encoding=src_buffer.encoding) as f:
f.write(dst_contents)
elif write_back == write_back.DIFF:
src_name = f"{src.name} (original)"
dst_name = f"{src.name} (formatted)"
diff_contents = diff(src_contents, dst_contents, src_name... | def format_file_in_place(
with open(src, "w", encoding=src_buffer.encoding) as f:
f.write(dst_contents)
elif write_back == write_back.DIFF:
src_name = f"{src} (original)"
dst_name = f"{src} (formatted)"
diff_contents = diff(src_contents, dst_contents, src_name, dst_name... |
class BlackTestCase(unittest.TestCase):
self.assertTrue(ff(tmp_file, write_back=black.WriteBack.DIFF))
sys.stdout.seek(0)
actual = sys.stdout.read()
actual = actual.replace(tmp_file.name, "<stdin>")
finally:
sys.stdout = hold_stdout
os.unli... | class BlackTestCase(unittest.TestCase):
self.assertTrue(ff(tmp_file, write_back=black.WriteBack.DIFF))
sys.stdout.seek(0)
actual = sys.stdout.read()
actual = actual.replace(str(tmp_file), "<stdin>")
finally:
sys.stdout = hold_stdout
os.unli... |
class TestUtil(unittest.TestCase):
"playlist":[{"controls":{"all":null}}]
}''')
inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
json_code = js_to_json(inp)
self.assertEqual(json.loads(json_code... | class TestUtil(unittest.TestCase):
"playlist":[{"controls":{"all":null}}]
}''')
inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabaner... |
def js_to_json(code):
if v in ('true', 'false', 'null'):
return v
if v.startswith('"'):
return v
if v.startswith("'"):
v = v[1:-1]
v = re.sub(r"\\\\|\\'|\"", lambda m: {
'\\\\': '\\\\', | def js_to_json(code):
if v in ('true', 'false', 'null'):
return v
if v.startswith('"'):
v = re.sub(r"\\'", "'", v[1:-1])
elif v.startswith("'"):
v = v[1:-1]
v = re.sub(r"\\\\|\\'|\"", lambda m: {
'\\\\': '\\\\', |
from django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE
from django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin
from django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode
from django.utils.functional import cached_property
from django.utils.tree impo... | from django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE
from django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin
from django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode
from django.utils.functional import cached_property
from django.utils.regex_hel... |
class Query(BaseExpression):
alias = seen[int_model] = join_info.joins[-1]
return alias or seen[None]
def add_annotation(self, annotation, alias, is_summary=False, select=True):
"""Add a single annotation expression to the Query."""
annotation = annotation.resolve_expression(
... | class Query(BaseExpression):
alias = seen[int_model] = join_info.joins[-1]
return alias or seen[None]
def check_alias(self, alias):
if FORBIDDEN_ALIAS_PATTERN.search(alias):
raise ValueError(
"Column aliases cannot contain whitespace characters, quotation mar... |
class Query(BaseExpression):
else:
param_iter = iter([])
for name, entry in select.items():
entry = str(entry)
entry_params = []
pos = entry.find("%s") | class Query(BaseExpression):
else:
param_iter = iter([])
for name, entry in select.items():
self.check_alias(name)
entry = str(entry)
entry_params = []
pos = entry.find("%s") |
class AggregateTestCase(TestCase):
)
self.assertEqual(len(qs), 6)
def test_exists_extra_where_with_aggregate(self):
qs = Book.objects.annotate(
count=Count("id"), | class AggregateTestCase(TestCase):
)
self.assertEqual(len(qs), 6)
def test_alias_sql_injection(self):
crafted_alias = """injected_name" from "aggregation_author"; --"""
msg = (
"Column aliases cannot contain whitespace characters, quotation marks, "
"semicolo... |
class NonAggregateAnnotationTestCase(TestCase):
],
)
class AliasTests(TestCase):
@classmethod | class NonAggregateAnnotationTestCase(TestCase):
],
)
def test_alias_sql_injection(self):
crafted_alias = """injected_name" from "annotations_book"; --"""
msg = (
"Column aliases cannot contain whitespace characters, quotation marks, "
"semicolons, or SQL ... |
class AliasTests(TestCase):
with self.subTest(operation=operation):
with self.assertRaisesMessage(FieldError, msg):
getattr(qs, operation)("rating_alias") | class AliasTests(TestCase):
with self.subTest(operation=operation):
with self.assertRaisesMessage(FieldError, msg):
getattr(qs, operation)("rating_alias")
def test_alias_sql_injection(self):
crafted_alias = """injected_name" from "annotations_book"; --"""
... |
class ValuesExpressionsTests(TestCase):
[{"salary": 10}, {"salary": 20}, {"salary": 30}],
)
def test_values_expression_group_by(self):
# values() applies annotate() first, so values selected are grouped by
# id, not firstname. | class ValuesExpressionsTests(TestCase):
[{"salary": 10}, {"salary": 20}, {"salary": 30}],
)
def test_values_expression_alias_sql_injection(self):
crafted_alias = """injected_name" from "expressions_company"; --"""
msg = (
"Column aliases cannot contain whitespace cha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.