/** * reverser polish notation * Input: * 3 * (a+(b*c)) * ((a+b)*(z+x)) * ((a+t)*((b+(a+c))^(c+d))) * a-b+c-d * * Output: * abc*+ * ab+zx+* * at+bac++cd+^* * ab-cd-+ * * * Author : Shikhar Subedi * * Problem code :ONP * * */ function spojONP() { $stringArray = takeInput(); foreach ($stringArray as $string) { $outputStack = reversePolish($string); printOutput($outputStack); } }
<link type='text/css' rel='stylesheet' href='css/styles.css' /> </head> <body> <?php include 'global/navigation.html'; ?> <div class="container-fluid" id="wrapper"> <div> <h4> 1. Create a function with no arguments/parameters and no return values that prints a message to the output. </h4> <hr /> <?php printOutput(); echo "\n"; ?> </div> <div> <h4> 2. Create a function that accepts multiple parameters and uses them to print a message to the screen. </h4> <hr /> <?php multiParameters("Rawr", "Meow", "Purr...."); echo "\n"; ?> </div> <div>
showApiError(300, 'No such item (the guid you provided has no release in our database)'); } break; // Get individual NZB details. // Get individual NZB details. case 'd': if (!isset($_GET['id'])) { showApiError(200, 'Missing parameter (id is required for downloading an NZB)'); } $page->users->addApiRequest($uid, $_SERVER['REQUEST_URI']); $data = $releases->getByGuid($_GET['id']); $relData = []; if ($data) { $relData[] = $data; } printOutput($relData, $outputXML, $page, offset()); break; // Capabilities request. // Capabilities request. case 'c': //get categories $category = new Category(['Settings' => $page->settings]); $cats = $category->getForMenu(); //insert cats into template variable $page->smarty->assign('parentcatlist', $cats); if ($outputXML) { //use apicaps.tpl if xml is requested $response = $page->smarty->fetch('apicaps.tpl'); header('Content-type: text/xml'); header('Content-Length: ' . strlen($response)); echo $response;
function OnePhaseDisambiguate($timeLimit = 0) { $startTime = time(); $phrases = $this->termArray->getAllPhrases(); if (count($phrases) == 0) { echo "Error: no terms available "; return false; } if (count($phrases) == 1) { // choose the first result, since there's no disambiguation // we can do anyways $this->ChooseResult($phrases[0], 0); return $this->termArray; } if (printOutput()) { echo "<br>Weights:<br>"; var_dump($this->weights); echo "<br>Alternate weights:<br>"; var_dump($this->alternateWeights); echo "<br>"; } while (!$this->doneDisambiguation() or !$this->donePhase1()) { if ($timeLimit > 0 and time() - $startTime > $timeLimit) { return false; } $this->UpdateWeights(); $this->UpdateScores(); if (printOutput()) { $this->PrintScoreTable(); echo "<br>Running the only phase of the 1 phase disambiguator<br>"; } $scoresToUse = []; foreach ($this->termArray->getAllTerms() as $term) { if (count($this->termArray->results[$term->phrase]) > 1 or $this->weights[$term->phrase][$term->position] != 1.0) { foreach ($this->termArray->results[$term->phrase] as $resultIndex => $result) { $scoresToUse[$term->phrase][$term->position][$resultIndex] = $this->scores[$term->phrase][$term->position][$resultIndex]; } } } $r = $this->FindBestPhrase($scoresToUse); if (printOutput()) { echo "The result with the best score is result {$r[2]} for phrase {$r[0]} at postition {$r[1]}<br><br>"; } $this->ChoosePhrase($r[0], $r[1]); $this->ChooseResult($r[0], $r[2]); } if (printOutput()) { echo "<br>Final score table:<br>"; $this->UpdateScores(); $this->PrintScoreTable(); } return $this->termArray; }
function run($text, $boundingBox = []) { $overallStartTime = microtime(true); $startTime = microtime(true); $this->parser = new TextParser(); $this->times["Create TextParser"] = microtime(true) - $startTime; $startTime = microtime(true); try { $full_results = $this->QueryNominatim($text, [], "10", $boundingBox); if (printOutput()) { echo "Query results for sending the entire text to Nominatim:<br>"; if ($full_results) { foreach ($full_results as $full_result) { echo $this->NominatimResultToString($full_result, "    "); } } else { echo "    No results found.<br>"; } echo "<br>"; } } catch (Exception $e) { echo "Error: unable to get results from Nominatim for the entire text."; } $this->times["Try sending full text to Nominatim"] = microtime(true) - $startTime; $startTime = microtime(true); $this->termArray = $this->parser->run($text); $this->times["Run text through TextParser"] = microtime(true) - $startTime; foreach ($this->parser->times as $parserDescription => $parserTime) { $this->times["TextParser: " . $parserDescription] = $parserTime; } $startTime = microtime(true); $this->SearchAll([], "10", $boundingBox); $this->times["Send all terms to Nominatim"] = microtime(true) - $startTime; $startTime = microtime(true); $this->termArray->removeTermsWithoutSearchResults(); $this->times["Discard terms that don't have search results"] = microtime(true) - $startTime; $startTime = microtime(true); $this->disambiguator = new WeightedInverseFrequency1PhaseDisambiguator($this->termArray); $this->times["Create disambiguator"] = microtime(true) - $startTime; $startTime = microtime(true); $disambiguatedTermArray = $this->disambiguator->Disambiguate(); $this->times["Run disambiguator"] = microtime(true) - $startTime; if (printOutput()) { echo "<br>"; $disambiguatedTermArray->PrintAllResults($this); } $this->times["TOTAL"] = microtime(true) - $overallStartTime; return $disambiguatedTermArray; }
while ($cart = mysql_fetch_array($rv, MYSQL_ASSOC)) { $output = array($cart['cartID'], -1, $cart['type'], $cart['type'], $cart['type'], $cart['title'], $cart['issuer'], $cart['type'], $cart['filename']); $final_output[] = $output; } // PHASE ONE :: Search by track name $qy = sprintf("SELECT * FROM `libtrack` \n\t\tWHERE airabilityID <= 1 \n\t\tAND file_name != '' \n\t\tAND %s", allWordsIn($input, "track_name")); //echo $qy; $rw = mysql_query($qy) or die("Line " . __LINE__ . ": " . mysql_error()); while ($track = mysql_fetch_array($rw, MYSQL_ASSOC)) { $cdid = $track['albumID']; $qz = sprintf("SELECT * FROM `libartist`, `libalbum`, `liblabel`, `def_rotations` \n\t\t\tWHERE libalbum.albumID = '%s' \n\t\t\tAND libalbum.artistID = libartist.artistID \n\t\t\tAND libalbum.labelID = liblabel.labelID \n\t\t\tAND def_rotations.rotationID = libalbum.rotationID\n\t\t\tLIMIT 1", $cdid); $rx = mysql_query($qz) or die("Line " . __LINE__ . ": " . mysql_error()); $album = mysql_fetch_array($rx, MYSQL_ASSOC); $output = array($album['album_code'], $track['track_num'], $album['genre'], substr($album['rotation_bin'], 0, 1), $album['artist_name'], $track['track_name'], $album['album_name'], $album['label'], $track['file_name']); $final_output[] = $output; } // PHASE TWO :: Search by album name and artist name and albumNo $qw = sprintf("SELECT * FROM `libartist`, `libalbum`, `liblabel`, `def_rotations` \n\t\tWHERE libalbum.artistID = libartist.artistID \n\t\tAND libalbum.labelID = liblabel.labelID \n\t\tAND def_rotations.rotationID = libalbum.rotationID\n\t\tAND %s", allWordsIn($input, array("libalbum.album_name", "libartist.artist_name", "libalbum.album_code"))); //echo $qw."\n"; $ru = mysql_query($qw) or die("Line " . __LINE__ . ": " . mysql_error()); while ($album = mysql_fetch_array($ru, MYSQL_ASSOC)) { $cdid = $album['albumID']; $qx = sprintf("SELECT track_name, track_num, file_name \n\t\t\tFROM `libtrack` \n\t\t\tWHERE airabilityID <= 1 \n\t\t\tAND file_name != '' \n\t\t\tAND albumID='%s'", $cdid); $rv = mysql_query($qx) or die(mysql_error()); while ($track = mysql_fetch_array($rv, MYSQL_ASSOC)) { $output = array($album['album_code'], $track['track_num'], $album['genre'], substr($album['rotation_bin'], 0, 1), $album['artist_name'], $track['track_name'], $album['album_name'], $album['label'], $track['file_name']); $final_output[] = $output; } } printOutput($final_output); //
$cdcodes[] = $cdcode; $output = array(); $output[] = $cdcode; //0 $output[] = $trnum; $output[] = $cd['genre']; $output[] = substr($cd['rotation_bin'], 0, 1); $output[] = $cd['artist_name']; $output[] = $track['track_name']; $output[] = $cd['album_name']; $output[] = $cd['label']; $output[] = $track['file_name']; //8 $final_output[] = $output; } } return $final_output; } /* require the plist to have 10 valid tracks - otherwise it's too short for cohesion */ $list = genBestOfPlaylist($showid); while (count($list) < $min_tracks) { $list = genBestOfPlaylist($showid); $showid = nextShowID($showid); if ($showid == -1) { $showid = getNewShowID(-1); } $list = genBestOfPlaylist($showid); } echo "SHOWID " . $showid . "\n"; printOutput($list);
$compiler = new htmlCompiler(); $compiler->source = $page->source; if ($GLOBALS['pie']['page_header'] || $GLOBALS['pie']['page_footer']) { // Header and footer require meta data. $compiler->meta = $page->meta; } if (!$compiler->compile()) { if (count($compiler->error) && empty($compiler->output)) { pieError("CompilerError"); } } // Update cache, if necessary. if ($GLOBALS['pie']['page_caching']) { if (!($f = fopen($cache->file($cid), 'w'))) { pieError("CacheWriteError"); } if (!fwrite($f, $compiler->output)) { pieError("CacheWriteError"); } fclose($f); } // Display result: if (@$_REQUEST['referer']) { if (substr($compiler->output, 0, 3) == "<h1") { list($header, $compiler->output) = explode("\n", $compiler->output, 2); print "{$header}\n"; } printReferer(); } printOutput($compiler->output); pieTail();
function run($text) { // The following appear in some Wikipedia texts and mess up the parsing: $textsToRemove = ["<br>", "</table>", "</dl>", "</ref>", "<ns>", "</ns>", "<id>", "</id>", "<small>", "<revision>", "<comment>", "</comment>", "<model>", "</model>", "<parentid>", "</parentid>"]; $text = str_replace($textsToRemove, "", $text); $currentDir = getcwd(); // needed for absolute paths to Stanford models $termArray = new TermArray(); $startTime = microtime(true); if (!function_exists("splitIntoWords")) { // The POS and NER taggers need an array of arrays, where each sentence is // it's own array. function splitIntoWords($sentence) { return explode(' ', $sentence); } } $text_arrays = array_map("splitIntoWords", explode('.', $text)); // Send the text to the POS tagger: $pos = new \StanfordNLP\POSTagger($currentDir . '/stanford-postagger-2015-04-20/models/english-left3words-distsim.tagger', $currentDir . '/stanford-postagger-2015-04-20/stanford-postagger.jar'); $startTime = microtime(true); $resultPOS = $pos->batchTag($text_arrays)[0]; $this->times["Run the POS tagger"] = microtime(true) - $startTime; if (printOutput()) { echo "<br>POS results:<br>"; var_dump($resultPOS); echo "<br>"; } if (!$resultPOS) { echo "<br>ERROR: POS tagging failed<br>"; return false; } // Send the text to the NER: $ner = new \StanfordNLP\NERTagger($currentDir . '/stanford-ner-2015-04-20/classifiers/english.all.3class.distsim.crf.ser.gz', $currentDir . '/stanford-ner-2015-04-20/stanford-ner.jar'); $startTime = microtime(true); $resultNER = $ner->batchTag($text_arrays)[0]; $this->times["Run the NER tagger"] = microtime(true) - $startTime; if (printOutput()) { echo "<br>NER results:<br>"; var_dump($resultNER); echo "<br><br>"; } if (!$resultNER) { echo "<br>ERROR: NER tagging failed<br>"; return false; } // Later code assumes that $resultPOS and $resultNER are indexed identically. // I have only seen these errors returned when the text contains something like // "<br>" which is handled differently by each tagger if (count($resultPOS) != count($resultNER)) { echo "<br>ERROR: POS and NER tagging are not indexed the same!<br>"; return false; } $words = []; for ($i = 0, $size = count($resultNER); $i < $size; $i++) { if ($resultPOS[$i][0] != $resultNER[$i][0]) { echo "<br>ERROR: POS and NER tagging are not indexed the same!<br>"; return false; } $words[$i] = $resultNER[$i][0]; } // The next bunch of code loops through the text to find all terms $startTime = microtime(true); $currentStreak = 0; $streakContainsLocation = false; $streakContainsNoun = false; $isAfterPreposition = false; $isAfterConjunction = false; for ($i = 0, $size = count($resultPOS); $i < $size; $i++) { $isNoun = strncmp($resultPOS[$i][1], "NN", 2) == 0; $isAdjectiveOrNumber = (strcmp($resultPOS[$i][1], "CD") == 0 or strcmp($resultPOS[$i][1], "JJ") == 0); // adjective (so "first avenue" would catch the first) $isLocation = strcmp($resultNER[$i][1], "LOCATION") == 0; if ($isNoun or $isAdjectiveOrNumber or $isLocation) { $currentStreak++; if ($isLocation) { $streakContainsLocation = true; } if ($isNoun) { $streakContainsNoun = true; } } else { $streakContainsLocation = false; $streakContainsNoun = false; $currentStreak = 0; $isAfterConjunction = strcmp($resultPOS[$i][1], "CC") == 0; if (!$isAfterConjunction) { // reset $isAfterPreposition only if this is not after a conjuction // that way a text like "near Waterloo and Guelph" will tag both Waterloo // and Guelph as after a preposition $isAfterPreposition = (strcmp($resultPOS[$i][1], "IN") == 0 or strcmp($resultPOS[$i][1], "TO") == 0); if (strcmp($resultPOS[$i][0], "for") == 0) { // TODO: make this case insensitive? $isAfterPreposition = false; } } } if ($streakContainsLocation or $streakContainsNoun) { $phrase = $resultPOS[$i][0]; $subStreakContainsNoun = $isNoun; $subStreakContainsLocation = $isLocation; if ($isNoun or $isLocation) { $newTerm = $termArray->addTerm($phrase, $i); $newTerm->isNoun = $isNoun; $newTerm->isLocation = $isLocation; $newTerm->isAfterPreposition = $isAfterPreposition; } for ($j = 1; $j < $currentStreak; $j++) { $phrase = $resultPOS[$i - $j][0] . ' ' . $phrase; $subStreakContainsNoun = ($subStreakContainsNoun or strncmp($resultPOS[$i - $j][1], "NN", 2) == 0); $subStreakContainsLocation = ($subStreakContainsLocation or strcmp($resultNER[$i - $j][1], "LOCATION") == 0); if ($subStreakContainsLocation or $subStreakContainsNoun) { $newTerm = $termArray->addTerm($phrase, $i - $j); $newTerm->isNoun = $subStreakContainsNoun; $newTerm->isLocation = $subStreakContainsLocation; $newTerm->isAfterPreposition = $isAfterPreposition; } } } } $this->times["Loop through text to find locations"] = microtime(true) - $startTime; // Now we remove some terms from the array: $startTime = microtime(true); if ($termArray->terms) { if ($termArray->countLocations() > 0) { if (printOutput()) { echo "<br>This text contains words tagged as locations, so we will only consider those words.<br>"; } $termArray->removeNouns(false); $this->termTypeUsed = "Locations"; } else { if (printOutput()) { echo "<br>This text does not contain words tagged as locations, so we must only use nouns.<br>"; } if ($termArray->countNounsAfterPrepositions() > 0) { if (printOutput()) { echo "Some nouns occured after prepositions, so we will only use those.<br>"; } $termArray->removeNouns(true); $this->termTypeUsed = "NounsAfterPrep"; } else { $this->termTypeUsed = "Nouns"; } } } else { echo "Warning: no nouns or locations found in text."; $this->termTypeUsed = "None"; } $this->times["Filter terms that are found"] = microtime(true) - $startTime; // the rest of this code deals with postal codes $startTime = microtime(true); $CanadaPostCodes = []; $USZipCodes = []; $DutchPostCodes = []; preg_match_all('/\\b[a-zA-Z][0-9][a-zA-Z][\\s]?[0-9][a-zA-Z][0-9]\\b/', $text, $CanadaPostCodes); preg_match_all('/\\b[0-9]{5}([\\s\\-][0-9]{4})?\\b/', $text, $USZipCodes); preg_match_all('/\\b[0-9]{4}[\\s]?[a-zA-Z]{2}\\b/', $text, $DutchPostCodes); $this->times["Find postal codes in the text"] = microtime(true) - $startTime; $startTime = microtime(true); foreach ($CanadaPostCodes[0] as $postcode) { if (isset($termArray->terms[$postcode])) { // if the postcode already got in another way, we don't add it again foreach ($termArray->terms[$postcode] as $term) { $term->isPostcode = true; $term->postcodeCountry = "ca"; } } else { $positions = [-10]; $postcodeWords = explode(" ", $postcode); // all post codes have 1 or 2 words $firstWordPositions = array_keys($words, $postcodeWords[0]); if (count($postcodeWords) == 1) { $positions = $firstWordPositions; } else { foreach ($firstWordPositions as $firstWordPosition) { if ($words[$firstWordPosition + 1] == $postcodeWords[1]) { if ($positions == [-10]) { $positions = [$firstWordPosition]; } else { $postions[] = $firstWordPosition; } } } } foreach ($positions as $postcodePosition) { $newTerm = $termArray->addTerm($postcode, $postcodePosition); $newTerm->isPostcode = true; $newTerm->postcodeCountry = "ca"; } } } foreach ($USZipCodes[0] as $postcode) { if (isset($termArray->terms[$postcode])) { // if the postcode already got in another way, we don't add it again foreach ($termArray->terms[$postcode] as $term) { $term->isPostcode = true; $term->postcodeCountry = "us"; } } else { $positions = [-10]; $postcodeWords = explode(" ", $postcode); // all post codes have 1 or 2 words $firstWordPositions = array_keys($words, $postcodeWords[0]); if (count($postcodeWords) == 1) { $positions = $firstWordPositions; } else { foreach ($firstWordPositions as $firstWordPosition) { if ($words[$firstWordPosition + 1] == $postcodeWords[1]) { if ($positions == [-10]) { $positions = [$firstWordPosition]; } else { $postions[] = $firstWordPosition; } } } } foreach ($positions as $postcodePosition) { $newTerm = $termArray->addTerm($postcode, $postcodePosition); $newTerm->isPostcode = true; $newTerm->postcodeCountry = "us"; } } } foreach ($DutchPostCodes[0] as $postcode) { if (isset($termArray->terms[$postcode])) { // if the postcode already got in another way, we don't add it again foreach ($termArray->terms[$postcode] as $term) { $term->isPostcode = true; $term->postcodeCountry = "nl"; } } else { $positions = [-10]; $postcodeWords = explode(" ", $postcode); // all post codes have 1 or 2 words $firstWordPositions = array_keys($words, $postcodeWords[0]); if (count($postcodeWords) == 1) { $positions = $firstWordPositions; } else { foreach ($firstWordPositions as $firstWordPosition) { if ($words[$firstWordPosition + 1] == $postcodeWords[1]) { if ($positions == [-10]) { $positions = [$firstWordPosition]; } else { $postions[] = $firstWordPosition; } } } } foreach ($positions as $postcodePosition) { $newTerm = $termArray->addTerm($postcode, $postcodePosition); $newTerm->isPostcode = true; $newTerm->postcodeCountry = "nl"; } } } $this->times["Update metadata for post codes"] = microtime(true) - $startTime; return $termArray; }
$compiler->source = $page->source; if ($GLOBALS['pie']['page_header'] || $GLOBALS['pie']['page_footer']) { // Header and footer require meta data. $compiler->meta = $page->meta; } if (!$compiler->compile()) { if (count($compiler->error) && empty($compiler->output)) { pieError("CompilerError"); } } // Update cache, if necessary. if ($GLOBALS['pie']['page_caching']) { if (!($f = fopen($cache->file($cid), 'w'))) { pieError("CacheWriteError"); } if (!fwrite($f, $compiler->output)) { pieError("CacheWriteError"); } fclose($f); } // Display result: $output = $compiler->output; if ($_REQUEST['referer']) { $_REQUEST['page'] = $string; if (substr($output, 0, 3) == "<h1") { list($header, $output) = explode("\n", $output, 2); } $output = "{$header}\n" . getReferer() . $output; } printOutput($output);