input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
---|---|---|
#vulnerable code
@Test
public void rendersSingleArtifact() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
MatcherAssert.assertThat(
XhtmlMatchers.xhtml(
new RsPrint(
new TkApp(farm).act(
new RqWithUser(
farm,
new RqFake(
"GET",
"/xml/C00000000?file=roles.xml"
)
)
)
).printBody()
),
XhtmlMatchers.hasXPaths("/roles")
);
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void rendersSingleArtifact() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
MatcherAssert.assertThat(
XhtmlMatchers.xhtml(
new RsPrint(
new TkApp(farm).act(
new RqWithUser.WithInit(
farm,
new RqFake(
"GET",
"/xml/C00000000?file=roles.xml"
)
)
)
).printBody()
),
XhtmlMatchers.hasXPaths("/roles")
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void setsJobs() throws Exception {
final FkFarm farm = new FkFarm(new FkProject());
final People people = new People(farm).bootstrap();
final String uid = "jobs";
people.invite(uid, uid);
final int jobs = Tv.TEN;
people.jobs(uid, jobs);
MatcherAssert.assertThat(
people.jobs(uid),
Matchers.is(jobs)
);
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void setsJobs() throws Exception {
final People people =
new People(new FkFarm(new FkProject())).bootstrap();
final String uid = "jobs";
people.invite(uid, uid);
final int jobs = Tv.TEN;
people.jobs(uid, jobs);
MatcherAssert.assertThat(
people.jobs(uid),
Matchers.is(jobs)
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
@SuppressWarnings("unchecked")
public void showsThatUserAlreadyHasMentor() throws IOException {
final Farm farm = FkFarm.props();
final People people = new People(farm).bootstrap();
final String mentor = "yoda";
final String applicant = "luke";
people.touch(mentor);
people.touch(applicant);
people.invite(applicant, mentor, true);
MatcherAssert.assertThat(
new TkApp(farm).act(
new RqWithBody(
new RqWithUser(
farm,
new RqFake("GET", "/join-post"),
applicant
),
"personality=INTJ-A&stackoverflow=187242"
)
),
Matchers.allOf(
new HmRsStatus(HttpURLConnection.HTTP_SEE_OTHER),
new HmRsHeader("Location", "/join"),
new HmRsHeader(
"Set-Cookie",
Matchers.hasItems(
Matchers.containsString(
URLEncoder.encode(
new FormattedText(
"You already have a mentor (@%s)",
mentor
).asString(),
StandardCharsets.UTF_8.displayName()
)
)
)
)
)
);
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
@SuppressWarnings("unchecked")
public void showsThatUserAlreadyHasMentor() throws IOException {
final Farm farm = new PropsFarm(new FkFarm());
final People people = new People(farm).bootstrap();
final String mentor = "yoda";
final String applicant = "luke";
people.touch(mentor);
people.touch(applicant);
people.invite(applicant, mentor, true);
MatcherAssert.assertThat(
new TkApp(farm).act(
new RqWithBody(
new RqWithUser(
farm,
new RqFake("GET", "/join-post"),
applicant
),
"personality=INTJ-A&stackoverflow=187242"
)
),
Matchers.allOf(
new HmRsStatus(HttpURLConnection.HTTP_SEE_OTHER),
new HmRsHeader("Location", "/join"),
new HmRsHeader(
"Set-Cookie",
Matchers.hasItems(
Matchers.containsString(
URLEncoder.encode(
new FormattedText(
"You already have a mentor (@%s)",
mentor
).asString(),
StandardCharsets.UTF_8.displayName()
)
)
)
)
)
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void rendersProfilePageWithoutRateInFirefox() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
final People people = new People(farm).bootstrap();
final String uid = "yegor256";
people.wallet(
uid, "test123"
);
MatcherAssert.assertThat(
new View(farm, String.format("/u/%s", uid)).html(),
Matchers.containsString("rate</a> is not defined")
);
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void rendersProfilePageWithoutRateInFirefox() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
final String uid = "yegor256";
MatcherAssert.assertThat(
new View(farm, String.format("/u/%s", uid)).html(),
Matchers.containsString("rate</a> is not defined")
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void parsesJson() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
final Take take = new TkGithub(
farm, (frm, github, event) -> "nothing"
);
MatcherAssert.assertThat(
take.act(
new RqWithBody(
new RqFake("POST", "/"),
String.format(
"payload=%s",
URLEncoder.encode(
"{\"foo\": \"bar\"}",
StandardCharsets.UTF_8.displayName()
)
)
)
),
new HmRsStatus(HttpURLConnection.HTTP_OK)
);
}
#location 8
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void parsesJson() throws Exception {
MatcherAssert.assertThat(
new TkGithub(
new PropsFarm(),
new Rebound.Fake("nothing")
).act(
new RqWithBody(
new RqFake("POST", "/"),
String.format(
"payload=%s",
URLEncoder.encode(
"{\"foo\": \"bar\"}",
StandardCharsets.UTF_8.displayName()
)
)
)
),
new HmRsStatus(HttpURLConnection.HTTP_OK)
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void rendersHomePage() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
final String uid = "yegor";
new Awards(farm, uid).bootstrap().add(
new FkProject(), 1, "gh:test/test#1", "reason"
);
new Agenda(farm, uid).bootstrap().add(
new FkProject(), "gh:test/test#2", "QA"
);
MatcherAssert.assertThat(
XhtmlMatchers.xhtml(new View(farm, "/u/Yegor256").html()),
XhtmlMatchers.hasXPaths("//xhtml:body")
);
}
#location 12
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void rendersHomePage() throws Exception {
final Farm farm = FkFarm.props();
final String uid = "yegor";
new Awards(farm, uid).bootstrap().add(
new FkProject(), 1, "gh:test/test#1", "reason"
);
new Agenda(farm, uid).bootstrap().add(
new FkProject(), "gh:test/test#2", "QA"
);
MatcherAssert.assertThat(
XhtmlMatchers.xhtml(new View(farm, "/u/Yegor256").html()),
XhtmlMatchers.hasXPaths("//xhtml:body")
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void rendersHomePage() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
MatcherAssert.assertThat(
XhtmlMatchers.xhtml(
new RsPrint(
new TkApp(farm).act(
new RqWithUser(
farm,
new RqFake(
"GET",
"/a/C00000000?a=pm/staff/roles"
)
)
)
).printBody()
),
XhtmlMatchers.hasXPaths("//xhtml:table")
);
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void rendersHomePage() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
MatcherAssert.assertThat(
XhtmlMatchers.xhtml(
new RsPrint(
new TkApp(farm).act(
new RqWithUser.WithInit(
farm,
new RqFake(
"GET",
"/a/C00000000?a=pm/staff/roles"
)
)
)
).printBody()
),
XhtmlMatchers.hasXPaths("//xhtml:table")
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void speed(final String uid, final double speed)
throws IOException {
if (!this.exists(uid)) {
throw new IllegalArgumentException(
new Par("Person @%s doesn't exist").say(uid)
);
}
try (final Item item = this.item()) {
new Xocument(item.path()).modify(
new Directives().xpath(
String.format(
"/people/person[@id='%s']",
uid
)
).addIf("speed").set(speed)
);
}
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
public void speed(final String uid, final double speed)
throws IOException {
this.checkExisting(uid);
try (final Item item = this.item()) {
new Xocument(item.path()).modify(
new Directives().xpath(
String.format(
"/people/person[@id='%s']",
uid
)
).addIf("speed").set(speed)
);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void setsEstimatesOnAssign() throws Exception {
final Project project = new FkProject();
final PropsFarm farm = new PropsFarm();
new Ledger(farm, project).bootstrap().add(
new Ledger.Transaction(
new Cash.S("$1000"),
"assets", "cash",
"income", "sponsor",
"There is some funding just arrived"
)
);
final String login = "dmarkov";
new Rates(project).bootstrap().set(login, new Cash.S("$50"));
final String job = "gh:yegor256/0pdd#19";
final Wbs wbs = new Wbs(project).bootstrap();
wbs.add(job);
wbs.role(job, "REV");
final Orders orders = new Orders(farm, project).bootstrap();
orders.assign(job, login, "0");
MatcherAssert.assertThat(
new Estimates(farm, project).bootstrap().get(job),
Matchers.equalTo(new Cash.S("$12.50"))
);
}
#location 22
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void setsEstimatesOnAssign() throws Exception {
final Project project = new FkProject();
final PropsFarm farm = new PropsFarm();
new Ledger(farm, project).bootstrap().add(
new Ledger.Transaction(
new Cash.S("$1000"),
"assets", "cash",
"income", "sponsor",
"There is some funding just arrived"
)
);
final String login = "dmarkov";
new Rates(project).bootstrap().set(login, new Cash.S("$50"));
final String job = "gh:yegor256/0pdd#19";
final Wbs wbs = new Wbs(project).bootstrap();
wbs.add(job);
wbs.role(job, "REV");
final Orders orders = new Orders(farm, project).bootstrap();
orders.assign(job, login, UUID.randomUUID().toString());
MatcherAssert.assertThat(
new Estimates(farm, project).bootstrap().get(job),
Matchers.equalTo(new Cash.S("$12.50"))
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void rendersHomePageViaHttp() throws Exception {
final Take app = new TkApp(new PropsFarm(new FkFarm()));
new FtRemote(app).exec(
home -> new JdkRequest(home)
.fetch()
.as(RestResponse.class)
.assertStatus(HttpURLConnection.HTTP_OK)
.as(XmlResponse.class)
.assertXPath("/xhtml:html/xhtml:body")
);
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void rendersHomePageViaHttp() throws Exception {
final Take app = new TkApp(FkFarm.props());
new FtRemote(app).exec(
home -> new JdkRequest(home)
.fetch()
.as(RestResponse.class)
.assertStatus(HttpURLConnection.HTTP_OK)
.as(XmlResponse.class)
.assertXPath("/xhtml:html/xhtml:body")
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
@Ignore
public void redirectOnError() throws Exception {
final Take take = new TkApp(new PropsFarm(new FkFarm()));
final String message = "Internal application error";
MatcherAssert.assertThat(
"Could not redirect on error",
new TextOf(
take.act(new RqFake("GET", "/?PsByFlag=PsGithub")).body()
).asString(),
new IsNot<>(
new StringContains(message)
)
);
MatcherAssert.assertThat(
"Could not redirect on error (with code)",
new TextOf(
take.act(
new RqFake(
"GET",
"/?PsByFlag=PsGithub&code=1257b773ba07221e7eb5"
)
).body()
).asString(),
new IsNot<>(
new StringContains(message)
)
);
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
@Ignore
public void redirectOnError() throws Exception {
final Take take = new TkApp(FkFarm.props());
final String message = "Internal application error";
MatcherAssert.assertThat(
"Could not redirect on error",
new TextOf(
take.act(new RqFake("GET", "/?PsByFlag=PsGithub")).body()
).asString(),
new IsNot<>(
new StringContains(message)
)
);
MatcherAssert.assertThat(
"Could not redirect on error (with code)",
new TextOf(
take.act(
new RqFake(
"GET",
"/?PsByFlag=PsGithub&code=1257b773ba07221e7eb5"
)
).body()
).asString(),
new IsNot<>(
new StringContains(message)
)
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void rendersProfilePageInFirefoxWithReputation() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
final String user = "yegor256";
MatcherAssert.assertThat(
new View(farm, String.format("/u/%s", user)).html(),
XhtmlMatchers.hasXPath(
String.format(
"//xhtml:a[@href='https://github.com/%s']",
user
)
)
);
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void rendersProfilePageInFirefoxWithReputation() throws Exception {
final Farm farm = FkFarm.props();
final String user = "yegor256";
MatcherAssert.assertThat(
new View(farm, String.format("/u/%s", user)).html(),
XhtmlMatchers.hasXPath(
String.format(
"//xhtml:a[@href='https://github.com/%s']",
user
)
)
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void votesHighIfMaxJobsReached() throws Exception {
final Project project = new FkProject();
final FkFarm farm = new FkFarm();
final String user = "g4s8";
final int total = 10;
final Pmo pmo = new Pmo(farm);
new Options(pmo, user).bootstrap().maxJobsInAgenda(total);
final Agenda agenda = new Agenda(pmo, user).bootstrap();
for (int num = 0; num < total; ++num) {
agenda.add(project, String.format("gh:test/test#%d", num), "DEV");
}
MatcherAssert.assertThat(
new VsOptionsMaxJobs(pmo).take(user, new StringBuilder(0)),
// @checkstyle MagicNumberCheck (1 lines)
Matchers.closeTo(1.0, 0.001)
);
}
#location 7
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void votesHighIfMaxJobsReached() throws Exception {
final Project project = new FkProject();
final String user = "g4s8";
final int total = 10;
final Pmo pmo = new Pmo(new FkFarm());
new Options(pmo, user).bootstrap().maxJobsInAgenda(total);
final Agenda agenda = new Agenda(pmo, user).bootstrap();
for (int num = 0; num < total; ++num) {
agenda.add(project, String.format("gh:test/test#%d", num), "DEV");
}
MatcherAssert.assertThat(
new VsOptionsMaxJobs(pmo).take(user, new StringBuilder(0)),
// @checkstyle MagicNumberCheck (1 lines)
Matchers.closeTo(1.0, 0.001)
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void rendersProjectPage() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
final Catalog catalog = new Catalog(new Pmo(farm)).bootstrap();
final String pid = "A1B2C3D4F";
catalog.add(pid, String.format("2017/07/%s/", pid));
catalog.link(pid, "github", "test/test");
final Roles roles = new Roles(
farm.find(String.format("@id='%s'", pid)).iterator().next()
).bootstrap();
final String uid = "yegor256";
roles.assign(uid, "PO");
new People(new Pmo(farm)).bootstrap().invite(uid, "mentor");
final Take take = new TkApp(farm);
MatcherAssert.assertThat(
XhtmlMatchers.xhtml(
new RsPrint(
take.act(
new RqWithHeaders(
new RqFake(
"GET",
String.format("/p/%s", pid)
),
// @checkstyle LineLength (1 line)
"Cookie: PsCookie=0975A5A5-F6DB193E-AF18000A-75726E3A-74657374-3A310005-6C6F6769-6E000879-65676F72-323536AE",
"Accept: application/xml"
)
)
).printBody()
),
XhtmlMatchers.hasXPaths(
String.format("/page[project='%s']", pid),
"/page/project_links[link='github:test/test']"
)
);
}
#location 14
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void rendersProjectPage() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
MatcherAssert.assertThat(
XhtmlMatchers.xhtml(
new RsPrint(
new TkApp(farm).act(
new RqWithHeaders(
new RqWithUser(
farm,
new RqFake(
"GET",
"/p/C00000000"
)
),
"Accept: application/xml"
)
)
).printBody()
),
XhtmlMatchers.hasXPaths(
"/page[project='C00000000']",
"/page/project_links[link='github:test/test']"
)
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public Input pdf(final String login) throws IOException {
final double share = this.share(login);
if (share == 0.0d) {
throw new IllegalArgumentException(
new Par(
"@%s doesn't have any share in %s"
).say(login, this.project.pid())
);
}
try (final Item item = this.item()) {
final Xocument doc = new Xocument(item);
String latex = new TextOf(
new ResourceOf("com/zerocracy/pm/cost/equity.tex")
).asString();
latex = latex
.replace("[OWNER]", login)
.replace("[ENTITY]", doc.xpath("//entity/text()", "PROJECT"))
.replace("[CEO]", doc.xpath("//ceo/text()", "CEO"))
.replace("[SHARE]", String.format("%.2f", share))
.replace("[SHARES]", String.format("%.0f", this.shares()))
.replace("[PAR]", this.par().toString());
return new Latex(latex).pdf();
}
}
#location 7
#vulnerability type RESOURCE_LEAK | #fixed code
public Input pdf(final String login) throws IOException {
final double share = this.share(login);
if (share == 0.0d) {
throw new IllegalArgumentException(
new Par(
"@%s doesn't have any share in %s"
).say(login, this.project.pid())
);
}
try (final Item item = this.item()) {
final Xocument doc = new Xocument(item);
String latex = new TextOf(
new ResourceOf("com/zerocracy/pm/cost/equity.tex")
).asString();
latex = latex
.replace("[OWNER]", login)
.replace("[ENTITY]", doc.xpath("//entity/text()", "PROJECT"))
.replace("[ADDRESS]", doc.xpath("//address/text()", "USA"))
.replace("[CEO]", doc.xpath("//ceo/text()", "CEO"))
.replace("[SHARE]", String.format("%.2f", share))
.replace("[SHARES]", String.format("%.0f", this.shares()))
.replace("[PAR]", this.par().toString());
return new Latex(latex).pdf();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void exec() throws IOException {
final Properties props = new Properties();
try (final InputStream input =
this.getClass().getResourceAsStream("/main.properties")) {
props.load(input);
}
final Github github = new RtGithub(
props.getProperty("github.0crat.login"),
props.getProperty("github.0crat.password")
);
final Map<String, SlackSession> sessions = new ConcurrentHashMap<>(0);
final Farm farm = new PingFarm(
new ReactiveFarm(
new SyncFarm(
new S3Farm(
new Region.Simple(
props.getProperty("s3.key"),
props.getProperty("s3.secret")
).bucket(props.getProperty("s3.bucket"))
)
),
Arrays.asList(
new StkNotify(github),
new com.zerocracy.radars.slack.StkNotify(sessions),
new StkAdd(github),
new StkRemove(),
new StkShow(),
new StkParent(),
new StkSet(),
new com.zerocracy.stk.pmo.profile.rate.StkShow(),
new com.zerocracy.stk.pmo.profile.wallet.StkSet(),
new com.zerocracy.stk.pmo.profile.wallet.StkShow(),
new com.zerocracy.stk.pmo.profile.skills.StkAdd(),
new com.zerocracy.stk.pmo.profile.skills.StkShow(),
new com.zerocracy.stk.pmo.profile.aliases.StkShow()
)
)
);
final GithubRadar ghradar = Main.ghradar(farm, github);
final SlackRadar skradar = Main.skradar(farm, props, sessions);
try (final Radar chain = new Radar.Chain(ghradar, skradar)) {
final GhookRadar gkradar = Main.gkradar(farm, github);
chain.start();
new FtCli(
new TkApp(
props,
new FkRegex("/slack", skradar),
new FkRegex("/alias", new TkAlias(farm)),
new FkRegex("/ghook", gkradar)
),
this.arguments
).start(Exit.NEVER);
}
}
#location 41
#vulnerability type RESOURCE_LEAK | #fixed code
public void exec() throws IOException {
final Properties props = new Properties();
try (final InputStream input =
this.getClass().getResourceAsStream("/main.properties")) {
props.load(input);
}
final Github github = new RtGithub(
props.getProperty("github.0crat.login"),
props.getProperty("github.0crat.password")
);
final Map<String, SlackSession> sessions = new ConcurrentHashMap<>(0);
final Farm farm = new PingFarm(
new ReactiveFarm(
new SyncFarm(
new S3Farm(
new Region.Simple(
props.getProperty("s3.key"),
props.getProperty("s3.secret")
).bucket(props.getProperty("s3.bucket"))
)
),
Stream.of(
new StkNotify(github),
new com.zerocracy.radars.slack.StkNotify(sessions),
new StkAdd(github),
new StkRemove(),
new StkShow(),
new StkParent(),
new StkSet(),
new com.zerocracy.stk.pmo.profile.rate.StkShow(),
new com.zerocracy.stk.pmo.profile.wallet.StkSet(),
new com.zerocracy.stk.pmo.profile.wallet.StkShow(),
new com.zerocracy.stk.pmo.profile.skills.StkAdd(),
new com.zerocracy.stk.pmo.profile.skills.StkShow(),
new com.zerocracy.stk.pmo.profile.aliases.StkShow()
).map(StkSafe::new).collect(Collectors.toList())
)
);
final GithubRadar ghradar = Main.ghradar(farm, github);
final SlackRadar skradar = Main.skradar(farm, props, sessions);
try (final Radar chain = new Radar.Chain(ghradar, skradar)) {
final GhookRadar gkradar = Main.gkradar(farm, github);
chain.start();
new FtCli(
new TkApp(
props,
new FkRegex("/slack", skradar),
new FkRegex("/alias", new TkAlias(farm)),
new FkRegex("/ghook", gkradar)
),
this.arguments
).start(Exit.NEVER);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
@SuppressWarnings("unchecked")
public void showsThatUserAlreadyHasMentor() throws IOException {
final Farm farm = new PropsFarm(new FkFarm());
final People people = new People(farm).bootstrap();
final String mentor = "yoda";
final String applicant = "luke";
people.touch(mentor);
people.touch(applicant);
people.invite(applicant, mentor, true);
MatcherAssert.assertThat(
new TkApp(farm).act(
new RqWithBody(
new RqWithUser(
farm,
new RqFake("GET", "/join-post"),
applicant
),
"personality=INTJ-A&stackoverflow=187242"
)
),
Matchers.allOf(
new HmRsStatus(HttpURLConnection.HTTP_SEE_OTHER),
new HmRsHeader("Location", "/join"),
new HmRsHeader(
"Set-Cookie",
Matchers.hasItems(
Matchers.containsString(
URLEncoder.encode(
new FormattedText(
"You already have a mentor (@%s)",
mentor
).asString(),
StandardCharsets.UTF_8.displayName()
)
)
)
)
)
);
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
@SuppressWarnings("unchecked")
public void showsThatUserAlreadyHasMentor() throws IOException {
final Farm farm = FkFarm.props();
final People people = new People(farm).bootstrap();
final String mentor = "yoda";
final String applicant = "luke";
people.touch(mentor);
people.touch(applicant);
people.invite(applicant, mentor, true);
MatcherAssert.assertThat(
new TkApp(farm).act(
new RqWithBody(
new RqWithUser(
farm,
new RqFake("GET", "/join-post"),
applicant
),
"personality=INTJ-A&stackoverflow=187242"
)
),
Matchers.allOf(
new HmRsStatus(HttpURLConnection.HTTP_SEE_OTHER),
new HmRsHeader("Location", "/join"),
new HmRsHeader(
"Set-Cookie",
Matchers.hasItems(
Matchers.containsString(
URLEncoder.encode(
new FormattedText(
"You already have a mentor (@%s)",
mentor
).asString(),
StandardCharsets.UTF_8.displayName()
)
)
)
)
)
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public boolean published(final String pid) throws IOException {
if (!this.exists(pid)) {
throw new IllegalArgumentException(
new Par(
"Project \"%s\" doesn't exist, can't check publish"
).say(pid)
);
}
try (final Item item = this.item()) {
return Boolean.parseBoolean(
new Xocument(item).xpath(
String.format(
"/catalog/project[@id='%s']/publish/text()",
pid
)
).get(0)
);
}
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
public boolean published(final String pid) throws IOException {
this.checkExist(pid);
try (final Item item = this.item()) {
return Boolean.parseBoolean(
new Xocument(item).xpath(
String.format(
"/catalog/project[@id='%s']/publish/text()",
pid
)
).get(0)
);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void rechargeIsRequiredIfCashBalanceIsLessThanLocked()
throws Exception {
final Project project = new FkProject();
final String job = "gh:test/test#1";
new Wbs(project).bootstrap().add(job);
final PropsFarm farm = new PropsFarm();
new Orders(farm, project).bootstrap().assign(job, "perf", "0");
new Estimates(farm, project).bootstrap()
.update(job, new Cash.S("$100"));
new Ledger(farm, project).bootstrap().add(
new Ledger.Transaction(
new Cash.S("$10"),
"assets", "cash",
"income", "test",
"Recharge#required test"
)
);
MatcherAssert.assertThat(
new Recharge(new PropsFarm(), project).required(),
new IsEqual<>(true)
);
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void rechargeIsRequiredIfCashBalanceIsLessThanLocked()
throws Exception {
final Project project = new FkProject();
final String job = "gh:test/test#1";
new Wbs(project).bootstrap().add(job);
final PropsFarm farm = new PropsFarm();
new Orders(farm, project).bootstrap()
.assign(job, "perf", UUID.randomUUID().toString());
new Estimates(farm, project).bootstrap()
.update(job, new Cash.S("$100"));
new Ledger(farm, project).bootstrap().add(
new Ledger.Transaction(
new Cash.S("$10"),
"assets", "cash",
"income", "test",
"Recharge#required test"
)
);
MatcherAssert.assertThat(
new Recharge(new PropsFarm(), project).required(),
new IsEqual<>(true)
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Response act(final RqRegex req) throws IOException {
final String pid = req.matcher().group(1);
final Catalog catalog = new Catalog(this.farm).bootstrap();
if (!catalog.exists(pid)) {
throw new RsForward(
new RsParFlash(
new Par("Project %s not found").say(pid),
Level.WARNING
)
);
}
return new RsWithHeaders(
new RsWithType(
new RsWithBody(
this.getClass().getResource("badge.svg")
),
"image/svg+xml"
),
"Cache-Control: no-cache",
String.format("X-Zerocracy-Project-ID: %s", pid)
);
}
#location 8
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
public Response act(final RqRegex req) throws IOException {
final Project project = new RqAnonProject(this.farm, req);
return new RsWithHeaders(
new RsWithType(
new RsWithBody(
this.getClass().getResource("badge.svg")
),
"image/svg+xml"
),
"Cache-Control: no-cache",
String.format("X-Zerocracy-Project-ID: %s", project.pid())
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void parsesJson() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
final Take take = new TkGithub(
farm, (frm, github, event) -> "nothing"
);
MatcherAssert.assertThat(
take.act(
new RqWithBody(
new RqFake("POST", "/"),
String.format(
"payload=%s",
URLEncoder.encode(
"{\"foo\": \"bar\"}",
StandardCharsets.UTF_8.displayName()
)
)
)
),
new HmRsStatus(HttpURLConnection.HTTP_OK)
);
}
#location 8
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void parsesJson() throws Exception {
MatcherAssert.assertThat(
new TkGithub(
new PropsFarm(),
new Rebound.Fake("nothing")
).act(
new RqWithBody(
new RqFake("POST", "/"),
String.format(
"payload=%s",
URLEncoder.encode(
"{\"foo\": \"bar\"}",
StandardCharsets.UTF_8.displayName()
)
)
)
),
new HmRsStatus(HttpURLConnection.HTTP_OK)
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void payZold() throws Exception {
MatcherAssert.assertThat(
new Zold(new PropsFarm()).pay(
"yegor256",
new Cash.S("$0.01"),
"ZoldITCase#payZold",
"none"
),
Matchers.not(Matchers.isEmptyString())
);
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void payZold() throws Exception {
final Farm farm = new PropsFarm();
final String target = "yegor256";
new Roles(new Pmo(farm)).bootstrap().assign(target, "PO");
MatcherAssert.assertThat(
new Zold(farm).pay(
target,
new Cash.S("$0.01"),
"ZoldITCase#payZold",
"none"
),
Matchers.not(Matchers.isEmptyString())
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void setsEstimatesOnAssign() throws Exception {
final Project project = new FkProject();
final PropsFarm farm = new PropsFarm();
new Ledger(farm, project).bootstrap().add(
new Ledger.Transaction(
new Cash.S("$1000"),
"assets", "cash",
"income", "sponsor",
"There is some funding just arrived"
)
);
final String login = "dmarkov";
new Rates(project).bootstrap().set(login, new Cash.S("$50"));
final String job = "gh:yegor256/0pdd#19";
final Wbs wbs = new Wbs(project).bootstrap();
wbs.add(job);
wbs.role(job, "REV");
final Orders orders = new Orders(farm, project).bootstrap();
orders.assign(job, login, "0");
MatcherAssert.assertThat(
new Estimates(farm, project).bootstrap().get(job),
Matchers.equalTo(new Cash.S("$12.50"))
);
}
#location 22
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void setsEstimatesOnAssign() throws Exception {
final Project project = new FkProject();
final PropsFarm farm = new PropsFarm();
new Ledger(farm, project).bootstrap().add(
new Ledger.Transaction(
new Cash.S("$1000"),
"assets", "cash",
"income", "sponsor",
"There is some funding just arrived"
)
);
final String login = "dmarkov";
new Rates(project).bootstrap().set(login, new Cash.S("$50"));
final String job = "gh:yegor256/0pdd#19";
final Wbs wbs = new Wbs(project).bootstrap();
wbs.add(job);
wbs.role(job, "REV");
final Orders orders = new Orders(farm, project).bootstrap();
orders.assign(job, login, UUID.randomUUID().toString());
MatcherAssert.assertThat(
new Estimates(farm, project).bootstrap().get(job),
Matchers.equalTo(new Cash.S("$12.50"))
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void rendersHomePage() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
MatcherAssert.assertThat(
XhtmlMatchers.xhtml(
new RsPrint(
new TkApp(farm).act(
new RqWithUser(
farm,
new RqFake("GET", "/identify")
)
)
).printBody()
),
XhtmlMatchers.hasXPaths("//xhtml:article")
);
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void rendersHomePage() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
MatcherAssert.assertThat(
XhtmlMatchers.xhtml(
new RsPrint(
new TkApp(farm).act(
new RqWithUser.WithInit(
farm,
new RqFake("GET", "/identify")
)
)
).printBody()
),
XhtmlMatchers.hasXPaths("//xhtml:article")
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public List<Dependency> dependencies(final Resource resource,
final Properties properties) {
if ("true".equals(properties.getProperty("computed", "false"))) {
log.info("Dependencies are pre-computed in properties");
Model model = new Model();
model = ThinPropertiesModelProcessor.process(model, properties);
return aetherDependencies(model.getDependencies());
}
initialize();
try {
log.info("Computing dependencies from pom and properties");
ProjectBuildingRequest request = getProjectBuildingRequest(properties);
request.setResolveDependencies(true);
synchronized (DependencyResolver.class) {
ProjectBuildingResult result = projectBuilder
.build(new PropertiesModelSource(properties, resource), request);
DependencyResolver.globals = null;
DependencyResolutionResult dependencies = result
.getDependencyResolutionResult();
if (!dependencies.getUnresolvedDependencies().isEmpty()) {
StringBuilder builder = new StringBuilder();
for (Dependency dependency : dependencies
.getUnresolvedDependencies()) {
List<Exception> errors = dependencies
.getResolutionErrors(dependency);
for (Exception exception : errors) {
if (builder.length() > 0) {
builder.append("\n");
}
builder.append(exception.getMessage());
}
}
throw new RuntimeException(builder.toString());
}
List<Dependency> output = runtime(dependencies.getDependencies());
if (log.isInfoEnabled()) {
for (Dependency dependency : output) {
log.info("Resolved: " + coordinates(dependency) + "="
+ dependency.getArtifact().getFile());
}
}
return output;
}
}
catch (ProjectBuildingException | NoLocalRepositoryManagerException e) {
throw new IllegalStateException("Cannot build model", e);
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public List<Dependency> dependencies(final Resource resource,
final Properties properties) {
if ("true".equals(properties.getProperty("computed", "false"))) {
log.info("Dependencies are pre-computed in properties");
Model model = new Model();
model = ThinPropertiesModelProcessor.process(model, properties);
return aetherDependencies(model.getDependencies(), properties);
}
initialize();
try {
log.info("Computing dependencies from pom and properties");
ProjectBuildingRequest request = getProjectBuildingRequest(properties);
request.setResolveDependencies(true);
synchronized (DependencyResolver.class) {
ProjectBuildingResult result = projectBuilder
.build(new PropertiesModelSource(properties, resource), request);
DependencyResolver.globals = null;
DependencyResolutionResult dependencies = result
.getDependencyResolutionResult();
if (!dependencies.getUnresolvedDependencies().isEmpty()) {
StringBuilder builder = new StringBuilder();
for (Dependency dependency : dependencies
.getUnresolvedDependencies()) {
List<Exception> errors = dependencies
.getResolutionErrors(dependency);
for (Exception exception : errors) {
if (builder.length() > 0) {
builder.append("\n");
}
builder.append(exception.getMessage());
}
}
throw new RuntimeException(builder.toString());
}
List<Dependency> output = runtime(dependencies.getDependencies());
if (log.isInfoEnabled()) {
for (Dependency dependency : output) {
log.info("Resolved: " + coordinates(dependency) + "="
+ dependency.getArtifact().getFile());
}
}
return output;
}
}
catch (ProjectBuildingException | NoLocalRepositoryManagerException e) {
throw new IllegalStateException("Cannot build model", e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
static Model process(Model model, Properties properties) {
if (properties != null) {
Set<String> exclusions = new HashSet<>();
for (String name : properties.stringPropertyNames()) {
if (name.startsWith("boms.")) {
String bom = properties.getProperty(name);
DefaultArtifact artifact = artifact(bom);
if (model.getDependencyManagement() == null) {
model.setDependencyManagement(new DependencyManagement());
}
boolean replaced = false;
for (Dependency dependency : model.getDependencyManagement()
.getDependencies()) {
if (ObjectUtils.nullSafeEquals(artifact.getArtifactId(),
dependency.getArtifactId())
&& ObjectUtils.nullSafeEquals(artifact.getGroupId(),
dependency.getGroupId())) {
dependency.setVersion(artifact.getVersion());
}
}
if (isParentBom(model, artifact)) {
model.getParent().setVersion(artifact.getVersion());
replaced = true;
}
if (!replaced) {
model.getDependencyManagement().addDependency(bom(artifact));
}
}
else if (name.startsWith("dependencies.")) {
String pom = properties.getProperty(name);
DefaultArtifact artifact = artifact(pom);
boolean replaced = false;
for (Dependency dependency : model.getDependencies()) {
if (ObjectUtils.nullSafeEquals(artifact.getArtifactId(),
dependency.getArtifactId())
&& ObjectUtils.nullSafeEquals(artifact.getGroupId(),
dependency.getGroupId())
&& artifact.getVersion() != null) {
dependency.setVersion(
StringUtils.hasLength(artifact.getVersion())
? artifact.getVersion()
: null);
dependency.setScope("runtime");
replaced = true;
}
}
if (!replaced) {
model.getDependencies().add(dependency(artifact));
}
}
else if (name.startsWith("exclusions.")) {
String pom = properties.getProperty(name);
exclusions.add(pom);
}
}
for (String pom : exclusions) {
Exclusion exclusion = exclusion(pom);
Dependency target = dependency(artifact(pom));
Dependency excluded = null;
for (Dependency dependency : model.getDependencies()) {
dependency.addExclusion(exclusion);
if (dependency.getGroupId().equals(target.getGroupId()) && dependency
.getArtifactId().equals(target.getArtifactId())) {
excluded = dependency;
}
}
if (excluded != null) {
model.getDependencies().remove(excluded);
}
}
}
return model;
}
#location 13
#vulnerability type NULL_DEREFERENCE | #fixed code
static Model process(Model model, Properties properties) {
if (properties != null) {
Set<String> exclusions = new HashSet<>();
for (String name : properties.stringPropertyNames()) {
if (name.startsWith("boms.")) {
String bom = properties.getProperty(name);
DefaultArtifact artifact = artifact(bom);
if (model.getDependencyManagement() == null) {
model.setDependencyManagement(new DependencyManagement());
}
boolean replaced = false;
for (Dependency dependency : model.getDependencyManagement()
.getDependencies()) {
if (ObjectUtils.nullSafeEquals(artifact.getArtifactId(),
dependency.getArtifactId())
&& ObjectUtils.nullSafeEquals(artifact.getGroupId(),
dependency.getGroupId())) {
dependency.setVersion(artifact.getVersion());
}
}
if (isParentBom(model, artifact)) {
model.getParent().setVersion(artifact.getVersion());
replaced = true;
}
if (!replaced) {
model.getDependencyManagement().addDependency(bom(artifact));
}
}
else if (name.startsWith("dependencies.")) {
String pom = properties.getProperty(name);
DefaultArtifact artifact = artifact(pom);
boolean replaced = false;
for (Dependency dependency : model.getDependencies()) {
if (ObjectUtils.nullSafeEquals(artifact.getArtifactId(),
dependency.getArtifactId())
&& ObjectUtils.nullSafeEquals(artifact.getGroupId(),
dependency.getGroupId())
&& artifact.getVersion() != null) {
dependency.setVersion(
StringUtils.hasLength(artifact.getVersion())
? artifact.getVersion()
: null);
dependency.setScope("runtime");
replaced = true;
}
}
if (!replaced) {
model.getDependencies().add(dependency(artifact));
}
}
else if (name.startsWith("exclusions.")) {
String pom = properties.getProperty(name);
exclusions.add(pom);
}
}
for (String pom : exclusions) {
Exclusion exclusion = exclusion(pom);
Dependency target = dependency(artifact(pom));
Dependency excluded = null;
for (Dependency dependency : model.getDependencies()) {
dependency.addExclusion(exclusion);
if (dependency.getGroupId().equals(target.getGroupId()) && dependency
.getArtifactId().equals(target.getArtifactId())) {
excluded = dependency;
}
}
if (excluded != null) {
model.getDependencies().remove(excluded);
}
}
}
for (Dependency dependency : new ArrayList<>(model.getDependencies())) {
if ("test".equals(dependency.getScope())
|| "provided".equals(dependency.getScope())) {
model.getDependencies().remove(dependency);
}
}
return model;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public List<Dependency> dependencies(final Resource resource,
final Properties properties) {
if ("true".equals(properties.getProperty("computed", "false"))) {
log.info("Dependencies are pre-computed in properties");
Model model = new Model();
model = ThinPropertiesModelProcessor.process(model, properties);
return aetherDependencies(model.getDependencies());
}
initialize();
try {
log.info("Computing dependencies from pom and properties");
ProjectBuildingRequest request = getProjectBuildingRequest(properties);
request.setResolveDependencies(true);
synchronized (DependencyResolver.class) {
ProjectBuildingResult result = projectBuilder
.build(new PropertiesModelSource(properties, resource), request);
DependencyResolver.globals = null;
DependencyResolutionResult dependencies = result
.getDependencyResolutionResult();
if (!dependencies.getUnresolvedDependencies().isEmpty()) {
StringBuilder builder = new StringBuilder();
for (Dependency dependency : dependencies
.getUnresolvedDependencies()) {
List<Exception> errors = dependencies
.getResolutionErrors(dependency);
for (Exception exception : errors) {
if (builder.length() > 0) {
builder.append("\n");
}
builder.append(exception.getMessage());
}
}
throw new RuntimeException(builder.toString());
}
List<Dependency> output = runtime(dependencies.getDependencies());
if (log.isInfoEnabled()) {
for (Dependency dependency : output) {
log.info("Resolved: " + coordinates(dependency) + "="
+ dependency.getArtifact().getFile());
}
}
return output;
}
}
catch (ProjectBuildingException | NoLocalRepositoryManagerException e) {
throw new IllegalStateException("Cannot build model", e);
}
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public List<Dependency> dependencies(final Resource resource,
final Properties properties) {
if ("true".equals(properties.getProperty("computed", "false"))) {
log.info("Dependencies are pre-computed in properties");
Model model = new Model();
model = ThinPropertiesModelProcessor.process(model, properties);
return aetherDependencies(model.getDependencies(), properties);
}
initialize();
try {
log.info("Computing dependencies from pom and properties");
ProjectBuildingRequest request = getProjectBuildingRequest(properties);
request.setResolveDependencies(true);
synchronized (DependencyResolver.class) {
ProjectBuildingResult result = projectBuilder
.build(new PropertiesModelSource(properties, resource), request);
DependencyResolver.globals = null;
DependencyResolutionResult dependencies = result
.getDependencyResolutionResult();
if (!dependencies.getUnresolvedDependencies().isEmpty()) {
StringBuilder builder = new StringBuilder();
for (Dependency dependency : dependencies
.getUnresolvedDependencies()) {
List<Exception> errors = dependencies
.getResolutionErrors(dependency);
for (Exception exception : errors) {
if (builder.length() > 0) {
builder.append("\n");
}
builder.append(exception.getMessage());
}
}
throw new RuntimeException(builder.toString());
}
List<Dependency> output = runtime(dependencies.getDependencies());
if (log.isInfoEnabled()) {
for (Dependency dependency : output) {
log.info("Resolved: " + coordinates(dependency) + "="
+ dependency.getArtifact().getFile());
}
}
return output;
}
}
catch (ProjectBuildingException | NoLocalRepositoryManagerException e) {
throw new IllegalStateException("Cannot build model", e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public List<Dependency> dependencies(final Resource resource,
final Properties properties) {
if ("true".equals(properties.getProperty("computed", "false"))) {
log.info("Dependencies are pre-computed in properties");
Model model = new Model();
model = ThinPropertiesModelProcessor.process(model, properties);
return aetherDependencies(model.getDependencies());
}
initialize();
try {
log.info("Computing dependencies from pom and properties");
ProjectBuildingRequest request = getProjectBuildingRequest(properties);
request.setResolveDependencies(true);
synchronized (DependencyResolver.class) {
ProjectBuildingResult result = projectBuilder
.build(new PropertiesModelSource(properties, resource), request);
DependencyResolver.globals = null;
DependencyResolutionResult dependencies = result
.getDependencyResolutionResult();
if (!dependencies.getUnresolvedDependencies().isEmpty()) {
StringBuilder builder = new StringBuilder();
for (Dependency dependency : dependencies
.getUnresolvedDependencies()) {
List<Exception> errors = dependencies
.getResolutionErrors(dependency);
for (Exception exception : errors) {
if (builder.length() > 0) {
builder.append("\n");
}
builder.append(exception.getMessage());
}
}
throw new RuntimeException(builder.toString());
}
List<Dependency> output = runtime(dependencies.getDependencies());
if (log.isInfoEnabled()) {
for (Dependency dependency : output) {
log.info("Resolved: " + coordinates(dependency) + "="
+ dependency.getArtifact().getFile());
}
}
return output;
}
}
catch (ProjectBuildingException | NoLocalRepositoryManagerException e) {
throw new IllegalStateException("Cannot build model", e);
}
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public List<Dependency> dependencies(final Resource resource,
final Properties properties) {
if ("true".equals(properties.getProperty("computed", "false"))) {
log.info("Dependencies are pre-computed in properties");
Model model = new Model();
model = ThinPropertiesModelProcessor.process(model, properties);
return aetherDependencies(model.getDependencies(), properties);
}
initialize();
try {
log.info("Computing dependencies from pom and properties");
ProjectBuildingRequest request = getProjectBuildingRequest(properties);
request.setResolveDependencies(true);
synchronized (DependencyResolver.class) {
ProjectBuildingResult result = projectBuilder
.build(new PropertiesModelSource(properties, resource), request);
DependencyResolver.globals = null;
DependencyResolutionResult dependencies = result
.getDependencyResolutionResult();
if (!dependencies.getUnresolvedDependencies().isEmpty()) {
StringBuilder builder = new StringBuilder();
for (Dependency dependency : dependencies
.getUnresolvedDependencies()) {
List<Exception> errors = dependencies
.getResolutionErrors(dependency);
for (Exception exception : errors) {
if (builder.length() > 0) {
builder.append("\n");
}
builder.append(exception.getMessage());
}
}
throw new RuntimeException(builder.toString());
}
List<Dependency> output = runtime(dependencies.getDependencies());
if (log.isInfoEnabled()) {
for (Dependency dependency : output) {
log.info("Resolved: " + coordinates(dependency) + "="
+ dependency.getArtifact().getFile());
}
}
return output;
}
}
catch (ProjectBuildingException | NoLocalRepositoryManagerException e) {
throw new IllegalStateException("Cannot build model", e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String getStreamContents(InputStream is) {
Preconditions.checkNotNull(is, "Cannot get String from a null object");
try {
final char[] buffer = new char[0x10000];
final StringBuilder out = new StringBuilder();
final Reader in = new InputStreamReader(is, "UTF-8");
int read;
do {
read = in.read(buffer, 0, buffer.length);
if (read > 0) {
out.append(buffer, 0, read);
}
} while (read >= 0);
in.close();
return out.toString();
} catch (IOException ioe) {
throw new IllegalStateException("Error while reading response body", ioe);
}
}
#location 16
#vulnerability type RESOURCE_LEAK | #fixed code
public static String getStreamContents(InputStream is) {
Preconditions.checkNotNull(is, "Cannot get String from a null object");
try {
final char[] buffer = new char[0x10000];
final StringBuilder out = new StringBuilder();
try (Reader in = new InputStreamReader(is, "UTF-8")) {
int read;
do {
read = in.read(buffer, 0, buffer.length);
if (read > 0) {
out.append(buffer, 0, read);
}
} while (read >= 0);
}
return out.toString();
} catch (IOException ioe) {
throw new IllegalStateException("Error while reading response body", ioe);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void findKBest(int k, PriorityQueue<Pair> heap,
Vector hidden, Vector output) {
computeOutputSoftmax(hidden, output);
for (int i = 0; i < osz_; i++) {
if (heap.size() == k && log(output.data_[i]) < heap.peek().first) {
continue;
}
heap.add(new Pair(output.data_[i], i));
if (heap.size() > k) {
heap.remove();
}
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
float negativeSampling(int target, float lr) {
float loss = 0.0f;
grad_.zero();
for (int n = 0; n <= args_.neg; n++) {
if (n == 0) {
loss += binaryLogistic(target, true, lr);
} else {
loss += binaryLogistic(getNegative(target), false, lr);
}
}
return loss;
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
int getNegative(int target) {
int negative;
do {
negative = negatives.get(negpos);
negpos = (negpos + 1) % negatives.size();
} while (target == negative);
return negative;
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
float binaryLogistic(int target, boolean label, float lr) {
float score = sigmoid(wo_.dotRow(hidden_, target));
float alpha = lr * (label ? 1f : 0f - score);
grad_.addRow(wo_, target, alpha);
synchronized (this) {
wo_.addRow(hidden_, target, alpha);
}
if (label) {
return -log(score);
} else {
return -log(1.0f - score);
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void setInfo() {
setLevel(Level.INFO);
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public static void setInfo() {
setLevel(Level.INFO);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
float negativeSampling(int target, float lr) {
float loss = 0.0f;
grad_.zero();
for (int n = 0; n <= args_.neg; n++) {
if (n == 0) {
loss += binaryLogistic(target, true, lr);
} else {
loss += binaryLogistic(getNegative(target), false, lr);
}
}
return loss;
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void update(int[] input, int target, float lr) {
assert (target >= 0);
assert (target < osz_);
if (input.length == 0) return;
computeHidden(input, hidden_);
if (args_.loss == Args.loss_name.ns) {
loss_ += negativeSampling(target, lr);
} else if (args_.loss == Args.loss_name.hs) {
loss_ += hierarchicalSoftmax(target, lr);
} else {
loss_ += softmax(target, lr);
}
nexamples_ += 1;
if (args_.model == Args.model_name.sup) {
grad_.mul(1.0f / input.length);
}
synchronized (this) {
for (int i : input) {
wi_.addRow(grad_, i, 1.0f);
}
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void update(int[] input, int target, float lr) {
assert (target >= 0);
assert (target < osz_);
if (input.length == 0) return;
computeHidden(input, hidden_);
if (args_.loss == Args.loss_name.ns) {
loss_ += negativeSampling(target, lr);
} else if (args_.loss == Args.loss_name.hs) {
loss_ += hierarchicalSoftmax(target, lr);
} else {
loss_ += softmax(target, lr);
}
nexamples_ += 1;
if (args_.model == Args.model_name.sup) {
grad_.mul(1.0f / input.length);
}
synchronized (this) {
for (int i : input) {
wi_.addRow(grad_, i, 1.0f);
}
}
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void update(int[] input, int target, float lr) {
assert (target >= 0);
assert (target < osz_);
if (input.length == 0) return;
computeHidden(input, hidden_);
if (args_.loss == Args.loss_name.ns) {
loss_ += negativeSampling(target, lr);
} else if (args_.loss == Args.loss_name.hs) {
loss_ += hierarchicalSoftmax(target, lr);
} else {
loss_ += softmax(target, lr);
}
nexamples_ += 1;
if (args_.model == Args.model_name.sup) {
grad_.mul(1.0f / input.length);
}
synchronized (this) {
for (int i : input) {
wi_.addRow(grad_, i, 1.0f);
}
}
}
#location 20
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
float binaryLogistic(int target, boolean label, float lr) {
float score = sigmoid(wo_.dotRow(hidden_, target));
float alpha = lr * (label ? 1f : 0f - score);
grad_.addRow(wo_, target, alpha);
synchronized (this) {
wo_.addRow(hidden_, target, alpha);
}
if (label) {
return -log(score);
} else {
return -log(1.0f - score);
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
float negativeSampling(int target, float lr) {
float loss = 0.0f;
grad_.zero();
for (int n = 0; n <= args_.neg; n++) {
if (n == 0) {
loss += binaryLogistic(target, true, lr);
} else {
loss += binaryLogistic(getNegative(target), false, lr);
}
}
return loss;
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
float softmax(int target, float lr) {
grad_.zero();
computeOutputSoftmax();
for (int i = 0; i < osz_; i++) {
float label = (i == target) ? 1.0f : 0.0f;
float alpha = lr * (label - output_.data_[i]);
grad_.addRow(wo_, i, alpha);
synchronized (this) {
wo_.addRow(hidden_, i, alpha);
}
}
return -log(output_.data_[target]);
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void update(int[] input, int target, float lr) {
assert (target >= 0);
assert (target < osz_);
if (input.length == 0) return;
computeHidden(input, hidden_);
if (args_.loss == Args.loss_name.ns) {
loss_ += negativeSampling(target, lr);
} else if (args_.loss == Args.loss_name.hs) {
loss_ += hierarchicalSoftmax(target, lr);
} else {
loss_ += softmax(target, lr);
}
nexamples_ += 1;
if (args_.model == Args.model_name.sup) {
grad_.mul(1.0f / input.length);
}
synchronized (this) {
for (int i : input) {
wi_.addRow(grad_, i, 1.0f);
}
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
float hierarchicalSoftmax(int target, float lr) {
float loss = 0.0f;
grad_.zero();
IntVector binaryCode = codes.get(target);
IntVector pathToRoot = paths.get(target);
for (int i = 0; i < pathToRoot.size(); i++) {
loss += binaryLogistic(pathToRoot.get(i), binaryCode.get(i) == 1, lr);
}
return loss;
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
float getLoss() {
return loss_ / nexamples_;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void update(int[] input, int target, float lr) {
assert (target >= 0);
assert (target < osz_);
if (input.length == 0) return;
computeHidden(input, hidden_);
if (args_.loss == Args.loss_name.ns) {
loss_ += negativeSampling(target, lr);
} else if (args_.loss == Args.loss_name.hs) {
loss_ += hierarchicalSoftmax(target, lr);
} else {
loss_ += softmax(target, lr);
}
nexamples_ += 1;
if (args_.model == Args.model_name.sup) {
grad_.mul(1.0f / input.length);
}
synchronized (this) {
for (int i : input) {
wi_.addRow(grad_, i, 1.0f);
}
}
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void dfs(int k, int node, float score,
PriorityQueue<Pair> heap,
Vector hidden) {
if (heap.size() == k && score < heap.peek().first) {
return;
}
if (tree[node].left == -1 && tree[node].right == -1) {
heap.add(new Pair(score, node));
if (heap.size() > k) {
heap.remove();
}
return;
}
float f = sigmoid(wo_.dotRow(hidden, node - osz_));
dfs(k, tree[node].left, score + log(1.0f - f), heap, hidden);
dfs(k, tree[node].right, score + log(f), heap, hidden);
}
#location 16
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
float softmax(int target, float lr) {
grad_.zero();
computeOutputSoftmax();
for (int i = 0; i < osz_; i++) {
float label = (i == target) ? 1.0f : 0.0f;
float alpha = lr * (label - output_.data_[i]);
grad_.addRow(wo_, i, alpha);
synchronized (this) {
wo_.addRow(hidden_, i, alpha);
}
}
return -log(output_.data_[target]);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
float binaryLogistic(int target, boolean label, float lr) {
float score = sigmoid(wo_.dotRow(hidden_, target));
float alpha = lr * (label ? 1f : 0f - score);
grad_.addRow(wo_, target, alpha);
synchronized (this) {
wo_.addRow(hidden_, target, alpha);
}
if (label) {
return -log(score);
} else {
return -log(1.0f - score);
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
List<Pair> predict(int[] input,
int k,
Vector hidden,
Vector output) {
assert (k > 0);
computeHidden(input, hidden);
PriorityQueue<Pair> heap = new PriorityQueue<>(k+1, PAIR_COMPARATOR);
if (args_.loss == Args.loss_name.hs) {
dfs(k, 2 * osz_ - 2, 0.0f, heap, hidden);
} else {
findKBest(k, heap, hidden, output);
}
List<Pair> result = new ArrayList<>(heap);
Collections.sort(result);
return result;
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static WebDocument fromText(String meta, List<String> pageData) {
String url = Regexps.firstMatch(urlPattern, meta, 2);
String id = url.replaceAll("http://|https://", "");
String source = Regexps.firstMatch(sourcePattern, meta, 2);
String crawlDate = Regexps.firstMatch(crawlDatePattern, meta, 2);
String labels = Regexps.firstMatch(labelPattern, meta, 2).replace('\"', ' ').trim();
String category = Regexps.firstMatch(categoryPattern, meta, 2).replace('\"', ' ').trim();
String title = Regexps.firstMatch(titlePattern, meta, 2).replace('\"', ' ').trim();
int i = source.lastIndexOf("/");
if (i >= 0 && i < source.length()) {
source = source.substring(i + 1);
}
return new WebDocument(source, id, title, pageData, url, crawlDate, labels, category);
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
public static WebDocument fromText(String meta, List<String> pageData) {
String url = Regexps.firstMatch(urlPattern, meta, 2);
String id = url.replaceAll("http://|https://", "");
String source = Regexps.firstMatch(sourcePattern, meta, 2);
String crawlDate = Regexps.firstMatch(crawlDatePattern, meta, 2);
String labels = getAttribute(Regexps.firstMatch(labelPattern, meta, 2));
String category = getAttribute(Regexps.firstMatch(categoryPattern, meta, 2));
String title = getAttribute(Regexps.firstMatch(titlePattern, meta, 2));
int i = source.lastIndexOf("/");
if (i >= 0 && i < source.length()) {
source = source.substring(i + 1);
}
return new WebDocument(source, id, title, pageData, url, crawlDate, labels, category);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void computeHidden(int[] input, Vector hidden) {
assert (hidden.size() == hsz_);
hidden.zero();
for (int i : input) {
hidden.addRow(wi_, i);
}
hidden.mul(1.0f / input.length);
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void computeOutputSoftmax(Vector hidden, Vector output) {
output.mul(wo_, hidden);
float max = output.data_[0], z = 0.0f;
for (int i = 0; i < osz_; i++) {
max = Math.max(output.data_[i], max);
}
for (int i = 0; i < osz_; i++) {
output.data_[i] = (float) Math.exp(output.data_[i] - max);
z += output.data_[i];
}
for (int i = 0; i < osz_; i++) {
output.data_[i] /= z;
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
List<Pair> predict(int[] input, int k) {
return predict(input, k, hidden_, output_);
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static WebDocument fromText(String meta, List<String> pageData) {
String url = Regexps.firstMatch(urlPattern, meta, 2);
String id = url.replaceAll("http://|https://", "");
String source = Regexps.firstMatch(sourcePattern, meta, 2);
String crawlDate = Regexps.firstMatch(crawlDatePattern, meta, 2);
String labels = Regexps.firstMatch(labelPattern, meta, 2).replace('\"', ' ').trim();
String category = Regexps.firstMatch(categoryPattern, meta, 2).replace('\"', ' ').trim();
String title = Regexps.firstMatch(titlePattern, meta, 2).replace('\"', ' ').trim();
int i = source.lastIndexOf("/");
if (i >= 0 && i < source.length()) {
source = source.substring(i + 1);
}
return new WebDocument(source, id, title, pageData, url, crawlDate, labels, category);
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
public static WebDocument fromText(String meta, List<String> pageData) {
String url = Regexps.firstMatch(urlPattern, meta, 2);
String id = url.replaceAll("http://|https://", "");
String source = Regexps.firstMatch(sourcePattern, meta, 2);
String crawlDate = Regexps.firstMatch(crawlDatePattern, meta, 2);
String labels = getAttribute(Regexps.firstMatch(labelPattern, meta, 2));
String category = getAttribute(Regexps.firstMatch(categoryPattern, meta, 2));
String title = getAttribute(Regexps.firstMatch(titlePattern, meta, 2));
int i = source.lastIndexOf("/");
if (i >= 0 && i < source.length()) {
source = source.substring(i + 1);
}
return new WebDocument(source, id, title, pageData, url, crawlDate, labels, category);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
float softmax(int target, float lr) {
grad_.zero();
computeOutputSoftmax();
for (int i = 0; i < osz_; i++) {
float label = (i == target) ? 1.0f : 0.0f;
float alpha = lr * (label - output_.data_[i]);
grad_.addRow(wo_, i, alpha);
synchronized (this) {
wo_.addRow(hidden_, i, alpha);
}
}
return -log(output_.data_[target]);
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
float binaryLogistic(int target, boolean label, float lr) {
float score = sigmoid(wo_.dotRow(hidden_, target));
float alpha = lr * (label ? 1f : 0f - score);
grad_.addRow(wo_, target, alpha);
synchronized (this) {
wo_.addRow(hidden_, target, alpha);
}
if (label) {
return -log(score);
} else {
return -log(1.0f - score);
}
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void update(int[] input, int target, float lr) {
assert (target >= 0);
assert (target < osz_);
if (input.length == 0) return;
computeHidden(input, hidden_);
if (args_.loss == Args.loss_name.ns) {
loss_ += negativeSampling(target, lr);
} else if (args_.loss == Args.loss_name.hs) {
loss_ += hierarchicalSoftmax(target, lr);
} else {
loss_ += softmax(target, lr);
}
nexamples_ += 1;
if (args_.model == Args.model_name.sup) {
grad_.mul(1.0f / input.length);
}
synchronized (this) {
for (int i : input) {
wi_.addRow(grad_, i, 1.0f);
}
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
int getNegative(int target) {
int negative;
do {
negative = negatives[negpos];
negpos = (negpos + 1) % negatives.length;
} while (target == negative);
return negative;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void update(int[] input, int target, float lr) {
assert (target >= 0);
assert (target < osz_);
if (input.length == 0) return;
computeHidden(input, hidden_);
if (args_.loss == Args.loss_name.ns) {
loss_ += negativeSampling(target, lr);
} else if (args_.loss == Args.loss_name.hs) {
loss_ += hierarchicalSoftmax(target, lr);
} else {
loss_ += softmax(target, lr);
}
nexamples_ += 1;
if (args_.model == Args.model_name.sup) {
grad_.mul(1.0f / input.length);
}
synchronized (this) {
for (int i : input) {
wi_.addRow(grad_, i, 1.0f);
}
}
}
#location 13
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
float binaryLogistic(int target, boolean label, float lr) {
float score = sigmoid(wo_.dotRow(hidden_, target));
float alpha = lr * (label ? 1f : 0f - score);
grad_.addRow(wo_, target, alpha);
synchronized (this) {
wo_.addRow(hidden_, target, alpha);
}
if (label) {
return -log(score);
} else {
return -log(1.0f - score);
}
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
float softmax(int target, float lr) {
grad_.zero();
computeOutputSoftmax();
for (int i = 0; i < osz_; i++) {
float label = (i == target) ? 1.0f : 0.0f;
float alpha = lr * (label - output_.data_[i]);
grad_.addRow(wo_, i, alpha);
synchronized (this) {
wo_.addRow(hidden_, i, alpha);
}
}
return -log(output_.data_[target]);
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void computeOutputSoftmax() {
computeOutputSoftmax(hidden_, output_);
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
float binaryLogistic(int target, boolean label, float lr) {
float score = sigmoid(wo_.dotRow(hidden_, target));
float alpha = lr * (label ? 1f : 0f - score);
grad_.addRow(wo_, target, alpha);
synchronized (this) {
wo_.addRow(hidden_, target, alpha);
}
if (label) {
return -log(score);
} else {
return -log(1.0f - score);
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static WebDocument fromText(String meta, List<String> pageData) {
String url = Regexps.firstMatch(urlPattern, meta, 2);
String id = url.replaceAll("http://|https://", "");
String source = Regexps.firstMatch(sourcePattern, meta, 2);
String crawlDate = Regexps.firstMatch(crawlDatePattern, meta, 2);
String labels = Regexps.firstMatch(labelPattern, meta, 2).replace('\"', ' ').trim();
String category = Regexps.firstMatch(categoryPattern, meta, 2).replace('\"', ' ').trim();
String title = Regexps.firstMatch(titlePattern, meta, 2).replace('\"', ' ').trim();
int i = source.lastIndexOf("/");
if (i >= 0 && i < source.length()) {
source = source.substring(i + 1);
}
return new WebDocument(source, id, title, pageData, url, crawlDate, labels, category);
}
#location 12
#vulnerability type NULL_DEREFERENCE | #fixed code
public static WebDocument fromText(String meta, List<String> pageData) {
String url = Regexps.firstMatch(urlPattern, meta, 2);
String id = url.replaceAll("http://|https://", "");
String source = Regexps.firstMatch(sourcePattern, meta, 2);
String crawlDate = Regexps.firstMatch(crawlDatePattern, meta, 2);
String labels = getAttribute(Regexps.firstMatch(labelPattern, meta, 2));
String category = getAttribute(Regexps.firstMatch(categoryPattern, meta, 2));
String title = getAttribute(Regexps.firstMatch(titlePattern, meta, 2));
int i = source.lastIndexOf("/");
if (i >= 0 && i < source.length()) {
source = source.substring(i + 1);
}
return new WebDocument(source, id, title, pageData, url, crawlDate, labels, category);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void stemEndingTest1() throws IOException {
TurkishMorphology morphology = TurkishMorphology.builder().addDictionaryLines("bakmak", "gelmek").build();
List<String> endings = Lists.newArrayList("acak", "ecek");
StemEndingGraph graph = new StemEndingGraph(morphology, endings);
CharacterGraphDecoder spellChecker = new CharacterGraphDecoder(graph.stemGraph);
List<ScoredItem<String>> res = spellChecker.getSuggestionsWithScores("bakcaak");
for (ScoredItem<String> re : res) {
System.out.println(re.item);
}
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void stemEndingTest1() throws IOException {
TurkishMorphology morphology = TurkishMorphology.builder().addDictionaryLines("bakmak", "gelmek").build();
List<String> endings = Lists.newArrayList("acak", "ecek");
StemEndingGraph graph = new StemEndingGraph(morphology, endings);
CharacterGraphDecoder spellChecker = new CharacterGraphDecoder(graph.stemGraph);
List<String> res = spellChecker.getSuggestions("bakcaak");
Assert.assertEquals(1, res.size());
Assert.assertEquals("bakacak", res.get(0));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
@Ignore("Slow test. Uses actual data.")
public void suggestWordTest() throws IOException, URISyntaxException {
TurkishMorphology morphology = TurkishMorphology.createWithDefaults();
TurkishSpellChecker spellChecker = new TurkishSpellChecker(morphology);
Path lmPath = Paths.get(ClassLoader.getSystemResource("lm-unigram.slm").toURI());
NgramLanguageModel lm = SmoothLm.builder(lmPath.toFile()).build();
Path r = Paths.get(ClassLoader.getSystemResource("10000_frequent_turkish_word").toURI());
List<String> words = Files.readAllLines(r, StandardCharsets.UTF_8);
int c = 0;
Stopwatch sw = Stopwatch.createStarted();
for (String word : words) {
List<String> suggestions = spellChecker.suggestForWord(word, lm);
c += suggestions.size();
}
Log.info("Elapsed = %d count = %d ", sw.elapsed(TimeUnit.MILLISECONDS), c);
}
#location 8
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
@Ignore("Slow test. Uses actual data.")
public void suggestWordTest() throws IOException, URISyntaxException {
TurkishMorphology morphology = TurkishMorphology.createWithDefaults();
TurkishSpellChecker spellChecker = new TurkishSpellChecker(morphology);
Log.info("Node count = %d", spellChecker.decoder.getGraph().getAllNodes().size());
Log.info("Node count with single connection= %d",
spellChecker.decoder.getGraph().getAllNodes(a->a.getAllChildNodes().size()==1).size());
Path lmPath = Paths.get(ClassLoader.getSystemResource("lm-unigram.slm").toURI());
NgramLanguageModel lm = SmoothLm.builder(lmPath.toFile()).build();
Path r = Paths.get(ClassLoader.getSystemResource("10000_frequent_turkish_word").toURI());
List<String> words = Files.readAllLines(r, StandardCharsets.UTF_8);
int c = 0;
Stopwatch sw = Stopwatch.createStarted();
for (String word : words) {
List<String> suggestions = spellChecker.suggestForWord(word, lm);
c += suggestions.size();
}
Log.info("Elapsed = %d count = %d ", sw.elapsed(TimeUnit.MILLISECONDS), c);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void update(int[] input, int target, float lr) {
assert (target >= 0);
assert (target < osz_);
if (input.length == 0) return;
computeHidden(input, hidden_);
if (args_.loss == Args.loss_name.ns) {
loss_ += negativeSampling(target, lr);
} else if (args_.loss == Args.loss_name.hs) {
loss_ += hierarchicalSoftmax(target, lr);
} else {
loss_ += softmax(target, lr);
}
nexamples_ += 1;
if (args_.model == Args.model_name.sup) {
grad_.mul(1.0f / input.length);
}
synchronized (this) {
for (int i : input) {
wi_.addRow(grad_, i, 1.0f);
}
}
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static WebDocument fromText(String meta, List<String> pageData) {
String url = Regexps.firstMatch(urlPattern, meta, 2);
String id = url.replaceAll("http://|https://", "");
String source = Regexps.firstMatch(sourcePattern, meta, 2);
String crawlDate = Regexps.firstMatch(crawlDatePattern, meta, 2);
String labels = Regexps.firstMatch(labelPattern, meta, 2).replace('\"', ' ').trim();
String category = Regexps.firstMatch(categoryPattern, meta, 2).replace('\"', ' ').trim();
String title = Regexps.firstMatch(titlePattern, meta, 2).replace('\"', ' ').trim();
int i = source.lastIndexOf("/");
if (i >= 0 && i < source.length()) {
source = source.substring(i + 1);
}
return new WebDocument(source, id, title, pageData, url, crawlDate, labels, category);
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
public static WebDocument fromText(String meta, List<String> pageData) {
String url = Regexps.firstMatch(urlPattern, meta, 2);
String id = url.replaceAll("http://|https://", "");
String source = Regexps.firstMatch(sourcePattern, meta, 2);
String crawlDate = Regexps.firstMatch(crawlDatePattern, meta, 2);
String labels = getAttribute(Regexps.firstMatch(labelPattern, meta, 2));
String category = getAttribute(Regexps.firstMatch(categoryPattern, meta, 2));
String title = getAttribute(Regexps.firstMatch(titlePattern, meta, 2));
int i = source.lastIndexOf("/");
if (i >= 0 && i < source.length()) {
source = source.substring(i + 1);
}
return new WebDocument(source, id, title, pageData, url, crawlDate, labels, category);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
float softmax(int target, float lr) {
grad_.zero();
computeOutputSoftmax();
for (int i = 0; i < osz_; i++) {
float label = (i == target) ? 1.0f : 0.0f;
float alpha = lr * (label - output_.data_[i]);
grad_.addRow(wo_, i, alpha);
synchronized (this) {
wo_.addRow(hidden_, i, alpha);
}
}
return -log(output_.data_[target]);
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void update(int[] input, int target, float lr) {
assert (target >= 0);
assert (target < osz_);
if (input.length == 0) return;
computeHidden(input, hidden_);
if (args_.loss == Args.loss_name.ns) {
loss_ += negativeSampling(target, lr);
} else if (args_.loss == Args.loss_name.hs) {
loss_ += hierarchicalSoftmax(target, lr);
} else {
loss_ += softmax(target, lr);
}
nexamples_ += 1;
if (args_.model == Args.model_name.sup) {
grad_.mul(1.0f / input.length);
}
synchronized (this) {
for (int i : input) {
wi_.addRow(grad_, i, 1.0f);
}
}
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public List<WordAnalysis> analyzeWithoutCache(String word) {
String s = normalize(word); // TODO: this may cause problem for some foreign words.
if (s.length() == 0) {
return Collections.emptyList();
}
List<WordAnalysis> res = wordAnalyzer.analyze(s);
if (res.size() == 0) {
res.addAll(analyzeWordsWithSingleQuote(s));
}
if (res.size() == 0 && useUnidentifiedTokenAnalyzer) {
invalidateCache(s);
res.addAll(unidentifiedTokenAnalyzer.parse(s));
}
if (res.size() == 0) {
res.add(new WordAnalysis(
DictionaryItem.UNKNOWN,
s,
Lists.newArrayList(WordAnalysis.InflectionalGroup.UNKNOWN)));
}
return res;
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public List<WordAnalysis> analyzeWithoutCache(String word) {
String s = normalize(word); // TODO: this may cause problem for some foreign words.
if (s.length() == 0) {
return Collections.emptyList();
}
List<WordAnalysis> res = wordAnalyzer.analyze(s);
if (res.size() == 0) {
res.addAll(analyzeWordsWithSingleQuote(s));
}
if (res.size() == 0 && useUnidentifiedTokenAnalyzer) {
invalidateCache(s);
res.addAll(unidentifiedTokenAnalyzer.analyze(s));
}
if (res.size() == 0) {
res.add(new WordAnalysis(
DictionaryItem.UNKNOWN,
s,
Lists.newArrayList(WordAnalysis.InflectionalGroup.UNKNOWN)));
}
return res;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
List<Pair> predict(int[] input,
int k,
Vector hidden,
Vector output) {
assert (k > 0);
computeHidden(input, hidden);
PriorityQueue<Pair> heap = new PriorityQueue<>(k+1, PAIR_COMPARATOR);
if (args_.loss == Args.loss_name.hs) {
dfs(k, 2 * osz_ - 2, 0.0f, heap, hidden);
} else {
findKBest(k, heap, hidden, output);
}
List<Pair> result = new ArrayList<>(heap);
Collections.sort(result);
return result;
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void update(int[] input, int target, float lr) {
assert (target >= 0);
assert (target < osz_);
if (input.length == 0) return;
computeHidden(input, hidden_);
if (args_.loss == Args.loss_name.ns) {
loss_ += negativeSampling(target, lr);
} else if (args_.loss == Args.loss_name.hs) {
loss_ += hierarchicalSoftmax(target, lr);
} else {
loss_ += softmax(target, lr);
}
nexamples_ += 1;
if (args_.model == Args.model_name.sup) {
grad_.mul(1.0f / input.length);
}
synchronized (this) {
for (int i : input) {
wi_.addRow(grad_, i, 1.0f);
}
}
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Model(Matrix wi,
Matrix wo,
Args args,
int seed) {
hidden_ = new Vector(args.dim);
output_ = new Vector(wo.m_);
grad_ = new Vector(args.dim);
random = new Random(seed);
wi_ = wi;
wo_ = wo;
args_ = args;
isz_ = wi.m_;
osz_ = wo.m_;
hsz_ = args.dim;
negpos = 0;
loss_ = 0.0f;
nexamples_ = 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void realClose() throws IOException {
if (!closed) {
closed = true;
backend.rrdClose();
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
void internalClose() throws IOException {
if (!closed) {
closed = true;
backend.rrdClose();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public RrdDb requestRrdDb(String path) throws IOException {
RrdEntry ref = null;
try {
ref = getEntry(path, true);
} catch (InterruptedException e) {
throw new RuntimeException("request interrupted for " + path, e);
}
try {
//Wait until the pool is not full and
//Don't lock on anything
while(ref.count == 0 && ! tryGetSlot()) {
passNext(ACTION.SWAP, ref);
countLock.lockInterruptibly();
full.await();
countLock.unlock();
ref = getEntry(path, true);
}
} catch (InterruptedException e) {
passNext(ACTION.DROP, ref);
throw new RuntimeException("request interrupted for " + path, e);
} finally {
if(countLock.isHeldByCurrentThread()) {
countLock.unlock();
}
}
//Someone might have already open it, rechecks
if(ref.count == 0) {
try {
ref.rrdDb = new RrdDb(path);
} catch (IOException e) {
//Don't forget to release the slot reserved earlier
usage.decrementAndGet();
passNext(ACTION.DROP, ref);
throw e;
}
}
ref.count++;
passNext(ACTION.SWAP, ref);
return ref.rrdDb;
}
#location 31
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public RrdDb requestRrdDb(String path) throws IOException {
RrdEntry ref = null;
try {
ref = getEntry(path, true);
} catch (InterruptedException e) {
throw new RuntimeException("request interrupted for " + path, e);
}
//Someone might have already open it, rechecks
if(ref.count == 0) {
try {
ref.rrdDb = new RrdDb(path);
} catch (IOException e) {
//Don't forget to release the slot reserved earlier
usage.decrementAndGet();
passNext(ACTION.DROP, ref);
throw e;
}
}
ref.count++;
passNext(ACTION.SWAP, ref);
return ref.rrdDb;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void testFile(String file, String version) throws IOException {
URL url = getClass().getResource(file);
RRDatabase rrd = new RRDatabase(url.getFile());
Assert.assertEquals("Invalid date", new Date(920808900000L), rrd.getLastUpdate());
Assert.assertEquals("Invalid number of archives", 2, rrd.getNumArchives());
Assert.assertEquals("Invalid number of datasources", 2, rrd.getDataSourcesName().size());
Assert.assertEquals("Invalid heartbeat for datasource 0", 600, rrd.getDataSource(0).getMinimumHeartbeat());
Assert.assertEquals("Invalid heartbeat for datasource 1", 600, rrd.getDataSource(1).getMinimumHeartbeat());
Assert.assertEquals("Invalid version", version, rrd.header.getVersion());
Assert.assertEquals("Invalid number of row", 24, rrd.getArchive(0).getRowCount());
Assert.assertEquals("Invalid number of row", 10, rrd.getArchive(1).getRowCount());
boolean b0 = "12405".equals(rrd.getDataSource(0).getPDPStatusBlock().lastReading);
boolean b1 = "UNKN".equals(rrd.getDataSource(1).getPDPStatusBlock().lastReading);
boolean b2 = "3".equals(rrd.getDataSource(1).getPDPStatusBlock().lastReading);
Assert.assertTrue("Failed getting last reading", b0 && (b1 || b2));
if("0003".equals(version) ) {
Assert.assertEquals("bad primary value", 1.43161853E7, rrd.getArchive(0).getCDPStatusBlock(0).primary_value, 1);
}
Assert.assertEquals("bad primary value", 1.4316557620000001E7, rrd.getArchive(1).getCDPStatusBlock(0).value, 1);
rrd.rrdFile.ras.seek( rrd.getArchive(0).dataOffset + 16 * rrd.getArchive(0).currentRow);
double speed = readDouble(rrd.rrdFile);
double weight = readDouble(rrd.rrdFile);
Assert.assertEquals(1.4316185300e+07, speed, 1e-7);
Assert.assertEquals(3, weight, 1e-7);
DataChunk data = rrd.getData(ConsolidationFunctionType.AVERAGE, 920802300, 920808900, 300);
Assert.assertEquals(0.02, data.toPlottable("speed").getValue(920802300), 1e-7);
Assert.assertEquals(1.0, data.toPlottable("weight").getValue(920802300), 1e-7);
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
private void testFile(String file, String version) throws IOException {
URL url = getClass().getResource(file);
RRDatabase rrd = new RRDatabase(url.getFile());
Assert.assertEquals("Invalid date", new Date(920808900000L), rrd.getLastUpdate());
Assert.assertEquals("Invalid number of archives", 2, rrd.getNumArchives());
Assert.assertEquals("Invalid number of datasources", 2, rrd.getDataSourcesName().size());
Assert.assertEquals("Invalid heartbeat for datasource 0", 600, rrd.getDataSource(0).getMinimumHeartbeat());
Assert.assertEquals("Invalid heartbeat for datasource 1", 600, rrd.getDataSource(1).getMinimumHeartbeat());
Assert.assertEquals("Invalid version", version, rrd.header.getVersion());
Assert.assertEquals("Invalid number of row", 24, rrd.getArchive(0).getRowCount());
Assert.assertEquals("Invalid number of row", 10, rrd.getArchive(1).getRowCount());
boolean b0 = "12405".equals(rrd.getDataSource(0).getPDPStatusBlock().lastReading);
boolean b1 = "UNKN".equals(rrd.getDataSource(1).getPDPStatusBlock().lastReading);
boolean b2 = "3".equals(rrd.getDataSource(1).getPDPStatusBlock().lastReading);
Assert.assertTrue("Failed getting last reading", b0 && (b1 || b2));
if("0003".equals(version) ) {
Assert.assertEquals("bad primary value", 1.43161853E7, rrd.getArchive(0).getCDPStatusBlock(0).primary_value, 1);
}
Assert.assertEquals("bad primary value", 1.4316557620000001E7, rrd.getArchive(1).getCDPStatusBlock(0).value, 1);
rrd.rrdFile.seek( rrd.getArchive(0).dataOffset + 16 * rrd.getArchive(0).currentRow);
double speed = readDouble(rrd.rrdFile);
double weight = readDouble(rrd.rrdFile);
Assert.assertEquals(1.4316185300e+07, speed, 1e-7);
Assert.assertEquals(3, weight, 1e-7);
DataChunk data = rrd.getData(ConsolidationFunctionType.AVERAGE, 920802300, 920808900, 300);
Assert.assertEquals(0.02, data.toPlottable("speed").getValue(920802300), 1e-7);
Assert.assertEquals(1.0, data.toPlottable("weight").getValue(920802300), 1e-7);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void release(RrdDb rrdDb) throws IOException {
// null pointer should not kill the thread, just ignore it
if (rrdDb == null) {
return;
}
String canonicalPath = rrdDb.getCanonicalPath();
RrdEntry ref;
try {
ref = getEntry(canonicalPath);
} catch (InterruptedException e) {
throw new RuntimeException("release interrupted for " + rrdDb, e);
}
if (ref.count.get() <= 0) {
throw new IllegalStateException("Could not release [" + canonicalPath + "], the file was never requested");
}
if (ref.count.decrementAndGet() <= 0 && ref.rrdDb != null) {
ref.rrdDb.close();
ref.rrdDb = null;
capacity.release();
ref.count.set(0);
ref.rlock.release();
ref.ulock.release();
}
if(ref.count.get() == 0) {
try {
//Got exclusive access to the pool
poolLock.writeLock().lockInterruptibly();
ref = pool.get(canonicalPath);
//It if failed, some one is working on it, so that's up to him to manage the cleaning
if(ref != null && ref.rlock.tryAcquire()) {
if(ref.count.get() == 0)
pool.remove(canonicalPath);
ref.rlock.release();
}
poolLock.writeLock().unlock();
} catch (InterruptedException e) {
throw new RuntimeException("release interrupted for " + rrdDb, e);
}
}
}
#location 21
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void release(RrdDb rrdDb) throws IOException {
// null pointer should not kill the thread, just ignore it
if (rrdDb == null) {
return;
}
String canonicalPath = rrdDb.getCanonicalPath();
RrdEntry ref;
try {
ref = getEntry(canonicalPath);
} catch (InterruptedException e) {
throw new RuntimeException("release interrupted for " + rrdDb, e);
}
if (ref.count.get() <= 0) {
ref.inuse.unlock();
throw new IllegalStateException("Could not release [" + canonicalPath + "], the file was never requested");
}
if (ref.count.decrementAndGet() <= 0 && ref.rrdDb != null) {
ref.rrdDb.close();
ref.rrdDb = null;
capacity.release();
ref.count.set(0);
ref.empty.signal();
ref.inuse.unlock();
}
//Ok, the last referenced was removed
//try to avoid the Map to grow and remove the reference
if(ref.count.get() == 0) {
try {
//Got exclusive access to the pool
poolLock.writeLock().lockInterruptibly();
ref = pool.get(canonicalPath);
// Already removed
if(ref == null) {
return;
}
ref.inuse.lockInterruptibly();
//No one started to wait on it, still no use, remove from the map
if(! ref.inuse.hasWaiters(ref.empty) && ref.count.get() == 0) {
pool.remove(canonicalPath);
}
ref.inuse.unlock();
} catch (InterruptedException e) {
throw new RuntimeException("release interrupted for " + rrdDb, e);
} finally {
if (poolLock.isWriteLocked()) {
poolLock.writeLock().unlock();
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testBackendFactoryWithExecutor() throws IOException {
RrdNioBackendFactory factory = (RrdNioBackendFactory) RrdBackendFactory.getFactory("NIO");
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
factory.setSyncThreadPool(new RrdSyncThreadPool());
File rrdfile = testFolder.newFile("testfile");
RrdBackend be = factory.open(rrdfile.getCanonicalPath(), false);
be.setLength(10);
be.writeDouble(0, 0);
be.close();
executor.shutdown();
DataInputStream is = new DataInputStream(new FileInputStream(rrdfile));
Double d = is.readDouble();
Assert.assertEquals("write to NIO failed", 0, d, 1e-10);
}
#location 14
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testBackendFactoryWithExecutor() throws IOException {
RrdNioBackendFactory factory = (RrdNioBackendFactory) RrdBackendFactory.getFactory("NIO");
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
factory.setSyncThreadPool(new RrdSyncThreadPool());
File rrdfile = testFolder.newFile("testfile");
RrdBackend be = factory.open(rrdfile.getCanonicalPath(), false);
be.setLength(10);
be.writeDouble(0, 0);
be.close();
executor.shutdown();
DataInputStream is = new DataInputStream(new FileInputStream(rrdfile));
Double d = is.readDouble();
Assert.assertEquals("write to NIO failed", 0, d, 1e-10);
is.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public RrdDb requestRrdDb(String path) throws IOException {
RrdEntry ref = null;
try {
ref = getEntry(path, true);
} catch (InterruptedException e) {
throw new RuntimeException("request interrupted for " + path, e);
}
try {
//Wait until the pool is not full and
//Don't lock on anything
while(ref.count == 0 && ! tryGetSlot()) {
passNext(ACTION.SWAP, ref);
countLock.lockInterruptibly();
full.await();
countLock.unlock();
ref = getEntry(path, true);
}
} catch (InterruptedException e) {
passNext(ACTION.DROP, ref);
throw new RuntimeException("request interrupted for " + path, e);
} finally {
if(countLock.isHeldByCurrentThread()) {
countLock.unlock();
}
}
//Someone might have already open it, rechecks
if(ref.count == 0) {
try {
ref.rrdDb = new RrdDb(path);
} catch (IOException e) {
//Don't forget to release the slot reserved earlier
usage.decrementAndGet();
passNext(ACTION.DROP, ref);
throw e;
}
}
ref.count++;
passNext(ACTION.SWAP, ref);
return ref.rrdDb;
}
#location 31
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public RrdDb requestRrdDb(String path) throws IOException {
RrdEntry ref = null;
try {
ref = getEntry(path, true);
} catch (InterruptedException e) {
throw new RuntimeException("request interrupted for " + path, e);
}
//Someone might have already open it, rechecks
if(ref.count == 0) {
try {
ref.rrdDb = new RrdDb(path);
} catch (IOException e) {
//Don't forget to release the slot reserved earlier
usage.decrementAndGet();
passNext(ACTION.DROP, ref);
throw e;
}
}
ref.count++;
passNext(ACTION.SWAP, ref);
return ref.rrdDb;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testEntriesNeg55To105InRrd() throws IOException, FontFormatException {
createGaugeRrd(165);
RrdDb rrd = new RrdDb(jrbFileName);
for(int i=0; i<160; i++) {
long timestamp = startTime + 1 + (i * 60);
Sample sample = rrd.createSample();
sample.setAndUpdate(timestamp + ":" + (i -55));
}
rrd.close();
prepareGraph();
/**
* Prior to JRB-12 fix, this was the behaviour. Note the lack of a decent negative label
expectMinorGridLines(3);
expectMajorGridLine(" 0");
expectMinorGridLines(4);
expectMajorGridLine(" 100");
expectMinorGridLines(1);
*/
//New behaviour is better; no minor grid lines, which is interesting, but much better representation
expectMajorGridLine(" -50");
expectMajorGridLine(" 0");
expectMajorGridLine(" 50");
expectMajorGridLine(" 100");
run();
}
#location 10
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testEntriesNeg55To105InRrd() throws IOException, FontFormatException {
createGaugeRrd(165);
RrdDb rrd = RrdDb.getBuilder().setPath(jrbFileName).build();
for(int i=0; i<160; i++) {
long timestamp = startTime + 1 + (i * 60);
Sample sample = rrd.createSample();
sample.setAndUpdate(timestamp + ":" + (i -55));
}
rrd.close();
prepareGraph();
/**
* Prior to JRB-12 fix, this was the behaviour. Note the lack of a decent negative label
expectMinorGridLines(3);
expectMajorGridLine(" 0");
expectMinorGridLines(4);
expectMajorGridLine(" 100");
expectMinorGridLines(1);
*/
//New behaviour is better; no minor grid lines, which is interesting, but much better representation
expectMajorGridLine(" -50");
expectMajorGridLine(" 0");
expectMajorGridLine(" 50");
expectMajorGridLine(" 100");
run();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testEntriesNeg50To100InRrd() throws IOException, FontFormatException {
createGaugeRrd(155);
RrdDb rrd = new RrdDb(jrbFileName);
for(int i=0; i<150; i++) {
long timestamp = startTime + 1 + (i * 60);
Sample sample = rrd.createSample();
sample.setAndUpdate(timestamp + ":" + (i -50));
}
rrd.close();
prepareGraph();
expectMajorGridLine(" -50");
expectMinorGridLines(4);
expectMajorGridLine(" 0");
expectMinorGridLines(4);
expectMajorGridLine(" 50");
expectMinorGridLines(4);
expectMajorGridLine(" 100");
run();
}
#location 10
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testEntriesNeg50To100InRrd() throws IOException, FontFormatException {
createGaugeRrd(155);
RrdDb rrd = RrdDb.getBuilder().setPath(jrbFileName).build();
for(int i=0; i<150; i++) {
long timestamp = startTime + 1 + (i * 60);
Sample sample = rrd.createSample();
sample.setAndUpdate(timestamp + ":" + (i -50));
}
rrd.close();
prepareGraph();
expectMajorGridLine(" -50");
expectMinorGridLines(4);
expectMajorGridLine(" 0");
expectMinorGridLines(4);
expectMajorGridLine(" 50");
expectMinorGridLines(4);
expectMajorGridLine(" 100");
run();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void testFile(String file, String version) throws IOException {
URL url = getClass().getResource(file);
RRDatabase rrd = new RRDatabase(url.getFile());
Assert.assertEquals("Invalid date", new Date(920808900000L), rrd.getLastUpdate());
Assert.assertEquals("Invalid number of archives", 2, rrd.getNumArchives());
Assert.assertEquals("Invalid number of datasources", 2, rrd.getDataSourcesName().size());
Assert.assertEquals("Invalid heartbeat for datasource 0", 600, rrd.getDataSource(0).getMinimumHeartbeat());
Assert.assertEquals("Invalid heartbeat for datasource 1", 600, rrd.getDataSource(1).getMinimumHeartbeat());
Assert.assertEquals("Invalid version", version, rrd.header.getVersion());
Assert.assertEquals("Invalid number of row", 24, rrd.getArchive(0).getRowCount());
Assert.assertEquals("Invalid number of row", 10, rrd.getArchive(1).getRowCount());
boolean b0 = "12405".equals(rrd.getDataSource(0).getPDPStatusBlock().lastReading);
boolean b1 = "UNKN".equals(rrd.getDataSource(1).getPDPStatusBlock().lastReading);
boolean b2 = "3".equals(rrd.getDataSource(1).getPDPStatusBlock().lastReading);
Assert.assertTrue("Failed getting last reading", b0 && (b1 || b2));
if("0003".equals(version) ) {
Assert.assertEquals("bad primary value", 1.43161853E7, rrd.getArchive(0).getCDPStatusBlock(0).primary_value, 1);
}
Assert.assertEquals("bad primary value", 1.4316557620000001E7, rrd.getArchive(1).getCDPStatusBlock(0).value, 1);
rrd.rrdFile.ras.seek( rrd.getArchive(0).dataOffset + 16 * rrd.getArchive(0).currentRow);
double speed = readDouble(rrd.rrdFile);
double weight = readDouble(rrd.rrdFile);
Assert.assertEquals(1.4316185300e+07, speed, 1e-7);
Assert.assertEquals(3, weight, 1e-7);
DataChunk data = rrd.getData(ConsolidationFunctionType.AVERAGE, 920802300, 920808900, 300);
Assert.assertEquals(0.02, data.toPlottable("speed").getValue(920802300), 1e-7);
Assert.assertEquals(1.0, data.toPlottable("weight").getValue(920802300), 1e-7);
}
#location 25
#vulnerability type RESOURCE_LEAK | #fixed code
private void testFile(String file, String version) throws IOException {
URL url = getClass().getResource(file);
RRDatabase rrd = new RRDatabase(url.getFile());
Assert.assertEquals("Invalid date", new Date(920808900000L), rrd.getLastUpdate());
Assert.assertEquals("Invalid number of archives", 2, rrd.getNumArchives());
Assert.assertEquals("Invalid number of datasources", 2, rrd.getDataSourcesName().size());
Assert.assertEquals("Invalid heartbeat for datasource 0", 600, rrd.getDataSource(0).getMinimumHeartbeat());
Assert.assertEquals("Invalid heartbeat for datasource 1", 600, rrd.getDataSource(1).getMinimumHeartbeat());
Assert.assertEquals("Invalid version", version, rrd.header.getVersion());
Assert.assertEquals("Invalid number of row", 24, rrd.getArchive(0).getRowCount());
Assert.assertEquals("Invalid number of row", 10, rrd.getArchive(1).getRowCount());
boolean b0 = "12405".equals(rrd.getDataSource(0).getPDPStatusBlock().lastReading);
boolean b1 = "UNKN".equals(rrd.getDataSource(1).getPDPStatusBlock().lastReading);
boolean b2 = "3".equals(rrd.getDataSource(1).getPDPStatusBlock().lastReading);
Assert.assertTrue("Failed getting last reading", b0 && (b1 || b2));
if("0003".equals(version) ) {
Assert.assertEquals("bad primary value", 1.43161853E7, rrd.getArchive(0).getCDPStatusBlock(0).primary_value, 1);
}
Assert.assertEquals("bad primary value", 1.4316557620000001E7, rrd.getArchive(1).getCDPStatusBlock(0).value, 1);
rrd.rrdFile.seek( rrd.getArchive(0).dataOffset + 16 * rrd.getArchive(0).currentRow);
double speed = readDouble(rrd.rrdFile);
double weight = readDouble(rrd.rrdFile);
Assert.assertEquals(1.4316185300e+07, speed, 1e-7);
Assert.assertEquals(3, weight, 1e-7);
DataChunk data = rrd.getData(ConsolidationFunctionType.AVERAGE, 920802300, 920808900, 300);
Assert.assertEquals(0.02, data.toPlottable("speed").getValue(920802300), 1e-7);
Assert.assertEquals(1.0, data.toPlottable("weight").getValue(920802300), 1e-7);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public RrdDb requestRrdDb(String path) throws IOException {
RrdEntry ref = null;
try {
ref = getEntry(path, true);
} catch (InterruptedException e) {
throw new RuntimeException("request interrupted for " + path, e);
}
try {
//Wait until the pool is not full and
//Don't lock on anything
while(ref.count == 0 && ! tryGetSlot()) {
passNext(ACTION.SWAP, ref);
countLock.lockInterruptibly();
full.await();
countLock.unlock();
ref = getEntry(path, true);
}
} catch (InterruptedException e) {
passNext(ACTION.DROP, ref);
throw new RuntimeException("request interrupted for " + path, e);
} finally {
if(countLock.isHeldByCurrentThread()) {
countLock.unlock();
}
}
//Someone might have already open it, rechecks
if(ref.count == 0) {
try {
ref.rrdDb = new RrdDb(path);
} catch (IOException e) {
//Don't forget to release the slot reserved earlier
usage.decrementAndGet();
passNext(ACTION.DROP, ref);
throw e;
}
}
ref.count++;
passNext(ACTION.SWAP, ref);
return ref.rrdDb;
}
#location 29
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public RrdDb requestRrdDb(String path) throws IOException {
RrdEntry ref = null;
try {
ref = getEntry(path, true);
} catch (InterruptedException e) {
throw new RuntimeException("request interrupted for " + path, e);
}
//Someone might have already open it, rechecks
if(ref.count == 0) {
try {
ref.rrdDb = new RrdDb(path);
} catch (IOException e) {
//Don't forget to release the slot reserved earlier
usage.decrementAndGet();
passNext(ACTION.DROP, ref);
throw e;
}
}
ref.count++;
passNext(ACTION.SWAP, ref);
return ref.rrdDb;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testBackendFactory() throws IOException {
RrdRandomAccessFileBackendFactory factory = (RrdRandomAccessFileBackendFactory) RrdBackendFactory.getFactory("SAFE");
File rrdfile = testFolder.newFile("testfile");
RrdBackend be = factory.open(rrdfile.getCanonicalPath(), false);
be.setLength(10);
be.writeDouble(0, 0);
be.close();
DataInputStream is = new DataInputStream(new FileInputStream(rrdfile));
Double d = is.readDouble();
Assert.assertEquals("write to random access file failed", 0, d, 1e-10);
is.close();
}
#location 15
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testBackendFactory() throws IOException {
File rrdfile = testFolder.newFile("testfile");
try(RrdSafeFileBackendFactory factory = new RrdSafeFileBackendFactory()) {
super.testBackendFactory(factory,rrdfile.getCanonicalPath());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testEntriesNeg50To0InRrd() throws IOException, FontFormatException {
createGaugeRrd(100);
RrdDb rrd = new RrdDb(jrbFileName);
for(int i=0; i<50; i++) {
long timestamp = startTime + 1 + (i * 60);
Sample sample = rrd.createSample();
sample.setAndUpdate(timestamp + ":" + (i -50));
}
rrd.close();
prepareGraph();
expectMinorGridLines(2);
expectMajorGridLine(" -40");
expectMinorGridLines(3);
expectMajorGridLine(" -20");
expectMinorGridLines(3);
run();
}
#location 10
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testEntriesNeg50To0InRrd() throws IOException, FontFormatException {
createGaugeRrd(100);
RrdDb rrd = RrdDb.getBuilder().setPath(jrbFileName).build();
for(int i=0; i<50; i++) {
long timestamp = startTime + 1 + (i * 60);
Sample sample = rrd.createSample();
sample.setAndUpdate(timestamp + ":" + (i -50));
}
rrd.close();
prepareGraph();
expectMinorGridLines(2);
expectMajorGridLine(" -40");
expectMinorGridLines(3);
expectMajorGridLine(" -20");
expectMinorGridLines(3);
run();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public RrdDb requestRrdDb(String path) throws IOException {
RrdEntry ref = null;
try {
ref = getEntry(path, true);
} catch (InterruptedException e) {
throw new RuntimeException("request interrupted for " + path, e);
}
try {
//Wait until the pool is not full and
//Don't lock on anything
while(ref.count == 0 && ! tryGetSlot()) {
passNext(ACTION.SWAP, ref);
countLock.lockInterruptibly();
full.await();
countLock.unlock();
ref = getEntry(path, true);
}
} catch (InterruptedException e) {
passNext(ACTION.DROP, ref);
throw new RuntimeException("request interrupted for " + path, e);
} finally {
if(countLock.isHeldByCurrentThread()) {
countLock.unlock();
}
}
//Someone might have already open it, rechecks
if(ref.count == 0) {
try {
ref.rrdDb = new RrdDb(path);
} catch (IOException e) {
//Don't forget to release the slot reserved earlier
usage.decrementAndGet();
passNext(ACTION.DROP, ref);
throw e;
}
}
ref.count++;
passNext(ACTION.SWAP, ref);
return ref.rrdDb;
}
#location 39
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public RrdDb requestRrdDb(String path) throws IOException {
RrdEntry ref = null;
try {
ref = getEntry(path, true);
} catch (InterruptedException e) {
throw new RuntimeException("request interrupted for " + path, e);
}
//Someone might have already open it, rechecks
if(ref.count == 0) {
try {
ref.rrdDb = new RrdDb(path);
} catch (IOException e) {
//Don't forget to release the slot reserved earlier
usage.decrementAndGet();
passNext(ACTION.DROP, ref);
throw e;
}
}
ref.count++;
passNext(ACTION.SWAP, ref);
return ref.rrdDb;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testEntriesNeg50To0InRrd() throws IOException, FontFormatException {
createGaugeRrd(100);
RrdDb rrd = new RrdDb(jrbFileName);
for(int i=0; i<50; i++) {
long timestamp = startTime + 1 + (i * 60);
Sample sample = rrd.createSample();
sample.setAndUpdate(timestamp + ":" + (i -50));
}
rrd.close();
prepareGraph();
expectMajorGridLine(" -52");
expectMajorGridLine(" -39");
expectMajorGridLine(" -26");
expectMajorGridLine(" -13");
expectMajorGridLine(" 0");
run();
}
#location 10
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testEntriesNeg50To0InRrd() throws IOException, FontFormatException {
createGaugeRrd(100);
RrdDb rrd = RrdDb.getBuilder().setPath(jrbFileName).build();
for(int i=0; i<50; i++) {
long timestamp = startTime + 1 + (i * 60);
Sample sample = rrd.createSample();
sample.setAndUpdate(timestamp + ":" + (i -50));
}
rrd.close();
prepareGraph();
expectMajorGridLine(" -52");
expectMajorGridLine(" -39");
expectMajorGridLine(" -26");
expectMajorGridLine(" -13");
expectMajorGridLine(" 0");
run();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testEntriesNeg50To100InRrd() throws IOException, FontFormatException {
createGaugeRrd(155);
RrdDb rrd = new RrdDb(jrbFileName);
for(int i=0; i<150; i++) {
long timestamp = startTime + 1 + (i * 60);
Sample sample = rrd.createSample();
sample.setAndUpdate(timestamp + ":" + (i -50));
}
rrd.close();
prepareGraph();
expectMajorGridLine("-100");
expectMajorGridLine(" -50");
expectMajorGridLine(" 0");
expectMajorGridLine(" 50");
expectMajorGridLine(" 100");
run();
}
#location 10
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testEntriesNeg50To100InRrd() throws IOException, FontFormatException {
createGaugeRrd(155);
RrdDb rrd = RrdDb.getBuilder().setPath(jrbFileName).build();
for(int i=0; i<150; i++) {
long timestamp = startTime + 1 + (i * 60);
Sample sample = rrd.createSample();
sample.setAndUpdate(timestamp + ":" + (i -50));
}
rrd.close();
prepareGraph();
expectMajorGridLine("-100");
expectMajorGridLine(" -50");
expectMajorGridLine(" 0");
expectMajorGridLine(" 50");
expectMajorGridLine(" 100");
run();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static void copyFile(String sourcePath, String destPath, boolean saveBackup)
throws IOException {
File source = new File(sourcePath);
File dest = new File(destPath);
if (saveBackup) {
String backupPath = getBackupPath(destPath);
File backup = new File(backupPath);
deleteFile(backup);
if (!dest.renameTo(backup)) {
throw new IOException("Could not create backup file " + backupPath);
}
}
deleteFile(dest);
if (!source.renameTo(dest)) {
//Rename failed so try to copy and erase
FileChannel sourceStream = null;
FileChannel destinationStream = null;
try {
sourceStream = new FileInputStream(source).getChannel();
destinationStream = new FileOutputStream(dest).getChannel();
long count = 0;
final long size = sourceStream.size();
while(count < size) {
count += destinationStream.transferFrom(sourceStream, count, size-count);
}
deleteFile(source);
}
finally {
if(sourceStream != null) {
sourceStream.close();
}
if(destinationStream != null) {
destinationStream.close();
}
}
}
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
private static void copyFile(String sourcePath, String destPath, boolean saveBackup)
throws IOException {
File source = new File(sourcePath);
File dest = new File(destPath);
if (saveBackup) {
String backupPath = getBackupPath(destPath);
File backup = new File(backupPath);
deleteFile(backup);
if (!dest.renameTo(backup)) {
throw new IOException("Could not create backup file " + backupPath);
}
}
deleteFile(dest);
if (!source.renameTo(dest)) {
//Rename failed so try to copy and erase
try(FileChannel sourceStream = new FileInputStream(source).getChannel(); FileChannel destinationStream = new FileOutputStream(dest).getChannel()) {
long count = 0;
final long size = sourceStream.size();
while(count < size) {
count += destinationStream.transferFrom(sourceStream, count, size-count);
}
deleteFile(source);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public RrdDb requestRrdDb(String path) throws IOException {
RrdEntry ref = null;
try {
ref = getEntry(path, true);
} catch (InterruptedException e) {
throw new RuntimeException("request interrupted for " + path, e);
}
if(ref.count == 0) {
//Wait until the pool is not full
//Don't lock on anything
while(usage.get() >= maxCapacity) {
passNext(ACTION.SWAP, ref);
try {
countLock.lockInterruptibly();
full.await();
ref = getEntry(path, true);
//Get an empty ref, can use it, reserve the slot
if(ref.count == 0 && usage.get() < maxCapacity) {
usage.incrementAndGet();
break;
}
} catch (InterruptedException e) {
throw new RuntimeException("request interrupted for " + path, e);
} finally {
if(countLock.isHeldByCurrentThread()) {
countLock.unlock();
}
}
}
//Someone might have already open it, rechecks
if(ref.count == 0) {
try {
ref.rrdDb = new RrdDb(path);
passNext(ACTION.SWAP, ref);
} catch (IOException e) {
//Don't forget to release the slot reserved earlier
usage.decrementAndGet();
passNext(ACTION.DROP, ref);
throw e;
}
}
} else {
passNext(ACTION.SWAP, ref);
}
ref.count++;
return ref.rrdDb;
}
#location 13
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public RrdDb requestRrdDb(String path) throws IOException {
RrdEntry ref = null;
try {
ref = getEntry(path, true);
} catch (InterruptedException e) {
throw new RuntimeException("request interrupted for " + path, e);
}
try {
//Wait until the pool is not full and
//Don't lock on anything
while(ref.count == 0 && ! tryGetSlot()) {
passNext(ACTION.SWAP, ref);
countLock.lockInterruptibly();
full.await();
countLock.unlock();
ref = getEntry(path, true);
}
} catch (InterruptedException e) {
passNext(ACTION.DROP, ref);
throw new RuntimeException("request interrupted for " + path, e);
} finally {
if(countLock.isHeldByCurrentThread()) {
countLock.unlock();
}
}
//Someone might have already open it, rechecks
if(ref.count == 0) {
try {
ref.rrdDb = new RrdDb(path);
} catch (IOException e) {
//Don't forget to release the slot reserved earlier
usage.decrementAndGet();
passNext(ACTION.DROP, ref);
throw e;
}
}
ref.count++;
passNext(ACTION.SWAP, ref);
return ref.rrdDb;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testEntriesNeg80To80InRrd() throws IOException, FontFormatException {
createGaugeRrd(180);
RrdDb rrd = new RrdDb(jrbFileName);
for(int i=0; i<160; i++) {
long timestamp = startTime + 1 + (i * 60);
Sample sample = rrd.createSample();
sample.setAndUpdate(timestamp + ":" + (i -80));
}
rrd.close();
prepareGraph();
// Original
expectMajorGridLine(" -80");
expectMajorGridLine(" -40");
expectMajorGridLine(" 0");
expectMajorGridLine(" 40");
expectMajorGridLine(" 80");
run();
}
#location 10
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testEntriesNeg80To80InRrd() throws IOException, FontFormatException {
createGaugeRrd(180);
RrdDb rrd = RrdDb.getBuilder().setPath(jrbFileName).build();
for(int i=0; i<160; i++) {
long timestamp = startTime + 1 + (i * 60);
Sample sample = rrd.createSample();
sample.setAndUpdate(timestamp + ":" + (i -80));
}
rrd.close();
prepareGraph();
// Original
expectMajorGridLine(" -80");
expectMajorGridLine(" -40");
expectMajorGridLine(" 0");
expectMajorGridLine(" 40");
expectMajorGridLine(" 80");
run();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void realClose() throws IOException {
if (!closed) {
closed = true;
backend.rrdClose();
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
void internalClose() throws IOException {
if (!closed) {
closed = true;
backend.rrdClose();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public RrdDb requestRrdDb(String path) throws IOException {
RrdEntry ref = null;
try {
ref = getEntry(path, true);
} catch (InterruptedException e) {
throw new RuntimeException("request interrupted for " + path, e);
}
try {
//Wait until the pool is not full and
//Don't lock on anything
while(ref.count == 0 && ! tryGetSlot()) {
passNext(ACTION.SWAP, ref);
countLock.lockInterruptibly();
full.await();
countLock.unlock();
ref = getEntry(path, true);
}
} catch (InterruptedException e) {
passNext(ACTION.DROP, ref);
throw new RuntimeException("request interrupted for " + path, e);
} finally {
if(countLock.isHeldByCurrentThread()) {
countLock.unlock();
}
}
//Someone might have already open it, rechecks
if(ref.count == 0) {
try {
ref.rrdDb = new RrdDb(path);
} catch (IOException e) {
//Don't forget to release the slot reserved earlier
usage.decrementAndGet();
passNext(ACTION.DROP, ref);
throw e;
}
}
ref.count++;
passNext(ACTION.SWAP, ref);
return ref.rrdDb;
}
#location 41
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public RrdDb requestRrdDb(String path) throws IOException {
RrdEntry ref = null;
try {
ref = getEntry(path, true);
} catch (InterruptedException e) {
throw new RuntimeException("request interrupted for " + path, e);
}
//Someone might have already open it, rechecks
if(ref.count == 0) {
try {
ref.rrdDb = new RrdDb(path);
} catch (IOException e) {
//Don't forget to release the slot reserved earlier
usage.decrementAndGet();
passNext(ACTION.DROP, ref);
throw e;
}
}
ref.count++;
passNext(ACTION.SWAP, ref);
return ref.rrdDb;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testTwoEntriesInRrd() throws IOException, FontFormatException {
createGaugeRrd(100);
RrdDb rrd = new RrdDb(jrbFileName);
for(int i=0; i<2; i++) {
long timestamp = startTime + 1 + (i * 60);
Sample sample = rrd.createSample();
sample.setAndUpdate(timestamp+":100");
}
rrd.close();
prepareGraph();
expectMajorGridLine(" 90");
expectMinorGridLines(1);
expectMajorGridLine(" 100");
expectMinorGridLines(1);
expectMajorGridLine(" 110");
expectMinorGridLines(1);
expectMajorGridLine(" 120");
expectMinorGridLines(1);
run();
}
#location 10
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testTwoEntriesInRrd() throws IOException, FontFormatException {
createGaugeRrd(100);
RrdDb rrd = RrdDb.getBuilder().setPath(jrbFileName).build();
for(int i=0; i<2; i++) {
long timestamp = startTime + 1 + (i * 60);
Sample sample = rrd.createSample();
sample.setAndUpdate(timestamp+":100");
}
rrd.close();
prepareGraph();
expectMajorGridLine(" 90");
expectMinorGridLines(1);
expectMajorGridLine(" 100");
expectMinorGridLines(1);
expectMajorGridLine(" 110");
expectMinorGridLines(1);
expectMajorGridLine(" 120");
expectMinorGridLines(1);
run();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testBackendFactory() throws IOException {
RrdRandomAccessFileBackendFactory factory = (RrdRandomAccessFileBackendFactory) RrdBackendFactory.getFactory("FILE");
File rrdfile = testFolder.newFile("testfile");
RrdBackend be = factory.open(rrdfile.getCanonicalPath(), false);
be.setLength(10);
be.writeDouble(0, 0);
be.close();
DataInputStream is = new DataInputStream(new FileInputStream(rrdfile));
Double d = is.readDouble();
Assert.assertEquals("write to random access file failed", 0, d, 1e-10);
is.close();
}
#location 15
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testBackendFactory() throws IOException {
File rrdfile = testFolder.newFile("testfile");
try(RrdRandomAccessFileBackendFactory factory = new RrdRandomAccessFileBackendFactory()) {
super.testBackendFactory(factory,rrdfile.getCanonicalPath());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void release(RrdDb rrdDb) throws IOException {
// null pointer should not kill the thread, just ignore it
if (rrdDb == null) {
return;
}
RrdEntry ref;
try {
ref = getEntry(rrdDb.getPath(), false);
} catch (InterruptedException e) {
throw new RuntimeException("release interrupted for " + rrdDb, e);
}
if(ref == null) {
return;
}
if (ref.count <= 0) {
passNext(ACTION.DROP, ref);
throw new IllegalStateException("Could not release [" + rrdDb.getPath() + "], the file was never requested");
}
if (--ref.count == 0) {
if(ref.rrdDb == null) {
passNext(ACTION.DROP, ref);
throw new IllegalStateException("Could not release [" + rrdDb.getPath() + "], pool corruption");
}
ref.rrdDb.close();
usage.decrementAndGet();
try {
countLock.lockInterruptibly();
if(usage.get() < maxCapacity) {
full.signal();
}
countLock.unlock();
} catch (InterruptedException e) {
throw new RuntimeException("release interrupted for " + rrdDb, e);
} finally {
passNext(ACTION.DROP, ref);
}
//If someone is waiting for an empty entry, signal it
ref.waitempty.countDown();
} else {
passNext(ACTION.SWAP, ref);
}
}
#location 21
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void release(RrdDb rrdDb) throws IOException {
// null pointer should not kill the thread, just ignore it
if (rrdDb == null) {
return;
}
RrdEntry ref;
try {
ref = getEntry(rrdDb.getPath(), false);
} catch (InterruptedException e) {
throw new RuntimeException("release interrupted for " + rrdDb, e);
}
if(ref == null) {
return;
}
if (ref.count <= 0) {
passNext(ACTION.DROP, ref);
throw new IllegalStateException("Could not release [" + rrdDb.getPath() + "], the file was never requested");
}
if (--ref.count == 0) {
if(ref.rrdDb == null) {
passNext(ACTION.DROP, ref);
throw new IllegalStateException("Could not release [" + rrdDb.getPath() + "], pool corruption");
}
ref.rrdDb.close();
passNext(ACTION.DROP, ref);
//If someone is waiting for an empty entry, signal it
ref.waitempty.countDown();
} else {
passNext(ACTION.SWAP, ref);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testEntriesZeroTo100InRrd() throws IOException, FontFormatException {
createGaugeRrd(105); //Make sure all entries are recorded (5 is just a buffer for consolidation)
RrdDb rrd = new RrdDb(jrbFileName);
for(int i=0; i<100; i++) {
long timestamp = startTime + 1 + (i * 60);
Sample sample = rrd.createSample();
sample.setAndUpdate(timestamp + ":" + i);
}
rrd.close();
prepareGraph();
expectMinorGridLines(4);
expectMajorGridLine(" 50");
expectMinorGridLines(4);
expectMajorGridLine(" 100");
run();
}
#location 10
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testEntriesZeroTo100InRrd() throws IOException, FontFormatException {
createGaugeRrd(105); //Make sure all entries are recorded (5 is just a buffer for consolidation)
RrdDb rrd = RrdDb.getBuilder().setPath(jrbFileName).build();
for(int i=0; i<100; i++) {
long timestamp = startTime + 1 + (i * 60);
Sample sample = rrd.createSample();
sample.setAndUpdate(timestamp + ":" + i);
}
rrd.close();
prepareGraph();
expectMinorGridLines(4);
expectMajorGridLine(" 50");
expectMinorGridLines(4);
expectMajorGridLine(" 100");
run();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testEntriesNeg80To90InRrd() throws IOException, FontFormatException {
createGaugeRrd(180);
RrdDb rrd = new RrdDb(jrbFileName);
for(int i=0; i<170; i++) {
long timestamp = startTime + 1 + (i * 60);
Sample sample = rrd.createSample();
sample.setAndUpdate(timestamp + ":" + (i -80));
}
rrd.close();
prepareGraph();
expectMajorGridLine(" -90");
expectMajorGridLine(" -45");
expectMajorGridLine(" 0");
expectMajorGridLine(" 45");
expectMajorGridLine(" 90");
run();
}
#location 10
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testEntriesNeg80To90InRrd() throws IOException, FontFormatException {
createGaugeRrd(180);
RrdDb rrd = RrdDb.getBuilder().setPath(jrbFileName).build();
for(int i=0; i<170; i++) {
long timestamp = startTime + 1 + (i * 60);
Sample sample = rrd.createSample();
sample.setAndUpdate(timestamp + ":" + (i -80));
}
rrd.close();
prepareGraph();
expectMajorGridLine(" -90");
expectMajorGridLine(" -45");
expectMajorGridLine(" 0");
expectMajorGridLine(" 45");
expectMajorGridLine(" 90");
run();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public RrdDb requestRrdDb(String path, String sourcePath)
throws IOException {
RrdEntry ref = null;
try {
do {
ref = getEntry(path, true);
if(ref.count != 0) {
//Not empty, give it back, but wait for signal
passNext(ACTION.SWAP, ref);
ref.waitempty.await();
// ref is not a real reference (not replaced by a placeholder
// So must try a get entry before carry on
ref = null; //might be checked by the catch
continue;
}
} while(ref.count != 0);
} catch (InterruptedException e) {
if(ref != null) {
passNext(ACTION.SWAP, ref);
}
throw new RuntimeException("request interrupted for new rrd " + path, e);
}
try {
ref.rrdDb = new RrdDb(path, sourcePath);
ref.count = 1;
capacity.acquire();
return ref.rrdDb;
} catch (InterruptedException e) {
throw new RuntimeException("request interrupted for new rrd " + path, e);
} finally {
passNext(ACTION.SWAP, ref);
}
}
#location 16
#vulnerability type NULL_DEREFERENCE | #fixed code
public RrdDb requestRrdDb(String path, String sourcePath)
throws IOException {
RrdEntry ref = null;
try {
ref = requestEmpty(path);
ref.rrdDb = new RrdDb(path, sourcePath);
return ref.rrdDb;
} catch (InterruptedException e) {
throw new RuntimeException("request interrupted for new rrd " + path, e);
} finally {
if(ref != null) {
passNext(ACTION.SWAP, ref);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testBackendFactoryDefaults() throws IOException {
// Don't close a default NIO, it will close the background sync threads executor
@SuppressWarnings("resource")
RrdNioBackendFactory factory = new RrdNioBackendFactory();
File rrdfile = testFolder.newFile("testfile");
super.testBackendFactory(factory,rrdfile.getCanonicalPath());
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testBackendFactoryDefaults() throws IOException {
try (RrdNioBackendFactory factory = new RrdNioBackendFactory(0)) {
File rrdfile = testFolder.newFile("testfile");
super.testBackendFactory(factory,rrdfile.getCanonicalPath());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.