Calculate && Format human readable ranking
178895
protected function makeRanking () : void
    {       
        $result = [];

        // Calculate ranking
        $done = array ();
        $rank = 1;

        while (count($done) < $this->_selfElection->countCandidates()) :
            $to_done = [];

            foreach ( $this->_StrongestPaths as $candidate_key => $challengers_key ) :
                if ( in_array($candidate_key, $done, true) ) :
                    continue;
                endif;

                $winner = true;

                foreach ($challengers_key as $beaten_key => $beaten_value) :
                    if ( in_array($beaten_key, $done, true) ) :
                        continue;
                    endif;

                    if ( $beaten_value < $this->_StrongestPaths[$beaten_key][$candidate_key] ) :
                        $winner = false;
                    endif;
                endforeach;

                if ($winner) :
                    $result[$rank][] = $candidate_key;

                    $to_done[] = $candidate_key;
                endif;
            endforeach;

            $done = array_merge($done, $to_done);

            $rank++;
        endwhile;

        $this->_Result = $this->createResult($result);
    }
307588
def classify(self, txt):
        '''
        
        '''
        ranks = []
        for lang, score in langid.rank(txt):
            if lang in self.preferred_languages:
                score += self.preferred_factor
            ranks.append((lang, score))
        ranks.sort(key=lambda x: x[1], reverse=True)
        return ranks[0][0]
719705
def dense_to_human_readable(dense_repr: Sequence[Sequence[int]], index_to_label: Dict[int, str]) -> List[List[str]]:
    

    transcripts = []
    for dense_r in dense_repr:
        non_empty_phonemes = [phn_i for phn_i in dense_r if phn_i != 0]
        transcript = [index_to_label[index] for index in non_empty_phonemes]
        transcripts.append(transcript)

    return transcripts
323010
function toHumanReadableSize(size, len) {
  if(!size) return '0B';
  if (!len || len <= 0) {
    len = 2;
  }
  var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  var i = Math.floor( Math.log(size) / Math.log(1024));
  return (size/Math.pow(1024, i)).toFixed(len) + units[i];
}
703482
def log_likelihood_rankings(data, params):
    """"""
    loglik = 0
    params = np.asarray(params)
    for ranking in data:
        for i, winner in enumerate(ranking[:-1]):
            loglik -= logsumexp(params.take(ranking[i:]) - params[winner])
    return loglik
191626
function calculateNodeScore (node, candidates) {
  const txt = node.text()
  let contentScore = 1

  // Ignore too small nodes
  if (txt.length < 25) {
    return
  }

  // Add points for any commas within this paragraph support Chinese commas
  const commas = txt.match(/[,，.。;；?？、]/g)
  if (commas && commas.length) {
    contentScore += commas.length
  }

  // For every 100 characters in this paragraph, add another point. Up to 3 points.
  contentScore += Math.min(Math.floor(txt.length / 100), 3)

  // If it has an article parent
  if (node.closest('article')) {
    contentScore += 25
  }

  // Initialize Parent and Grandparent
  // First initialize the parent node with contentScore / 1, then grandParentNode with contentScore / 2
  const parent = node.parent()

  if (parent && parent.length > 0) {
    scoreCandidate(parent, contentScore, candidates)
    const grandParent = parent.parent()
    if (grandParent && grandParent.length > 0) {
      scoreCandidate(grandParent, contentScore / 2, candidates)
    }
  }
}
298052
def percent_rank(expr, sort=None, ascending=True):
    
    return _rank_op(expr, PercentRank, types.float64, sort=sort, ascending=ascending)
295415
def _humanize_time(amount, units):
    """"""
    intervals = (1, 60, 60 * 60, 60 * 60 * 24, 604800, 2419200, 29030400)
    names = (
        ("second", "seconds"),
        ("minute", "minutes"),
        ("hour", "hours"),
        ("day", "days"),
        ("week", "weeks"),
        ("month", "months"),
        ("year", "years"),
    )

    result = []
    unit = [x[1] for x in names].index(units)
    # Convert to seconds
    amount = amount * intervals[unit]
    for i in range(len(names) - 1, -1, -1):
        a = int(amount) // intervals[i]
        if a > 0:
            result.append((a, names[i][1 % a]))
            amount -= a * intervals[i]
    return result
684548
def compare_report_print(sorted_list, scores, best_name):
    
    title_items = ["Rank", "Name", "Class-Score", "Overall-Score"]
    class_scores_len = map(lambda x: len(
        str(x["class"])), list(scores.values()))
    shifts = ["%-" +
              str(len(sorted_list) +
                  4) +
              "s", "%-" +
              str(max(map(lambda x: len(str(x)), sorted_list)) +
                  4) +
              "s", "%-" +
              str(max(class_scores_len) + 11) + "s"]
    result = ""
    result += "Best : " + str(best_name) + "\n\n"
    result += ("".join(shifts)
               ) % tuple(title_items[:-1]) + title_items[-1] + "\n"
    prev_rank = 0
    for index, cm in enumerate(sorted_list):
        rank = index
        if scores[sorted_list[rank]] == scores[sorted_list[prev_rank]]:
            rank = prev_rank
        result += ("".join(shifts)) % (str(rank + 1), str(cm),
                                       str(scores[cm]["class"])) + str(scores[cm]["overall"]) + "\n"
        prev_rank = rank
    if best_name is None:
        result += "\nWarning: " + COMPARE_RESULT_WARNING
    return result
128172
def create_ranking(ranking_tuples):
        
        return ",".join([str(r) for c, r in sorted(
                ranking_tuples,
                key=lambda x: x[0].pk
                )])
1301665
def result(self):
    """"""
    for value in six.itervalues(self.__result):
      value.sort(key = _humanSortKey)
    return self.__result
1231478
def rank_reference_paragraphs(wiki_title, references_content, normalize=True):
  """"""
  normalized_title = _normalize_text(wiki_title)
  title_tokens = _tokens_to_score(
      set(tokenizer.encode(text_encoder.native_to_unicode(normalized_title))))
  ref_paragraph_info = []
  doc_counts = collections.defaultdict(int)
  for ref in references_content:
    for paragraph in ref.split("\n"):
      normalized_paragraph = _normalize_text(paragraph)
      if cc_utils.filter_paragraph(normalized_paragraph):
        # Skip paragraph
        continue
      counts = _token_counts(normalized_paragraph, title_tokens)
      for token in title_tokens:
        if counts[token]:
          doc_counts[token] += 1
      content = normalized_paragraph if normalize else paragraph
      info = {"content": content, "counts": counts}
      ref_paragraph_info.append(info)

  for info in ref_paragraph_info:
    score = 0.
    for token in title_tokens:
      term_frequency = info["counts"][token]
      inv_doc_frequency = (
          float(len(ref_paragraph_info)) / max(doc_counts[token], 1))
      score += term_frequency * math.log(inv_doc_frequency)
    info["score"] = score

  ref_paragraph_info.sort(key=lambda el: el["score"], reverse=True)
  return [info["content"] for info in ref_paragraph_info]
780792
def guess_listing_type(lines, threshold=100):
    '''
    '''
    scores = {
        'unix': 0,
        'msdos': 0,
        'nlst': 0,
    }
    for line in lines:
        if not line:
            continue

        if re.search(r'---|r--|rw-|rwx', line):
            scores['unix'] += 1

        if '<DIR>' in line or re.search(r'^.{0,4}\d\d', line):
            scores['msdos'] += 1

        words = line.split(' ', 1)

        if len(words) == 1:
            scores['nlst'] += 1

        if max(scores.values()) > threshold:
            break

    top = max(scores.items(), key=lambda item: item[1])

    if top[1]:
        return top[0]
    else:
        return 'unknown'
282919
function filterCandidates (topCandidate, siblings, $) {
  const articleContent = $("<div id='readabilityArticle'></div>")
  const siblingScoreThreshold = Math.max(
    10,
    topCandidate.data('readabilityScore') * 0.3
  )

  siblings.each(function (index, elem) {
    const node = $(this)
    const type = node.get(0).name
    const score = node.data('readabilityScore')
    const children = siblings.contents().length
    let append = false

    if (node.is(topCandidate) || score > siblingScoreThreshold) {
      append = true
    }

    if (children > 0) {
      siblings.contents().each((index, elem) => {
        if (elem.name === 'img') {
          append = true
        }
      })
    }

    if (
      !append &&
      (type === 'p' ||
        type === 'ul' ||
        type === 'blockquote' ||
        type === 'pre' ||
        type === 'h2')
    ) {
      $(elem)
        .find('a')
        .each((index, elems) => {
          if ($(elems).text().length > 1) {
            return
          }
          if (elems.name === 'a') {
            $(elems).remove()
          }
        })

      const linkDensity = getLinkDensity(node, $)
      const len = node.text().length
      if (len < 3) {
        return
      }

      if (len > 80 && linkDensity < 0.25) {
        append = true
      } else if (
        len < 80 &&
        linkDensity === 0 &&
        node.text().replace(regexps.trimRe, '').length > 0
      ) {
        append = true
      }
    }

    if (append) {
      articleContent.append(node)
    }
  })

  return articleContent
}
529305
def rank(self, value):
        ''''''
        value = self.value_pickler.dumps(value)
        return self.backend_structure().rank(value)
384272
def main(args):
    '''
    '''
    
    print("\nNote it's very possible that this doesn't work correctly so take what it gives with a bucketload of salt\n")

    #########################
    #                       #
    #                       #
    #         prompt        #
    #                       #
    #                       #
    #########################

    if not len(sys.argv) > 1:
        initialAnswers = askInitial()

        inputPath = pathlib.Path(initialAnswers['inputPath'])
        year = int(initialAnswers['year'])
        # create a list from every row
        badFormat = badFormater(inputPath)  # create a list from every row
        howManyCandidates = len(badFormat) - 1

        length = int(len(badFormat['Cand'])/2)
        finalReturn = []

        if "Get your rank in the year" in initialAnswers['whatToDo']:
            candidateNumber = askCandidateNumber()
            weightedAverage = myGrades(year, candidateNumber, badFormat, length)
            rank = myRank(weightedAverage, badFormat, year, length)

            if "Get your weighted average" in initialAnswers['whatToDo']:
                finalReturn.append('Your weighted average for the year is: {:.2f}%'.format(
                    weightedAverage))

            finalReturn.append('Your rank is {}th of {} ({:.2f} percentile)'.format(
                rank, howManyCandidates, (rank * 100) / howManyCandidates))
        elif "Get your weighted average" in initialAnswers['whatToDo']:
            candidateNumber = askCandidateNumber()
            weightedAverage = myGrades(year, candidateNumber, badFormat, length)
            finalReturn.append('Your weighted average for the year is: {:.2f}%'.format(
                weightedAverage))

        if "Reformat results by module and output to csv" in initialAnswers['whatToDo']:

            formatOutputPath = pathlib.Path(askFormat())

            goodFormat = goodFormater(badFormat, formatOutputPath, year, length)

            if "Plot the results by module" in initialAnswers['whatToDo']:
                howPlotAsk(goodFormat)

        elif "Plot the results by module" in initialAnswers['whatToDo']:
            goodFormat = goodFormater(badFormat, None, year, length)
            howPlotAsk(goodFormat)

        [print('\n', x) for x in finalReturn]

    #########################
    #                       #
    #          end          #
    #         prompt        #
    #                       #
    #                       #
    #########################

    #########################
    #                       #
    #                       #
    #       run with        #
    #       cli args        #
    #                       #
    #########################

    if len(sys.argv) > 1:
        if not args.input:
            inputPath = pathlib.Path(askInput())
        else:
            inputPath = pathlib.Path(args.input)
        if not args.year:
            year = int(askYear())
        else:
            year = int(args.year)

        # create a list from every row
        badFormat = badFormater(inputPath)  # create a list from every row
        howManyCandidates = len(badFormat) - 1

        length = int(len(badFormat['Cand'])/2)
        finalReturn = []

        if args.rank:
            if not args.candidate:
                candidateNumber = askCandidateNumber()
            else:
                candidateNumber = args.candidate

            weightedAverage = myGrades(year, candidateNumber, badFormat, length)
            rank = myRank(weightedAverage, badFormat, year, length)

            if args.my:
                finalReturn.append('Your weighted average for the year is: {:.2f}%'.format(
                    weightedAverage))

            finalReturn.append('Your rank is {}th of {} ({:.2f} percentile)'.format(
                rank, howManyCandidates, (rank * 100) / howManyCandidates))

        elif args.my:
            if not args.candidate:
                candidateNumber = askCandidateNumber()
            else:
                candidateNumber = args.candidate

            weightedAverage = myGrades(year, candidateNumber, badFormat, length)
            finalReturn.append('Your weighted average for the year is: {:.2f}%'.format(
                weightedAverage))

        if args.format is not None:
            formatOutputPath = pathlib.Path(args.format)
            goodFormat = goodFormater(badFormat, formatOutputPath, year, length)

            if args.plot:
                howPlotArgs(goodFormat)
        elif args.plot:
            goodFormat = goodFormater(badFormat, None, year, length)
            howPlotArgs(goodFormat)

        [print('\n', x) for x in finalReturn]

    #########################
    #                       #
    #         end           #
    #       run with        #
    #       cli args        #
    #                       #
    #########################

    print('')
678813
def human_readable_hyp_ref(self, dense_decoded, dense_y):
        

        hyps = []
        refs = []
        for i in range(len(dense_decoded)):
            ref = [phn_i for phn_i in dense_y[i] if phn_i != 0]
            hyp = [phn_i for phn_i in dense_decoded[i] if phn_i != 0]
            ref = self.corpus.indices_to_labels(ref)
            hyp = self.corpus.indices_to_labels(hyp)
            refs.append(ref)
            hyps.append(hyp)

        return hyps, refs