function getTopFive($uid) { $db = new DB(); //Create an array of all companies in format [companyname => companyid] $sql = "SELECT company_id, Name FROM Companies"; $compresults = $db->execute($sql); $allcompanies = []; $compavg = []; while ($row = $compresults->fetch_assoc()) { $allcompanies[$row['Name']] = $row['company_id']; } //Find the user's priority selection $usrsql = "SELECT priority FROM People WHERE person_id = {$uid}"; $usrresults = $db->execute($usrsql); $usrresults = $usrresults->fetch_assoc(); $priority = $usrresults['priority']; //get the average rating of each company in the prioritized category and store in an array foreach ($allcompanies as $key => $value) { //hey guess what SQL can calculate column averages for you $avgsql = "SELECT AVG({$priority}) FROM Reviews WHERE company_id = {$value}"; $avgresults = $db->execute($avgsql); $avgresults = $avgresults->fetch_assoc(); $compavg[$key] = implode(".", $avgresults); } //sort finished array high to low and grab the top 5 arsort($compavg); $topfive = array_slice($compavg, 0, 5); return $topfive; }
public static function get_form_actions($action = 'all') { $temp_actions = self::$registered_actions; if (empty($temp_actions)) { self::actions_init(); $temp_actions = self::$registered_actions->actions; } else { $temp_actions = $temp_actions->actions; } $actions = array(); foreach ($temp_actions as $a) { if ('all' != $action && $a->id_base == $action) { return $a; } $actions[$a->id_base] = $a; } unset($temp_actions, $a); $action_limit = 10; if (count($actions) <= $action_limit) { return $actions; } // remove the last few inactive icons if there are too many $temp_actions = $actions; arsort($temp_actions); foreach ($temp_actions as $type => $a) { if (!isset($a->action_options['active']) || empty($a->action_options['active'])) { unset($actions[$type]); if (count($actions) <= $action_limit) { break; } } unset($type, $a); } return $actions; }
/** * Generates statistical, based on n-grams language profile from the given text. * @param string $string The input text. It should be UTF-8 encoded. Practically it should be at least 3000 characters long, 40000 characters size is for increased accuracy. * @param int $n_grams_max (optional) The size of the array of the generated n-grams. * @param int $n_max (optional) The limit if the number of characters that a n-gram may contain. * @return array An array that contains cunstructed n-grams, sorted in reverse order by their frequences. Frequences are not stored in the array. */ function &_api_generate_n_grams(&$string, $encoding, $n_grams_max = 350, $n_max = 4) { if (empty($string)) { return array(); } // We construct only lowercase n-grams if it is applicable for the given language. // Removing all puntuation and some other non-letter characters. Apostrophe characters stay. // Splitting the sample text into separate words. $words = preg_split('/_/u', preg_replace('/[\\x00-\\x1F\\x20-\\x26\\x28-\\x3E\\?@\\x5B-\\x60{|}~\\x7F]/u', '_', ' ' . api_strtolower(api_utf8_encode($string, $encoding), 'UTF-8') . ' '), -1, PREG_SPLIT_NO_EMPTY); $prefix = '_'; // Beginning of a word. $suffix = str_repeat('_', $n_max); // End of a word. Only the last '_' stays. $n_grams = array(); // The array that will contain the constructed n-grams. foreach ($words as $word) { $k = api_strlen($word, 'UTF-8') + 1; $word = $prefix . $word . $suffix; for ($n = 1; $n <= $n_max; $n++) { for ($i = 0; $i < $k; $i++) { $n_gram = api_utf8_decode(api_substr($word, $i, $n, 'UTF-8'), $encoding); if (isset($n_grams[$n_gram])) { $n_grams[$n_gram]++; } else { $n_grams[$n_gram] = 1; } } } } // Sorting the n-grams in reverse order by their frequences. arsort($n_grams); // Reduction the number of n-grams. return array_keys(array_slice($n_grams, 0, $n_grams_max)); }
public function Pinyin($_String, $_Code = 'UTF8') { //GBK页面可改为gb2312,其他随意填写为UTF8 $_DataKey = "a|ai|an|ang|ao|ba|bai|ban|bang|bao|bei|ben|beng|bi|bian|biao|bie|bin|bing|bo|bu|ca|cai|can|cang|cao|ce|ceng|cha" . "|chai|chan|chang|chao|che|chen|cheng|chi|chong|chou|chu|chuai|chuan|chuang|chui|chun|chuo|ci|cong|cou|cu|" . "cuan|cui|cun|cuo|da|dai|dan|dang|dao|de|deng|di|dian|diao|die|ding|diu|dong|dou|du|duan|dui|dun|duo|e|en|er" . "|fa|fan|fang|fei|fen|feng|fo|fou|fu|ga|gai|gan|gang|gao|ge|gei|gen|geng|gong|gou|gu|gua|guai|guan|guang|gui" . "|gun|guo|ha|hai|han|hang|hao|he|hei|hen|heng|hong|hou|hu|hua|huai|huan|huang|hui|hun|huo|ji|jia|jian|jiang" . "|jiao|jie|jin|jing|jiong|jiu|ju|juan|jue|jun|ka|kai|kan|kang|kao|ke|ken|keng|kong|kou|ku|kua|kuai|kuan|kuang" . "|kui|kun|kuo|la|lai|lan|lang|lao|le|lei|leng|li|lia|lian|liang|liao|lie|lin|ling|liu|long|lou|lu|lv|luan|lue" . "|lun|luo|ma|mai|man|mang|mao|me|mei|men|meng|mi|mian|miao|mie|min|ming|miu|mo|mou|mu|na|nai|nan|nang|nao|ne" . "|nei|nen|neng|ni|nian|niang|niao|nie|nin|ning|niu|nong|nu|nv|nuan|nue|nuo|o|ou|pa|pai|pan|pang|pao|pei|pen" . "|peng|pi|pian|piao|pie|pin|ping|po|pu|qi|qia|qian|qiang|qiao|qie|qin|qing|qiong|qiu|qu|quan|que|qun|ran|rang" . "|rao|re|ren|reng|ri|rong|rou|ru|ruan|rui|run|ruo|sa|sai|san|sang|sao|se|sen|seng|sha|shai|shan|shang|shao|" . "she|shen|sheng|shi|shou|shu|shua|shuai|shuan|shuang|shui|shun|shuo|si|song|sou|su|suan|sui|sun|suo|ta|tai|" . "tan|tang|tao|te|teng|ti|tian|tiao|tie|ting|tong|tou|tu|tuan|tui|tun|tuo|wa|wai|wan|wang|wei|wen|weng|wo|wu" . "|xi|xia|xian|xiang|xiao|xie|xin|xing|xiong|xiu|xu|xuan|xue|xun|ya|yan|yang|yao|ye|yi|yin|ying|yo|yong|you" . "|yu|yuan|yue|yun|za|zai|zan|zang|zao|ze|zei|zen|zeng|zha|zhai|zhan|zhang|zhao|zhe|zhen|zheng|zhi|zhong|" . "zhou|zhu|zhua|zhuai|zhuan|zhuang|zhui|zhun|zhuo|zi|zong|zou|zu|zuan|zui|zun|zuo"; $_DataValue = "-20319|-20317|-20304|-20295|-20292|-20283|-20265|-20257|-20242|-20230|-20051|-20036|-20032|-20026|-20002|-19990" . "|-19986|-19982|-19976|-19805|-19784|-19775|-19774|-19763|-19756|-19751|-19746|-19741|-19739|-19728|-19725" . "|-19715|-19540|-19531|-19525|-19515|-19500|-19484|-19479|-19467|-19289|-19288|-19281|-19275|-19270|-19263" . "|-19261|-19249|-19243|-19242|-19238|-19235|-19227|-19224|-19218|-19212|-19038|-19023|-19018|-19006|-19003" . "|-18996|-18977|-18961|-18952|-18783|-18774|-18773|-18763|-18756|-18741|-18735|-18731|-18722|-18710|-18697" . "|-18696|-18526|-18518|-18501|-18490|-18478|-18463|-18448|-18447|-18446|-18239|-18237|-18231|-18220|-18211" . "|-18201|-18184|-18183|-18181|-18012|-17997|-17988|-17970|-17964|-17961|-17950|-17947|-17931|-17928|-17922" . "|-17759|-17752|-17733|-17730|-17721|-17703|-17701|-17697|-17692|-17683|-17676|-17496|-17487|-17482|-17468" . "|-17454|-17433|-17427|-17417|-17202|-17185|-16983|-16970|-16942|-16915|-16733|-16708|-16706|-16689|-16664" . "|-16657|-16647|-16474|-16470|-16465|-16459|-16452|-16448|-16433|-16429|-16427|-16423|-16419|-16412|-16407" . "|-16403|-16401|-16393|-16220|-16216|-16212|-16205|-16202|-16187|-16180|-16171|-16169|-16158|-16155|-15959" . "|-15958|-15944|-15933|-15920|-15915|-15903|-15889|-15878|-15707|-15701|-15681|-15667|-15661|-15659|-15652" . "|-15640|-15631|-15625|-15454|-15448|-15436|-15435|-15419|-15416|-15408|-15394|-15385|-15377|-15375|-15369" . "|-15363|-15362|-15183|-15180|-15165|-15158|-15153|-15150|-15149|-15144|-15143|-15141|-15140|-15139|-15128" . "|-15121|-15119|-15117|-15110|-15109|-14941|-14937|-14933|-14930|-14929|-14928|-14926|-14922|-14921|-14914" . "|-14908|-14902|-14894|-14889|-14882|-14873|-14871|-14857|-14678|-14674|-14670|-14668|-14663|-14654|-14645" . "|-14630|-14594|-14429|-14407|-14399|-14384|-14379|-14368|-14355|-14353|-14345|-14170|-14159|-14151|-14149" . "|-14145|-14140|-14137|-14135|-14125|-14123|-14122|-14112|-14109|-14099|-14097|-14094|-14092|-14090|-14087" . "|-14083|-13917|-13914|-13910|-13907|-13906|-13905|-13896|-13894|-13878|-13870|-13859|-13847|-13831|-13658" . "|-13611|-13601|-13406|-13404|-13400|-13398|-13395|-13391|-13387|-13383|-13367|-13359|-13356|-13343|-13340" . "|-13329|-13326|-13318|-13147|-13138|-13120|-13107|-13096|-13095|-13091|-13076|-13068|-13063|-13060|-12888" . "|-12875|-12871|-12860|-12858|-12852|-12849|-12838|-12831|-12829|-12812|-12802|-12607|-12597|-12594|-12585" . "|-12556|-12359|-12346|-12320|-12300|-12120|-12099|-12089|-12074|-12067|-12058|-12039|-11867|-11861|-11847" . "|-11831|-11798|-11781|-11604|-11589|-11536|-11358|-11340|-11339|-11324|-11303|-11097|-11077|-11067|-11055" . "|-11052|-11045|-11041|-11038|-11024|-11020|-11019|-11018|-11014|-10838|-10832|-10815|-10800|-10790|-10780" . "|-10764|-10587|-10544|-10533|-10519|-10331|-10329|-10328|-10322|-10315|-10309|-10307|-10296|-10281|-10274" . "|-10270|-10262|-10260|-10256|-10254"; $_TDataKey = explode('|', $_DataKey); $_TDataValue = explode('|', $_DataValue); $_Data = array_combine($_TDataKey, $_TDataValue); arsort($_Data); reset($_Data); if ($_Code != 'gb2312') { $_String = $this->_U2_Utf8_Gb($_String); } $_Res = ''; for ($i = 0; $i < strlen($_String); $i++) { $_P = ord(substr($_String, $i, 1)); if ($_P > 160) { $_Q = ord(substr($_String, ++$i, 1)); $_P = $_P * 256 + $_Q - 65536; } $_Res .= $this->_Pinyin($_P, $_Data); } return str_replace("_", '', $_Res); // return preg_replace("/[^a-z0-9]*/", '', $_Res); }
function array_sort2($arr, $keys, $type = 'asc') { if (empty($arr)) { return false; } $keysvalue = $new_array = array(); foreach ($arr as $k => $v) { $keysvalue[$k] = $v[$keys]; } if ($type == 'asc') { asort($keysvalue); } else { arsort($keysvalue); } reset($keysvalue); $count = count($keysvalue); foreach ($keysvalue as $k => $v) { if ($type == 'asc') { $new_array[$k] = $arr[$k]; } else { $new_array[$count - 1 - $k] = $arr[$k]; } } return $new_array; }
private function generateTagCloud($tags, $resize = true, $min_font_size = 9, $max_font_size = 25, $font_weight) { if ($resize == true) { arsort($tags); $max_qty = max(array_values($tags)); $min_qty = min(array_values($tags)); $spread = $max_qty - $min_qty; if ($spread == 0) { $spread = 1; } $step = ((int) $max_font_size - (int) $min_font_size) / $spread; $cloud = array(); foreach ($tags as $key => $value) { $size = rand((int) $min_font_size, (int) $max_font_size); $cloud[] = '<a href="' . $this->url->link('product/search', 'tag=' . $value) . '" style="text-decoration:none;font-size:' . $size . 'px;font-weight:' . $font_weight . ';" title="">' . $value . '</a> '; } } else { foreach ($tags as $key => $value) { $cloud[] = '<a href="' . $this->url->link('product/search', 'tag=' . $value) . '" style="text-decoration:none;" title="">' . $value . '</a> '; } } $tagcloud = ''; shuffle($cloud); for ($x = 0; $x < count($cloud); $x++) { $tagcloud .= $cloud[$x]; } return $tagcloud; }
public function classify($string) { if ($this->total_samples === 0) { return array(); } $tokens = $this->tokenizer->tokenize($string); $total_score = 0; $scores = array(); foreach ($this->subjects as $subject => $subject_data) { $subject_data['prior_value'] = log($subject_data['count_samples'] / $this->total_samples); $this->subjects[$subject] = $subject_data; $scores[$subject] = 0; foreach ($tokens as $token) { $count = isset($this->tokens[$token][$subject]) ? $this->tokens[$token][$subject] : 0; $scores[$subject] += log(($count + 1) / ($subject_data['count_tokens'] + $this->total_tokens)); } $scores[$subject] = $subject_data['prior_value'] + $scores[$subject]; $total_score += $scores[$subject]; } $min = min($scores); $sum = 0; foreach ($scores as $subject => $score) { $scores[$subject] = exp($score - $min); $sum += $scores[$subject]; } $total = 1 / $sum; foreach ($scores as $subject => $score) { $scores[$subject] = $score * $total; } arsort($scores); $max = max($scores); $maxs = array_search(max($scores), $scores); return $maxs; }
public function getUserLang() { $langs = array(); if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\\s*(;\\s*q\\s*=\\s*(1|0\\.[0-9]+))?/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse); if (count($lang_parse[1])) { $langs = array_combine($lang_parse[1], $lang_parse[4]); $tmp = array(); foreach ($langs as $lang => $val) { if (MULTILINGUAL_EXTENDED == true) { if (strlen($lang) == 5) { $lang = substr($lang, 0, 2) . '-' . strtoupper(substr($lang, 3, 2)); $tmp[$lang] = $val; } } else { $lang = substr($lang, 0, 2); $tmp[$lang] = $val; } if ($val === '') { $tmp[$lang] = 1; } } $langs = $tmp; arsort($langs, SORT_NUMERIC); } } return current(array_keys($langs)); }
private function getOrigins($dateBetween) { $directLink = $this->l('Direct link'); $sql = 'SELECT http_referer FROM ' . _DB_PREFIX_ . 'connections WHERE 1 ' . Shop::addSqlRestriction() . ' AND date_add BETWEEN ' . $dateBetween; $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->query($sql); $websites = array($directLink => 0); while ($row = Db::getInstance(_PS_USE_SQL_SLAVE_)->nextRow($result)) { if (!isset($row['http_referer']) || empty($row['http_referer'])) { ++$websites[$directLink]; } else { $website = preg_replace('/^www./', '', parse_url($row['http_referer'], PHP_URL_HOST)); if (!isset($websites[$website])) { $websites[$website] = 1; } else { ++$websites[$website]; } } } arsort($websites); return $websites; }
/** * @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; }
/** * Array of best matched post_ids. Better matches have a lower index! * * @return int[] */ public function get_possible_ids_ordered() { $pages_with_name = $this->data; $slugs = $this->slugs; $parent_slugs = array_slice($slugs, 0, -1); foreach ($this->data as $key => $page) { if ($page->parent_name) { $slug_pos = array_keys($slugs, $page->post_name, true); $par_slug_pos = array_keys($slugs, $page->parent_name, true); if ((bool) $par_slug_pos !== false && (bool) $slug_pos !== false) { $remove = true; foreach ($slug_pos as $child_slug_pos) { if (in_array($child_slug_pos - 1, $par_slug_pos)) { $remove = false; break; } } if ($remove === true) { unset($pages_with_name[$key]); } } } } $possible_ids = array(); foreach ($pages_with_name as $key => $page) { $correct_slug = end($slugs); if ($page->post_name === $correct_slug) { $possible_ids[$page->ID] = $this->calculate_score($parent_slugs, $pages_with_name, $page); } } arsort($possible_ids); return array_keys($possible_ids); }
public function executeShow(sfWebRequest $request) { $this->question = $this->getRoute()->getObject(); // ログイン者の回答済み内容 $yourAnswer = Doctrine::getTable('VoteAnswer')->findOneByMemberIdAndVoteQuestionId($this->getUser()->getMemberId(), $this->question->getId()); if ($yourAnswer || $this->question->getMemberId() == $this->getUser()->getMemberId()) { // 結果出力のためのデータ集計 $answers = Doctrine::getTable('VoteAnswer')->findByVoteQuestionId($this->question->getId()); $options = Doctrine::getTable('VoteQuestionOption')->findByVoteQuestionId($this->question->getId()); $this->options = $options->toKeyValueArray('id', 'body'); $this->answerTotal = array(); $this->total = 0; foreach ($answers as $answer) { $this->total++; if (isset($this->answerTotal[$answer->getVoteQuestionOptionId()])) { $this->answerTotal[$answer->getVoteQuestionOptionId()]++; } else { $this->answerTotal[$answer->getVoteQuestionOptionId()] = 1; } } arsort($this->answerTotal); } else { // 回答済みでないかつ作成者でないときフォームオブジェクト作成 $voteAnswer = new VoteAnswer(); $voteAnswer->setVoteQuestion($this->question); $voteAnswer->setMember($this->getUser()->getMember()); $this->form = new VoteAnswerForm($voteAnswer); } }
/** * Formats any number of seconds into a readable string * * @param int Seconds to format * @param int Number of divisors to return, ie (3) gives '1 Year, 3 Days, 9 Hours' whereas (2) gives '1 Year, 3 Days' * @param string Seperator to use between divisors * @param array Set of Name => Seconds pairs to use as divisors, ie array('Year' => 31536000) * @return string Formatted interval */ public function format_interval($seconds, $precision = -1, $separator = ', ', $divisors = NULL) { // Default set of divisors to use if (!isset($divisors)) { $divisors = array('Year' => 31536000, 'Month' => 2628000, 'Day' => 86400, 'Hour' => 3600, 'Minute' => 60, 'Second' => 1); } arsort($divisors); // Iterate over each divisor foreach ($divisors as $name => $divisor) { // If there is at least 1 of thie divisor's time period if ($value = floor($seconds / $divisor)) { // Add the formatted value - divisor pair to the output array. // Omits the plural for a singular value. if ($value == 1) { $out[] = "{$value} {$name}"; } else { $out[] = "{$value} {$name}s"; } // Stop looping if we've hit the precision limit if (--$precision == 0) { break; } } // Strip this divisor from the total seconds $seconds %= $divisor; } // Join the value - divisor pairs with $separator between each element return implode($separator, $out); }
/** * Scan the exports directory, return the files grouped into intervals of 3 minutes, newest first. * * @param string $dir fullpath to the Exports folder. (optional) * @return array */ function group_exports($dir = null) { $ignored = array('.', '..', '.svn', '.git', '.htaccess'); if (!$dir) { $dir = \PressBooks\Modules\Export\Export::getExportFolder(); } else { $dir = rtrim($dir, '/') . '/'; } $files = array(); foreach (scandir($dir) as $file) { if (in_array($file, $ignored)) { continue; } $files[$file] = filemtime($dir . $file); } arsort($files); $interval = 3 * 60; // Three minutes $pos = 0; $output = array(); foreach ($files as $file => $timestamp) { if (0 == $pos) { $pos = $timestamp; } if ($pos - $timestamp > $interval) { $pos = $timestamp; } $output[$pos][] = $file; } return $output; }
/** * Retrieves the overrides data * * @param boolean True if all overrides shall be returned without considering pagination, defaults to false * * @return array Array of objects containing the overrides of the override.ini file * * @since 2.5 */ public function getOverrides($all = false) { // Get a storage key $store = $this->getStoreId(); // Try to load the data from internal storage if (!empty($this->cache[$store])) { return $this->cache[$store]; } // Parse the override.ini file in oder to get the keys and strings $filename = constant('JPATH_' . strtoupper($this->getState('filter.client'))) . DS . 'language' . DS . 'overrides' . DS . $this->getState('filter.language') . '.override.ini'; $strings = LanguagesHelper::parseFile($filename); // Consider the odering if ($this->getState('list.ordering') == 'text') { if (strtoupper($this->getState('list.direction')) == 'DESC') { arsort($strings); } else { asort($strings); } } else { if (strtoupper($this->getState('list.direction')) == 'DESC') { krsort($strings); } else { ksort($strings); } } // Consider the pagination if (!$all && $this->getState('list.limit') && $this->getTotal() > $this->getState('list.limit')) { $strings = array_slice($strings, $this->getStart(), $this->getState('list.limit'), true); } // Add the items to the internal cache $this->cache[$store] = $strings; return $this->cache[$store]; }
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; }
protected function getInternalData() { $wow = WoW::getInstance(); try { $adapter = $wow->getAdapter('WoWAPI'); $result = $adapter->getData('guild'); } catch (Exception $e) { return $e->getMessage(); } $achievements = array(); foreach ($result->body->achievements->achievementsCompleted as $key => $achievement) { $achievements[$achievement] = new stdClass(); $achievements[$achievement]->timestamp = $result->body->achievements->achievementsCompletedTimestamp[$key]; } arsort($achievements); $achievements = array_slice($achievements, 0, $this->params->module->get('rows', 10) ? $this->params->module->get('rows', 10) : count($achievements), true); foreach ($achievements as $key => $achievement) { try { $result = $adapter->getAchievement($key); } catch (Exception $e) { unset($achievements[$key]); continue; } $achievements[$key]->id = $key; $achievements[$key]->name = $result->body->title; $achievements[$key]->image = 'http://media.blizzard.com/wow/icons/18/' . $result->body->icon . '.jpg'; $achievements[$key]->link = $wow->getBattleNetUrl() . 'achievement#15080:a' . $key; // TODO 15080 ?? $achievements[$key]->link = $this->link($achievements[$key]); $achievements[$key]->raw = $result->body; } return $achievements; }
/** * @before _secure, _admin */ public function logs($action = "", $name = "") { $this->seo(array("title" => "Activity Logs", "view" => $this->getLayoutView())); $view = $this->getActionView(); if ($action == "unlink") { $file = APP_PATH . "/logs/" . $name . ".txt"; @unlink($file); $this->redirect("/analytics/logs"); } $logs = array(); $path = APP_PATH . "/logs"; $iterator = new DirectoryIterator($path); foreach ($iterator as $item) { if (!$item->isDot() && substr($item->getFilename(), 0, 1) != ".") { $logs[] = $item->getFilename(); } } arsort($logs); // find the directory size exec('du -h ' . $path, $output, $return); if ($return == 0) { $output = array_pop($output); $output = explode("/", $output); $size = array_shift($output); $size = trim($size); } else { $size = 'Failed to get size'; } $view->set("size", $size); $view->set("logs", $logs); }
function dodefault() { $keywords = trim($this->post['keywords']); $results = array(); $nums = array(); //匹配次数,作为排序权重 if ($keywords) { $keywords = preg_replace("/\\s+/", ' ', $keywords); $kws = explode(' ', $keywords); $kws = array_map('trim', $kws); $kws = array_unique($kws); $keywords = implode(' ', $kws); $i = 0; foreach ($_ENV['actions']->data as $action => $text) { foreach ($kws as $kw) { if (strpos(strtolower($text), strtolower($kw)) !== FALSE) { $nums[$i] = 0; $results[$i] = $_ENV['actions']->getHTML($action, $text, $kws, $nums[$i]); $i++; break; } } } } arsort($nums); $results2 = array(); foreach ($nums as $key => $value) { $results2[] = $results[$key]; } $this->view->assign("keywords", $keywords); $this->view->assign("list", $results2); $this->view->display('admin_actions'); }
function ArraySortBy($Array, $ValueKey, $SortFlag = SORT_NUMERIC, $Reverse = false, $DefaultValue = NULL) { $Keys = array(); if (is_array($ValueKey)) { $ValueFunction = $ValueKey[1]; $ValueKey = $ValueKey[0]; } foreach ($Array as $Key => $SubArray) { if (is_array($SubArray)) { if (array_key_exists($ValueKey, $SubArray)) { if (isset($ValueFunction)) { $Keys[$Key] = $ValueFunction($SubArray[$ValueKey]); } else { $Keys[$Key] = $SubArray[$ValueKey]; } } else { $Keys[$Key] = $DefaultValue; } } } if ($Reverse) { arsort($Keys, $SortFlag); } else { asort($Keys, $SortFlag); } $Result = array(); foreach ($Keys as $Key => $Value) { $Result[] = $Array[$Key]; } return $Result; }
public function renderDefault() { $clanky = array(); $this->backlink = $this->storeRequest(); $moje_clanky = $this->pravaKClankum($this->redakce->findClankyByAutor($this->getUser()->id)); $clanky_ke_schvaleni = $this->pravaKClankum($this->redakce->clankyKeSchvaleni($this->prava->seznamPrav($this->modul), $this->vyse_prav['vsechny_clanky'])); $seznam_clanku = array_merge($clanky_ke_schvaleni, $moje_clanky); $razeni = array('od' => 'DESC'); if ($this->order) { if (preg_match('~(.*)_DESC~', $this->order, $tmp)) { $razeni = array($tmp[1] => 'DESC'); } else { $razeni = array($this->order => 'ASC'); } if (isset($razeni['rubrika'])) { foreach ($seznam_clanku as $key => $clanek) { $rubriky[$key] = join(' - ', $clanek['rubrika_nazev']); } if ($razeni['rubrika'] == 'ASC') { asort($rubriky); } else { arsort($rubriky); } foreach ($rubriky as $key => $rubrika) { $clanky[] = $seznam_clanku[$key]; } } else { $clanky = $seznam_clanku; } } else { $clanky = $seznam_clanku; } $this->template->clanky = $clanky; $this->template->razeni = $razeni; }
public static function searchNGram($cuv) { $leng = mb_strlen($cuv); $hash = NGram::searchLexemIds($cuv); if (empty($hash)) { return array(); } arsort($hash); $max = current($hash); $lexIds = array_keys($hash, $max); $results = array(); foreach ($lexIds as $id) { $lexem = Model::factory('Lexem')->where('id', $id)->where_gte('charLength', $leng - self::$LENGTH_DIF)->where_lte('charLength', $leng + self::$LENGTH_DIF)->find_one(); if ($lexem) { $results[] = $lexem; if (count($results) == self::$MAX_RESULTS) { break; } } } // Sort the lexems by their Levenshtein distance from $cuv $distances = array(); foreach ($results as $lexem) { $distances[] = Levenshtein::dist($cuv, $lexem->formNoAccent); } array_multisort($distances, $results); return $results; }
public function populyar_post_by_visits() { $post = new Post(); $posts = $post->order_by('time_created', 'desc'); $posts = $posts->get(); $res = $this->like('page', 'blog/post/', 'after')->get(); $sluge = array(); foreach ($res->all as $key => $value) { $post = explode('/', $value->page); if ($post[1] == 'post') { if (array_key_exists($post[2], $sluge)) { $sluge[$post[2]]++; } else { $sluge[$post[2]] = 1; } } } foreach ($posts->all as $post_key => $post_value) { if (!array_key_exists($post_value->slug, $sluge)) { $sluge[$post_value->slug] = 0; } } arsort($sluge); return $sluge; }
function array_sort($array, $on, $order = SORT_ASC) { $new_array = array(); $sortable_array = array(); if (count($array) > 0) { foreach ($array as $k => $v) { if (is_array($v)) { foreach ($v as $k2 => $v2) { if ($k2 == $on) { $sortable_array[$k] = $v2; } } } else { $sortable_array[$k] = $v; } } switch ($order) { case SORT_ASC: asort($sortable_array); break; case SORT_DESC: arsort($sortable_array); break; } foreach ($sortable_array as $k => $v) { $new_array[$k] = $array[$k]; } } return $new_array; }
/** * @return array Get list of browser "plugins" (javascript, media player, etc.) */ private function getEquipment() { $sql = 'SELECT DISTINCT g.* FROM `' . _DB_PREFIX_ . 'connections` c LEFT JOIN `' . _DB_PREFIX_ . 'guest` g ON g.`id_guest` = c.`id_guest` WHERE c.`date_add` BETWEEN ' . ModuleGraph::getDateBetween() . ' ' . Shop::addSqlRestriction(false, 'c'); $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->query($sql); $calcArray = array('jsOK' => 0, 'jsKO' => 0, 'javaOK' => 0, 'javaKO' => 0, 'wmpOK' => 0, 'wmpKO' => 0, 'qtOK' => 0, 'qtKO' => 0, 'realOK' => 0, 'realKO' => 0, 'flashOK' => 0, 'flashKO' => 0, 'directorOK' => 0, 'directorKO' => 0); while ($row = Db::getInstance(_PS_USE_SQL_SLAVE_)->nextRow($result)) { if (!$row['javascript']) { ++$calcArray['jsKO']; continue; } ++$calcArray['jsOK']; $row['windows_media'] ? ++$calcArray['wmpOK'] : ++$calcArray['wmpKO']; $row['real_player'] ? ++$calcArray['realOK'] : ++$calcArray['realKO']; $row['adobe_flash'] ? ++$calcArray['flashOK'] : ++$calcArray['flashKO']; $row['adobe_director'] ? ++$calcArray['directorOK'] : ++$calcArray['directorKO']; $row['sun_java'] ? ++$calcArray['javaOK'] : ++$calcArray['javaKO']; $row['apple_quicktime'] ? ++$calcArray['qtOK'] : ++$calcArray['qtKO']; } if (!$calcArray['jsOK']) { return false; } $equip = array('Windows Media Player' => $calcArray['wmpOK'] / ($calcArray['wmpOK'] + $calcArray['wmpKO']), 'Real Player' => $calcArray['realOK'] / ($calcArray['realOK'] + $calcArray['realKO']), 'Apple Quicktime' => $calcArray['qtOK'] / ($calcArray['qtOK'] + $calcArray['qtKO']), 'Sun Java' => $calcArray['javaOK'] / ($calcArray['javaOK'] + $calcArray['javaKO']), 'Adobe Flash' => $calcArray['flashOK'] / ($calcArray['flashOK'] + $calcArray['flashKO']), 'Adobe Shockwave' => $calcArray['directorOK'] / ($calcArray['directorOK'] + $calcArray['directorKO'])); arsort($equip); return $equip; }
public function __construct($lang = "") { if (\file_exists(\pocketmine\PATH . "src/pocketmine/lang/Installer/" . $lang . ".ini")) { $this->lang = $lang; $this->langfile = \pocketmine\PATH . "src/pocketmine/lang/Installer/" . $lang . ".ini"; } else { $files = []; foreach (new \DirectoryIterator(\pocketmine\PATH . "src/pocketmine/lang/Installer/") as $file) { if ($file->getExtension() === "ini" and \substr($file->getFilename(), 0, 2) === $lang) { $files[$file->getFilename()] = $file->getSize(); } } if (\count($files) > 0) { \arsort($files); \reset($files); $l = \key($files); $l = \substr($l, 0, -4); $this->lang = isset(self::$languages[$l]) ? $l : $lang; $this->langfile = \pocketmine\PATH . "src/pocketmine/lang/Installer/" . $l . ".ini"; } else { $this->lang = "en"; $this->langfile = \pocketmine\PATH . "src/pocketmine/lang/Installer/en.ini"; } } $this->loadLang(\pocketmine\PATH . "src/pocketmine/lang/Installer/en.ini", "en"); if ($this->lang !== "en") { $this->loadLang($this->langfile, $this->lang); } }
/** * Rank / sort items parsed from the log * * @see parseFile() */ public function generateStatistics() { if ($this->items === null) { throw new \Exception('You have to parse a file first'); } $this->statistics = ['hosts' => [], 'files' => []]; array_walk($this->items, function ($item) { $url = parse_url($item->request); $host = $url['host']; $file = $host . $url['path']; if (isset($this->statistics['hosts'][$host])) { $this->statistics['hosts'][$host] += 1; } else { $this->statistics['hosts'][$host] = 1; } if ($item->requestMethod == 'GET' && strpos($url['path'], '.') !== false) { if (isset($this->statistics['files'][$file])) { $this->statistics['files'][$file] += 1; } else { $this->statistics['files'][$file] = 1; } } }); arsort($this->statistics['files']); arsort($this->statistics['hosts']); }
public function index() { $arrType = []; $arrMenu = Menu::getCache(['active' => 0]); if (!empty($arrMenu)) { foreach ($arrMenu as $type => $html) { if (strpos($type, '-') !== false) { unset($arrMenu[$type]); list($type, $subType) = explode('-', $type); $arrMenu[$type][$subType] = '<ol class="dd-list">' . $html . '</ol>'; $arrType[] = $subType; } else { $arrMenu[$type] = '<ol class="dd-list">' . $html . '</ol>'; $arrType[] = $type; } } arsort($arrMenu); } else { $arrMenu = []; } $arrParent = Menu::getCache(['parent' => true]); $admin = Auth::admin()->get(); $permission = new Permission(); $arrPermission = ['frontend' => ['view' => $permission->can($admin, 'menusfrontend_view_all'), 'create' => $permission->can($admin, 'menusfrontend_create_all'), 'edit' => $permission->can($admin, 'menusfrontend_edit_all'), 'delete' => $permission->can($admin, 'menusfrontend_delete_all')], 'backend' => ['view' => $permission->can($admin, 'menusbackend_view_all'), 'create' => $permission->can($admin, 'menusbackend_create_all'), 'edit' => $permission->can($admin, 'menusbackend_edit_all'), 'delete' => $permission->can($admin, 'menusbackend_delete_all')]]; $this->layout->title = 'Menu'; $this->layout->content = View::make('admin.menus-all')->with(['arrMenu' => $arrMenu, 'arrParent' => $arrParent, 'arrType' => $arrType, 'arrPermission' => $arrPermission]); }
function widget() { // Check if obj exists in cache $users = wp_cache_get('active_users'); if ($users == false) { // Generate the query $users = get_users(array('role' => 'student')); // Cache the results wp_cache_set('active_users', $users, '', 300); } //$users = get_users( array( 'role' => 'student' ) ); $users_for_counts = array(); foreach ($users as $user) { $users_for_counts[] = $user->ID; } // Check if obj exists in cache $counts = wp_cache_get('user_count'); if ($counts == false) { // Generate the obj $counts = count_many_users_posts($users_for_counts); // Cache the results wp_cache_set('user_count', $counts, '', 300); } arsort($counts); $counts = array_slice($counts, 0, 5, true); echo 'There are currently <strong>' . intval(count($users)) . '</strong> students with HS Insider accounts.'; echo '<p><strong>Most-active students:</strong></p><ul>'; foreach ($counts as $user_id => $count) { echo '<li><a href="' . esc_url(get_author_posts_url($user_id)) . '" target=_blank>' . esc_html(get_the_author_meta('display_name', $user_id)) . '</a>: (<strong>' . intval($count) . '</strong>)</li>'; } echo '</ul>'; }
/** * 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')); }