code stringlengths 12 2.05k | label_name stringlengths 6 8 | label int64 0 95 |
|---|---|---|
async def apiui_command_help(request, user):
template = env.get_template('apiui_command_help.html')
if len(request.query_args) != 0:
data = urllib.parse.unquote(request.query_args[0][1])
print(data)
else:
data = ""
if use_ssl:
content = template.render(links=await respect... | CWE-79 | 1 |
def test_uses_xdg_config_home(self, apiver):
with WindowsSafeTempDir() as d:
account_info = self._make_sqlite_account_info(
env={
'HOME': self.home,
'USERPROFILE': self.home,
XDG_CONFIG_HOME_ENV_VAR: d,
}... | CWE-367 | 29 |
def read_config(self, config, **kwargs):
# FIXME: federation_domain_whitelist needs sytests
self.federation_domain_whitelist = None # type: Optional[dict]
federation_domain_whitelist = config.get("federation_domain_whitelist", None)
if federation_domain_whitelist is not None:
... | CWE-601 | 11 |
def __post_init__(self, title: str) -> None: # type: ignore
super().__post_init__()
reference = Reference.from_ref(title)
dedup_counter = 0
while reference.class_name in _existing_enums:
existing = _existing_enums[reference.class_name]
if self.values == exist... | CWE-94 | 14 |
def lcase(s):
try:
return unidecode.unidecode(s.lower())
except Exception as ex:
log = logger.create()
log.error_or_exception(ex)
return s.lower() | CWE-918 | 16 |
def preprocess_input_exprs_arg_string(input_exprs_str):
"""Parses input arg into dictionary that maps input key to python expression.
Parses input string in the format of 'input_key=<python expression>' into a
dictionary that maps each input_key to its python expression.
Args:
input_exprs_str: A string th... | CWE-94 | 14 |
def download_check_files(self, filelist):
# only admins and allowed users may download
if not cherrypy.session['admin']:
uo = self.useroptions.forUser(self.getUserId())
if not uo.getOptionValue('media.may_download'):
return 'not_permitted'
# make sure ... | CWE-22 | 2 |
def test_refresh_token(self):
token = self.xsrf_token
# A user's token is stable over time. Refreshing the page in one tab
# might update the cookie while an older tab still has the old cookie
# in its DOM. Simulate this scenario by passing a constant token
# in the body an... | CWE-203 | 38 |
def edit_book_comments(comments, book):
modif_date = False
if comments:
comments = clean_html(comments)
if len(book.comments):
if book.comments[0].text != comments:
book.comments[0].text = comments
modif_date = True
else:
if comments:
book.comm... | CWE-918 | 16 |
def delete_auth_token(user_id):
# Invalidate any prevously generated Kobo Auth token for this user.
ub.session.query(ub.RemoteAuthToken).filter(ub.RemoteAuthToken.user_id == user_id)\
.filter(ub.RemoteAuthToken.token_type==1).delete()
return ub.session_commit() | CWE-918 | 16 |
def is_whitelisted(self, method):
fn = getattr(self, method, None)
if not fn:
raise NotFound("Method {0} not found".format(method))
elif not getattr(fn, "whitelisted", False):
raise Forbidden("Method {0} not whitelisted".format(method)) | CWE-79 | 1 |
def is_whitelisted(method):
# check if whitelisted
if frappe.session['user'] == 'Guest':
if (method not in frappe.guest_methods):
frappe.throw(_("Not permitted"), frappe.PermissionError)
if method not in frappe.xss_safe_methods:
# strictly sanitize form_dict
# escapes html characters like <> except for ... | CWE-79 | 1 |
def open_soap_envelope(text):
"""
:param text: SOAP message
:return: dictionary with two keys "body"/"header"
"""
try:
envelope = ElementTree.fromstring(text)
except Exception as exc:
raise XmlParseError("%s" % exc)
assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE
... | CWE-611 | 13 |
def test_login_get_non_idempotent(self):
login_code = LoginCode.objects.create(user=self.user, code='foobar', next='/private/')
response = self.client.get('/accounts/login/code/', {
'code': login_code.code,
})
self.assertEqual(response.status_code, 302)
self.ass... | CWE-312 | 71 |
void AveragePool(const float* input_data, const Dims<4>& input_dims, int stride,
int pad_width, int pad_height, int filter_width,
int filter_height, float* output_data,
const Dims<4>& output_dims) {
AveragePool<Ac>(input_data, input_dims, stride, stride, pad_width, p... | CWE-835 | 42 |
def test_is_valid_hostname(self):
"""Tests that the is_valid_hostname function accepts only valid
hostnames (or domain names), with optional port number.
"""
self.assertTrue(is_valid_hostname("example.com"))
self.assertTrue(is_valid_hostname("EXAMPLE.COM"))
self.asse... | CWE-918 | 16 |
def test_dump(self):
node = ast.parse('spam(eggs, "and cheese")')
self.assertEqual(ast.dump(node),
"Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
"args=[Name(id='eggs', ctx=Load()), Constant(value='and cheese')], "
"keywords=[]))])"
)
... | CWE-125 | 47 |
def load(doc):
code = config.retrieveBoilerplateFile(doc, "bs-extensions")
exec(code, globals()) | CWE-22 | 2 |
def test_get_header_lines(self):
result = self._callFUT(b"slam\nslim")
self.assertEqual(result, [b"slam", b"slim"]) | CWE-444 | 41 |
def clean_code(self):
code = self.cleaned_data['code']
username = code.user.get_username()
user = authenticate(self.request, **{
get_user_model().USERNAME_FIELD: username,
'code': code.code,
})
if not user:
raise forms.ValidationError(
... | CWE-312 | 71 |
def mysql_starts_with(field: Field, value: str) -> Criterion:
return functions.Cast(field, SqlTypes.CHAR).like(f"{value}%") | CWE-89 | 0 |
def upload_new_file_gdrive(book_id, first_author, renamed_author, title, title_dir, original_filepath, filename_ext):
error = False
book = calibre_db.get_book(book_id)
file_name = get_valid_filename(title, chars=42) + ' - ' + \
get_valid_filename(first_author, chars=42) + \
f... | CWE-918 | 16 |
def history_data(start_time, offset=None):
"""Return history data.
Arguments:
start_time: select history starting from this timestamp.
offset: number of items to skip
"""
# history atimes are stored as ints, ensure start_time is not a float
start_time = int(start_time)
hist = ob... | CWE-79 | 1 |
def edit_user(user_id):
content = ub.session.query(ub.User).filter(ub.User.id == int(user_id)).first() # type: ub.User
if not content or (not config.config_anonbrowse and content.name == "Guest"):
flash(_(u"User not found"), category="error")
return redirect(url_for('admin.admin'))
language... | CWE-918 | 16 |
def check_valid_read_column(column):
if column != "0":
if not calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.id == column) \
.filter(and_(db.Custom_Columns.datatype == 'bool', db.Custom_Columns.mark_for_delete == 0)).all():
return False
return True | CWE-918 | 16 |
def _get_shared_models(self, args: "DictConfig") -> Dict[str, dict]:
with open(args.blueprint.model_opt_path) as f:
all_model_opts = yaml.load(f.read())
active_model_opts = {
model: opt
for model, opt in all_model_opts.items()
if self.conversations_nee... | CWE-502 | 15 |
def _getKeysForServer(self, server_name):
"""Get the signing key data from a homeserver.
:param server_name: The name of the server to request the keys from.
:type server_name: unicode
:return: The verification keys returned by the server.
:rtype: twisted.internet.defer.Def... | CWE-770 | 37 |
def render_prepare_search_form(cc):
# prepare data for search-form
tags = calibre_db.session.query(db.Tags)\
.join(db.books_tags_link)\
.join(db.Books)\
.filter(calibre_db.common_filters()) \
.group_by(text('books_tags_link.tag'))\
.order_by(db.Tags.name).all()
series... | CWE-918 | 16 |
def check_valid_restricted_column(column):
if column != "0":
if not calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.id == column) \
.filter(and_(db.Custom_Columns.datatype == 'text', db.Custom_Columns.mark_for_delete == 0)).all():
return False
return True | CWE-918 | 16 |
def upload_file(request):
path = tempfile.mkdtemp()
file_name = os.path.join(path, "%s.txt" % request.node.name)
with open(file_name, "w") as f:
f.write(request.node.name)
return file_name | CWE-22 | 2 |
def test_after_start_response_http11(self):
to_send = "GET /after_start_response HTTP/1.1\n\n"
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, response_body = read_http(fp)
self.assertline(line,... | CWE-444 | 41 |
def save(self, request, login_code_url='login_code', domain_override=None, extra_context=None):
login_code = models.LoginCode.create_code_for_user(
user=self.cleaned_data['user'],
next=self.cleaned_data['next'],
)
if not domain_override:
current_site = ge... | CWE-312 | 71 |
def feed_publisher(book_id):
off = request.args.get("offset") or 0
entries, __, pagination = calibre_db.fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), 0,
db.Books,
db.Books.publi... | CWE-918 | 16 |
def init_app(app):
from redash.authentication import (
google_oauth,
saml_auth,
remote_user_auth,
ldap_auth,
)
login_manager.init_app(app)
login_manager.anonymous_user = models.AnonymousUser
login_manager.REMEMBER_COOKIE_DURATION = settings.REMEMBER_COOKIE_DURATION
... | CWE-601 | 11 |
def lcase(s):
try:
return unidecode.unidecode(s.lower())
except Exception as ex:
log = logger.create()
log.error_or_exception(ex)
return s.lower() | CWE-918 | 16 |
def test_visitor(self):
class CustomVisitor(self.asdl.VisitorBase):
def __init__(self):
super().__init__()
self.names_with_seq = []
def visitModule(self, mod):
for dfn in mod.dfns:
self.visit(dfn)
def v... | CWE-125 | 47 |
def __post_init__(self) -> None:
super().__post_init__()
if self.default is not None:
self.default = f'"{self.default}"' | CWE-94 | 14 |
def adv_search_shelf(q, include_shelf_inputs, exclude_shelf_inputs):
q = q.outerjoin(ub.BookShelf, db.Books.id == ub.BookShelf.book_id)\
.filter(or_(ub.BookShelf.shelf == None, ub.BookShelf.shelf.notin_(exclude_shelf_inputs)))
if len(include_shelf_inputs) > 0:
q = q.filter(ub.BookShelf.shelf.in_... | CWE-918 | 16 |
def _make_sqlite_account_info(self, env=None, last_upgrade_to_run=None):
"""
Returns a new SqliteAccountInfo that has just read the data from the file.
:param dict env: Override Environment variables.
"""
# Override HOME to ensure hermetic tests
with mock.patch('os.e... | CWE-367 | 29 |
def edit_user_table():
visibility = current_user.view_settings.get('useredit', {})
languages = calibre_db.speaking_language()
translations = babel.list_translations() + [LC('en')]
allUser = ub.session.query(ub.User)
tags = calibre_db.session.query(db.Tags)\
.join(db.books_tags_link)\
... | CWE-918 | 16 |
def test_conf_set_no_read(self):
orig_parser = memcache.ConfigParser
memcache.ConfigParser = ExcConfigParser
exc = None
try:
app = memcache.MemcacheMiddleware(
FakeApp(), {'memcache_servers': '1.2.3.4:5'})
except Exception, err:
exc... | CWE-94 | 14 |
def format_runtime(runtime):
retVal = ""
if runtime.days:
retVal = format_unit(runtime.days, 'duration-day', length="long", locale=get_locale()) + ', '
mins, seconds = divmod(runtime.seconds, 60)
hours, minutes = divmod(mins, 60)
# ToDo: locale.number_symbols._data['timeSeparator'] -> locali... | CWE-918 | 16 |
def check_unrar(unrarLocation):
if not unrarLocation:
return
if not os.path.exists(unrarLocation):
return _('Unrar binary file not found')
try:
unrarLocation = [unrarLocation]
value = process_wait(unrarLocation, pattern='UNRAR (.*) freeware')
if value:
v... | CWE-918 | 16 |
def from_data(*, data: oai.Operation, path: str, method: str, tag: str) -> Union[Endpoint, ParseError]:
""" Construct an endpoint from the OpenAPI data """
if data.operationId is None:
return ParseError(data=data, detail="Path operations with operationId are not yet supported")
... | CWE-94 | 14 |
def parse_soap_enveloped_saml_thingy(text, expected_tags):
"""Parses a SOAP enveloped SAML thing and returns the thing as
a string.
:param text: The SOAP object as XML string
:param expected_tags: What the tag of the SAML thingy is expected to be.
:return: SAML thingy as a string
"""
envelo... | CWE-611 | 13 |
def test_received_headers_too_large(self):
from waitress.utilities import RequestHeaderFieldsTooLarge
self.parser.adj.max_request_header_size = 2
data = b"""\
GET /foobar HTTP/8.4
X-Foo: 1
"""
result = self.parser.received(data)
self.assertEqual(result, 30)
self.asse... | CWE-444 | 41 |
def test_uses_default(self):
account_info = self._make_sqlite_account_info(
env={
'HOME': self.home,
'USERPROFILE': self.home,
}
)
actual_path = os.path.abspath(account_info.filename)
assert os.path.join(self.home, '.b2_account_... | CWE-367 | 29 |
def save_cover(img, book_path):
content_type = img.headers.get('content-type')
if use_IM:
if content_type not in ('image/jpeg', 'image/png', 'image/webp', 'image/bmp'):
log.error("Only jpg/jpeg/png/webp/bmp files are supported as coverfile")
return False, _("Only jpg/jpeg/png/we... | CWE-918 | 16 |
def edit_single_cc_data(book_id, book, column_id, to_save):
cc = (calibre_db.session.query(db.Custom_Columns)
.filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions))
.filter(db.Custom_Columns.id == column_id)
.all())
return edit_cc_data(book_id, book, to_save, cc) | CWE-918 | 16 |
def language_overview():
if current_user.check_visibility(constants.SIDEBAR_LANGUAGE) and current_user.filter_language() == u"all":
order_no = 0 if current_user.get_view_property('language', 'dir') == 'desc' else 1
charlist = list()
languages = calibre_db.speaking_language(reverse_order=not ... | CWE-918 | 16 |
def get(image_file, domain, title, singer, album):
import ast
import base64
import json
import os
from html import unescape
import requests
api = f"http://{domain}:7873/bGVhdmVfcmlnaHRfbm93"
with open(image_file, "rb") as f:
im_bytes = f.read()
f.close()
im_b64 = b... | CWE-78 | 6 |
def get_share_link(recipe):
url = recipe.storage.url + '/ocs/v2.php/apps/files_sharing/api/v1/shares?format=json&path=' + recipe.file_path # noqa: E501
headers = {
"OCS-APIRequest": "true",
"Content-Type": "application/json"
}
r = requests.get(
... | CWE-918 | 16 |
def test_challenge(self):
rc, root, folder, object = self._makeTree()
response = FauxCookieResponse()
testURL = 'http://test'
request = FauxRequest(RESPONSE=response, URL=testURL,
ACTUAL_URL=testURL)
root.REQUEST = request
helper = self.... | CWE-601 | 11 |
def whitelist(f):
"""Decorator: Whitelist method to be called remotely via REST API."""
f.whitelisted = True
return f | CWE-79 | 1 |
def connectionLost(self, reason = connectionDone) -> None:
# If the maximum size was already exceeded, there's nothing to do.
if self.deferred.called:
return
if reason.check(ResponseDone):
self.deferred.callback(self.stream.getvalue())
elif reason.check(Poten... | CWE-770 | 37 |
def merge_list_book():
vals = request.get_json().get('Merge_books')
to_file = list()
if vals:
# load all formats from target book
to_book = calibre_db.get_book(vals[0])
vals.pop(0)
if to_book:
for file in to_book.data:
to_file.append(file.format)
... | CWE-918 | 16 |
def test_http10_listlentwo(self):
body = string.ascii_letters
to_send = (
"GET /list_lentwo HTTP/1.0\n"
"Connection: Keep-Alive\n"
"Content-Length: %d\n\n" % len(body)
)
to_send += body
to_send = tobytes(to_send)
self.connect()
... | CWE-444 | 41 |
def upload_new_file_gdrive(book_id, first_author, renamed_author, title, title_dir, original_filepath, filename_ext):
error = False
book = calibre_db.get_book(book_id)
file_name = get_valid_filename(title, chars=42) + ' - ' + \
get_valid_filename(first_author, chars=42) + \
f... | CWE-918 | 16 |
def __setitem__(self, key, value):
self.dict[_hkey(key)] = [value if isinstance(value, unicode) else
str(value)] | CWE-93 | 33 |
def move(request, topic_id):
topic = get_object_or_404(Topic, pk=topic_id)
form = CommentMoveForm(topic=topic, data=request.POST)
if form.is_valid():
comments = form.save()
for comment in comments:
comment_posted(comment=comment, mentions=None)
topic.decrease_commen... | CWE-601 | 11 |
def add_original_file(self, filename, original_filename, version):
with open(filename, 'rb') as f:
sample = base64.b64encode(f.read()).decode('utf-8')
original_file = MISPObject('original-imported-file')
original_file.add_attribute(**{'type': 'attachment', 'value': original_filen... | CWE-78 | 6 |
def test_after_start_response_http11_close(self):
to_send = tobytes(
"GET /after_start_response HTTP/1.1\n" "Connection: close\n\n"
)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, response_body = read_http(fp)
... | CWE-444 | 41 |
def testMultiple(self):
with ops.Graph().as_default() as G:
with ops.device('/cpu:0'):
x = array_ops.placeholder(dtypes.float32)
pi = array_ops.placeholder(dtypes.int64)
gi = array_ops.placeholder(dtypes.int64)
v = 2. * (array_ops.zeros([128, 128]) + x)
with ops.device(... | CWE-843 | 43 |
def __init__(self, protocol='http', hostname='localhost', port='8080',
subsystem=None, accept='application/json',
trust_env=None, verify=False): | CWE-295 | 52 |
def testOrdering(self):
import six
import random
with ops.Graph().as_default() as G:
with ops.device('/cpu:0'):
x = array_ops.placeholder(dtypes.int32, name='x')
pi = array_ops.placeholder(dtypes.int64, name='pi')
gi = array_ops.placeholder(dtypes.int64, name='gi')
wit... | CWE-843 | 43 |
def test_keepalive_http_10(self):
# Handling of Keep-Alive within HTTP 1.0
data = "Default: Don't keep me alive"
s = tobytes(
"GET / HTTP/1.0\n" "Content-Length: %d\n" "\n" "%s" % (len(data), data)
)
self.connect()
self.sock.send(s)
response = http... | CWE-444 | 41 |
def __init__(self, app, conf):
self.app = app
self.memcache_servers = conf.get('memcache_servers')
if not self.memcache_servers:
path = os.path.join(conf.get('swift_dir', '/etc/swift'),
'memcache.conf')
memcache_conf = ConfigParser()
... | CWE-94 | 14 |
def author_list():
if current_user.check_visibility(constants.SIDEBAR_AUTHOR):
if current_user.get_view_property('author', 'dir') == 'desc':
order = db.Authors.sort.desc()
order_no = 0
else:
order = db.Authors.sort.asc()
order_no = 1
entries = ... | CWE-918 | 16 |
def move_files_on_change(calibre_path, new_authordir, new_titledir, localbook, db_filename, original_filepath, path):
new_path = os.path.join(calibre_path, new_authordir, new_titledir)
new_name = get_valid_filename(localbook.title, chars=96) + ' - ' + new_authordir
try:
if original_filepath:
... | CWE-918 | 16 |
def _glob_to_re(glob: str, word_boundary: bool) -> Pattern:
"""Generates regex for a given glob.
Args:
glob
word_boundary: Whether to match against word boundaries or entire string.
"""
if IS_GLOB.search(glob):
r = re.escape(glob)
r = r.replace(r"\*", ".*?")
r =... | CWE-331 | 72 |
def atom_timestamp(self):
return (self.timestamp.strftime('%Y-%m-%dT%H:%M:%S+00:00') or '') | CWE-918 | 16 |
def setup_db(cls, config_calibre_dir, app_db_path):
cls.dispose()
if not config_calibre_dir:
cls.config.invalidate()
return False
dbpath = os.path.join(config_calibre_dir, "metadata.db")
if not os.path.exists(dbpath):
cls.config.invalidate()
... | CWE-918 | 16 |
def get_markdown(text):
if not text:
return ""
pattern = fr'([\[\s\S\]]*?)\(([\s\S]*?):([\[\s\S\]]*?)\)'
# Regex check
if re.match(pattern, text):
# get get value of group regex
scheme = re.search(pattern, text, re.IGNORECASE).group(2)
# scheme check
if scheme in... | CWE-79 | 1 |
def __init__(self, hs, tls_client_options_factory):
self.hs = hs
self.signing_key = hs.signing_key
self.server_name = hs.hostname
real_reactor = hs.get_reactor()
# We need to use a DNS resolver which filters out blacklisted IP
# addresses, to prevent DNS rebinding.
... | CWE-601 | 11 |
def test_get_conditions(self, freeze):
conditions = ClearableFileInput().get_conditions(None)
assert all(
condition in conditions
for condition in [
{"bucket": "test-bucket"},
{"success_action_status": "201"},
["starts-with", "$... | CWE-22 | 2 |
def save_cover_from_url(url, book_path):
try:
if not cli.allow_localhost:
# 127.0.x.x, localhost, [::1], [::ffff:7f00:1]
ip = socket.getaddrinfo(urlparse(url).hostname, 0)[0][4][0]
if ip.startswith("127.") or ip.startswith('::ffff:7f') or ip == "::1":
log.... | CWE-918 | 16 |
def admin():
version = updater_thread.get_current_version_info()
if version is False:
commit = _(u'Unknown')
else:
if 'datetime' in version:
commit = version['datetime']
tz = timedelta(seconds=time.timezone if (time.localtime().tm_isdst == 0) else time.altzone)
... | CWE-918 | 16 |
def extra_view_dispatch(request, view):
"""
Dispatch to an Xtheme extra view.
:param request: A request.
:type request: django.http.HttpRequest
:param view: View name.
:type view: str
:return: A response of some kind.
:rtype: django.http.HttpResponse
"""
theme = getattr(request,... | CWE-79 | 1 |
def prevent_open_redirect(next, host):
# Prevent an attacker from adding an arbitrary url after the
# _next variable in the request.
if next:
parts = next.split('/')
if ':' not in parts[0] and parts[:2] != ['', '']:
return next
elif len(par... | CWE-601 | 11 |
def download_list():
if current_user.get_view_property('download', 'dir') == 'desc':
order = ub.User.name.desc()
order_no = 0
else:
order = ub.User.name.asc()
order_no = 1
if current_user.check_visibility(constants.SIDEBAR_DOWNLOAD) and current_user.role_admin():
entr... | CWE-918 | 16 |
def home_get_dat():
d = db.sentences_stats('get_data')
n = db.sentences_stats('all_networks')
('clean_online')
rows = db.sentences_stats('get_clicks')
c = rows[0][0]
rows = db.sentences_stats('get_sessions')
s = rows[0][0]
rows = db.sentences_stats('get_online')
o = rows[0][0]
... | CWE-79 | 1 |
def make_homeserver(self, reactor, clock):
self.fetches = []
def get_file(destination, path, output_stream, args=None, max_size=None):
"""
Returns tuple[int,dict,str,int] of file length, response headers,
absolute URI, and response code.
"""
... | CWE-601 | 11 |
async def get_resolved_ref(self):
if hasattr(self, 'resolved_ref'):
return self.resolved_ref
try:
# Check if the reference is a valid SHA hash
self.sha1_validate(self.unresolved_ref)
except ValueError:
# The ref is a head/tag and we resolve it... | CWE-94 | 14 |
def test_request_body_too_large_with_no_cl_http10_keepalive(self):
body = "a" * self.toobig
to_send = "GET / HTTP/1.0\nConnection: Keep-Alive\n\n"
to_send += body
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0... | CWE-444 | 41 |
def test_before_start_response_http_10(self):
to_send = "GET /before_start_response HTTP/1.0\n\n"
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, response_body = read_http(fp)
self.assertline(li... | CWE-444 | 41 |
def testInputPreProcessErrorBadFormat(self):
input_str = 'inputx=file[[v1]v2'
with self.assertRaises(RuntimeError):
saved_model_cli.preprocess_inputs_arg_string(input_str)
input_str = 'inputx:file'
with self.assertRaises(RuntimeError):
saved_model_cli.preprocess_inputs_arg_string(input_str... | CWE-94 | 14 |
def class_instances_from_soap_enveloped_saml_thingies(text, modules):
"""Parses a SOAP enveloped header and body SAML thing and returns the
thing as a dictionary class instance.
:param text: The SOAP object as XML
:param modules: modules representing xsd schemas
:return: The body and headers as cla... | CWE-611 | 13 |
def create(request, topic_id):
topic = get_object_or_404(Topic, pk=topic_id)
form = FavoriteForm(user=request.user, topic=topic, data=request.POST)
if form.is_valid():
form.save()
else:
messages.error(request, utils.render_form_errors(form))
return redirect(request.POST.get('next',... | CWE-601 | 11 |
def __init__(self, *args, **kwargs):
super(BasketShareForm, self).__init__(*args, **kwargs)
try:
self.fields["image"] = GroupModelMultipleChoiceField(
queryset=kwargs["initial"]["images"],
initial=kwargs["initial"]["selected"],
widget=form... | CWE-601 | 11 |
def setUp(self):
self.reactor = ThreadedMemoryReactorClock()
self.hs_clock = Clock(self.reactor)
self.homeserver = setup_test_homeserver(
self.addCleanup, http_client=None, clock=self.hs_clock, reactor=self.reactor
) | CWE-601 | 11 |
def resend_activation_email(request):
if request.user.is_authenticated:
return redirect(request.GET.get('next', reverse('spirit:user:update')))
form = ResendActivationForm(data=post_data(request))
if is_post(request):
if not request.is_limited() and form.is_valid():
user = form.... | CWE-601 | 11 |
def read_http(fp): # pragma: no cover
try:
response_line = fp.readline()
except socket.error as exc:
fp.close()
# errno 104 is ENOTRECOVERABLE, In WinSock 10054 is ECONNRESET
if get_errno(exc) in (errno.ECONNABORTED, errno.ECONNRESET, 104, 10054):
raise ConnectionClo... | CWE-444 | 41 |
def load(doc):
code = config.retrieveBoilerplateFile(doc, "bs-extensions")
exec(code, globals()) | CWE-78 | 6 |
def sql_one_row(self, sentence, column):
self.cursor.execute(sentence)
return self.cursor.fetchone()[column] | CWE-79 | 1 |
def add_objects(db_book_object, db_object, db_session, db_type, add_elements):
changed = False
if db_type == 'languages':
db_filter = db_object.lang_code
elif db_type == 'custom':
db_filter = db_object.value
else:
db_filter = db_object.name
for add_element in add_elements:
... | CWE-918 | 16 |
def add_objects(db_book_object, db_object, db_session, db_type, add_elements):
changed = False
if db_type == 'languages':
db_filter = db_object.lang_code
elif db_type == 'custom':
db_filter = db_object.value
else:
db_filter = db_object.name
for add_element in add_elements:
... | CWE-918 | 16 |
def relative(self, relativePath) -> FileInputSource:
return FileInputSource(os.path.join(self.directory(), relativePath)) | CWE-78 | 6 |
def test_received(self):
inst, sock, map = self._makeOneWithMap()
inst.server = DummyServer()
inst.received(b"GET / HTTP/1.1\n\n")
self.assertEqual(inst.server.tasks, [inst])
self.assertTrue(inst.requests) | CWE-444 | 41 |
def find_double_newline(s):
"""Returns the position just after a double newline in the given string."""
pos1 = s.find(b"\n\r\n") # One kind of double newline
if pos1 >= 0:
pos1 += 3
pos2 = s.find(b"\n\n") # Another kind of double newline
if pos2 >= 0:
pos2 += 2
if pos1 >= 0:
... | CWE-444 | 41 |
def initSession(self, expire_on_commit=True):
self.session = self.session_factory()
self.session.expire_on_commit = expire_on_commit
self.update_title_sort(self.config) | CWE-918 | 16 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.