ronantakizawa/codereview-bench huggingface dataset:
Repository: NationalSecurityAgency/ghidra
File: Ghidra/Debug/Debugger-agent-gdb/src/main/java/agent/gdb/manager/parsing/GdbMiParser.java (Java)

Code before:
					break;
				case 'r':
					baos.write('\r');
					break;
				case 'e':
					baos.write(0x1b);
					break;
				case 'a':
					baos.write(0x07);
					break;
				case '0':
				case '1':
				case '2':
				case '3':
					char ch2 = buf.get();
					if (ch2 < '0' || ch2 > '9') {
						throw new GdbParseError("octal", "\\" + ch + ch2);
					}
					char ch3 = buf.get();
					if (ch3 < '0' || ch3 > '9') {
						throw new GdbParseError("octal", "\\" + ch + ch2 + ch3);
					}
					int octchar = ((ch - '0') << 6) | ((ch2 - '0') << 3) | (ch3 - '0');
					baos.write(octchar);
					break;
				default:
					baos.write(ch);
					break;
			}
		}
		return baos.toString(StandardCharsets.UTF_8);
	}

	/**
	 * Parse the list at the cursor
	 * 
	 * @return the list
	 * @throws GdbParseError if no text matches the pattern
	 */
	public Object parseList() throws GdbParseError {
		match(LBRACKET, true);
		List<Object> result = new ArrayList<>();
		while (buf.hasRemaining()) {
			char c = peek(true);
			if (c == ']') {
				match(RBRACKET, false);
				break;
			}
			if (c == ',') {
				match(COMMA, false);
			}

Review comment (suggestion):
If we only consider what GDB will produce, vs. what it will accept, then true, we should not expect to see a first digit above 3. I do wonder if we should explicitly forbid, e.g., `\4`, since we should never expect GDB to produce that (though it will accept it and echo back `\004`).

Code after:
					break;
				case 'r':
					baos.write('\r');
					break;
				case 'e':
					baos.write(0x1b);
					break;
				case 'a':
					baos.write(0x07);
					break;
				case '0':
				case '1':
				case '2':
				case '3':
					char ch2 = buf.get();
					if (ch2 < '0' || ch2 > '9') {
						throw new GdbParseError("octal", "" + ch2);
					}
					char ch3 = buf.get();
					if (ch3 < '0' || ch3 > '9') {
						throw new GdbParseError("octal", "" + ch3);
					}
					int octchar = ((ch - '0') << 6) | ((ch2 - '0') << 3) | (ch3 - '0');
					baos.write(octchar);
					break;
				case '\\':
				case '"':
					baos.write(ch);
					break;
				default:
					throw new GdbParseError("escape", "" + ch);
			}
		}
		return baos.toString(StandardCharsets.UTF_8);
	}

	/**
	 * Parse the list at the cursor
	 * 
	 * @return the list
	 * @throws GdbParseError if no text matches the pattern
	 */
	public Object parseList() throws GdbParseError {
		match(LBRACKET, true);
		List<Object> result = new ArrayList<>();
		while (buf.hasRemaining()) {
			char c = peek(true);
			if (c == ']') {
				match(RBRACKET, false);
				break;
			}
Repository: NationalSecurityAgency/ghidra
File: Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/interpreter/InterpreterPanel.java (Java)

Code before:
	private String getInputTextPaneText() {
		String text = null;
		try {
			Document doc = inputTextPane.getDocument();
			text = doc.getText(0, doc.getLength());
		}
		catch (BadLocationException e) {
			Msg.error(this, "internal buffer error", e);
		}
		return text;
	}

	private void setInputTextPaneText(String text) {
		try {
			final Document document = inputTextPane.getDocument();
			document.remove(0, document.getLength());
			document.insertString(0, text, STDIN_SET);
		}
		catch (BadLocationException e) {
			Msg.error(this, "internal document positioning error", e);
		}
	}

	private void repositionScrollpane() {
		// NOTE:  CRAZY CODE!  subtract one to position short of final newline
		outputTextPane.setCaretPosition(Math.max(0, outputTextPane.getDocument().getLength() - 1));
	}

	void addText(String text, TextType type) {
		SimpleAttributeSet attributes;
		switch (type) {
			case STDERR:
				attributes = STDERR_SET;
				break;
			case STDIN:
				attributes = STDIN_SET;
				break;
			case STDOUT:
			default:
				attributes = STDOUT_SET;
				break;
		}
		try {
			StyledDocument document = outputTextPane.getStyledDocument();
			document.insertString(document.getLength(), text, attributes);
			repositionScrollpane();
		}
		catch (BadLocationException e) {
			Msg.error(this, "internal document positioning error", e);
		}
	}

Review comment (bug):
From what I understand, this is needed for the Python (really Jython) interpreter plugin. I'm not sure it's a matter of preference or a real bug, but we might revert this on our end. Have you tried using the Python plugin with this change?

Code after:
	private String getInputTextPaneText() {
		String text = null;
		try {
			Document doc = inputTextPane.getDocument();
			text = doc.getText(0, doc.getLength());
		}
		catch (BadLocationException e) {
			Msg.error(this, "internal buffer error", e);
		}
		return text;
	}

	private void setInputTextPaneText(String text) {
		try {
			final Document document = inputTextPane.getDocument();
			document.remove(0, document.getLength());
			document.insertString(0, text, STDIN_SET);
		}
		catch (BadLocationException e) {
			Msg.error(this, "internal document positioning error", e);
		}
	}

	private void repositionScrollpane() {
		outputTextPane.setCaretPosition(Math.max(0, outputTextPane.getDocument().getLength()));
	}

	AnsiRenderer stdErrRenderer = new AnsiRenderer();
	AnsiRenderer stdInRenderer = new AnsiRenderer();
	AnsiRenderer stdOutRenderer = new AnsiRenderer();

	void addText(String text, TextType type) {
		SimpleAttributeSet attributes;
		AnsiRenderer renderer;
		switch (type) {
			case STDERR:
				renderer = stdErrRenderer;
				attributes = STDERR_SET;
				break;
			case STDIN:
				renderer = stdInRenderer;
				attributes = STDIN_SET;
				break;
			case STDOUT:
			default:
				renderer = stdOutRenderer;
				attributes = STDOUT_SET;
				break;
		}
		try {
			StyledDocument document = outputTextPane.getStyledDocument();
Repository: NationalSecurityAgency/ghidra
File: Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/archive/FileArchive.java (Java)

Code before:
		}

		@Override
		public void favoritesChanged(DataTypeManager dtm, DataTypePath path, boolean isFavorite) {
			// don't care
		}

		@Override
		public void sourceArchiveAdded(DataTypeManager dtm, SourceArchive dataTypeSource) {
			setChanged(true);
		}

		@Override
		public void sourceArchiveChanged(DataTypeManager dtm, SourceArchive dataTypeSource) {
			setChanged(true);
		}
	}

	@Override
	public void saveAs(Component component) throws IOException {
		File saveAsFile = ArchiveUtils.getFile(component, this);
		if (saveAsFile == null) {
			return;
		}

		if (saveAsFile.getName().equals(getFile().getName())) {
			save();
		}
		else {
			saveAs(saveAsFile);
		}
	}

	@Override
	public ImageIcon getIcon(boolean expanded) {
		return expanded ? OPEN_ICON : CLOSED_ICON;
	}
}


Review comment (suggestion):
this needs to change to compare the full file path, not just the name.

Suggest ```saveAsFile.equals(archiveFile.getFile(false))```


Code after:
		}

		@Override
		public void favoritesChanged(DataTypeManager dtm, DataTypePath path, boolean isFavorite) {
			// don't care
		}

		@Override
		public void sourceArchiveAdded(DataTypeManager dtm, SourceArchive dataTypeSource) {
			setChanged(true);
		}

		@Override
		public void sourceArchiveChanged(DataTypeManager dtm, SourceArchive dataTypeSource) {
			setChanged(true);
		}
	}

	@Override
	public void saveAs(Component component) throws IOException {
		File saveAsFile = ArchiveUtils.getFile(component, this);
		if (saveAsFile == null) {
			return;
		}

		if (saveAsFile.equals(archiveFile.getFile(false))) {
			save();
		}
		else {
			saveAs(saveAsFile);
		}
	}

	@Override
	public ImageIcon getIcon(boolean expanded) {
		return expanded ? OPEN_ICON : CLOSED_ICON;
	}
}
Repository: NationalSecurityAgency/ghidra
File: Ghidra/Features/Decompiler/src/decompile/cpp/sleigh_arch.cc (C++)

Code before:

{
  return description[languageindex].getDescription();
}

/// If the current \b languageindex matches the \b last_languageindex,
/// try to reuse the previous Sleigh object, so we don't reload
/// the .sla file.
/// \return \b true if it can be reused
bool SleighArchitecture::isTranslateReused(void)

{
  return (translators.find(languageindex) != translators.end());
}

Translate *SleighArchitecture::buildTranslator(DocumentStorage &store)

{				// Build a sleigh translator
  map<int4,Sleigh>::iterator iter;

  iter = translators.find(languageindex);
  if (iter != translators.end()) {
    iter->second.reset(loader, context);
    return &iter->second;
  }
  translators[languageindex] = Sleigh(loader,context);
  return &translators[languageindex];
}

PcodeInjectLibrary *SleighArchitecture::buildPcodeInjectLibrary(void)

{ // Build the pcode injector based on sleigh
  PcodeInjectLibrary *res;

  res = new PcodeInjectLibrarySleigh(this);
  return res;
}

void SleighArchitecture::buildTypegrp(DocumentStorage &store)

{
  types = new TypeFactory(this); // Initialize the object
}

void SleighArchitecture::buildCoreTypes(DocumentStorage &store)

{
  const Element *el = store.getTag("coretypes");

  if (el != (const Element *)0) {
    XmlDecode decoder(this,el);

Review comment (suggestion):
Please use the emplace method to avoid the need for a copy constructor and a default constructor for the Sleigh class.

```
  pair<map<int4,Sleigh>::iterator,bool> res;
  res = translators.emplace(piecewise_construct,forward_as_tuple(languageindex),forward_as_tuple(loader,context));
  return &(*res.first).second;

```

Code after:

{
  return description[languageindex].getDescription();
}

/// If the current \b languageindex matches the \b last_languageindex,
/// try to reuse the previous Sleigh object, so we don't reload
/// the .sla file.
/// \return \b true if it can be reused
bool SleighArchitecture::isTranslateReused(void)

{
  return (translators.find(languageindex) != translators.end());
}

Translate *SleighArchitecture::buildTranslator(DocumentStorage &store)

{				// Build a sleigh translator
  map<int4,Sleigh>::iterator iter;

  iter = translators.find(languageindex);
  if (iter != translators.end()) {
    iter->second.reset(loader, context);
    return &iter->second;
  }
  pair<map<int4,Sleigh>::iterator,bool> res;
  res = translators.emplace(piecewise_construct,forward_as_tuple(languageindex),forward_as_tuple(loader,context));
  return &(*res.first).second;
}

PcodeInjectLibrary *SleighArchitecture::buildPcodeInjectLibrary(void)

{ // Build the pcode injector based on sleigh
  PcodeInjectLibrary *res;

  res = new PcodeInjectLibrarySleigh(this);
  return res;
}

void SleighArchitecture::buildTypegrp(DocumentStorage &store)

{
  types = new TypeFactory(this); // Initialize the object
}

void SleighArchitecture::buildCoreTypes(DocumentStorage &store)

{
  const Element *el = store.getTag("coretypes");

  if (el != (const Element *)0) {
Repository: OpenBB-finance/OpenBBTerminal
File: gamestonk_terminal/common/prediction_techniques/mc_model.py (Python)

Code before:
    data : Union[pd.Series, np.array]
        Input data.
    n_future : int
        Number of future steps
    n_sims : int
        Number of simulations to run
    use_log : bool, optional
        Flag to use log returns, by default True

    Returns
    -------
    np.array
        Array of predictions.  Has shape (n_future, n_sims)
    """

    if use_log:
        changes = np.log(1 + data.pct_change().dropna())
    else:
        changes = data.pct_change().drop_na()

    dist_mean = changes.mean()
    dist_var = changes.var()
    dist_drift = dist_mean - 0.5 * dist_var
    dist_std = np.sqrt(dist_var)

    Z = norm.ppf(np.random.rand(n_future, n_sims))
    predicted_change = np.exp(dist_drift + dist_std * Z)
    possible_paths = np.zeros_like(predicted_change)
    possible_paths[0] = data.values[-1]

    for t in range(1, n_future):
        possible_paths[t] = possible_paths[t - 1] * predicted_change[t]
    return possible_paths


Review comment (suggestion):
a chart to represent a variable is usually a bad idea, this is usually used only in loops.

Also, having it upper case usually stands for a constant.

Code after:
    data : Union[pd.Series, np.array]
        Input data.
    n_future : int
        Number of future steps
    n_sims : int
        Number of simulations to run
    use_log : bool, optional
        Flag to use log returns, by default True

    Returns
    -------
    np.array
        Array of predictions.  Has shape (n_future, n_sims)
    """
    changes = data.pct_change().dropna()
    if use_log:
        changes = np.log(1 + changes)

    dist_mean = changes.mean()
    dist_var = changes.var()
    dist_drift = dist_mean - 0.5 * dist_var
    dist_std = np.sqrt(dist_var)

    random_steps = norm.ppf(np.random.rand(n_future, n_sims))
    predicted_change = np.exp(dist_drift + dist_std * random_steps)
    possible_paths = np.zeros_like(predicted_change)
    possible_paths[0] = data.values[-1]

    for t in range(1, n_future):
        possible_paths[t] = possible_paths[t - 1] * predicted_change[t]
    return possible_paths
Repository: OpenBB-finance/OpenBBTerminal
File: gamestonk_terminal/custom/custom_view.py (Python)

Code before:
def custom_plot(
    data: pd.DataFrame,
    y_col: str,
    x_col: str = "",
    kind: str = "line",
    export: str = "",
    external_axes: Optional[List[plt.Axes]] = None,
):
    """Plot custom data

    Parameters
    ----------
    data: pd.DataFrame
        Dataframe of custom data
    y_col: str
        Column for y data
    x_col: str
        Column for x data.  Uses index if not supplied.
    kind : str
        Kind of plot to pass to pandas plot function
    export: str
        Format to export image
    external_axes: Optional[List[plt.Axes]]:
        External axes for plot
    """
    if not external_axes:
        _, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
    else:
        ax = external_axes[0]

    if x_col:
        data.plot(x=x_col, y=y_col, kind=kind, ax=ax)
    else:
        data.reset_index().plot(x=data.index.name, y=y_col, kind=kind, ax=ax)

    if kind in ["scatter", "line"]:
        theme.style_primary_axis(ax)

    theme.visualize_output()
    console.print()
    export_data(
        export,
        os.path.dirname(os.path.abspath(__file__)),
        "custom_plot",
    )


Review comment (suggestion):
If we actually have a list of axes this conditional starts yelling about using `all()` or `any()`. In the other branch I've changed the conditional to `if external_axes is None:` and it works with both types that we can pass

Code after:
    data: pd.DataFrame,
    y_col: str,
    x_col: str = "",
    kind: str = "line",
    export: str = "",
    external_axes: Optional[List[plt.Axes]] = None,
):
    """Plot custom data

    Parameters
    ----------
    data: pd.DataFrame
        Dataframe of custom data
    y_col: str
        Column for y data
    x_col: str
        Column for x data.  Uses index if not supplied.
    kind : str
        Kind of plot to pass to pandas plot function
    export: str
        Format to export image
    external_axes: Optional[List[plt.Axes]]:
        External axes for plot
    """
    if external_axes is None:
        _, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
    else:
        ax = external_axes[0]

    if x_col:
        data.plot(x=x_col, y=y_col, kind=kind, ax=ax)
    else:
        data.reset_index().plot(x=data.index.name, y=y_col, kind=kind, ax=ax)

    if kind in ["scatter", "line"]:
        theme.style_primary_axis(ax)
        theme.visualize_output()

    export_data(
        export,
        os.path.dirname(os.path.abspath(__file__)),
        "custom_plot",
    )
Repository: OpenBB-finance/OpenBBTerminal
File: openbb_terminal/stocks/stocks_helper.py (Python)

Code before:

import argparse
import logging
import os
from datetime import datetime, timedelta, date
from typing import List, Union, Optional, Iterable

import financedatabase as fd
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import mplfinance as mpf
import numpy as np
import pandas as pd
import pandas_market_calendars as mcal
import plotly.graph_objects as go
import pyEX
import pytz
import requests

import yfinance as yf
from alpha_vantage.timeseries import TimeSeries
from numpy.core.fromnumeric import transpose
from plotly.subplots import make_subplots
from scipy import stats

from openbb_terminal.config_terminal import theme, API_POLYGON_KEY
from openbb_terminal import config_terminal as cfg
from openbb_terminal.helper_funcs import (
    export_data,
    parse_known_args_and_warn,
    plot_autoscale,
    get_user_timezone_or_invalid,
    print_rich_table,
    lambda_long_number_format_y_axis,
)
from openbb_terminal.rich_config import console

logger = logging.getLogger(__name__)

# pylint: disable=no-member,too-many-branches,C0302,R0913

INTERVALS = [1, 5, 15, 30, 60]
SOURCES = ["yf", "av", "iex"]

market_coverage_suffix = {
    "USA": ["CBT", "CME", "NYB", "CMX", "NYM"],
    "Argentina": ["BA"],
    "Austria": ["VI"],
    "Australia": ["AX"],
    "Belgium": ["BR"],
    "Brazil": ["SA"],

Review comment (suggestion):
let's load config_terminal as cfg and then use `cfg.API_POLYGON_KEY`. That's how we doing in the other places

Code after:

import argparse
import logging
import os
from datetime import datetime, timedelta, date
from typing import List, Union, Optional, Iterable

import financedatabase as fd
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import mplfinance as mpf
import numpy as np
import pandas as pd
import pandas_market_calendars as mcal
import plotly.graph_objects as go
import pyEX
import pytz
import requests

import yfinance as yf
from alpha_vantage.timeseries import TimeSeries
from numpy.core.fromnumeric import transpose
from plotly.subplots import make_subplots
from scipy import stats

from openbb_terminal import config_terminal as cfg
from openbb_terminal.helper_funcs import (
    export_data,
    parse_known_args_and_warn,
    plot_autoscale,
    get_user_timezone_or_invalid,
    print_rich_table,
    lambda_long_number_format_y_axis,
)
from openbb_terminal.rich_config import console

logger = logging.getLogger(__name__)

# pylint: disable=no-member,too-many-branches,C0302,R0913

INTERVALS = [1, 5, 15, 30, 60]
SOURCES = ["yf", "av", "iex"]

market_coverage_suffix = {
    "USA": ["CBT", "CME", "NYB", "CMX", "NYM"],
    "Argentina": ["BA"],
    "Austria": ["VI"],
    "Australia": ["AX"],
    "Belgium": ["BR"],
    "Brazil": ["SA"],
    "Canada": ["CN", "NE", "TO", "V"],
Repository: OpenBB-finance/OpenBBTerminal
File: openbb_terminal/stocks/options/op_helpers.py (Python)

Code before:
        Returns
        ----------
        num : float
            The Vomma

        """
        return (
            change
            * np.exp(-self.div_cont * self.exp_time)
            * self.d1
            * self.d2
            * np.sqrt(self.exp_time)
            * self.price
            * norm.pdf(self.d1)
            / self._sigma
        )


@log_start_end(log=logger)
def get_dte(chain: pd.DataFrame) -> pd.DataFrame:
    """
    Returns a new column containing the DTE as an integer, including 0.
    Requires the chain to have the column labeled as, expiration.
    """
    if "expiration" not in chain.columns:
        raise ValueError("No column labeled 'expiration' was found.")

    now = datetime.now()
    temp = pd.DatetimeIndex(chain.expiration)
    temp_ = (temp - now).days + 1
    chain["dte"] = temp_

    return chain


Review comment (suggestion):
If expirarion = now, then this would return 1 instead of 0.

I would like to see this done how I do elsewhere, where you look at the total_seconds between now the expiration (need to add 16 hours) and then convert seconds to days.  This will also avoid the divergence for 0dte calculates.

Code after:
            The Vomma

        """
        return (
            change
            * np.exp(-self.div_cont * self.exp_time)
            * self.d1
            * self.d2
            * np.sqrt(self.exp_time)
            * self.price
            * norm.pdf(self.d1)
            / self._sigma
        )


def get_dte(chain: pd.DataFrame) -> pd.DataFrame:
    """
    Returns a new column containing the DTE as an integer, including 0.
    Requires the chain to have the column labeled as, expiration.
    """
    if "expiration" not in chain.columns:
        raise ValueError("No column labeled 'expiration' was found.")

    now = datetime.now()
    temp = pd.DatetimeIndex(chain.expiration)
    temp_ = (temp - now).days + 1
    chain["dte"] = temp_

    return chain
Repository: OpenBB-finance/OpenBBTerminal
File: openbb_terminal/stocks/stocks_helper.py (Python)

Code before:
            if possible_sources:
                console.print(
                    f"[red]{column} can be plotted with the following sources: {', '.join(possible_sources)}[/red]"
                )
            else:
                console.print(
                    f"[red]{column} does not exist in a existing data source.[/red]"
                )
        return True
    return False


def heikin_ashi(data: pd.DataFrame) -> pd.DataFrame:
    """Return OHLC data as Heikin Ashi Candles.

    Parameters
    ----------
    data: pd.DataFrame
        DataFrame containing OHLC data.

    Returns
    -------
    pd.DataFrame
        Appended DataFrame with Heikin Ashi candle calculations.
    """

    ha = candles.ha(
        data["Open"],
        data["High"],
        data["Low"],
        data["Close"],
    )
    ha.columns = [
        "HA Open",
        "HA High",
        "HA Low",
        "HA Close",
    ]

    return pd.concat([data, ha], axis=1)


Review comment (suggestion):
can you add a check that the correct column names are in the data, that way accessing data["Open"] doesnt throw an error if data["open"] sneaks in

Code after:
            if possible_sources:
                console.print(
                    f"[red]{column} can be plotted with the following sources: {', '.join(possible_sources)}[/red]"
                )
            else:
                console.print(
                    f"[red]{column} does not exist in a existing data source.[/red]"
                )
        return True
    return False


def heikin_ashi(data: pd.DataFrame) -> pd.DataFrame:
    """Return OHLC data as Heikin Ashi Candles.

    Parameters
    ----------
    data: pd.DataFrame
        DataFrame containing OHLC data.

    Returns
    -------
    pd.DataFrame
        Appended DataFrame with Heikin Ashi candle calculations.
    """

    check_columns = ["Open", "High", "Low", "Close"]

    data.rename(
        columns={"open": "Open", "high": "High", "low": "Low", "close": "Close"},
        inplace=True,
    )

    for item in check_columns:
        if item not in data.columns:
            raise ValueError(
                "The expected column labels, "
                f"{check_columns}"
                ", were not found in DataFrame."
            )

    ha = candles.ha(
        data["Open"],
        data["High"],
        data["Low"],
        data["Close"],
    )
    ha.columns = [
        "HA Open",
        "HA High",
        "HA Low",