First Fit Decreasing heuristics for the Bin Packing Problem.
    Parameters:
        - s: list with item widths
        - B: bin capacity
    Returns a list of lists with bin compositions.
971730
def FFD(s,B):
    
    remain = [B]        # keep list of empty space per bin
    sol = [[]]          # a list ot items (i.e., sizes) on each used bin
    for item in sorted(s,reverse=True):
        for (j,free) in enumerate(remain):
            if free >= item:
                remain[j] -= item
                sol[j].append(item)
                break
        else: #does not fit in any bin
            sol.append([item])
            remain.append(B-item)
    return sol
527085
def get_possible_splits(n):
    
    get_bin = lambda x, n: x >= 0 and str(bin(x))[2:].zfill(n) or "-" + str(bin(x))[3:].zfill(n)
    possible_splits = []
    for i in range(2**(n - 1)):
        possible_splits.append(get_bin(i, n - 1))
    return possible_splits
1063124
def mr(items, targets, **kwargs):
    
    bins = [(target, []) for target in targets]
    skip = []

    for item in items:
        capacities = [target - sum(content) for target, content in bins]
        weighted = weight(capacities, **kwargs)

        (target, content), capacity, _ = max(zip(bins, capacities, weighted),
                                             key=operator.itemgetter(2))
        if item <= capacity:
            content.append(item)
        else:
            skip.append(item)
    return bins, skip
104346
def ed(s1, s2):
    '''
    '''
    m, n = len(s1), len(s2)
    if m < n:
        m, n = n, m         # ensure n <= m, to use O(min(n,m)) space
        s1, s2 = s2, s1
    d = list(range(n+1))
    for i in range(m):
        p = i
        d[0] = i+1
        for j in range(n):
            t = 0 if s1[i] == s2[j] else 1
            p, d[j+1] = d[j+1], min(p+t, d[j]+1, d[j+1]+1)
    return d[n]
991755
def _locate_bin(bins, n):
    
    while bins[n] != n:
        n = bins[n]
    return n
144579
def uniform_binned(self, name=None):
        
        if self.GetDimension() == 1:
            new_hist = Hist(
                self.GetNbinsX(), 0, self.GetNbinsX(),
                name=name, type=self.TYPE)
        elif self.GetDimension() == 2:
            new_hist = Hist2D(
                self.GetNbinsX(), 0, self.GetNbinsX(),
                self.GetNbinsY(), 0, self.GetNbinsY(),
                name=name, type=self.TYPE)
        else:
            new_hist = Hist3D(
                self.GetNbinsX(), 0, self.GetNbinsX(),
                self.GetNbinsY(), 0, self.GetNbinsY(),
                self.GetNbinsZ(), 0, self.GetNbinsZ(),
                name=name, type=self.TYPE)
        # copy over the bin contents and errors
        for outbin, inbin in zip(new_hist.bins(), self.bins()):
            outbin.value = inbin.value
            outbin.error = inbin.error
        new_hist.decorate(self)
        new_hist.entries = self.entries
        return new_hist
941806
def ssd(p1, p2):
    
    return 2 - np.sum([(a-b)**2 for a,b in zip(p1,p2)])
357624
def spaced_items(list_, n, **kwargs):
    
    indexes = spaced_indexes(len(list_), n, **kwargs)
    items = list_[indexes]
    return items
1191817
def compute_merkle_tree(items: Iterable[bytes]) -> MerkleTree:
    

    if not all(isinstance(l, bytes) and len(l) == 32 for l in items):
        raise ValueError('Not all items are hashes')

    leaves = sorted(items)
    if len(leaves) == 0:
        return MerkleTree(layers=[[EMPTY_MERKLE_ROOT]])

    if not len(leaves) == len(set(leaves)):
        raise ValueError('The leaves items must not contain duplicate items')

    tree = [leaves]
    layer = leaves
    while len(layer) > 1:
        # [a, b, c, d, e] -> [(a, b), (c, d), (e, None)]
        iterator = iter(layer)
        paired_items = zip_longest(iterator, iterator)

        layer = [_hash_pair(a, b) for a, b in paired_items]
        tree.append(layer)

    return MerkleTree(layers=tree)
486363
def bins(start, end):
        
        if end - start < 536870912:
            offsets = [585, 73, 9, 1]
        else:
            raise BigException
            offsets = [4681, 585, 73, 9, 1]
        binFirstShift = 17
        binNextShift = 3

        start = start >> binFirstShift
        end = (end - 1)  >> binFirstShift

        bins = [1]
        for offset in offsets:
            bins.extend(range(offset + start, offset + end + 1))
            start >>= binNextShift
            end >>= binNextShift
        return frozenset(bins)
1002643
def tsp(edges, constraint_generation=False):
    
    edges = populate_edge_weights(edges)
    incoming, outgoing, nodes = node_to_edge(edges)

    nedges, nnodes = len(edges), len(nodes)
    L = LPInstance()

    L.add_objective(edges, objective=MINIMIZE)
    balance = []
    # For each node, select exactly 1 incoming and 1 outgoing edge
    for v in nodes:
        incoming_edges = incoming[v]
        outgoing_edges = outgoing[v]
        icc = summation(incoming_edges)
        occ = summation(outgoing_edges)
        balance.append("{0} = 1".format(icc))
        balance.append("{0} = 1".format(occ))

    # Subtour elimination - Miller-Tucker-Zemlin (MTZ) formulation
    # <http://en.wikipedia.org/wiki/Travelling_salesman_problem>
    # Desrochers and laporte, 1991 (DFJ) has a stronger constraint
    # See also:
    # G. Laporte / The traveling salesman problem: Overview of algorithms
    start_step = nedges + 1
    u0 = nodes[0]
    nodes_to_steps = dict((n, start_step + i) for i, n in enumerate(nodes[1:]))
    edge_store = dict((e[:2], i) for i, e in enumerate(edges))
    mtz = []
    for i, e in enumerate(edges):
        a, b = e[:2]
        if u0 in (a, b):
            continue
        na, nb = nodes_to_steps[a], nodes_to_steps[b]
        con_ab = " x{0} - x{1} + {2}x{3}".format(na, nb, nnodes - 1, i + 1)
        if (b, a) in edge_store:  # This extra term is the stronger DFJ formulation
            j = edge_store[(b, a)]
            con_ab += " + {0}x{1}".format(nnodes - 3, j + 1)
        con_ab += " <= {0}".format(nnodes - 2)
        mtz.append(con_ab)

    # Step variables u_i bound between 1 and n, as additional variables
    bounds = []
    for i in xrange(start_step, nedges + nnodes):
        bounds.append(" 1 <= x{0} <= {1}".format(i, nnodes - 1))

    L.add_vars(nedges)

    """
    Constraint generation seek to find 'cuts' in the LP problem, by solving the
    relaxed form. The subtours were then incrementally added to the constraints.
    """
    if constraint_generation:
        L.constraints = balance
        subtours = []
        while True:
            selected, obj_val = L.lpsolve()
            results = sorted(x for i, x in enumerate(edges) if i in selected) \
                if selected else None
            if not results:
                break
            G = edges_to_graph(results)
            cycles = list(nx.simple_cycles(G))
            if len(cycles) == 1:
                break
            for c in cycles:
                incident = [edge_store[a, b] for a, b in pairwise(c + [c[0]])]
                icc = summation(incident)
                subtours.append("{0} <= {1}".format(icc, len(incident) - 1))
            L.constraints = balance + subtours
    else:
        L.constraints = balance + mtz
        L.add_vars(nnodes - 1, offset=start_step, binary=False)
        L.bounds = bounds
        selected, obj_val = L.lpsolve()
        results = sorted(x for i, x in enumerate(edges) if i in selected) \
            if selected else None

    return results
430296
def partition(a:Collection, sz:int)->List[Collection]:
    ""
    return [a[i:i+sz] for i in range(0, len(a), sz)]
849672
def calc_fitness(self,X,labels,fit_choice,sel):
        

        if 'lexicase' in sel:
            # return list(map(lambda yhat: self.f_vec[fit_choice](labels,yhat),X))
            return np.asarray(
                              [self.proper(self.f_vec[fit_choice](labels,
                                                        yhat)) for yhat in X],
                                                        order='F')
            # return list(Parallel(n_jobs=-1)(delayed(self.f_vec[fit_choice])(labels,yhat) for yhat in X))
        else:
            # return list(map(lambda yhat: self.f[fit_choice](labels,yhat),X))
            return np.asarray([self.f[fit_choice](labels,yhat) for yhat in X],
                            order='F').reshape(-1)
1234481
def s2b(s):
    
    ret = []
    for c in s:
        ret.append(bin(ord(c))[2:].zfill(8))
    return "".join(ret)
1309205
def _bin_zfill(num, width=None):
    
    s = bin(num)[2:]
    return s if width is None else s.zfill(width)
777480
def get_histogram_bins(min_, max_, std, count):
    

    width = _get_bin_width(std, count)
    count = int(round((max_ - min_) / width) + 1)

    if count:
        bins = [i * width + min_ for i in xrange(1, count + 1)]
    else:
        bins = [min_]

    return bins
612093
def range_hist(items, bins):
    
    big_hist = ut.dict_hist(items)
    hist = ut.odict([(b, 0) for b in bins])

    for k, v in big_hist.items():
        for b in bins:
            if isinstance(b, (list, tuple)):
                if k >= b[0] and k < b[1]:
                    hist[b] += v
            elif k == b:
                hist[b] += v
    return hist