Skip to content

Conversation

@omar-coderabbitai
Copy link
Owner

@omar-coderabbitai omar-coderabbitai commented Sep 16, 2025

Lets see if anything changes

Summary by CodeRabbit

  • New Features
    • Added a simple calculator CLI with a persistent history and basic operations.
    • Introduced a Todo List UI component with filtering, add, toggle, and item count.
    • Added a word counter CLI that processes a text file and reports unique word metrics.
    • Introduced a lightweight HTTP server with HTML response, echo, and memo endpoints.
    • Added an HTTP service exposing visit counter endpoints.
    • Added a number statistics tool computing mean and median from a list.

@coderabbitai
Copy link

coderabbitai bot commented Sep 16, 2025

Walkthrough

Adds six new files across Python, JavaScript, Java, C++, and Go: a Python calculator module with CLI and history, a React TodoList component, a Java word counter program, a Node.js HTTP server, a C++ NumberStats demo with compute functions and main, and a Go HTTP server with counter endpoints.

Changes

Cohort / File(s) Summary
Python CLI calculator
calculator.py
New module with global history, doMath(a, b, op="+"), startup print, and __main__ CLI prompting for inputs and printing the result. Includes type coercion, operator mapping, and history appends.
React component
test2.js
New default-exported TodoList functional component with state for todos, filter, and count; effect to sync count; memoized filtered view; handlers addTodo() and toggle(id); renders input, list, filters, and count.
Java word counter
test3.java
New public class WordCounter with public static Map counts, main(String[] args) reading a file, tokenizing, updating counts, tracking a total, and printing a final metric; includes IO handling with try-catch-finally.
Node.js HTTP server
test4.js
New HTTP server on port 8080 with routes: / (serve local HTML), /echo (query msg echo), /memo (cache key write), fallback 404; logs on start; uses in-memory cache.
C++ NumberStats demo
test5.cpp
Adds NumberStats struct, functions computeMean(NumberStats) and computeMedian(NumberStats), and main() initializing empty data, invoking functions, and printing mean/median.
Go HTTP server
test6.go
New Go program with global visits, HTTP client (5s timeout), handlers /inc (parse n, update visits) and /get (return derived value), and server startup on port 9090.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant CLI as calculator.py (__main__)
  participant Mod as doMath()

  User->>CLI: Run module
  CLI->>User: Prompt a, b, op
  User-->>CLI: Inputs
  CLI->>Mod: doMath(a, b, op)
  Mod-->>CLI: result
  CLI->>User: Print "Result: <res>" or error
Loading
sequenceDiagram
  autonumber
  actor Browser
  participant UI as TodoList Component
  Browser->>UI: Mount with props.items
  UI->>UI: Init state (todos, filter, count)
  UI->>UI: useEffect sync count on todos
  Browser->>UI: Click Add / Toggle / Filter
  UI->>UI: Update state
  UI->>Browser: Render visible items and count
Loading
sequenceDiagram
  autonumber
  actor Client
  participant Node as test4.js Server
  Client->>Node: GET /
  alt Root
    Node-->>Client: 200 HTML or 500 fail
  else /echo?msg=...
    Node-->>Client: 200 "You said: <msg>"
  else /memo
    Node-->>Client: 201 (no body)
  else other
    Node-->>Client: 404
  end
Loading
sequenceDiagram
  autonumber
  actor Client
  participant GoSrv as test6.go Server
  Client->>GoSrv: GET /inc?n=<n>
  GoSrv-->>Client: 200 "ok: <visits>" or 400 "bad n"
  Client->>GoSrv: GET /get
  GoSrv-->>Client: 200 "<derived visits>"
Loading
sequenceDiagram
  autonumber
  actor User
  participant Java as WordCounter
  User->>Java: Run with [path] or default
  Java->>Java: Open file, read lines
  Java->>Java: Split, normalize, update counts and total
  Java-->>User: Print final metric
Loading
sequenceDiagram
  autonumber
  actor User
  participant Cpp as test5.cpp
  User->>Cpp: Run program
  Cpp->>Cpp: Init NumberStats (empty)
  Cpp->>Cpp: computeMean(ns)
  Cpp->>Cpp: computeMedian(ns)
  Cpp-->>User: Print mean and median
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

Thump-thump! I tap my keys with glee,
New files sprout like clover by a tree.
Servers hum, a calc says “hi,”
Todos flip, stats drift by—
I twitch my ears at every test,
Hop through code, then nest to rest. 🐇✨

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Title Check ⚠️ Warning The PR title "@coderabbitai" is just a username/handle and does not describe the changeset; this pull request adds multiple new sample files (calculator.py, a React TodoList, WordCounter.java, a Node HTTP server, test5.cpp NumberStats, and a Go server) but the title gives no indication of those changes, so it is misleading and unhelpful for reviewers or history. Please rename the PR to a short, descriptive title that summarizes the primary change (for example: "Add sample buggy exercises: calculator, TodoList, WordCounter, Node/Go servers, NumberStats") or pick a single concise focus if one file is the intended main change so reviewers can immediately understand the purpose.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch og-qa-2

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai bot changed the title @coderabbitai Add Python calculator, React TodoList, Java counter, Node/Go/C++ apps Sep 16, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 15

🧹 Nitpick comments (9)
test1.py (3)

27-28: Result persistence is fine; consider bounding history size.

To prevent unbounded growth, keep a capped history.

Option (outside the diffed lines, for maintainability):

from collections import deque
history = deque(maxlen=1000)

31-31: Avoid module-level side effects.

Printing on import is surprising; move greeting under the main guard.

-print ( "Welcome to Calc" )
+# moved under __main__

35-37: CLI: separate statements, propagate errors cleanly.

Use newlines, and let doMath handle parsing; print a friendly message if None.

-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)
+if __name__ == "__main__":
+  print("Welcome to Calc")
+  a = input("a: ")
+  b = input("b: ")
+  op = input("op: ")
+  res = doMath(a, b, op)
+  if res is None:
+    print("Error: invalid input or operation (e.g., divide by zero).")
+  else:
+    print("Result:", res)
test2.js (2)

41-41: Use a stable key.

Index-based keys cause reconciliation bugs.

-{visible.map((t,i)=><div key={i}><input type="checkbox" checked={!!t.done} onChange={()=>toggle(t.id)}/><span>{t.text}</span></div>)}
+{visible.map(t => (
+  <div key={t.id}>
+    <input type="checkbox" checked={!!t.done} onChange={() => toggle(t.id)} />
+    <span>{t.text}</span>
+  </div>
+))}

39-41: Optional: avoid direct DOM access with a controlled input.

Cleaner React pattern; reduces coupling.

If desired, introduce local state:

const [text, setText] = useState("");
// ...
<input value={text} onChange={e => setText(e.target.value)} placeholder="Add todo"/>
<button onClick={()=>{ if(!text) return; setTodos(p=>[...p,{id:Date.now(),text,done:false}]); setText(""); }}>Add</button>
test3.java (1)

5-5: Use generics for type safety.

Raw types lose compile-time checks.

-public static Map counts=new HashMap();
+public static Map<String, Integer> counts = new HashMap<>();
test4.js (1)

21-21: Return a message for 404.

Empty body is unhelpful.

-res.writeHead(404); res.end(); // ISSUE: empty response body
+res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('Not found');
test5.cpp (1)

16-17: Main initializes empty data leading to no output or division by zero earlier.

Seed with data or guard before printing.

-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; }
+int main(){
+  NumberStats stats;
+  stats.data = {1, 2, 3, 4, 5};
+  computeMean(stats);
+  computeMedian(stats);
+  cout << "Mean: " << stats.mean << " Median: " << stats.median;
+  return 0;
+}
test6.go (1)

11-11: Check ListenAndServe error.

Surface startup failure.

-func main(){ http.HandleFunc("/inc",incHandler); http.HandleFunc("/get",getHandler); http.ListenAndServe(":9090",nil) }
+func main() {
+  http.HandleFunc("/inc", incHandler)
+  http.HandleFunc("/get", getHandler)
+  if err := http.ListenAndServe(":9090", nil); err != nil {
+    panic(err)
+  }
+}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2ec0fdd and 80d0b0f.

📒 Files selected for processing (6)
  • test1.py (1 hunks)
  • test2.js (1 hunks)
  • test3.java (1 hunks)
  • test4.js (1 hunks)
  • test5.cpp (1 hunks)
  • test6.go (1 hunks)
🧰 Additional context used
🪛 Ruff (0.12.2)
test1.py

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


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)


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


35-35: Multiple statements on one line (semicolon)

(E702)


35-35: Multiple statements on one line (semicolon)

(E702)


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

(E701)


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

(E701)

Comment on lines +7 to +16
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
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.

Comment on lines +20 to +24
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
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.

Comment on lines +15 to +19
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]);
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.

Comment on lines +26 to +27
setTodos([{id:Date.now(),text:input.value,done:true}]); // done default wrong
input.value="";
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.

Comment on lines +31 to +34
function toggle(id){
// ISSUE: toggles ALL todos regardless of id
setTodos(todos.map(t=>{return {...t,done:!t.done}}));
}
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.

Comment on lines +12 to +13
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
}
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.

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.

Comment on lines +7 to +8
var visits int
var client=&http.Client{ Timeout:5*time.Second }
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.

Comment on lines +14 to +15
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) }
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.

fmt.Fprintf(w,"ok: %d\n",visits) }


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.

@omar-coderabbitai
Copy link
Owner Author

@coderabbitai configuration

@coderabbitai
Copy link

coderabbitai bot commented Sep 16, 2025

CodeRabbit configuration
language: en-US
tone_instructions: ''
early_access: false
enable_free_tier: true
reviews:
  profile: chill
  request_changes_workflow: false
  high_level_summary: true
  high_level_summary_placeholder: '@coderabbitai summary'
  high_level_summary_in_walkthrough: false
  auto_title_placeholder: '@coderabbitai'
  auto_title_instructions: ''
  review_status: true
  commit_status: true
  fail_commit_status: false
  collapse_walkthrough: false
  changed_files_summary: true
  sequence_diagrams: true
  estimate_code_review_effort: true
  assess_linked_issues: true
  related_issues: true
  related_prs: true
  suggested_labels: true
  auto_apply_labels: false
  suggested_reviewers: true
  auto_assign_reviewers: false
  poem: true
  labeling_instructions: []
  path_filters: []
  path_instructions:
    - path: ''
      instructions: >-
        - Only comment on issues that would block merging — ignore minor or
        stylistic concerns.

        - Restrict feedback to errors, security risks, or functionality-breaking
        problems.

        - Do not post comments on code style, formatting, or non-critical
        improvements.

        - Keep reviews short: flag only issues that make the PR unsafe to merge.

        - Limit review comments to 3–5 items maximum, unless additional blockers
        exist.

        - Group similar issues into a single comment instead of posting multiple
        notes.

        - Skip repetition — if a pattern repeats, mention it once at a summary
        level only.

        - Do not add general suggestions, focus strictly on merge-blocking
        concerns.

        - If there are no critical problems, respond with minimal approval
        (e.g., 'Looks good'). Do not add additional review.

        - Avoid line-by-line commentary unless it highlights a critical bug or
        security hole.

        - Highlight only issues that could cause runtime errors, data loss, or
        severe maintainability
          issues.
        - Ignore minor optimization opportunities — focus solely on correctness
        and safety.

        - Provide a top-level summary of critical blockers rather than detailed
        per-line notes.

        - Comment only when the issue must be resolved before merge — otherwise
        remain silent.

        - When in doubt, err on the side of fewer comments — brevity and
        blocking issues only.

        - Avoid posting any refactoring issues
  abort_on_close: true
  disable_cache: false
  auto_review:
    enabled: true
    auto_incremental_review: false
    ignore_title_keywords: []
    labels: []
    drafts: false
    base_branches:
      - feature/.*
      - main-.*
    ignore_usernames: []
  finishing_touches:
    docstrings:
      enabled: true
    unit_tests:
      enabled: true
  pre_merge_checks:
    docstrings:
      mode: warning
      threshold: 80
    title:
      mode: warning
      requirements: ''
    description:
      mode: warning
    issue_assessment:
      mode: warning
    custom_checks: []
  tools:
    ast-grep:
      rule_dirs: []
      util_dirs: []
      essential_rules: true
      packages: []
    shellcheck:
      enabled: true
    ruff:
      enabled: true
    markdownlint:
      enabled: true
    github-checks:
      enabled: true
      timeout_ms: 90000
    languagetool:
      enabled: true
      enabled_rules: []
      disabled_rules: []
      enabled_categories: []
      disabled_categories: []
      enabled_only: false
      level: default
    biome:
      enabled: true
    hadolint:
      enabled: true
    swiftlint:
      enabled: true
    phpstan:
      enabled: true
      level: default
    phpmd:
      enabled: true
    phpcs:
      enabled: true
    golangci-lint:
      enabled: true
    yamllint:
      enabled: true
    gitleaks:
      enabled: true
    checkov:
      enabled: true
    detekt:
      enabled: true
    eslint:
      enabled: true
    flake8:
      enabled: true
    rubocop:
      enabled: true
    buf:
      enabled: true
    regal:
      enabled: true
    actionlint:
      enabled: true
    pmd:
      enabled: true
    cppcheck:
      enabled: true
    semgrep:
      enabled: true
    circleci:
      enabled: true
    clippy:
      enabled: true
    sqlfluff:
      enabled: true
    prismaLint:
      enabled: true
    pylint:
      enabled: true
    oxc:
      enabled: true
    shopifyThemeCheck:
      enabled: true
    luacheck:
      enabled: true
    brakeman:
      enabled: true
    dotenvLint:
      enabled: true
    htmlhint:
      enabled: true
    checkmake:
      enabled: true
    osvScanner:
      enabled: true
chat:
  art: true
  auto_reply: true
  integrations:
    jira:
      usage: auto
    linear:
      usage: auto
knowledge_base:
  opt_out: false
  web_search:
    enabled: true
  code_guidelines:
    enabled: true
    filePatterns: []
  learnings:
    scope: auto
  issues:
    scope: auto
  jira:
    usage: auto
    project_keys: []
  linear:
    usage: auto
    team_keys: []
  pull_requests:
    scope: auto
  mcp:
    usage: auto
    disabled_servers: []
code_generation:
  docstrings:
    language: en-US
    path_instructions: []
  unit_tests:
    path_instructions: []

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants