ronantakizawa/codereview-bench huggingface dataset:
Repository: DiceDB/dice
File: internal/cmd/cmd_zcard_watch.go (Go)

Code before:
func newZCARDWATCHRes() *CmdRes {
	return &CmdRes{
		Rs: &wire.Result{
			Message:  "OK",
			Status:   wire.Status_OK,
			Response: &wire.Result_ZCARDWATCHRes{},
		},
	}
}

var (
	ZCARDWATCHResNilRes = newZCARDWATCHRes()
)

func evalZCARDWATCH(c *Cmd, s *dstore.Store) (*CmdRes, error) {
	r, err := evalZCARD(c, s)
	if err != nil {
		return nil, err
	}

	r.Rs.Fingerprint64 = c.Fingerprint()
	return r, nil
}

func executeZCARDWATCH(c *Cmd, sm *shardmanager.ShardManager) (*CmdRes, error) {
	if len(c.C.Args) != 1 {
		return ZCARDWATCHResNilRes, errors.ErrWrongArgumentCount("ZCARD.WATCH")
	}
	shard := sm.GetShardForKey(c.C.Args[0])
	return evalZCARDWATCH(c, shard.Thread.Store())
}


Review comment (suggestion):
`==0` is correct. For `.watch` commands the check on arguments is handled at primary command level. This way, we need not make changes at two places when we support other args. Revert this change.

Code after:
func newZCARDWATCHRes() *CmdRes {
	return &CmdRes{
		Rs: &wire.Result{
			Message:  "OK",
			Status:   wire.Status_OK,
			Response: &wire.Result_ZCARDWATCHRes{},
		},
	}
}

var (
	ZCARDWATCHResNilRes = newZCARDWATCHRes()
)

func evalZCARDWATCH(c *Cmd, s *dstore.Store) (*CmdRes, error) {
	r, err := evalZCARD(c, s)
	if err != nil {
		return nil, err
	}

	r.Rs.Fingerprint64 = c.Fingerprint()
	return r, nil
}

func executeZCARDWATCH(c *Cmd, sm *shardmanager.ShardManager) (*CmdRes, error) {
	if len(c.C.Args) == 0 {
		return ZCARDWATCHResNilRes, errors.ErrWrongArgumentCount("ZCARD.WATCH")
	}
	shard := sm.GetShardForKey(c.C.Args[0])
	return evalZCARDWATCH(c, shard.Thread.Store())
}
Repository: DiceDB/dice
File: internal/cmd/cmd_zcount_watch.go (Go)

Code before:
func newZCOUNTWATCHRes() *CmdRes {
	return &CmdRes{
		Rs: &wire.Result{
			Message:  "OK",
			Status:   wire.Status_OK,
			Response: &wire.Result_ZCOUNTWATCHRes{},
		},
	}
}

var (
	ZCOUNTWATCHResNilRes = newZCOUNTWATCHRes()
)

func evalZCOUNTWATCH(c *Cmd, s *dstore.Store) (*CmdRes, error) {
	r, err := evalZCOUNT(c, s)
	if err != nil {
		return nil, err
	}

	r.Rs.Fingerprint64 = c.Fingerprint()
	return r, nil
}

func executeZCOUNTWATCH(c *Cmd, sm *shardmanager.ShardManager) (*CmdRes, error) {
	if len(c.C.Args) != 3 {
		return ZCOUNTWATCHResNilRes, errors.ErrWrongArgumentCount("ZCOUNT.WATCH")
	}
	shard := sm.GetShardForKey(c.C.Args[0])
	return evalZCOUNTWATCH(c, shard.Thread.Store())
}


Review comment (suggestion):
`==0` is correct. For `.watch` commands the check on arguments is handled at primary command level. This way, we need not make changes at two places when we support other args. Revert this change.

Code after:
func newZCOUNTWATCHRes() *CmdRes {
	return &CmdRes{
		Rs: &wire.Result{
			Message:  "OK",
			Status:   wire.Status_OK,
			Response: &wire.Result_ZCOUNTWATCHRes{},
		},
	}
}

var (
	ZCOUNTWATCHResNilRes = newZCOUNTWATCHRes()
)

func evalZCOUNTWATCH(c *Cmd, s *dstore.Store) (*CmdRes, error) {
	r, err := evalZCOUNT(c, s)
	if err != nil {
		return nil, err
	}

	r.Rs.Fingerprint64 = c.Fingerprint()
	return r, nil
}

func executeZCOUNTWATCH(c *Cmd, sm *shardmanager.ShardManager) (*CmdRes, error) {
	if len(c.C.Args) == 0 {
		return ZCOUNTWATCHResNilRes, errors.ErrWrongArgumentCount("ZCOUNT.WATCH")
	}
	shard := sm.GetShardForKey(c.C.Args[0])
	return evalZCOUNTWATCH(c, shard.Thread.Store())
}
Repository: DiceDB/dice
File: internal/cmd/cmd_zrange_watch.go (Go)

Code before:
func newZRANGEWATCHRes() *CmdRes {
	return &CmdRes{
		Rs: &wire.Result{
			Message:  "OK",
			Status:   wire.Status_OK,
			Response: &wire.Result_ZRANGEWATCHRes{},
		},
	}
}

var (
	ZRANGEWATCHResNilRes = newZRANGEWATCHRes()
)

func evalZRANGEWATCH(c *Cmd, s *dstore.Store) (*CmdRes, error) {
	r, err := evalZRANGE(c, s)
	if err != nil {
		return nil, err
	}

	r.Rs.Fingerprint64 = c.Fingerprint()
	return r, nil
}

func executeZRANGEWATCH(c *Cmd, sm *shardmanager.ShardManager) (*CmdRes, error) {
	if len(c.C.Args) < 3 || len(c.C.Args) > 4 {
		return ZRANGEWATCHResNilRes, errors.ErrWrongArgumentCount("ZRANGE.WATCH")
	}
	shard := sm.GetShardForKey(c.C.Args[0])
	return evalZRANGEWATCH(c, shard.Thread.Store())
}


Review comment (suggestion):
`==0` is correct. For `.watch` commands the check on arguments is handled at primary command level. This way, we need not make changes at two places when we support other args. Revert this change.

Code after:
func newZRANGEWATCHRes() *CmdRes {
	return &CmdRes{
		Rs: &wire.Result{
			Message:  "OK",
			Status:   wire.Status_OK,
			Response: &wire.Result_ZRANGEWATCHRes{},
		},
	}
}

var (
	ZRANGEWATCHResNilRes = newZRANGEWATCHRes()
)

func evalZRANGEWATCH(c *Cmd, s *dstore.Store) (*CmdRes, error) {
	r, err := evalZRANGE(c, s)
	if err != nil {
		return nil, err
	}

	r.Rs.Fingerprint64 = c.Fingerprint()
	return r, nil
}

func executeZRANGEWATCH(c *Cmd, sm *shardmanager.ShardManager) (*CmdRes, error) {
	if len(c.C.Args) == 0 {
		return ZRANGEWATCHResNilRes, errors.ErrWrongArgumentCount("ZRANGE.WATCH")
	}
	shard := sm.GetShardForKey(c.C.Args[0])
	return evalZRANGEWATCH(c, shard.Thread.Store())
}
Repository: DiceDB/dice
File: internal/cmd/cmd_zrank_watch.go (Go)

Code before:
func newZRANKWATCHRes() *CmdRes {
	return &CmdRes{
		Rs: &wire.Result{
			Message:  "OK",
			Status:   wire.Status_OK,
			Response: &wire.Result_ZRANKWATCHRes{},
		},
	}
}

var (
	ZRANKWATCHResNilRes = newZRANKWATCHRes()
)

func evalZRANKWATCH(c *Cmd, s *dstore.Store) (*CmdRes, error) {
	r, err := evalZRANK(c, s)
	if err != nil {
		return nil, err
	}

	r.Rs.Fingerprint64 = c.Fingerprint()
	return r, nil
}

func executeZRANKWATCH(c *Cmd, sm *shardmanager.ShardManager) (*CmdRes, error) {
	if len(c.C.Args) != 2 {
		return ZRANKWATCHResNilRes, errors.ErrWrongArgumentCount("ZRANK.WATCH")
	}
	shard := sm.GetShardForKey(c.C.Args[0])
	return evalZRANKWATCH(c, shard.Thread.Store())
}


Review comment (suggestion):
`==0` is correct. For `.watch` commands the check on arguments is handled at primary command level. This way, we need not make changes at two places when we support other args. Revert this change.

Code after:
func newZRANKWATCHRes() *CmdRes {
	return &CmdRes{
		Rs: &wire.Result{
			Message:  "OK",
			Status:   wire.Status_OK,
			Response: &wire.Result_ZRANKWATCHRes{},
		},
	}
}

var (
	ZRANKWATCHResNilRes = newZRANKWATCHRes()
)

func evalZRANKWATCH(c *Cmd, s *dstore.Store) (*CmdRes, error) {
	r, err := evalZRANK(c, s)
	if err != nil {
		return nil, err
	}

	r.Rs.Fingerprint64 = c.Fingerprint()
	return r, nil
}

func executeZRANKWATCH(c *Cmd, sm *shardmanager.ShardManager) (*CmdRes, error) {
	if len(c.C.Args) == 0 {
		return ZRANKWATCHResNilRes, errors.ErrWrongArgumentCount("ZRANK.WATCH")
	}
	shard := sm.GetShardForKey(c.C.Args[0])
	return evalZRANKWATCH(c, shard.Thread.Store())
}
Repository: Dokploy/dokploy
File: packages/server/src/services/compose.ts (TypeScript)

Code before:
				await execAsyncRemote(compose.serverId, command);
			} else {
				await execAsync(command, {
					cwd: projectPath,
				});
			}
		}
	} catch (error) {
		throw error;
	}

	return true;
};

export const startCompose = async (composeId: string) => {
	const compose = await findComposeById(composeId);
	try {
		const { COMPOSE_PATH } = paths(!!compose.serverId);
		if (compose.composeType === "docker-compose") {
			if (compose.serverId) {
				await execAsyncRemote(
					compose.serverId,
					`cd ${join(
						COMPOSE_PATH,
						compose.appName,
						"code",
					)} && docker compose -p ${compose.appName} up -d`,
				);
			} else {
				await execAsync(`docker compose -p ${compose.appName} up -d`, {
					cwd: join(COMPOSE_PATH, compose.appName, "code"),
				});
			}
		}

		await updateCompose(composeId, {
			composeStatus: "done",
		});
	} catch (error) {
		await updateCompose(composeId, {
			composeStatus: "idle",
		});
		throw error;
	}

	return true;
};

export const stopCompose = async (composeId: string) => {
	const compose = await findComposeById(composeId);
	try {

Review comment (suggestion):
@Siumauricio Should you also consider`compose.yml` here? [That's the default now](https://docs.docker.com/compose/intro/compose-application-model/#the-compose-file) and `docker-compose.yml` is for backwards compatibility.

Code after:
				deleteVolumes ? "--volumes" : ""
			} && rm -rf ${projectPath}`;

			if (compose.serverId) {
				await execAsyncRemote(compose.serverId, command);
			} else {
				await execAsync(command, {
					cwd: projectPath,
				});
			}
		}
	} catch (error) {
		throw error;
	}

	return true;
};

export const startCompose = async (composeId: string) => {
	const compose = await findComposeById(composeId);
	try {
		const { COMPOSE_PATH } = paths(!!compose.serverId);

		const projectPath = join(COMPOSE_PATH, compose.appName, "code");
		const path =
			compose.sourceType === "raw" ? "docker-compose.yml" : compose.composePath;
		const baseCommand = `docker compose -p ${compose.appName} -f ${path} up -d`;
		if (compose.composeType === "docker-compose") {
			if (compose.serverId) {
				await execAsyncRemote(
					compose.serverId,
					`cd ${projectPath} && ${baseCommand}`,
				);
			} else {
				await execAsync(baseCommand, {
					cwd: projectPath,
				});
			}
		}

		await updateCompose(composeId, {
			composeStatus: "done",
		});
	} catch (error) {
		await updateCompose(composeId, {
			composeStatus: "idle",
		});
		throw error;
	}

	return true;
Repository: Dokploy/dokploy
File: apps/api/src/schema.ts (TypeScript)

Code before:
		description: z.string().optional(),
		server: z.boolean().optional(),
		type: z.enum(["deploy", "redeploy"]),
		applicationType: z.literal("application"),
		serverId: z.string().min(1),
	}),
	z.object({
		composeId: z.string(),
		title: z.string().optional(),
		description: z.string().optional(),
		server: z.boolean().optional(),
		type: z.enum(["deploy", "redeploy"]),
		applicationType: z.literal("compose"),
		serverId: z.string().min(1),
	}),
	z.object({
		applicationId: z.string(),
		previewDeploymentId: z.string(),
		title: z.string().optional(),
		description: z.string().optional(),
		server: z.boolean().optional(),
		type: z.enum(["deploy"]),
		applicationType: z.literal("application-preview"),
		serverId: z.string().min(1),
	}),
]);

export type DeployJob = z.infer<typeof deployJobSchema>;


Review comment (refactor):
why are we duplicating this structure? since we already have the `deployJobSchema` it doesn't make sense to duplicate the structure with another name

Code after:
import { z } from "zod";

export const deployJobSchema = z.discriminatedUnion("applicationType", [
	z.object({
		applicationId: z.string(),
		titleLog: z.string().optional(),
		descriptionLog: z.string().optional(),
		server: z.boolean().optional(),
		type: z.enum(["deploy", "redeploy"]),
		applicationType: z.literal("application"),
		serverId: z.string().min(1),
	}),
	z.object({
		composeId: z.string(),
		titleLog: z.string().optional(),
		descriptionLog: z.string().optional(),
		server: z.boolean().optional(),
		type: z.enum(["deploy", "redeploy"]),
		applicationType: z.literal("compose"),
		serverId: z.string().min(1),
	}),
	z.object({
		applicationId: z.string(),
		previewDeploymentId: z.string(),
		titleLog: z.string().optional(),
		descriptionLog: z.string().optional(),
		server: z.boolean().optional(),
		type: z.enum(["deploy"]),
		applicationType: z.literal("application-preview"),
		serverId: z.string().min(1),
	}),
]);

export type DeployJob = z.infer<typeof deployJobSchema>;
Repository: Dokploy/dokploy
File: apps/dokploy/server/queues/queueSetup.ts (TypeScript)

Code before:
import { Queue } from "bullmq";
import { redisConfig } from "./redis-connection";

const myQueue = new Queue("deployments", {
	connection: redisConfig,
});

process.on("SIGTERM", () => {
	myQueue.close();
	process.exit(0);
});

myQueue.on("error", (error) => {
	if ((error as any).code === "ECONNREFUSED") {
		console.error(
			"Make sure you have installed Redis and it is running.",
			error,
		);
	}
});

export const cleanQueuesByApplication = async (applicationId: string) => {
	const jobs = await myQueue.getJobs(["waiting", "delayed"]);

	for (const job of jobs) {
		if (job?.data?.applicationId === applicationId) {
			await job.remove();
			console.log(`Removed job ${job.id} for application ${applicationId}`);
		}
	}
};

export const cleanQueuesByCompose = async (composeId: string) => {
	const jobs = await myQueue.getJobs(["waiting", "delayed"]);

	for (const job of jobs) {
		if (job?.data?.composeId === composeId) {
			await job.remove();
			console.log(`Removed job ${job.id} for compose ${composeId}`);
		}
	}
};

export { myQueue };


Review comment (suggestion):
Hey @Siumauricio,

Just glancing at the code changes here:

```ts
		if (type === "application") {
			const command = `pkill -2 -f "docker build"`;

			if (serverId) {
				await execAsyncRemote(serverId, command);
			} else {
				await execAsync(command);
			}
		} else if (type === "compose") {
			const command = `pkill -2 -f "docker compose"`;
```


it's not obvious to me that this will only kill the dokploy build/compose and not other build/compose processes on my machine that are independent of Dokploy.

Are you able to confirm this?

Thank you!

Code after:
export const cleanQueuesByCompose = async (composeId: string) => {
	const jobs = await myQueue.getJobs(["waiting", "delayed"]);

	for (const job of jobs) {
		if (job?.data?.composeId === composeId) {
			await job.remove();
			console.log(`Removed job ${job.id} for compose ${composeId}`);
		}
	}
};

export const killDockerBuild = async (
	type: "application" | "compose",
	serverId: string | null,
) => {
	try {
		if (type === "application") {
			const command = `pkill -2 -f "docker build"`;

			if (serverId) {
				await execAsyncRemote(serverId, command);
			} else {
				await execAsync(command);
			}
		} else if (type === "compose") {
			const command = `pkill -2 -f "docker compose"`;

			if (serverId) {
				await execAsyncRemote(serverId, command);
			} else {
				await execAsync(command);
			}
		}
	} catch (error) {
		console.error(error);
	}
};

export { myQueue };
Repository: ErikBjare/gptme
File: gptme/util.py (Python)

Code before:
def print_preview(code: str, lang: str, copy: bool = False):  # pragma: no cover
    print()
    print("[bold white]Preview[/bold white]")

    if copy:
        set_copiable()
        set_copytext(code)

    # NOTE: we can set background_color="default" to remove background
    print(Syntax(code.strip("\n"), lang))
    print()


override_auto = False


def ask_execute(question="Execute code?", default=True) -> bool:  # pragma: no cover
    print_bell()  # Ring the bell just before asking for input
    termios.tcflush(sys.stdin, termios.TCIFLUSH)  # flush stdin

    choicestr = f"[{'Y' if default else 'y'}/{'n' if default else 'N'}]"
    copystr = r"\[c] to copy" if copiable else ""
    answer = console.input(
        f"[bold bright_yellow on red] {question} {choicestr}{copystr} [/] ",
    )
    if copiable and "c" in answer.lower():
        if copy():
            print("Copied to clipboard.")
        if len(answer) > 1:
            answer = answer.lower().strip("c")

    global override_auto
    if answer.lower() in [
        "auto"
    ]:  # secret option to stop asking for the rest of the session
        override_auto = True
    return answer.lower() in (["y", "yes"] + [""] if default else []) or override_auto


def clean_example(s: str, strict=False) -> str:
    orig = s
    s = re.sub(
        r"(^|\n)([>] )?([A-Za-z]+):",
        r"\1\3:",
        s,
    )
    if strict:
        assert s != orig, "Couldn't find a message"
    return s



Review comment (suggestion):
It should still be:

```suggestion
    if copiable and "c" == answer.strip().lower():
```

Code after:


def print_preview(code: str, lang: str, copy: bool = False):  # pragma: no cover
    print()
    print("[bold white]Preview[/bold white]")

    if copy:
        set_copiable()
        set_copytext(code)

    # NOTE: we can set background_color="default" to remove background
    print(Syntax(code.strip("\n"), lang))
    print()


override_auto = False


def ask_execute(question="Execute code?", default=True) -> bool:  # pragma: no cover
    print_bell()  # Ring the bell just before asking for input
    termios.tcflush(sys.stdin, termios.TCIFLUSH)  # flush stdin

    choicestr = f"[{'Y' if default else 'y'}/{'n' if default else 'N'}]"
    copystr = r"\[c] to copy" if copiable else ""
    answer = console.input(
        f"[bold bright_yellow on red] {question} {choicestr}{copystr} [/] ",
    )

    global override_auto

    if not override_auto and copiable and "c" == answer.lower().strip():
        if copy():
            print("Copied to clipboard.")
            return False
        clear_copiable()

    if answer.lower() in [
        "auto"
    ]:  # secret option to stop asking for the rest of the session
        override_auto = True
    return answer.lower() in (["y", "yes"] + [""] if default else []) or override_auto


def clean_example(s: str, strict=False) -> str:
    orig = s
    s = re.sub(
        r"(^|\n)([>] )?([A-Za-z]+):",
        r"\1\3:",
        s,
    )
    if strict:
Repository: ErikBjare/gptme
File: gptme/tools/computer.py (Python)

Code before:
"""
Tool for computer interaction through X11 or macOS native commands, including screen capture, keyboard, and mouse control.

The computer tool provides direct interaction with the desktop environment.
Similar to Anthropic's computer use demo, but integrated with gptme's architecture.

.. rubric:: Features

- Keyboard input simulation
- Mouse control (movement, clicks, dragging)
- Screen capture with automatic scaling
- Cursor position tracking

.. rubric:: Installation

On Linux, requires X11 and xdotool::

    # On Debian/Ubuntu
    sudo apt install xdotool

    # On Arch Linux
    sudo pacman -S xdotool

On macOS, uses native ``screencapture`` and external tool `cliclicker`::

    brew install cliclicker


Review comment (suggestion):
```suggestion
Tool for computer interaction for X11 or macOS environments, including screen capture, keyboard, and mouse control.
```

Code after:
"""
Tool for computer interaction for X11 or macOS environments, including screen capture, keyboard, and mouse control.

The computer tool provides direct interaction with the desktop environment.
Similar to Anthropic's computer use demo, but integrated with gptme's architecture.

.. rubric:: Features

- Keyboard input simulation
- Mouse control (movement, clicks, dragging)
- Screen capture with automatic scaling
- Cursor position tracking

.. rubric:: Installation

On Linux, requires X11 and xdotool::

    # On Debian/Ubuntu
    sudo apt install xdotool

    # On Arch Linux
    sudo pacman -S xdotool

On macOS, uses native ``screencapture`` and external tool `cliclicker`::

    brew install cliclicker
Repository: ErikBjare/gptme
File: gptme/util/ask_execute.py (Python)

Code before:

from rich import print
from rich.console import Console
from rich.syntax import Syntax

from ..message import Message
from ..tools.base import ConfirmFunc
from . import print_bell
from .clipboard import copy, set_copytext
from .prompt import get_prompt_session
from .useredit import edit_text_with_editor

console = Console(log_path=False)

# Global state
override_auto = False
auto_skip_count = 0
copiable = False
editable = False

# Editable text state
_editable_text = None
_editable_ext = None

#Compiled regex pattern
pattern = re.compile(r'(auto)(?: (\d+))?')


def set_copiable():
    """Mark content as copiable."""
    global copiable
    copiable = True


def clear_copiable():
    """Clear copiable state."""
    global copiable
    copiable = False


def set_editable_text(text: str, ext: str | None = None):
    """Set the text that can be edited and optionally its file extension."""
    global _editable_text, _editable_ext, editable
    _editable_text = text
    _editable_ext = ext
    editable = True


def get_editable_text() -> str:
    """Get the current editable text."""
    global _editable_text

Review comment (suggestion):
Call this something like `re_auto`, I don't think we need to compile it, at least not at import-time.

Code after:

from rich import print
from rich.console import Console
from rich.syntax import Syntax

from ..message import Message
from ..tools.base import ConfirmFunc
from . import print_bell
from .clipboard import copy, set_copytext
from .prompt import get_prompt_session
from .useredit import edit_text_with_editor

console = Console(log_path=False)

# Global state
override_auto = False
auto_skip_count = 0
copiable = False
editable = False

# Editable text state
_editable_text = None
_editable_ext = None


def set_copiable():
    """Mark content as copiable."""
    global copiable
    copiable = True


def clear_copiable():
    """Clear copiable state."""
    global copiable
    copiable = False


def set_editable_text(text: str, ext: str | None = None):
    """Set the text that can be edited and optionally its file extension."""
    global _editable_text, _editable_ext, editable
    _editable_text = text
    _editable_ext = ext
    editable = True


def get_editable_text() -> str:
    """Get the current editable text."""
    global _editable_text
    if _editable_text is None:
        raise RuntimeError("No editable text set")
    return _editable_text