ronantakizawa/codereview-bench huggingface dataset:
Repository: cloudflare/wildebeest
File: frontend/src/routes/(frontend)/explore/index.tsx (TypeScript)

Code before:
	}
)

export default component$(() => {
	const statuses = statusesLoader().value
	return (
		<StatusesPanel
			initialStatuses={statuses}
			fetchMoreStatuses={$(async (numOfCurrentStatuses: number) => {
				let statuses: MastodonStatus[] = []
				try {
					const response = await fetch(`/api/v1/timelines/public?offset=${numOfCurrentStatuses}`)
					if (response.ok) {
						const results = await response.text()
						statuses = JSON.parse(results)
					}
				} catch {
					/* empty */
				}
				return statuses
			})}
		/>
	)
})

export const requestUrlLoader = loader$(async ({ request: { url } }) => url)

export const head: DocumentHead = ({ resolveValue }) => {
	const url = resolveValue(requestUrlLoader)
	return getDocumentHead({
		title: 'Explore - Wildebeest',
		og: {
			url,
		},
	})
}


Review comment (suggestion):
NIT - I find this easier to grok... is there any reason for it to be destructured in the parameter list?

```suggestion
export const requestUrlLoader = loader$(async ({ request }) => request.url)
```

Code after:
	}
)

export default component$(() => {
	const statuses = statusesLoader().value
	return (
		<StatusesPanel
			initialStatuses={statuses}
			fetchMoreStatuses={$(async (numOfCurrentStatuses: number) => {
				let statuses: MastodonStatus[] = []
				try {
					const response = await fetch(`/api/v1/timelines/public?offset=${numOfCurrentStatuses}`)
					if (response.ok) {
						const results = await response.text()
						statuses = JSON.parse(results)
					}
				} catch {
					/* empty */
				}
				return statuses
			})}
		/>
	)
})

export const requestUrlLoader = loader$(async ({ request }) => request.url)

export const head: DocumentHead = ({ resolveValue }) => {
	const url = resolveValue(requestUrlLoader)
	return getDocumentHead({
		title: 'Explore - Wildebeest',
		og: {
			url,
		},
	})
}
Repository: cloudflare/wildebeest
File: frontend/src/routes/(admin)/settings/aliases/index.tsx (TypeScript)

Code before:
import { component$ } from '@builder.io/qwik'
import { loader$ } from '@builder.io/qwik-city'

export const loader = loader$(({ redirect }) => {
	redirect(303, '/explore')
})

export default component$(() => {
	loader.use()

	return (
		<div class="max-w-4xl py-14 px-8">
			<h2 class="text-2xl font-bold mb-6">Account Aliases</h2>

			<div class="bg-green-800 border-green-700 text-green-100 border mb-5 p-5 text-center rounded">
				Successfully created a new alias. You can now initiate the move from the old account.
			</div>

			<p class="text-sm text-wildebeest-400 mb-10">
				If you want to move from another account to this one, here you can create an alias, which is required before you
				can proceed with moving followers from the old account to this one. This action by itself is harmless and
				reversible. The account migration is initiated from the old account.
			</p>

			<div class="my-5">
				<label class="font-semibold mb-3" for="old-account">
					Handle of the old account
					<span class="ml-1 text-red-500">*</span>
				</label>
				<div class="text-sm text-wildebeest-400">Specify the username@domain of the account you want to move from</div>
			</div>
			<input
				class="bg-black text-white p-3 rounded outline-none border border-black hover:border-wildebeest-vibrant-500 focus:border-wildebeest-vibrant-500 w-full mb-5"
				type="text"

Review comment (suggestion):
@jculvey `.use()` is deprecated in the latest qwikCity version you just call the loader directly, I've rebased your branch (so to have the latest qwikCity version) and replaced these `.use()` calls, I hope you don't mind 🙏 

Code after:
import { component$, useStore, useSignal, $ } from '@builder.io/qwik'
import { loader$ } from '@builder.io/qwik-city'
import { WildebeestEnv } from '~/types'
import { checkAuth } from '~/utils/checkAuth'

export const loader = loader$<WildebeestEnv, void>(async ({ request, platform, redirect }) => {
	const isAuthorized = await checkAuth(request, platform)

	if (!isAuthorized) {
		redirect(303, '/explore')
	}
})

export default component$(() => {
	const ref = useSignal<Element>()
	const state = useStore({ alias: '' })
	const toast = useSignal<'success' | 'failure' | null>(null)

	const handleInput = $((event: Event) => {
		state.alias = (event.target as HTMLInputElement).value
	})

	const handleSubmit = $(async () => {
		const res = await fetch('/api/wb/settings/account/alias', { method: 'POST', body: JSON.stringify(state) })
		if (res.status == 200) {
			toast.value = 'success'
		} else {
			toast.value = 'failure'
		}
	})

	return (
		<form ref={ref} class="login-form" preventdefault:submit onSubmit$={handleSubmit}>
			<div class="max-w-4xl py-14 px-8">
Repository: cloudwego/netpoll
File: sys_epoll_linux_loong64.go (Go)

Code before:
// Copyright 2022 Loongson Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package netpoll

import (
	"syscall"
	"unsafe"
)

const EPOLLET = syscall.EPOLLET

type epollevent struct {
	events uint32
	_      int32

Review comment (security):
```suggestion
// Copyright 2021 CloudWeGo Authors
```

Code after:
// Copyright 2022 CloudWeGo Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//go:build linux && loong64
// +build linux,loong64

package netpoll

import (
	"syscall"
	"unsafe"
)

const EPOLLET = syscall.EPOLLET
Repository: covid19india/covid19india-react
File: src/components/Charts/agechart.js (JavaScript)

Code before:
  defaults.global.tooltips.backgroundColor = 'rgba(255, 255, 255, 0.8)';
  defaults.global.tooltips.displayColors = false;
  defaults.global.tooltips.borderColor = '#c62828';
  defaults.global.tooltips.borderWidth = 1;
  defaults.global.tooltips.titleFontColor = '#000';
  defaults.global.tooltips.bodyFontColor = '#000';
  defaults.global.tooltips.caretPadding = 4;
  defaults.global.tooltips.intersect = false;
  defaults.global.tooltips.mode = 'nearest';
  defaults.global.tooltips.position = 'nearest';

  defaults.global.legend.display = true;
  defaults.global.legend.position = 'bottom';

  defaults.global.hover.intersect = false;

  const ages = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
  let unknown = 0;
  if (!props.data || props.data.length === 0) {
    return <div></div>;
  }

  props.data.forEach((patient) => {
    if (patient.agebracket) {
      const age = parseInt(patient.agebracket);
      if (age >= 0 && age <= 10) {
        ages[0]++;
      }
      if (age > 10 && age <= 20) {
        ages[1]++;
      }
      if (age > 20 && age <= 30) {
        ages[2]++;
      }
      if (age > 30 && age <= 40) {
        ages[3]++;
      }
      if (age > 40 && age <= 50) {
        ages[4]++;
      }
      if (age > 50 && age <= 60) {
        ages[5]++;
      }
      if (age > 60 && age <= 70) {
        ages[6]++;
      }
      if (age > 70 && age <= 80) {
        ages[7]++;
      }
      if (age > 80 && age <= 90) {
        ages[8]++;

Review comment (performance):
Simpler complexity could be - 
```js
let itr = parseInt(age/10);
if(age!=0 && age%10 == 0){
    itr--;
}
ages[itr]++;
```

Code after:
  defaults.global.tooltips.backgroundColor = 'rgba(255, 255, 255, 0.8)';
  defaults.global.tooltips.displayColors = false;
  defaults.global.tooltips.borderColor = '#c62828';
  defaults.global.tooltips.borderWidth = 1;
  defaults.global.tooltips.titleFontColor = '#000';
  defaults.global.tooltips.bodyFontColor = '#000';
  defaults.global.tooltips.caretPadding = 4;
  defaults.global.tooltips.intersect = false;
  defaults.global.tooltips.mode = 'nearest';
  defaults.global.tooltips.position = 'nearest';

  defaults.global.legend.display = true;
  defaults.global.legend.position = 'bottom';

  defaults.global.hover.intersect = false;

  const ages = Array(10).fill(0);
  let unknown = 0;
  if (!props.data || props.data.length === 0) {
    return <div></div>;
  }

  props.data.forEach((patient) => {
    if (patient.agebracket) {
      const age = parseInt(patient.agebracket);
      for (let i = 0; i < 10; i++) {
        if (age > i * 10 && age <= (i + 1) * 10) {
          ages[i]++;
        }
      }
    } else {
      unknown++;
    }
  });

  const chartData = {
    labels: [
      '0-10',
      '11-20',
      '21-30',
      '31-40',
      '41-50',
      '51-60',
      '61-70',
      '71-80',
      '81-90',
      '91-100',
    ],
    datasets: [
      {
        data: ages,
Repository: covid19india/covid19india-react
File: src/__tests__/components/Level.test.js (JavaScript)

Code before:
import React from 'react';
import {render} from '@testing-library/react';
import Level from '../../components/level';

const data = {
  active: '80',
  confirmed: '86',
  recovered: '7',
  deaths: '4',
  deltaconfirmed: '10',
  deltadeaths: '3',
  deltarecovered: '5',
};

test('Level renders total state data', () => {
  const {container} = render(<Level data={data} />);

  expect(container).toHaveTextContent(
    'Confirmed[+10]86 Active 80Recovered[+5]7 Deceased[+3]4'
  );
});


Review comment (suggestion):
Can you change the name of the variable to `state`? As we are passing `states[0]` in the code. 
https://github.com/covid19india/covid19india-react/blob/00584fa82e87472952e0a3118af9811281d1e1ae/src/components/home.js#L122
It explains it better while reading the tests.

Code after:
import React from 'react';
import {render} from '@testing-library/react';
import Level from '../../components/level';

const state = {
  active: '80',
  confirmed: '86',
  recovered: '7',
  deaths: '4',
  deltaconfirmed: '10',
  deltadeaths: '3',
  deltarecovered: '5',
};

test('Level renders total state data', () => {
  const {container} = render(<Level data={state} />);

  expect(container).toHaveTextContent(
    'Confirmed[+10]86 Active 80Recovered[+5]7 Deceased[+3]4'
  );
});
Repository: covid19india/covid19india-react
File: src/components/timeseriesexplorer.js (JavaScript)

Code before:
                );
                onHighlightState(JSON.parse(selectedState));
              }}
            >
              {states.map((s) => {
                return (
                  <option
                    value={s.statecode}
                    key={s.statecode}
                    statedata={JSON.stringify(s)}
                  >
                    {s.statecode === 'TT' ? 'All States' : s.state}
                  </option>
                );
              })}
            </select>
          </div>
        )}
      </div>

      <TimeSeries
        timeseries={
          timeseries && activeStateCode
            ? timeseries[activeStateCode]
            : stateTimeSeries
        }
        stateCode={activeStateCode}
        type={graphOption}
        mode={timeseriesMode}
        logMode={timeseriesLogMode}
      />
    </div>
  );
}

export default React.memo(TimeSeriesExplorer);


Review comment (suggestion):
Might be better to instead pass only the state timeseries from both home.js and state.js. The complete timeseries data for all the states is not used anywhere in either TimeSeriesExplorer or TimeSeries. No need for the if conditions as well then.

Code after:
                onHighlightState(JSON.parse(selectedState));
              }}
            >
              {states.map((s) => {
                return (
                  <option
                    value={s.statecode}
                    key={s.statecode}
                    statedata={JSON.stringify(s)}
                  >
                    {s.statecode === 'TT' ? 'All States' : s.state}
                  </option>
                );
              })}
            </select>
          </div>
        )}
      </div>

      <TimeSeries
        timeseries={timeseries}
        type={graphOption}
        mode={timeseriesMode}
        logMode={timeseriesLogMode}
      />
    </div>
  );
}

export default React.memo(TimeSeriesExplorer);
Repository: covid19india/covid19india-react
File: src/components/deltabargraph.js (JavaScript)

Code before:

    const margin = {top: 50, right: 0, bottom: 50, left: 0};
    const chartRight = width - margin.right;
    let chartBottom = height - margin.bottom;
    const barRadius = 5;
    if (arrayKey === 'dailyactive') {
      for (const day of data) {
        if (day[arrayKey] < 0) {
          chartBottom = height - margin.bottom * 2;
        }
      }
    }

    const formatTime = d3.timeFormat('%e %b');
    const xScale = d3
      .scaleBand()
      .domain(data.map((d) => formatTime(d.date)))
      .range([margin.left, chartRight])
      .paddingInner(0.33);

    const yScale = d3
      .scaleLinear()
      .domain([
        0,
        Math.max(
          1,
          d3.max(data, (d) => Math.abs(d[arrayKey]))
        ),
      ])
      .range([chartBottom, margin.top]); // - barRadius

    const xAxis = d3.axisBottom(xScale).tickSize(0);

    svg
      .select('.x-axis')
      .style('transform', `translateY(${chartBottom}px)`)
      .call(xAxis)
      .attr('class', `x-axis ${arrayKey}`)
      .call((g) => g.select('.domain').remove())
      .selectAll('text')
      .attr('y', 0)
      .attr('dy', '1.5em')
      .style('text-anchor', 'middle');

    svg
      .selectAll('.bar')
      .data(data)
      .join('path')
      .attr('class', 'bar')
      .attr('d', (d) =>
        roundedBar(

Review comment (suggestion):
You'll have to handle the active chart separately here since it's domain can contain values less than 0.

Code after:
    const width = +svg.attr('width');
    const height = +svg.attr('height');

    const margin = {top: 50, right: 0, bottom: 50, left: 0};
    const chartRight = width - margin.right;
    const chartBottom = height - margin.bottom;
    const r = 5;

    const formatTime = d3.timeFormat('%e %b');
    const xScale = d3
      .scaleBand()
      .domain(data.map((d) => formatTime(d.date)))
      .range([margin.left, chartRight])
      .paddingInner(0.33);

    const yScale = d3
      .scaleLinear()
      .domain([
        Math.min(
          0,
          d3.min(data, (d) => d[arrayKey])
        ),
        Math.max(
          1,
          d3.max(data, (d) => d[arrayKey])
        ),
      ])
      .range([chartBottom, margin.top]);

    const xAxis = d3.axisBottom(xScale).tickSize(0);

    const t = svg.transition().duration(500);
    svg.selectAll('.delta').remove();
    svg
      .select('.x-axis')
      .transition(t)
      .style('transform', `translateY(${yScale(0)}px)`)
      .call(xAxis)
      .on('start', () => svg.select('.domain').remove())
      .selectAll('text')
      .attr('y', 0)
      .attr('dy', (d, i) => (data[i][arrayKey] < 0 ? '-1.5em' : '1.5em'))
      .style('text-anchor', 'middle')
      .attr('fill', (d, i) => {
        switch (arrayKey) {
          case 'dailyconfirmed':
            return '#dc3545';
          case 'dailyrecovered':
            return '#28a745';
          case 'dailyactive':
            return '#0479fb';
Repository: crewAIInc/crewAI
File: src/crewai/__init__.py (Python)

Code before:

def _is_tracking_disabled():
    """Check if tracking should be disabled based on environment variables."""
    return (
        os.getenv("CREWAI_DISABLE_TELEMETRY", "false").lower() == "true"
        or os.getenv("CREWAI_DISABLE_TRACKING", "false").lower() == "true"
    )


def _track_install():
    """Track package installation/first-use via Scarf analytics."""
    global _telemetry_submitted
    
    if _telemetry_submitted or _is_tracking_disabled():
        return
    
    try:
        pixel_url = "https://api.scarf.sh/v2/packages/CrewAI/crewai/docs/00f2dad1-8334-4a39-934e-003b2e1146db"
        
        req = urllib.request.Request(pixel_url)
        req.add_header('User-Agent', f'CrewAI-Python/{__version__}')
        
        with urllib.request.urlopen(req, timeout=2):  # nosec B310
            _telemetry_submitted = True
            
    except (URLError, OSError, Exception):
        pass


def _track_install_async():
    """Track installation in background thread to avoid blocking imports."""
    if not _is_tracking_disabled():
        thread = threading.Thread(target=_track_install, daemon=True)
        thread.start()


_track_install_async()

__version__ = "0.134.0"
__all__ = [
    "Agent",
    "Crew",
    "CrewOutput",
    "Process",
    "Task",
    "LLM",
    "BaseLLM",
    "Flow",
    "Knowledge",
    "TaskOutput",
    "LLMGuardrail",

Review comment (suggestion):
I think you can keep `Exception` onlye
```suggestion
except Exception:
```

Code after:

def _track_install():
    """Track package installation/first-use via Scarf analytics."""
    global _telemetry_submitted
    
    if _telemetry_submitted or Telemetry._is_telemetry_disabled():
        return
    
    try:
        pixel_url = "https://api.scarf.sh/v2/packages/CrewAI/crewai/docs/00f2dad1-8334-4a39-934e-003b2e1146db"
        
        req = urllib.request.Request(pixel_url)
        req.add_header('User-Agent', f'CrewAI-Python/{__version__}')
        
        with urllib.request.urlopen(req, timeout=2):  # nosec B310
            _telemetry_submitted = True
            
    except Exception:
        pass


def _track_install_async():
    """Track installation in background thread to avoid blocking imports."""
    if not Telemetry._is_telemetry_disabled():
        thread = threading.Thread(target=_track_install, daemon=True)
        thread.start()


_track_install_async()

__version__ = "0.134.0"
__all__ = [
    "Agent",
    "Crew",
    "CrewOutput",
    "Process",
    "Task",
    "LLM",
    "BaseLLM",
    "Flow",
    "Knowledge",
    "TaskOutput",
    "LLMGuardrail",
    "__version__",
]
Repository: crewAIInc/crewAI
File: src/crewai/experimental/evaluation/agent_evaluator.py (Python)

Code before:
import threading
from typing import Any

from crewai.experimental.evaluation.base_evaluator import AgentEvaluationResult, AggregationStrategy
from crewai.agent import Agent
from crewai.task import Task
from crewai.experimental.evaluation.evaluation_display import EvaluationDisplayFormatter
from crewai.utilities.events.agent_events import AgentEvaluationStartedEvent, AgentEvaluationCompletedEvent, AgentEvaluationFailedEvent
from crewai.experimental.evaluation import BaseEvaluator, create_evaluation_callbacks
from collections.abc import Sequence
from crewai.utilities.events.crewai_event_bus import crewai_event_bus
from crewai.utilities.events.utils.console_formatter import ConsoleFormatter
from crewai.utilities.events.task_events import TaskCompletedEvent
from crewai.utilities.events.agent_events import LiteAgentExecutionCompletedEvent
from crewai.experimental.evaluation.base_evaluator import AgentAggregatedEvaluationResult, EvaluationScore, MetricCategory

class ExecutionState:
    def __init__(self):
        self.traces = {}
        self.current_agent_id = None
        self.current_task_id = None
        self.iteration = 1
        self.iterations_results = {}
        self.agent_evaluators = {}

class AgentEvaluator:

Review comment (suggestion):
couple type errors here:
<img width="762" height="383" alt="Screenshot 2025-07-15 at 12 12 08 PM" src="https://github.com/user-attachments/assets/1422fff1-f109-4ea7-8e4b-0651c0164430" />


Code after:
import threading
from typing import Any

from crewai.experimental.evaluation.base_evaluator import AgentEvaluationResult, AggregationStrategy
from crewai.agent import Agent
from crewai.task import Task
from crewai.experimental.evaluation.evaluation_display import EvaluationDisplayFormatter
from crewai.utilities.events.agent_events import AgentEvaluationStartedEvent, AgentEvaluationCompletedEvent, AgentEvaluationFailedEvent
from crewai.experimental.evaluation import BaseEvaluator, create_evaluation_callbacks
from collections.abc import Sequence
from crewai.utilities.events.crewai_event_bus import crewai_event_bus
from crewai.utilities.events.utils.console_formatter import ConsoleFormatter
from crewai.utilities.events.task_events import TaskCompletedEvent
from crewai.utilities.events.agent_events import LiteAgentExecutionCompletedEvent
from crewai.experimental.evaluation.base_evaluator import AgentAggregatedEvaluationResult, EvaluationScore, MetricCategory

class ExecutionState:
    def __init__(self):
        self.traces = {}
        self.current_agent_id: str | None = None
        self.current_task_id: str | None = None
        self.iteration = 1
        self.iterations_results = {}
        self.agent_evaluators = {}

class AgentEvaluator:
Repository: crewAIInc/crewAI
File: src/crewai/cli/enterprise/main.py (Python)

Code before:
import requests
from typing import Dict, Any
from rich.console import Console
from requests.exceptions import RequestException, JSONDecodeError

from crewai.cli.command import BaseCommand
from crewai.cli.settings.main import SettingsCommand
from crewai.cli.version import get_crewai_version

console = Console()


class EnterpriseCommand(BaseCommand):
    def __init__(self):
        super().__init__()
        self.settings_command = SettingsCommand()

    def configure(self, enterprise_url: str) -> None:
        try:
            enterprise_url = enterprise_url.rstrip('/')

            oauth_config = self._fetch_oauth_config(enterprise_url)

            self._update_oauth_settings(enterprise_url, oauth_config)

            console.print(
                f"✅ Successfully configured CrewAI Enterprise with OAuth2 settings from {enterprise_url}",
                style="bold green"
            )

        except Exception as e:
            console.print(f"❌ Failed to configure Enterprise settings: {str(e)}", style="bold red")
            raise SystemExit(1)

    def _fetch_oauth_config(self, enterprise_url: str) -> Dict[str, Any]:
        oauth_endpoint = f"{enterprise_url}/oauth/parameters"

        try:

Review comment (suggestion):
`EnterpriseConfigureCommand` would be better? Since enterprise is the name of the group of commands. 

Really small detail, don't need to change if you are not convinced haha

Code after:
import requests
from typing import Dict, Any
from rich.console import Console
from requests.exceptions import RequestException, JSONDecodeError

from crewai.cli.command import BaseCommand
from crewai.cli.settings.main import SettingsCommand
from crewai.cli.version import get_crewai_version

console = Console()


class EnterpriseConfigureCommand(BaseCommand):
    def __init__(self):
        super().__init__()
        self.settings_command = SettingsCommand()

    def configure(self, enterprise_url: str) -> None:
        try:
            enterprise_url = enterprise_url.rstrip('/')

            oauth_config = self._fetch_oauth_config(enterprise_url)

            self._update_oauth_settings(enterprise_url, oauth_config)

            console.print(
                f"✅ Successfully configured CrewAI Enterprise with OAuth2 settings from {enterprise_url}",
                style="bold green"
            )

        except Exception as e:
            console.print(f"❌ Failed to configure Enterprise settings: {str(e)}", style="bold red")
            raise SystemExit(1)

    def _fetch_oauth_config(self, enterprise_url: str) -> Dict[str, Any]:
        oauth_endpoint = f"{enterprise_url}/oauth/parameters"

        try: