def rolling_window(arr, window_size, stride=1, return_idx=False):
    """
    There is an example of an iterator for pure-Python objects in:
    http://stackoverflow.com/questions/6822725/rolling-or-sliding-window-iterator-in-python
    This is a rolling-window iterator Numpy arrays, with window size and
    stride control. See examples below for demos.

    Parameters
    ----------
    arr : array_like
        Input numpy array.
    window_size : int
        Width of the window.
    stride : int (optional)
        Number of indices to advance the window each iteration step.
    return_idx : bool (optional)
        Whether to return the slice indices alone with the array segment.

    Examples
    --------
    >>> a = np.array([1,2,3,4,5,6])
    >>> for x in rolling_window(a, 3):
    ...     print(x)
    [1 2 3]
    [2 3 4]
    [3 4 5]
    [4 5 6]
    >>> for x in rolling_window(a, 2, stride=2):
    ...     print(x)
    [1 2]
    [3 4]
    [5 6]
    >>> for (i1,i2),x in rolling_window(a, 2, stride=2, return_idx=True): # doctest: +SKIP
    ...     print(i1, i2, x)
    (0, 2, array([1, 2]))
    (2, 4, array([3, 4]))
    (4, 6, array([5, 6]))

    """
    window_size = int(window_size)
    stride = int(stride)
    if window_size < 0 or stride < 1:
        raise ValueError
    arr_len = len(arr)
    if arr_len < window_size:
        if return_idx:
            yield (0, arr_len), arr
        else:
            yield arr
    ix1 = 0
    while ix1 < arr_len:
        ix2 = ix1 + window_size
        result = arr[ix1:ix2]
        if return_idx:
            yield (ix1, ix2), result
        else:
            yield result
        if len(result) < window_size or ix2 >= arr_len:
            break
        ix1 += stride
