public function execute($session) { $t = new \Console_Table(CONSOLE_TABLE_ALIGN_LEFT, ''); $commands = $session->getShellInterpreter()->getBuiltInCommands(); foreach ($commands as $prefix => $className) { $t->addRow([$prefix, $className::getDescription()]); } echo $t->getTable(); return true; }
public function execute($session) { $trace = $session->getCallStack()->getTrace(); $t = new \Console_Table(CONSOLE_TABLE_ALIGN_LEFT, ''); $t->setAlign(2, CONSOLE_TABLE_ALIGN_RIGHT); foreach ($trace as $i => $a) { $t->addRow([$this->getCallable($a), isset($a['file']) ? $a['file'] : '', isset($a['line']) ? $a['line'] : '']); } echo $t->getTable(); return true; }
function skype_history($threshold = 60, $since = "Last Monday") { $calls = SkypeHistory_Call::getCalls(); $since = strtotime($since); $table = new Console_Table(); $table->setHeaders(array('Date', 'Time', 'Duration', '<>', 'Participants')); $types = array('INCOMING_PSTN' => '<-', 'INCOMING_P2P' => '<-', 'OUTGOING_PSTN' => '->', 'OUTGOING_P2P' => '->'); $previous_date = NULL; $total_duration = 0; printf("Gathering skype call history, this may take a few seconds.\n"); foreach ($calls as $i => $id) { $call = new SkypeHistory_Call($id); // Bail out once the cutoff is reached. if ($call->timestamp < $since) { break; } if ($call->duration < $threshold) { continue; } $participants = array(); $participants[] = $call->PARTNER_DISPNAME; if ($call->conf_participants_count > 1) { for ($j = 1; $j < (int) $call->conf_participants_count; $j++) { $p = $call->getProperty("CONF_PARTICIPANT {$j}"); // drewstephens0815 OUTGOING_P2P FINISHED Andrew Stephens list($nick, $type, $status, $display_name) = explode(" ", $p, 4); $participants[] = $display_name; } } $date = date('D M d,Y', (int) $call->timestamp); if ($date == $previous_date) { $date = ''; } else { if (!empty($previous_date)) { $table->addSeparator(); } $previous_date = $date; } $total_duration += (int) $call->duration; $table->addRow(array($date, date('g:ia', (int) $call->timestamp), format_interval($call->duration), $types[$call->type], format_participants($participants))); printf("\r%s", str_repeat('.', $i)); } printf("\r"); print $table->getTable(); printf("Number of calls: %s\n", count($calls)); printf("Total duration: %s\n", format_interval($total_duration)); }
public function trace() { if (!class_exists('Console_Table')) { throw new Exception('PEAR:Console_Table not installed!'); } $trace = debug_backtrace(); array_splice($trace, 0, 1); $table = new Console_Table(); $table->setHeaders(array('File', 'Line', 'Call', '#Args')); foreach ($trace as $item) { $row = array(); $row[] = $item['file']; $row[] = $item['line']; $row[] = $item['class'] . $item['type'] . $item['function']; $row[] = sizeof($item['args']); $table->addRow($row); } echo $table->getTable(); }
function tag($args = []) { if (isset($args[0])) { $arg = array_shift($args); if ($arg == 'init') { $tags = []; foreach ($this->urls as $url => $data) { foreach ($data['tags'] as $tag) { $tags[] = $tag; } } $tags = array_unique($tags); sort($tags); if (0 != filesize(TAG_FILE)) { err(TAG_FILE . " contains tag entries. Manually truncate the file first."); } else { $tag_len = count($tags); $filtered_tags = []; foreach ($tags as $tK => $tV) { $i = $tK + 1; $tbl = new Console_Table(); $tbl->addRow(array("[{$i}/{$tag_len}]", $tV, " subscribe? (y/n)")); echo $tbl->getTable(); //send the cursor back up a line to answer yes or no. echo chr(27) . "[" . 2 . "A" . "\t\t\t\t\t\t\t"; $ans = strtolower(Seld\CliPrompt\CliPrompt::prompt()); if ($ans == 'y' || $ans == 'yes') { $filtered_tags[] = $tV; } } file_put_contents(TAG_FILE, implode(PHP_EOL, $filtered_tags)); suc("wrote default tags into " . TAG_FILE); } } else { if ($arg == 'update') { //not written yet. } } } else { err("<tag init> and <tag update> are available."); } }
--idList=ID,ID,ID - imports only the given source ids --limit=LIMIT - stop after processing LIMIT items --skip=COUNT - skip first COUNT items and than start processing --progress=COUNT - render progress after COUNT items rollback usage: migrator rollback MIGRATION [--progress=COUNT] [--idList=ID,ID,ID] --progress=COUNT - render progress after COUNT items --idList=ID,Id,ID - rolls only the given source ids back. <?php return; } if ('list' == $argv[1]) { require 'table.php'; $table = new Console_Table(); $table->setHeaders(array('Migration', 'Imported', 'Available', 'Delta')); foreach ($migrations as $key => $object) { $table->addRow(array(esc_html($key), intval($object->getNumberOfImportedItems()), intval($object->getNumberOfAvailableItems()), intval($object->getDelta()))); } echo $table->getTable(); } if ('import' == $argv[1] && count($argv) >= 3) { $migration = $argv[2]; $update = false; $idlist = array(); $limit = 0; $skip = 0; $progress = -1; for ($i = 3; $i < count($argv); $i++) { if ($argv[$i] == '--update') {
/** * Display a list of available service on console * * execute from the application folder: * php -r "require 'vendor/autoload.php'; Arrowsphere\Client\xAC::getServicesList();" */ public static function getServicesList() { $map = ['GET' => 'get', 'POST' => 'create', 'PUT' => 'update', 'DELETE' => 'delete']; $table = new \Console_Table(); $table->setHeaders(['Method', 'Type', 'Description', 'Parameters']); foreach (self::getServices() as $key => $service) { if ($service['type'] == 'entity') { foreach ($service['actions'] as $action) { $table->addRow([sprintf('xAC::%s()->%s()', $service['endpoint'], $action['endpoint'] == 'default' ? $map[$action['method']] : $action['endpoint']), 'entity/' . $action['type'], $action['description']]); } } else { $table->addRow(['xAC::' . $service['endpoint'] . '()->get()', $service['type'], $service['description']]); } } echo $table->getTable(); }
<?php require_once 'DB.php'; require_once 'Console/Table.php'; $dbh = DB::connect('mysqli://*****:*****@localhost/pear'); if (PEAR::isError($dbh)) { die('Database connection failed'); } $sql = ' SELECT p.license, COUNT(p.id) as count FROM packages p WHERE p.package_type = "pear" GROUP BY p.license'; $data = $dbh->getAll($sql, DB_FETCHMODE_ASSOC); $table = new Console_Table(); $table->setHeaders(array('License', 'Amount of packages')); $table->addData($data); echo $table->getTable();
/** * Display final results * * Display final results, when data source parsing is over. * * @access public * @return void * @since version 1.8.0b3 (2008-06-07) */ function display() { $o = $this->args['output-level']; $info = $this->parseData; $hdr = array(); $src = $this->_parser->dataSource; if (isset($this->args['dir'])) { $dir = $this->args['dir']; $hdr[] = 'Files'; } elseif (isset($this->args['file'])) { $file = $this->args['file']; $hdr[] = 'File'; } elseif (isset($this->args['string'])) { $string = $this->args['string']; $hdr[] = 'Source code'; } elseif ($src['dataType'] == 'directory') { $dir = $src['dataSource']; $hdr[] = 'Files'; } elseif ($src['dataType'] == 'file') { $file = $src['dataSource']; $hdr[] = 'File'; } else { $string = $src['dataSource']; $hdr[] = 'Source code'; } $table = new Console_Table(); $f = 0; if ($o & 16) { $hdr[] = 'Version'; $f++; } if ($o & 1) { $hdr[] = 'C'; $f++; } if ($o & 2) { $hdr[] = 'Extensions'; $filter2 = array(&$this, '_splitExtname'); $table->addFilter($f + 1, $filter2); $f++; } if ($o & 4) { if ($o & 8) { $hdr[] = 'Constants/Tokens'; } else { $hdr[] = 'Constants'; } $f++; } else { if ($o & 8) { $hdr[] = 'Tokens'; $f++; } } $table->setHeaders($hdr); $filter0 = array(&$this, '_splitFilename'); $table->addFilter(0, $filter0); if ($o > 3 && $o < 16 || $o > 19) { $filter3 = array(&$this, '_splitConstant'); $table->addFilter($f, $filter3); } $ext = implode("\r\n", $info['extensions']); $const = implode("\r\n", array_merge($info['constants'], $info['tokens'])); if (isset($dir)) { $ds = DIRECTORY_SEPARATOR; $dir = str_replace(array('\\', '/'), $ds, $dir); $data = array($dir . $ds . '*'); } elseif (isset($file)) { $data = array($file); } else { $data = array('<?php ... ?>'); } if ($o & 16) { if (empty($info['max_version'])) { $data[] = $info['version']; } else { $data[] = implode("\r\n", array($info['version'], $info['max_version'])); } } if ($o & 1) { $data[] = $info['cond_code'][0]; } if ($o & 2) { $data[] = $ext; } if ($o & 4) { if ($o & 8) { $data[] = $const; } else { $data[] = implode("\r\n", $info['constants']); } } else { if ($o & 8) { $data[] = implode("\r\n", $info['tokens']); } } $table->addRow($data); unset($info['max_version']); unset($info['version']); unset($info['classes']); unset($info['functions']); unset($info['extensions']); unset($info['constants']); unset($info['tokens']); unset($info['cond_code']); $ignored = $info['ignored_files']; $all_functions = array(); unset($info['ignored_files']); unset($info['ignored_functions']); unset($info['ignored_extensions']); unset($info['ignored_constants']); // summarize : print only summary for directory without files details if ($this->args['summarize'] === false && isset($dir)) { foreach ($info as $file => $info) { if (is_numeric($file[0])) { // extra information available only when debug mode is on $all_functions[$file] = $info; continue; } if ($info === false) { continue; // skip this (invalid) file } $ext = implode("\r\n", $info['extensions']); $const = implode("\r\n", array_merge($info['constants'], $info['tokens'])); $file = str_replace(array('\\', '/'), $ds, $file); $table->addSeparator(); $data = array($file); if ($o & 16) { if (empty($info['max_version'])) { $data[] = $info['version']; } else { $data[] = implode("\r\n", array($info['version'], $info['max_version'])); } } if ($o & 1) { $data[] = $info['cond_code'][0]; } if ($o & 2) { $data[] = $ext; } if ($o & 4) { if ($o & 8) { $data[] = $const; } else { $data[] = implode("\r\n", $info['constants']); } } else { if ($o & 8) { $data[] = implode("\r\n", $info['tokens']); } } $table->addRow($data); } } else { foreach ($info as $file => $info) { if (is_numeric($file[0])) { // extra information available only when debug mode is on $all_functions[$file] = $info; } } } $output = $table->getTable(); // verbose level $v = isset($this->args['verbose']) ? $this->args['verbose'] : 0; // command line resume if ($v & 1) { $output .= "\nCommand Line resume :\n\n"; $table = new Console_Table(); $table->setHeaders(array('Option', 'Value')); $filter0 = array(&$this, '_splitOption'); $table->addFilter(0, $filter0); $filter1 = array(&$this, '_splitValue'); $table->addFilter(1, $filter1); if (is_array($this->args)) { foreach ($this->args as $key => $raw) { if ($key == 'summarize') { $raw = $raw === true ? 'TRUE' : 'FALSE'; } if (is_array($raw)) { $raw = implode(', ', $raw); } $contents = array($key, $raw); $table->addRow($contents); } } $output .= $table->getTable(); } // parser options resume if ($v & 2) { $output .= "\nParser options :\n\n"; $table = new Console_Table(); $table->setHeaders(array('Option', 'Value')); $filter0 = array(&$this, '_splitOption'); $table->addFilter(0, $filter0); $filter1 = array(&$this, '_splitValue'); $table->addFilter(1, $filter1); $opts = $this->_parser->options; if (is_array($opts)) { foreach ($opts as $key => $raw) { if ($key == 'debug' || $key == 'recurse_dir' || $key == 'is_string') { $raw = $raw === true ? 'TRUE' : 'FALSE'; } if (substr($key, -6) == '_match') { $val = array_values($raw[1]); array_unshift($val, $raw[0]); $raw = implode("\r\n", $val); } else { if (is_array($raw)) { $raw = implode("\r\n", $raw); } } $contents = array($key, $raw); $table->addRow($contents); } } $output .= $table->getTable(); } // extra information if ($v & 4) { $output .= "\nDebug:\n\n"; $table = new Console_Table(); $table->setHeaders(array('Version', 'Function', 'Extension', 'PECL')); foreach ($all_functions as $version => $functions) { foreach ($functions as $func) { $table->addRow(array($version, $func['function'], $func['extension'], isset($func['pecl']) ? $func['pecl'] === true ? 'yes' : 'no' : '')); } } $output .= $table->getTable(); } echo $output; }
function make() { global $cmd_options, $apps, $dirs, $debug, $test, $c, $silence, $redir_err; $compendium = BASE . DS . 'po' . DS . 'compendium.po'; foreach ($cmd_options[0] as $option) { switch ($option[0]) { case 'h': usage(); footer(); case 'l': case '--locale': $lang = $option[1]; break; case 'm': case '--module': $module = $option[1]; break; case 'c': case '--compendium': $compendium = $option[1]; break; case 'n': case '--no-compendium': $compendium = ''; break; } } $horde = array_search('horde', $dirs); require_once 'Console/Table.php'; $stats = new Console_Table(); $stats->setHeaders(array(_("Module"), _("Language"), _("Translated"), _("Fuzzy"), _("Untranslated"))); for ($i = 0; $i < count($dirs); $i++) { if (!empty($module) && $module != $apps[$i]) { continue; } $c->writeln(sprintf(_("Building MO files for module %s..."), $c->bold($apps[$i]))); if (empty($lang)) { $langs = get_languages($dirs[$i]); } else { if (!@file_exists($dirs[$i] . DS . 'po' . DS . $lang . '.po')) { $c->writeln(_("Skipped...")); $c->writeln(); continue; } $langs = array($lang); } foreach ($langs as $locale) { $c->writeln(sprintf(_("Building locale %s... "), $c->bold($locale))); $dir = $dirs[$i] . DS . 'locale' . DS . $locale . DS . 'LC_MESSAGES'; if (!is_dir($dir)) { require_once 'System.php'; if ($debug) { $c->writeln(sprintf(_("Making directory %s"), $dir)); } if (!$test && !@System::mkdir("-p {$dir}")) { $c->writeln($c->red(_("Warning: ")) . sprintf(_("Could not create locale directory for locale %s:"), $locale)); $c->writeln($dir); $c->writeln(); continue; } } /* Convert to unix linebreaks. */ $pofile = $dirs[$i] . DS . 'po' . DS . $locale . '.po'; $fp = fopen($pofile, 'r'); $content = fread($fp, filesize($pofile)); fclose($fp); $content = str_replace("\r", '', $content); $fp = fopen($pofile, 'wb'); fwrite($fp, $content); fclose($fp); /* Check PO file sanity. */ $sh = $GLOBALS['msgfmt'] . " --check \"{$pofile}\"{$redir_err}"; if ($debug || $test) { $c->writeln(_("Executing:")); $c->writeln($sh); } if ($test) { $ret = 0; } else { exec($sh, $out, $ret); } if ($ret != 0) { $c->writeln($c->red(_("Warning: ")) . _("an error has occured:")); $c->writeln(implode("\n", $out)); $c->writeln(); continue; } /* Compile MO file. */ $sh = $GLOBALS['msgfmt'] . ' --statistics --check -o "' . $dir . DS . $apps[$i] . '.mo" '; if ($apps[$i] != 'horde') { $horde_po = $dirs[$horde] . DS . 'po' . DS . $locale . '.po'; if (!@is_readable($horde_po)) { $c->writeln($c->red(_("Warning: ")) . sprintf(_("the Horde PO file for the locale %s does not exist:"), $locale)); $c->writeln($horde_po); $c->writeln(); $sh .= $dirs[$i] . DS . 'po' . DS . $locale . '.po'; } else { $sh = $GLOBALS['msgcomm'] . " --more-than=0 --sort-output \"{$pofile}\" \"{$horde_po}\" | {$sh} -"; } } else { $sh .= $pofile; } $sh .= $redir_err; if ($debug || $test) { $c->writeln(_("Executing:")); $c->writeln($sh); } $out = ''; if ($test) { $ret = 0; } else { putenv('LANG=en'); exec($sh, $out, $ret); putenv('LANG=' . $GLOBALS['language']); } if ($ret == 0) { $c->writeln($c->green(_("done"))); $messages = array(0, 0, 0); if (preg_match('/(\\d+) translated/', $out[0], $match)) { $messages[0] = $match[1]; if (isset($horde_msg)) { $messages[0] -= $horde_msg[0]; } } if (preg_match('/(\\d+) fuzzy/', $out[0], $match)) { $messages[1] = $match[1]; if (isset($horde_msg)) { $messages[1] -= $horde_msg[1]; } } if (preg_match('/(\\d+) untranslated/', $out[0], $match)) { $messages[2] = $match[1]; if (isset($horde_msg)) { $messages[2] -= $horde_msg[2]; } } if ($apps[$i] == 'horde') { $horde_msg = $messages; } $stats->addRow(array($apps[$i], $locale, $messages[0], $messages[1], $messages[2])); } else { $c->writeln($c->red(_("failed"))); exec($sh, $out, $ret); $c->writeln(implode("\n", $out)); } if (count($langs) > 1) { continue; } /* Merge translation into compendium. */ if (!empty($compendium)) { echo sprintf(_("Merging the PO file for %s to the compendium... "), $c->bold($apps[$i])); if (!empty($dir) && substr($dir, -1) != DS) { $dir .= DS; } $sh = $GLOBALS['msgcat'] . " --sort-output \"{$compendium}\" \"{$pofile}\" > \"{$compendium}.tmp\""; if (!$debug) { $sh .= $silence; } if ($debug || $test) { $c->writeln(); $c->writeln(_("Executing:")); $c->writeln($sh); } $out = ''; if ($test) { $ret = 0; } else { exec($sh, $out, $ret); } @unlink($compendium); rename($compendium . '.tmp', $compendium); if ($ret == 0) { $c->writeln($c->green(_("done"))); } else { $c->writeln($c->red(_("failed"))); } } $c->writeln(); } } if (empty($module)) { $c->writeln(_("Results:")); } else { $c->writeln(_("Results (including Horde):")); } $c->writeln($stats->getTable()); }
require 'config.php'; require 'includes/definitions.inc.php'; require 'includes/functions.php'; require 'includes/polling/functions.inc.php'; require 'includes/alerts.inc.php'; $options = getopt('l:u:r::'); if (isset($options['l'])) { if ($options['l'] == 'pollers') { $tbl = new Console_Table(); $tbl->setHeaders(array('ID', 'Poller Name', 'Last Polled', '# Devices', 'Poll Time')); foreach (dbFetchRows('SELECT * FROM `pollers`') as $poller) { $tbl->addRow(array($poller['id'], $poller['poller_name'], $poller['last_polled'], $poller['devices'], $poller['time_taken'])); } echo $tbl->getTable(); } elseif ($options['l'] == 'groups') { $tbl = new Console_Table(); $tbl->setHeaders(array('ID', 'Group Name', 'Description')); foreach (dbFetchRows('SELECT * FROM `poller_groups`') as $groups) { $tbl->addRow(array($groups['id'], $groups['group_name'], $groups['descr'])); } echo $tbl->getTable(); } } elseif (isset($options['u']) && !empty($options['u'])) { if (is_numeric($options['u'])) { $db_column = 'id'; } else { $db_column = 'poller_name'; } if (dbDelete('pollers', "`{$db_column}` = ?", array($options['u'])) >= 0) { echo 'Poller ' . $options['u'] . " has been removed\n"; }
$tbl->addRow(array($entry['timestamp'], gethostbyid($entry['device_id']), $entry['program'], $entry['msg'], $entry['level'], $entry['facility'])); } echo $tbl->getTable(); } else { if ($options['list'] == 'devices') { $tbl = new Console_Table(); $tbl->setHeaders(array('Device ID', 'Device Hostname')); $query = 'SELECT device_id,hostname FROM `devices` ORDER BY hostname'; foreach (dbFetchRows($query, $sql_param) as $device) { $tbl->addRow(array($device['device_id'], $device['hostname'])); } echo $tbl->getTable(); exit; } else { if (isset($options['device-stats'])) { $tbl = new Console_Table(); $tbl->setHeaders(array('Port name', 'Status', 'IPv4 Address', 'Speed In', 'Speed Out', 'Packets In', 'Packets Out', 'Speed', 'Duplex', 'Type', 'MAC Address', 'MTU')); foreach (dbFetchRows('SELECT * FROM `ports` WHERE `device_id` = ?', array($options['d'])) as $port) { if ($port['ifOperStatus'] == 'up') { $port['in_rate'] = $port['ifInOctets_rate'] * 8; $port['out_rate'] = $port['ifOutOctets_rate'] * 8; $in_perc = @round($port['in_rate'] / $port['ifSpeed'] * 100); $out_perc = @round($port['in_rate'] / $port['ifSpeed'] * 100); } if ($port['ifSpeed']) { $port_speed = humanspeed($port['ifSpeed']); } if ($port[ifDuplex] != 'unknown') { $port_duplex = $port['ifDuplex']; } if ($port['ifPhysAddress'] && $port['ifPhysAddress'] != '') {
/** * テキストテーブル文字列の取得 * * 文字列でテーブルを描画します。 * * @param array $data * * @return string */ private function _getTextTable($data) { if (!$data) { return ''; } $table = new Console_Table(); $table->setAlign(0, CONSOLE_TABLE_ALIGN_LEFT); $data = $this->isList($data) !== true ? array($data) : $data; $table->setHeaders(array_keys($data[0])); foreach ($data as $row) { $table->addRow($row); } $result = $table->getTable(); return $result; }
usage(); exit(1); } // login $service = VMware_VCloud_SDK_Service::getService(); $service->login($server, array('username' => $user, 'password' => $pswd), $httpConfig); // create an SDK Query object $sdkQuery = VMware_VCloud_SDK_Query::getInstance($service); $qm = "queryRecords"; $type = "adminVM"; $params = new VMware_VCloud_SDK_Query_Params(); $params->setSortAsc('name'); $params->setPageSize(128); $recsObj = $sdkQuery->{$qm}($type, $params); // table to store output $tbl = new Console_Table(); $tbl->setHeaders(array('VirtualMachine', 'vApp', 'vAppTemplate', 'vCenter Server', 'VM MoRef', 'ChainLength')); // array to store URL pages $pageUrls = array(); // retrieve all pages getPages($recsObj->get_href()); foreach ($pageUrls as $url) { // GET operation on URL $record = $service->get($url); // query all adminVM using query service foreach ($record->getRecord() as $vm) { if ($vm->get_status() == "UNRESOLVED") { continue; } // create VM SDK object based on VM href $adminVMSDKObj = $service->createSDKObj($vm->get_href());
/** * Get info about specific bundle * * @return void */ private function execInfo() { $tbl = new ConsoleTable(); $tbl->setHeaders(array('Param', 'Value')); $bundle = $this->service->getBundleInfo($this->getBundleParam()); if (is_array($bundle)) { foreach ($bundle as $param => $value) { $tbl->addRow(array($param, $value)); } } $this->out($tbl->getTable()); }
/** * Return pretty printed table from data, useful for printing to console or wrapped in <pre> * @return string */ public function getValue() { require_once 'Console/Table.php'; $tbl = new \Console_Table(); $tbl->setHeaders($this->getColHeadings()); $tbl->addData($this->getAllRows()); return $tbl->getTable(); }
/** * Retrieve/format statistics. * * @since 15xxxx Initial release. */ protected function statistics() { $args = ['type' => $this->type, 'days' => $this->days, 'weeks' => $this->weeks, 'months' => $this->months, 'years' => $this->years, 'start_time' => $this->start_time, 'source' => $this->source, 'sku' => $this->sku, 'key' => $this->config->websharks->api_key]; $endpoint = 'https://www.websharks-inc.com/sales/api.php'; $endpoint = $this->UrlQuery->addArgs($args, $endpoint); $response = json_decode($this->UrlRemote->request('GET::' . $endpoint)); if (!is_object($response) || !empty($response->error)) { if (!empty($response->error)) { throw new \Exception('Unable to retrieve statistics.' . "\n" . 'The API said: `' . $response->error . '`'); } throw new \Exception('Unable to retrieve statistics.' . "\n" . 'The API call failed w/ an unknown error.'); } $statistics = ''; // Initialize. $table = new \Console_Table(CONSOLE_TABLE_ALIGN_LEFT, CONSOLE_TABLE_BORDER_ASCII, 1, 'UTF-8', true); $table_color = new \Console_Color2(); // Coloration class. $table_colorize_amount = function ($amount) use($table_color) { return $table_color->convert('%G' . $amount . '%n'); }; $table_colorize_from = function ($from) use($table_color) { return $table_color->convert('%b' . $from . '%n'); }; $table_colorize_to = function ($to) use($table_color) { return $table_color->convert('%b' . $to . '%n'); }; $table->setHeaders(['From', 'To', 'Amount']); $table->addFilter(0, $table_colorize_from); $table->addFilter(1, $table_colorize_to); $table->addFilter(2, $table_colorize_amount); $chart = ''; // Initialize. $chart_data = ''; // Initialize. $chart_gnuplot = []; // Initialize. $chart_first_from = $chart_last_to = ''; // Initialize. $chart_data_file = $this->FsDir->tmp() . '/' . md5(__CLASS__ . 'gnuplot') . '.dat'; date_default_timezone_set('UTC'); // UTC timezone. $statistics .= '**' . $response->title . '**'; if ($response->caption) { // Caption also? $statistics .= ' _*' . $response->caption . '*_'; } $statistics .= "\n"; // Additional line break. foreach ($response->results as $_result) { $_from = date('D M d, Y @ H:i a T', strtotime($_result->from)); $_to = date('D M d, Y @ H:i a T', strtotime($_result->to)); $table->addRow([$_from, $_to, '$' . $_result->amount]); } unset($_result); // Housekeeping. $statistics .= $table->getTable(); // Append table. foreach ($response->results as $_result) { if (empty($chart_first_from)) { $chart_first_from = date('D M d, Y @ H:i a T', strtotime($_result->from)); } $chart_last_to = date('D M d, Y @ H:i a T', strtotime($_result->to)); $chart_data .= '"" ' . $_result->amount . "\n"; } $chart_data = trim($chart_data); file_put_contents($chart_data_file, $chart_data); unset($_result); // Housekeeping. $chart_gnuplot[] = 'gnuplot'; $chart_gnuplot[] = '-e'; // Eval the following. $chart_gnuplot[] = 'set terminal dumb size 83, 20;' . ' set yrange [0:*]; set ylabel "Gross Revenue (in USD)";' . ' set xlabel "' . $chart_first_from . ' - ' . $chart_last_to . '";' . ' plot "' . str_replace('"', '', $chart_data_file) . '" using 2:xtic(1) notitle with histograms'; exec(implode(' ', array_map('escapeshellarg', $chart_gnuplot)), $chart, $chart_status); if ($chart_status === 0) { $statistics .= implode("\n", $chart); // Append chart. } return $statistics; }
/** * Show documentation for a shell. * Usage: * wpmvc Help Shell <shell_name> [command_name] * wpmvc Help Shell Generate * wpmvc Help Shell Generate Scaffold * @param mixed $args * @return null */ public function shell($args) { list($name, $method) = $args; if (empty($name)) { $this->out('No shell given'); return; } try { $shell = $this->get_shell_meta($name); } catch (Exception $ex) { $this->out('Error:'); $this->out($ex->getMessage()); return; } $this->nl(); $this->out(Console_Color::convert('%UShells > %n%U%9' . $shell->title . '%n')); $this->nl(); $this->out($shell->doc); $this->nl(2); $this->out('Commands:'); $table = new Console_Table(CONSOLE_TABLE_ALIGN_LEFT, ' ', 1, null, true); if ($method == 'default') { $method = '(default)'; } if (!empty($method) && !empty($shell->methods[$method])) { $table->addRow(array(Console_Color::convert('%9' . $method . '%n'), $shell->methods[$method])); } else { foreach ($shell->methods as $method => $doc) { $table->addRow(array(Console_Color::convert('%9' . $method . '%n'), $doc)); $table->addSeparator(); } } $this->out($table->getTable()); }
public function usage() { echo "Subcommands:\n\n"; $table = new Console_Table(CONSOLE_TABLE_ALIGN_LEFT, ''); foreach ($this->command_defs as $command => $def) { $row = array(basename($this->executable), $command, implode(' ', $def->arguments), ' ' . $def->description); $table->addRow($row); } echo $table->getTable(); }
/** * Converts an array to a table. * * @param array $headers Headers for the table. * @param array $data A two dimensional array with the table * data. * @param boolean $returnObject Whether to return the Console_Table object * instead of the rendered table. * * @static * * @return Console_Table|string A Console_Table object or the generated * table. */ function fromArray($headers, $data, $returnObject = false) { if (!is_array($headers) || !is_array($data)) { return false; } $table = new Console_Table(); $table->setHeaders($headers); foreach ($data as $row) { $table->addRow($row); } return $returnObject ? $table : $table->getTable(); }
/** * Parse File Input * * @return void * @access private * @since 0.8.0 */ function _parseFile() { $info = $this->parseFile($this->file, $this->options); if ($info === false) { $err = 'Failed opening file "' . $this->file . '". Please check your spelling and try again.'; $this->_printUsage($err); return; } $table = new Console_Table(); $table->setHeaders(array('File', 'Version', 'Extensions', 'Constants/Tokens')); $filter = array(&$this, '_splitFilename'); $table->addFilter(0, $filter); $ext = implode("\r\n", $info['extensions']); $const = implode("\r\n", $info['constants']); $table->addRow(array($this->file, $info['version'], $ext, $const)); $output = $table->getTable(); // verbose level $v = $this->args->getValue('v'); // command line resume if ($v & 1) { $output .= "\nCommand Line resume :\n\n"; $table = new Console_Table(); $table->setHeaders(array('Option', 'Value')); $opts = $this->args->getValues(); if (is_array($opts)) { foreach ($opts as $key => $raw) { if (is_array($raw)) { $raw = implode(', ', $raw); } $contents = array($key, $raw); $table->addRow($contents); } } $output .= $table->getTable(); } // parser options resume if ($v & 2) { $output .= "\nParser options :\n\n"; $table = new Console_Table(); $table->setHeaders(array('Option', 'Value')); $opts = $this->options; if (is_array($opts)) { foreach ($opts as $key => $raw) { if ($key == 'debug' || $key == 'recurse_dir') { $raw = $raw === true ? 'TRUE' : 'FALSE'; } if (is_array($raw)) { $raw = implode("\r\n", $raw); } $contents = array($key, $raw); $table->addRow($contents); } } $output .= $table->getTable(); } // extra information if ($v & 4) { $output .= "\nDebug:\n\n"; $table = new Console_Table(); $table->setHeaders(array('Version', 'Function', 'Extension')); unset($info['max_version']); unset($info['version']); unset($info['constants']); unset($info['extensions']); foreach ($info as $version => $functions) { foreach ($functions as $func) { $table->addRow(array($version, $func['function'], $func['extension'])); } } $output .= $table->getTable(); } echo $output; }
/** * custom user info */ public static function userInfo() { if (!self::debug()) { return; } if (empty(self::$DATA[self::USER])) { return; } $tbl = new Console_Table(); $tbl->setHeaders(array('key', 'value', 'src')); $cnt = 0; foreach (self::$DATA[self::USER] as $row) { if ($cnt > 0) { $tbl->addSeparator(); } $tbl->addRow($row); $cnt++; } echo PHP_EOL . $tbl->getTable() . PHP_EOL; }
function tabla($tabla, $titulos) { if (count($tabla) > 0) { $this->imprimir(Console_Table::fromArray($titulos, $tabla)); } else { self::mensaje('...No hay DATOS!'); } }
function lista($lista, $titulo) { if (count($lista) > 0) { $i = 0; foreach ($lista as $l) { $datos[$i][0] = $l; $i++; } $this->imprimir(Console_Table::fromArray(array($titulo), $datos)); } }
/** * Dump the data as returned by fetch(). * * This method is meant for debugging purposes. It returns what fetch() * would return to its DataGrid host as a nicely formatted console-style * table. * * @param integer $offset Limit offset (starting from 0) * @param integer $len Limit length * @param string $sortField Field to sort by * @param string $sortDir Sort direction : 'ASC' or 'DESC' * @return string The table string, ready to be printed * @uses Structures_DataGrid_DataSource::fetch() * @access public */ function dump($offset = 0, $len = null, $sortField = null, $sortDir = 'ASC') { $records =& $this->fetch($offset, $len, $sortField, $sortDir); $columns = $this->getColumns(); if (!$columns and !$records) { return "<Empty set>\n"; } include_once 'Console/Table.php'; $table = new Console_Table(); $headers = array(); if ($columns) { foreach ($columns as $col) { $headers[] = is_null($col->fieldName) ? $col->columnName : "{$col->columnName} ({$col->fieldName})"; } } else { $headers = array_keys($records[0]); } $table->setHeaders($headers); foreach ($records as $rec) { $table->addRow($rec); } return $table->getTable(); }
/** * Return Console_Table object * * Used for displaying detail lines of the report in tabular format. * * @return Console_Table */ public function table() { $tbl = new Console_Table(CONSOLE_TABLE_ALIGN_LEFT, " ", 0); //set up filters for limiting widths of columns inside the table $filter0 = array($this, '_splitName'); $tbl->addFilter(0, $filter0); $filter1 = array($this, '_splitSize'); $tbl->addFilter(1, $filter1); if ($this->cols == 3) { $filter2 = array($this, '_splitDetail'); $tbl->addFilter(2, $filter2); } return $tbl; }
public function toString() { $this->_colorizer = new Zend_Tool_Framework_Client_Console_ResponseDecorator_Colorizer(); $string = array(); $string[] = array(array('LINE', 'bgRed')); $string[] = array(array($this->_data['errstr'], array('hiWhite', 'bgRed')), array('SPACER', 'bgRed'), array(' | ' . $this->_error2string($this->_data['errno']), 'bgRed')); $string[] = array(array('LINE', 'bgRed')); $insertCodeOffset = null; if (isset($this->_data['backtrace'])) { $table = new Console_Table(CONSOLE_TABLE_ALIGN_LEFT, ''); $index = 1; for ($i = 0; $i < sizeof($this->_data['backtrace']); $i++) { $frame = $this->_data['backtrace'][$i]; $row = array(); if ($i == 0) { // We are dealing with an exception if (is_string($this->_data['errno'])) { $table->addRow(array(' | ' . $this->_normalizeFilePath($this->_data['errfile']), '@ ' . $this->_data['errline'])); } else { // We are dealing with an error if ($frame['class'] == 'FirePHP_Error_Handler') { $i++; if (!isset($frame['file']) && !isset($frame['line'])) { $frame = $this->_data['backtrace'][$i]; } $row[] = ' | ' . $this->_normalizeFilePath($frame['file']); $row[] = '@ ' . $frame['line']; } else { throw new Exception('Could not determine where to insert code!'); } } } if (!$row) { if (!isset($frame['file'])) { // This is a call_user_func*() call frame if (sizeof($this->_data['backtrace']) >= $i + 1) { $frameNext = $this->_data['backtrace'][$i + 1]; $row[] = ' | ' . $this->_normalizeFilePath($frameNext['file']); $row[] = '@ ' . $frameNext['line']; $row[] = '- call_user_func*(\'' . $frame['class'] . '\',\'' . $frame['function'] . '\')'; $i++; } } else { $row[] = ' | ' . $this->_normalizeFilePath($frame['file']); $row[] = '@ ' . $frame['line']; $row[] = '- ' . (isset($frame['type']) ? $frame['class'] . $frame['type'] . $frame['function'] : $frame['function']) . '(' . $this->_renderArgs($frame['args']) . ')'; } } $table->addRow($row); $index++; } $insertCodeOffset = sizeof($string) + 1; foreach (explode("\n", $table->getTable()) as $line) { if ($line = rtrim($line)) { $string[] = rtrim($line); } } } if (isset($this->_data['errfile']) && isset($this->_data['errline'])) { $code = array(); $code[] = ' |'; $start = $this->_data['errline'] - 5; if ($start < 0) { $start = 0; } // TODO: Make number of lines configurable $end = $start + 10; $lines = file($this->_data['errfile']); if ($end >= sizeof($lines)) { $end = sizeof($lines) - 1; } for ($i = $start; $i <= $end; $i++) { $errorLine = $i + 1 == $this->_data['errline']; $lines[$i] = str_replace("\t", ' ', rtrim($lines[$i])); $code[] = str_pad($i + 1, 4, ' ', STR_PAD_LEFT) . ($errorLine ? '|>' : '| ') . $lines[$i]; // See if we have annotated arguments on previous lines and insert them if ($errorLine && ($vars = FirePHP_Annotator::getVariables())) { for ($j = sizeof($code) - 1; $j >= sizeof($code) - 4; $j--) { if (($pos = strpos($code[$j], 'FirePHP_Annotator::setVariables(')) !== false) { $varLines = array(); $varLines[] = ''; foreach ($vars as $name => $value) { $varLines[] = ' :' . str_repeat(' ', $pos - 1) . $name . ' = ' . $this->_renderVar($value, 70); } $varLines[] = ''; array_splice($code, $j + 1, 0, $varLines); break; } } } } $code[] = ' |'; if ($insertCodeOffset !== null) { array_splice($string, $insertCodeOffset, 0, $code); } else { array_splice($string, sizeof($string), 0, $code); } } $string[] = array(array('LINE', 'bgRed')); $string[] = array('RIGHT', array('Generated by FirePHP: http://www.firephp.org/', 'cyan')); $this->_markupOutput($string); return implode("\n", $string); }
<?php require_once 'DB.php'; require_once 'Console/Table.php'; $dbh = DB::connect('mysqli://*****:*****@localhost/pear'); if (PEAR::isError($dbh)) { die('Database connection failed'); } $sql = ' SELECT p.name, p.license FROM packages p WHERE p.package_type = "pear" AND p.license LIKE "%PHP%" ORDER BY p.name'; $data = $dbh->getAll($sql, DB_FETCHMODE_ASSOC); $table = new Console_Table(); $table->setHeaders(array('Package (' . count($data) . ')', 'License')); $table->addData($data); echo $table->getTable();