This will rearrange the array a[n] from lowest to highest, and
    rearrange the rest of a[i]'s in the same way. It is dumb and slow.

    Returns a numpy array.
187326
def sort_matrix(a,n=0):
    
    a = _n.array(a)
    return a[:,a[n,:].argsort()]
664698
private void moveAtFirst(int n_from) {
		int eT = elements[0];
		int eF = elements[n_from];
		positions[eT] = -1;
		positions[eF] = 0;
		elements[0] = eF;
		elements[n_from] = -1;
	}
248409
def wrap(lower, upper, x):
    
    #I have no idea how I came up with this algorithm; it should be simplified.
    #
    # Note that Python's % operator works on floats and arrays;
    # usually one can simply use that instead.  E.g. to wrap array or
    # scalar x into 0,2*pi, just use "x % (2*pi)".
    range_=upper-lower
    return lower + np.fmod(x-lower + 2*range_*(1-np.floor(x/(2*range_))), range_)
372255
def arglexsort(arrays):
    
    dtypes = ','.join(array.dtype.str for array in arrays)
    recarray = np.empty(len(arrays[0]), dtype=dtypes)
    for i, array in enumerate(arrays):
        recarray['f%s' % i] = array
    return recarray.argsort()
279401
function(arr, i) {
			var ret = arr.slice(0);
			for (var j = 0; j < i; j++) {
				ret = [ret[ret.length - 1]].concat(ret.slice(0, ret.length - 1));
			}
			return ret;
		}
923601
def unsort(self, array):
        
        if self.sorted:
            inverse = sorted(enumerate(self.indices), key=itemgetter(1))
            array = [array[i[0]] for i in inverse]
        return array
911045
def permute(self, ordering: np.ndarray, *, axis: int) -> None:
		
		if axis not in (0, 1):
			raise ValueError("Axis must be 0 (rows) or 1 (columns)")
		for layer in self.layers.values():
			layer._permute(ordering, axis=axis)
		if axis == 0:
			if self.row_graphs is not None:
				for g in self.row_graphs.values():
					g._permute(ordering)
			for a in self.row_attrs.values():
				a._permute(ordering)
		elif axis == 1:
			if self.col_graphs is not None:
				for g in self.col_graphs.values():
					g._permute(ordering)
			for a in self.col_attrs.values():
				a._permute(ordering)
726317
def sortedIndex(self, obj, iterator=lambda x: x):
        
        array = self.obj
        value = iterator(obj)
        low = 0
        high = len(array)
        while low < high:
            mid = (low + high) >> 1
            if iterator(array[mid]) < value:
                low = mid + 1
            else:
                high = mid
        return self._wrap(low)
9691
function reverseArray(array) {
  let index = array.length,
      newArray = [];

  while (index--) {
    newArray.push(array[index]);
  }

  return newArray;
}
1057838
def sort_and_distribute(array, splits=2):
   
   if not isinstance(array, (list,tuple)): raise TypeError("array must be a list")
   if not isinstance(splits, int): raise TypeError("splits must be an integer")
   remaining = sorted(array)
   if sys.version_info < (3, 0):
      myrange = xrange(splits)
   else:
      myrange = range(splits)
   groups = [[] for i in myrange]
   while len(remaining) > 0:
      for i in myrange:
         if len(remaining) > 0: groups[i].append(remaining.pop(0))
   return groups
947992
function sort(array, minValue, maxValue) {
  if (array.length === 0) {
    return array;
  }

  var rangeSize = maxValue - minValue;
  var buckets = new Array(rangeSize);
  var sortedIndex = 0;
  var i;

  for (i = 0; i < array.length; i++) {
    // Change the value to a zero-based index
    var bucketIndex = array[i] - minValue;
    if (!buckets[bucketIndex]) {
      buckets[bucketIndex] = 0;
    }
    buckets[bucketIndex]++;
  }

  for (i = 0; i < buckets.length; i++) {
    while (buckets[i] > 0) {
      // Change the index to the correct value
      array[sortedIndex++] = i + minValue;
      buckets[i]--;
    }
  }

  return array;
}
1207043
def nsmallest(n, iterable, key=None):
    

    # Short-cut for n==1 is to use min()
    if n == 1:
        it = iter(iterable)
        sentinel = object()
        if key is None:
            result = min(it, default=sentinel)
        else:
            result = min(it, default=sentinel, key=key)
        return [] if result is sentinel else [result]

    # When n>=size, it's faster to use sorted()
    try:
        size = len(iterable)
    except (TypeError, AttributeError):
        pass
    else:
        if n >= size:
            return sorted(iterable, key=key)[:n]

    # When key is none, use simpler decoration
    if key is None:
        it = iter(iterable)
        # put the range(n) first so that zip() doesn't
        # consume one too many elements from the iterator
        result = [(elem, i) for i, elem in zip(range(n), it)]
        if not result:
            return result
        _heapify_max(result)
        top = result[0][0]
        order = n
        _heapreplace = _heapreplace_max
        for elem in it:
            if elem < top:
                _heapreplace(result, (elem, order))
                top = result[0][0]
                order += 1
        result.sort()
        return [r[0] for r in result]

    # General case, slowest method
    it = iter(iterable)
    result = [(key(elem), i, elem) for i, elem in zip(range(n), it)]
    if not result:
        return result
    _heapify_max(result)
    top = result[0][0]
    order = n
    _heapreplace = _heapreplace_max
    for elem in it:
        k = key(elem)
        if k < top:
            _heapreplace(result, (k, order, elem))
            top = result[0][0]
            order += 1
    result.sort()
    return [r[2] for r in result]
74641
def Vaknin (x):
  
  # Preallocate array with 2 more rows than input array
  x_new = np.zeros((x.shape[0]+2, x.shape[1]))
  # print x_new.shape
  # Duplicate first and last row of x into first and last row of x_new
  x_new[0, :] = x[0, :]
  x_new[-1, :] = x[-1, :]
  # Duplicate all of x into middle rows of x_neww
  x_new[1:-1, :] = x
  return x_new
575373
def _array(group_idx, a, size, fill_value, dtype=None):
    """"""
    if fill_value is not None and not (np.isscalar(fill_value) or
                                       len(fill_value) == 0):
        raise ValueError("fill_value must be None, a scalar or an empty "
                         "sequence")
    order_group_idx = np.argsort(group_idx, kind='mergesort')
    counts = np.bincount(group_idx, minlength=size)
    ret = np.split(a[order_group_idx], np.cumsum(counts)[:-1])
    ret = np.asanyarray(ret)
    if fill_value is None or np.isscalar(fill_value):
        _fill_untouched(group_idx, ret, fill_value)
    return ret
1312668
def normalize_array(a,direction="column"):
    
    b = a.copy()
    if(direction == "column"):
        sums = np.sum(b,0)
        return np.nan_to_num(b/sums)
    elif(direction == "row"):
        sums =np.sum(b,1)
        return  np.nan_to_num((b.transpose() / sums).transpose())
    elif(direction == "all"):
        sums = np.sum(b)
        return np.nan_to_num(b / sums)
    else:
        print "Error non existing normalization"
        return b
85661
def reduce(args):
    
    if len(args) < 2: return args
    args.sort()
    ret = [args[0]]
    for next_i, (s, e) in enumerate(args, start=1):
        if next_i == len(args):
            ret[-1] = ret[-1][0], max(ret[-1][1], e)
            break

        ns, ne = args[next_i]
        if e > ns or ret[-1][1] > ns:
            ret[-1] = ret[-1][0], max(e, ne, ret[-1][1])
        else:
            ret.append((ns, ne))
    return ret
955427
def reverse_index_mapping(self):
        
        if self._reverse_index_mapping is None:
            if self.is_indexed:
                # Initialize array to out of range
                r = np.zeros(self.base_length, dtype=np.int32) - 1
                r[self.order] = np.arange(len(self.order), dtype=np.int32)
            elif self.data.base is None:
                # Starts at the beginning; produces the identity
                r = np.arange(self.data_length, dtype=np.int32)
            else:
                r = np.zeros(self.base_length, dtype=np.int32) - 1
                r[self.data_start - self.base_start:self.data_end - self.base_start] = np.arange(self.data_length, dtype=np.int32)
            self._reverse_index_mapping = r
        return self._reverse_index_mapping