This is the implementation of the equation number 5 in the paper
by Griffiths and Steyvers.

@return array The vector of probabilites for all topics as computed by the equation 5
966298
protected function conditionalDistribution($i,$w)
     {
         $p = array_fill_keys(range(0,$this->ntopics-1),0);
         for ($topic=0;$topic<$this->ntopics;$topic++) {
            if (isset($this->count_topics_words[$topic][$w]))
                $numerator = $this->count_topics_words[$topic][$w]+$this->b;
            else
                $numerator = $this->b;

            $numerator *= $this->count_docs_topics[$i][$topic]+$this->a;

            $denominator = $this->words_in_topic[$topic]+$this->voccnt*$this->b;
            $denominator *= $this->words_in_doc[$i]+$this->ntopics*$this->a;

            $p[$topic] = $numerator/$denominator;
         }

         // divide by sum to obtain probabilities
         $sum = array_sum($p);

         return array_map(
            function ($p) use ($sum) {
                return $p/$sum;
            },
            $p
         );
     }
514145
public function x()
    {
        // Load file
        $file = new \SplFileObject($this->storage('finals.all'));

        // Get instance MJD, and MJD at line 0
        $mjdQ = $this->mjd;
        $mjd0 = (int)substr($file->getCurrentLine(), 7, 8);

        // Check for requested MJD before first date
        if ($mjdQ < $mjd0) {
            return false;
        }

        // Determine nearest center pointer
        $p = $mjdQ - $mjd0 - 1;

        // Fix for values within |n| of lower bound
        if ($p < static::INTERP_C && $p > -static::INTERP_C) {
            $p = static::INTERP_C;
        }

        // Compile dataset
        $ds = [];
        for ($i = $p - static::INTERP_C; $i < $p + static::INTERP_C; $i++) {
            $file->seek($i);
            $line = $file->getCurrentLine();

            // Parse data from line
            $mjd = substr($line, 7, 8);
            $xf  = substr($line, 136, 9);
            $xp  = substr($line, 18, 9);

            // Use final value first, if not present use prediction
            $x = trim($xf) ? $xf : $xp;

            // Check if no dut1 data, error
            if (trim($x) == '') {
                return false;
            }

            // Add the data
            $ds[$i - $p + static::INTERP_C]['x'] = (float)$mjd;
            $ds[$i - $p + static::INTERP_C]['y'] = (float)$x;
        }

        // Interpolate pole x
        return $this->lagrangeInterp($mjdQ, $ds);
    }
164865
private function compoundCurve()
    {
        $values = array();
        $count  = $this->readCount();

        for ($i = 0; $i < $count; $i++) {
            $this->readByteOrder();

            $type = $this->readType();

            switch ($type) {
                case ($this->getDimensionedPrimitive(self::WKB_TYPE_LINESTRING)):
                    // no break
                case ($this->getDimensionedPrimitive(self::WKB_TYPE_CIRCULARSTRING)):
                    $value = $this->readPoints($this->readCount());
                    break;
                default:
                    throw new UnexpectedValueException($this->getBadTypeInTypeMessage($type, self::WKB_TYPE_COMPOUNDCURVE, array(self::WKB_TYPE_LINESTRING, self::WKB_TYPE_CIRCULARSTRING)));
            }

            $values[] = array(
                'type'  => $this->getTypeName($type),
                'value' => $value,
            );
        }

        return $values;
    }
184102
private double[] initProbability() {
        double[] prob = new double[ngramFrequencyData.getLanguageList().size()];
        if (priorMap != null) {
            //TODO analyze and optimize this code, looks like double copy.
            System.arraycopy(priorMap, 0, prob, 0, prob.length);
            for(int i=0;i<prob.length;++i) prob[i] = priorMap[i];
        } else {
            for(int i=0;i<prob.length;++i) prob[i] = 1.0 / ngramFrequencyData.getLanguageList().size();
        }
        return prob;
    }


    /**
     * update language probabilities with N-gram string(N=1,2,3)
     * @param count 1-n: how often the gram occurred.
     */
    private boolean updateLangProb(@NotNull double[] prob, @NotNull String ngram, int count, double alpha) {
        double[] langProbMap = ngramFrequencyData.getProbabilities(ngram);
        if (langProbMap==null) {
            return false;
        }
        if (logger.isTraceEnabled()) logger.trace(ngram + "(" + Util.unicodeEncode(ngram) + "):" + Util.wordProbToString(langProbMap, ngramFrequencyData.getLanguageList()));

        double weight = alpha / BASE_FREQ;
        if (ngram.length() >1) {
            if (prefixFactor !=1.0 && ngram.charAt(0)==' ') {
                weight *= prefixFactor;
            } else if (suffixFactor!=1.0 && ngram.charAt(ngram.length()-1)==' ') {
                weight *= suffixFactor;
            }
        }
        for (int i=0; i<prob.length; ++i) {
            for (int amount=0; amount<count; amount++) {
                prob[i] *= (weight + langProbMap[i]);
            }
        }
        return true;
    }


    /**
     * Returns the detected languages sorted by probabilities descending.
     * Languages with less probability than PROB_THRESHOLD are ignored.
     */
    @NotNull
    private List<DetectedLanguage> sortProbability(double[] prob) {
        List<DetectedLanguage> list = new ArrayList<>();
        //step 1: add all that have reached a minimal probability:
        for (int j=0;j<prob.length;++j) {
            double p = prob[j];
            if (p >= probabilityThreshold) {
                list.add(new DetectedLanguage(ngramFrequencyData.getLanguage(j), p));
            }
        }
        //step 2: sort in descending order
        if (list.size() >= 2) {
            Collections.sort(list, PROBABILITY_SORTING_COMPARATOR);
        }
        return list;
    }

}
501592
private function diagonals()
    {

        $diagonals = array_fill(0, 2, []);

        $diagonalIndexes = range(0, count($this->board) - 1);

        $diagonalIndexesReverse = array_reverse($diagonalIndexes);

        foreach ($diagonalIndexes as $index => $value) {

            array_push($diagonals[0], $this->board->getValue([$value, $value]));

            array_push($diagonals[1], $this->board->getValue([$value, $diagonalIndexesReverse[$index]]));
        }

        return $diagonals;
    }
1143748
public static function available_numofreviews_list() {
        $options = array();
        $options[30] = 30;
        $options[20] = 20;
        $options[15] = 15;
        for ($i = 10; $i >= 0; $i--) {
            $options[$i] = $i;
        }
        return $options;
    }
1085184
public function factors()
    {
        $number = $this->value;
        $limit = floor(sqrt(abs($number)));
        $ret = array();
        for ($x = 1; $x <= $limit; $x++) {
            if ($number % $x == 0) {
                $other = intval($number / $x);
                $ret[$x] = $x;
                $ret[$other] = $other;
            }
        }
        ksort($ret);
        return array_values($ret);
    }
180334
public function getMutationScoreIndicator(): float
    {
        $detectionRateAll = 0;
        $defeatedTotal = $this->killedCount + $this->timedOutCount + $this->errorCount;

        if ($this->totalMutantsCount) {
            $detectionRateAll = floor(100 * $defeatedTotal / $this->totalMutantsCount);
        }

        return $detectionRateAll;
    }
840291
public function build()
    {
        $this->checkIfOneTopicExist();

        if ($this->hasOnlyOneTopic()) {
            foreach ($this->conditions[0] as $topic) {
                return '/topics/'.$topic;
            }
        }

        return [
            'condition' => $this->topicsForFcm($this->conditions),
        ];
    }
137995
public function doPass()
    {
        /* Compute vectors */
        foreach ($this->Data as $Key => $Settings) {
            if ($Settings["Type"] != NODE_TYPE_CENTRAL) {
                unset($this->Data[$Key]["Vectors"]);

                $X1 = $Settings["X"];
                $Y1 = $Settings["Y"];

                /* Repulsion vectors */
                foreach ($this->Data as $Key2 => $Settings2) {
                    if ($Key != $Key2) {
                        $X2 = $this->Data[$Key2]["X"];
                        $Y2 = $this->Data[$Key2]["Y"];
                        $FreeZone = $this->Data[$Key2]["FreeZone"];

                        $Distance = $this->getDistance($X1, $Y1, $X2, $Y2);
                        $Angle = $this->getAngle($X1, $Y1, $X2, $Y2) + 180;

                        /* Nodes too close, repulsion occurs */
                        if ($Distance < $FreeZone) {
                            $Force = log(pow(2, $FreeZone - $Distance));
                            if ($Force > 1) {
                                $this->Data[$Key]["Vectors"][] = [
                                    "Type"  => "R",
                                    "Angle" => $Angle % 360,
                                    "Force" => $Force
                                ];
                            }
                        }
                    }
                }

                /* Attraction vectors */
                if (isset($Settings["Connections"])) {
                    foreach ($Settings["Connections"] as $ID => $NodeID) {
                        if (isset($this->Data[$NodeID])) {
                            $X2 = $this->Data[$NodeID]["X"];
                            $Y2 = $this->Data[$NodeID]["Y"];
                            $FreeZone = $this->Data[$Key2]["FreeZone"];

                            $Distance = $this->getDistance($X1, $Y1, $X2, $Y2);
                            $Angle = $this->getAngle($X1, $Y1, $X2, $Y2);

                            if ($Distance > $FreeZone) {
                                $Force = log(($Distance - $FreeZone) + 1);
                            } else {
                                $Force = log(($FreeZone - $Distance) + 1);
                                ($Angle = $Angle + 180);
                            }

                            if ($Force > 1) {
                                $this->Data[$Key]["Vectors"][] = [
                                    "Type"  => "A",
                                    "Angle" => $Angle % 360,
                                    "Force" => $Force
                                ];
                            }
                        }
                    }
                }
            }
        }

        /* Move the nodes accoding to the vectors */
        foreach ($this->Data as $Key => $Settings) {
            $X = $Settings["X"];
            $Y = $Settings["Y"];

            if (isset($Settings["Vectors"]) && $Settings["Type"] != NODE_TYPE_CENTRAL) {
                foreach ($Settings["Vectors"] as $ID => $Vector) {
                    $Type = $Vector["Type"];
                    $Force = $Vector["Force"];
                    $Angle = $Vector["Angle"];
                    $Factor = $Type == "A" ? $this->MagneticForceA : $this->MagneticForceR;

                    $X = cos(deg2rad($Angle)) * $Force * $Factor + $X;
                    $Y = sin(deg2rad($Angle)) * $Force * $Factor + $Y;
                }
            }

            $this->Data[$Key]["X"] = $X;
            $this->Data[$Key]["Y"] = $Y;
        }
    }
992039
private function _calculateNonConjunctionResult()
    {
        $requiredVectors      = array();
        $requiredVectorsSizes = array();
        $requiredVectorsIds   = array(); // is used to prevent arrays comparison

        $optional = array();

        foreach ($this->_subqueries as $subqueryId => $subquery) {
            if ($this->_signs[$subqueryId] === true) {
                // required
                $requiredVectors[]      = $subquery->matchedDocs();
                $requiredVectorsSizes[] = count(end($requiredVectors));
                $requiredVectorsIds[]   = $subqueryId;
            } elseif ($this->_signs[$subqueryId] === false) {
                // prohibited
                // Do nothing. matchedDocs() may include non-matching id's
                // Calculating prohibited vector may take significant time, but do not affect the result
                // Skipped.
            } else {
                // neither required, nor prohibited
                // array union
                $optional += $subquery->matchedDocs();
            }
        }

        // sort resvectors in order of subquery cardinality increasing
        array_multisort(
            $requiredVectorsSizes, SORT_ASC, SORT_NUMERIC,
            $requiredVectorsIds,   SORT_ASC, SORT_NUMERIC,
            $requiredVectors
        );

        $required = null;
        foreach ($requiredVectors as $nextResVector) {
            if($required === null) {
                $required = $nextResVector;
            } else {
                //$required = array_intersect_key($required, $nextResVector);

                /**
                 * This code is used as workaround for array_intersect_key() slowness problem.
                 */
                $updatedVector = array();
                foreach ($required as $id => $value) {
                    if (isset($nextResVector[$id])) {
                        $updatedVector[$id] = $value;
                    }
                }
                $required = $updatedVector;
            }

            if (count($required) == 0) {
                // Empty result set, we don't need to check other terms
                break;
            }
        }


        if ($required !== null) {
            $this->_resVector = &$required;
        } else {
            $this->_resVector = &$optional;
        }

        ksort($this->_resVector, SORT_NUMERIC);
    }
484065
public function numeric()
    {
        $ret = array();
        foreach (self::$ordinality as $part) {
            if ($part === self::STABILITY) {
                $ret[]= array_search($this->get($part), self::$stabilities);
            } else {
                $ret[]= $this->get($part);
            }
        }
        return $ret;
    }
236651
def compute_topic_document_probability
      outp = []

      @corpus.documents.each_with_index do |doc, idx|
        tops = [0.0] * num_topics
        ttl  = doc.counts.inject(0.0) { |sum, i| sum + i }
        phi[idx].each_with_index do |word_dist, word_idx|
          word_dist.each_with_index do |top_prob, top_idx|
            tops[top_idx] += Math.log(top_prob) * doc.counts[word_idx]
          end
        end
        tops = tops.map { |i| i / ttl }
        outp << tops
      end

      outp
    end
612862
public function getD()
    {
        for ($i = 0; $i < $this->n; ++$i) {
            $D[$i] = array_fill(0, $this->n, 0.0);
            $D[$i][$i] = $this->d[$i];
            if ($this->e[$i] == 0) {
                continue;
            }
            $o = ($this->e[$i] > 0) ? $i + 1 : $i - 1;
            $D[$i][$o] = $this->e[$i];
        }
        return new Matrix($D);
    }
1150951
private function arrayPair() {
    if ($this->currentType === '&') {
      return $this->writeVariable();
    }
    $node = $this->expr();
    if ($this->currentType === T_DOUBLE_ARROW) {
      $expr = $node;
      $node = new ArrayPairNode();
      $node->addChild($expr, 'key');
      $this->mustMatch(T_DOUBLE_ARROW, $node);
      if ($this->currentType === '&') {
        $node->addChild($this->writeVariable(), 'value');
      }
      else {
        $node->addChild($this->expr(), 'value');
      }
    }
    return $node;
  }
383169
public static function asArray()
    {
        return array(
            'DEF' => self::DEF,
            'RECT' => self::RECT,
            'CIRCLE' => self::CIRCLE,
            'POLY' => self::POLY,
            'ELLIPSE' => self::ELLIPSE
        );
    }
1286378
public int[] optimalCwaArray() {
    int[] arr = new int[numSamples()];
    for (int recall = 1; recall <= numSamples(); recall++) {
      arr[recall - 1] = precision(recall);
    }
    return arr;
  }