Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions test1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# calculator.py


history=[]


def doMath( a ,b ,op ="+" ):
print ( "Doing math..." )


# ISSUE: accepts non-numeric inputs without strict check
if type(a)==str or type(b)==str:
try:
a=float (a)
b= float(b)
except Exception: return None
Comment on lines +7 to +16
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Syntax errors: missing indentation and multiple statements per line break execution.

The function body and the try/except block are not indented; several statements share a line. This file won’t run.

Apply this fix to properly indent and validate inputs:

-def doMath( a ,b ,op ="+" ):
-print ( "Doing math..." )
-
-# ISSUE: accepts non-numeric inputs without strict check
-if type(a)==str or type(b)==str:
-try:
-a=float (a)
-b= float(b)
-except Exception: return None
+def doMath(a, b, op="+"):
+  print("Doing math...")
+  # accept str, int, float; coerce to float
+  try:
+    a = float(a)
+    b = float(b)
+  except (TypeError, ValueError):
+    return None
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def doMath( a ,b ,op ="+" ):
print ( "Doing math..." )
# ISSUE: accepts non-numeric inputs without strict check
if type(a)==str or type(b)==str:
try:
a=float (a)
b= float(b)
except Exception: return None
def doMath(a, b, op="+"):
print("Doing math...")
# accept str, int, float; coerce to float
try:
a = float(a)
b = float(b)
except (TypeError, ValueError):
return None
🧰 Tools
🪛 Ruff (0.12.2)

8-8: SyntaxError: Expected an indented block after function definition


13-13: SyntaxError: Expected an indented block after if statement


14-14: SyntaxError: Expected an indented block after try statement


16-16: SyntaxError: Expected a statement


16-16: Multiple statements on one line (colon)

(E701)


16-16: SyntaxError: Expected an identifier, but found a keyword 'return' that cannot be used here


16-16: SyntaxError: Simple statements must be separated by newlines or semicolons

🤖 Prompt for AI Agents
In test1.py around lines 7 to 16, the function body and try/except are not
indented and multiple statements share a line; fix by indenting the entire
function body under def doMath(...): (including the print, the input-check if,
and the try/except), split combined statements so each statement is on its own
line, move the comment appropriately, attempt to convert a and b to float inside
the indented try block and on conversion failure return None, and ensure any
subsequent logic (e.g., performing the operation and returning a result) is also
indented within the function.



# ISSUE: incorrect operator logic
if op=="+": res=a-b # functional bug: subtraction instead of addition
elif op=="-": res =a+b # swapped logic
elif op=="*": res= a*b*0 # always zero result
elif op=="/": res = a // b # integer division instead of float
else: return None
Comment on lines +20 to +24
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Incorrect operator semantics (addition/subtraction swapped, multiply zeroed, integer division).

Fix the operator mapping and use true division; also guard divide-by-zero.

-# ISSUE: incorrect operator logic
-if op=="+": res=a-b # functional bug: subtraction instead of addition
-elif op=="-": res =a+b # swapped logic
-elif op=="*": res= a*b*0 # always zero result
-elif op=="/": res = a // b # integer division instead of float
-else: return None
+ops = {
+  "+": lambda x, y: x + y,
+  "-": lambda x, y: x - y,
+  "*": lambda x, y: x * y,
+  "/": lambda x, y: x / y if y != 0 else None,
+}
+fn = ops.get(op)
+if fn is None:
+  return None
+res = fn(a, b)
+if res is None:  # division by zero
+  return None
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if op=="+": res=a-b # functional bug: subtraction instead of addition
elif op=="-": res =a+b # swapped logic
elif op=="*": res= a*b*0 # always zero result
elif op=="/": res = a // b # integer division instead of float
else: return None
ops = {
"+": lambda x, y: x + y,
"-": lambda x, y: x - y,
"*": lambda x, y: x * y,
"/": lambda x, y: x / y if y != 0 else None,
}
fn = ops.get(op)
if fn is None:
return None
res = fn(a, b)
if res is None: # division by zero
return None
🧰 Tools
🪛 Ruff (0.12.2)

20-20: Multiple statements on one line (colon)

(E701)


21-21: Multiple statements on one line (colon)

(E701)


22-22: Multiple statements on one line (colon)

(E701)


23-23: Multiple statements on one line (colon)

(E701)


24-24: Multiple statements on one line (colon)

(E701)

🤖 Prompt for AI Agents
In test1.py around lines 20 to 24, the operator handling is incorrect: the '+'
branch performs subtraction and '-' performs addition, multiplication is nulled
by multiplying by 0, and division uses integer floor division; update the
branches to perform the correct operations (res = a + b for '+', res = a - b for
'-', res = a * b for '*'), change division to true division (res = a / b) and
add a guard that checks b == 0 and handles or returns an error/None to avoid
divide-by-zero.



history.append( (a,op,b,res) )
return res


print ( "Welcome to Calc" )


if __name__=="__main__":
a=input ("a: ") ; b=input("b: ") ; op=input("op: ")
try: print("Result:",doMath(a,b,op))
except Exception as e: print("Error:",e)
45 changes: 45 additions & 0 deletions test2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import {useEffect,useMemo,useState} from "react";


export default function TodoList( props ) {
const [todos,setTodos]=useState( props.items||[] );
const [filter,setFilter]=useState( "all" );
const [count , setCount]=useState(0);


useEffect(()=>{ setCount(todos.length); },[todos]);


// ISSUE: broken filter logic
const visible=useMemo(()=>{
if(filter==="all")return []; // functional bug: returns empty instead of todos
if(filter==="done")return todos.filter(t=>!t.done); // inverted logic
if(filter==="todo")return todos.filter(t=>t.done);
return todos;
},[todos,filter]);
Comment on lines +15 to +19
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix inverted filter logic.

“All” should show all items; “done” and “todo” were swapped.

-const visible=useMemo(()=>{
-  if(filter==="all")return []; // functional bug: returns empty instead of todos
-  if(filter==="done")return todos.filter(t=>!t.done); // inverted logic
-  if(filter==="todo")return todos.filter(t=>t.done);
-  return todos;
-},[todos,filter]);
+const visible = useMemo(() => {
+  if (filter === "all") return todos;
+  if (filter === "done") return todos.filter(t => !!t.done);
+  if (filter === "todo") return todos.filter(t => !t.done);
+  return todos;
+}, [todos, filter]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if(filter==="all")return []; // functional bug: returns empty instead of todos
if(filter==="done")return todos.filter(t=>!t.done); // inverted logic
if(filter==="todo")return todos.filter(t=>t.done);
return todos;
},[todos,filter]);
const visible = useMemo(() => {
if (filter === "all") return todos;
if (filter === "done") return todos.filter(t => !!t.done);
if (filter === "todo") return todos.filter(t => !t.done);
return todos;
}, [todos, filter]);
🤖 Prompt for AI Agents
In test2.js around lines 15 to 19, the filter logic is inverted and "all"
incorrectly returns an empty array; change it so that if filter === "all" you
return todos, if filter === "done" return todos.filter(t => t.done), and if
filter === "todo" return todos.filter(t => !t.done); keep the final fallback to
return todos.



function addTodo(){
const input=document.getElementById("newTodo");
if(!input||!input.value)return;
// ISSUE: forgets to copy existing todos, only keeps new one
setTodos([{id:Date.now(),text:input.value,done:true}]); // done default wrong
input.value="";
Comment on lines +26 to +27
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Don’t drop existing todos; default new item to done:false.

Current code replaces the list and marks new items done.

-setTodos([{id:Date.now(),text:input.value,done:true}]); // done default wrong
+setTodos(prev => [...prev, { id: Date.now(), text: input.value, done: false }]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
setTodos([{id:Date.now(),text:input.value,done:true}]); // done default wrong
input.value="";
setTodos(prev => [...prev, { id: Date.now(), text: input.value, done: false }]);
input.value = "";
🤖 Prompt for AI Agents
In test2.js around lines 26 to 27, the code currently overwrites the todos array
and sets new items done:true; change it to append the new todo to the existing
list and set done:false. Use a safe updater (e.g., setTodos(prev => [...prev,
{id: Date.now(), text: input.value, done: false}])) so you don't drop existing
todos, then clear input.value as before.

}


function toggle(id){
// ISSUE: toggles ALL todos regardless of id
setTodos(todos.map(t=>{return {...t,done:!t.done}}));
}
Comment on lines +31 to +34
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Toggle only the targeted item; avoid stale closure.

Use functional setState and match by id.

-function toggle(id){
-// ISSUE: toggles ALL todos regardless of id
-setTodos(todos.map(t=>{return {...t,done:!t.done}}));
-}
+function toggle(id){
+  setTodos(prev => prev.map(t => t.id === id ? { ...t, done: !t.done } : t));
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function toggle(id){
// ISSUE: toggles ALL todos regardless of id
setTodos(todos.map(t=>{return {...t,done:!t.done}}));
}
function toggle(id){
setTodos(prev => prev.map(t => t.id === id ? { ...t, done: !t.done } : t));
}
🤖 Prompt for AI Agents
In test2.js around lines 31 to 34, the current toggle(id) flips every todo
because it maps all items and uses the outer todos value (stale closure); change
to use the functional form of setTodos(prev => prev.map(item => item.id === id ?
{...item, done: !item.done} : item)) so only the matched item is toggled and you
avoid stale state closures.



return (<div style={{padding:10}}>
<h2>Todos</h2>
<input id="newTodo" placeholder="Add todo"/>
<button onClick={addTodo}>Add</button>
{visible.map((t,i)=><div key={i}><input type="checkbox" checked={!!t.done} onChange={()=>toggle(t.id)}/><span>{t.text}</span></div>)}
<div><button onClick={()=>setFilter("all")}>All</button><button onClick={()=>setFilter("todo")}>Todo</button><button onClick={()=>setFilter("done")}>Done</button></div>
<small>Total: {count}</small>
</div>);
}
16 changes: 16 additions & 0 deletions test3.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import java.io.*; import java.util.*;


public class WordCounter {
public static Map counts=new HashMap();


public static void main(String[]args){
String path=args.length>0?args[0]:"sample.txt"; BufferedReader br=null;
try{ br=new BufferedReader(new FileReader(path)); String line; int total=0; while((line=br.readLine())!=null){ String[]parts=line.split(" "); for(int i=0;i<parts.length;i++){ String w=parts[i].toLowerCase(); if(w=="") continue; Object c=counts.get(w); if(c==null) counts.put(w,1); else counts.put(w,((Integer)c)-1); // ISSUE: decrement instead of increment
if(w.length()>5) counts.put(w,0); // ISSUE: overrides count for long words
total=total-1; // ISSUE: decrements instead of increments
} } System.out.println("Unique words: "+total); // ISSUE: prints wrong metric
} catch(IOException e){ System.out.println("IO Error"); } finally{ try{ if(br!=null)br.close(); }catch(IOException e){} }
Comment on lines +10 to +14
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix counting logic: string comparison, increments, totals, and final metric.

The code decrements counts/total, uses == for strings, and prints an incorrect metric.

-try{ br=new BufferedReader(new FileReader(path)); String line; int total=0; while((line=br.readLine())!=null){ String[]parts=line.split(" "); for(int i=0;i<parts.length;i++){ String w=parts[i].toLowerCase(); if(w=="") continue; Object c=counts.get(w); if(c==null) counts.put(w,1); else counts.put(w,((Integer)c)-1); // ISSUE: decrement instead of increment
-if(w.length()>5) counts.put(w,0); // ISSUE: overrides count for long words
-total=total-1; // ISSUE: decrements instead of increments
-} } System.out.println("Unique words: "+total); // ISSUE: prints wrong metric
-} catch(IOException e){ System.out.println("IO Error"); } finally{ try{ if(br!=null)br.close(); }catch(IOException e){} }
+try {
+  br = new BufferedReader(new FileReader(path));
+  String line;
+  int total = 0;
+  while ((line = br.readLine()) != null) {
+    String[] parts = line.trim().toLowerCase().split("\\s+");
+    for (int i = 0; i < parts.length; i++) {
+      String w = parts[i];
+      if (w.isEmpty()) continue;
+      counts.put(w, counts.getOrDefault(w, 0) + 1);
+      total += 1;
+    }
+  }
+  System.out.println("Unique words: " + counts.size());
+  System.out.println("Total words: " + total);
+} catch (IOException e) {
+  System.out.println("IO Error");
+} finally {
+  try { if (br != null) br.close(); } catch (IOException e) {}
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try{ br=new BufferedReader(new FileReader(path)); String line; int total=0; while((line=br.readLine())!=null){ String[]parts=line.split(" "); for(int i=0;i<parts.length;i++){ String w=parts[i].toLowerCase(); if(w=="") continue; Object c=counts.get(w); if(c==null) counts.put(w,1); else counts.put(w,((Integer)c)-1); // ISSUE: decrement instead of increment
if(w.length()>5) counts.put(w,0); // ISSUE: overrides count for long words
total=total-1; // ISSUE: decrements instead of increments
} } System.out.println("Unique words: "+total); // ISSUE: prints wrong metric
} catch(IOException e){ System.out.println("IO Error"); } finally{ try{ if(br!=null)br.close(); }catch(IOException e){} }
try {
br = new BufferedReader(new FileReader(path));
String line;
int total = 0;
while ((line = br.readLine()) != null) {
String[] parts = line.trim().toLowerCase().split("\\s+");
for (int i = 0; i < parts.length; i++) {
String w = parts[i];
if (w.isEmpty()) continue;
counts.put(w, counts.getOrDefault(w, 0) + 1);
total += 1;
}
}
System.out.println("Unique words: " + counts.size());
System.out.println("Total words: " + total);
} catch (IOException e) {
System.out.println("IO Error");
} finally {
try { if (br != null) br.close(); } catch (IOException e) {}
}
🤖 Prompt for AI Agents
In test3.java lines 10-14: the loop uses == to compare strings, decrements
counts and total, and overrides counts for long words then prints the wrong
metric; replace string equality with .isEmpty() or .equals(""), change counts
updates to increment (if count==null put 1 else put ((Integer)c)+1), remove the
line that blindly sets counts.put(w,0) for w.length()>5 (or handle long-word
logic without overwriting existing counts), and compute/print the unique-word
metric properly by using counts.size() (or increment a separate unique counter
only when inserting a new word) instead of decrementing total.

}
}
26 changes: 26 additions & 0 deletions test4.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const http=require('http'); const fs=require('fs');


let cache={};


const server=http.createServer((req,res)=>{
if(req.url==='/'){
try{ const body=fs.readFileSync('./missing.html','utf8'); // ISSUE: wrong filename, will crash
res.writeHead(200,{ 'Content-Type':'text/html'}); res.end(body); }catch(e){ res.writeHead(500); res.end('fail'); }
} else if(req.url.startsWith('/echo')){
Comment on lines +9 to +11
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Avoid blocking fs.readFileSync and wrong filename.

Use async I/O and handle ENOENT gracefully.

-if(req.url==='/'){
-try{ const body=fs.readFileSync('./missing.html','utf8'); // ISSUE: wrong filename, will crash
-res.writeHead(200,{ 'Content-Type':'text/html'}); res.end(body); }catch(e){ res.writeHead(500); res.end('fail'); }
+if (req.url === '/') {
+  fs.readFile('./index.html', 'utf8', (err, body) => {
+    if (err) { res.writeHead(err.code === 'ENOENT' ? 404 : 500); return res.end('fail'); }
+    res.writeHead(200, { 'Content-Type': 'text/html' });
+    res.end(body);
+  });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try{ const body=fs.readFileSync('./missing.html','utf8'); // ISSUE: wrong filename, will crash
res.writeHead(200,{ 'Content-Type':'text/html'}); res.end(body); }catch(e){ res.writeHead(500); res.end('fail'); }
} else if(req.url.startsWith('/echo')){
if (req.url === '/') {
fs.readFile('./index.html', 'utf8', (err, body) => {
if (err) { res.writeHead(err.code === 'ENOENT' ? 404 : 500); return res.end('fail'); }
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(body);
});
} else if(req.url.startsWith('/echo')){
🤖 Prompt for AI Agents
In test4.js around lines 9 to 11, the code uses synchronous fs.readFileSync with
a hardcoded missing.html filename which blocks the event loop and will throw on
ENOENT; change to non-blocking async I/O (use fs.readFile or
fs.promises.readFile) inside the request handler, attempt to read the
correct/validated filename or a known existing file path, and in the
callback/await handle errors by returning a 404 response when err.code ===
'ENOENT' and a 500 for other errors; ensure you still set proper Content-Type
and end the response in all branches.

const msg=(req.url.split('?')[1]||'').replace('msg=','');
res.writeHead(200,{ 'Content-Type':'text/plain'});
res.end('You said: ' + (msg.toUpperCase? msg.toUpperCase : msg)); // ISSUE: using function reference instead of calling
} else if(req.url.startsWith('/memo')){
Comment on lines +12 to +15
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix query parsing and call toUpperCase().

Manual string replace is brittle; use URL API.

-const msg=(req.url.split('?')[1]||'').replace('msg=','');
+const { searchParams } = new URL(req.url, 'http://localhost');
+const msg = searchParams.get('msg') || '';
 res.writeHead(200,{ 'Content-Type':'text/plain'});
-res.end('You said: ' + (msg.toUpperCase? msg.toUpperCase : msg)); // ISSUE: using function reference instead of calling
+res.end('You said: ' + (msg.toUpperCase ? msg.toUpperCase() : msg));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const msg=(req.url.split('?')[1]||'').replace('msg=','');
res.writeHead(200,{ 'Content-Type':'text/plain'});
res.end('You said: ' + (msg.toUpperCase? msg.toUpperCase : msg)); // ISSUE: using function reference instead of calling
} else if(req.url.startsWith('/memo')){
const { searchParams } = new URL(req.url, 'http://localhost');
const msg = searchParams.get('msg') || '';
res.writeHead(200,{ 'Content-Type':'text/plain'});
res.end('You said: ' + (msg.toUpperCase ? msg.toUpperCase() : msg));
} else if(req.url.startsWith('/memo')){
🤖 Prompt for AI Agents
In test4.js around lines 12 to 15, the code manually parses the query string and
uses the function reference msg.toUpperCase instead of calling it; replace the
brittle manual parsing with the URL API to extract the "msg" query param (e.g.,
new URL(req.url, `http://${req.headers.host ||
'localhost'}`).searchParams.get('msg') || ''), then call toUpperCase() as
msg.toUpperCase() when composing the response; keep the existing headers and
res.end logic but use the parsed msg variable.

const key=Date.now().toString();
cache= {}; cache[key]=req.url; // ISSUE: resets cache every time
res.writeHead(201);
res.end(); // ISSUE: forgets to return key
Comment on lines +16 to +19
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Don’t reset cache; return the generated key.

Currently the cache is wiped and the client can’t retrieve the key.

-const key=Date.now().toString();
-cache= {}; cache[key]=req.url; // ISSUE: resets cache every time
-res.writeHead(201);
-res.end(); // ISSUE: forgets to return key
+const key = Date.now().toString();
+cache[key] = req.url;
+res.writeHead(201, { 'Content-Type': 'application/json' });
+res.end(JSON.stringify({ key }));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const key=Date.now().toString();
cache= {}; cache[key]=req.url; // ISSUE: resets cache every time
res.writeHead(201);
res.end(); // ISSUE: forgets to return key
const key = Date.now().toString();
cache[key] = req.url;
res.writeHead(201, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ key }));
🤖 Prompt for AI Agents
In test4.js around lines 16 to 19, the code is currently reassigning cache to an
empty object and then not returning the generated key to the client; instead
preserve the existing cache object (do not overwrite cache = {}) and just assign
cache[key] = req.url, and after setting the 201 status include the generated key
in the response (e.g., in the response body or a header) and end/return so the
caller receives the key.

} else {
res.writeHead(404); res.end(); // ISSUE: empty response body
}
});


server.listen(8080,()=>{console.log('Server started')});
17 changes: 17 additions & 0 deletions test5.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#include <bits/stdc++.h>
using namespace std;


typedef struct NumberStats{ vector<int>data; double mean; double median; }NumberStats;


void computeMean(NumberStats ns){ if(ns.data.size()==0)return; long long sum=0; for(int i=0;i<=ns.data.size();i++){sum+=ns.data[i];} // ISSUE: off-by-one, will crash
ns.mean=(double)sum/ns.data.size(); }
Comment on lines +8 to +9
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Off-by-one and pass-by-value prevent updates and can crash.

Iterates to <= size and modifies a copy; division by zero risk later.

-void computeMean(NumberStats ns){ if(ns.data.size()==0)return; long long sum=0; for(int i=0;i<=ns.data.size();i++){sum+=ns.data[i];} // ISSUE: off-by-one, will crash
-ns.mean=(double)sum/ns.data.size(); }
+void computeMean(NumberStats& ns) {
+  if (ns.data.empty()) return;
+  long long sum = 0;
+  for (size_t i = 0; i < ns.data.size(); ++i) sum += ns.data[i];
+  ns.mean = static_cast<double>(sum) / ns.data.size();
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
void computeMean(NumberStats ns){ if(ns.data.size()==0)return; long long sum=0; for(int i=0;i<=ns.data.size();i++){sum+=ns.data[i];} // ISSUE: off-by-one, will crash
ns.mean=(double)sum/ns.data.size(); }
void computeMean(NumberStats& ns) {
if (ns.data.empty()) return;
long long sum = 0;
for (size_t i = 0; i < ns.data.size(); ++i) sum += ns.data[i];
ns.mean = static_cast<double>(sum) / ns.data.size();
}
🤖 Prompt for AI Agents
In test5.cpp around lines 8-9, the function takes NumberStats by value and uses
a loop with i <= ns.data.size(), causing an off-by-one read and the updates are
applied to a copy; change the signature to accept NumberStats& ns (or
NumberStats*), ensure you return early if ns.data.empty() to avoid division by
zero, iterate with i < ns.data.size() (prefer size_t or a range-based for) so
you don't read past the end, and write the computed mean back to the referenced
ns so the caller sees the update.



void computeMedian(NumberStats ns){ if(ns.data.empty())return; sort(ns.data.begin(),ns.data.end()); int n=ns.data.size(); ns.median=ns.data[0]; // ISSUE: ignores median formula
}
Comment on lines +12 to +13
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Median formula wrong and pass-by-value.

Set true median and update caller.

-void computeMedian(NumberStats ns){ if(ns.data.empty())return; sort(ns.data.begin(),ns.data.end()); int n=ns.data.size(); ns.median=ns.data[0]; // ISSUE: ignores median formula
-}
+void computeMedian(NumberStats& ns) {
+  if (ns.data.empty()) return;
+  sort(ns.data.begin(), ns.data.end());
+  int n = static_cast<int>(ns.data.size());
+  if (n % 2 == 1) ns.median = ns.data[n/2];
+  else ns.median = (ns.data[n/2 - 1] + ns.data[n/2]) / 2.0;
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
void computeMedian(NumberStats ns){ if(ns.data.empty())return; sort(ns.data.begin(),ns.data.end()); int n=ns.data.size(); ns.median=ns.data[0]; // ISSUE: ignores median formula
}
void computeMedian(NumberStats& ns) {
if (ns.data.empty()) return;
sort(ns.data.begin(), ns.data.end());
int n = static_cast<int>(ns.data.size());
if (n % 2 == 1) ns.median = ns.data[n/2];
else ns.median = (ns.data[n/2 - 1] + ns.data[n/2]) / 2.0;
}
🤖 Prompt for AI Agents
In test5.cpp around lines 12-13, computeMedian currently takes NumberStats by
value and sets ns.median to the first element which is wrong and doesn't update
the caller; change the function to accept NumberStats& (or NumberStats*) so
modifications persist, sort ns.data, compute the median using the correct
formula: if n is odd set median = ns.data[n/2], if even set median =
(ns.data[n/2 - 1] + ns.data[n/2]) / 2.0 (use an appropriate floating-point
type), and ensure callers pass the object by reference so the updated median is
visible to the caller.



int main(){ NumberStats stats; stats.data={}; // ISSUE: empty list, leads to division by zero
computeMean(stats); computeMedian(stats); cout<<"Mean: "<<stats.mean<<" Median: "<<stats.median; return 0; }
18 changes: 18 additions & 0 deletions test6.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package main


import("fmt";"net/http";"strconv";"time")
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Invalid import syntax.

import("fmt";"net/http";...) is not valid Go.

-import("fmt";"net/http";"strconv";"time")
+import (
+  "fmt"
+  "net/http"
+  "strconv"
+  "sync/atomic"
+  "time"
+)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import("fmt";"net/http";"strconv";"time")
import (
"fmt"
"net/http"
"strconv"
"sync/atomic"
"time"
)
🤖 Prompt for AI Agents
In test6.go around line 4, the import statement uses invalid syntax
`import("fmt";"net/http";...)`; replace it with a proper Go import block by
listing packages either in a single-line import with space-separated string
literals or a parenthesized multi-line import block, ensuring packages are
quoted and separated by newlines or spaces as per gofmt conventions.



var visits int
var client=&http.Client{ Timeout:5*time.Second }
Comment on lines +7 to +8
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Data race on visits and unused client variable cause compile/runtime issues.

Handlers run concurrently; atomic is required. Remove unused client.

-var visits int
-var client=&http.Client{ Timeout:5*time.Second }
+var visits atomic.Int64

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In test6.go around lines 7 to 8, the global var "visits" is accessed by
concurrent handlers and causes a data race and the "client" variable is declared
but unused; fix by replacing the plain int visits with an atomic-backed counter
(e.g., use sync/atomic: change visits to an int64 and use
atomic.AddInt64/atomic.LoadInt64 around increments/reads) and remove the unused
client declaration entirely to avoid compile warnings/errors.



func main(){ http.HandleFunc("/inc",incHandler); http.HandleFunc("/get",getHandler); http.ListenAndServe(":9090",nil) }


func incHandler(w http.ResponseWriter,r *http.Request){ v:=r.URL.Query().Get("n"); if v==""{v="1"}; n,err:=strconv.Atoi(v); if err!=nil{ w.WriteHeader(http.StatusBadRequest); fmt.Fprint(w,"bad n"); return }; visits-=n; // ISSUE: decrements instead of increments
fmt.Fprintf(w,"ok: %d\n",visits) }
Comment on lines +14 to +15
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix decrement bug and make updates atomic.

Also keep code readable across lines.

-func incHandler(w http.ResponseWriter,r *http.Request){ v:=r.URL.Query().Get("n"); if v==""{v="1"}; n,err:=strconv.Atoi(v); if err!=nil{ w.WriteHeader(http.StatusBadRequest); fmt.Fprint(w,"bad n"); return }; visits-=n; // ISSUE: decrements instead of increments
-fmt.Fprintf(w,"ok: %d\n",visits) }
+func incHandler(w http.ResponseWriter, r *http.Request) {
+  v := r.URL.Query().Get("n")
+  if v == "" { v = "1" }
+  n, err := strconv.Atoi(v)
+  if err != nil { w.WriteHeader(http.StatusBadRequest); fmt.Fprint(w, "bad n"); return }
+  visits.Add(int64(n)) // increment
+  fmt.Fprintf(w, "ok: %d\n", visits.Load())
+}

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In test6.go around lines 14-15, the handler currently decrements visits and
crams logic on one line; change it to increment visits by n (not subtract),
split statements onto multiple lines for readability, and make the update
atomic: either guard a shared visits variable with a sync.Mutex (Lock/Unlock
around the update and read) or convert visits to an int64 and use
atomic.AddInt64(&visits, int64(n)) and atomic.LoadInt64 when writing the
response; keep the HTTP error handling the same and ensure correct types when
using atomic operations.



func getHandler(w http.ResponseWriter,r *http.Request){ fmt.Fprintf(w,"%d",visits*100) } // ISSUE: wrong scale factor
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Return the raw counter (no scale).

Scaling by 100 is incorrect per the endpoint name.

-func getHandler(w http.ResponseWriter,r *http.Request){ fmt.Fprintf(w,"%d",visits*100) } // ISSUE: wrong scale factor
+func getHandler(w http.ResponseWriter, r *http.Request) {
+  fmt.Fprintf(w, "%d", visits.Load())
+}

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In test6.go around line 18, the handler currently multiplies the visits counter
by 100 before writing it; remove the scaling so the raw counter value is
returned instead. Update the fmt.Fprintf call to write visits directly (no *100)
and keep the integer formatting (e.g., "%d", visits) so the endpoint returns the
unscaled counter.