gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _maybe_right_yaxis(self, ax):
    ypos = ax.get_yaxis().get_ticks_position().strip().lower()

    if self.secondary_y and ypos != "right":
        orig_ax = ax
        ax = ax.twinx()
        if len(orig_ax.get_lines()) == 0:  # no data on left y
            orig_ax.get_yaxis().set_visible(False)
    else:
        ax.get_yaxis().set_visible(True)

    return ax


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def _maybe_right_yaxis(self, ax):
    _types = (list, tuple, np.ndarray)
    sec_true = isinstance(self.secondary_y, bool) and self.secondary_y
    list_sec = isinstance(self.secondary_y, _types)
    has_sec = list_sec and len(self.secondary_y) > 0
    all_sec = list_sec and len(self.secondary_y) == self.nseries

    if (sec_true or has_sec) and not hasattr(ax, "right_ax"):
        orig_ax, new_ax = ax, ax.twinx()
        orig_ax.right_ax, new_ax.left_ax = new_ax, orig_ax

        if len(orig_ax.get_lines()) == 0:  # no data on left y
            orig_ax.get_yaxis().set_visible(False)

        if len(new_ax.get_lines()) == 0:
            new_ax.get_yaxis().set_visible(False)

        if sec_true or all_sec:
            ax = new_ax
    else:
        ax.get_yaxis().set_visible(True)

    return ax
# Buggy code
def _setup_subplots(self):
    if self.subplots:
        nrows, ncols = self._get_layout()
        if self.ax is None:
            fig, axes = _subplots(
                nrows=nrows,
                ncols=ncols,
                sharex=self.sharex,
                sharey=self.sharey,
                figsize=self.figsize,
                secondary_y=self.secondary_y,
                data=self.data,
            )
        else:
            fig, axes = _subplots(
                nrows=nrows,
                ncols=ncols,
                sharex=self.sharex,
                sharey=self.sharey,
                figsize=self.figsize,
                ax=self.ax,
                secondary_y=self.secondary_y,
                data=self.data,
            )
    else:
        if self.ax is None:
            fig = self.plt.figure(figsize=self.figsize)
            ax = fig.add_subplot(111)
            ax = self._maybe_right_yaxis(ax)
            self.ax = ax
        else:
            fig = self.ax.get_figure()
            self.ax = self._maybe_right_yaxis(self.ax)

        axes = [self.ax]

    self.fig = fig
    self.axes = axes


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def _setup_subplots(self):
    if self.subplots:
        nrows, ncols = self._get_layout()
        if self.ax is None:
            fig, axes = _subplots(
                nrows=nrows,
                ncols=ncols,
                sharex=self.sharex,
                sharey=self.sharey,
                figsize=self.figsize,
                secondary_y=self.secondary_y,
                data=self.data,
            )
        else:
            fig, axes = _subplots(
                nrows=nrows,
                ncols=ncols,
                sharex=self.sharex,
                sharey=self.sharey,
                figsize=self.figsize,
                ax=self.ax,
                secondary_y=self.secondary_y,
                data=self.data,
            )
    else:
        if self.ax is None:
            fig = self.plt.figure(figsize=self.figsize)
            ax = fig.add_subplot(111)
            ax = self._maybe_right_yaxis(ax)
        else:
            fig = self.ax.get_figure()
            ax = self._maybe_right_yaxis(self.ax)

        axes = [ax]

    self.fig = fig
    self.axes = axes
# Buggy code
def _adorn_subplots(self):
    if self.subplots:
        to_adorn = self.axes
    else:
        to_adorn = [self.ax]

    # todo: sharex, sharey handling?

    for ax in to_adorn:
        if self.yticks is not None:
            ax.set_yticks(self.yticks)

        if self.xticks is not None:
            ax.set_xticks(self.xticks)

        if self.ylim is not None:
            ax.set_ylim(self.ylim)

        if self.xlim is not None:
            ax.set_xlim(self.xlim)

        ax.grid(self.grid)

    if self.legend and not self.subplots:
        self.ax.legend(loc="best", title=self.legend_title)

    if self.title:
        if self.subplots:
            self.fig.suptitle(self.title)
        else:
            self.ax.set_title(self.title)

    if self._need_to_set_index:
        labels = [_stringify(key) for key in self.data.index]
        labels = dict(zip(range(len(self.data.index)), labels))

        for ax_ in self.axes:
            # ax_.set_xticks(self.xticks)
            xticklabels = [labels.get(x, "") for x in ax_.get_xticks()]
            ax_.set_xticklabels(xticklabels, rotation=self.rot)


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def _adorn_subplots(self):
    to_adorn = self.axes

    # todo: sharex, sharey handling?

    for ax in to_adorn:
        if self.yticks is not None:
            ax.set_yticks(self.yticks)

        if self.xticks is not None:
            ax.set_xticks(self.xticks)

        if self.ylim is not None:
            ax.set_ylim(self.ylim)

        if self.xlim is not None:
            ax.set_xlim(self.xlim)

        ax.grid(self.grid)

    if self.title:
        if self.subplots:
            self.fig.suptitle(self.title)
        else:
            self.axes[0].set_title(self.title)

    if self._need_to_set_index:
        labels = [_stringify(key) for key in self.data.index]
        labels = dict(zip(range(len(self.data.index)), labels))

        for ax_ in self.axes:
            # ax_.set_xticks(self.xticks)
            xticklabels = [labels.get(x, "") for x in ax_.get_xticks()]
            ax_.set_xticklabels(xticklabels, rotation=self.rot)
# Buggy code
def _make_plot(self):
    from scipy.stats import gaussian_kde

    plotf = self._get_plot_function()
    for i, (label, y) in enumerate(self._iter_data()):
        ax, style = self._get_ax_and_style(i)

        if self.style:
            style = self.style
        gkde = gaussian_kde(y)
        sample_range = max(y) - min(y)
        ind = np.linspace(
            min(y) - 0.5 * sample_range, max(y) + 0.5 * sample_range, 1000
        )
        ax.set_ylabel("Density")
        plotf(ax, ind, gkde.evaluate(ind), style, label=label, **self.kwds)
        ax.grid(self.grid)


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def _make_plot(self):
    from scipy.stats import gaussian_kde

    plotf = self._get_plot_function()
    for i, (label, y) in enumerate(self._iter_data()):
        ax = self._get_ax(i)
        style = self._get_style(i, label)

        label = com._stringify(label)

        gkde = gaussian_kde(y)
        sample_range = max(y) - min(y)
        ind = np.linspace(
            min(y) - 0.5 * sample_range, max(y) + 0.5 * sample_range, 1000
        )
        ax.set_ylabel("Density")
        plotf(ax, ind, gkde.evaluate(ind), style, label=label, **self.kwds)
        ax.grid(self.grid)
# Buggy code
def _post_plot_logic(self):
    df = self.data

    if self.subplots and self.legend:
        self.axes[0].legend(loc="best")


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def _post_plot_logic(self):
    df = self.data

    if self.subplots and self.legend:
        for ax in self.axes:
            ax.legend(loc="best")
# Buggy code
def __init__(self, data, **kwargs):
    MPLPlot.__init__(self, data, **kwargs)


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def __init__(self, data, **kwargs):
    self.mark_right = kwargs.pop("mark_right", True)
    MPLPlot.__init__(self, data, **kwargs)
# Buggy code
def _use_dynamic_x(self):
    freq = self._index_freq()

    ax, _ = self._get_ax_and_style(0)
    ax_freq = getattr(ax, "freq", None)
    if freq is None:  # convert irregular if axes has freq info
        freq = ax_freq
    else:  # do not use tsplot if irregular was plotted first
        if (ax_freq is None) and (len(ax.get_lines()) > 0):
            return False

    return (freq is not None) and self._is_dynamic_freq(freq)


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def _use_dynamic_x(self):
    freq = self._index_freq()

    ax = self._get_ax(0)
    ax_freq = getattr(ax, "freq", None)
    if freq is None:  # convert irregular if axes has freq info
        freq = ax_freq
    else:  # do not use tsplot if irregular was plotted first
        if (ax_freq is None) and (len(ax.get_lines()) > 0):
            return False

    return (freq is not None) and self._is_dynamic_freq(freq)
# Buggy code
def _make_plot(self):
    # this is slightly deceptive
    if self.use_index and self._use_dynamic_x():
        data = self._maybe_convert_index(self.data)
        self._make_ts_plot(data)
    else:
        x = self._get_xticks(convert_period=True)

        plotf = self._get_plot_function()

        for i, (label, y) in enumerate(self._iter_data()):
            ax, style = self._get_ax_and_style(i)

            if self.style:
                style = self.style

            mask = com.isnull(y)
            if mask.any():
                y = np.ma.array(y)
                y = np.ma.masked_where(mask, y)

            plotf(ax, x, y, style, label=label, **self.kwds)
            ax.grid(self.grid)


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def _make_plot(self):
    # this is slightly deceptive
    if self.use_index and self._use_dynamic_x():
        data = self._maybe_convert_index(self.data)
        self._make_ts_plot(data, **self.kwds)
    else:
        import matplotlib.pyplot as plt

        cycle = "".join(plt.rcParams.get("axes.color_cycle", list("bgrcmyk")))
        colors = self.kwds.pop("colors", cycle)
        lines = []
        labels = []
        x = self._get_xticks(convert_period=True)

        plotf = self._get_plot_function()

        for i, (label, y) in enumerate(self._iter_data()):
            ax = self._get_ax(i)
            style = self._get_style(i, label)
            kwds = self.kwds.copy()
            if re.match("[a-z]+", style) is None:
                kwds["color"] = colors[i % len(colors)]

            label = com._stringify(label)

            mask = com.isnull(y)
            if mask.any():
                y = np.ma.array(y)
                y = np.ma.masked_where(mask, y)

            newline = plotf(ax, x, y, style, label=label, **kwds)[0]
            lines.append(newline)
            leg_label = label
            if self.mark_right and self.on_right(i):
                leg_label += " (right)"
            labels.append(leg_label)
            ax.grid(self.grid)

        self._make_legend(lines, labels)
# Buggy code
def _make_ts_plot(self, data, **kwargs):
    from pandas.tseries.plotting import tsplot

    plotf = self._get_plot_function()

    if isinstance(data, Series):
        ax, _ = self._get_ax_and_style(0)  # self.axes[0]

        label = com._stringify(self.label)
        tsplot(data, plotf, ax=ax, label=label, style=self.style, **kwargs)
        ax.grid(self.grid)
    else:
        for i, col in enumerate(data.columns):
            ax, _ = self._get_ax_and_style(i)
            label = com._stringify(col)
            tsplot(data[col], plotf, ax=ax, label=label, **kwargs)
            ax.grid(self.grid)


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def _make_ts_plot(self, data, **kwargs):
    from pandas.tseries.plotting import tsplot
    import matplotlib.pyplot as plt

    kwargs = kwargs.copy()
    cycle = "".join(plt.rcParams.get("axes.color_cycle", list("bgrcmyk")))
    colors = kwargs.pop("colors", "".join(cycle))

    plotf = self._get_plot_function()
    lines = []
    labels = []

    def to_leg_label(label, i):
        if self.mark_right and self.on_right(i):
            return label + " (right)"
        return label

    if isinstance(data, Series):
        ax = self._get_ax(0)  # self.axes[0]
        style = self.style or ""
        label = com._stringify(self.label)
        if re.match("[a-z]+", style) is None:
            kwargs["color"] = colors[0]

        newlines = tsplot(data, plotf, ax=ax, label=label, style=self.style, **kwargs)
        ax.grid(self.grid)
        lines.append(newlines[0])
        leg_label = to_leg_label(label, 0)
        labels.append(leg_label)
    else:
        for i, col in enumerate(data.columns):
            label = com._stringify(col)
            ax = self._get_ax(i)
            style = self._get_style(i, col)
            kwds = kwargs.copy()
            if re.match("[a-z]+", style) is None:
                kwds["color"] = colors[i % len(colors)]

            newlines = tsplot(data[col], plotf, ax=ax, label=label, style=style, **kwds)

            lines.append(newlines[0])
            leg_label = to_leg_label(label, i)
            labels.append(leg_label)
            ax.grid(self.grid)

    self._make_legend(lines, labels)
# Buggy code
def _maybe_convert_index(self, data):
    # tsplot converts automatically, but don't want to convert index
    # over and over for DataFrames
    from pandas.core.frame import DataFrame

    if isinstance(data.index, DatetimeIndex) and isinstance(data, DataFrame):
        freq = getattr(data.index, "freq", None)

        if freq is None:
            freq = getattr(data.index, "inferred_freq", None)

        if isinstance(freq, DateOffset):
            freq = freq.rule_code

        freq = get_period_alias(freq)

        if freq is None:
            ax, _ = self._get_ax_and_style(0)
            freq = getattr(ax, "freq", None)

        if freq is None:
            raise ValueError("Could not get frequency alias for plotting")

        data = DataFrame(
            data.values, index=data.index.to_period(freq=freq), columns=data.columns
        )
    return data


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def _maybe_convert_index(self, data):
    # tsplot converts automatically, but don't want to convert index
    # over and over for DataFrames
    from pandas.core.frame import DataFrame

    if isinstance(data.index, DatetimeIndex) and isinstance(data, DataFrame):
        freq = getattr(data.index, "freq", None)

        if freq is None:
            freq = getattr(data.index, "inferred_freq", None)
        if isinstance(freq, DateOffset):
            freq = freq.rule_code
        freq = get_period_alias(freq)

        if freq is None:
            ax = self._get_ax(0)
            freq = getattr(ax, "freq", None)

        if freq is None:
            raise ValueError("Could not get frequency alias for plotting")

        data = DataFrame(
            data.values, index=data.index.to_period(freq=freq), columns=data.columns
        )
    return data
# Buggy code
def _post_plot_logic(self):
    df = self.data

    if self.legend:
        if self.subplots:
            for ax in self.axes:
                ax.legend(loc="best")
        else:
            self.axes[0].legend(loc="best")

    condition = (
        not self._use_dynamic_x
        and df.index.is_all_dates
        and not self.subplots
        or (self.subplots and self.sharex)
    )

    index_name = self._get_index_name()

    for ax in self.axes:
        if condition:
            format_date_labels(ax)

        if index_name is not None:
            ax.set_xlabel(index_name)


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def _post_plot_logic(self):
    df = self.data

    condition = (
        not self._use_dynamic_x
        and df.index.is_all_dates
        and not self.subplots
        or (self.subplots and self.sharex)
    )

    index_name = self._get_index_name()

    for ax in self.axes:
        if condition:
            format_date_labels(ax)

        if index_name is not None:
            ax.set_xlabel(index_name)

    if self.subplots and self.legend:
        for ax in self.axes:
            ax.legend(loc="best")
# Buggy code
def __repr__(self):
    from pandas.core.format import _format_datetime64

    values = self.values

    freq = None
    if self.offset is not None:
        freq = self.offset.freqstr

    summary = str(self.__class__)
    if len(self) > 0:
        first = _format_datetime64(values[0], tz=self.tz)
        last = _format_datetime64(values[-1], tz=self.tz)
        summary += "\n[%s, ..., %s]" % (first, last)
    tagline = "\nLength: %d, Freq: %s, Timezone: %s"
    summary += tagline % (len(self), freq, self.tz)

    return summary


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def __repr__(self):
    from pandas.core.format import _format_datetime64

    values = self.values

    freq = None
    if self.offset is not None:
        freq = self.offset.freqstr

    summary = str(self.__class__)
    if len(self) == 1:
        first = _format_datetime64(values[0], tz=self.tz)
        summary += "\n[%s]" % first
    elif len(self) == 2:
        first = _format_datetime64(values[0], tz=self.tz)
        last = _format_datetime64(values[-1], tz=self.tz)
        summary += "\n[%s, %s]" % (first, last)
    elif len(self) > 2:
        first = _format_datetime64(values[0], tz=self.tz)
        last = _format_datetime64(values[-1], tz=self.tz)
        summary += "\n[%s, ..., %s]" % (first, last)

    tagline = "\nLength: %d, Freq: %s, Timezone: %s"
    summary += tagline % (len(self), freq, self.tz)

    return summary
# Buggy code
def intersection(self, other):
    """
    Specialized intersection for DatetimeIndex objects. May be much faster
    than Index.union

    Parameters
    ----------
    other : DatetimeIndex or array-like

    Returns
    -------
    y : Index or DatetimeIndex
    """
    if not isinstance(other, DatetimeIndex):
        try:
            other = DatetimeIndex(other)
        except TypeError:
            pass
        result = Index.intersection(self, other)
        if isinstance(result, DatetimeIndex):
            if result.freq is None:
                result.offset = to_offset(result.inferred_freq)
        return result

    elif other.offset != self.offset or (
        not self.is_monotonic or not other.is_monotonic
    ):
        result = Index.intersection(self, other)
        if isinstance(result, DatetimeIndex):
            if result.freq is None:
                result.offset = to_offset(result.inferred_freq)
        return result

    # to make our life easier, "sort" the two ranges
    if self[0] <= other[0]:
        left, right = self, other
    else:
        left, right = other, self

    end = min(left[-1], right[-1])
    start = right[0]

    if end < start:
        return type(self)(data=[])
    else:
        lslice = slice(*left.slice_locs(start, end))
        left_chunk = left.values[lslice]
        return self._view_like(left_chunk)


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def intersection(self, other):
    """
    Specialized intersection for DatetimeIndex objects. May be much faster
    than Index.union

    Parameters
    ----------
    other : DatetimeIndex or array-like

    Returns
    -------
    y : Index or DatetimeIndex
    """
    if not isinstance(other, DatetimeIndex):
        try:
            other = DatetimeIndex(other)
        except TypeError:
            pass
        result = Index.intersection(self, other)
        if isinstance(result, DatetimeIndex):
            if result.freq is None:
                result.offset = to_offset(result.inferred_freq)
        return result

    elif (
        other.offset is None
        or self.offset is None
        or other.offset != self.offset
        or (not self.is_monotonic or not other.is_monotonic)
    ):
        result = Index.intersection(self, other)
        if isinstance(result, DatetimeIndex):
            if result.freq is None:
                result.offset = to_offset(result.inferred_freq)
        return result

    # to make our life easier, "sort" the two ranges
    if self[0] <= other[0]:
        left, right = self, other
    else:
        left, right = other, self

    end = min(left[-1], right[-1])
    start = right[0]

    if end < start:
        return type(self)(data=[])
    else:
        lslice = slice(*left.slice_locs(start, end))
        left_chunk = left.values[lslice]
        return self._view_like(left_chunk)
# Buggy code
def get_value(self, series, key):
    """
    Fast lookup of value from 1-dimensional ndarray. Only use this if you
    know what you're doing
    """
    try:
        return Index.get_value(self, series, key)
    except KeyError:
        try:
            loc = self._get_string_slice(key)
            return series[loc]
        except (TypeError, ValueError, KeyError):
            pass

        if isinstance(key, time):
            locs = self.indexer_at_time(key)
            return series.take(locs)

        stamp = Timestamp(key)
        try:
            return self._engine.get_value(series, stamp)
        except KeyError:
            raise KeyError(stamp)


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def get_value(self, series, key):
    """
    Fast lookup of value from 1-dimensional ndarray. Only use this if you
    know what you're doing
    """
    try:
        return Index.get_value(self, series, key)
    except KeyError:
        try:
            loc = self._get_string_slice(key)
            return series[loc]
        except (TypeError, ValueError, KeyError):
            pass

        if isinstance(key, time):
            locs = self.indexer_at_time(key)
            return series.take(locs)

        if isinstance(key, basestring):
            stamp = Timestamp(key, tz=self.tz)
        else:
            stamp = Timestamp(key)
        try:
            return self._engine.get_value(series, stamp)
        except KeyError:
            raise KeyError(stamp)
# Buggy code
def date_range(start=None, end=None, periods=None, freq="D", tz=None, normalize=False):
    """
    Return a fixed frequency datetime index, with day (calendar) as the default
    frequency

    Parameters
    ----------
    start : string or datetime-like, default None
        Left bound for generating dates
    end : string or datetime-like, default None
        Right bound for generating dates
    periods : integer or None, default None
        If None, must specify start and end
    freq : string or DateOffset, default 'D' (calendar daily)
        Frequency strings can have multiples, e.g. '5H'
    tz : string or None
        Time zone name for returning localized DatetimeIndex, for example
        Asia/Beijing
    normalize : bool, default False
        Normalize start/end dates to midnight before generating date range

    Notes
    -----
    2 of start, end, or periods must be specified

    Returns
    -------
    rng : DatetimeIndex
    """
    return DatetimeIndex(
        start=start, end=end, periods=periods, freq=freq, tz=tz, normalize=normalize
    )


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def date_range(
    start=None, end=None, periods=None, freq="D", tz=None, normalize=False, name=None
):
    """
    Return a fixed frequency datetime index, with day (calendar) as the default
    frequency

    Parameters
    ----------
    start : string or datetime-like, default None
        Left bound for generating dates
    end : string or datetime-like, default None
        Right bound for generating dates
    periods : integer or None, default None
        If None, must specify start and end
    freq : string or DateOffset, default 'D' (calendar daily)
        Frequency strings can have multiples, e.g. '5H'
    tz : string or None
        Time zone name for returning localized DatetimeIndex, for example
        Asia/Beijing
    normalize : bool, default False
        Normalize start/end dates to midnight before generating date range
    name : str, default None
        Name of the resulting index

    Notes
    -----
    2 of start, end, or periods must be specified

    Returns
    -------
    rng : DatetimeIndex
    """
    return DatetimeIndex(
        start=start,
        end=end,
        periods=periods,
        freq=freq,
        tz=tz,
        normalize=normalize,
        name=name,
    )
# Buggy code
def bdate_range(start=None, end=None, periods=None, freq="B", tz=None, normalize=True):
    """
    Return a fixed frequency datetime index, with business day as the default
    frequency

    Parameters
    ----------
    start : string or datetime-like, default None
        Left bound for generating dates
    end : string or datetime-like, default None
        Right bound for generating dates
    periods : integer or None, default None
        If None, must specify start and end
    freq : string or DateOffset, default 'B' (business daily)
        Frequency strings can have multiples, e.g. '5H'
    tz : string or None
        Time zone name for returning localized DatetimeIndex, for example
        Asia/Beijing
    normalize : bool, default False
        Normalize start/end dates to midnight before generating date range

    Notes
    -----
    2 of start, end, or periods must be specified

    Returns
    -------
    rng : DatetimeIndex
    """

    return DatetimeIndex(
        start=start, end=end, periods=periods, freq=freq, tz=tz, normalize=normalize
    )


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def bdate_range(
    start=None, end=None, periods=None, freq="B", tz=None, normalize=True, name=None
):
    """
    Return a fixed frequency datetime index, with business day as the default
    frequency

    Parameters
    ----------
    start : string or datetime-like, default None
        Left bound for generating dates
    end : string or datetime-like, default None
        Right bound for generating dates
    periods : integer or None, default None
        If None, must specify start and end
    freq : string or DateOffset, default 'B' (business daily)
        Frequency strings can have multiples, e.g. '5H'
    tz : string or None
        Time zone name for returning localized DatetimeIndex, for example
        Asia/Beijing
    normalize : bool, default False
        Normalize start/end dates to midnight before generating date range
    name : str, default None
        Name for the resulting index

    Notes
    -----
    2 of start, end, or periods must be specified

    Returns
    -------
    rng : DatetimeIndex
    """

    return DatetimeIndex(
        start=start,
        end=end,
        periods=periods,
        freq=freq,
        tz=tz,
        normalize=normalize,
        name=name,
    )
# Buggy code
def apply(self, other):
    n = self.n

    wkday, _ = lib.monthrange(other.year, other.month)
    first = _get_firstbday(wkday)

    if other.day > first and n <= 0:
        # as if rolled forward already
        n += 1

    other = other + relativedelta(months=n)
    wkday, _ = lib.monthrange(other.year, other.month)
    first = _get_firstbday(wkday)
    result = datetime(other.year, other.month, first)
    return result


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def apply(self, other):
    n = self.n

    wkday, _ = lib.monthrange(other.year, other.month)
    first = _get_firstbday(wkday)

    if other.day > first and n <= 0:
        # as if rolled forward already
        n += 1
    elif other.day < first and n > 0:
        other = other + timedelta(days=first - other.day)
        n -= 1

    other = other + relativedelta(months=n)
    wkday, _ = lib.monthrange(other.year, other.month)
    first = _get_firstbday(wkday)
    result = datetime(other.year, other.month, first)
    return result
# Buggy code
def period_range(start=None, end=None, periods=None, freq="D"):
    """
    Return a fixed frequency datetime index, with day (calendar) as the default
    frequency


    Parameters
    ----------
    start :
    end :
    normalize : bool, default False
        Normalize start/end dates to midnight before generating date range

    Returns
    -------

    """
    return PeriodIndex(start=start, end=end, periods=periods, freq=freq)


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def period_range(start=None, end=None, periods=None, freq="D", name=None):
    """
    Return a fixed frequency datetime index, with day (calendar) as the default
    frequency


    Parameters
    ----------
    start :
    end :
    periods : int, default None
        Number of periods in the index
    freq : str/DateOffset, default 'D'
        Frequency alias
    name : str, default None
        Name for the resulting PeriodIndex

    Returns
    -------
    prng : PeriodIndex
    """
    return PeriodIndex(start=start, end=end, periods=periods, freq=freq, name=name)
# Buggy code
def initialize_options(self):
    self.all = True
    self._clean_me = []
    self._clean_trees = []
    self._clean_exclude = ["np_datetime.c", "np_datetime_strings.c", "period.c"]

    for root, dirs, files in list(os.walk("pandas")):
        for f in files:
            if f in self._clean_exclude:
                continue
            if os.path.splitext(f)[-1] in (".pyc", ".so", ".o", ".pyd", ".c"):
                self._clean_me.append(pjoin(root, f))
        for d in dirs:
            if d == "__pycache__":
                self._clean_trees.append(pjoin(root, d))

    for d in ("build",):
        if os.path.exists(d):
            self._clean_trees.append(d)


# Traceback (IndexError)
In [1]: from pandas import *

In [2]: a = DataFrame(columns=['column1'], data=[1])

In [3]: b = DataFrame(columns=['column1'])

In [4]: a.merge(b, on=['column1'], how='left')


IndexError                                Traceback (most recent call last)
IndexError: index out of range for array

# Fixed code
def initialize_options(self):
    self.all = True
    self._clean_me = []
    self._clean_trees = []
    self._clean_exclude = ["np_datetime.c", "np_datetime_strings.c", "period.c"]

    for root, dirs, files in list(os.walk("pandas")):
        for f in files:
            if f in self._clean_exclude:
                continue
            if os.path.splitext(f)[-1] in (".pyc", ".so", ".o", ".pyd", ".c", ".orig"):
                self._clean_me.append(pjoin(root, f))
        for d in dirs:
            if d == "__pycache__":
                self._clean_trees.append(pjoin(root, d))

    for d in ("build",):
        if os.path.exists(d):
            self._clean_trees.append(d)
# Buggy code
def _dt_index_cmp(opname):
    """
    Wrap comparison operations to convert datetime-like to datetime64
    """

    def wrapper(self, other):
        if isinstance(other, datetime):
            func = getattr(self, opname)
            result = func(_to_m8(other))
        elif isinstance(other, np.ndarray):
            func = getattr(super(DatetimeIndex, self), opname)
            result = func(other)
        else:
            other = _ensure_datetime64(other)
            func = getattr(super(DatetimeIndex, self), opname)
            result = func(other)
        try:
            return result.view(np.ndarray)
        except:
            return result

    return wrapper


# Traceback (ValueError)
from pandas import *
import numpy as np
periods = 1000
ind = DatetimeIndex(start='2012/1/1', freq='5min', periods=periods)
df = DataFrame({'high': np.arange(periods), 'low': np.arange(periods)}, index=ind)

grouped = df.groupby(lambda x: datetime(x.year, x.month, x.day))



In [9]: grouped.groups

ValueError                                Traceback (most recent call last)
<ipython-input-9-aec229cf123a> in <module>()
----> 1 grouped.groups

~/pandas/pandas/core/groupby.pyc in groups(self)
150     @property
151     def groups(self):
--> 152         return self.grouper.groups
153
154     @property

~/pandas/pandas/core/index.pyc in groupby(self, to_groupby)
740
741     def groupby(self, to_groupby):
--> 742         return self._groupby(self.values, to_groupby)
743
744     def map(self, mapper):

...
...
...

~/pandas/pandas/lib.so in pandas.lib.groupby_arrays (pandas/src/tseries.c:67246)()

ValueError: Buffer dtype mismatch, expected 'int64_t' but got Python object

# Fixed code
def _dt_index_cmp(opname):
    """
    Wrap comparison operations to convert datetime-like to datetime64
    """

    def wrapper(self, other):
        func = getattr(super(DatetimeIndex, self), opname)
        if isinstance(other, datetime):
            func = getattr(self, opname)
            other = _to_m8(other)
        elif isinstance(other, list):
            other = DatetimeIndex(other)
        elif not isinstance(other, np.ndarray):
            other = _ensure_datetime64(other)
        result = func(other)

        try:
            return result.view(np.ndarray)
        except:
            return result

    return wrapper
# Buggy code
def wrapper(self, other):
    if isinstance(other, datetime):
        func = getattr(self, opname)
        result = func(_to_m8(other))
    elif isinstance(other, np.ndarray):
        func = getattr(super(DatetimeIndex, self), opname)
        result = func(other)
    else:
        other = _ensure_datetime64(other)
        func = getattr(super(DatetimeIndex, self), opname)
        result = func(other)
    try:
        return result.view(np.ndarray)
    except:
        return result


# Traceback (ValueError)
from pandas import *
import numpy as np
periods = 1000
ind = DatetimeIndex(start='2012/1/1', freq='5min', periods=periods)
df = DataFrame({'high': np.arange(periods), 'low': np.arange(periods)}, index=ind)

grouped = df.groupby(lambda x: datetime(x.year, x.month, x.day))



In [9]: grouped.groups

ValueError                                Traceback (most recent call last)
<ipython-input-9-aec229cf123a> in <module>()
----> 1 grouped.groups

~/pandas/pandas/core/groupby.pyc in groups(self)
150     @property
151     def groups(self):
--> 152         return self.grouper.groups
153
154     @property

~/pandas/pandas/core/index.pyc in groupby(self, to_groupby)
740
741     def groupby(self, to_groupby):
--> 742         return self._groupby(self.values, to_groupby)
743
744     def map(self, mapper):

...
...
...

~/pandas/pandas/lib.so in pandas.lib.groupby_arrays (pandas/src/tseries.c:67246)()

ValueError: Buffer dtype mismatch, expected 'int64_t' but got Python object

# Fixed code
def wrapper(self, other):
    func = getattr(super(DatetimeIndex, self), opname)
    if isinstance(other, datetime):
        func = getattr(self, opname)
        other = _to_m8(other)
    elif isinstance(other, list):
        other = DatetimeIndex(other)
    elif not isinstance(other, np.ndarray):
        other = _ensure_datetime64(other)
    result = func(other)

    try:
        return result.view(np.ndarray)
    except:
        return result
# Buggy code
def get_loc(self, key):
    """y
    Get integer location for requested label

    Returns
    -------
    loc : int
    """
    try:
        return self._engine.get_loc(key)
    except KeyError:
        try:
            return self._get_string_slice(key)
        except (TypeError, KeyError):
            pass

        if isinstance(key, time):
            return self._indices_at_time(key)

        stamp = Timestamp(key)
        try:
            return self._engine.get_loc(stamp)
        except KeyError:
            raise KeyError(stamp)


# Traceback (ValueError)
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>()
----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m')

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize)
1209     """
1210     return DatetimeIndex(start=start, end=end, periods=periods,
-> 1211                          freq=freq, tz=tz, normalize=normalize)
1212
1213

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds)
202
203         if data is None and offset is None:
--> 204             raise ValueError("Must provide freq argument if no data is "
205                              "supplied")
206

ValueError: Must provide freq argument if no data is supplied

# Fixed code
def get_loc(self, key):
    """
    Get integer location for requested label

    Returns
    -------
    loc : int
    """
    try:
        return self._engine.get_loc(key)
    except KeyError:
        try:
            return self._get_string_slice(key)
        except (TypeError, KeyError):
            pass

        if isinstance(key, time):
            return self._indices_at_time(key)

        stamp = Timestamp(key)
        try:
            return self._engine.get_loc(stamp)
        except KeyError:
            raise KeyError(stamp)
# Buggy code
def match(values, index):
    """


    Parameters
    ----------

    Returns
    -------
    match : ndarray
    """
    if com.is_float_dtype(index):
        return _match_generic(values, index, lib.Float64HashTable, com._ensure_float64)
    elif com.is_integer_dtype(index):
        return _match_generic(values, index, lib.Int64HashTable, com._ensure_int64)
    else:
        return _match_generic(values, index, lib.PyObjectHashTable, com._ensure_object)


# Traceback (ValueError)
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>()
----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m')

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize)
1209     """
1210     return DatetimeIndex(start=start, end=end, periods=periods,
-> 1211                          freq=freq, tz=tz, normalize=normalize)
1212
1213

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds)
202
203         if data is None and offset is None:
--> 204             raise ValueError("Must provide freq argument if no data is "
205                              "supplied")
206

ValueError: Must provide freq argument if no data is supplied

# Fixed code
def match(to_match, values, na_sentinel=-1):
    """
    Compute locations of to_match into values

    Parameters
    ----------
    to_match : array-like
        values to find positions of
    values : array-like
        Unique set of values
    na_sentinel : int, default -1
        Value to mark "not found"

    Examples
    --------

    Returns
    -------
    match : ndarray of integers
    """
    values = np.asarray(values)
    if issubclass(values.dtype.type, basestring):
        values = np.array(values, dtype="O")

    f = lambda htype, caster: _match_generic(to_match, values, htype, caster)
    return _hashtable_algo(f, values.dtype)
# Buggy code
def unique(values):
    """ """
    pass


# Traceback (ValueError)
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>()
----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m')

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize)
1209     """
1210     return DatetimeIndex(start=start, end=end, periods=periods,
-> 1211                          freq=freq, tz=tz, normalize=normalize)
1212
1213

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds)
202
203         if data is None and offset is None:
--> 204             raise ValueError("Must provide freq argument if no data is "
205                              "supplied")
206

ValueError: Must provide freq argument if no data is supplied

# Fixed code
def unique(values):
    """
    Compute unique values (not necessarily sorted) efficiently from input array
    of values

    Parameters
    ----------
    values : array-like

    Returns
    -------
    uniques
    """
    f = lambda htype, caster: _unique_generic(values, htype, caster)
    return _hashtable_algo(f, values.dtype)
# Buggy code
def count(values, uniques=None):
    if uniques is not None:
        raise NotImplementedError
    else:
        if com.is_float_dtype(values):
            return _count_generic(values, lib.Float64HashTable, com._ensure_float64)
        elif com.is_integer_dtype(values):
            return _count_generic(values, lib.Int64HashTable, com._ensure_int64)
        else:
            return _count_generic(values, lib.PyObjectHashTable, com._ensure_object)


# Traceback (ValueError)
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>()
----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m')

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize)
1209     """
1210     return DatetimeIndex(start=start, end=end, periods=periods,
-> 1211                          freq=freq, tz=tz, normalize=normalize)
1212
1213

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds)
202
203         if data is None and offset is None:
--> 204             raise ValueError("Must provide freq argument if no data is "
205                              "supplied")
206

ValueError: Must provide freq argument if no data is supplied

# Fixed code
def count(values, uniques=None):
    f = lambda htype, caster: _count_generic(values, htype, caster)

    if uniques is not None:
        raise NotImplementedError
    else:
        return _hashtable_algo(f, values.dtype)
# Buggy code
def _count_generic(values, table_type, type_caster):
    values = type_caster(values)
    table = table_type(len(values))
    uniques, labels, counts = table.factorize(values)

    return Series(counts, index=uniques)


# Traceback (ValueError)
In [17]: date_range(datetime.datetime.today(), periods=10, freq='2h20m')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/home/chang/Dropbox/git/pandas/<ipython-input-17-ff4e03382573> in <module>()
----> 1 date_range(datetime.datetime.today(), periods=10, freq='2h20m')

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in date_range(start, end, periods, freq, tz, normalize)
1209     """
1210     return DatetimeIndex(start=start, end=end, periods=periods,
-> 1211                          freq=freq, tz=tz, normalize=normalize)
1212
1213

/home/chang/Dropbox/git/pandas/pandas/tseries/index.pyc in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, **kwds)
202
203         if data is None and offset is None:
--> 204             raise ValueError("Must provide freq argument if no data is "
205                              "supplied")
206

ValueError: Must provide freq argument if no data is supplied

# Fixed code
def _count_generic(values, table_type, type_caster):
    from pandas.core.series import Series

    values = type_caster(values)
    table = table_type(len(values))
    uniques, labels, counts = table.factorize(values)

    return Series(counts, index=uniques)