function PhpaieLogin()
{
    $pg_LIVEUSER1LOGIN = new LIVEUSER1LOGIN(isset($_POST) && array_count_values($_POST) ? $_POST : $_GET);
    //Récupération des variables pour le formulaire
    $pg_LIVEUSER1LOGIN->pageDisplay("");
    //exit();
}
function search_AddWords(&$obj, $module = 'Search', $id = -1, $attr = '', $content = '', $expires = NULL)
{
    $obj->DeleteWords($module, $id, $attr);
    $db =& $obj->GetDb();
    $non_indexable = strpos($content, NON_INDEXABLE_CONTENT);
    if ($non_indexable !== FALSE) {
        return;
    }
    @$obj->SendEvent('SearchItemAdded', array($module, $id, $attr, &$content, $expires));
    if ($content != "") {
        //Clean up the content
        $stemmed_words = $obj->StemPhrase($content);
        $words = array_count_values($stemmed_words);
        $q = "SELECT id FROM " . cms_db_prefix() . 'module_search_items WHERE module_name=?';
        $parms = array($module);
        if ($id != -1) {
            $q .= " AND content_id=?";
            $parms[] = $id;
        }
        if ($attr != '') {
            $q .= " AND extra_attr=?";
            $parms[] = $attr;
        }
        $dbresult = $db->Execute($q, $parms);
        if ($dbresult && $dbresult->RecordCount() > 0 && ($row = $dbresult->FetchRow())) {
            $itemid = $row['id'];
        } else {
            $itemid = $db->GenID(cms_db_prefix() . "module_search_items_seq");
            $db->Execute('INSERT INTO ' . cms_db_prefix() . 'module_search_items (id, module_name, content_id, extra_attr, expires) VALUES (?,?,?,?,?)', array($itemid, $module, $id, $attr, $expires != NULL ? trim($db->DBTimeStamp($expires), "'") : NULL));
        }
        foreach ($words as $word => $count) {
            $db->Execute('INSERT INTO ' . cms_db_prefix() . 'module_search_index (item_id, word, count) VALUES (?,?,?)', array($itemid, $word, $count));
        }
    }
}
Example #3
0
function WordIntoDB($url, $fileID, $db)
{
    $path = $url;
    $fp = fopen($path, 'r');
    $contents = stream_get_contents($fp);
    $contents = strip_tags($contents);
    $contents = strtolower($contents);
    $i = 0;
    $sep = " \n\t\"\\'!,.()''\"~!@#\$%^&*(),./<>\\+_=-|?;:[]{}`бу^1234567890";
    $acontents[$i++] = trim(strtok($contents, $sep));
    while ($token = strtok($sep)) {
        $acontents[$i++] = trim($token);
    }
    $count = array_count_values($acontents);
    ksort($count);
    if (!ini_get('safe_mode')) {
        set_time_limit(0);
    }
    foreach ($count as $row => $times) {
        //echo $row."=>".$times."<br>";
        $word_id = $db->InsertWord($row);
        $db->InsertFileWords($fileID, $word_id, $times);
    }
    fclose($fp);
}
Example #4
0
function reussite($date, $ent)
{
    $sqlReussite = "select * from kazak_cheval where entraineur='{$ent}' and dateAnnee='{$date}' and rang between 1 and 3";
    $resReussite = mysql_query($sqlReussite);
    //var_dump($res);
    echo "<b>" . $ent . " <i>(" . $date . ")</i></b>";
    echo "<br>";
    //echo "<table><tr><td>";
    $arrayHypodrome = array();
    while ($dataReussite = mysql_fetch_array($resReussite)) {
        $hypodrome = $dataReussite['hypodrome'];
        //echo $entraineur;
        $arrayHypodrome[] = $hypodrome;
        //echo 	$arrayEntraineur[$i];
        //echo $i=$i+1;
        //echo "<br>";
    }
    $result = array_count_values($arrayHypodrome);
    arsort($result);
    foreach ($result as $cle => $value) {
        // echo $cle.' => '.$value.'<br/>';
        if ($value > 3) {
            echo $cle . ' => ' . $value . '<br/>';
        }
        //else {echo "moins de 3 reussites pour l'ensemble des hippodromes";	 }
    }
    echo "</span></a>";
}
 /**
  * Establish if there is a day
  * witch matches for all people
  * @param caldates
  * @return Day 
  */
 public function compareCommonDates(CalendarDateRepository $calDates)
 {
     $dates = $calDates->getDates();
     //get the number of peope
     $numberOfPeople = count($dates);
     $dateArr = array();
     $dayNameArr = array();
     //flatten the array...
     foreach ($dates as $date) {
         foreach ($date as $value) {
             $dateArr[] = $value;
             $dayNameArr[] = $value->getName();
         }
     }
     //check if there is a value with the same amount of matches as people
     $countArr = array_count_values($dayNameArr);
     if (in_array($numberOfPeople, $countArr)) {
         //get the value of the index
         $day = array_search($numberOfPeople, $countArr);
         foreach ($dateArr as $date) {
             if ($date->getName() == $day) {
                 //TODO how handle multiple days matching? new calendarDateRepo?
                 return $date;
             }
         }
     }
     return null;
 }
Example #6
0
 /**
  * 获取成功的订单
  * @return [type] [description]
  */
 public function getSuccess()
 {
     $data = array('main' => url('/'), 'announce' => url('/announce'), 'category' => url('/category'), 'deliver' => url('/deliver'), 'good' => url('/good'), 'map' => url('/map'), 'shop_info' => url('/shop_info'), 'success' => url('/success'), 'widge_success' => array());
     $shop_id = Auth::user()->shop_id;
     $orders = Order::where('shop_id', $shop_id)->where('state_of_shop', 3)->get();
     $data['widge_success']['deal_count'] = count($orders);
     $data['widge_success']['deal'] = array();
     $shop = Shop::find($shop_id);
     foreach ($orders as $order) {
         $comment = CommentOrder::where('order_id', $order->id)->get();
         $one = array('deal_id' => $order->id, 'deal_statue' => $order->state, 'same_again' => '##', 'deal_again' => '##', 'shop_name' => $shop->name, 'deal_number' => $order->number, 'deal_time' => date('Y-m-d', $order->ordertime), 'deal_phone' => $shop->linktel, 'deliver_address' => $order->receive_address, 'deliver_phone' => $order->receive_phone, 'deliver_remark' => $order->beta, 'deal_speed' => isset($comment[0]) ? $comment[0]->speed : 0, 'deal_satisfied' => isset($comment[0]) ? $comment[0]->value : 0, 'good' => array(), 'others' => array(array('item_name' => '不知道', 'item_value' => '-5', 'item_amount' => '1', 'item_total' => '0')));
         $one['total'] = $order->total;
         $menu_ids = array_count_values(explode(',', $order->order_menus));
         foreach ($menu_ids as $menu_id => $amount) {
             $menuComment = CommentMenu::where('order_id', $order->id)->where('menu_id', $menu_id)->get();
             $menu = Menu::find($menu_id);
             //var_dump($menuComment);
             $onemenu = array('goods_id' => $menu_id, 'goods_name' => $menu->title, 'goods_value' => $menu->price, 'goods_amount' => $amount, 'goods_total' => $amount * $menu->price, 'good_atisfied' => isset($menuComment[0]) ? $menuComment[0]->value : 0);
             array_push($one['good'], $onemenu);
         }
         array_push($data['widge_success']['deal'], $one);
     }
     return View::make("template.success.success")->with($data);
     //var_dump($data);
 }
Example #7
0
 public function index(array $params = [])
 {
     Assets::addCSS('svgtree-0.3.0.min.css');
     Assets::addCSS('main.css');
     Assets::addJS('jsrender.min.js');
     Assets::addJS('db.js');
     Assets::addJS('main.js');
     Assets::addJS('search.js');
     Assets::addJS('svgtree-0.3.0.min.js');
     Assets::addJS('trees.js');
     $this->SearchModel = $this->loader->loadModel('Search');
     if (isset($_POST['words'])) {
         $words = json_decode($_POST['words']);
         $results = $this->SearchModel->searchFromKeywords($words);
         $response = [];
         // if we have some results to handle
         if ($results) {
             // count values
             $results = array_count_values($results);
             // sort by count
             arsort($results);
             // keep only sorted links id
             $results = array_keys($results);
             foreach ($results as $linkId) {
                 $link = $this->SearchModel->getLink($linkId);
                 if ($link) {
                     $response[] = $link;
                 }
             }
         }
         echo json_encode($response);
         exit;
     }
     $this->loader->loadView('index', $this->data, true);
 }
Example #8
0
 private function calculate($move, $warPlace, $playerName)
 {
     $coordinates = $move->getCoordenates();
     $x = $coordinates['x'];
     $y = $coordinates['y'];
     $feedback = new Feedback();
     $result = array(isset($warPlace[$x - 1][$y + 1]) ? $warPlace[$x - 1][$y + 1] : null, isset($warPlace[$x][$y + 1]) ? $warPlace[$x][$y + 1] : null, isset($warPlace[$x + 1][$y + 1]) ? $warPlace[$x + 1][$y + 1] : null, isset($warPlace[$x - 1][$y]) ? $warPlace[$x - 1][$y] : null, isset($warPlace[$x + 1][$y]) ? $warPlace[$x + 1][$y] : null, isset($warPlace[$x - 1][$y - 1]) ? $warPlace[$x - 1][$y - 1] : null, isset($warPlace[$x][$y - 1]) ? $warPlace[$x][$y - 1] : null, isset($warPlace[$x + 1][$y - 1]) ? $warPlace[$x + 1][$y - 1] : null);
     $rEnd = array();
     foreach ($result as $idx => $r) {
         if (!is_null($r)) {
             $rEnd[] = $r;
         }
     }
     $count = array_count_values($rEnd);
     asort($count);
     unset($count['.']);
     if (count($count) == 0) {
         $feedback->add(Feedback::WIN, $move);
         return $feedback;
     }
     $dominanteId = key($count);
     $dominanteCount = array_shift($count);
     if ($dominanteId == $playerName || $dominanteId == '.') {
         $feedback->add(Feedback::WIN, $move);
         return $feedback;
     }
     if ($dominanteCount == 1) {
         $feedback->add(Feedback::WIN, $move);
         return $feedback;
     }
     $feedback->add(Feedback::LOSE, $move);
     return $feedback;
 }
Example #9
0
 public function doMobileshow()
 {
     global $_W, $_GPC;
     $rid = $_GPC['id'];
     $sql = "SELECT * FROM " . tablename($this->tablename_log) . " WHERE `rid`=:rid";
     $info = pdo_fetchall($sql, array(':rid' => $rid));
     $sql = "SELECT * FROM " . tablename($this->tablename) . " WHERE `rid`=:rid LIMIT 1";
     $quiz = pdo_fetch($sql, array(':rid' => $rid));
     $sql = "SELECT * FROM " . tablename($this->tablename_question) . " WHERE `id`=:id";
     $q = pdo_fetch($sql, array(':id' => $quiz['qid']));
     //var_dump($q);
     $arr = array();
     foreach ($info as $key => $value) {
         $arr[] = $info[$key]['chk_answer'];
     }
     $per = array_count_values($arr);
     ksort($per);
     //var_dump($per);
     $total_count = sizeof($info);
     $config = $this->get_config($q);
     //foreach($per as $key => $value){
     //$str .= '选项'.$key.'次数'.$value;
     //}
     //var_dump($str);
     //var_dump($per);
     include $this->template('show');
 }
Example #10
0
 public function getStatistics()
 {
     $integrated = array();
     // Bands
     $sql = 'select gig_bands as bands from gigs';
     $rows = $this->db()->query($sql);
     while ($row = $this->db()->fetch_array($rows)) {
         $bandsArrayRow = explode('+', $row['bands']);
         foreach ($bandsArrayRow as $band) {
             if (strpos($band, ':')) {
                 $bandTrimmed = explode(":", $band);
                 $integrated[] = utf8_encode(trim($bandTrimmed[1]));
             } else {
                 $integrated[] = utf8_encode(trim($band));
             }
         }
     }
     $sql = 'select count(*) as gigs from gigs';
     $rows2 = $this->db()->query($sql);
     $row2 = $this->db()->fetch_array($rows2);
     $stats['gigs'] = $row2;
     $stats['bandsNumber'] = count(array_count_values($integrated));
     $stats['integrated'] = array_count_values($integrated);
     return $stats;
 }
Example #11
0
 /**
  * Returns the colors of the image in an array, ordered in descending order, where the keys are the colors, and the values are the count of the color.
  *
  * @return array
  */
 function Get_Color()
 {
     if (isset($this->image)) {
         $im = $this->image;
         $imgWidth = imagesx($im);
         $imgHeight = imagesy($im);
         for ($y = 0; $y < $imgHeight; $y++) {
             for ($x = 0; $x < $imgWidth; $x++) {
                 $index = imagecolorat($im, $x, $y);
                 $Colors = imagecolorsforindex($im, $index);
                 $Colors['red'] = intval(($Colors['red'] + 15) / 32) * 32;
                 //ROUND THE COLORS, TO REDUCE THE NUMBER OF COLORS, SO THE WON'T BE ANY NEARLY DUPLICATE COLORS!
                 $Colors['green'] = intval(($Colors['green'] + 15) / 32) * 32;
                 $Colors['blue'] = intval(($Colors['blue'] + 15) / 32) * 32;
                 if ($Colors['red'] >= 256) {
                     $Colors['red'] = 240;
                 }
                 if ($Colors['green'] >= 256) {
                     $Colors['green'] = 240;
                 }
                 if ($Colors['blue'] >= 256) {
                     $Colors['blue'] = 240;
                 }
                 $hexarray[] = substr("0" . dechex($Colors['red']), -2) . substr("0" . dechex($Colors['green']), -2) . substr("0" . dechex($Colors['blue']), -2);
             }
         }
         $hexarray = array_count_values($hexarray);
         natsort($hexarray);
         $hexarray = array_reverse($hexarray, true);
         return $hexarray;
     } else {
         die("You must enter a filename! (\$image parameter)");
     }
 }
Example #12
0
 /**
  * Template method. Main algorithm
  *
  * {@inheritdoc}
  */
 public function parse(array $options)
 {
     $this->checkOptions($options);
     $this->declaredNamespaces = $options['declared_namespaces'];
     $pattern = '#\\b((?<module>(' . implode('[\\\\]|', $this->declaredNamespaces) . '[\\\\])[a-zA-Z0-9]+)[a-zA-Z0-9_\\\\]*)\\b#';
     $modules = [];
     foreach ($options['files_for_parse'] as $file) {
         $content = file_get_contents($file);
         $module = $this->extractModuleName($file);
         // also collect modules without dependencies
         if (!isset($modules[$module])) {
             $modules[$module] = ['name' => $module, 'dependencies' => []];
         }
         if (preg_match_all($pattern, $content, $matches)) {
             $dependencies = array_count_values($matches['module']);
             foreach ($dependencies as $dependency => $count) {
                 if ($module == $dependency) {
                     continue;
                 }
                 if (isset($modules[$module]['dependencies'][$dependency])) {
                     $modules[$module]['dependencies'][$dependency]['count'] += $count;
                 } else {
                     $modules[$module]['dependencies'][$dependency] = ['lib' => $dependency, 'count' => $count];
                 }
             }
         }
     }
     return $modules;
 }
Example #13
0
 private function hasDuplicatedValues(array $values)
 {
     $duplicatedValues = array_filter(array_count_values($values), function ($counter) {
         return $counter !== 1;
     });
     return empty($duplicatedValues) === false;
 }
Example #14
0
function solution($A)
{
    $counta = count($A);
    $countleaders = 0;
    for ($i = 0; $i < $counta - 1; $i++) {
        $front[$i] = array_slice($A, 0, $i + 1);
        $after[$i] = array_slice($A, $i + 1, $counta - $i - 1);
        //print_r($front[$i]);
        //print_r($after[$i]);
        $countfront = count($front[$i]);
        $countafter = count($after[$i]);
        $maxfront = current(array_keys(array_count_values($front[$i]), max(array_count_values($front[$i]))));
        $maxafter = current(array_keys(array_count_values($after[$i]), max(array_count_values($after[$i]))));
        //echo $countfront;
        //echo $countafter;
        //echo max(array_count_values($front[$i])).'.';
        //echo max(array_count_values($after[$i])).'.';
        //echo $maxfront;
        //echo $maxafter;
        //echo $maxafter;
        if (max(array_count_values($front[$i])) > $countfront / 2 && max(array_count_values($after[$i])) > $countafter / 2 && $maxfront === $maxafter) {
            $countleaders++;
        }
    }
    return $countleaders;
}
Example #15
0
 /**
  * Constructor
  *
  * @param array $characterMap
  * @throws \InvalidArgumentException
  */
 public function __construct(array $characterMap)
 {
     // Trim characters of whitespaces
     array_walk($characterMap, function (&$char) {
         $char = trim($char);
     });
     $nonSingleCharacters = array();
     foreach ($characterMap as $character) {
         if (strlen($character) > 1) {
             $nonSingleCharacters[] = $character;
         }
     }
     if (count($nonSingleCharacters)) {
         throw new \InvalidArgumentException("The character map contains references that aren't 1 character in length: '" . implode("' '", $nonSingleCharacters) . "'");
     }
     $frequencies = array_count_values($characterMap);
     $duplicates = array();
     foreach ($frequencies as $character => $frequency) {
         if ($frequency > 1) {
             $duplicates[] = $character;
         }
     }
     if (count($duplicates)) {
         throw new \InvalidArgumentException("The character map contains duplicates of the following characters: '" . implode("' '", $duplicates) . "'");
     }
     $this->characterMap = $characterMap;
 }
Example #16
0
 public function update($module_name, $action, $id, $groups, $user, $title, $icon)
 {
     $output = array();
     if ($groups) {
         $count = array_count_values($groups);
         $authorized = isset($count[0]) ? $count[0] >= $count[1] : 0;
         $this->model()->delete($module_name, $action, $id, 'group')->add($module_name, $action, $id, 'group', array_keys(array_filter($groups, function ($a) use($authorized) {
             return $a == $authorized;
         })), $authorized);
     } else {
         if ($user) {
             $this->model()->delete($module_name, $action, $id, 'user', $user_id = array_keys($user)[0]);
             if (($authorized = current($user)) != -1) {
                 $this->model()->add($module_name, $action, $id, 'user', $user_id, $authorized);
             }
         }
     }
     $this->access->reload();
     if ($groups) {
         $output['details'] = display($this->index($action, $title, $icon, $module_name, $id));
     } else {
         if ($user) {
             $output['user_authorized'] = $authorized = $this->access($module_name, $action, $id, NULL, $user_id);
             $output['user_ambiguous'] = $authorized === NULL;
             $output['user_forced'] = is_int($authorized);
         }
     }
     $output['count'] = $this->access->count($module_name, $action, $id, $ambiguous);
     $output['ambiguous'] = $ambiguous;
     return json_encode($output);
 }
 public function index_post($postid, $type, $questionid, $parentid, $title, $content, $format, $text, $tagstring, $categoryid)
 {
     require_once QA_INCLUDE_DIR . 'db/post-create.php';
     //	Get words from each textual element
     $titlewords = array_unique(qa_string_to_words($title));
     $contentcount = array_count_values(qa_string_to_words($text));
     $tagwords = array_unique(qa_string_to_words($tagstring));
     $wholetags = array_unique(qa_tagstring_to_tags($tagstring));
     //	Map all words to their word IDs
     $words = array_unique(array_merge($titlewords, array_keys($contentcount), $tagwords, $wholetags));
     $wordtoid = qa_db_word_mapto_ids_add($words);
     //	Add to title words index
     $titlewordids = qa_array_filter_by_keys($wordtoid, $titlewords);
     qa_db_titlewords_add_post_wordids($postid, $titlewordids);
     //	Add to content words index (including word counts)
     $contentwordidcounts = array();
     foreach ($contentcount as $word => $count) {
         if (isset($wordtoid[$word])) {
             $contentwordidcounts[$wordtoid[$word]] = $count;
         }
     }
     qa_db_contentwords_add_post_wordidcounts($postid, $type, $questionid, $contentwordidcounts);
     //	Add to tag words index
     $tagwordids = qa_array_filter_by_keys($wordtoid, $tagwords);
     qa_db_tagwords_add_post_wordids($postid, $tagwordids);
     //	Add to whole tags index
     $wholetagids = qa_array_filter_by_keys($wordtoid, $wholetags);
     qa_db_posttags_add_post_wordids($postid, $wholetagids);
     //	Update counts cached in database (will be skipped if qa_suspend_update_counts() was called
     qa_db_word_titlecount_update($titlewordids);
     qa_db_word_contentcount_update(array_keys($contentwordidcounts));
     qa_db_word_tagwordcount_update($tagwordids);
     qa_db_word_tagcount_update($wholetagids);
     qa_db_tagcount_update();
 }
Example #18
0
 /**
  * @throws Exception\InvalidEnumerationValueException
  * @throws Exception\InvalidEnumerationDefinitionException
  * @internal param string $class
  */
 protected static function loadValues()
 {
     $class = get_called_class();
     if (isset(static::$enumConstants[$class])) {
         return;
     }
     $reflection = new \ReflectionClass($class);
     $constants = $reflection->getConstants();
     $defaultValue = NULL;
     if (isset($constants['__default'])) {
         $defaultValue = $constants['__default'];
         unset($constants['__default']);
     }
     if (empty($constants)) {
         throw new Exception\InvalidEnumerationValueException(sprintf('No enumeration constants defined for "%s"', $class), 1381512807);
     }
     foreach ($constants as $constant => $value) {
         if (!is_int($value) && !is_string($value)) {
             throw new Exception\InvalidEnumerationDefinitionException(sprintf('Constant value must be of type integer or string; constant=%s; type=%s', $constant, is_object($value) ? get_class($value) : gettype($value)), 1381512797);
         }
     }
     $constantValueCounts = array_count_values($constants);
     arsort($constantValueCounts, SORT_NUMERIC);
     $constantValueCount = current($constantValueCounts);
     $constant = key($constantValueCounts);
     if ($constantValueCount > 1) {
         throw new Exception\InvalidEnumerationDefinitionException(sprintf('Constant value is not unique; constant=%s; value=%s; enum=%s', $constant, $constantValueCount, $class), 1381512859);
     }
     if ($defaultValue !== NULL) {
         $constants['__default'] = $defaultValue;
     }
     static::$enumConstants[$class] = $constants;
 }
 public function getFriends2()
 {
     //是否需要检查聊天num
     $is_chat_num = intval($_REQUEST["chat_num"]);
     if ($is_chat_num > 0) {
         $sql_f = "select  fromUserId as uid from __TABLE__ where  toUserId={$this->mid} and flagNew=1";
         $chats = D("Chat")->query($sql_f);
         foreach ($chats as $key => $v) {
             $chat_ids[] = $v["uid"];
         }
         $chat_nums = array_count_values($chat_ids);
     }
     //在线好友
     $friends = $this->api->friend_get($this->mid);
     $map["uid"] = array("IN", $friends);
     $map["activeTime"] = array("GT", time() - 15 * 60);
     $daoOnline = D("UserOnline");
     $onlineFris = $daoOnline->where($map)->findAll();
     //echo $daoOnline->getLastSql();
     //不输出离线用户的num
     //		if($is_chat_num>0){
     //			$onlineFris = $onlineFris?$onlineFris:array();
     //			$onlineFris = array_merge($onlineFris,$chats);
     //		}
     foreach ($onlineFris as $key => $v) {
         $onlineFris[$key]["mini"] = getShortMini(getUserMini($v["uid"]), 8);
         $onlineFris[$key]["head"] = getUserFace($v["uid"]);
         if ($is_chat_num > 0) {
             $onlineFris[$key]["chat_num"] = $chat_nums[$v["uid"]];
             $onlineFris[$key]["uname"] = $onlineFris[$key]["uname"] ? $onlineFris[$key]["uname"] : getUserName($v["uid"]);
         }
     }
     //dump($onlineFris);
     echo json_encode($onlineFris);
 }
Example #20
0
 /**
  * It counts the number of occurrences of every HTTP response
  * obtained by the request.
  *
  * @param array $links Array of links
  * @return array Flat array of HTTP responses and their occurrences
  */
 public function countTheOccurrencesOfHttpResponses($links)
 {
     $httpStatusOccurrences = array_count_values(array_map(function ($value) {
         return $value['httpStatus'];
     }, $links));
     return $httpStatusOccurrences;
 }
Example #21
0
 public function __construct($turnBack = 10, $condition = array())
 {
     $publicDay = date('Y-m-d');
     //$publicDay = '2012-10-20';
     $txt = '';
     $turnBackDay = date("Y-m-d", strtotime("-" . $turnBack . " day", strtotime($publicDay)));
     $rsCon = Pond::find()->all();
     foreach ($rsCon as $item) {
         $txt = $txt . $item->tags;
     }
     $txt = '##@' . $txt . '##@';
     $txt = str_replace(array(', ,', ',,'), ',', $txt);
     $txt = str_replace(array('##@,', ',##@'), '', $txt);
     //$txt = 'พี่ปลาอายุ40,พี่ปลาอายุ40,test2,test3 ,test4,พี่ปลาอายุ50,พี่ปลาอายุ50,test2,พี่ปลาอายุ40,พี่ปลาอายุ40,test5,test3,พี่ปลาอายุ50,พี่ปลาอายุ50,พี่ปลาอายุ50';
     $arTag = explode(',', $txt, -1);
     foreach ($arTag as $key => $val) {
         $arTag[$key] = trim($val);
     }
     $countValAr = array_count_values($arTag);
     arsort($countValAr);
     $targetArray = array();
     $icount = 0;
     foreach ($countValAr as $key => $value) {
         $targetArray[] = $key;
         if ($icount >= 9) {
             break;
         }
         $icount = $icount + 1;
     }
     $this->arTagCount = $countValAr;
     $this->arTagResult = $targetArray;
 }
Example #22
0
 /**
  * see class description
  * 
  * @param array $A
  *        	Either a vector or a collection of tokens to be transformed to a vector
  * @param array $B
  *        	Either a vector or a collection of tokens to be transformed to a vector
  * @return float The euclidean distance between $A and $B
  */
 public function dist(&$A, &$B)
 {
     if (is_int(key($A))) {
         $v1 = array_count_values($A);
     } else {
         $v1 =& $A;
     }
     if (is_int(key($B))) {
         $v2 = array_count_values($B);
     } else {
         $v2 =& $B;
     }
     $r = array();
     foreach ($v1 as $k => $v) {
         $r[$k] = $v;
     }
     foreach ($v2 as $k => $v) {
         if (isset($r[$k])) {
             $r[$k] -= $v;
         } else {
             $r[$k] = $v;
         }
     }
     return sqrt(array_sum(array_map(function ($x) {
         return $x * $x;
     }, $r)));
 }
Example #23
0
 /**
  * Tests hook_post_update_NAME().
  */
 public function testPostUpdate()
 {
     $this->runUpdates();
     $this->assertRaw('<h3>Update first</h3>');
     $this->assertRaw('First update');
     $this->assertRaw('<h3>Update second</h3>');
     $this->assertRaw('Second update');
     $this->assertRaw('<h3>Update test1</h3>');
     $this->assertRaw('Test1 update');
     $this->assertRaw('<h3>Update test0</h3>');
     $this->assertRaw('Test0 update');
     $this->assertRaw('<h3>Update test_batch</h3>');
     $this->assertRaw('Test post update batches');
     // Test state value set by each post update.
     $updates = ['update_test_postupdate_post_update_first', 'update_test_postupdate_post_update_second', 'update_test_postupdate_post_update_test1', 'update_test_postupdate_post_update_test0', 'update_test_postupdate_post_update_test_batch-1', 'update_test_postupdate_post_update_test_batch-2', 'update_test_postupdate_post_update_test_batch-3'];
     $this->assertIdentical($updates, \Drupal::state()->get('post_update_test_execution', []));
     // Test post_update key value stores contains a list of the update functions
     // that have run.
     $existing_updates = array_count_values(\Drupal::keyValue('post_update')->get('existing_updates'));
     $expected_updates = ['update_test_postupdate_post_update_first', 'update_test_postupdate_post_update_second', 'update_test_postupdate_post_update_test1', 'update_test_postupdate_post_update_test0', 'update_test_postupdate_post_update_test_batch'];
     foreach ($expected_updates as $expected_update) {
         $this->assertEqual($existing_updates[$expected_update], 1, new FormattableMarkup("@expected_update exists in 'existing_updates' key and only appears once.", ['@expected_update' => $expected_update]));
     }
     $this->drupalGet('update.php/selection');
     $this->assertText('No pending updates.');
 }
Example #24
0
 /**
  * Spawns another worker, based on which need more.
  * @return void
  */
 private function _spawnWorker(&$children)
 {
     $count = array_count_values($children);
     $parent = getmypid();
     $candidates = array();
     // find a list of candidate workers
     foreach ($this->_workers as $id => $worker) {
         if (!isset($count[$id]) || $count[$id] < $worker->_spawn_config['processes']) {
             $candidates[] = $worker;
         }
     }
     // shuffle the candidates, take the first
     shuffle($candidates);
     $worker = array_pop($candidates);
     // fork the process
     if ($pid = $this->fork()) {
         //$this->_logger->debug(sprintf("spawned child #%d for worker %d",$pid,$worker->_spawn_id));
         $children[$pid] = $worker->_spawn_id;
         return;
     } else {
         $this->_worker = $worker;
         $this->_parent = $parent;
         $this->onFork(getmypid());
         $code = $this->_executeWorker($worker);
         $this->onTerminate($code);
         exit($code);
     }
 }
Example #25
0
function gauss($data, $field = FALSE)
{
    if ($field) {
        // tranforms results to unidimensional array
        $gauss = array();
        foreach ($data as $row) {
            array_push($gauss, $row->{$field});
        }
    } else {
        $gauss = $data;
    }
    // count frequency of values
    $gauss = array_count_values($gauss);
    // fills values gaps
    for ($i = 0; $i <= 10; $i++) {
        if (!isset($gauss[$i])) {
            $gauss[$i] = 0;
        } else {
            $gauss[$i] = $gauss[$i];
        }
    }
    // sorts array by key
    ksort($gauss);
    return $gauss;
}
Example #26
0
 public function matches()
 {
     $index = array_count_values(explode(' ', $this->text));
     if (isset($index[$this->params['find']])) {
         $this->count = $index[$this->params['find']];
     }
 }
 function ngrams($data, $max_ngs = DEPTH, $max_n = N)
 {
     $data = preg_replace("/[^a-zA-Z\\s]/", "", $data);
     $words = str_word_count(strtolower($data), 1);
     $ngrams = array();
     // split words into ngramgs
     foreach ($words as $word) {
         $word = $word;
         $length = strlen($word);
         for ($index = 0; $index < $length; $index++) {
             for ($n = 1; $n <= $max_n; $n++) {
                 $ngram = substr($word, $index, $n);
                 if (strlen($ngram) < $n) {
                     continue;
                 }
                 $ngrams[] = $ngram;
             }
         }
     }
     // determine ngram frequency counts
     $frequencies = array_count_values($ngrams);
     arsort($frequencies);
     // throw away all but the top 750 most frequently occuring ngrams
     $frequencies = array_slice($frequencies, 0, $max_ngs);
     return $frequencies;
 }
Example #28
0
 public function getAttributeValues()
 {
     $model = Mage::registry('entity_attribute');
     $customerCollection = Mage::getResourceModel('customer/customer_collection');
     $customerCollection->addAttributeToSelect($model->getAttributeCode());
     $customerCollection->addAttributeToFilter($model->getAttributeCode(), array('notnull' => true));
     $customerValue = $customerCollection->getColumnValues($model->getAttributeCode());
     $guestCollection = Mage::getModel('amcustomerattr/guest')->getCollection();
     $guestCollection->addFieldToFilter($model->getAttributeCode(), array('notnull' => true));
     $guestValue = $guestCollection->getColumnValues($model->getAttributeCode());
     $valuesAsString = array_merge($customerValue, $guestValue);
     $valuesAsArray = array();
     foreach ($valuesAsString as $attrIdsString) {
         $valuesAsArray = array_merge($valuesAsArray, explode(',', $attrIdsString));
     }
     $optionCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')->setAttributeFilter($model->getAttributeId())->addFieldToFilter('main_table.option_id', array('in' => $valuesAsArray))->setStoreFilter();
     $qtyValues = array_count_values($valuesAsArray);
     $result = array();
     $options = $optionCollection->toOptionArray();
     $sum = array_sum($qtyValues);
     foreach ($options as $value) {
         $qty = $qtyValues[$value['value']];
         $label = $value['label'] . ' - ' . $qty . ' (' . round($qty / $sum * 100, 1) . '%)';
         $result[$value['value']] = array('qty' => $qty, 'label' => $label);
     }
     return $result;
 }
Example #29
-1
 /**
  * Show the application dashboard to the user.
  *
  * @return Response
  */
 public function index()
 {
     $tweets = Tweet::all();
     $words = [];
     $aux = [];
     if ($tweets->count() != 0) {
         foreach ($tweets as $tweet) {
             $aux = (array) $tweet->tweet;
             $aux = $aux[0];
             $aux = str_replace(',', '', $aux);
             $aux = explode(' ', $aux);
             $words = array_merge($aux, $words);
         }
         $words = array_count_values($words);
         arsort($words);
         $words = array_keys($words);
         $aux = [];
         for ($i = 0; $i < sizeof($words); $i++) {
             if (strlen($words[$i]) > 3) {
                 $aux[] = $words[$i];
             }
         }
     }
     $words = $aux;
     $user = Auth::user();
     return view('home', compact('user', 'words'));
 }
 /**
  * Display a summary of all surveys.
  *
  * @return response
  */
 public function summary()
 {
     // Fetch all completed surveys
     $surveys = Survey::all();
     // Stats
     $crumpled = 0;
     $folded = 0;
     $addresses = [];
     $thinking = [];
     foreach ($surveys as $survey) {
         // Folded/Crumpled
         if ($survey->crumpled) {
             $crumpled++;
         } else {
             $folded++;
         }
         // Thinking (seperate thoughts)
         $thinking = array_merge(explode(',', trim($survey->thinking)), $thinking);
         // Location
         $addresses[] = $survey->address;
     }
     // Calculate frequencies
     $addresses = array_count_values($addresses);
     $thinking = array_count_values($thinking);
     // Sort by value in descending order
     arsort($addresses);
     arsort($thinking);
     return view('summary', ['crumpled' => $crumpled, 'folded' => $folded, 'addresses' => $addresses, 'thoughts' => array_keys(array_slice($thinking, 0, 5)), 'numSurveys' => count($surveys)]);
 }