code stringlengths 12 2.05k | label_name stringlengths 6 8 | label int64 0 95 |
|---|---|---|
def publish(request, topic_id, pk=None):
initial = None
if pk: # todo: move to form
comment = get_object_or_404(
Comment.objects.for_access(user=request.user), pk=pk)
quote = markdown.quotify(comment.comment, comment.user.st.nickname)
initial = {'comment': quote}
user =... | CWE-601 | 11 |
def create_class_from_xml_string(target_class, xml_string):
"""Creates an instance of the target class from a string.
:param target_class: The class which will be instantiated and populated
with the contents of the XML. This class must have a c_tag and a
c_namespace class variable.
:param x... | CWE-611 | 13 |
def xsrf_token(self):
"""The XSRF-prevention token for the current user/session.
To prevent cross-site request forgery, we set an '_xsrf' cookie
and include the same '_xsrf' value as an argument with all POST
requests. If the two do not match, we reject the form submission
a... | CWE-203 | 38 |
def test_logout_post(self):
login_code = LoginCode.objects.create(user=self.user, code='foobar')
self.client.login(username=self.user.username, code=login_code.code)
response = self.client.post('/accounts/logout/?next=/accounts/login/')
self.assertEqual(response.status_code, 302)
... | CWE-312 | 71 |
def help_page(page_slug: str) -> str:
"""Fava's included documentation."""
if page_slug not in HELP_PAGES:
abort(404)
html = markdown2.markdown_path(
(resource_path("help") / (page_slug + ".md")),
extras=["fenced-code-blocks", "tables", "header-ids"],
)
return render_template... | CWE-79 | 1 |
async def handle_404(request, response):
if 'json' not in response.headers['Content-Type']:
if request.path.endswith('/'):
return web.HTTPFound(request.path.rstrip('/'))
return web.json_response({
"status": 404,
"message": "Page '{}' not found".format(request.path... | CWE-601 | 11 |
def get_pos_tagger(self):
from nltk.corpus import brown
regexp_tagger = RegexpTagger(
[
(r"^-?[0-9]+(.[0-9]+)?$", "CD"), # cardinal numbers
(r"(The|the|A|a|An|an)$", "AT"), # articles
(r".*able$", "JJ"), # adjectives
(r"... | CWE-1333 | 73 |
def get_valid_filename(value, replace_whitespace=True, chars=128):
"""
Returns the given string converted to a string that can be used for a clean
filename. Limits num characters to 128 max.
"""
if value[-1:] == u'.':
value = value[:-1]+u'_'
value = value.replace("/", "_").replace(":", "... | CWE-918 | 16 |
def sentences_stats(self, type, vId = None):
return self.sql_execute(self.prop_sentences_stats(type, vId)) | CWE-89 | 0 |
def feed_hot():
off = request.args.get("offset") or 0
all_books = ub.session.query(ub.Downloads, func.count(ub.Downloads.book_id)).order_by(
func.count(ub.Downloads.book_id).desc()).group_by(ub.Downloads.book_id)
hot_books = all_books.offset(off).limit(config.config_books_per_page)
entries = lis... | CWE-918 | 16 |
def _copy_file(self, in_path, out_path):
if not os.path.exists(in_path):
raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path)
try:
shutil.copyfile(in_path, out_path)
except shutil.Error:
traceback.print_exc()
raise er... | CWE-59 | 36 |
def check_read_formats(entry):
EXTENSIONS_READER = {'TXT', 'PDF', 'EPUB', 'CBZ', 'CBT', 'CBR', 'DJVU'}
bookformats = list()
if len(entry.data):
for ele in iter(entry.data):
if ele.format.upper() in EXTENSIONS_READER:
bookformats.append(ele.format.lower())
return bookf... | CWE-918 | 16 |
def ends_with(field: Term, value: str) -> Criterion:
return field.like(f"%{value}") | CWE-89 | 0 |
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 test_login_post(self):
login_code = LoginCode.objects.create(user=self.user, code='foobar', next='/private/')
response = self.client.post('/accounts/login/code/', {
'code': login_code.code,
})
self.assertEqual(response.status_code, 302)
self.assertEqual(resp... | CWE-312 | 71 |
def render_archived_books(page, sort_param):
order = sort_param[0] or []
archived_books = (
ub.session.query(ub.ArchivedBook)
.filter(ub.ArchivedBook.user_id == int(current_user.id))
.filter(ub.ArchivedBook.is_archived == True)
.all()
)
archived_book_ids = [archived_book.... | CWE-918 | 16 |
def download(url, location):
"""
Download files to the specified location.
:param url: The file URL.
:type url: str
:param location: The absolute path to where the downloaded
file is to be stored.
:type location: str
"""
request = urllib2.urlopen(url)
try:
content = r... | CWE-295 | 52 |
def check_username(username):
username = username.strip()
if ub.session.query(ub.User).filter(func.lower(ub.User.name) == username.lower()).scalar():
log.error(u"This username is already taken")
raise Exception (_(u"This username is already taken"))
return username | CWE-918 | 16 |
def get_cc_columns(filter_config_custom_read=False):
tmpcc = calibre_db.session.query(db.Custom_Columns)\
.filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all()
cc = []
r = None
if config.config_columns_to_ignore:
r = re.compile(config.config_columns_to_ignore)
for col i... | CWE-918 | 16 |
def runserverobj(method, docs=None, dt=None, dn=None, arg=None, args=None):
frappe.desk.form.run_method.runserverobj(method, docs=docs, dt=dt, dn=dn, arg=arg, args=args) | CWE-79 | 1 |
def make_homeserver(self, reactor, clock):
self.mock_federation = Mock()
self.mock_registry = Mock()
self.query_handlers = {}
def register_query_handler(query_type, handler):
self.query_handlers[query_type] = handler
self.mock_registry.register_query_handler = ... | CWE-601 | 11 |
def adv_search_serie(q, include_series_inputs, exclude_series_inputs):
for serie in include_series_inputs:
q = q.filter(db.Books.series.any(db.Series.id == serie))
for serie in exclude_series_inputs:
q = q.filter(not_(db.Books.series.any(db.Series.id == serie)))
return q | CWE-918 | 16 |
def _get_element_ptr_tuplelike(parent, key):
typ = parent.typ
assert isinstance(typ, TupleLike)
if isinstance(typ, StructType):
assert isinstance(key, str)
subtype = typ.members[key]
attrs = list(typ.tuple_keys())
index = attrs.index(key)
annotation = key
else:
... | CWE-190 | 19 |
def atom_timestamp(self):
return (self.timestamp.strftime('%Y-%m-%dT%H:%M:%S+00:00') or '') | CWE-918 | 16 |
def __init__(self):
self.reqparse = reqparse.RequestParser()
super(AuthenticatedService, self).__init__()
self.auth_dict = dict()
if current_user.is_authenticated():
roles_marshal = []
for role in current_user.roles:
roles_marshal.append(marsha... | CWE-601 | 11 |
def edit_all_cc_data(book_id, book, to_save):
cc = calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all()
return edit_cc_data(book_id, book, to_save, cc) | CWE-918 | 16 |
def send_mail(book_id, book_format, convert, kindle_mail, calibrepath, user_id):
"""Send email with attachments"""
book = calibre_db.get_book(book_id)
if convert == 1:
# returns None if success, otherwise errormessage
return convert_book_format(book_id, calibrepath, u'epub', book_format.low... | CWE-918 | 16 |
def test_login_unknown_code(self):
response = self.client.post('/accounts/login/code/', {
'code': 'unknown',
})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['form'].errors, {
'code': ['Login code is invalid. It might have expi... | CWE-312 | 71 |
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 test_login_get(self):
login_code = LoginCode.objects.create(user=self.user, code='foobar')
response = self.client.get('/accounts/login/code/', {
'code': login_code.code,
})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['form']... | CWE-312 | 71 |
def __init__(self, text, book):
self.text = text
self.book = book | CWE-918 | 16 |
def test_equal_body(self):
# check server doesnt close connection when body is equal to
# cl header
to_send = tobytes(
"GET /equal_body HTTP/1.0\n"
"Connection: Keep-Alive\n"
"Content-Length: 0\n"
"\n"
)
self.connect()
s... | CWE-444 | 41 |
def get_imports(self, *, prefix: str) -> Set[str]:
"""
Get a set of import strings that should be included when this property is used somewhere
Args:
prefix: A prefix to put before any relative (local) module names.
"""
imports = super().get_imports(prefix=prefix... | CWE-94 | 14 |
def get_cc_columns(filter_config_custom_read=False):
tmpcc = calibre_db.session.query(db.Custom_Columns)\
.filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all()
cc = []
r = None
if config.config_columns_to_ignore:
r = re.compile(config.config_columns_to_ignore)
for col i... | CWE-918 | 16 |
def feed_categoryindex():
shift = 0
off = int(request.args.get("offset") or 0)
entries = calibre_db.session.query(func.upper(func.substr(db.Tags.name, 1, 1)).label('id'))\
.join(db.books_tags_link).join(db.Books).filter(calibre_db.common_filters())\
.group_by(func.upper(func.substr(db.Tags.n... | CWE-918 | 16 |
def MD5(self,data:str):
sha = hashlib.md5(bytes(data.encode()))
hash = str(sha.digest())
return self.__Salt(hash,salt=self.salt) | CWE-916 | 34 |
def field_names(ctx, rd, field):
'''
Get a list of all names for the specified field
Optional: ?library_id=<default library>
'''
db, library_id = get_library_data(ctx, rd)[:2]
return tuple(db.all_field_names(field)) | CWE-502 | 15 |
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)
# don't evaluate context functions
args = [x.as_const(eval_ctx) for x in self.args]
if isinstance(ob... | CWE-134 | 54 |
def execute_cmd(cmd, from_async=False):
"""execute a request as python module"""
for hook in frappe.get_hooks("override_whitelisted_methods", {}).get(cmd, []):
# override using the first hook
cmd = hook
break
# via server script
if run_server_script_api(cmd):
return None
try:
method = get_attr(cmd)
ex... | CWE-79 | 1 |
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 innerfn(fn):
global whitelisted, guest_methods, xss_safe_methods, allowed_http_methods_for_whitelisted_func
whitelisted.append(fn)
allowed_http_methods_for_whitelisted_func[fn] = methods
if allow_guest:
guest_methods.append(fn)
if xss_safe:
xss_safe_methods.append(fn)
return fn | CWE-79 | 1 |
def sanitized_join(path: str, root: pathlib.Path) -> pathlib.Path:
result = (root / path).absolute()
if not str(result).startswith(str(root) + "/"):
raise ValueError("resulting path is outside root")
return result | CWE-22 | 2 |
def read_templates(
self,
filenames: List[str],
custom_template_directory: Optional[str] = None,
autoescape: bool = False, | CWE-79 | 1 |
def parse_configuration_file(config_path):
"""
Read the config file for an experiment to get ParlAI settings.
:param config_path:
path to config
:return:
parsed configuration dictionary
"""
result = {}
result["configs"] = {}
with open(config_path) as f:
cfg = ya... | CWE-502 | 15 |
def testPartialIndexInsert(self):
with ops.Graph().as_default() as G:
with ops.device('/cpu:0'):
x = array_ops.placeholder(dtypes.float32)
f = array_ops.placeholder(dtypes.float32)
v = array_ops.placeholder(dtypes.float32)
pi = array_ops.placeholder(dtypes.int64)
gi =... | CWE-843 | 43 |
def load_djpeg(self):
# ALTERNATIVE: handle JPEGs via the IJG command line utilities
import tempfile, os
file = tempfile.mktemp()
os.system("djpeg %s >%s" % (self.filename, file))
try:
self.im = Image.core.open_ppm(file)
finally:
try: os.unl... | CWE-59 | 36 |
def test_http10_list(self):
body = string.ascii_letters
to_send = (
"GET /list 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()
self.sock... | CWE-444 | 41 |
def _moderate(request, pk, field_name, to_value, action=None, message=None):
topic = get_object_or_404(Topic, pk=pk)
if is_post(request):
count = (
Topic.objects
.filter(pk=pk)
.exclude(**{field_name: to_value})
.update(**{
field_name: to_... | CWE-601 | 11 |
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 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 _rpsl_db_query_to_graphql_out(query: RPSLDatabaseQuery, info: GraphQLResolveInfo):
"""
Given an RPSL database query, execute it and clean up the output
to be suitable to return to GraphQL.
Main changes are:
- Enum handling
- Adding the asn and prefix fields if applicable
- Ensuring the ... | CWE-212 | 66 |
def _load_from(self, data: bytes) -> None:
if data.strip() == b'':
data = XMP_EMPTY # on some platforms lxml chokes on empty documents
def basic_parser(xml):
return parse(BytesIO(xml))
def strip_illegal_bytes_parser(xml):
return parse(BytesIO(re_xml_ill... | CWE-611 | 13 |
def test_received_error_from_parser(self):
from waitress.utilities import BadRequest
data = b"""\
GET /foobar HTTP/1.1
Transfer-Encoding: chunked
X-Foo: 1
garbage
"""
# header
result = self.parser.received(data)
# body
result = self.parser.received(data[result:])
... | CWE-444 | 41 |
def __init__(self, pidfile=None):
if not pidfile:
self.pidfile = "/tmp/%s.pid" % self.__class__.__name__.lower()
else:
self.pidfile = pidfile | CWE-59 | 36 |
def feed_authorindex():
shift = 0
off = int(request.args.get("offset") or 0)
entries = calibre_db.session.query(func.upper(func.substr(db.Authors.sort, 1, 1)).label('id'))\
.join(db.books_authors_link).join(db.Books).filter(calibre_db.common_filters())\
.group_by(func.upper(func.substr(db.Au... | CWE-918 | 16 |
def test_request_body_too_large_with_wrong_cl_http10(self):
body = "a" * self.toobig
to_send = "GET / HTTP/1.0\n" "Content-Length: 5\n\n"
to_send += body
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb")
# ... | CWE-444 | 41 |
def toggle_archived(book_id):
is_archived = change_archived_books(book_id, message="Book {} archivebit toggled".format(book_id))
if is_archived:
remove_synced_book(book_id)
return "" | CWE-918 | 16 |
def test_logout_unknown_token(self):
login_code = LoginCode.objects.create(user=self.user, code='foobar')
self.client.login(username=self.user.username, code=login_code.code)
response = self.client.post(
'/accounts-rest/logout/',
HTTP_AUTHORIZATION='Token unknown',
... | CWE-312 | 71 |
def stmt(self, stmt, msg=None):
mod = ast.Module([stmt])
self.mod(mod, msg) | CWE-125 | 47 |
def test_replay_banner_metadata(self, fmod):
""" Test adding metadata in replay banner (both framed and non-frame)
"""
resp = self.get('/test/20140103030321{0}/http://example.com/?example=1', fmod)
assert '<div>Custom Banner Here!</div>' in resp.text
assert '"some":"value"' i... | CWE-79 | 1 |
def run_custom_method(doctype, name, custom_method):
"""cmd=run_custom_method&doctype={doctype}&name={name}&custom_method={custom_method}"""
doc = frappe.get_doc(doctype, name)
if getattr(doc, custom_method, frappe._dict()).is_whitelisted:
frappe.call(getattr(doc, custom_method), **frappe.local.form_dict)
else:
... | CWE-79 | 1 |
def head_file(path):
try:
data_file, metadata = get_info(
path,
pathlib.Path(app.config["DATA_ROOT"])
)
stat = data_file.stat()
except (OSError, ValueError):
return flask.Response(
"Not Found",
404,
mimetype="text/plain... | CWE-22 | 2 |
def parse_soap_enveloped_saml(text, body_class, header_class=None):
"""Parses a SOAP enveloped SAML thing and returns header parts and body
:param text: The SOAP object as XML
:return: header parts and body as saml.samlbase instances
"""
envelope = ElementTree.fromstring(text)
assert envelope.t... | CWE-611 | 13 |
def delete(request, pk):
favorite = get_object_or_404(TopicFavorite, pk=pk, user=request.user)
favorite.delete()
return redirect(request.POST.get('next', favorite.topic.get_absolute_url())) | CWE-601 | 11 |
def sql_insert(self, sentence):
self.cursor.execute(sentence)
self.conn.commit()
return True | CWE-89 | 0 |
def camera_img_return_path(camera_unique_id, img_type, filename):
"""Return an image from stills or time-lapses"""
camera = Camera.query.filter(Camera.unique_id == camera_unique_id).first()
camera_path = assure_path_exists(
os.path.join(PATH_CAMERAS, '{uid}'.format(uid=camera.unique_id)))
if img... | CWE-22 | 2 |
def test_roundtrip_file(self):
f = open(self.filename, 'wb')
self.x.tofile(f)
f.close()
# NB. doesn't work with flush+seek, due to use of C stdio
f = open(self.filename, 'rb')
y = np.fromfile(f, dtype=self.dtype)
f.close()
assert_array_equal(y, self.x.... | CWE-59 | 36 |
def check_valid_db(cls, config_calibre_dir, app_db_path, config_calibre_uuid):
if not config_calibre_dir:
return False, False
dbpath = os.path.join(config_calibre_dir, "metadata.db")
if not os.path.exists(dbpath):
return False, False
try:
check_eng... | CWE-918 | 16 |
def _load_yamlconfig(self, configfile):
yamlconfig = None
try:
if self._recent_pyyaml():
# https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation
# only for 5.1+
yamlconfig = yaml.load(open(configfile), Loader=yaml.FullLoad... | CWE-502 | 15 |
def get_recipe_from_file(self, file):
recipe_html = file.getvalue().decode("utf-8")
recipe_json, recipe_tree, html_data, images = get_recipe_from_source(recipe_html, 'CookBookApp', self.request)
recipe = Recipe.objects.create(
name=recipe_json['name'].strip(),
creat... | CWE-918 | 16 |
def test_invalid_sum(self):
pos = dict(lineno=2, col_offset=3)
m = ast.Module([ast.Expr(ast.expr(**pos), **pos)])
with self.assertRaises(TypeError) as cm:
compile(m, "<test>", "exec")
self.assertIn("but got <_ast.expr", str(cm.exception)) | CWE-125 | 47 |
def malt_regex_tagger():
from nltk.tag import RegexpTagger
_tagger = RegexpTagger(
[
(r"\.$", "."),
(r"\,$", ","),
(r"\?$", "?"), # fullstop, comma, Qmark
(r"\($", "("),
(r"\)$", ")"), # round brackets
(r"\[$", "["),
... | CWE-1333 | 73 |
def expr(self, node, msg=None, *, exc=ValueError):
mod = ast.Module([ast.Expr(node)])
self.mod(mod, msg, exc=exc) | CWE-125 | 47 |
def make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver(
resource_for_federation=Mock(), http_client=None
)
return hs | CWE-601 | 11 |
def join_in(request, topic_id):
# todo: replace by create_access()?
# This is for topic creators who left their own topics and want to join again
topic = get_object_or_404(
Topic,
pk=topic_id,
user=request.user,
category_id=settings.ST_TOPIC_PRIVATE_CATEGORY_PK)
form = To... | CWE-601 | 11 |
def test_request_body_too_large_with_no_cl_http11(self):
body = "a" * self.toobig
to_send = "GET / HTTP/1.1\n\n"
to_send += body
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb")
# server trusts the content... | CWE-444 | 41 |
def clean_id(id_):
'''
Returns if the passed id is clean.
'''
if re.search(r'\.\.\{sep}'.format(sep=os.sep), id_):
return False
return True | CWE-22 | 2 |
def render_delete_book_result(book_format, jsonResponse, warning, book_id):
if book_format:
if jsonResponse:
return json.dumps([warning, {"location": url_for("editbook.edit_book", book_id=book_id),
"type": "success",
... | CWE-918 | 16 |
def needs_clamp(t, encoding):
if encoding not in (Encoding.ABI, Encoding.JSON_ABI):
return False
if isinstance(t, (ByteArrayLike, DArrayType)):
if encoding == Encoding.JSON_ABI:
# don't have bytestring size bound from json, don't clamp
return False
return True
... | CWE-190 | 19 |
def test_login(self):
login_code = LoginCode.objects.create(user=self.user, code='foobar', next='/private/')
response = self.client.post('/accounts-rest/login/code/', {
'code': login_code.code,
})
self.assertEqual(response.status_code, 200)
self.assertFalse(Logi... | CWE-312 | 71 |
def write_data_table(self, report, report_data, has_totals=True):
self.data.append([c["title"] for c in report.schema])
for datum in report_data:
datum = report.read_datum(datum)
self.data.append([format_data(data, format_iso_dates=True) for data in datum])
if has_to... | CWE-1236 | 12 |
def __init__(self, hs):
super().__init__(hs)
self.http_client = SimpleHttpClient(hs)
# We create a blacklisting instance of SimpleHttpClient for contacting identity
# servers specified by clients
self.blacklisting_http_client = SimpleHttpClient(
hs, ip_blacklist=... | CWE-601 | 11 |
def test_request_body_too_large_with_wrong_cl_http11_connclose(self):
body = "a" * self.toobig
to_send = "GET / HTTP/1.1\nContent-Length: 5\nConnection: close\n\n"
to_send += body
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock... | CWE-444 | 41 |
def append(self, key, value):
self.dict.setdefault(_hkey(key), []).append(
value if isinstance(value, unicode) else str(value)) | CWE-93 | 33 |
def testInvalidSparseTensor(self):
with test_util.force_cpu():
shape = [2, 2]
val = [0]
dense = constant_op.constant(np.zeros(shape, dtype=np.int32))
for bad_idx in [
[[-1, 0]], # -1 is invalid.
[[1, 3]], # ...so is 3.
]:
sparse = sparse_tensor.SparseTe... | CWE-476 | 46 |
def filter(self, names):
for name in [_hkey(n) for n in names]:
if name in self.dict:
del self.dict[name] | CWE-93 | 33 |
def upload_cover(request, book):
if 'btn-upload-cover' in request.files:
requested_file = request.files['btn-upload-cover']
# check for empty request
if requested_file.filename != '':
if not current_user.role_upload():
abort(403)
ret, message = helper.... | CWE-918 | 16 |
def test_basic_auth_invalid_credentials(self):
with self.assertRaises(InvalidStatusCode) as raised:
self.start_client(user_info=("hello", "ihateyou"))
self.assertEqual(raised.exception.status_code, 401) | CWE-203 | 38 |
def test_render_quoting(self):
w = widgets.AdminURLFieldWidget()
self.assertHTMLEqual(
conditional_escape(w.render('test', 'http://example.com/<sometag>some text</sometag>')),
'<p class="url">Currently:<a href="http://example.com/%3Csometag%3Esome%20text%3C/sometag%3E">http:/... | CWE-79 | 1 |
def exec_command(self, cmd, tmp_path, become_user=None, sudoable=False, executable=None, in_data=None):
''' run a command on the zone '''
if sudoable and self.runner.become and self.runner.become_method not in self.become_methods_supported:
raise errors.AnsibleError("Internal Error: thi... | CWE-59 | 36 |
def _re_word_boundary(r: str) -> str:
"""
Adds word boundary characters to the start and end of an
expression to require that the match occur as a whole word,
but do so respecting the fact that strings starting or ending
with non-word characters will change word boundaries.
"""
# we can't us... | CWE-331 | 72 |
def test_date_and_server(self):
to_send = "GET / HTTP/1.0\n" "Content-Length: 0\n\n"
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, echo = self._read_echo(fp)
self.assertline(line, "200", "OK",... | CWE-444 | 41 |
def test_multi_file(
self,
driver,
live_server,
freeze,
upload_file,
another_upload_file,
yet_another_upload_file, | CWE-22 | 2 |
def respond_error(self, context, exception):
context.respond_server_error()
stack = traceback.format_exc()
return """
<html>
<body>
<style>
body {
font-family: sans-serif;
color: #888;
... | CWE-79 | 1 |
def check_send_to_kindle_with_converter(formats):
bookformats = list()
if 'EPUB' in formats and 'MOBI' not in formats:
bookformats.append({'format': 'Mobi',
'convert': 1,
'text': _('Convert %(orig)s to %(format)s and send to Kindle',
... | CWE-918 | 16 |
def main():
app = create_app()
init_errorhandler()
app.register_blueprint(web)
app.register_blueprint(opds)
app.register_blueprint(jinjia)
app.register_blueprint(about)
app.register_blueprint(shelf)
app.register_blueprint(admi)
app.register_blueprint(remotelogin)
app.register_b... | CWE-918 | 16 |
def __init__(self, sourceName: str):
self.sourceName = sourceName
self.type = "file"
self.content = None | CWE-22 | 2 |
async def get_user_list(
*, client: Client, an_enum_value: List[AnEnum], some_date: Union[date, datetime], | CWE-94 | 14 |
def test_level_as_none(self):
body = [ast.ImportFrom(module='time',
names=[ast.alias(name='sleep')],
level=None,
lineno=0, col_offset=0)]
mod = ast.Module(body)
code = compile(mod, 'test', 'exec')
... | CWE-125 | 47 |
def sql_insert(self, sentence):
self.cursor.execute(sentence)
self.conn.commit()
return True | CWE-79 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.