import h5py
import numpy
import math
import struct

def fair_share(N,npr,rk):

    npp = N // npr
    nxtra = N % npr
    if rk < nxtra:
        i0 = rk*(npp+1)
        iN = i0 + npp+1
    else:
        i0 = rk*npp+nxtra
        iN = i0 + npp
    return i0, iN

def bisect(a, x, lo=0, hi=None):
    """Return the index where to insert item x in list a, assuming a is sorted.

    The return value i is such that all e in a[:i] have e <= x, and all e in
    a[i:] have e > x.  So if x already appears in the list, a.insert(x) will
    insert just after the rightmost x already there.

    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched.
    """

    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if x < a[mid]: hi = mid
        else: lo = mid+1
    return lo
