text stringlengths 79 3.72M |
|---|
<vulnerable_code>import pytest
from langchain.docstore.document import Document
from langchain.vectorstores.singlestoredb import SingleStoreDB
from tests.integration_tests.vectorstores.fake_embeddings import FakeEmbeddings
TEST_SINGLESTOREDB_URL = "root:pass@localhost:3306/db"
drop(table_name)
@pytest.mark.skip... |
<vulnerable_code> default_request_timeout: Optional[Union[float, Tuple[float, float]]] = None
"""Timeout for requests to Anthropic Completion API. Default is 600 seconds."""
anthropic_api_url: str = "https://api.anthropic.com"
anthropic_api_key: Optional[str] = None
)
"""Get custom api... |
<vulnerable_code> ) -> BaseSingleActionAgent:
"""Construct an agent from an LLM and tools."""
if not isinstance(llm, ChatOpenAI):
raise ValueError("Only supported with OpenAI models.")
prompt = cls.create_prompt(
extra_prompt_messages=extra_prompt_messages,
... |
<vulnerable_code>"""Loader that uses unstructured to load files."""
import collections
from abc import ABC, abstractmethod
from typing import IO, Any, List, Sequence, Union
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
"unstructured package not ... |
<vulnerable_code>)
def test_unstructured_pdf_loader() -> None:
"""Test unstructured loader."""
file_path = Path(__file__).parent.parent / "examples/hello.pdf"
loader = UnstructuredPDFLoader(str(file_path))<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my... |
<vulnerable_code>
def get_snippets(self, query: str) -> List[str]:
"""Run query through DuckDuckGo and return concatenated results."""
from duckduckgo_search import ddg
results = ddg(
query,
region=self.region,
safesearch=self.safesearch,
time... |
<vulnerable_code> def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
return {
**{"model_kwargs": self.model_kwargs},
}
<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase1... |
<vulnerable_code> """Process response from SerpAPI."""
if "error" in res.keys():
raise ValueError(f"Got error from SerpAPI: {res['error']}")
if "answer_box" in res.keys() and "answer" in res["answer_box"].keys():
toret = res["answer_box"]["answer"]
elif "answer_box... |
<vulnerable_code>CALL apoc.meta.data()
YIELD label, other, elementType, type, property
WHERE type = "RELATIONSHIP" AND elementType = "node"
RETURN "(:" + label + ")-[:" + property + "]->(:" + toString(other[0]) + ")" AS output
"""
<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few... |
<vulnerable_code>from langchain.chains.graph_qa.cypher import GraphCypherQAChain
from langchain.chains.loading import load_chain
from langchain.graphs import Neo4jGraph
from langchain.llms.openai import OpenAI
assert output == expected_output
def test_cypher_save_load() -> None:
"""Test saving and loading."... |
<vulnerable_code> * Modified 2009-2010 by Guido Vollbeding.
* libjpeg-turbo Modifications:
* Modified 2011 by Siarhei Siamashka.
* Copyright (C) 2015, 2017, D. R. Commander.
* For conditions of distribution and use, see the accompanying README.ijg
* file.
*
}
}
/* Allocate one-row buffer for returned dat... |
<vulnerable_code>import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@ResponseBody
@PostMapping("/save")
@RequiresPermissions("novel:friendLi... |
<vulnerable_code>package com.java2nb.novel.domain;
import java.io.Serializable;
import java.math.BigDecimal;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.java2nb.common.jsonserializer.LongToStringSerializer;
import org.springframework.format.annotation.DateTimeFormat;
import java.uti... |
<vulnerable_code>
#ifndef GPAC_DISABLE_AV_PARSERS
typedef struct
{
u64 pos;
size += tmp;
if (tmp!=255) break;
}
if (gf_bs_available(bs) < size) {
gf_bs_seek(bs, pos-3);
return GF_FALSE;
}
while (1) {
pos = (u32) gf_bs_get_position(ctx->bs);
u8 latm_buffer[4096];
u32 latm_frame_size = 4096;
... |
<vulnerable_code> // text
if (token = this.tokenizer.inlineText(src, inRawBlock, smartypants)) {
src = src.substring(token.raw.length);
prevChar = token.raw.slice(-1);
keepPrevChar = true;
tokens.push(token);
continue;<commit_title>[PATCH] Last few cases for uneven und... |
<vulnerable_code> code: /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,
br: /^( {2,}|\\)\n(?!\s*$)/,
del: noopTest,
text: /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*]|\b_|$)|[^ ](?= {2,}\n)))/,
punctuation: /^([\spunctuation])/
};
url: /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,
_back... |
<vulnerable_code>
RequestDispatcher dispatcher = request.getRequestDispatcher("Error"); //New Request Dispatcher
request.setAttribute("error", e.getMessage());
request.setAttribute("previous", "searchcontact");
dispatcher.forward(request, response);
... |
<vulnerable_code> * Calls doPost
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws Se... |
<vulnerable_code> } catch (MessagingException e) {
RequestDispatcher dispatcher = request.getRequestDispatcher("Error"); //New Request Dispatcher
request.setAttribute("error", e.getMessage());
request.setAttribute("previous", request.getServletPath());
dispatcher.f... |
<vulnerable_code> String query;
if (forename.isEmpty() && surname.isEmpty()) {
query = "";
} else if(forename.isEmpty()) {
query = "familyname LIKE '%" + surname + "' and";
} else if(surname.isEmpty()) {
query = "forename LIKE '%" + forename + "' and ";... |
<vulnerable_code> } catch (SQLException e) {
RequestDispatcher dispatcher = request.getRequestDispatcher("Error"); //New Request Dispatcher
request.setAttribute("error", e.getMessage());
request.setAttribute("previous", "searchcontact");
dispatc... |
<vulnerable_code>#include "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: cdf.c,v 1.45 2011/08/28 08:38:48 christos Exp $")
#endif
#include <assert.h>
cdf_read_sector(const cdf_info_t *info, void *buf, size_t offs, size_t len,
const cdf_header_t *h, cdf_secid_t id)
{
assert((size_t)CDF_SEC_SIZE(h) == len);
return ... |
<vulnerable_code>
#define CHUNK_HEADER_LEN STRUCT_OFFSET(chunk_t, mem[0])
/** Return the number of bytes needed to allocate a chunk to hold
* <b>memlen</b> bytes. */
#define CHUNK_ALLOC_SIZE(memlen) (CHUNK_HEADER_LEN + (memlen))
/** Return the number of usable bytes in a chunk allocated with
* malloc(<b>memlen</b>).... |
<vulnerable_code> expected = {"responses"} # White-list documented dict() object
# HTTPMessage, parse_headers(), and the HTTP status code constants are
# intentionally omitted for simplicity
denylist = {"HTTPMessage", "parse_headers"}
for name in dir(client):
if name.... |
<vulnerable_code>
outlen = backend._ffi.new("size_t *", buf_size)
buf = backend._ffi.new("unsigned char[]", buf_size)
res = crypt(pkey_ctx, buf, outlen, data, len(data))
if res <= 0:
_handle_rsa_enc_dec_error(backend, key)
return backend._ffi.buffer(buf)[: outlen[0]]
def _handle_rsa_enc_d... |
<vulnerable_code>
class PagePrefMfa(Controller):
@cherrypy.expose
def default(self, action=None, **kwargs):
form = MfaToggleForm(obj=self.app.currentuser)
if form.is_submitted():<commit_title>[PATCH] Ratelimit "Resend code to my email" in Two-Factor<commit_description><fixed_code>
class PagePre... |
<vulnerable_code> metavar='LIMIT',
type=int,
default=20,
help='maximum number of requests per hour that can be made on sensitive endpoints. When this limit is reached, an HTTP 429 message is returned to the user or the user is logged out. This security measure is used to limit brute force... |
<vulnerable_code> cherrypy.request.app._ratelimit_datastore = datastore
# If user is authenticated, use the username else use the ip address
token = (request.login or request.remote.ip) + '.' + (scope or request.path_info)
# Get hits count using datastore.
hits = datastore.get_and_increment(tok... |
<vulnerable_code>
/* parse header first */
p = msg->enc_buf.data;
msg->stun_hdr.msg_type = get16(p, 0);
msg->stun_hdr.msg_len = get16(p, 2);
memcpy(msg->stun_hdr.tran_id, p + 4, STUN_TID_BYTES);
len = msg->stun_hdr.msg_len;
p = msg->enc_buf.data + 20;
msg->stun_attr = NULL;
while (len > 0) {
i = s... |
<vulnerable_code>
/* Don't add a printk in there. printk relies on the PDA which is not initialized
yet. */
static void __init clear_bss(void)
{
memset(__bss_start, 0,
(unsigned long) __bss_stop - (unsigned long) __bss_start);<commit_title>[PATCH] x86/xen: Use clear_bss() for Xen PV guests<commit_descripti... |
<vulnerable_code>extern void early_xen_iret_patch(void);
/* First C function to be called on Xen boot */
asmlinkage __visible void __init xen_start_kernel(void)
{
struct physdev_set_iopl set_iopl;
unsigned long initrd_start = 0;
int rc;
if (!xen_start_info)
return;
__text_gen_insn(&early_xen_iret_patch,
JM... |
<vulnerable_code> psf_binheader_writef (psf, "44", BHW4 (0), BHW4 (0)) ; /* SMTPE format */
psf_binheader_writef (psf, "44", BHW4 (psf->instrument->loop_count), BHW4 (0)) ;
/* Loop count is signed 16 bit number so we limit it range to something sensible. */
psf->instrument->loop_count &= 0x7fff ;
for (tmp = 0... |
<vulnerable_code># Generate a demo config for the main front proxy. This sets up both HTTP and HTTPS listeners,
# as well as a listener for the double proxy to connect to via SSL client authentication.
generate_config(SCRIPT_DIR,
'envoy_front_proxy_v2.template.yaml',
'{}/envoy_front_prox... |
<vulnerable_code># Example usage:
#
# bazel run //tools/config_validation:validate_fragment -- \
# envoy.config.bootstrap.v3.Bootstrap $PWD/configs/google_com_proxy.v2.yaml
import json
import pathlib<commit_title>[PATCH 01/52] configs: Update configs v2 -> v3 (#13562)<commit_description>Signed-off-by: Ryan Northey <... |
<vulnerable_code>Example use:
./tools/envoy_collect.py --output-path=./envoy.tar -c
./configs/google_com_proxy.v2.yaml --service-node foo
<Ctrl-C>
tar -tvf ./envoy.tar
-rw------- htuch/eng 0 2017-08-13 21:13 access_0.log<commit_title>[PATCH 01/52] configs: Update configs v2 -> v3 (#13562)<commit_desc... |
<vulnerable_code># SHA. Otherwise, return the tarball download.
def GetVersionUrl(metadata):
# Figure out if it's a GitHub repo.
github_repo = None
github_version = None
for url in metadata['urls']:
if url.startswith('https://github.com/'):
components = url.split('/')
github_repo = f'https://git... |
<vulnerable_code><commit_title>[PATCH 01/52] configs: Update configs v2 -> v3 (#13562)<commit_description>Signed-off-by: Ryan Northey <ryan@synca.io><fixed_code>
# CLI tool to query GitHub API and compare with repository_locations.bzl. It:
# - Computes the release date of dependencies and fails if there is a mismatch
#... |
<vulnerable_code># Utilities for reasoning about dependencies.
from importlib.util import spec_from_loader, module_from_spec
from importlib.machinery import SourceFileLoader
'api/bazel/repository_locations_utils.bzl')
def RepositoryLocations():
spec_loader = repository_loca... |
<vulnerable_code>#
# python tools/deprecate_version/deprecate_version.py
#
# A GitHub access token must be set in GH_ACCESS_TOKEN. To create one, go to
# Settings -> Developer settings -> Personal access tokens in GitHub and create
# a token with public_repo scope. Keep this safe, it's broader than it needs to
# be th... |
<vulnerable_code>
if __name__ == '__main__':
access_token = os.getenv('GH_ACCESS_TOKEN')
if not access_token:
print('Missing GH_ACCESS_TOKEN')
sys.exit(1)
sys.exit(SyncAssignable(access_token))<commit_title>[PATCH 01/52] configs: Update configs v2 -> v3 (#13562)<commit_description>Signed-off-by: Ryan No... |
<vulnerable_code> # An exact version match is a hit.
if cpe.version == dep_version:
return True
# Allow the 'last_updated' dependency metadata to substitute for date.
# TODO(htuch): Make a finer grained distinction between Envoy update date and dependency
# release date in 'last_updated'.
# TODO(htuch): ... |
<vulnerable_code> def BuildCpe(self, cpe_str):
return cve_scan.Cpe.FromString(cpe_str)
def BuildDep(self, cpe_str, version=None, last_updated=None):
return {'cpe': cpe_str, 'version': version, 'last_updated': last_updated}
def CpeMatch(self, cpe_str, dep_cpe_str, version=None, last_updated=None):
ret... |
<vulnerable_code>
def GetExtensionMetadata(target):
r = subprocess.run(
[BUILDOZER_PATH, '-stdout', 'print security_posture status undocumented', target],
stdout=subprocess.PIPE,<commit_title>[PATCH 01/52] configs: Update configs v2 -> v3 (#13562)<commit_description>Signed-off-by: Ryan Northey <ryan@sync... |
<vulnerable_code>import { GET_CONTENT } from '@plone/volto/constants/ActionTypes';
import config from '@plone/volto/registry';
describe('api middleware helpers', () => {
it('addExpandersToPath should work as expected', () => {
config.settings.apiExpanders = [
{<commit_title>[PATCH] Skip failing tests<commi... |
<vulnerable_code>
void track_set_index(Track *track, int i, long ind)
{
if (i > MAXINDEX) {
fprintf(stderr, "too many indexes\n");
return;
}<commit_title>[PATCH] Check that the array index isn't negative. This fixes<commit_description><fixed_code>
void track_set_index(Track *track, int i, lo... |
<vulnerable_code> create_download_cache_folder, cache_download)
from pip.vcs import vcs
from pip.log import logger
__all__ = ['xmlrpclib_transport', 'get_file_content', 'urlopen',
'is_url', 'url_to_path', 'path_to_url', 'path_to_url2',
self._tunnel()
# wrap the sock... |
<vulnerable_code>from pip.backwardcompat import get_python_lib
import pip.exceptions
def running_under_virtualenv():
"""<commit_title>[PATCH] move cert_path to locations module<commit_description><fixed_code>
from pip.backwardcompat import get_python_lib
import pip.exceptions
cert_path = os.path.join(os.path.dir... |
<vulnerable_code> int key_len;
pjsip_transport *tp_ref = NULL;
transport *tp_entry = NULL;
/* If listener is specified, verify that the listener type matches
* the destination type.
if (!tp_iter->tp->is_shutdown &&
!tp_iter->tp->is_destroying)
{
if (tdata &&
(pjsip_transport_get_flag_fro... |
<vulnerable_code> return function;
}
JavascriptPromiseAsyncSpawnStepArgumentExecutorFunction* JavascriptLibrary::CreatePromiseAsyncSpawnStepArgumentExecutorFunction(JavascriptMethod entryPoint, JavascriptGenerator* generator, Var argument, JavascriptFunction* resolve, JavascriptFunction* reject, bool is... |
<vulnerable_code> JavascriptGenerator* gen = asyncSpawnExecutorFunction->GetGenerator();
JavascriptPromiseAsyncSpawnStepArgumentExecutorFunction* nextFunction = library->CreatePromiseAsyncSpawnStepArgumentExecutorFunction(EntryJavascriptPromiseAsyncSpawnStepNextExecutorFunction, gen, varCallArgs);
... |
<vulnerable_code><commit_title>[PATCH] [CVE-2017-0224, CVE-2017-0235] Chakra -<commit_description><fixed_code>
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt fil... |
<vulnerable_code>/* Find a utf-8 substring within the first len_bytes (not characters).
*
* - case-insensitive
* - needle must be zero-terminated, but hackstack need not be
* - haystack can be null-terminated
* - if haystack is shorter than len bytes, that'll end the search
* - if we hit invalid utf-8... |
<vulnerable_code> unsigned int pos;
unsigned int *list;
unsigned int count;
unsigned int rand;
};
struct rnd_state rnd_state;
};
} else {
state->list = cachep->random_seq;
state->count = count;
state->pos = 0;
state->rand = rand;
ret = true;
}
return ret;
/* Get the next entry on the list and rand... |
<vulnerable_code> * scanning order-- 1, 8, 16, etc.), then this will produce an encoded block
* larger than 200 bytes.
*/
#define BUFSIZE (DCTSIZE2 * 4)
#define LOAD_BUFFER() { \
if (state->free_in_buffer < BUFSIZE) { \<commit_title>[PATCH] Huffman enc.: Fix very rare local buffer overrun<commit_description>... d... |
<vulnerable_code>#include "addrtoname.h"
#include "extract.h"
struct aodv_rreq {
uint8_t rreq_type; /* AODV message type (1) */
uint8_t rreq_flags; /* various flags */
{
const struct aodv_hello *ah;
switch (ep->type) {
case AODV_EXT_HELLO:
ah = (const struct aodv_hello *)(const void *)ep;
ND_TCHECK(*ah);
... |
<vulnerable_code> AsyncGeneratorFunction
} = data;
const localWeakMapGet = LocalWeakMap.prototype.get;
function localUnexpected() {
return new VMError('Should not happen');
}
return value(error, sst);
};
wrappedPrepareStackTrace.set(value, newWrapped);
wrappedPrepareStackTrace.set(newWrapped, newWra... |
<vulnerable_code>
static void cleanup_connection(void)
{
if (close(ctx.sock) < 0) {
LOG_ERR("Could not close the socket");
}
memset(&ctx.fds[1], 0, sizeof(ctx.fds[1]));
ctx.nfds = 0;
ctx.sock = 0;
}
goto error;
}
if (!start_coap_client()) {
ctx.code_status = UPDATEHUB_NETWORKING_ERROR;
goto error;<comm... |
<vulnerable_code> char_u *start_leader, *end_leader;
int ret = OK;
char_u *alias;
/*
* Initialise variable so that clear_tv() can't mistake this for a
return FAIL;
}
switch (**arg)
{
/*
*/
if (ret == OK && evaluate && end_leader > start_leader)
ret = eval7_leader(rettv,... |
<vulnerable_code>
static int included_patches[] =
{ /* Add new patch number below this line */
/**/
4205,
/**/<commit_title>[PATCH] patch 8.2.4206: condition with many "(" causes a crash<commit_description>Problem: Condition with many "(" causes a crash.
Solution: Limit recursion to 1000.<fixed_code>
static... |
<vulnerable_code> # initial data
f = NamedTemporaryFile(delete=False, mode='wt')
data = """<table>
<tr>
<td>foo</td><td>bar</td>
</tr>
<tr>
<td>a</td><td>1</td>
</tr>
<tr>
<td>b</td><td>2</td>
</tr>
<tr>
<td>c</td><td>2</td>
</tr>
</table>"""
... |
<vulnerable_code> rc = bfa_port_get_stats(BFA_FCPORT(&bfad->bfa),
fcstats, bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (rc != BFA_STATUS_OK)
return NULL;
wait_for_completion(&fcomp.comp);
<commit_title>[PATCH] scsi: bfa: release allocated memory in case of error<commit_descript... |
<vulnerable_code> return NULL;
}
/* TODO: Add gdImageGetRowPtr and works with ptr at the row level
* for the true color and palette images
* new formats will simply work with ptr<commit_title>[PATCH] fix php 72494, invalid color index not handled, can lead to<commit_description><fixed_code>
return NULL;
}
... |
<vulnerable_code>}
function unescape(html) {
return html.replace(/&([#\w]+);/g, function(_, n) {
n = n.toLowerCase();
if (n === 'colon') return ':';
if (n.charAt(0) === '#') {<commit_title>[PATCH] added explicit matching for HTML entities to prevent XSS<commit_description><fixed_code>
}
function unescap... |
<vulnerable_code> 'zerver/migrations/0060_move_avatars_to_be_uid_based.py',
'zerver/migrations/0104_fix_unreads.py',
'zerver/migrations/0206_stream_rendered_description.py',
'pgroonga/migrations/0002_html_escape_subject.py',
]),
'description': "Don't ... |
<vulnerable_code><commit_title>[PATCH] CVE-2019-18933: Fix insecure account creation via social<commit_description><fixed_code>
# -*- coding: utf-8 -*-
# Generated by Django 1.11.24 on 2019-10-16 22:48
from __future__ import unicode_literals
from django.conf import settings
from django.contrib.auth import get_backends... |
<vulnerable_code><commit_title>[PATCH] CVE-2019-18933: Fix insecure account creation via social<commit_description><fixed_code>
# -*- coding: utf-8 -*-
# Generated by Django 1.11.26 on 2019-11-21 01:47
from __future__ import unicode_literals
from django.db import migrations
from typing import Any, List
class Migratio... |
<vulnerable_code> realm=get_realm('zephyr'),
return_data=dict()))
def test_email_auth_backend_disabled_password_auth(self) -> None:
user_profile = self.example_user('hamlet')
password = "testpassword"<commit_titl... |
<vulnerable_code> form['password'].field.required = False
if form.is_valid():
if password_auth_enabled(realm):
password = form.cleaned_data['password']
else:
# SSO users don't need no passwords
password = None
if realm_creation:<commit_title>[PATC... |
<vulnerable_code> if bot_type in (UserProfile.INCOMING_WEBHOOK_BOT, UserProfile.EMBEDDED_BOT) and service_name:
check_valid_bot_config(bot_type, service_name, config_data)
bot_profile = do_create_user(email=email, password='',
realm=user_profile.realm, full_name=full_nam... |
<vulnerable_code> if return_data is not None:
return_data['email_auth_disabled'] = True
return None
user_profile = common_get_active_user(username, realm, return_data=return_data)
if user_profile is None:<commit_title>[PATCH] CVE-2019-18933: Fix insecure account c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.