gurudesh/pytracebugs huggingface dataset:
# Buggy code
def highlight_null(self, null_color="red"):
    """
    Shade the background ``null_color`` for missing values.

    .. versionadded:: 0.17.1

    Parameters
    ----------
    null_color: str

    Returns
    -------
    self
    """
    self.applymap(self._highlight_null, null_color=null_color)
    return self


# Traceback (KeyError)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.5/site-packages/IPython/core/formatters.py in __call__(self, obj)
339             method = _safe_get_formatter_method(obj, self.print_method)
340             if method is not None:
--> 341                 return method()
342             return None
343         else:

/usr/local/lib/python3.5/site-packages/pandas/core/style.py in _repr_html_(self)
158         Hooks into Jupyter notebook rich display system.
159         '''
--> 160         return self.render()
161
162     def _translate(self):

/usr/local/lib/python3.5/site-packages/pandas/core/style.py in render(self)
259         """
260         self._compute()
--> 261         d = self._translate()
262         # filter out empty styles, every cell will have a class
263         # but the list of props may just be [['', '']].

/usr/local/lib/python3.5/site-packages/pandas/core/style.py in _translate(self)
220                 cs = [DATA_CLASS, "row%s" % r, "col%s" % c]
221                 cs.extend(cell_context.get("data", {}).get(r, {}).get(c, []))
--> 222                 row_es.append({"type": "td", "value": self.data.iloc[r][c],
223                                "class": " ".join(cs), "id": "_".join(cs[1:])})
224                 props = []

/usr/local/lib/python3.5/site-packages/pandas/core/series.py in __getitem__(self, key)
555     def __getitem__(self, key):
556         try:
--> 557             result = self.index.get_value(self, key)
558
559             if not np.isscalar(result):

/usr/local/lib/python3.5/site-packages/pandas/core/index.py in get_value(self, series, key)
1788
1789         try:
-> 1790             return self._engine.get_value(s, k)
1791         except KeyError as e1:
1792             if len(self) > 0 and self.inferred_type in ['integer','boolean']:

pandas/index.pyx in pandas.index.IndexEngine.get_value (pandas/index.c:3204)()

pandas/index.pyx in pandas.index.IndexEngine.get_value (pandas/index.c:2903)()

pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:3843)()

pandas/hashtable.pyx in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:6525)()

pandas/hashtable.pyx in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:6463)()

KeyError: 0

# Fixed code
def highlight_null(self, null_color="red"):
    """
    Shade the background ``null_color`` for missing values.

    .. versionadded:: 0.17.1

    Parameters
    ----------
    null_color: str

    Returns
    -------
    self : Styler
    """
    self.applymap(self._highlight_null, null_color=null_color)
    return self
# Buggy code
def sort_values(self, return_indexer=False, ascending=True):
    """
    Return sorted copy of Index
    """
    if return_indexer:
        _as = self.argsort()
        if not ascending:
            _as = _as[::-1]
        sorted_index = self.take(_as)
        return sorted_index, _as
    else:
        sorted_values = np.sort(self.values)
        attribs = self._get_attributes_dict()
        freq = attribs["freq"]
        from pandas.tseries.period import PeriodIndex

        if freq is not None and not isinstance(self, PeriodIndex):
            if freq.n > 0 and not ascending:
                freq = freq * -1
            elif freq.n < 0 and ascending:
                freq = freq * -1
        attribs["freq"] = freq

        if not ascending:
            sorted_values = sorted_values[::-1]

        return self._simple_new(sorted_values, **attribs)


# Traceback (TypeError)
In [1]: import pandas as pd

In [2]: pd.Timestamp(None, tz='utc') - pd.Timestamp('now', tz='utc')
Traceback (most recent call last):

File "<ipython-input-2-5e0738cec5fa>", line 1, in <module>
pd.Timestamp(None, tz='utc') - pd.Timestamp('now', tz='utc')

File "pandas\tslib.pyx", line 1099, in pandas.tslib._NaT.__sub__ (pandas\tslib.c:21618)

File "pandas\tslib.pyx", line 1026, in pandas.tslib._Timestamp.__sub__ (pandas\tslib.c:20036)

TypeError: Timestamp subtraction must have the same timezones or no timezones

# Fixed code
def sort_values(self, return_indexer=False, ascending=True):
    """
    Return sorted copy of Index
    """
    if return_indexer:
        _as = self.argsort()
        if not ascending:
            _as = _as[::-1]
        sorted_index = self.take(_as)
        return sorted_index, _as
    else:
        sorted_values = np.sort(self.values)
        attribs = self._get_attributes_dict()
        freq = attribs["freq"]

        if freq is not None and not isinstance(self, com.ABCPeriodIndex):
            if freq.n > 0 and not ascending:
                freq = freq * -1
            elif freq.n < 0 and ascending:
                freq = freq * -1
        attribs["freq"] = freq

        if not ascending:
            sorted_values = sorted_values[::-1]

        return self._simple_new(sorted_values, **attribs)
# Buggy code
def _sub_datelike(self, other):
    # subtract a datetime from myself, yielding a TimedeltaIndex

    from pandas import TimedeltaIndex

    other = Timestamp(other)

    # require tz compat
    if not self._has_same_tz(other):
        raise TypeError(
            "Timestamp subtraction must have the same timezones or no timezones"
        )

    i8 = self.asi8
    result = i8 - other.value
    result = self._maybe_mask_results(result, fill_value=tslib.iNaT)
    return TimedeltaIndex(result, name=self.name, copy=False)


# Traceback (TypeError)
In [1]: import pandas as pd

In [2]: pd.Timestamp(None, tz='utc') - pd.Timestamp('now', tz='utc')
Traceback (most recent call last):

File "<ipython-input-2-5e0738cec5fa>", line 1, in <module>
pd.Timestamp(None, tz='utc') - pd.Timestamp('now', tz='utc')

File "pandas\tslib.pyx", line 1099, in pandas.tslib._NaT.__sub__ (pandas\tslib.c:21618)

File "pandas\tslib.pyx", line 1026, in pandas.tslib._Timestamp.__sub__ (pandas\tslib.c:20036)

TypeError: Timestamp subtraction must have the same timezones or no timezones

# Fixed code
def _sub_datelike(self, other):
    # subtract a datetime from myself, yielding a TimedeltaIndex
    from pandas import TimedeltaIndex

    other = Timestamp(other)
    if other is tslib.NaT:
        result = self._nat_new(box=False)
    # require tz compat
    elif not self._has_same_tz(other):
        raise TypeError(
            "Timestamp subtraction must have the same timezones or no timezones"
        )
    else:
        i8 = self.asi8
        result = i8 - other.value
        result = self._maybe_mask_results(result, fill_value=tslib.iNaT)
    return TimedeltaIndex(result, name=self.name, copy=False)
# Buggy code
def _add_datelike(self, other):
    # adding a timedeltaindex to a datetimelike
    from pandas import Timestamp, DatetimeIndex

    other = Timestamp(other)
    i8 = self.asi8
    result = i8 + other.value
    result = self._maybe_mask_results(result, fill_value=tslib.iNaT)
    return DatetimeIndex(result, name=self.name, copy=False)


# Traceback (TypeError)
In [1]: import pandas as pd

In [2]: pd.Timestamp(None, tz='utc') - pd.Timestamp('now', tz='utc')
Traceback (most recent call last):

File "<ipython-input-2-5e0738cec5fa>", line 1, in <module>
pd.Timestamp(None, tz='utc') - pd.Timestamp('now', tz='utc')

File "pandas\tslib.pyx", line 1099, in pandas.tslib._NaT.__sub__ (pandas\tslib.c:21618)

File "pandas\tslib.pyx", line 1026, in pandas.tslib._Timestamp.__sub__ (pandas\tslib.c:20036)

TypeError: Timestamp subtraction must have the same timezones or no timezones

# Fixed code
def _add_datelike(self, other):
    # adding a timedeltaindex to a datetimelike
    from pandas import Timestamp, DatetimeIndex

    if other is tslib.NaT:
        result = self._nat_new(box=False)
    else:
        other = Timestamp(other)
        i8 = self.asi8
        result = i8 + other.value
        result = self._maybe_mask_results(result, fill_value=tslib.iNaT)
    return DatetimeIndex(result, name=self.name, copy=False)
# Buggy code
def _sub_datelike(self, other):
    raise TypeError("cannot subtract a datelike from a TimedeltaIndex")


# Traceback (TypeError)
In [1]: import pandas as pd

In [2]: pd.Timestamp(None, tz='utc') - pd.Timestamp('now', tz='utc')
Traceback (most recent call last):

File "<ipython-input-2-5e0738cec5fa>", line 1, in <module>
pd.Timestamp(None, tz='utc') - pd.Timestamp('now', tz='utc')

File "pandas\tslib.pyx", line 1099, in pandas.tslib._NaT.__sub__ (pandas\tslib.c:21618)

File "pandas\tslib.pyx", line 1026, in pandas.tslib._Timestamp.__sub__ (pandas\tslib.c:20036)

TypeError: Timestamp subtraction must have the same timezones or no timezones

# Fixed code
def _sub_datelike(self, other):
    from pandas import DatetimeIndex

    if other is tslib.NaT:
        result = self._nat_new(box=False)
    else:
        raise TypeError("cannot subtract a datelike from a TimedeltaIndex")
    return DatetimeIndex(result, name=self.name, copy=False)
# Buggy code
def setup(self):
    self.N = 100000
    self.rng = date_range(start="1/1/2000", periods=self.N, freq="T")
    if hasattr(Series, "convert"):
        Series.resample = Series.convert
    self.ts = Series(np.random.randn(self.N), index=self.rng)
    self.rng = date_range(start="1/1/2000", periods=20000, freq="H")
    self.strings = [x.strftime("%Y-%m-%d %H:%M:%S") for x in self.rng]


# Traceback (ValueError)
import pandas
pandas.__version__
u'0.17.1'
pandas.to_datetime('2005-1-13', format='%Y-%m-%d')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/dpinte/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pandas/util/decorators.py", line 89, in wrapper
return func(*args, **kwargs)
File "/Users/dpinte/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pandas/tseries/tools.py", line 276, in to_datetime
unit=unit, infer_datetime_format=infer_datetime_format)
File "/Users/dpinte/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pandas/tseries/tools.py", line 397, in _to_datetime
return _convert_listlike(np.array([ arg ]), box, format)[0]
File "/Users/dpinte/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pandas/tseries/tools.py", line 383, in _convert_listlike
raise e
ValueError: time data '2005-1-13' does match format specified

# Fixed code
def setup(self):
    self.rng = date_range(start="1/1/2000", periods=20000, freq="H")
    self.strings = [x.strftime("%Y-%m-%d %H:%M:%S") for x in self.rng]
    self.strings_nosep = [x.strftime("%Y%m%d %H:%M:%S") for x in self.rng]
    self.strings_tz_space = [
        x.strftime("%Y-%m-%d %H:%M:%S") + " -0800" for x in self.rng
    ]
# Buggy code
def _get_setitem_indexer(self, key):
    if self.axis is not None:
        return self._convert_tuple(key, is_setter=True)

    axis = self.obj._get_axis(0)
    if isinstance(axis, MultiIndex):
        try:
            return axis.get_loc(key)
        except Exception:
            pass

    if isinstance(key, tuple) and not self.ndim < len(key):
        return self._convert_tuple(key, is_setter=True)

    try:
        return self._convert_to_indexer(key, is_setter=True)
    except TypeError:
        raise IndexingError(key)


# Traceback (ValueError)
series length = 5
series length = 999999
series length = 1000000
Traceback (most recent call last):
File "<stdin>", line 9, in <module>
File "/home/nekobon/.env_exp/lib/python3.4/site-packages/pandas/core/indexing.py", line 114, in __setitem__
indexer = self._get_setitem_indexer(key)
File "/home/nekobon/.env_exp/lib/python3.4/site-packages/pandas/core/indexing.py", line 109, in _get_setitem_indexer
return self._convert_to_indexer(key, is_setter=True)
File "/home/nekobon/.env_exp/lib/python3.4/site-packages/pandas/core/indexing.py", line 1042, in _convert_to_indexer
return labels.get_loc(obj)
File "/home/nekobon/.env_exp/lib/python3.4/site-packages/pandas/core/index.py", line 1692, in get_loc
return self._engine.get_loc(_values_from_object(key))
File "pandas/index.pyx", line 137, in pandas.index.IndexEngine.get_loc (pandas/index.c:3979)
File "pandas/index.pyx", line 145, in pandas.index.IndexEngine.get_loc (pandas/index.c:3680)
File "pandas/index.pyx", line 464, in pandas.index._bin_search (pandas/index.c:9124)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

# Fixed code
def _get_setitem_indexer(self, key):
    if self.axis is not None:
        return self._convert_tuple(key, is_setter=True)

    axis = self.obj._get_axis(0)
    if isinstance(axis, MultiIndex):
        try:
            return axis.get_loc(key)
        except Exception:
            pass

    if isinstance(key, tuple) and not self.ndim < len(key):
        return self._convert_tuple(key, is_setter=True)
    if isinstance(key, range):
        return self._convert_range(key, is_setter=True)

    try:
        return self._convert_to_indexer(key, is_setter=True)
    except TypeError:
        raise IndexingError(key)
# Buggy code
def size(self):
    """
    Compute group sizes

    """
    ids, _, ngroup = self.group_info
    out = np.bincount(ids[ids != -1], minlength=ngroup)
    return Series(out, index=self.result_index)


# Traceback (TypeError)
In [1]: df = pd.DataFrame({"id":[1,2,3,4,5,6], "grade":['a', 'b', 'b', 'a', 'a', 'e']})

In [2]: df.groupby("grade").size()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-d8e387418f9d> in <module>()
----> 1 df.groupby("grade").size()

/home/joris/scipy/pandas/pandas/core/groupby.pyc in size(self)
818
819         """
--> 820         return self.grouper.size()
821
822     sum = _groupby_function('sum', 'add', np.sum)

/home/joris/scipy/pandas/pandas/core/groupby.pyc in size(self)
1380         """
1381         ids, _, ngroup = self.group_info
-> 1382         out = np.bincount(ids[ids != -1], minlength=ngroup)
1383         return Series(out, index=self.result_index)
1384

TypeError: Cannot cast array data from dtype('int64') to dtype('int32') according to the rule 'safe'

In [4]: pd.__version__
Out[4]: '0.17.0rc1+108.g3fb802a'

# Fixed code
def size(self):
    """
    Compute group sizes

    """
    ids, _, ngroup = self.group_info
    ids = com._ensure_platform_int(ids)
    out = np.bincount(ids[ids != -1], minlength=ngroup)
    return Series(out, index=self.result_index, dtype="int64")
# Buggy code
def group_info(self):
    ngroups = self.ngroups
    obs_group_ids = np.arange(ngroups, dtype="int64")
    rep = np.diff(np.r_[0, self.bins])

    if ngroups == len(self.bins):
        comp_ids = np.repeat(np.arange(ngroups, dtype="int64"), rep)
    else:
        comp_ids = np.repeat(np.r_[-1, np.arange(ngroups, dtype="int64")], rep)

    return comp_ids, obs_group_ids, ngroups


# Traceback (TypeError)
In [1]: df = pd.DataFrame({"id":[1,2,3,4,5,6], "grade":['a', 'b', 'b', 'a', 'a', 'e']})

In [2]: df.groupby("grade").size()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-d8e387418f9d> in <module>()
----> 1 df.groupby("grade").size()

/home/joris/scipy/pandas/pandas/core/groupby.pyc in size(self)
818
819         """
--> 820         return self.grouper.size()
821
822     sum = _groupby_function('sum', 'add', np.sum)

/home/joris/scipy/pandas/pandas/core/groupby.pyc in size(self)
1380         """
1381         ids, _, ngroup = self.group_info
-> 1382         out = np.bincount(ids[ids != -1], minlength=ngroup)
1383         return Series(out, index=self.result_index)
1384

TypeError: Cannot cast array data from dtype('int64') to dtype('int32') according to the rule 'safe'

In [4]: pd.__version__
Out[4]: '0.17.0rc1+108.g3fb802a'

# Fixed code
def group_info(self):
    ngroups = self.ngroups
    obs_group_ids = np.arange(ngroups)
    rep = np.diff(np.r_[0, self.bins])

    rep = com._ensure_platform_int(rep)
    if ngroups == len(self.bins):
        comp_ids = np.repeat(np.arange(ngroups), rep)
    else:
        comp_ids = np.repeat(np.r_[-1, np.arange(ngroups)], rep)

    return (
        comp_ids.astype("int64", copy=False),
        obs_group_ids.astype("int64", copy=False),
        ngroups,
    )
# Buggy code
def count(self):
    """Compute count of group, excluding missing values"""
    ids, _, ngroups = self.grouper.group_info
    val = self.obj.get_values()

    mask = (ids != -1) & ~isnull(val)
    out = np.bincount(ids[mask], minlength=ngroups) if ngroups != 0 else []

    return Series(out, index=self.grouper.result_index, name=self.name)


# Traceback (TypeError)
In [1]: df = pd.DataFrame({"id":[1,2,3,4,5,6], "grade":['a', 'b', 'b', 'a', 'a', 'e']})

In [2]: df.groupby("grade").size()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-d8e387418f9d> in <module>()
----> 1 df.groupby("grade").size()

/home/joris/scipy/pandas/pandas/core/groupby.pyc in size(self)
818
819         """
--> 820         return self.grouper.size()
821
822     sum = _groupby_function('sum', 'add', np.sum)

/home/joris/scipy/pandas/pandas/core/groupby.pyc in size(self)
1380         """
1381         ids, _, ngroup = self.group_info
-> 1382         out = np.bincount(ids[ids != -1], minlength=ngroup)
1383         return Series(out, index=self.result_index)
1384

TypeError: Cannot cast array data from dtype('int64') to dtype('int32') according to the rule 'safe'

In [4]: pd.__version__
Out[4]: '0.17.0rc1+108.g3fb802a'

# Fixed code
def count(self):
    """Compute count of group, excluding missing values"""
    ids, _, ngroups = self.grouper.group_info
    val = self.obj.get_values()

    mask = (ids != -1) & ~isnull(val)
    ids = com._ensure_platform_int(ids)
    out = np.bincount(ids[mask], minlength=ngroups) if ngroups != 0 else []

    return Series(out, index=self.grouper.result_index, name=self.name, dtype="int64")
# Buggy code
def count(self, level=None):
    """
    Return number of non-NA/null observations in the Series

    Parameters
    ----------
    level : int or level name, default None
        If the axis is a MultiIndex (hierarchical), count along a
        particular level, collapsing into a smaller Series

    Returns
    -------
    nobs : int or Series (if level specified)
    """
    from pandas.core.index import _get_na_value

    if level is None:
        return notnull(_values_from_object(self)).sum()

    if isinstance(level, compat.string_types):
        level = self.index._get_level_number(level)

    lev = self.index.levels[level]
    lab = np.array(self.index.labels[level], subok=False, copy=True)

    mask = lab == -1
    if mask.any():
        lab[mask] = cnt = len(lev)
        lev = lev.insert(cnt, _get_na_value(lev.dtype.type))

    out = np.bincount(lab[notnull(self.values)], minlength=len(lev))
    return self._constructor(out, index=lev).__finalize__(self)


# Traceback (TypeError)
In [1]: df = pd.DataFrame({"id":[1,2,3,4,5,6], "grade":['a', 'b', 'b', 'a', 'a', 'e']})

In [2]: df.groupby("grade").size()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-d8e387418f9d> in <module>()
----> 1 df.groupby("grade").size()

/home/joris/scipy/pandas/pandas/core/groupby.pyc in size(self)
818
819         """
--> 820         return self.grouper.size()
821
822     sum = _groupby_function('sum', 'add', np.sum)

/home/joris/scipy/pandas/pandas/core/groupby.pyc in size(self)
1380         """
1381         ids, _, ngroup = self.group_info
-> 1382         out = np.bincount(ids[ids != -1], minlength=ngroup)
1383         return Series(out, index=self.result_index)
1384

TypeError: Cannot cast array data from dtype('int64') to dtype('int32') according to the rule 'safe'

In [4]: pd.__version__
Out[4]: '0.17.0rc1+108.g3fb802a'

# Fixed code
def count(self, level=None):
    """
    Return number of non-NA/null observations in the Series

    Parameters
    ----------
    level : int or level name, default None
        If the axis is a MultiIndex (hierarchical), count along a
        particular level, collapsing into a smaller Series

    Returns
    -------
    nobs : int or Series (if level specified)
    """
    from pandas.core.index import _get_na_value

    if level is None:
        return notnull(_values_from_object(self)).sum()

    if isinstance(level, compat.string_types):
        level = self.index._get_level_number(level)

    lev = self.index.levels[level]
    lab = np.array(self.index.labels[level], subok=False, copy=True)

    mask = lab == -1
    if mask.any():
        lab[mask] = cnt = len(lev)
        lev = lev.insert(cnt, _get_na_value(lev.dtype.type))

    out = np.bincount(lab[notnull(self.values)], minlength=len(lev))
    return self._constructor(out, index=lev, dtype="int64").__finalize__(self)
# Buggy code
def _conv_value(val):
    # Convert numpy types to Python types for the Excel writers.
    if com.is_integer(val):
        val = int(val)
    elif com.is_float(val):
        val = float(val)
    elif com.is_bool(val):
        val = bool(val)
    elif isinstance(val, Period):
        val = "%s" % val

    return val


# Traceback (IndexError)
Traceback (most recent call last):
File "/Users/myourshaw/lab/pypeline/python2/excel_example.py", line 10, in <module>
xl_file.parse('Sheet1')
File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/io/excel.py", line 208, in parse
**kwds)
File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/io/excel.py", line 291, in _parse_excel
data[header] = _trim_excel_header(data[header])
IndexError: list index out of range

# Fixed code
def _conv_value(val):
    # Convert numpy types to Python types for the Excel writers.
    if com.is_integer(val):
        val = int(val)
    elif com.is_float(val):
        val = float(val)
    elif com.is_bool(val):
        val = bool(val)
    elif isinstance(val, Period):
        val = "%s" % val
    elif com.is_list_like(val):
        val = str(val)

    return val
# Buggy code
def __new__(cls, path, engine=None, **kwargs):
    # only switch class if generic(ExcelWriter)
    if cls == ExcelWriter:
        if engine is None:
            ext = os.path.splitext(path)[-1][1:]
            try:
                engine = config.get_option("io.excel.%s.writer" % ext)
            except KeyError:
                error = ValueError("No engine for filetype: '%s'" % ext)
                raise error
        cls = get_writer(engine)

    return object.__new__(cls)


# Traceback (IndexError)
Traceback (most recent call last):
File "/Users/myourshaw/lab/pypeline/python2/excel_example.py", line 10, in <module>
xl_file.parse('Sheet1')
File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/io/excel.py", line 208, in parse
**kwds)
File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/io/excel.py", line 291, in _parse_excel
data[header] = _trim_excel_header(data[header])
IndexError: list index out of range

# Fixed code
def __new__(cls, path, engine=None, **kwargs):
    # only switch class if generic(ExcelWriter)
    if issubclass(cls, ExcelWriter):
        if engine is None:
            if isinstance(path, string_types):
                ext = os.path.splitext(path)[-1][1:]
            else:
                ext = "xlsx"

            try:
                engine = config.get_option("io.excel.%s.writer" % ext)
            except KeyError:
                error = ValueError("No engine for filetype: '%s'" % ext)
                raise error
        cls = get_writer(engine)

    return object.__new__(cls)
# Buggy code
def __init__(
    self, path, engine=None, date_format=None, datetime_format=None, **engine_kwargs
):
    # validate that this engine can handle the extension
    ext = os.path.splitext(path)[-1]
    self.check_extension(ext)

    self.path = path
    self.sheets = {}
    self.cur_sheet = None

    if date_format is None:
        self.date_format = "YYYY-MM-DD"
    else:
        self.date_format = date_format
    if datetime_format is None:
        self.datetime_format = "YYYY-MM-DD HH:MM:SS"
    else:
        self.datetime_format = datetime_format


# Traceback (IndexError)
Traceback (most recent call last):
File "/Users/myourshaw/lab/pypeline/python2/excel_example.py", line 10, in <module>
xl_file.parse('Sheet1')
File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/io/excel.py", line 208, in parse
**kwds)
File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/io/excel.py", line 291, in _parse_excel
data[header] = _trim_excel_header(data[header])
IndexError: list index out of range

# Fixed code
def __init__(
    self, path, engine=None, date_format=None, datetime_format=None, **engine_kwargs
):
    # validate that this engine can handle the extension
    if isinstance(path, string_types):
        ext = os.path.splitext(path)[-1]
    else:
        ext = "xls" if engine == "xlwt" else "xlsx"

    self.check_extension(ext)

    self.path = path
    self.sheets = {}
    self.cur_sheet = None

    if date_format is None:
        self.date_format = "YYYY-MM-DD"
    else:
        self.date_format = date_format
    if datetime_format is None:
        self.datetime_format = "YYYY-MM-DD HH:MM:SS"
    else:
        self.datetime_format = datetime_format
# Buggy code
def __init__(self, path, engine=None, encoding=None, **engine_kwargs):
    # Use the xlwt module as the Excel writer.
    import xlwt

    super(_XlwtWriter, self).__init__(path, **engine_kwargs)

    if encoding is None:
        encoding = "ascii"
    self.book = xlwt.Workbook(encoding=encoding)
    self.fm_datetime = xlwt.easyxf(num_format_str=self.datetime_format)
    self.fm_date = xlwt.easyxf(num_format_str=self.date_format)


# Traceback (IndexError)
Traceback (most recent call last):
File "/Users/myourshaw/lab/pypeline/python2/excel_example.py", line 10, in <module>
xl_file.parse('Sheet1')
File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/io/excel.py", line 208, in parse
**kwds)
File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/io/excel.py", line 291, in _parse_excel
data[header] = _trim_excel_header(data[header])
IndexError: list index out of range

# Fixed code
def __init__(self, path, engine=None, encoding=None, **engine_kwargs):
    # Use the xlwt module as the Excel writer.
    import xlwt

    engine_kwargs["engine"] = engine
    super(_XlwtWriter, self).__init__(path, **engine_kwargs)

    if encoding is None:
        encoding = "ascii"
    self.book = xlwt.Workbook(encoding=encoding)
    self.fm_datetime = xlwt.easyxf(num_format_str=self.datetime_format)
    self.fm_date = xlwt.easyxf(num_format_str=self.date_format)
# Buggy code
def _setitem_frame(self, key, value):
    # support boolean setting with DataFrame input, e.g.
    # df[df > df2] = 0
    if key.values.dtype != np.bool_:
        raise TypeError("Must pass DataFrame with boolean values only")

    self._check_inplace_setting(value)
    self._check_setitem_copy()
    self.where(-key, value, inplace=True)


# Traceback (ValueError)
import pandas as pd
df = pd.DataFrame()
df[df>0]
Traceback (most recent call last):

File "<ipython-input-3-efe84c9ebabc>", line 1, in <module>
df[df>0]

File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 1787, in __getitem__
return self._getitem_frame(key)

File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 1859, in _getitem_frame
raise ValueError('Must pass DataFrame with boolean values only')

ValueError: Must pass DataFrame with boolean values only

# Fixed code
def _setitem_frame(self, key, value):
    # support boolean setting with DataFrame input, e.g.
    # df[df > df2] = 0
    if key.values.size and not com.is_bool_dtype(key.values):
        raise TypeError("Must pass DataFrame with boolean values only")

    self._check_inplace_setting(value)
    self._check_setitem_copy()
    self.where(-key, value, inplace=True)
# Buggy code
def get(self, key, default=None):
    """
    Get item from object for given key (DataFrame column, Panel slice,
    etc.). Returns default value if not found

    Parameters
    ----------
    key : object

    Returns
    -------
    value : type of items contained in object
    """
    try:
        return self[key]
    except (KeyError, ValueError):
        return default


# Traceback (IndexError)
s = pd.Series([1,2,3], index=["a","b","c"])
s
a    1
b    2
c    3
dtype: int64
s.get("d", 0)
0
s.get(10, 0)
Traceback (most recent call last):
File "<ipython-input-18-26d73ac73179>", line 1, in <module>
s.get(10, 0)
File "/usr/local/lib/python2.7/dist-packages/pandas-0.14.0_421_g20dfc6b-py2.7-linux-x86_64.egg/pandas/core/generic.py", line 1040, in get
return self[key]
File "/usr/local/lib/python2.7/dist-packages/pandas-0.14.0_421_g20dfc6b-py2.7-linux-x86_64.egg/pandas/core/series.py", line 484, in __getitem__
result = self.index.get_value(self, key)
File "/usr/local/lib/python2.7/dist-packages/pandas-0.14.0_421_g20dfc6b-py2.7-linux-x86_64.egg/pandas/core/index.py", line 1202, in get_value
return tslib.get_value_box(s, key)
File "tslib.pyx", line 540, in pandas.tslib.get_value_box (pandas/tslib.c:11831)
File "tslib.pyx", line 555, in pandas.tslib.get_value_box (pandas/tslib.c:11678)
IndexError: index out of bounds

# Fixed code
def get(self, key, default=None):
    """
    Get item from object for given key (DataFrame column, Panel slice,
    etc.). Returns default value if not found

    Parameters
    ----------
    key : object

    Returns
    -------
    value : type of items contained in object
    """
    try:
        return self[key]
    except (KeyError, ValueError, IndexError):
        return default
# Buggy code
def _write_data_nodates(self):
    data = self.datarows
    byteorder = self._byteorder
    TYPE_MAP = self.TYPE_MAP
    typlist = self.typlist
    for row in data:
        # row = row.squeeze().tolist() # needed for structured arrays
        for i, var in enumerate(row):
            typ = ord(typlist[i])
            if typ <= 244:  # we've got a string
                if var is None or var == np.nan:
                    var = _pad_bytes("", typ)
                if len(var) < typ:
                    var = _pad_bytes(var, typ)
                self._write(var)
            else:
                try:
                    self._file.write(struct.pack(byteorder + TYPE_MAP[typ], var))
                except struct.error:
                    # have to be strict about type pack won't do any
                    # kind of casting
                    self._file.write(
                        struct.pack(
                            byteorder + TYPE_MAP[typ], self.type_converters[typ](var)
                        )
                    )


# Traceback (UnicodeEncodeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\pandas\io\stata.py", line 1242, in write_file
self._write_data_nodates()
File "C:\Python27\lib\site-packages\pandas\io\stata.py", line 1326, in _write_data_nodates
self._write(var)
File "C:\Python27\lib\site-packages\pandas\io\stata.py", line 1104, in _write
self._file.write(to_write)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 1:ordinal not in range(128)

# Fixed code
def _write_data_nodates(self):
    data = self.datarows
    byteorder = self._byteorder
    TYPE_MAP = self.TYPE_MAP
    typlist = self.typlist
    for row in data:
        # row = row.squeeze().tolist() # needed for structured arrays
        for i, var in enumerate(row):
            typ = ord(typlist[i])
            if typ <= 244:  # we've got a string
                if var is None or var == np.nan:
                    var = _pad_bytes("", typ)
                if len(var) < typ:
                    var = _pad_bytes(var, typ)
                if compat.PY3:
                    self._write(var)
                else:
                    self._write(var.encode(self._encoding))
            else:
                try:
                    self._file.write(struct.pack(byteorder + TYPE_MAP[typ], var))
                except struct.error:
                    # have to be strict about type pack won't do any
                    # kind of casting
                    self._file.write(
                        struct.pack(
                            byteorder + TYPE_MAP[typ], self.type_converters[typ](var)
                        )
                    )
# Buggy code
def _write_data_dates(self):
    convert_dates = self._convert_dates
    data = self.datarows
    byteorder = self._byteorder
    TYPE_MAP = self.TYPE_MAP
    MISSING_VALUES = self.MISSING_VALUES
    typlist = self.typlist
    for row in data:
        # row = row.squeeze().tolist() # needed for structured arrays
        for i, var in enumerate(row):
            typ = ord(typlist[i])
            # NOTE: If anyone finds this terribly slow, there is
            # a vectorized way to convert dates, see genfromdta for going
            # from int to datetime and reverse it. will copy data though
            if i in convert_dates:
                var = _datetime_to_stata_elapsed(var, self.fmtlist[i])
            if typ <= 244:  # we've got a string
                if len(var) < typ:
                    var = _pad_bytes(var, typ)
                self._write(var)
            else:
                self._file.write(struct.pack(byteorder + TYPE_MAP[typ], var))


# Traceback (UnicodeEncodeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\pandas\io\stata.py", line 1242, in write_file
self._write_data_nodates()
File "C:\Python27\lib\site-packages\pandas\io\stata.py", line 1326, in _write_data_nodates
self._write(var)
File "C:\Python27\lib\site-packages\pandas\io\stata.py", line 1104, in _write
self._file.write(to_write)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 1:ordinal not in range(128)

# Fixed code
def _write_data_dates(self):
    convert_dates = self._convert_dates
    data = self.datarows
    byteorder = self._byteorder
    TYPE_MAP = self.TYPE_MAP
    MISSING_VALUES = self.MISSING_VALUES
    typlist = self.typlist
    for row in data:
        # row = row.squeeze().tolist() # needed for structured arrays
        for i, var in enumerate(row):
            typ = ord(typlist[i])
            # NOTE: If anyone finds this terribly slow, there is
            # a vectorized way to convert dates, see genfromdta for going
            # from int to datetime and reverse it. will copy data though
            if i in convert_dates:
                var = _datetime_to_stata_elapsed(var, self.fmtlist[i])
            if typ <= 244:  # we've got a string
                if len(var) < typ:
                    var = _pad_bytes(var, typ)
                if compat.PY3:
                    self._write(var)
                else:
                    self._write(var.encode(self._encoding))
            else:
                self._file.write(struct.pack(byteorder + TYPE_MAP[typ], var))
# Buggy code
def ewma(
    arg, com=None, span=None, halflife=None, min_periods=0, freq=None, adjust=True
):
    com = _get_center_of_mass(com, span, halflife)
    arg = _conv_timerule(arg, freq)

    def _ewma(v):
        result = algos.ewma(v, com, int(adjust))
        first_index = _first_valid_index(v)
        result[first_index : first_index + min_periods] = NaN
        return result

    return_hook, values = _process_data_structure(arg)
    output = np.apply_along_axis(_ewma, 0, values)
    return return_hook(output)


# Traceback (AssertionError)
In [118]: import pandas

In [119]: indices = [datetime.datetime(1975, 1, i, 12, 0) for i in range(1, 6)]

In [120]: indices.append(datetime.datetime(1975, 1, 3, 6, 0))  # So that we can have 2 datapoints on one of the days

In [121]: series = pandas.Series(range(1, 7), index=indices)

In [122]: series = series.map(lambda x: float(x))  # Use floats instead of ints as values

In [123]: series = series.sort_index()  # Sort chronologically

In [124]: expected_result = pandas.Series([1.0, 2.0, 6.0, 4.0, 5.0], index=[datetime.datetime(1975, 1, i, 12, 0) for i in range(1, 6)])

In [125]: actual_result = pandas.rolling_max(series, window=1, freq='D')

In [126]: assert((actual_result==expected_result).all())
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-126-cc436c4798a7> in <module>()
----> 1 assert((actual_result==expected_result).all())

AssertionError:

In [127]: expected_result
Out[127]:
1975-01-01 12:00:00    1
1975-01-02 12:00:00    2
1975-01-03 12:00:00    6
1975-01-04 12:00:00    4
1975-01-05 12:00:00    5
dtype: float64

In [128]: actual_result
Out[128]:
1975-01-01    1.0
1975-01-02    2.0
1975-01-03    4.5
1975-01-04    4.0
1975-01-05    5.0
Freq: D, dtype: float64

# Fixed code
def ewma(
    arg,
    com=None,
    span=None,
    halflife=None,
    min_periods=0,
    freq=None,
    adjust=True,
    how=None,
):
    com = _get_center_of_mass(com, span, halflife)
    arg = _conv_timerule(arg, freq, how)

    def _ewma(v):
        result = algos.ewma(v, com, int(adjust))
        first_index = _first_valid_index(v)
        result[first_index : first_index + min_periods] = NaN
        return result

    return_hook, values = _process_data_structure(arg)
    output = np.apply_along_axis(_ewma, 0, values)
    return return_hook(output)
# Buggy code
def ewmvar(
    arg, com=None, span=None, halflife=None, min_periods=0, bias=False, freq=None
):
    com = _get_center_of_mass(com, span, halflife)
    arg = _conv_timerule(arg, freq)
    moment2nd = ewma(arg * arg, com=com, min_periods=min_periods)
    moment1st = ewma(arg, com=com, min_periods=min_periods)

    result = moment2nd - moment1st**2
    if not bias:
        result *= (1.0 + 2.0 * com) / (2.0 * com)

    return result


# Traceback (AssertionError)
In [118]: import pandas

In [119]: indices = [datetime.datetime(1975, 1, i, 12, 0) for i in range(1, 6)]

In [120]: indices.append(datetime.datetime(1975, 1, 3, 6, 0))  # So that we can have 2 datapoints on one of the days

In [121]: series = pandas.Series(range(1, 7), index=indices)

In [122]: series = series.map(lambda x: float(x))  # Use floats instead of ints as values

In [123]: series = series.sort_index()  # Sort chronologically

In [124]: expected_result = pandas.Series([1.0, 2.0, 6.0, 4.0, 5.0], index=[datetime.datetime(1975, 1, i, 12, 0) for i in range(1, 6)])

In [125]: actual_result = pandas.rolling_max(series, window=1, freq='D')

In [126]: assert((actual_result==expected_result).all())
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-126-cc436c4798a7> in <module>()
----> 1 assert((actual_result==expected_result).all())

AssertionError:

In [127]: expected_result
Out[127]:
1975-01-01 12:00:00    1
1975-01-02 12:00:00    2
1975-01-03 12:00:00    6
1975-01-04 12:00:00    4
1975-01-05 12:00:00    5
dtype: float64

In [128]: actual_result
Out[128]:
1975-01-01    1.0
1975-01-02    2.0
1975-01-03    4.5
1975-01-04    4.0
1975-01-05    5.0
Freq: D, dtype: float64

# Fixed code
def ewmvar(
    arg,
    com=None,
    span=None,
    halflife=None,
    min_periods=0,
    bias=False,
    freq=None,
    how=None,
):
    com = _get_center_of_mass(com, span, halflife)
    arg = _conv_timerule(arg, freq, how)
    moment2nd = ewma(arg * arg, com=com, min_periods=min_periods)
    moment1st = ewma(arg, com=com, min_periods=min_periods)

    result = moment2nd - moment1st**2
    if not bias:
        result *= (1.0 + 2.0 * com) / (2.0 * com)

    return result
# Buggy code
def ewmcov(
    arg1,
    arg2=None,
    com=None,
    span=None,
    halflife=None,
    min_periods=0,
    bias=False,
    freq=None,
    pairwise=None,
):
    if arg2 is None:
        arg2 = arg1
        pairwise = True if pairwise is None else pairwise
    elif isinstance(arg2, (int, float)) and com is None:
        com = arg2
        arg2 = arg1
        pairwise = True if pairwise is None else pairwise
    arg1 = _conv_timerule(arg1, freq)
    arg2 = _conv_timerule(arg2, freq)

    def _get_ewmcov(X, Y):
        mean = lambda x: ewma(
            x, com=com, span=span, halflife=halflife, min_periods=min_periods
        )
        return mean(X * Y) - mean(X) * mean(Y)

    result = _flex_binary_moment(arg1, arg2, _get_ewmcov, pairwise=bool(pairwise))
    if not bias:
        com = _get_center_of_mass(com, span, halflife)
        result *= (1.0 + 2.0 * com) / (2.0 * com)

    return result


# Traceback (AssertionError)
In [118]: import pandas

In [119]: indices = [datetime.datetime(1975, 1, i, 12, 0) for i in range(1, 6)]

In [120]: indices.append(datetime.datetime(1975, 1, 3, 6, 0))  # So that we can have 2 datapoints on one of the days

In [121]: series = pandas.Series(range(1, 7), index=indices)

In [122]: series = series.map(lambda x: float(x))  # Use floats instead of ints as values

In [123]: series = series.sort_index()  # Sort chronologically

In [124]: expected_result = pandas.Series([1.0, 2.0, 6.0, 4.0, 5.0], index=[datetime.datetime(1975, 1, i, 12, 0) for i in range(1, 6)])

In [125]: actual_result = pandas.rolling_max(series, window=1, freq='D')

In [126]: assert((actual_result==expected_result).all())
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-126-cc436c4798a7> in <module>()
----> 1 assert((actual_result==expected_result).all())

AssertionError:

In [127]: expected_result
Out[127]:
1975-01-01 12:00:00    1
1975-01-02 12:00:00    2
1975-01-03 12:00:00    6
1975-01-04 12:00:00    4
1975-01-05 12:00:00    5
dtype: float64

In [128]: actual_result
Out[128]:
1975-01-01    1.0
1975-01-02    2.0
1975-01-03    4.5
1975-01-04    4.0
1975-01-05    5.0
Freq: D, dtype: float64

# Fixed code
def ewmcov(
    arg1,
    arg2=None,
    com=None,
    span=None,
    halflife=None,
    min_periods=0,
    bias=False,
    freq=None,
    pairwise=None,
    how=None,
):
    if arg2 is None:
        arg2 = arg1
        pairwise = True if pairwise is None else pairwise
    elif isinstance(arg2, (int, float)) and com is None:
        com = arg2
        arg2 = arg1
        pairwise = True if pairwise is None else pairwise
    arg1 = _conv_timerule(arg1, freq, how)
    arg2 = _conv_timerule(arg2, freq, how)

    def _get_ewmcov(X, Y):
        mean = lambda x: ewma(
            x, com=com, span=span, halflife=halflife, min_periods=min_periods
        )
        return mean(X * Y) - mean(X) * mean(Y)

    result = _flex_binary_moment(arg1, arg2, _get_ewmcov, pairwise=bool(pairwise))
    if not bias:
        com = _get_center_of_mass(com, span, halflife)
        result *= (1.0 + 2.0 * com) / (2.0 * com)

    return result
# Buggy code
def _conv_timerule(arg, freq):
    types = (DataFrame, Series)
    if freq is not None and isinstance(arg, types):
        # Conform to whatever frequency needed.
        arg = arg.resample(freq)

    return arg


# Traceback (AssertionError)
In [118]: import pandas

In [119]: indices = [datetime.datetime(1975, 1, i, 12, 0) for i in range(1, 6)]

In [120]: indices.append(datetime.datetime(1975, 1, 3, 6, 0))  # So that we can have 2 datapoints on one of the days

In [121]: series = pandas.Series(range(1, 7), index=indices)

In [122]: series = series.map(lambda x: float(x))  # Use floats instead of ints as values

In [123]: series = series.sort_index()  # Sort chronologically

In [124]: expected_result = pandas.Series([1.0, 2.0, 6.0, 4.0, 5.0], index=[datetime.datetime(1975, 1, i, 12, 0) for i in range(1, 6)])

In [125]: actual_result = pandas.rolling_max(series, window=1, freq='D')

In [126]: assert((actual_result==expected_result).all())
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-126-cc436c4798a7> in <module>()
----> 1 assert((actual_result==expected_result).all())

AssertionError:

In [127]: expected_result
Out[127]:
1975-01-01 12:00:00    1
1975-01-02 12:00:00    2
1975-01-03 12:00:00    6
1975-01-04 12:00:00    4
1975-01-05 12:00:00    5
dtype: float64

In [128]: actual_result
Out[128]:
1975-01-01    1.0
1975-01-02    2.0
1975-01-03    4.5
1975-01-04    4.0
1975-01-05    5.0
Freq: D, dtype: float64

# Fixed code
def _conv_timerule(arg, freq, how):
    types = (DataFrame, Series)
    if freq is not None and isinstance(arg, types):
        # Conform to whatever frequency needed.
        arg = arg.resample(freq, how=how)

    return arg
# Buggy code
def _rolling_func(func, desc, check_minp=_use_window):
    @Substitution(desc, _unary_arg, _roll_kw, _type_of_input_retval, _roll_notes)
    @Appender(_doc_template)
    @wraps(func)
    def f(arg, window, min_periods=None, freq=None, center=False, **kwargs):
        def call_cython(arg, window, minp, args=(), kwargs={}, **kwds):
            minp = check_minp(minp, window)
            return func(arg, window, minp, **kwds)

        return _rolling_moment(
            arg, window, call_cython, min_periods, freq=freq, center=center, **kwargs
        )

    return f


# Traceback (AssertionError)
In [118]: import pandas

In [119]: indices = [datetime.datetime(1975, 1, i, 12, 0) for i in range(1, 6)]

In [120]: indices.append(datetime.datetime(1975, 1, 3, 6, 0))  # So that we can have 2 datapoints on one of the days

In [121]: series = pandas.Series(range(1, 7), index=indices)

In [122]: series = series.map(lambda x: float(x))  # Use floats instead of ints as values

In [123]: series = series.sort_index()  # Sort chronologically

In [124]: expected_result = pandas.Series([1.0, 2.0, 6.0, 4.0, 5.0], index=[datetime.datetime(1975, 1, i, 12, 0) for i in range(1, 6)])

In [125]: actual_result = pandas.rolling_max(series, window=1, freq='D')

In [126]: assert((actual_result==expected_result).all())
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-126-cc436c4798a7> in <module>()
----> 1 assert((actual_result==expected_result).all())

AssertionError:

In [127]: expected_result
Out[127]:
1975-01-01 12:00:00    1
1975-01-02 12:00:00    2
1975-01-03 12:00:00    6
1975-01-04 12:00:00    4
1975-01-05 12:00:00    5
dtype: float64

In [128]: actual_result
Out[128]:
1975-01-01    1.0
1975-01-02    2.0
1975-01-03    4.5
1975-01-04    4.0
1975-01-05    5.0
Freq: D, dtype: float64

# Fixed code
def _rolling_func(func, desc, check_minp=_use_window, how=None):
    if how is None:
        how_arg_str = "None"
    else:
        how_arg_str = "'%s" % how

    @Substitution(
        desc, _unary_arg, _roll_kw % how_arg_str, _type_of_input_retval, _roll_notes
    )
    @Appender(_doc_template)
    @wraps(func)
    def f(arg, window, min_periods=None, freq=None, center=False, how=how, **kwargs):
        def call_cython(arg, window, minp, args=(), kwargs={}, **kwds):
            minp = check_minp(minp, window)
            return func(arg, window, minp, **kwds)

        return _rolling_moment(
            arg,
            window,
            call_cython,
            min_periods,
            freq=freq,
            center=center,
            how=how,
            **kwargs,
        )

    return f