See RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs
969871
def candidate_pair_priority(local, remote, ice_controlling):
    
    G = ice_controlling and local.priority or remote.priority
    D = ice_controlling and remote.priority or local.priority
    return (1 << 32) * min(G, D) + 2 * max(G, D) + (G > D and 1 or 0)
302713
private static void precedenceIfOverlap(ReconfigurationProblem rp, Slice d, Slice c) {
        Model csp = rp.getModel();
        //No need to place the constraints if the slices do not have a chance to overlap
        if (!(c.getHoster().isInstantiated() && !d.getHoster().contains(c.getHoster().getValue()))
                && !(d.getHoster().isInstantiated() && !c.getHoster().contains(d.getHoster().getValue()))
                ) {
            BoolVar eq = csp.boolVar(rp.makeVarLabel(d.getHoster(), "", c.getHoster(), "?"));
          rp.getModel().arithm(d.getHoster(), "=", c.getHoster()).reifyWith(eq);
          org.chocosolver.solver.constraints.Constraint leqCstr = rp.getModel().arithm(c.getEnd(), "<=", d.getStart());
            ChocoUtils.postImplies(rp, eq, leqCstr);
        }
    }
383908
def compute_rpo(self):
        
        nb = len(self.nodes) + 1
        for node in self.post_order():
            node.num = nb - node.po
        self.rpo = sorted(self.nodes, key=lambda n: n.num)
587952
def rcm_chip_order(machine):
    
    # Convert the Machine description into a placement-problem-style-graph
    # where the vertices are chip coordinate tuples (x, y) and each net
    # represents the links leaving each chip. This allows us to re-use the
    # rcm_vertex_order function above to generate an RCM ordering of chips in
    # the machine.
    vertices = list(machine)
    nets = []
    for (x, y) in vertices:
        neighbours = []
        for link in Links:
            if (x, y, link) in machine:
                dx, dy = link.to_vector()
                neighbour = ((x + dx) % machine.width,
                             (y + dy) % machine.height)

                # In principle if the link to chip is marked as working, that
                # chip should be working. In practice this might not be the
                # case (especially for carelessly hand-defined Machine
                # objects).
                if neighbour in machine:
                    neighbours.append(neighbour)
        nets.append(Net((x, y), neighbours))

    return rcm_vertex_order(vertices, nets)
997015
def prioritize():
    

    while True:
        hp_qs = Message.objects.high_priority().using('default')
        mp_qs = Message.objects.medium_priority().using('default')
        lp_qs = Message.objects.low_priority().using('default')
        while hp_qs.count() or mp_qs.count():
            while hp_qs.count():
                for message in hp_qs.order_by("when_added"):
                    yield message
            while hp_qs.count() == 0 and mp_qs.count():
                yield mp_qs.order_by("when_added")[0]
        while hp_qs.count() == 0 and mp_qs.count() == 0 and lp_qs.count():
            yield lp_qs.order_by("when_added")[0]
        if Message.objects.non_deferred().using('default').count() == 0:
            break
919229
def _process_pair(first_fn, second_fn, error_protocol):
    
    ebook = None
    metadata = None

    if _is_meta(first_fn) and not _is_meta(second_fn):    # 1st meta, 2nd data
        logger.debug(
            "Parsed: '%s' as meta, '%s' as data." % (first_fn, second_fn)
        )
        metadata, ebook = first_fn, second_fn
    elif not _is_meta(first_fn) and _is_meta(second_fn):  # 1st data, 2nd meta
        logger.debug(
            "Parsed: '%s' as meta, '%s' as data." % (second_fn, first_fn)
        )
        metadata, ebook = second_fn, first_fn
    elif _is_meta(first_fn) and _is_meta(second_fn):      # both metadata
        logger.debug(
            "Parsed: both '%s' and '%s' as meta." % (first_fn, second_fn)
        )
        return [
            _safe_read_meta_file(first_fn, error_protocol),
            _safe_read_meta_file(second_fn, error_protocol)
        ]
    else:                                                 # both data
        logger.debug(
            "Parsed: both '%s' and '%s' as data." % (first_fn, second_fn)
        )
        return [
            EbookFile(first_fn),
            EbookFile(second_fn)
        ]

    # process pairs, which were created in first two branches of the if
    # statement above
    pair = DataPair(
        metadata_file=_safe_read_meta_file(metadata, error_protocol),
        ebook_file=EbookFile(ebook)
    )
    if not pair.metadata_file:
        logger.error(
            "Can't parse MetadataFile '%s'. Continuing with data file '%s'." % (
                metadata, ebook
            )
        )
        return [pair.ebook_file]

    return [pair]
752042
@Override
    public int compareTo(Request<T> other) {
        Priority left = this.getPriority();
        Priority right = other.getPriority();

        // High-priority requests are "lesser" so they are sorted to the front.
        // Equal priorities are sorted by sequence number to provide FIFO ordering.
        return left == right ?
                this.sequence - other.sequence :
                right.ordinal() - left.ordinal();
    }
985839
public static List<EncodedPair> sortByNameAndValues(List<? extends EncodedPair> pairs){
       List<EncodedPair> sorted = new ArrayList<EncodedPair>(pairs);
       Collections.sort(sorted, PAIR_NAME_VALUE_COMPARATOR);
       return sorted;
    }
570184
def _parity_interaction(q0: ops.Qid,
                        q1: ops.Qid,
                        rads: float,
                        atol: float,
                        gate: Optional[ops.Gate] = None):
    """"""

    if abs(rads) < atol:
        return

    if gate is not None:
        g = cast(ops.Gate, gate)
        yield g.on(q0), g.on(q1)

    yield MS(-1 * rads).on(q0, q1)

    if gate is not None:
        g = protocols.inverse(gate)
        yield g.on(q0), g.on(q1)
1245317
private static void quickSort(int[] data, final int start, final int end, Comparator<? super DBIDRef> comp, IntegerDBIDVar vl, IntegerDBIDVar vk, IntegerDBIDVar vr) {
    final int len = end - start;
    if(len < INSERTION_THRESHOLD) {
      // Classic insertion sort.
      for(int i = start + 1; i <= end; i++) {
        for(int j = i; j > start; j--) {
          vl.internalSetIndex(data[j]);
          vr.internalSetIndex(data[j - 1]);
          if(comp.compare(vl, vr) < 0) {
            int tmp = data[j - 1];
            data[j - 1] = data[j];
            data[j] = tmp;
          }
          else {
            break;
          }
        }
      }
      return;
    }

    // Choose pivots by looking at five candidates.
    final int seventh = (len >> 3) + (len >> 6) + 1;
    final int m3 = (start + end) >> 1; // middle
    final int m2 = m3 - seventh;
    final int m1 = m2 - seventh;
    final int m4 = m3 + seventh;
    final int m5 = m4 + seventh;

    // Explicit (and optimal) sorting network for 5 elements
    // See Knuth for details.
    if(compare(vl, data[m1], vk, data[m2], comp) > 0) {
      int tmp = data[m2];
      data[m2] = data[m1];
      data[m1] = tmp;
    }
    if(compare(vl, data[m1], vk, data[m3], comp) > 0) {
      int tmp = data[m3];
      data[m3] = data[m1];
      data[m1] = tmp;
    }
    if(compare(vl, data[m2], vk, data[m3], comp) > 0) {
      int tmp = data[m3];
      data[m3] = data[m2];
      data[m2] = tmp;
    }
    if(compare(vl, data[m4], vk, data[m5], comp) > 0) {
      int tmp = data[m5];
      data[m5] = data[m4];
      data[m4] = tmp;
    }
    if(compare(vl, data[m1], vk, data[m4], comp) > 0) {
      int tmp = data[m4];
      data[m4] = data[m1];
      data[m1] = tmp;
    }
    if(compare(vl, data[m3], vk, data[m4], comp) > 0) {
      int tmp = data[m4];
      data[m4] = data[m3];
      data[m3] = tmp;
    }
    if(compare(vl, data[m2], vk, data[m5], comp) > 0) {
      int tmp = data[m5];
      data[m5] = data[m2];
      data[m2] = tmp;
    }
    if(compare(vl, data[m2], vk, data[m3], comp) > 0) {
      int tmp = data[m3];
      data[m3] = data[m2];
      data[m2] = tmp;
    }
    if(compare(vl, data[m4], vk, data[m5], comp) > 0) {
      int tmp = data[m5];
      data[m5] = data[m4];
      data[m4] = tmp;
    }

    // Choose the 2 and 4th as pivots, as we want to get three parts
    // Copy to variables v1 and v3, replace them with the start and end
    // Note: do not modify v1 or v3 until we put them back!
    vl.internalSetIndex(data[m2]);
    vr.internalSetIndex(data[m4]);
    data[m2] = data[start];
    data[m4] = data[end];

    // A tie is when the two chosen pivots are the same
    final boolean tied = comp.compare(vl, vr) == 0;

    // Insertion points for pivot areas.
    int left = start + 1;
    int right = end - 1;

    // Note: we merged the ties and no ties cases.
    // This likely is marginally slower, but not at a macro level
    // And you never know with hotspot.
    for(int k = left; k <= right; k++) {
      int tmp = data[k];
      vk.internalSetIndex(tmp);
      final int c = comp.compare(vk, vl);
      if(c == 0) {
        continue;
      }
      else if(c < 0) {
        // Traditional quicksort
        data[k] = data[left];
        data[left] = tmp;
        left++;
      }
      else if(tied || comp.compare(vk, vr) > 0) {
        // Now look at the right. First skip correct entries there, too
        while(true) {
          vk.internalSetIndex(data[right]);
          if(comp.compare(vk, vr) > 0 && k < right) {
            right--;
          }
          else {
            break;
          }
        }
        // Now move tmp from k to the right.
        data[k] = data[right];
        data[right] = tmp;
        right--;
        // Test the element we just inserted: left or center?
        vk.internalSetIndex(data[k]);
        if(comp.compare(vk, vl) < 0) {
          tmp = data[k];
          data[k] = data[left];
          data[left] = tmp;
          left++;
        } // else: center. cannot be on right.
      }
    }
    // Put the pivot elements back in.
    // Remember: we must not modify v1 and v3 above.
    data[start] = data[left - 1];
    data[left - 1] = vl.internalGetIndex();
    data[end] = data[right + 1];
    data[right + 1] = vr.internalGetIndex();
    // v1 and v3 are now safe to modify again. Perform recursion:
    quickSort(data, start, left - 2, comp, vl, vk, vr);
    // Handle the middle part - if necessary:
    if(!tied) {
      // TODO: the original publication had a special tie handling here.
      // It shouldn't affect correctness, but probably improves situations
      // with a lot of tied elements.
      quickSort(data, left, right, comp, vl, vk, vr);
    }
    quickSort(data, right + 2, end, comp, vl, vk, vr);
  }
813647
public static <T extends Comparable<T>> Pair<T, T> ordered(T lhs, T rhs) {
        return new MakeOrder<T>(new ComparableComparator<T>()).apply(lhs, rhs);
    }
1267869
def compute_post_order(graph, start_node)
      i = 1
      result = []
      visited = Set.new
      post_order_df = proc do |node|
        visited << node
        node.real_successors.each do |successor|
          post_order_df.call(successor) unless visited.include?(successor)
        end
        result << node
        node.post_order_number = i
        i += 1
      end
      post_order_df.call(start_node)
      result
    end
102254
def _dict_raise_on_duplicates(ordered_pairs):
    
    d = {}
    for k, v in ordered_pairs:
        if k in d:
           raise ValueError("duplicate key: %r" % (k,))
        else:
           d[k] = v
    return d
995652
def parmap(f, X, nprocs=multiprocessing.cpu_count()):
    
    q_in = multiprocessing.Queue(1)
    q_out = multiprocessing.Queue()

    proc = [multiprocessing.Process(target=fun, args=(f, q_in, q_out))
            for _ in range(nprocs)]
    for p in proc:
        p.daemon = True
        p.start()

    sent = [q_in.put((i, x)) for i, x in enumerate(X)]
    [q_in.put((None, None)) for _ in range(nprocs)]
    res = [q_out.get() for _ in range(len(sent))]

    [p.join() for p in proc]

    return [x for i, x in sorted(res)]
660897
public void processPacketAESCM(RawPacket pkt, int index) {
        long ssrc = pkt.getRTCPSSRC();

        /* Compute the CM IV (refer to chapter 4.1.1 in RFC 3711):
        *
        * k_s   XX XX XX XX XX XX XX XX XX XX XX XX XX XX
        * SSRC              XX XX XX XX
        * index                               XX XX XX XX
        * ------------------------------------------------------XOR
        * IV    XX XX XX XX XX XX XX XX XX XX XX XX XX XX 00 00
        *        0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
        */
        ivStore[0] = saltKey[0];
        ivStore[1] = saltKey[1];
        ivStore[2] = saltKey[2];
        ivStore[3] = saltKey[3];

        // The shifts transform the ssrc and index into network order
        ivStore[4] = (byte) (((ssrc >> 24) & 0xff) ^ this.saltKey[4]);
        ivStore[5] = (byte) (((ssrc >> 16) & 0xff) ^ this.saltKey[5]);
        ivStore[6] = (byte) (((ssrc >> 8) & 0xff) ^ this.saltKey[6]);
        ivStore[7] = (byte) ((ssrc & 0xff) ^ this.saltKey[7]);

        ivStore[8] = saltKey[8];
        ivStore[9] = saltKey[9];

        ivStore[10] = (byte) (((index >> 24) & 0xff) ^ this.saltKey[10]);
        ivStore[11] = (byte) (((index >> 16) & 0xff) ^ this.saltKey[11]);
        ivStore[12] = (byte) (((index >> 8) & 0xff) ^ this.saltKey[12]);
        ivStore[13] = (byte) ((index & 0xff) ^ this.saltKey[13]);

        ivStore[14] = ivStore[15] = 0;

        // Encrypted part excludes fixed header (8 bytes)  
        final int payloadOffset = 8;
        final int payloadLength = pkt.getLength() - payloadOffset;
        cipherCtr.process(cipher, pkt.getBuffer(), payloadOffset, payloadLength, ivStore);
    }
867655
private List<SequenceState<State, Observation, Path>> computeViterbiSequence(
            List<TimeStep<State, Observation, Path>> timeSteps, int originalGpxEntriesCount,
            QueryGraph queryGraph) {
        final HmmProbabilities probabilities
                = new HmmProbabilities(measurementErrorSigma, transitionProbabilityBeta);
        final ViterbiAlgorithm<State, Observation, Path> viterbi = new ViterbiAlgorithm<>();

        logger.debug("\n=============== Paths ===============");
        int timeStepCounter = 0;
        TimeStep<State, Observation, Path> prevTimeStep = null;
        int i = 1;
        for (TimeStep<State, Observation, Path> timeStep : timeSteps) {
            logger.debug("\nPaths to time step {}", i++);
            computeEmissionProbabilities(timeStep, probabilities);

            if (prevTimeStep == null) {
                viterbi.startWithInitialObservation(timeStep.observation, timeStep.candidates,
                        timeStep.emissionLogProbabilities);
            } else {
                computeTransitionProbabilities(prevTimeStep, timeStep, probabilities, queryGraph);
                viterbi.nextStep(timeStep.observation, timeStep.candidates,
                        timeStep.emissionLogProbabilities, timeStep.transitionLogProbabilities,
                        timeStep.roadPaths);
            }
            if (viterbi.isBroken()) {
                String likelyReasonStr = "";
                if (prevTimeStep != null) {
                    Observation prevGPXE = prevTimeStep.observation;
                    Observation gpxe = timeStep.observation;
                    double dist = distanceCalc.calcDist(prevGPXE.getPoint().lat, prevGPXE.getPoint().lon,
                            gpxe.getPoint().lat, gpxe.getPoint().lon);
                    if (dist > 2000) {
                        likelyReasonStr = "Too long distance to previous measurement? "
                                + Math.round(dist) + "m, ";
                    }
                }

                throw new IllegalArgumentException("Sequence is broken for submitted track at time step "
                        + timeStepCounter + " (" + originalGpxEntriesCount + " points). "
                        + likelyReasonStr + "observation:" + timeStep.observation + ", "
                        + timeStep.candidates.size() + " candidates: "
                        + getSnappedCandidates(timeStep.candidates)
                        + ". If a match is expected consider increasing max_visited_nodes.");
            }

            timeStepCounter++;
            prevTimeStep = timeStep;
        }

        return viterbi.computeMostLikelySequence();
    }
154628
def __priority(self, pr, repo, pkg):
        
        if (pr[0] == repo and pr[1].startswith("*") and
                pr[1].endswith("*")):
            if pr[1][1:-1] in pkg:
                self.black.append(self.__add(repo, pkg))
        elif pr[0] == repo and pr[1].endswith("*"):
            if pkg.startswith(pr[1][:-1]):
                self.black.append(self.__add(repo, pkg))
        elif pr[0] == repo and pr[1].startswith("*"):
            if pkg.endswith(pr[1][1:]):
                self.black.append(self.__add(repo, pkg))
        elif pr[0] == repo and "*" not in pr[1]:
            self.black.append(self.__add(repo, pkg))