code
stringlengths
12
2.05k
label_name
stringlengths
6
8
label
int64
0
95
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 get_credits(request, project=None, component=None): """View for credits.""" if project is None: obj = None kwargs = {"translation__isnull": False} elif component is None: obj = get_project(request, project) kwargs = {"translation__component__project": obj} else: ...
CWE-79
1
def _get_index_absolute_path(index): return os.path.join(INDEXDIR, index)
CWE-22
2
def _get_unauth_response(self, request, reason): """ Get an error response (or raise a Problem) for a given request and reason message. :type request: Request. :param request: HttpRequest :type reason: Reason string. :param reason: str """ if request....
CWE-79
1
def _register_function_args(context: Context, sig: FunctionSignature) -> List[IRnode]: ret = [] # the type of the calldata base_args_t = TupleType([arg.typ for arg in sig.base_args]) # tuple with the abi_encoded args if sig.is_init_func: base_args_ofst = IRnode(0, location=DATA, typ=base_a...
CWE-190
19
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 test_filelike_longcl_http11(self): to_send = "GET /filelike_longcl HTTP/1.1\n\n" to_send = tobytes(to_send) self.connect() for t in range(0, 2): self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http...
CWE-444
41
def _normalize_path(self, path, prefix): if not path.startswith(os.path.sep): path = os.path.join(os.path.sep, path) normpath = os.path.normpath(path) return os.path.join(prefix, normpath[1:])
CWE-59
36
def custom_login(request, **kwargs): # Currently, Django 1.5 login view does not redirect somewhere if the user is logged in if request.user.is_authenticated: return redirect(request.GET.get('next', request.user.st.get_absolute_url())) if request.method == "POST" and request.is_limited(): r...
CWE-601
11
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 get_user_list( *, client: Client, an_enum_value: List[AnEnum], some_date: Union[date, datetime],
CWE-94
14
def test_parse_header_bad_content_length(self): data = b"GET /foobar HTTP/8.4\ncontent-length: abc" self.parser.parse_header(data) self.assertEqual(self.parser.body_rcv, None)
CWE-444
41
def opds_download_link(book_id, book_format): # I gave up with this: With enabled ldap login, the user doesn't get logged in, therefore it's always guest # workaround, loading the user from the request and checking it's download rights here # in case of anonymous browsing user is None user = load_user_f...
CWE-918
16
def test_credits_view_rst(self): response = self.get_credits("rst") self.assertEqual(response.status_code, 200) self.assertEqual( response.content.decode(), "\n\n* Czech\n\n * Weblate Test <weblate@example.org> (1)\n\n", )
CWE-79
1
def feed_get_cover(book_id): return get_book_cover(book_id)
CWE-918
16
def _create_database(self, last_upgrade_to_run): """ Make sure that the database is created and sets the file permissions. This should be done before storing any sensitive data in it. """ # Create the tables in the database conn = self._connect() try: ...
CWE-367
29
def load_event(self, args, filename, from_misp, stix_version): self.outputname = '{}.json'.format(filename) if len(args) > 0 and args[0]: self.add_original_file(filename, args[0], stix_version) try: event_distribution = args[1] if not isinstance(event_dist...
CWE-78
6
def check_xsrf_cookie(self): """Verifies that the ``_xsrf`` cookie matches the ``_xsrf`` argument. To prevent cross-site request forgery, we set an ``_xsrf`` cookie and include the same value as a non-cookie field with all ``POST`` requests. If the two do not match, we rejec...
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 Ghostscript(tile, size, fp, scale=1): """Render an image using Ghostscript""" # Unpack decoder tile decoder, tile, offset, data = tile[0] length, bbox = data #Hack to support hi-res rendering scale = int(scale) or 1 orig_size = size orig_bbox = bbox size = (size[0] * scale, siz...
CWE-59
36
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 values_from_list(values: List[str]) -> Dict[str, str]: """ Convert a list of values into dict of {name: value} """ output: Dict[str, str] = {} for i, value in enumerate(values): if value[0].isalpha(): key = value.upper() else: key ...
CWE-94
14
def setUp(self): shape = (2, 4, 3) rand = np.random.random self.x = rand(shape) + rand(shape).astype(np.complex)*1j self.x[0,:, 1] = [nan, inf, -inf, nan] self.dtype = self.x.dtype self.filename = tempfile.mktemp()
CWE-59
36
def create_option(self, name, value, label, selected, index, subindex=None, attrs=None): result = super(TagFormWidget, self).create_option( name=name, value=value, label=label, selected=selected, index=index, subindex=subindex, attrs=attrs ) result['attrs']['data-col...
CWE-79
1
def snake_case(value: str) -> str: return stringcase.snakecase(group_title(_sanitize(value)))
CWE-94
14
def test_notfilelike_nocl_http11(self): to_send = "GET /notfilelike_nocl 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, "200"...
CWE-444
41
def sentences_victim(self, type, data = None, sRun = 1, column = 0): if sRun == 2: return self.sql_insert(self.prop_sentences_victim(type, data)) elif sRun == 3: return self.sql_one_row(self.prop_sentences_victim(type, data), column) else: return self.sql_...
CWE-89
0
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 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 get_object_src_http(dataset, rel_path): path = _get_obj_abosolute_path(dataset, rel_path) response = send_file(path, cache_timeout=datetime.timedelta( days=365).total_seconds(), add_etags=True, conditiona...
CWE-22
2
def set_session_tracks(display_obj): """Save igv tracks as a session object. This way it's easy to verify that a user is requesting one of these files from remote_static view endpoint Args: display_obj(dict): A display object containing case name, list of genes, lucus and tracks """ session_tra...
CWE-918
16
def check_auth(username, password): try: username = username.encode('windows-1252') except UnicodeEncodeError: username = username.encode('utf-8') user = ub.session.query(ub.User).filter(func.lower(ub.User.name) == username.decode('utf-8').lower())...
CWE-918
16
def exec_command(self, cmd, tmp_path, become_user=None, sudoable=False, executable='/bin/sh', in_data=None): ''' run a command on the chroot ''' if sudoable and self.runner.become and self.runner.become_method not in self.become_methods_supported: raise errors.AnsibleError("Internal Err...
CWE-59
36
def all(cls, **kwargs): """Return a `Page` of instances of this `Resource` class from its general collection endpoint. Only `Resource` classes with specified `collection_path` endpoints can be requested with this method. Any provided keyword arguments are passed to the API e...
CWE-918
16
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_victim(self, type, data = None, sRun = 1, column = 0): if sRun == 2: return self.sql_insert(self.prop_sentences_victim(type, data)) elif sRun == 3: return self.sql_one_row(self.prop_sentences_victim(type, data), column) else: return self.sql_...
CWE-79
1
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 put_file(self, in_path, out_path): ''' transfer a file from local to chroot ''' out_path = self._normalize_path(out_path, self.get_jail_path()) vvv("PUT %s TO %s" % (in_path, out_path), host=self.jail) self._copy_file(in_path, out_path)
CWE-59
36
def basic_parser(xml): return parse(BytesIO(xml))
CWE-611
13
def get_vars_next(self): next = current.request.vars._next host = current.request.env.http_host if isinstance(next, (list, tuple)): next = next[0] if next and self.settings.prevent_open_redirect_attacks: return self.prevent_open_redirect(next, host) re...
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 test_fix_missing_locations(self): src = ast.parse('write("spam")') src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()), [ast.Str('eggs')], []))) self.assertEqual(src, ast.fix_missing_locations(src)) self.maxDiff = None ...
CWE-125
47
def test_module(self): body = [ast.Num(42)] x = ast.Module(body) self.assertEqual(x.body, body)
CWE-125
47
def _fill(self, target=1, more=None, untilend=False): if more: target = len(self._buf) + more while untilend or (len(self._buf) < target): # crutch to enable HttpRequest.from_bytes if self._sock is None: chunk = b"" else: ...
CWE-93
33
def prepare(self, reactor, clock, hs): # build a replication server server_factory = ReplicationStreamProtocolFactory(hs) self.streamer = hs.get_replication_streamer() self.server = server_factory.buildProtocol(None) # Make a new HomeServer object for the worker self...
CWE-601
11
def test_invalid_identitifer(self): m = ast.Module([ast.Expr(ast.Name(42, ast.Load()))]) ast.fix_missing_locations(m) with self.assertRaises(TypeError) as cm: compile(m, "<test>", "exec") self.assertIn("identifier must be of type str", str(cm.exception))
CWE-125
47
def __init__(self, *, openapi: GeneratorData) -> None: self.openapi: GeneratorData = openapi self.env: Environment = Environment(loader=PackageLoader(__package__), trim_blocks=True, lstrip_blocks=True) self.project_name: str = self.project_name_override or f"{utils.kebab_case(openapi.title)...
CWE-94
14
def feed_booksindex(): shift = 0 off = int(request.args.get("offset") or 0) entries = calibre_db.session.query(func.upper(func.substr(db.Books.sort, 1, 1)).label('id'))\ .filter(calibre_db.common_filters()).group_by(func.upper(func.substr(db.Books.sort, 1, 1))).all() elements = [] if off ==...
CWE-918
16
def get_search_results(self, term, offset=None, order=None, limit=None, allow_show_archived=False, config_read_column=False, *join):
CWE-918
16
def freeze(self, monkeypatch): """Freeze datetime and UUID.""" monkeypatch.setattr( "s3file.forms.S3FileInputMixin.upload_folder", os.path.join(storage.aws_location, "tmp"), )
CWE-22
2
def yet_another_upload_file(request): path = tempfile.mkdtemp() file_name = os.path.join(path, "yet_another_%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_received_control_line_finished_garbage_in_input(self): buf = DummyBuffer() inst = self._makeOne(buf) result = inst.received(b"garbage\n") self.assertEqual(result, 8) self.assertTrue(inst.error)
CWE-444
41
def test_get_response_requests_exception(self, mock_get): mock_response = mock.Mock() mock_response.status_code = 500 mock_response.text = "Server Error" exception_message = "Some requests exception" requests_exception = requests.RequestException(exception_message) mo...
CWE-918
16
def mysql_insensitive_starts_with(field: Field, value: str) -> Criterion: return functions.Upper(functions.Cast(field, SqlTypes.CHAR)).like(functions.Upper(f"{value}%"))
CWE-89
0
def image(self, request, pk): obj = self.get_object() if obj.get_space() != request.space: raise PermissionDenied(detail='You do not have the required permission to perform this action', code=403) serializer = self.serializer_class(obj, data=request.data, partial=True) ...
CWE-918
16
def HEAD(self, path): return self._request('HEAD', path)
CWE-295
52
def testRuntimeError(self, inputs, exception=errors.InvalidArgumentError, message=None):
CWE-125
47
def do_download_file(book, book_format, client, data, headers): if config.config_use_google_drive: #startTime = time.time() df = gd.getFileFromEbooksFolder(book.path, data.name + "." + book_format) #log.debug('%s', time.time() - startTime) if df: return gd.do_gdrive_downl...
CWE-918
16
def remote_static(): """Stream *large* static files with special requirements.""" file_path = request.args.get("file") or "." # Check that user is logged in or that file extension is valid if current_user.is_authenticated is False or file_path not in session.get("igv_tracks", []): LOG.warning(f...
CWE-918
16
def put_file(self, in_path, out_path): ''' transfer a file from local to chroot ''' if not out_path.startswith(os.path.sep): out_path = os.path.join(os.path.sep, out_path) normpath = os.path.normpath(out_path) out_path = os.path.join(self.chroot, normpath[1:]) v...
CWE-59
36
def del_project(request, client_id, project): if request.method == 'GET': client = Client.objects.get(id=client_id) try: scrapyd = get_scrapyd(client) result = scrapyd.delete_project(project=project) return JsonResponse(result) except ConnectionError: ...
CWE-78
6
def formatType(self): format_type = self.type.lower() if format_type == 'amazon': return u"Amazon" elif format_type.startswith("amazon_"): return u"Amazon.{0}".format(format_type[7:]) elif format_type == "isbn": return u"ISBN" elif format_t...
CWE-918
16
def test_template_render_with_noautoescape(self): """ Test if the autoescape value is getting passed to urlize_quoted_links filter. """ template = Template("{% load rest_framework %}" "{% autoescape off %}{{ content|urlize_quoted_links }}" ...
CWE-79
1
def pref_get(key): if get_user() is None: return "Authentication required", 401 if key in get_preferences(): return Response(json.dumps({'key': key, 'value': get_preferences()[key]})) else: return Response(json.dumps({'key': key, 'error': 'novalue'}))
CWE-79
1
def test_confirmation_obj_not_exist_error(self) -> None: """Since the key is a param input by the user to the registration endpoint, if it inserts an invalid value, the confirmation object won't be found. This tests if, in that scenario, we handle the exception by redirecting the user to ...
CWE-613
7
def test_constant_initializer_with_numpy(self): initializer = initializers.Constant(np.ones((3, 2))) model = sequential.Sequential() model.add(layers.Dense(2, input_shape=(3,), kernel_initializer=initializer)) model.add(layers.Dense(3)) model.compile( loss='mse', optimizer='sgd', ...
CWE-502
15
def test_request_body_too_large_with_wrong_cl_http10_keepalive(self): body = "a" * self.toobig to_send = "GET / HTTP/1.0\n" "Content-Length: 5\n" "Connection: Keep-Alive\n\n" to_send += body to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp ...
CWE-444
41
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 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-79
1
def __init__(self, bot): super().__init__() self.bot = bot self.config = Config.get_conf(self, identifier=2_113_674_295, force_registration=True) self.config.register_global(custom={}, tenorkey=None) self.config.register_guild(custom={}) self.try_after = None
CWE-502
15
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 constructObject(data): try: classBase = eval(data[""] + "." + data[""].title()) except NameError: logger.error("Don't know how to handle message type: \"%s\"", data[""]) return None try: returnObj = classBase() returnObj.decode(data) except KeyError as e: ...
CWE-94
14
def test_can_read_token_from_query_parameters(self): """Tests that Sydent correct extracts an auth token from query parameters""" self.sydent.run() request, _ = make_request( self.sydent.reactor, "GET", "/_matrix/identity/v2/hash_details?access_token=" + self.test_to...
CWE-918
16
def ready(self): pass
CWE-532
28
def test_file_logger_log_hyperparams(tmpdir): logger = CSVLogger(tmpdir) hparams = { "float": 0.3, "int": 1, "string": "abc", "bool": True, "dict": {"a": {"b": "c"}}, "list": [1, 2, 3], "namespace": Namespace(foo=Namespace(bar="buzz")), "layer": to...
CWE-502
15
def test_file_insert_submit_value(self, driver, live_server, upload_file, freeze): driver.get(live_server + self.url) file_input = driver.find_element(By.XPATH, "//input[@name='file']") file_input.send_keys(upload_file) assert file_input.get_attribute("name") == "file" save_b...
CWE-22
2
def _glob_matches(glob: str, value: str, word_boundary: bool = False) -> bool: """Tests if value matches glob. Args: glob value: String to test against glob. word_boundary: Whether to match against word boundaries or entire string. Defaults to False. """ try: ...
CWE-331
72
def test_register(self) -> None: reset_emails_in_zulip_realm() realm = get_realm("zulip") stream_names = [f"stream_{i}" for i in range(40)] for stream_name in stream_names: stream = self.make_stream(stream_name, realm=realm) DefaultStream.objects.create(strea...
CWE-613
7
def testInputParserBoth(self): x0 = np.array([[1], [2]]) input_path = os.path.join(test.get_temp_dir(), 'input.npz') np.savez(input_path, a=x0) x1 = np.ones([2, 10]) input_str = 'x0=' + input_path + '[a]' input_expr_str = 'x1=np.ones([2,10])' feed_dict = saved_model_cli.load_inputs_from_in...
CWE-94
14
void AveragePool(const uint8* input_data, const Dims<4>& input_dims, int stride, int pad_width, int pad_height, int filter_width, int filter_height, int32 output_activation_min, int32 output_activation_max, uint8* output_data, const Dims<4>& output_dim...
CWE-835
42
def test_in_generator(self): to_send = "GET /in_generator 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, "200", "OK", "HTTP/1.1...
CWE-444
41
def extension_element_from_string(xml_string): element_tree = ElementTree.fromstring(xml_string) return _extension_element_from_element_tree(element_tree)
CWE-611
13
def starts_with(field: Term, value: str) -> Criterion: return field.like(f"{value}%")
CWE-89
0
def table_get_locale(): locale = babel.list_translations() + [LC('en')] ret = list() current_locale = get_locale() for loc in locale: ret.append({'value': str(loc), 'text': loc.get_language_name(current_locale)}) return json.dumps(ret)
CWE-918
16
def test_large_body(self): # 1024 characters. body = "This string has 32 characters.\r\n" * 32 s = tobytes( "GET / HTTP/1.0\n" "Content-Length: %d\n" "\n" "%s" % (len(body), body) ) self.connect() self.sock.send(s) fp = self.sock.makefile("rb", 0) ...
CWE-444
41
def testPeek(self): 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) gi = array_ops.placeholder(dtypes.int64) p = array_ops.placeholder(dtypes.int32, name='p') with ...
CWE-843
43
def delete_user_session(user_id, session_key): try: log.info("Deleted session_key : " + session_key) session.query(User_Sessions).filter(User_Sessions.user_id==user_id, User_Sessions.session_key==session_key).delete() session.commit() except (e...
CWE-79
1
def authorized(): resp = google_remote_app().authorized_response() access_token = resp["access_token"] if access_token is None: logger.warning("Access token missing in call back request.") flash("Validation error. Please retry.") return redirect(url_for("redash.login")) profile...
CWE-601
11
def _sanitize(value: str) -> str: return re.sub(r"[^\w _-]+", "", value)
CWE-94
14
def test_received_nonsense_nothing(self): data = b"""\ """ result = self.parser.received(data) self.assertEqual(result, 2) self.assertTrue(self.parser.completed) self.assertEqual(self.parser.headers, {})
CWE-444
41
def generate_auth_token(user_id): host_list = request.host.rsplit(':') if len(host_list) == 1: host = ':'.join(host_list) else: host = ':'.join(host_list[0:-1]) if host.startswith('127.') or host.lower() == 'localhost' or host.startswith('[::ffff:7f'): warning = _('PLease access ...
CWE-918
16
def test_render_idn(self): w = widgets.AdminURLFieldWidget() self.assertHTMLEqual( conditional_escape(w.render('test', 'http://example-äüö.com')), '<p class="url">Currently:<a href="http://xn--example--7za4pnc.com">http://example-äüö.com</a><br />Change:<input class="vURLFiel...
CWE-79
1
def list_zones(self): pipe = subprocess.Popen([self.zoneadm_cmd, 'list', '-ip'], cwd=self.runner.basedir, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) #stdout, stderr = p.communicate() ...
CWE-59
36
def receivePing(): vrequest = request.form['id'] db.sentences_victim('report_online', [vrequest]) return json.dumps({'status' : 'OK', 'vId' : vrequest});
CWE-79
1
def get(self): if not current_user.is_authenticated(): return "Must be logged in to log out", 200 logout_user() return "Logged Out", 200
CWE-601
11
def DELETE(self, path, body=None, log_request_body=True): return self._request('DELETE', path, body=body, log_request_body=log_request_body)
CWE-295
52
def test_account_info_env_var_overrides_xdg_config_home(self): 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 test_received_preq_error(self): inst, sock, map = self._makeOneWithMap() inst.server = DummyServer() preq = DummyParser() inst.request = preq preq.completed = True preq.error = True inst.received(b"GET / HTTP/1.1\n\n") self.assertEqual(inst.request...
CWE-444
41
def authorize_and_redirect(request): if not request.GET.get("redirect"): return HttpResponse("You need to pass a url to ?redirect=", status=401) if not request.META.get("HTTP_REFERER"): return HttpResponse('You need to make a request that includes the "Referer" header.', status=400) referer...
CWE-601
11
def delete(request, pk): like = get_object_or_404(CommentLike, pk=pk, user=request.user) if is_post(request): like.delete() like.comment.decrease_likes_count() if is_ajax(request): url = reverse( 'spirit:comment:like:create', kwargs={'comment...
CWE-601
11