Given a list of slices, draw N samples such that each slice contributes as much as possible

    Parameters
    --------------------------
    slice_list : list of Slice
        List of slices
    N : int
        Number of samples to draw
169496
def fill_sampling(slice_list, N):
    
    A = [len(s.inliers) for s in slice_list]
    N_max = np.sum(A)
    if N > N_max:
        raise ValueError("Tried to draw {:d} samples from a pool of only {:d} items".format(N, N_max))
    
    samples_from = np.zeros((len(A),), dtype='int') # Number of samples to draw from each group

    remaining = N
    while remaining > 0:
        remaining_groups = np.flatnonzero(samples_from - np.array(A))
        
        if remaining < len(remaining_groups):
            np.random.shuffle(remaining_groups)
            for g in remaining_groups[:remaining]:
                samples_from[g] += 1
        else:
            # Give each group the allowed number of samples. Constrain to their max size.
            to_each = max(1, int(remaining / len(remaining_groups)))
            samples_from = np.min(np.vstack((samples_from + to_each, A)), axis=0)
        
        # Update remaining count
        remaining = int(N - np.sum(samples_from))
    if not remaining == 0:
        raise ValueError("Still {:d} samples left! This is an error in the selection.")

    # Construct index list of selected samples
    samples = []
    for s, a, n in zip(slice_list, A, samples_from):
        if a == n:
            samples.append(np.array(s.inliers)) # all
        elif a == 0:
            samples.append(np.arange([]))
        else:
            chosen = np.random.choice(s.inliers, n, replace=False)
            samples.append(np.array(chosen))
    return samples
722857
def check_num_slices(num_slices, img_shape=None, num_dims=3):
    

    if not isinstance(num_slices, Iterable) or len(num_slices) == 1:
        num_slices = np.repeat(num_slices, num_dims)

    if img_shape is not None:
        if len(num_slices) != len(img_shape):
            raise ValueError('The number of dimensions requested is different from image.'
                             ' Must be either 1 or equal to {}'.format(len(img_shape) + 1))
        # upper bounding them to image shape
        num_slices = np.minimum(img_shape, num_slices)

    # lower bounding it to 1
    return np.maximum(1, num_slices)
1068482
def draw_slices(hist, func=np.sum, **kwargs):
    
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    kwargs.setdefault('ls','-')
    ax = plt.gca()

    data = hist

    # Slices
    vslice = func(data,axis=0)
    hslice = func(data,axis=1)

    npix = np.array(data.shape)
    #xlim,ylim = plt.array(zip([0,0],npix-1))
    xlim = ax.get_xlim()
    ylim = ax.get_ylim()
    #extent = ax.get_extent()
    #xlim =extent[:2]
    #ylim = extent[2:]

    # Bin centers
    xbin = np.linspace(xlim[0],xlim[1],len(vslice))#+0.5 
    ybin = np.linspace(ylim[0],ylim[1],len(hslice))#+0.5
    divider = make_axes_locatable(ax)
    
    #gh2 = pywcsgrid2.GridHelperSimple(wcs=self.header, axis_nums=[2, 1])
    hax = divider.append_axes("right", size=1.2, pad=0.05,sharey=ax,
                              axes_class=axes_divider.LocatableAxes)
    hax.axis["left"].toggle(label=False, ticklabels=False)
    #hax.plot(hslice, plt.arange(*ylim)+0.5,'-') # Bin center
    hax.plot(hslice, ybin, **kwargs) # Bin center
    hax.xaxis.set_major_locator(MaxNLocator(4,prune='both'))
    hax.set_ylim(*ylim)

    #gh1 = pywcsgrid2.GridHelperSimple(wcs=self.header, axis_nums=[0, 2])
    vax = divider.append_axes("top", size=1.2, pad=0.05, sharex=ax,
                              axes_class=axes_divider.LocatableAxes)
    vax.axis["bottom"].toggle(label=False, ticklabels=False)
    vax.plot(xbin, vslice, **kwargs) 
    vax.yaxis.set_major_locator(MaxNLocator(4,prune='lower'))
    vax.set_xlim(*xlim)

    return vax,hax
916930
def iterintervals(self, n=2):
        
        # tee the original iterator into n identical iterators
        streams = tee(iter(self), n)

        # advance the "cursor" on each iterator by an increasing
        # offset, e.g. if n=3:
        #
        #                   [a, b, c, d, e, f, ..., w, x, y, z]
        #  first cursor -->  *
        # second cursor -->     *
        #  third cursor -->        *
        for stream_index, stream in enumerate(streams):
            for i in range(stream_index):
                next(stream)

        # now, zip the offset streams back together to yield tuples,
        # in the n=3 example it would yield:
        # (a, b, c), (b, c, d), ..., (w, x, y), (x, y, z)
        for intervals in zip(*streams):
            yield intervals
615069
def new_batch(self):
        
        i = next(self.slicer)
        return self.X_all[i], self.Y_all[i]
426613
def slice(self, order_by='pk', n=None):
        
        if n is not None and n < 0:
            raise ValueError('slice parameter cannot be negative')
        
        queryset = self.order_by(order_by)
        
        if n is None:
            return queryset[0]
        else:
            return queryset[0:n]
1321103
def _generate_examples(self, num_examples, data_path, label_path):
    
    images = _extract_mnist_images(data_path, num_examples)
    labels = _extract_mnist_labels(label_path, num_examples)
    data = list(zip(images, labels))

    # Data is shuffled automatically to distribute classes uniformly.
    for image, label in data:
      yield {
          "image": image,
          "label": label,
      }
212993
def fib_list(n):
    

    # precondition
    assert n >= 0, 'n must be a positive integer'

    list_results = [0, 1]
    for i in range(2, n+1):
        list_results.append(list_results[i-1] + list_results[i-2])
    return list_results[n]
593626
def _make_sampling_sequence(n):
    # type: (int) -> List[int]
    
    seq = list(range(5))
    i = 50
    while len(seq) < n:
        seq.append(i)
        i += 50
    return seq
323352
def sample_labels(self, n):
        
        if n >= len(self):
            return self.labels
        sample = random.sample(self.labels, n)
        return set(sample)
834008
def slices(self):
        
        if self.chunks is None:
            yield tuple(slice(None, s) for s in self.shape)
        else:
            ceilings = tuple(-(-s // c) for s, c in zip(self.shape, self.chunks))
            for idx in np.ndindex(ceilings):  # could also use itertools.product
                out = []
                for i, c, s in zip(idx, self.chunks, self.shape):
                    start = i * c
                    stop = min(start + c, s + 1)
                    out.append(slice(start, stop, 1))
                yield tuple(out)
1322849
def get_list_representation(self):
        """"""
        if self.is_list:
            return self.list_or_slice
        else:
            return self[list(range(self.num_examples))]
906016
def possiblesplits(n, minsplits=2, maxsplits=0):
    """"""
    if not maxsplits: maxsplits = n
    for nrsplits in range(minsplits,maxsplits + 1):
        for split in sum_to_n(n,nrsplits):
            split_with_indices = []
            begin = 0
            for length in split:
                split_with_indices.append( (begin, length) )
                begin += length
            yield split_with_indices
1347561
def draw(self,N=1.5):
        
        while N>0.5:
            for (l,mvmt) in self.ordering_step():
                pass
            N = N-1
        if N>0:
            for (l,mvmt) in self.ordering_step(oneway=True):
                pass
        self.setxy()
        self.draw_edges()
1210025
def slices(img, shape=[3, 4]):
    
    sh = np.asarray(shape)
    i_max = np.prod(sh)
    allimg = np.zeros(img.shape[-2:] * sh)

    for i in range(0, i_max):
        # i = 0
        islice = round((img.shape[0] / float(i_max)) * i)
        #         print(islice)
        imgi = img[islice, :, :]
        coords = index_to_coords(i, sh)
        aic = np.asarray(img.shape[-2:]) * coords

        allimg[aic[0]:aic[0] + imgi.shape[-2], aic[1]:aic[1] + imgi.shape[-1]] = imgi

    #     plt.imshow(imgi)
    #     print(imgi.shape)
    #     print(img.shape)
    return allimg
1112184
def safe_slice(list_, *args):
    
    if len(args) == 3:
        start = args[0]
        stop  = args[1]
        step  = args[2]
    else:
        step = 1
        if len(args) == 2:
            start = args[0]
            stop  = args[1]
        else:
            start = 0
            stop = args[0]
    len_ = len(list_)
    if stop > len_:
        stop = len_
    return list_[slice(start, stop, step)]
933902
def draw_rects(self, *rects):
        
        rect_array = ffi.new('SDL_Rect[]', len(rects))
        for i, r in enumerate(rects):
            rect_array[i] = r._ptr[0]
        check_int_err(lib.SDL_RenderDrawRects(self._ptr, rect_array, len(rects)))