public static function tearDownAfterClass()
 {
     if (!self::$timing) {
         echo "\n";
         return;
     }
     $class = get_called_class();
     echo "Timing results : {$class}\n";
     $s = sprintf("%40s %6s %9s %9s %4s\n", 'name', 'count', 'total', 'avg', '% best');
     echo str_repeat('=', strlen($s)) . "\n";
     echo $s;
     echo str_repeat('-', strlen($s)) . "\n";
     array_walk(self::$timing, function (&$value, $key) {
         $value['avg'] = round($value['total'] / $value['count'] * 1000000, 3);
     });
     usort(self::$timing, function ($a, $b) {
         $at = $a['avg'];
         $bt = $b['avg'];
         return $at === $bt ? 0 : ($at < $bt ? -1 : 1);
     });
     $best = self::$timing[0]['avg'];
     foreach (self::$timing as $timing) {
         printf("%40s %6d %7.3fms %7.3fus %4.1f%%\n", $timing['name'], $timing['count'], round($timing['total'] * 1000, 3), $timing['avg'], round($timing['avg'] / $best * 100, 3));
     }
     echo str_repeat('-', strlen($s)) . "\n\n";
     printf("\nTiming compensated for avg overhead for: timeIt of %.3fus and startTimer/endTimer of %.3fus per invocation\n\n", self::$timeItOverhead * 1000000, self::$startEndOverhead * 1000000);
     parent::tearDownAfterClass();
 }
Example #2
1
 public function getAllProjects()
 {
     $key = "{$this->cachePrefix}-all-projects";
     if ($this->cache && ($projects = $this->cache->fetch($key))) {
         return $projects;
     }
     $first = json_decode($this->client->get('projects.json', ['query' => ['limit' => 100]])->getBody(), true);
     $projects = $first['projects'];
     if ($first['total_count'] > 100) {
         $requests = [];
         for ($i = 100; $i < $first['total_count']; $i += 100) {
             $requests[] = $this->client->getAsync('projects.json', ['query' => ['limit' => 100, 'offset' => $i]]);
         }
         /** @var Response[] $responses */
         $responses = Promise\unwrap($requests);
         $responseProjects = array_map(function (Response $response) {
             return json_decode($response->getBody(), true)['projects'];
         }, $responses);
         $responseProjects[] = $projects;
         $projects = call_user_func_array('array_merge', $responseProjects);
     }
     usort($projects, function ($projectA, $projectB) {
         return strcasecmp($projectA['name'], $projectB['name']);
     });
     $this->cache && $this->cache->save($key, $projects);
     return $projects;
 }
Example #3
0
 /**
  *
  * @return boolean
  */
 public function cleanOldExecutions()
 {
     $em = $this->getEntityManager();
     $processes = $em->getRepository('Minibus\\Model\\Entity\\Process')->findAll();
     foreach ($processes as $process) {
         $executions = $process->getExecutions();
         if ($executions instanceof \Doctrine\ORM\PersistentCollection) {
             $count = $executions->count();
             $numberToDelete = $count - $this->getNumberToKeep();
             $first = true;
             $executions = $executions->toArray();
             usort($executions, function (Execution $e1, Execution $e2) {
                 return $e2->getId() > $e1->getId();
             });
             foreach ($executions as $execution) {
                 $count--;
                 // Si une exécution est encours, si ce n'est pas la première exécution d'un process
                 // en cours on l'arrête.
                 if ((false === $process->getRunning() || false === $first) && $execution->getState() == Execution::RUNNING_STATE) {
                     $execution->setState(Execution::STOPPED_STATE);
                 }
                 if ($count <= $numberToDelete) {
                     $em->remove($execution);
                     $execution->getProcess()->removeExecution($execution);
                 }
                 $first = false;
             }
         }
     }
     $em->flush();
 }
Example #4
0
 /**
  * @param ResourceLocatorInterface $locator
  */
 public function registerLocator(ResourceLocatorInterface $locator)
 {
     $this->locators[] = $locator;
     @usort($this->locators, function ($locator1, $locator2) {
         return $locator2->getPriority() - $locator1->getPriority();
     });
 }
Example #5
0
 function show($view, $loc = null, $title = "")
 {
     global $db;
     $config = $db->selectObject('linklistmodule_config', "location_data='" . serialize($loc) . "'");
     if ($config == null) {
         $config->orderby = 'name';
         $config->orderhow = 0;
         // Ascending
     }
     if (!defined('SYS_SORTING')) {
         require_once BASE . 'subsystems/sorting.php';
     }
     $links = $db->selectObjects('linklist_link', "location_data='" . serialize($loc) . "'");
     switch ($config->orderhow) {
         case 0:
             usort($links, 'pathos_sorting_byNameAscending');
             break;
         case 1:
             usort($links, 'pathos_sorting_byNameDescending');
             break;
         case 2:
             shuffle($links);
             break;
     }
     $template = new template('linklistmodule', $view, $loc);
     $template->assign('links', $links);
     $template->register_permissions(array('administrate', 'configure', 'create', 'edit', 'delete'), $loc);
     $template->output();
 }
 private function getLatestSymfonyVersion()
 {
     // Get GitHub JSON request
     $opts = array('http' => array('method' => "GET", 'header' => "User-Agent: LiipMonitorBundle\r\n"));
     $context = stream_context_create($opts);
     $githubUrl = 'https://api.github.com/repos/symfony/symfony/tags';
     $githubJSONResponse = file_get_contents($githubUrl, false, $context);
     // Convert it to a PHP object
     $githubResponseArray = json_decode($githubJSONResponse, true);
     if (empty($githubResponseArray)) {
         throw new \Exception("No valid response or no tags received from GitHub.");
     }
     $tags = array();
     foreach ($githubResponseArray as $tag) {
         $tags[] = $tag['name'];
     }
     // Sort tags
     usort($tags, "version_compare");
     // Filter out non final tags
     $filteredTagList = array_filter($tags, function ($tag) {
         return !stripos($tag, "PR") && !stripos($tag, "RC") && !stripos($tag, "BETA");
     });
     // The first one is the last stable release for Symfony 2
     $reverseFilteredTagList = array_reverse($filteredTagList);
     return str_replace("v", "", $reverseFilteredTagList[0]);
 }
Example #7
0
function search_doc_files($s)
{
    $a = get_app();
    $itemspage = get_pconfig(local_channel(), 'system', 'itemspage');
    App::set_pager_itemspage(intval($itemspage) ? $itemspage : 20);
    $pager_sql = sprintf(" LIMIT %d OFFSET %d ", intval(App::$pager['itemspage']), intval(App::$pager['start']));
    $regexop = db_getfunc('REGEXP');
    $r = q("select item_id.sid, item.* from item left join item_id on item.id = item_id.iid where service = 'docfile' and\n\t\tbody {$regexop} '%s' and item_type = %d {$pager_sql}", dbesc($s), intval(ITEM_TYPE_DOC));
    $r = fetch_post_tags($r, true);
    for ($x = 0; $x < count($r); $x++) {
        $r[$x]['text'] = $r[$x]['body'];
        $r[$x]['rank'] = 0;
        if ($r[$x]['term']) {
            foreach ($r[$x]['term'] as $t) {
                if (stristr($t['term'], $s)) {
                    $r[$x]['rank']++;
                }
            }
        }
        if (stristr($r[$x]['sid'], $s)) {
            $r[$x]['rank']++;
        }
        $r[$x]['rank'] += substr_count(strtolower($r[$x]['text']), strtolower($s));
        // bias the results to the observer's native language
        if ($r[$x]['lang'] === App::$language) {
            $r[$x]['rank'] = $r[$x]['rank'] + 10;
        }
    }
    usort($r, 'doc_rank_sort');
    return $r;
}
 /**
  * Load the fixture jobs in database
  *
  * @return null
  */
 public function load()
 {
     $rawJobs = array();
     $fileLocator = $this->container->get('file_locator');
     foreach ($this->jobsFilePaths as $jobsFilePath) {
         $realPath = $fileLocator->locate('@' . $jobsFilePath);
         $this->reader->setFilePath($realPath);
         // read the jobs list
         while ($rawJob = $this->reader->read()) {
             $rawJobs[] = $rawJob;
         }
         // sort the jobs by order
         usort($rawJobs, function ($item1, $item2) {
             if ($item1['order'] === $item2['order']) {
                 return 0;
             }
             return $item1['order'] < $item2['order'] ? -1 : 1;
         });
     }
     // store the jobs
     foreach ($rawJobs as $rawJob) {
         unset($rawJob['order']);
         $job = $this->processor->process($rawJob);
         $config = $job->getRawConfiguration();
         $config['filePath'] = sprintf('%s/%s', $this->installerDataPath, $config['filePath']);
         $job->setRawConfiguration($config);
         $this->em->persist($job);
     }
     $this->em->flush();
 }
Example #9
0
	public function run() {
		$typeName = $this->defaultType;
		$categoryId = intval($this->getInput('categoryid','get'));
		$alias = $this->getInput('alias','get');
		$tagServicer = $this->_getTagService();
		$hotTags = $tagServicer->getHotTags($categoryId,20);
		$tagIds = array();
		foreach ($hotTags as $k => $v) {
			$attentions = $this->_getTagAttentionDs()->getAttentionUids($k,0,5);
			$hotTags[$k]['weight'] = 0.7 * $v['content_count'] + 0.3 * $v['attention_count'];
			$hotTags[$k]['attentions'] = array_keys($attentions);
			$tagIds[] = $k;
		}
		usort($hotTags, array($this, 'cmp'));
		
		$myTags = $this->_getTagAttentionDs()->getAttentionByUidAndTagsIds($this->loginUser->uid,$tagIds);

		$this->setOutput($myTags, 'myTags');
		$this->setOutput($hotTags, 'hotTags');
		$this->setOutput($categoryId, 'categoryId');
		
		//seo设置
		Wind::import('SRV:seo.bo.PwSeoBo');
		$seoBo = PwSeoBo::getInstance();
		$seoBo->init('topic', 'hot');
		Wekit::setV('seo', $seoBo);
	}
Example #10
0
function scan($dir)
{
    $files = array();
    // Is there actually such a folder/file?
    if (file_exists($dir)) {
        $scanned = scandir($dir);
        //get a directory listing
        $scanned = array_diff(scandir($dir), array('.', '..', '.DS_Store', 'Thumbs.db'));
        //sort folders first, then by type, then alphabetically
        usort($scanned, create_function('$a,$b', '
			return	is_dir ($a)
				? (is_dir ($b) ? strnatcasecmp ($a, $b) : -1)
				: (is_dir ($b) ? 1 : (
					strcasecmp (pathinfo ($a, PATHINFO_EXTENSION), pathinfo ($b, PATHINFO_EXTENSION)) == 0
					? strnatcasecmp ($a, $b)
					: strcasecmp (pathinfo ($a, PATHINFO_EXTENSION), pathinfo ($b, PATHINFO_EXTENSION))
				))
			;
		'));
        foreach ($scanned as $f) {
            if (!$f || $f[0] == '.') {
                continue;
                // Ignore hidden files
            }
            if (is_dir($dir . '/' . $f)) {
                // The path is a folder
                $files[] = array("name" => $f, "type" => "folder", "path" => $dir . '/' . $f, "items" => scan($dir . '/' . $f));
            } else {
                // It is a file
                $files[] = array("name" => $f, "type" => "file", "ext" => pathinfo($f, PATHINFO_EXTENSION), "path" => $dir . '/' . $f, "size" => filesize($dir . '/' . $f));
            }
        }
    }
    return $files;
}
 /**
  * @param Maintainer\MaintainerInterface $maintainer
  */
 public function registerMaintainer(Maintainer\MaintainerInterface $maintainer)
 {
     $this->maintainers[] = $maintainer;
     @usort($this->maintainers, function ($maintainer1, $maintainer2) {
         return $maintainer2->getPriority() - $maintainer1->getPriority();
     });
 }
Example #12
0
 public function siteSidebar()
 {
     global $Language;
     global $dbTags;
     global $Url;
     $db = $dbTags->db['postsIndex'];
     $filter = $Url->filters('tag');
     $html = '<div class="plugin plugin-tags">';
     $html .= '<h2>' . $this->getDbField('label') . '</h2>';
     $html .= '<div class="plugin-content">';
     $html .= '<ul>';
     $tagArray = array();
     foreach ($db as $tagKey => $fields) {
         $tagArray[] = array('tagKey' => $tagKey, 'count' => $dbTags->countPostsByTag($tagKey), 'name' => $fields['name']);
     }
     // Sort the array based on options
     if ($this->getDbField('sort') == "count") {
         usort($tagArray, function ($a, $b) {
             return $b['count'] - $a['count'];
         });
     } elseif ($this->getDbField('sort') == "alpha") {
         usort($tagArray, function ($a, $b) {
             return strcmp($a['tagKey'], $b['tagKey']);
         });
     }
     foreach ($tagArray as $tagKey => $fields) {
         // Print the parent
         $html .= '<li><a href="' . HTML_PATH_ROOT . $filter . '/' . $fields['tagKey'] . '">' . $fields['name'] . ' (' . $fields['count'] . ')</a></li>';
     }
     $html .= '</ul>';
     $html .= '</div>';
     $html .= '</div>';
     return $html;
 }
Example #13
0
 function Form()
 {
     $rgb = new RGB();
     $this->iColors = array_keys($rgb->rgb_table);
     usort($this->iColors, '_cmp');
     $this->iGradstyles = array("Vertical", 2, "Horizontal", 1, "Vertical from middle", 3, "Horizontal from middle", 4, "Horizontal wider middle", 6, "Vertical wider middle", 7, "Rectangle", 5);
 }
 public function init()
 {
     // collect tables
     foreach ($this->node->xpath("value") as $key => $node) {
         $table = $this->getDocument()->getFormatter()->createTable($this, $node);
         // skip translation tables
         if ($table->isTranslationTable()) {
             continue;
         }
         $this->tables[] = $table;
     }
     usort($this->tables, function ($a, $b) {
         return strcmp($a->getModelName(), $b->getModelName());
     });
     /*
      * before you can check for foreign keys
      * you have to store at first all tables in the
      * object registry
      */
     foreach ($this->tables as $table) {
         $table->initIndices();
         $table->initForeignKeys();
     }
     // initialize many to many relation
     if ($this->getDocument()->getConfig()->get(FormatterInterface::CFG_ENHANCE_M2M_DETECTION)) {
         foreach ($this->tables as $table) {
             $table->initManyToManyRelations();
         }
     }
 }
Example #15
0
 public static function show_news($folder = 'posts', $template = 'templates')
 {
     $m = new Mustache_Engine();
     $files = glob("{$folder}/*.md");
     /** /
         usort($files, function($a, $b) {
             return filemtime($a) < filemtime($b);
         });
         /**/
     $html = '';
     foreach ($files as $file) {
         $route = substr($file, strlen($folder) + 1, -3);
         $page = new FrontMatter($file);
         $title = $page->fetch('title') != '' ? $page->fetch('title') : $route;
         $date = $page->fetch('date');
         $author = $page->fetch('author');
         $description = $page->fetch('description') == '' ? '' : $page->fetch('description');
         $data[] = array('title' => $title, 'route' => $route, 'author' => $author, 'description' => $description, 'date' => $date);
     }
     /**/
     function date_compare($a, $b)
     {
         $t1 = strtotime($a['date']);
         $t2 = strtotime($b['date']);
         return $t1 - $t2;
     }
     usort($data, 'date_compare');
     $data = array_reverse($data);
     /**/
     $template = file_get_contents('templates/show_news.tpl');
     $data['files'] = $data;
     return $m->render($template, $data);
     return $html;
 }
Example #16
0
 /**
  * Registers new class patch.
  *
  * @param ClassPatchInterface $patch
  */
 public function registerClassPatch(ClassPatchInterface $patch)
 {
     $this->patches[] = $patch;
     @usort($this->patches, function (ClassPatchInterface $patch1, ClassPatchInterface $patch2) {
         return $patch2->getPriority() - $patch1->getPriority();
     });
 }
Example #17
0
 protected function generateContent($templatePath, $contentType)
 {
     // We build these into a single string so that we can deploy this resume as a
     // single file.
     $assetPath = join(DIRECTORY_SEPARATOR, array($templatePath, $contentType));
     if (!file_exists($assetPath)) {
         return '';
     }
     $assets = array();
     // Our PHAR deployment can't handle the GlobAsset typically used here
     foreach (new \DirectoryIterator($assetPath) as $fileInfo) {
         if ($fileInfo->isDot() || !$fileInfo->isFile()) {
             continue;
         }
         array_push($assets, new FileAsset($fileInfo->getPathname()));
     }
     usort($assets, function (FileAsset $a, FileAsset $b) {
         return strcmp($a->getSourcePath(), $b->getSourcePath());
     });
     $collection = new AssetCollection($assets);
     switch ($contentType) {
         case 'css':
             $collection->ensureFilter(new Filter\LessphpFilter());
             break;
     }
     return $collection->dump();
 }
Example #18
0
 /**
  * @return array of \app\model\Venue ascending by price
  */
 public function getVenuesSortedByPrice()
 {
     usort($this->venues, function ($venueA, $venueB) {
         return $venueA->getPrice() > $venueB->getPrice();
     });
     return $this->venues;
 }
Example #19
0
 public function display_page(Page $page, SetupPanel $panel)
 {
     $setupblock_html1 = "";
     $setupblock_html2 = "";
     usort($panel->blocks, "blockcmp");
     /*
      * Try and keep the two columns even; count the line breaks in
      * each an calculate where a block would work best
      */
     $len1 = 0;
     $len2 = 0;
     foreach ($panel->blocks as $block) {
         if ($block instanceof SetupBlock) {
             $html = $this->sb_to_html($block);
             $len = count(explode("<br>", $html)) + 1;
             if ($len1 <= $len2) {
                 $setupblock_html1 .= $this->sb_to_html($block);
                 $len1 += $len;
             } else {
                 $setupblock_html2 .= $this->sb_to_html($block);
                 $len2 += $len;
             }
         }
     }
     $table = "\n\t\t\t<form action='" . make_link("setup/save") . "' method='POST'><table>\n\t\t\t<tr><td>{$setupblock_html1}</td><td>{$setupblock_html2}</td></tr>\n\t\t\t<tr><td colspan='2'><input type='submit' value='Save Settings'></td></tr>\n\t\t\t</table></form>\n\t\t\t";
     $page->set_title("Shimmie Setup");
     $page->set_heading("Shimmie Setup");
     $page->add_block(new Block("Navigation", $this->build_navigation(), "left", 0));
     $page->add_block(new Block("Setup", $table));
 }
Example #20
0
/**
 *
 * Returns array of people containing entity, mutuals (friends), groups (shared) and priority
 * @param Int $guid
 * @param Int $friends_limit
 * @param Int $groups_limit
 * @return Array
 */
function get_suggestions($guid, $friends_of_friends_limit = 10, $groups_members_limit = 10)
{
    $dbprefix = elgg_get_config('dbprefix');
    $guid = sanitize_int($guid);
    $suggestions = array();
    if ($friends_of_friends_limit) {
        // get some friends of friends
        $options = array('selects' => array('COUNT(fof.guid_two) as priority'), 'type' => 'user', 'joins' => array("JOIN {$dbprefix}users_entity ue ON ue.guid = e.guid", "JOIN {$dbprefix}entity_relationships fr ON fr.guid_one = {$guid} AND fr.relationship = 'friend'", "JOIN {$dbprefix}entity_relationships fof ON fof.guid_one = fr.guid_two AND fof.relationship = 'friend'"), "wheres" => array("ue.banned = 'no'", "e.guid NOT IN (SELECT f.guid_two FROM {$dbprefix}entity_relationships f WHERE f.guid_one = {$guid} AND f.relationship = 'friend')", "fof.guid_two = e.guid", "e.guid != {$guid}"), 'group_by' => 'e.guid', 'order_by' => 'priority desc, ue.last_action desc', 'limit' => abs((int) $friends_of_friends_limit));
        $fof = elgg_get_entities($options);
        foreach ($fof as $f) {
            $priority = (int) $f->getVolatileData('select:priority');
            $suggestions[$f->guid] = array('entity' => $f, 'mutuals' => $priority, 'groups' => 0, 'priority' => $priority);
        }
    }
    if ($groups_members_limit) {
        // get some mutual group members
        $options = array('selects' => array('COUNT(mog.guid_two) as priority'), 'type' => 'user', 'joins' => array("JOIN {$dbprefix}users_entity ue ON ue.guid = e.guid", "JOIN {$dbprefix}entity_relationships g ON g.guid_one = {$guid} AND g.relationship = 'member'", "JOIN {$dbprefix}groups_entity ge ON ge.guid = g.guid_two", "JOIN {$dbprefix}entity_relationships mog ON mog.guid_two = g.guid_two AND mog.relationship = 'member'"), "wheres" => array("ue.banned = 'no'", "e.guid NOT IN (SELECT f.guid_two FROM {$dbprefix}entity_relationships f WHERE f.guid_one = {$guid} AND f.relationship = 'friend')", "mog.guid_one = e.guid", "e.guid != {$guid}"), 'group_by' => 'e.guid', 'order_by' => 'priority desc, ue.last_action desc', 'limit' => 3);
        // get members of groups
        $mog = elgg_get_entities($options);
        foreach ($mog as $m) {
            if (!isset($suggestions[$m->guid])) {
                $priority = (int) $m->getVolatileData('select:priority');
                $suggestions[$m->guid] = array('entity' => $m, 'mutuals' => 0, 'groups' => $priority, 'priority' => $priority);
            } else {
                $priority = (int) $m->getVolatileData('select:priority');
                $suggestions[$m->guid]['groups'] = $priority;
                $suggestions[$m->guid]['priority'] += $priority;
            }
        }
    }
    // sort by priority
    usort($suggestions, __NAMESPACE__ . '\\suggested_friends_sorter');
    return $suggestions;
}
Example #21
0
 /**
  * Generates, encodes, re-orders variables for the query string.
  *
  * @param array $params The specific parameters for this payment
  * @param array $pairs Pairs
  * @param string $namespace The namespace
  *
  * @return string An encoded string of parameters
  */
 public static function generate_query_string($params, &$pairs = array(), $namespace = null)
 {
     if (is_array($params)) {
         foreach ($params as $k => $v) {
             if (is_int($k)) {
                 GoCardless_Utils::generate_query_string($v, $pairs, $namespace . '[]');
             } else {
                 GoCardless_Utils::generate_query_string($v, $pairs, $namespace !== null ? $namespace . "[{$k}]" : $k);
             }
         }
         if ($namespace !== null) {
             return $pairs;
         }
         if (empty($pairs)) {
             return '';
         }
         usort($pairs, array(__CLASS__, 'sortPairs'));
         $strs = array();
         foreach ($pairs as $pair) {
             $strs[] = $pair[0] . '=' . $pair[1];
         }
         return implode('&', $strs);
     } else {
         $pairs[] = array(rawurlencode($namespace), rawurlencode($params));
     }
 }
 public static function getFacebookLikesGroupedBySubmitter(array $gifs, Router $router)
 {
     $json = FacebookHelper::getLikes($gifs, $router);
     $submitters = [];
     foreach ($json as $item) {
         $url = $item['url'];
         $likesCount = intval($item['total_count']);
         /** @var Gif $gif */
         $gif = FacebookHelper::findGif($gifs, $url);
         if (!array_key_exists($gif->getSubmittedBy(), $submitters)) {
             $submitters[$gif->getSubmittedBy()] = ['gifs' => [], 'likes' => 0];
         }
         $submitters[$gif->getSubmittedBy()]['gifs'][] = $gif;
         $submitters[$gif->getSubmittedBy()]['likes'] += $likesCount;
     }
     // Sort array
     $submittersIndexed = [];
     foreach ($submitters as $submitter => $infos) {
         $submittersIndexed[] = ['submitter' => $submitter, 'gifs' => $infos['gifs'], 'likes' => $infos['likes']];
     }
     usort($submittersIndexed, function ($a, $b) {
         return $b['likes'] - $a['likes'];
     });
     return $submittersIndexed;
 }
 /**
  * Generates the HTML for the represented <source> or <img> element.
  *
  * @param SrcsetGeneratorInterface $srcset_gen
  *   The generator instance that will be used to generate the srcset
  *   attributes.
  * @param mixed                    $image
  *   The image representation that will be passed to $srcset_gen
  * @param string                   $alt
  *   The for an <img> `alt` attribute. Only used if $this->as_img is true.
  *
  * @return string
  *   The HTML for either a <source> or <img> element depending on the value
  *
  * @see SrcsetGeneratorInterface
  */
 public function renderWith(SrcsetGeneratorInterface $srcset_gen, $image, $alt = '')
 {
     $last = F\last($this->sizes);
     $srcset = F\map($this->sizes, function (Size $size) use($image, $srcset_gen) {
         return $srcset_gen->listFor($image, $size);
     });
     $srcset = F\unique(F\flatten($srcset), function (Src $src) {
         return $src->getUrl();
     });
     # Not really needed, but makes debugging nicer.
     usort($srcset, function (Src $l, Src $r) {
         $l = $l->getWidth() ?: (int) $l->getMultiplier();
         $r = $r->getWidth() ?: (int) $r->getMultiplier();
         return $l - $r;
     });
     $srcset = implode(', ', $srcset);
     $sizes = F\map($this->sizes, function (Size $size) use($last) {
         return $size === $last ? $size->renderWidthOnly() : (string) $size;
     });
     $sizes = implode(', ', $sizes);
     $media = !$this->as_img ? ' media="' . $last->getMediaQuery() . '"' : '';
     $alt = $this->as_img ? ' alt="' . htmlspecialchars($alt) . '"' : '';
     $attributes = "srcset=\"{$srcset}\" sizes=\"{$sizes}\"{$media}{$alt}";
     return $this->as_img ? "<img {$attributes}>" : "<source {$attributes}>";
 }
Example #24
0
 private function obtener_tuits()
 {
     $search = "from%3Atelemedellin%20#NoticiasTM";
     $notweets = 6;
     $consumerkey = "lvX5ZuwYkNNFwaYaLz0Rw";
     $consumersecret = "tkEfo98Xcpg0rYphooAetOSVjBcYEXhM4pKTGh1Bw";
     $accesstoken = "44186827-6qP8bJ2cRD5Hwkol6hJn782lzSEprym5tyVI4mAc5";
     $accesstokensecret = "xI07T7D9S6E6jnEQ2muSYD1kSBIATRkGgKM3C6w";
     $connection = Yii::app()->twitter->getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
     $search = str_replace("#", "%23", $search);
     $tweets = $connection->get("https://api.twitter.com/1.1/search/tweets.json?q=" . $search . "&count=" . $notweets);
     $nuevos_tweets = array();
     if (!empty($tweets) && !empty($tweets->statuses)) {
         foreach ($tweets->statuses as $tweet) {
             if (substr($tweet->text, 0, 2) == 'RT') {
                 continue;
             }
             $texto_original = $tweet->text;
             $texto_nuevo = '';
             $ultimo_indice = 0;
             $entidades = array();
             //print_r($tweet->entities);exit();
             if (count($tweet->entities->hashtags)) {
                 foreach ($tweet->entities->hashtags as $hashtag) {
                     $nh = '<a href="https://twitter.com/search?q=%23NoticiasTM" target="_blank" rel="nofollow" title="Ver los tuits del Hashtag #NoticiasTM en Twitter"><s>#</s><b class="hashtag">' . $hashtag->text . '</b></a>';
                     $entidades[] = array('texto' => $nh, 'pi' => $hashtag->indices[0], 'pf' => $hashtag->indices[1]);
                 }
             }
             if (count($tweet->entities->user_mentions)) {
                 foreach ($tweet->entities->user_mentions as $user_mention) {
                     $num = '<a href="https://twitter.com/' . $user_mention->screen_name . '" target="_blank" rel="nofollow" title="Ver el perfil del usuario ' . $user_mention->screen_name . ' en Twitter"><s>@</s><b class="user_mention">' . $user_mention->screen_name . '</b></a>';
                     $entidades[] = array('texto' => $num, 'pi' => $user_mention->indices[0], 'pf' => $user_mention->indices[1]);
                 }
             }
             if (count($tweet->entities->urls)) {
                 foreach ($tweet->entities->urls as $url) {
                     $nu = '<a href="' . $url->expanded_url . '" target="_blank" rel="nofollow" class="tlink">' . $url->url . '</a>';
                     $entidades[] = array('texto' => $nu, 'pi' => $url->indices[0], 'pf' => $url->indices[1]);
                 }
             }
             if (count($tweet->entities->media)) {
                 foreach ($tweet->entities->media as $media) {
                     $nm = '<a href="' . $media->expanded_url . '" target="_blank" rel="nofollow" class="tlink">' . $media->url . '</a>';
                     $entidades[] = array('texto' => $nm, 'pi' => $media->indices[0], 'pf' => $media->indices[1]);
                 }
             }
             usort($entidades, "NewsTicker::ceo");
             for ($i = 0; $i < count($entidades); $i++) {
                 $pedazo = mb_substr($texto_original, $ultimo_indice, $entidades[$i]['pi'] - $ultimo_indice, 'UTF-8');
                 $texto_nuevo .= $pedazo;
                 $texto_nuevo .= $entidades[$i]['texto'];
                 $ultimo_indice = $entidades[$i]['pf'];
             }
             $texto_nuevo .= mb_substr($texto_original, $ultimo_indice, 200, 'UTF-8');
             $nuevos_tweets[] = $texto_nuevo;
         }
         Yii::app()->cache->set('tweets', $nuevos_tweets, 300);
     }
     return $nuevos_tweets;
 }
Example #25
0
 /**
  * Compose and get order full history.
  * Consists of the status history comments as well as of invoices, shipments and creditmemos creations
  *
  * @return array
  */
 public function getFullHistory()
 {
     $order = $this->getOrder();
     $history = array();
     foreach ($order->getAllStatusHistory() as $orderComment) {
         $history[] = $this->_prepareHistoryItem($orderComment->getStatusLabel(), $orderComment->getIsCustomerNotified(), $orderComment->getCreatedAtDate(), $orderComment->getComment());
     }
     foreach ($order->getCreditmemosCollection() as $_memo) {
         $history[] = $this->_prepareHistoryItem($this->__('Credit memo #%s created', $_memo->getIncrementId()), $_memo->getEmailSent(), $_memo->getCreatedAtDate());
         foreach ($_memo->getCommentsCollection() as $_comment) {
             $history[] = $this->_prepareHistoryItem($this->__('Credit memo #%s comment added', $_memo->getIncrementId()), $_comment->getIsCustomerNotified(), $_comment->getCreatedAtDate(), $_comment->getComment());
         }
     }
     foreach ($order->getShipmentsCollection() as $_shipment) {
         $history[] = $this->_prepareHistoryItem($this->__('Shipment #%s created', $_shipment->getIncrementId()), $_shipment->getEmailSent(), $_shipment->getCreatedAtDate());
         foreach ($_shipment->getCommentsCollection() as $_comment) {
             $history[] = $this->_prepareHistoryItem($this->__('Shipment #%s comment added', $_shipment->getIncrementId()), $_comment->getIsCustomerNotified(), $_comment->getCreatedAtDate(), $_comment->getComment());
         }
     }
     foreach ($order->getInvoiceCollection() as $_invoice) {
         $history[] = $this->_prepareHistoryItem($this->__('Invoice #%s created', $_invoice->getIncrementId()), $_invoice->getEmailSent(), $_invoice->getCreatedAtDate());
         foreach ($_invoice->getCommentsCollection() as $_comment) {
             $history[] = $this->_prepareHistoryItem($this->__('Invoice #%s comment added', $_invoice->getIncrementId()), $_comment->getIsCustomerNotified(), $_comment->getCreatedAtDate(), $_comment->getComment());
         }
     }
     foreach ($order->getTracksCollection() as $_track) {
         $history[] = $this->_prepareHistoryItem($this->__('Tracking number %s for %s assigned', $_track->getNumber(), $_track->getTitle()), false, $_track->getCreatedAtDate());
     }
     usort($history, array(__CLASS__, "_sortHistoryByTimestamp"));
     return $history;
 }
Example #26
0
 public function getEntities()
 {
     $args['method'] = "glpi.listMyEntities";
     $result = $this->connector->call($args);
     usort($result, array($this, "sortEntities"));
     return $result;
 }
Example #27
0
 function __SLEGetTransport($arFields, $arCurrentUserSubscribe)
 {
     if (array_key_exists($arFields["ENTITY_TYPE"] . "_" . $arFields["ENTITY_ID"] . "_" . $arFields["EVENT_ID"] . "_N_N", $arCurrentUserSubscribe["TRANSPORT"])) {
         $arTransport[] = $arCurrentUserSubscribe["TRANSPORT"][$arFields["ENTITY_TYPE"] . "_" . $arFields["ENTITY_ID"] . "_" . $arFields["EVENT_ID"] . "_N_N"];
     }
     if (array_key_exists($arFields["ENTITY_TYPE"] . "_" . $arFields["ENTITY_ID"] . "_all_N_N", $arCurrentUserSubscribe["TRANSPORT"])) {
         $arTransport[] = $arCurrentUserSubscribe["TRANSPORT"][$arFields["ENTITY_TYPE"] . "_" . $arFields["ENTITY_ID"] . "_all_N_N"];
     }
     $bHasLogEventCreatedBy = CSocNetLogTools::HasLogEventCreatedBy($arFields["EVENT_ID"]);
     if ($bHasLogEventCreatedBy) {
         if ($arFields["EVENT_ID"]) {
             if (array_key_exists("U_" . $arFields["USER_ID"] . "_all_N_Y", $arCurrentUserSubscribe["TRANSPORT"])) {
                 $arTransport[] = $arCurrentUserSubscribe["TRANSPORT"]["U_" . $arFields["USER_ID"] . "_all_N_Y"];
             } elseif (array_key_exists("U_" . $arFields["USER_ID"] . "_all_Y_Y", $arCurrentUserSubscribe["TRANSPORT"])) {
                 $arTransport[] = $arCurrentUserSubscribe["TRANSPORT"]["U_" . $arFields["USER_ID"] . "_all_Y_Y"];
             }
         }
     }
     if (!array_key_exists($arFields["ENTITY_TYPE"] . "_" . $arFields["ENTITY_ID"] . "_" . $arFields["EVENT_ID"] . "_N_N", $arCurrentUserSubscribe["TRANSPORT"]) && !array_key_exists($arFields["ENTITY_TYPE"] . "_" . $arFields["ENTITY_ID"] . "_all_N_N", $arCurrentUserSubscribe["TRANSPORT"])) {
         if (array_key_exists($arFields["ENTITY_TYPE"] . "_0_" . $arFields["EVENT_ID"] . "_N_N", $arCurrentUserSubscribe["TRANSPORT"])) {
             $arTransport[] = $arCurrentUserSubscribe["TRANSPORT"][$arFields["ENTITY_TYPE"] . "_0_" . $arFields["EVENT_ID"] . "_N_N"];
         } elseif (array_key_exists($arFields["ENTITY_TYPE"] . "_0_all_N_N", $arCurrentUserSubscribe["TRANSPORT"])) {
             $arTransport[] = $arCurrentUserSubscribe["TRANSPORT"][$arFields["ENTITY_TYPE"] . "_0_all_N_N"];
         } else {
             $arTransport[] = "N";
         }
     }
     $arTransport = array_unique($arTransport);
     usort($arTransport, "__SLTransportSort");
     return $arTransport;
 }
 /**
  * @param  File[]
  * @return File[] sorted
  */
 protected function sortFiles(array $files)
 {
     usort($files, function (File $a, File $b) {
         return strcmp($a->name, $b->name);
     });
     return $files;
 }
Example #29
0
 /**
  * Сортирует список методов по указанному алгоритму
  *
  * @param Method[] $methods Список методов
  * @param string   $sort    Алгоритм сортировки
  *
  * @return void
  */
 public function sort(array &$methods, $sort = self::BY_COMPLEXITY)
 {
     if (!in_array($sort, self::SORTS, true)) {
         $sort = self::BY_COMPLEXITY;
     }
     usort($methods, $sort === self::BY_COMPLEXITY ? $this->byComplexity() : $this->byName());
 }
 /**
  * Customizes the sorting algorithm of a custom column.
  */
 public function replyToSortCustomColumn($aTerms, $aTaxonomies, $aArgs)
 {
     if ('edit-tags.php' == $GLOBALS['pagenow'] && isset($_GET['orderby']) && 'custom' == $_GET['orderby']) {
         usort($aTerms, array($this, '_replyToSortByCustomOptionValue'));
     }
     return $aTerms;
 }