function OneQuery($query_key, $text, $limit = 1, $properties = null)
 {
     $url = 'http://tnrs.iplantc.org/tnrsm-svc/matchNames?retrieve=all&names=' . rawurlencode($text);
     $limit = 3;
     if (0) {
         file_put_contents('tmp/r.txt', "URL = {$url}\n", FILE_APPEND);
     }
     $json = get($url);
     if (0) {
         file_put_contents('tmp/r.txt', $json . "\n", FILE_APPEND);
     }
     $obj = json_decode($json);
     if (0) {
         file_put_contents('tmp/r.txt', print_r($obj, true), FILE_APPEND);
     }
     $n = min($limit, count($obj->items));
     for ($i = 0; $i < $n; $i++) {
         $hit = new stdclass();
         $hit->match = count($obj->items) == 1;
         $hit->name = $obj->items[$i]->acceptedName;
         similar_text($text, $hit->name, $hit->score);
         $hit->id = '';
         $this->StoreHit($query_key, $hit);
     }
 }
Ejemplo n.º 2
0
 function widget_lmee_by_talk($args)
 {
     extract($args);
     echo $before_widget;
     $lmee_popular_options = get_option('widget_lmee_popular');
     $title = '灌水区-这里很热闹';
     //设置默认的标题
     echo $before_title . $title . $after_title;
     $page_ID = 789;
     //用来作为公告栏的页面或者文章id
     $num = 5;
     //显示公告的条数
     echo '<ul class="by_talk">';
     $announcement = '';
     $comments = get_comments("number={$num}&post_id={$page_ID}");
     if (!empty($comments)) {
         $flg = 1;
         foreach ($comments as $comment) {
             if ($flg == 1) {
                 $li_title = $comment->comment_content;
                 if (similar_text($li_title, "<") > 0) {
                     //echo "is";
                     $start = stripos($li_title, "<");
                     //从前往后查找
                     $__li_title = strrev($li_title);
                     //反转字符串
                     $length = strlen($li_title) - $start - stripos($__li_title, ">");
                     $_li_title = substr_replace($li_title, "含引用", $start, $length);
                     $_li_html = substr_replace($li_title, "", $start, $length);
                     $announcement .= '<li class="by-talk-first"><a href="' . get_page_link($page_ID) . '#comment-' . $comment->comment_ID . '" title="' . $_li_title . '" rel="nofollow" target="_blank">' . $_li_html . '</a><br /><span style="color:#999;text-align:right;">(' . get_comment_date('Y/m/d H:i', $comment->comment_ID) . ')</span></li><hr />';
                 } else {
                     //echo "un";
                     $announcement .= '<li class="by-talk-first"><a href="' . get_page_link($page_ID) . '#comment-' . $comment->comment_ID . '" title="' . $li_title . '" rel="nofollow" target="_blank">' . convert_smilies($comment->comment_content) . '</a><br /><span style="color:#999;text-align:right;">(' . get_comment_date('Y/m/d H:i', $comment->comment_ID) . ')</span></li><hr />';
                 }
                 $flg++;
             } else {
                 $li_title = $comment->comment_content;
                 if (similar_text($li_title, "<") > 0) {
                     //echo "is";
                     $start = stripos($li_title, "<");
                     //从前往后查找
                     $__li_title = strrev($li_title);
                     //反转字符串
                     $length = strlen($li_title) - $start - stripos($__li_title, ">");
                     $_li_title = substr_replace($li_title, "含引用", $start, $length);
                     $_li_html = substr_replace($li_title, "", $start, $length);
                     $announcement .= '<li><a href="' . get_page_link($page_ID) . '#comment-' . $comment->comment_ID . '" title="' . $_li_title . '" rel="nofollow" target="_blank">' . $_li_html . '</a><br /><span style="color:#999;text-align:right;">(' . get_comment_date('Y/m/d H:i', $comment->comment_ID) . ')</span></li><hr />';
                 } else {
                     //echo "un";
                     $announcement .= '<li><a href="' . get_page_link($page_ID) . '#comment-' . $comment->comment_ID . '" title="' . $li_title . '" rel="nofollow" target="_blank">' . convert_smilies($comment->comment_content) . '</a><br /><span style="color:#999;text-align:right;">(' . get_comment_date('Y/m/d H:i', $comment->comment_ID) . ')</span></li><hr />';
                 }
             }
         }
     }
     //if ( empty($announcement) ) $announcement = '<li>还没有人灌水奥!</li>';
     echo $announcement;
     echo '</ul>';
     echo "<p style='text-align:right;'>[<a href='" . get_page_link($page_ID) . "#respond' rel='nofollow'>说两句</a>]</p>";
     echo $after_widget;
 }
Ejemplo n.º 3
0
 public function m_relatedURL($title)
 {
     global $system, $settings;
     $title = mysql_real_escape_string($title);
     $system->dbm->db->select("`id`, `url`, `title`", "`{$this->table}`", "`domain` = '{$settings['domain']}' AND `title` <> '{$title}'");
     while ($row = $system->dbm->db->fetch_array()) {
         similar_text($title, $row[title], $percent);
         $percent = intval($percent);
         //			print "$title $percent% -> Id: $row[id] - Title: $row[title] - Url: $row[url]<br>";
         //			if($percent > 60){
         $sim[$percent][id] = $row[id];
         $row[url] = str_replace("op=", '', $row[url]);
         $row[url] = str_replace("&mode=", '/', $row[url]);
         $row[url] = str_replace("&filter=", '/', $row[url]);
         $row[url] = str_replace("&p=", '/', $row[url]);
         $row[url] = str_replace("&f=", '/', $row[url]);
         $sim[$percent][url] = $row[url];
         $sim[$percent][title] = $row[title];
         //			}
     }
     //		print_r($sim);
     if (count($sim) > 0) {
         krsort($sim);
         $system->xorg->smarty->assign("relatedContent", array_slice($sim, 0, 5, true));
         return $system->xorg->smarty->fetch($settings[moduleAddress] . "/relatedContent/view/tpl/object/relatedContent" . $settings[ext4]);
     }
 }
Ejemplo n.º 4
0
 public function getKeys($imgPath)
 {
     if (!($res = @imagecreatefromjpeg($imgPath))) {
         return '';
     }
     //提取文字部分图片
     $wordData = array();
     for ($i = 0; $i < $this->imgInfo['wordNum']; $i++) {
         $wordData[$i] = '';
         $x = $i * ($this->imgInfo['wordWidth'] + $this->imgInfo['wordSpace']) + $this->imgInfo['offsetWidth'];
         $y = $this->imgInfo['offsetHeight'];
         for ($h = $y; $h < $this->imgInfo['offsetHeight'] + $this->imgInfo['wordHeight']; $h++) {
             for ($w = $x; $w < $x + $this->imgInfo['wordWidth']; $w++) {
                 $rgb = imagecolorsforindex($res, imagecolorat($res, $w, $h));
                 $wordData[$i] .= $rgb['red'] < 127 || $rgb['green'] < 127 || $rgb['blue'] < 127 ? '1' : '0';
             }
         }
     }
     $keys = '';
     //相似度比较
     foreach ($wordData as $wordStr) {
         $maxPercent = 0.0;
         foreach ($this->keyData as $k => $v) {
             $percent = 0.0;
             similar_text($v, $wordStr, $percent);
             if ($percent > $maxPercent) {
                 $maxPercent = $percent;
                 $key = $k;
             }
         }
         $keys .= $key;
     }
     return $keys;
 }
 function OneQuery($query_key, $text, $limit = 5, $properties = null)
 {
     $param = array('partialName' => $text, 'ontologyName' => 'ENVO', 'reverseKeyOrder' => false);
     //print_r($param);
     $envo_result = $this->client->call('getTermsByName', $param);
     //print_r($envo_result);
     //$envo_result = $this->client->call('getOntologyNames');
     //print_r($this->client);
     // Check for a fault
     if ($this->client->fault) {
         // handle this
     } else {
         // Check for errors
         $err = $this->client->getError();
         if ($err) {
         } else {
             //print_r($envo_result);
             // Extract names
             $n = count($envo_result['getTermsByNameReturn']['item']);
             //echo "n=$n\n";
             $n = min($n, $limit);
             for ($i = 0; $i < $n; $i++) {
                 $hit = new stdclass();
                 //echo $envo_result['getTermsByNameReturn']['item'][$i]['key'] . "\n";
                 similar_text($text, $envo_result['getTermsByNameReturn']['item'][$i]['value'], $hit->score);
                 $hit->match = $hit->score == 100;
                 $hit->id = $envo_result['getTermsByNameReturn']['item'][$i]['key'];
                 $hit->name = $envo_result['getTermsByNameReturn']['item'][$i]['value'];
                 $this->StoreHit($query_key, $hit);
             }
         }
     }
 }
Ejemplo n.º 6
0
 /**
  *
  * @param string $word
  * @param array $words
  * @return array
  */
 public static function similarWord($word, array $words)
 {
     $similarity = config('pages.similar.similarity');
     $metaSimilarity = 0;
     $minLevenshtein = 1000;
     $metaMinLevenshtein = 1000;
     $result = [];
     $metaResult = [];
     foreach ($words as $n) {
         $minLevenshtein = min($minLevenshtein, levenshtein($n, $word));
     }
     foreach ($words as $n => $k) {
         if (levenshtein($k, $word) <= $minLevenshtein) {
             if (similar_text($k, $word) >= $similarity) {
                 $result[$n] = $k;
             }
         }
     }
     foreach ($result as $n) {
         $metaMinLevenshtein = min($metaMinLevenshtein, levenshtein(metaphone($n), metaphone($word)));
     }
     foreach ($result as $n) {
         if (levenshtein($n, $word) == $metaMinLevenshtein) {
             $metaSimilarity = max($metaSimilarity, similar_text(metaphone($n), metaphone($word)));
         }
     }
     foreach ($result as $n => $k) {
         if (levenshtein(metaphone($k), metaphone($word)) <= $metaMinLevenshtein) {
             if (similar_text(metaphone($k), metaphone($word)) >= $metaSimilarity) {
                 $metaResult[$n] = $k;
             }
         }
     }
     return $metaResult;
 }
Ejemplo n.º 7
0
 private function getTestsToRun()
 {
     $root = $this->getProjectRoot();
     $test_dir = $root . "/tests/";
     $tests = array();
     foreach (glob($test_dir . "*.t") as $test) {
         $relname = substr($test, strlen($test_dir));
         $tests[$relname] = $test;
     }
     if (!$this->getRunAllTests()) {
         /* run tests that sound similar to the modified paths */
         printf("Finding tests based on name similarity\n");
         printf("Use `arc unit --everything` to run them all\n");
         $paths = array();
         foreach ($this->getPaths() as $path) {
             $paths[] = $this->stripName($path);
         }
         foreach ($tests as $relname => $test) {
             $keep = false;
             $strip = $this->stripName($relname);
             foreach ($paths as $path) {
                 $pct = 0;
                 similar_text($path, $strip, $pct);
                 if ($pct > 55) {
                     $keep = true;
                     break;
                 }
             }
             if (!$keep) {
                 unset($tests[$relname]);
             }
         }
     }
     return $tests;
 }
Ejemplo n.º 8
0
 public static function compare($first, $second)
 {
     $first = static::sanitize($first);
     $second = static::sanitize($second);
     similar_text($first, $second, $result);
     return (double) number_format($result, 2);
 }
 function OneQuery($query_key, $text, $limit = 1, $properties = null)
 {
     $url = '';
     if ($properties) {
         file_put_contents(dirname(__FILE__) . '/tmp/prop.txt', json_encode($properties), FILE_APPEND);
         if ($properties[0]->pid == '/type/object/id') {
             // find datasets for this organisation
             $url .= 'http://api.gbif.org/v1/organization/' . $properties[0]->v . '/publishedDataset';
         } else {
             // crude search
             $url = 'http://api.gbif.org/v1/dataset?q=' . urlencode($text);
         }
     } else {
         // crude search
         $url = 'http://api.gbif.org/v1/dataset?q=' . urlencode($text);
     }
     file_put_contents(dirname(__FILE__) . '/tmp/url.txt', $url . "\n", FILE_APPEND);
     $json = get($url);
     if ($json != '') {
         $obj = json_decode($json);
         foreach ($obj->results as $result) {
             $hit = new stdclass();
             $hit->id = $result->key;
             $hit->name = $result->title;
             similar_text($text, $hit->name, $hit->score);
             $hit->match = $hit->score == 1;
             $this->StoreHit($query_key, $hit);
         }
     }
 }
Ejemplo n.º 10
0
function show_similar_codes($reference)
{
    $reference = strtolower($reference);
    $result = do_query("\n            SELECT deposref, uid FROM users WHERE uid > 1\n        UNION\n            SELECT deposref, uid FROM old_deposrefs\n        ORDER BY deposref\n    ");
    while ($row = mysql_fetch_assoc($result)) {
        $deposref = strtolower($row['deposref']);
        $scores[$deposref] = round((9 + similar_text($reference, $deposref) - levenshtein($reference, $deposref)) * 100 / 18);
        $uid[$deposref] = $row['uid'];
    }
    arsort($scores);
    $first = true;
    foreach ($scores as $deposref => $score) {
        if ($score >= 50) {
            if ($first) {
                $first = false;
                echo "<p>" . _("Did you mean one of these?  Higher percentage = closer match.") . "</p>\n";
                echo "<p>" . _("Click an entry to copy it to the form below, then click 'Deposit' again.") . "</p>\n";
                echo "<table class='display_data'>\n";
                echo "<tr><th>Reference</th><th>Match</th><th>UID</th></tr>\n";
            }
            $formatted = format_deposref($deposref);
            echo "<tr", " class=\"me\"", " onmouseover=\"style.backgroundColor='#8ae3bf';\"", " onmouseout=\"style.backgroundColor='#7ad3af';\"", " onclick=\"ObjById('reference').value = '{$deposref}';\">";
            echo "<td>{$formatted}</td><td>{$score}%</td><td>{$uid[$deposref]}</td></tr>\n";
        }
    }
    if (!$first) {
        echo "</table>\n";
    }
}
Ejemplo n.º 11
0
 function compare($debug = false)
 {
     $first = $this->str1;
     $second = $this->str2;
     $this->levenshtein = levenshtein($first, $second);
     $this->similarity['value'] = $sim = similar_text($first, $second, $perc);
     $this->similarity['percentage'] = $perc;
     if ($debug) {
         echo "{$first} | {$second}<br>";
         echo "leven: " . $this->levenshtein;
         echo '<br>similarity: ' . $sim . ', ' . $perc . '%<br><br>';
     }
     $soundex1 = soundex($first);
     $soundex2 = soundex($second);
     $this->soundex['levenshtein'] = levenshtein($soundex1, $soundex2);
     $this->soundex['similarity'] = $sim = similar_text($soundex1, $soundex2, $perc);
     $this->soundex['percentage'] = $perc;
     if ($debug) {
         echo "Soundex: " . $soundex1 . ", " . $soundex2 . "<BR>";
         echo 'levenshtein: ' . $this->soundex['levenshtein'] . '<br>';
         echo 'similarity: ' . $sim . ', ' . $perc . '%<br><br>';
     }
     $m1 = metaphone($first);
     $m2 = metaphone($second);
     $this->metaphone['levenshtein'] = levenshtein($m1, $m2);
     $this->metaphone['similarity'] = $sim = similar_text($m1, $m2, $perc);
     $this->metaphone['percentage'] = $perc;
     if ($debug) {
         echo "metaphone: " . $m1 . ", " . $m2 . "<br>";
         echo 'levenshtein: ' . $this->metaphone['levenshtein'] . '<br>';
         echo 'similarity: ' . $sim . ', ' . $perc . '%<br>';
         echo '<br>-------------------<br>';
     }
 }
Ejemplo n.º 12
0
 public static function stringSimilarity($s1, $s2)
 {
     $s1 = preg_replace("/[^A-Za-z0-9]/", '', strtolower($s1));
     $s2 = preg_replace("/[^A-Za-z0-9]/", '', strtolower($s2));
     similar_text($s1, $s2, $percent);
     return floatval($percent);
 }
 public function solve(Request $request, \Exception $exception)
 {
     if (!$exception instanceof ServiceNotFoundException) {
         return null;
     }
     try {
         $finder = new ObjectFinder();
         $container = $finder->find('Symfony\\Component\\DependencyInjection\\Container');
         $ids = $container->getServiceIds();
         $searchedId = $exception->getId();
         $similarity = array();
         foreach ($ids as $id) {
             $percentage = 0.0;
             similar_text($id, $searchedId, $percentage);
             if ($percentage >= 90.0) {
                 $similarity[$id] = $percentage;
             }
         }
         arsort($similarity);
         if (!$similarity) {
             return null;
         }
         return new SimpleBlockSolution('Do you have a typo in the service name?', 'Solution:service_name_typo.html.php', array('serviceIds' => $similarity));
     } catch (\Exception $ex) {
         return null;
     }
 }
Ejemplo n.º 14
0
 function getLocation($place)
 {
     global $ANALYTICS;
     $query = "select LocId from Location where Search LIKE '%" . $place . "%'";
     $result = mysql_fetch_array(mysql_query($query, $ANALYTICS));
     $loc_id = $result['LocId'];
     if (!isset($loc_id)) {
         $query1 = "select LocId, Search from Location";
         $query_return = mysql_query($query1, $ANALYTICS);
         $max = 0.0;
         $place = strtoupper($place);
         $location = '';
         $loc_id = 0;
         while ($result1 = mysql_fetch_array($query_return)) {
             $match = 0.0;
             $loc = strtoupper($result1['Search']);
             similar_text($place, $loc, $match);
             if ($match > 80 && $match > $max) {
                 $max = $match;
                 $location = $result1['Search'];
                 $loc_id = $result1['LocId'];
             }
         }
     }
     return $loc_id;
 }
 function OneQuery($query_key, $text, $limit = 1, $properties = null)
 {
     $url = 'http://gni.globalnames.org/name_strings.json?search_term=' . rawurlencode($text);
     $limit = 5;
     if (0) {
         file_put_contents('tmp/r.txt', "URL = {$url}\n", FILE_APPEND);
     }
     $json = get($url);
     if (0) {
         file_put_contents('tmp/r.txt', $json . "\n", FILE_APPEND);
     }
     $obj = json_decode($json);
     if (0) {
         file_put_contents('tmp/r.txt', print_r($obj, true), FILE_APPEND);
     }
     $n = min($limit, $obj->name_strings_total);
     for ($i = 0; $i < $n; $i++) {
         $hit = new stdclass();
         $hit->match = $obj->name_strings_total == 1;
         $hit->name = $obj->name_strings[$i]->name;
         $hit->id = $obj->name_strings[$i]->id;
         similar_text($text, $hit->name, $hit->score);
         $this->StoreHit($query_key, $hit);
     }
 }
 /**
  * Compare similarity of two strings by seeing how many characters they have in common.
  * 
  * This method should be agnostic to things like reverse artist-name ordering, ignores 
  * punctuation, transliterates accents, and should not be very sensitive to things like 
  * '&' versus 'and'. 
  */
 protected function checkMatch($a, $b)
 {
     $a = $this->characterize($a);
     $b = $this->characterize($b);
     similar_text($a, $b, $p);
     return $p >= 0.8;
 }
Ejemplo n.º 17
0
 /**
  * @Route("/new", name="new")
  */
 public function newAction(Request $request)
 {
     $file_root = $request->server->get('DOCUMENT_ROOT') . '/integrity/web/files/';
     $comparison = new Comparison();
     $form = $this->createFormBuilder($comparison)->add('first_file', FileType::class)->add('second_file', FileType::class)->add('save', SubmitType::class, array('label' => 'Submit'))->getForm();
     $form->handleRequest($request);
     if ($form->isSubmitted() && $form->isValid()) {
         $em = $this->getDoctrine()->getManager();
         $em->persist($comparison);
         $em->flush();
         if (is_file($file_root . $comparison->getFirstFileName()) && is_file($file_root . $comparison->getSecondFileName())) {
             if (sha1_file($file_root . $comparison->getFirstFileName()) === sha1_file($file_root . $comparison->getSecondFileName())) {
                 $comparison->setPercentage('100');
                 $em->persist($comparison);
                 $em->flush();
             } else {
                 similar_text(file_get_contents($file_root . $comparison->getFirstFileName()), file_get_contents($file_root . $comparison->getSecondFileName()), $percentage);
                 $comparison->setPercentage($percentage);
                 $em->persist($comparison);
                 $em->flush();
             }
         }
         return $this->redirectToRoute('view_item', array('id' => $comparison->getId()));
     }
     return $this->render('default/new.html.twig', ['base_dir' => realpath($this->container->getParameter('kernel.root_dir') . '/..'), 'form' => $form->createView()]);
 }
Ejemplo n.º 18
0
 public function run()
 {
     $result = "";
     // ²éÕÒ4¸öÊý×Ö
     $data = array("", "", "", "");
     for ($i = 0; $i < 4; ++$i) {
         $x = $i * (WORD_WIDTH + WORD_SPACING) + OFFSET_X;
         $y = OFFSET_Y;
         for ($h = $y; $h < OFFSET_Y + WORD_HIGHT; ++$h) {
             for ($w = $x; $w < $x + WORD_WIDTH; ++$w) {
                 $data[$i] .= $this->DataArray[$h][$w];
             }
         }
     }
     // ½øÐйؼü×ÖÆ¥Åä
     foreach ($data as $numKey => $numString) {
         $max = 0.0;
         $num = 0;
         foreach ($this->Keys as $key => $value) {
             $percent = 0.0;
             similar_text($value, $numString, $percent);
             if (intval($percent) > $max) {
                 $max = $percent;
                 $num = $key;
                 if (intval($percent) > 95) {
                     break;
                 }
             }
         }
         $result .= $num;
     }
     $this->data = $result;
     // ²éÕÒ×î¼ÑÆ¥ÅäÊý×Ö
     return $result;
 }
Ejemplo n.º 19
0
 /**
  * Verify that the name of the author is similar to that of the query.
  *
  * A percentage is calculated and compared against a similarity threshold,
  * making it simple to filter the obviously incorrect results.
  *
  * @param $query
  * @param $name
  * @return bool
  */
 protected function authorsNameIsSimilar(string $query, string $name)
 {
     $percentage = 0;
     similar_text($name, $query, $percentage);
     debug("{$name}'s similarity to {$query}: {$percentage}");
     return $percentage > 50;
 }
Ejemplo n.º 20
0
 public function testReport()
 {
     // Empty report
     $this->assertEmpty($this->report->gate);
     $this->assertEmpty($this->report->door);
     $this->assertFalse($this->report->containsError());
     $this->assertSame(0, count($this->report->actions));
     // Adds a first action
     // Our report should be valid.
     $action = new AMQPAction('method', 'target');
     $this->report->addAction($action);
     $this->assertSame(1, count($this->report->actions));
     $this->assertFalse($this->report->containsError());
     // Let's attach an exception to a new action.
     // Our report should then be invalid.
     $action = new AMQPAction('methodWithException', 'target');
     $ex = new \RuntimeException('Lorem ipsum dolor');
     $action->attachError(new ActionError($ex));
     $this->report->addAction($action);
     $this->assertSame(2, count($this->report->actions));
     $this->assertTrue($this->report->containsError());
     // Attaches to gate
     $this->report->attachToGate('QuuxGate', 'Quuxians');
     $this->assertSame('QuuxGate', $this->report->gate);
     $this->assertSame('Quuxians', $this->report->door);
     // Test rendering
     $actualReport = (string) $this->report;
     $expectedReport = file_get_contents(__DIR__ . '/../data/report.json');
     $score = similar_text($expectedReport, $actualReport);
     $this->assertGreaterThan(550, $score, 'data/report.json and rendered report differ too much. Try $this->assertEquals($expectedReport, $actualReport) to see a diff.');
 }
Ejemplo n.º 21
0
 /**
  * Rescues a missing record by providing the best matching one.
  *
  * Match is computed from the slug of the module's own visible records, thus rescue if only
  * triggered if 'slug' is defined in the conditions.
  *
  * @return Content|null The record best matching the condition slug, or null if
  * none was similar enough.
  *
  * @throws RecordNotFound if the record could not be rescued.
  *
  * @todo-20140429 This should be in an exception rescue listener.
  */
 protected function rescue()
 {
     $conditions = $this->conditions;
     if (!empty($conditions['nid']) || empty($conditions['slug'])) {
         return;
     }
     $slug = $conditions['slug'];
     $model = $this->module->model;
     $tries = $model->select('nid, slug')->own->visible->order('date DESC')->pairs;
     $key = null;
     $max = 0;
     foreach ($tries as $nid => $compare) {
         similar_text($slug, $compare, $p);
         if ($p > $max) {
             $key = $nid;
             if ($p > 90) {
                 break;
             }
             $max = $p;
         }
     }
     if ($p < 60) {
         throw new RecordNotFound('Record not found.', []);
     } else {
         if ($key) {
             $record = $model[$key];
             \ICanBoogie\log('The record %title was rescued!', ['title' => $record->title]);
             throw new ForceRedirect($record->url, 301);
         }
     }
 }
Ejemplo n.º 22
0
 public function slugs()
 {
     $slugs = Slug::orderBy('updated_at', 'desc')->get();
     /******************/
     $dirtyCities = Flight::doesntHave('city')->orderBy('country_code')->groupBy('city')->get();
     $cleanCities = City::groupBy('city_slug')->get();
     $noMatches = array();
     $dirtyCountries = array();
     $cleanCountries = array();
     foreach ($dirtyCities as $dirtyCity) {
         $similarsArray = array();
         foreach ($cleanCities as $cleanCity) {
             similar_text($dirtyCity->city_slug, $cleanCity->city_slug, $percent);
             $similarityArray[$cleanCity->city_slug] = $percent;
             $cleanCountries[$cleanCity->city_slug] = $cleanCity->country_code;
         }
         //sort in descending order
         arsort($similarityArray);
         //take first few with highest similarity
         $similarityArray = array_slice($similarityArray, 0, 8);
         $noMatches[$dirtyCity->city_slug] = $similarityArray;
         $dirtyCountries[$dirtyCity->city_slug] = $dirtyCity->country_code;
     }
     return view('scrapers.slugs')->with(['slugs' => $slugs, 'noMatches' => $noMatches, 'dirtyCountries' => $dirtyCountries, 'cleanCountries' => $cleanCountries]);
 }
Ejemplo n.º 23
0
 public function fuzzyFind($query)
 {
     $finder = new SymfonyFinder();
     $files = $finder->in($this->findServicesRootPath() . '/*/Features')->in($this->findDomainsRootPath() . '/*/Jobs')->name('*.php')->files();
     $matches = ['jobs' => [], 'features' => []];
     foreach ($files as $file) {
         $base = $file->getBaseName();
         $name = str_replace(['.php', ' '], '', $base);
         $query = str_replace(' ', '', trim($query));
         similar_text($query, mb_strtolower($name), $percent);
         if ($percent > 35) {
             if (strpos($base, 'Feature.php')) {
                 $matches['features'][] = [$this->findFeature($name)->toArray(), $percent];
             } elseif (strpos($base, 'Job.php')) {
                 $matches['jobs'][] = [$this->findJob($name)->toArray(), $percent];
             }
         }
     }
     // sort the results by their similarity percentage
     $this->sortFuzzyResults($matches['jobs']);
     $this->sortFuzzyResults($matches['features']);
     $matches['features'] = $this->mapFuzzyResults($matches['features']);
     $matches['jobs'] = array_map(function ($result) {
         return $result[0];
     }, $matches['jobs']);
     return $matches;
 }
 function OneQuery($query_key, $text, $limit = 1, $properties = null)
 {
     $param = array('scientificnames' => array($text), 'like' => true, 'fuzzy' => true, 'marine_only' => false);
     $worms_result = $this->client->call('getAphiaRecordsByNames', $param);
     // Check for a fault
     if ($this->client->fault) {
         // handle this
     } else {
         // Check for errors
         $err = $this->client->getError();
         if ($err) {
         } else {
             // Extract names
             $limit = 3;
             $n = count($worms_result[0]);
             $n = min($n, $limit);
             for ($i = 0; $i < $n; $i++) {
                 $hit = new stdclass();
                 similar_text($text, $worms_result[0][$i]['scientificname'], $hit->score);
                 $hit->match = $hit->score == 100;
                 $hit->id = $worms_result[0][$i]['AphiaID'];
                 $hit->name = $worms_result[0][$i]['scientificname'];
                 $this->StoreHit($query_key, $hit);
             }
         }
     }
 }
Ejemplo n.º 25
0
 function find_by_partial_name($name = false, $projectID = false)
 {
     $stack1 = array();
     $people = array();
     $db = new db_alloc();
     if ($projectID) {
         $db->query("SELECT clientID FROM project WHERE projectID = %d", $projectID);
         $row = $db->qr();
         if ($row["clientID"]) {
             $extra = prepare("AND clientID = %d", $row["clientID"]);
         }
     }
     $q = prepare("SELECT clientContactID, clientContactName\n                    FROM clientContact\n                   WHERE 1=1\n                     AND clientContactName like '%s%%'" . $extra, $name);
     $db->query($q);
     while ($row = $db->row()) {
         $people[$db->f("clientContactID")] = $row;
     }
     foreach ($people as $personID => $row) {
         similar_text(strtolower($row["clientContactName"]), strtolower($name), $percent1);
         $stack1[$personID] = $percent1;
     }
     asort($stack1);
     end($stack1);
     $probable1_clientContactID = key($stack1);
     $person_percent1 = current($stack1);
     if ($probable1_clientContactID) {
         return $probable1_clientContactID;
     }
 }
Ejemplo n.º 26
0
 /**
  */
 public function __construct($propertySchema, $settings = array())
 {
     $this->propertySchema = $propertySchema;
     unset($settings['Name']);
     // check for settings given but not supported
     if (($unsupportedSettings = array_diff_key($settings, $this->supportedSettings)) !== array()) {
         $supportedSettings = array_keys($this->supportedSettings);
         foreach (array_keys($unsupportedSettings) as $unsupportedSetting) {
             foreach ($supportedSettings as $supportedSetting) {
                 $similarity = 0;
                 similar_text($supportedSetting, $unsupportedSetting, $similarity);
                 if ($similarity > 50) {
                     throw new \Exception(sprintf('The settings "%s" you\'re trying to set don\'t exist, did you mean: "%s" ?.', $unsupportedSetting, $supportedSetting), 1359625876);
                 }
             }
         }
         throw new \Exception(sprintf('The settings "%s" you\'re trying to set don\'t exist in class "%s".', implode(',', array_keys($unsupportedSettings)), get_class($this)), 1359625876);
     }
     // check for required settings being set
     array_walk($this->supportedSettings, function ($supportedSettingData, $supportedSettingName, $settings) {
         if (isset($supportedSettingData['required']) && $supportedSettingData['required'] == TRUE && !array_key_exists($supportedSettingName, $settings)) {
             throw new \Exception('Missing required OptionsProvider setting: ' . $supportedSettingName . chr(10) . $supportedSettingData['description'], 1359625876);
         }
     }, $settings);
     // merge with default values
     $this->settings = array_merge(array_map(function ($value) {
         return isset($value['default']) ? $value['default'] : NULL;
     }, $this->supportedSettings), $settings);
 }
Ejemplo n.º 27
0
function compareMetaphone($v1, $v2)
{
    $v1 = metaphone($v1);
    $v2 = metaphone($v2);
    similar_text($v1, $v2, $p);
    // return similarity percentage
    return $p;
}
Ejemplo n.º 28
0
function most_similar(&$context, $string, $source_str)
{
    /* Calculate the similarity between two strings */
    $sim = similar_text($string, $source_str);
    if (empty($context) || $sim > $context['sim']) {
        $context = array('sim' => $sim, 'title' => $string);
    }
}
Ejemplo n.º 29
0
 /**
  * @return void
  */
 function testMultiInsert()
 {
     // Multi-insert
     $pq = PhpQuery::newDocument('<li><span class="field1"></span><span class="field1"></span></li>')->find('.field1')->php('longlongtest');
     $validResult = '<li><span class="field1"><php>longlongtest</php></span><span class="field1"><php>longlongtest</php></span></li>';
     similar_text($pq->htmlOuter(), $validResult, $similarity);
     $this->assertGreaterThan(80, $similarity);
 }
 /**
  * determine the score of the result based on algorithm
  * @return float score
  **/
 public function score(SearchResultInterface $result)
 {
     $titlePercent = 0;
     $bodyPercent = 0;
     similar_text($this->getKeywords(), $result->resultTitle(), $titlePercent);
     similar_text($this->getKeywords(), $result->resultBody(), $bodyPercent);
     return $score = $titlePercent * 0.5 + $bodyPercent;
 }