This method sorts the population in descending order while calculating the
selection probabilities.
775121
@Override
	protected double[] probabilities(
		final Seq<Phenotype<G, C>> population,
		final int count
	) {
		assert population != null : "Population must not be null. ";
		assert !population.isEmpty() : "Population is empty.";
		assert count > 0 : "Population to select must be greater than zero. ";

		final double N = population.size();
		final double[] probabilities = new double[population.size()];

		final double b = (_c - 1.0)/(pow(_c, N) - 1.0);
		for (int i = 0; i < probabilities.length; ++i) {
			probabilities[i] = pow(_c, i)*b;
		}

		return probabilities;
	}
43895
protected void moveSelectionDown() {
		final IStructuredSelection selection = this.list.getStructuredSelection();
		final int index = this.conversions.indexOf(selection.getFirstElement());
		if (index >= 0 && (index + selection.size()) < this.conversions.size()) {
			final ConversionMapping next = this.conversions.remove(index + selection.size());
			this.conversions.add(index, next);
			refreshListUI();
			this.list.refresh(true);
			enableButtons();
			preferenceValueChanged();
		}
	}
572414
def p(i, sample_size, weights):
        

        # Determine the initial pick values
        weight_i = weights[i]
        weights_sum = sum(weights)

        # Build a list of weights that don't contain the weight `i`. This list will
        # be used to build the possible picks before weight `i`.
        other_weights = list(weights)
        del other_weights[i]

        # Calculate the probability
        probability_of_i = 0
        for picks in range(0, sample_size):

            # Build the list of possible permutations for this pick in the sample
            permutations = list(itertools.permutations(other_weights, picks))

            # Calculate the probability for this permutation
            permutation_probabilities = []
            for permutation in permutations:

                # Calculate the probability for each pick in the permutation
                pick_probabilities = []
                pick_weight_sum = weights_sum

                for pick in permutation:
                    pick_probabilities.append(pick / pick_weight_sum)

                    # Each time we pick we update the sum of the weight the next
                    # pick is from.
                    pick_weight_sum -= pick

                # Add the probability of picking i as the last pick
                pick_probabilities += [weight_i / pick_weight_sum]

                # Multiply all the probabilities for the permutation together
                permutation_probability = reduce(
                    lambda x, y: x * y, pick_probabilities
                    )
                permutation_probabilities.append(permutation_probability)

            # Add together all the probabilities for all permutations together
            probability_of_i += sum(permutation_probabilities)

        return probability_of_i
839681
function normalizeSelection(ranges, primIndex) {
    var prim = ranges[primIndex];
    ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
    primIndex = indexOf(ranges, prim);
    for (var i = 1; i < ranges.length; i++) {
      var cur = ranges[i], prev = ranges[i - 1];
      if (cmp(prev.to(), cur.from()) >= 0) {
        var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
        var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
        if (i <= primIndex) --primIndex;
        ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
      }
    }
    return new Selection(ranges, primIndex);
  }
655860
public void sort(IndexedSortable s, int p, int r) {
    sort(s, p, r, null);
  }
317301
def population(self):
        ""
        try:
            return self._p
        except AttributeError:
            self._p = self._population_class(base=self,
                                             tournament_size=self._tournament_size,
                                             classifier=self.classifier,
                                             labels=self._labels,
                                             es_extra_test=self.es_extra_test,
                                             popsize=self._popsize,
                                             random_generations=self._random_generations,
                                             negative_selection=self._negative_selection)
            return self._p
50316
public void sortbyselection(List<String> sortFlds, List<Integer> sortDirs) {
		moveToId(-1);
		int i = 0;
		while (super.next()) {
			int minId = findSmallestFrom(i, sortFlds, sortDirs);
			if (minId != i) {
				swapRecords(i, minId);
			}
			moveToId(i);
			i++;
		}
	}
528324
function(){
    var s = this.selection.selection;
    return Math.abs(s.second.x - s.first.x) >= 5 || 
           Math.abs(s.second.y - s.first.y) >= 5;
  }
942806
def tournament(self, negative=False):
        """"""
        if self.generation <= self._random_generations and not negative:
            return self.random_selection()
        if not self._negative_selection and negative:
            return self.random_selection(negative=negative)
        vars = self.random()
        fit = [(k, self.population[x].fitness) for k, x in enumerate(vars)]
        if negative:
            fit = min(fit, key=lambda x: x[1])
        else:
            fit = max(fit, key=lambda x: x[1])
        index = fit[0]
        return vars[index]
793915
public static void descendingOrder(DMatrixRMaj U , boolean tranU ,
                                       DMatrixRMaj W ,
                                       DMatrixRMaj V , boolean tranV )
    {
        int numSingular = Math.min(W.numRows,W.numCols);

        checkSvdMatrixSize(U, tranU, W, V, tranV);

        for( int i = 0; i < numSingular; i++ ) {
            double bigValue=-1;
            int bigIndex=-1;

            // find the smallest singular value in the submatrix
            for( int j = i; j < numSingular; j++ ) {
                double v = W.get(j,j);

                if( v > bigValue ) {
                    bigValue = v;
                    bigIndex = j;
                }
            }

            // only swap if the current index is not the smallest
            if( bigIndex == i)
                continue;

            if( bigIndex == -1 ) {
                // there is at least one uncountable singular value.  just stop here
                break;
            }

            double tmp = W.get(i,i);
            W.set(i,i,bigValue);
            W.set(bigIndex,bigIndex,tmp);

            if( V != null ) {
                swapRowOrCol(V, tranV, i, bigIndex);
            }

            if( U != null ) {
                swapRowOrCol(U, tranU, i, bigIndex);
            }
        }
    }
588076
public void create() {
    GeneticConfiguration cfg =
      new GeneticConfiguration(config, mutation_rate, recombination_rate,
                               evolve_comparators);
    population = new ArrayList(size);
    int ix = 0;
    for (; ix < copies_of_original; ix++)
      population.add(cfg.makeCopy());
    for (; ix < size; ix++)
      population.add(cfg.makeRandomCopy());
  }

  /**
   * Returns all configurations in the current generation.
   */
  public List<GeneticConfiguration> getConfigs() {
    return population;
  }

  public void setNewGeneration(List<GeneticConfiguration> nextgen) {
    this.population = nextgen;
  }

  /**
   * Sorts the population by their achieved F-numbers.
   */
  public void sort() {
    Collections.sort(population);
    for (int ix = 0; ix < population.size(); ix++)
      population.get(ix).setRank(ix + 1);
  }

  /**
   * Returns the best configuration.
   */
  public GeneticConfiguration getBestConfiguration() {
    return population.get(0);
  }

  /**
   * Returns the worst configuration.
   */
  public GeneticConfiguration getWorstConfiguration() {
    return population.get(population.size() - 1);
  }

  /**
   * Returns a random configuration.
   */
  public GeneticConfiguration pickRandomConfig() {
    return population.get((int) Math.random() * population.size());
  }

  /**
   * Runs a tournament among k individuals to find the most fit
   * individual.
   */
  public GeneticConfiguration runTournament(int k) {
    GeneticConfiguration best = pickRandomConfig();
    for (int ix = 1; ix < k; ix++) {
      GeneticConfiguration candidate = pickRandomConfig();
      if (candidate.getFNumber() > best.getFNumber())
        best = candidate;
    }
    return best;
  }

  /**
   * Sets the size of the population.
   */
  public void setSize(int size) {
    this.size = size;
  }

  public void setMutationRate(int mutation_rate) {
    this.mutation_rate = mutation_rate;
  }

  public void setRecombinationRate(double recombination_rate) {
    this.recombination_rate = recombination_rate;
  }

  public void setEvolveComparators(boolean evolve_comparators) {
    this.evolve_comparators = evolve_comparators;
  }

  public void setCopiesOfOriginal(int copies) {
    this.copies_of_original = copies;
  }

  /**
   * Returns the size of the population.
   */
  public int size() {
    return size;
  }
}
570716
def rankingEval(self):
		'''
		
		'''
		fitnessAll = numpy.zeros(self.length)
		fitnessNorm = numpy.zeros(self.length)

		for i in range(self.length):
			self.Ind[i].fitnessEval()
			fitnessAll[i] = self.Ind[i].fitness

		maxFitness = fitnessAll.max()
		for i in range(self.length):
			fitnessNorm[i] = (maxFitness - fitnessAll[i]) / maxFitness
		fitnessSorted = fitnessNorm.argsort()

		# Compute the selection probabilities of each individual
		probability = numpy.zeros(self.length)
		S = 2.0
		for i in range(self.length):
			probability[fitnessSorted[i]] = ((2-S)/self.length) + (2*i*(S-1))/(self.length*(self.length-1))
		self.rankingComputed = 1
		self.fitness = 	fitnessAll

		return [fitnessAll, fitnessSorted[::-1], probability]
236435
public void nondominated_sorting_delete(S indiv) {

    // find the non-domination level of 'indiv'
    //int indivRank = indiv.getRank();
    int indivRank = (int) indiv.getAttribute(ranking.getAttributeIdentifier());

    ArrayList<Integer> curLevel = new ArrayList<>();  // used to keep the solutions in the current non-domination level
    ArrayList<Integer> dominateList = new ArrayList<>();  // used to keep the solutions need to be moved

    for (int i = 0; i < populationSize; i++) {
      if (rankIdx[indivRank][i] == 1) {
        curLevel.add(i);
      }
    }

    int flag;
    // find the solutions belonging to the 'indivRank+1'th level and are dominated by 'indiv'
    int investigateRank = indivRank + 1;
    if (investigateRank < numRanks) {
      for (int i = 0; i < populationSize; i++) {
        if (rankIdx[investigateRank][i] == 1) {
          flag = 0;
          if (checkDominance(indiv, population.get(i)) == 1) {
            for (int j = 0; j < curLevel.size(); j++) {
              if (checkDominance(population.get(i), population.get(curLevel.get(j))) == -1) {
                flag = 1;
                break;
              }
            }
            if (flag == 0) {  // the ith solution can move to the prior level
              dominateList.add(i);
              rankIdx[investigateRank][i] = 0;
              rankIdx[investigateRank - 1][i] = 1;
              //((DoubleSolution) population.get(i)).setRank(investigateRank - 1);
              population.get(i).setAttribute(ranking.getAttributeIdentifier(), investigateRank - 1);
            }
          }
        }
      }
    }

    int curIdx;
    int curListSize = dominateList.size();
    while (curListSize != 0) {
      curLevel.clear();
      for (int i = 0; i < populationSize; i++) {
        if (rankIdx[investigateRank][i] == 1) {
          curLevel.add(i);
        }
      }
      investigateRank = investigateRank + 1;

      if (investigateRank < numRanks) {
        for (int i = 0; i < curListSize; i++) {
          curIdx = dominateList.get(i);
          for (int j = 0; j < populationSize; j++) {
            if (j == populationSize) {
              System.err.println("There are problems");
            }
            if (rankIdx[investigateRank][j] == 1) {
              flag = 0;
              if (checkDominance(population.get(curIdx), population.get(j)) == 1) {
                for (int k = 0; k < curLevel.size(); k++) {
                  if (checkDominance(population.get(j), population.get(curLevel.get(k))) == -1) {
                    flag = 1;
                    break;
                  }
                }
                if (flag == 0) {
                  dominateList.add(j);
                  rankIdx[investigateRank][j] = 0;
                  rankIdx[investigateRank - 1][j] = 1;
                  //((DoubleSolution) population.get(j)).setRank(investigateRank - 1);
                  population.get(j).setAttribute(ranking.getAttributeIdentifier(), investigateRank - 1);
                }
              }
            }
          }
        }
      }
      for (int i = 0; i < curListSize; i++) {
        dominateList.remove(0);
      }

      curListSize = dominateList.size();
    }

  }
1017538
private SortedClassProbability[] sortByDescendingClassProbability(String[] domainValues, double[] classProbabilities) {
    assert (classProbabilities.length == domainValues.length);
    SortedClassProbability[] arr = new SortedClassProbability[domainValues.length];
    for (int i = 0; i < domainValues.length; i++) {
      arr[i] = new SortedClassProbability();
      arr[i].name = domainValues[i];
      arr[i].probability = classProbabilities[i];
    }
    Arrays.sort(arr, Collections.reverseOrder());
    return arr;
  }
1012329
def process(self, candidates):
        
        return sorted(candidates, key=attrgetter('score'), reverse=self.reverse)
853567
def process_selection(self, instance_count, node_reg, node_ids):
        # Select primaries for current view_no
        if instance_count == 0:
            return []

        '''
        
        '''

        primaries = []
        primary_rank = None

        for i in range(instance_count):
            if i == 0:
                primary_name = self._next_primary_node_name_for_master(node_reg, node_ids)
                primary_rank = self.node.get_rank_by_name(primary_name, node_reg, node_ids)
                if primary_rank is None:
                    raise LogicError('primary_rank must not be None')
            else:
                primary_name, _ = self.next_primary_replica_name_for_backup(
                    i, primary_rank, primaries, node_reg, node_ids)

            primaries.append(primary_name)
            logger.display("{} selected primary {} for instance {} (view {})"
                           .format(PRIMARY_SELECTION_PREFIX,
                                   primary_name, i, self.viewNo),
                           extra={"cli": "ANNOUNCE",
                                  "tags": ["node-election"]})
        if len(primaries) != instance_count:
            raise LogicError('instances inconsistency')

        if len(primaries) != len(set(primaries)):
            raise LogicError('repeating instances')

        return primaries
1003719
public void setSorting(List<SortProperty> newSorting) {
		Validate.notNull(newSorting, "Sorting required");

		if (!sorting.equals(newSorting)) {
			sorting.clear();
			sorting.addAll(newSorting);
			selectionIndex = -1;
			clearCache();
		}
	}