Formula to calculate:
idf(t) = 1 + log ( totalDocuments / (documentsThatContainTheTerm + 1))
@throws \Exception
432009
public function execute()
    {
        $db = $this->dbHandle;
        $db->/** @scrutinizer ignore-call */
        sqliteCreateFunction('log', 'log', 1);
        $sql = '
		INSERT INTO inverse_document_frequency (term, inverseDocumentFrequency)
		SELECT DISTINCT term, (1+(log(:documentCount / COUNT(documentPath) + 1))) AS inverseDocumentFrequency
					  FROM term_count
				  GROUP BY term
		';

        if (!$stmt = $db->prepare($sql)) {
            $errorInfo = $db->errorInfo();
            $errorMsg = $errorInfo[2];
            throw new \Exception('SQLite Exception: ' . $errorMsg . ' in SQL: <br /><pre>' . $sql . '</pre>');
        }
        $stmt->bindValue(':documentCount', $this->documentCount);
        $result = $stmt->execute();
        if ($result === false) {
            $errorInfo = $db->errorInfo();
            $errorMsg = $errorInfo[2];
            throw new \Exception('SQLite Exception: ' . $errorMsg . ' in SQL: <br /><pre>' . $sql . '</pre>');
        }
    }
1103274
public function score($docId, Zend_Search_Lucene_Interface $reader)
    {
        if (isset($this->_docVector[$docId])) {
            return $reader->getSimilarity()->tf($this->_termFreqs[$docId]) *
                   $this->_weight->getValue() *
                   $reader->norm($docId, $this->_term->field) *
                   $this->getBoost();
        } else {
            return 0;
        }
    }
1299734
def calculate_term_frequencies(self):
		
		for doc in self.processed_corpus:
			term_frequency_doc = defaultdict(int)
			for word in doc:
				term_frequency_doc[word] += 1
			
			for key,value in term_frequency_doc.iteritems():
				term_frequency_doc[key] = (1.0 * value) / len(doc)
			self.term_frequencies.append(term_frequency_doc)
810964
protected function getDocCommentPos(): ?int
    {
        if ($this->docCommentPos === -1) {
            $this->docCommentPos = $this->loadDocCommentPos();
        }

        return $this->docCommentPos;
    }
687088
public function actionIndex(): int
    {
        $dataTypes = $this->getDataTypes();
        $definitions = [];
        $overrideData = Data::parseYamlFile($this->overrideFile);

        $this->disableLogging();

        try {
            // Import from single file.
            if ($this->getStorageType() === self::SINGLE_FILE) {
                $definitions = $this->importDefinitionsFromFile($overrideData);
                $this->importFromDefinitions($dataTypes, $definitions);

                Schematic::info('Loaded schema from '.$this->file);
            }

            // Import from multiple files.
            if ($this->getStorageType() === self::MULTIPLE_FILES) {
                $definitions = $this->importDefinitionsFromDirectory($overrideData);
                $this->importFromDefinitions($dataTypes, $definitions);

                Schematic::info('Loaded schema from '.$this->path);
            }

            return 0;
        } catch (\Exception $e) {
            Schematic::error($e->getMessage());
            return 1;
        }
    }
1347287
public function findText()
    {
        $parameters = func_get_args();

        //set parameter values
        if (count($parameters) == 1) {
            $text = $parameters[0];
        } else if (count($parameters) == 2) {
            $WorkSheetName = $parameters[0];
            $text = $parameters[1];
        } else {
            throw new Exception('Invalid number of arguments');
        }
        $strURI = Product::$baseProductUri . '/cells/' . $this->getFileName() . ((count($parameters) == 2) ? '/worksheets/' . $WorkSheetName : '') . '/findText?text=' . $text;
        $signedURI = Utils::sign($strURI);
        $responseStream = Utils::processCommand($signedURI, 'POST', '', '');
        $json = json_decode($responseStream);
        return $json->TextItems->TextItemList;

    }
647184
public static BigDecimal calculate(String formula) throws Exception {
        formula = formula.replaceAll("\\s", "");
        if (isFormula(formula)) {
            return doCalculate(formula);
        } else {
            throw new Exception("calculation formula is not valid, please check up on it carefully.");
        }
    }
564807
public function getDocumentId($document, $throw = true)
    {
        $oid = is_object($document) ? spl_object_hash($document) : $document;
        if (empty($this->documentIds[$oid])) {
            if (!$throw) {
                return;
            }
            $msg = 'Document is not managed and has no id';
            if (is_object($document)) {
                $msg .= ': '.self::objToStr($document);
            }

            throw new PHPCRException($msg);
        }

        return $this->documentIds[$oid];
    }
1316206
public function getEntityLine()
    {
        if ($this->definition) {
            foreach (file($this->getEntityPath(), FILE_IGNORE_NEW_LINES)
                as $lineNumber => $line
            ) {
                if (strpos($line, $this->definition) !== false) {
                    return $lineNumber + 1;
                }
            }
        }
        return 0;
    }
213539
protected function _loadDocument() {
		$this->_Document = new DOMDocument();

		$reporting = error_reporting(0);
		$loaded = $this->_Document->loadHTML($this->_html);
		error_reporting($reporting);

		if (!$loaded) {
			throw new Exception('Unable to load HTML document.');
		}
	}
1280268
public function calculate($term)
    {
        $tokens = $this->tokenize($term);
        if (sizeof($tokens) == 0) {
            return 0;
        }

        $rootNode = $this->parse($tokens);
        if ($rootNode->isEmpty()) {
            return 0;
        }

        $calculator = $this->container->get('stringcalc_calculator');

        $result = $calculator->calculate($rootNode);

        return $result;
    }
1135250
public function calculateFormula($formula)
    {
        //check whether worksheet name is set or not
        if ($this->worksheetName == '')
            throw new Exception('Worksheet name not specified');
        $strURI = Product::$baseProductUri . '/cells/' . $this->getFileName() .
            '/worksheets/' . $this->worksheetName . '/formulaResult?formula=' . $formula;
        $signedURI = Utils::sign($strURI);
        $responseStream = Utils::processCommand($signedURI, 'GET', '', '');
        $json = json_decode($responseStream);
        return $json->Value->Value;

    }
1095241
protected function consolidate(): int
    {
        $bytes = 0;
        if ("\n" !== $this->newline) {
            $this->document->fseek(-1, SEEK_CUR);
            $bytes = $this->document->fwrite($this->newline, strlen($this->newline)) - 1;
        }

        if (null === $this->flush_threshold) {
            return $bytes;
        }

        ++$this->flush_counter;
        if (0 === $this->flush_counter % $this->flush_threshold) {
            $this->flush_counter = 0;
            $this->document->fflush();
        }

        return $bytes;
    }
840775
public function getDocumentScore()
    {
        if (!$this->valid()) {
            throw new \LogicException('Document score is available only while iterating over results.');
        }

        if (!isset($this->documents[$this->key]['_score'])) {
            return null;
        }

        return $this->documents[$this->key]['_score'];
    }
772033
function( term ) {
    
    var document_count
    var appearances = 1
    
    for( key in this.documents ) {
      this.documents[ key ][ term ]
        ? appearances++ : 0
    }
    
    document_count = Object.keys( this.documents )
    document_count = document_count.length + 1
    
    return Math.log( document_count / appearances )
    
  }
980312
function TFIDF (ops) {
  const calculateScore = (x, i, resultset) => {
    const idf = Math.log((global.D + 1) / resultset.length);
    x.score = +x.match.reduce(
      (acc, cur) => acc + idf * +cur.split(':')[1], 0
    ).toFixed(2); // TODO: make precision an option
    return x
  };
  return ops
    .resultSet
    .map(calculateScore)
  // sort by score descending
    .sort((a, b) => b.score - a.score)
  // limit to n hits
    .slice(ops.offset, ops.limit)
}
962316
public function processDocument(Document $document)
    {
        /** @var TableOfContents[] $tocs */
        $tocs = [];

        $headings = [];

        $document->heading_ids = [];
        $walker = $document->walker();
        while ($event = $walker->next()) {
            $node = $event->getNode();

            if ($node instanceof TableOfContents && !$event->isEntering()) {
                $tocs[] = $node;
                continue;
            }

            if (!($node instanceof Heading) || !$event->isEntering()) {
                continue;
            }

            $this->ensureHeadingHasId($document, $node);
            $headings[] = new Entry($node);
        }

        if (count($headings) && (count($tocs) || $this->hasAutoTOC())) {
            $generated = $this->generate($headings);

            if (count($tocs)) {
                foreach ($tocs as $toc) {
                    $toc->appendChild($this->render($generated->getChildren()));
                }
            } else {
                $document->prependChild($this->render($generated->getChildren()));
            }
        }
    }