functions outside of loop not updating - php

I'm trying to do a loop that display a few conditions based on load average and cpus/memory etc. However, it seems like it only pull the usage information once for the entire loop. I want it to update it on each loop: Here's what I got, any kind of help on this is great appreciated!
<?php
exec("cat /proc/cpuinfo | grep processor | wc -l",$processors);
$totalc=$processors[0];
function sys_getloadavg_hack()
{
$str = substr(strrchr(shell_exec("uptime"),":"),1);
$avs = array_map("trim",explode(",",$str));
return $avs;
}
$load = sys_getloadavg_hack();
function get_memory() {
foreach(file('/proc/meminfo') as $ri)
$m[strtok($ri, ':')] = strtok('');
return 100 - round(($m['MemFree'] + $m['Buffers'] + $m['Cached']) / $m['MemTotal'] * 100);
}
function print_exec(){
$out_arr=array();
$last_line=exec("mpstat",$out_arr);
return $last_line;
}
for ($i=1; $i<=50; $i++)
{
$memory = get_memory();
$cpu = substr(print_exec(),-5);
if($memory>"10" && $cpu>"10" && $load[0]<$totalc) {
echo "Everything is good!";
} else {
}
echo "Memory: $memory || CPU: $cpu || Load AVG: $load[0] || #CPU's: $totalc<br> || #Runtime: $i\n\n";
usleep(800000);
}
?>

You have to make all calculations every loop.
For example: You call sys_getloadavg_hack() only once before your loop.
Try to add the sys_getloadavg_hack() call in the for loop.
for(...)
{
$load = sys_getloadavg_hack();
...
}

Related

php loop flip coin until 2 heads, then stop

I'm new to php and am trying to write a loop that will flip a coin until exactly two heads have been flipped and then stop.
So far I've written a function for coin flipping:
function cointoss () {
$cointoss = mt_rand(0,1);
$headsimg = '<img src=""/>';
$tailsimg = '<img src=""/>';
if ($cointoss == 1){
print $headsimg;
} else {
print $tailsimg;
}
return $cointoss;
}
...but am stuck on writing the loop. I've tried a couple ways:
#this code takes forever to load
$twoheads = 0;
for ($twoheads = 1 ; $twoheads <= 20; $twoheads++) {
$cointoss = mt_rand(0,1);
cointoss ();
if ($cointoss == 1) {
do {
cointoss ();
} while ($cointoss == 1);
}
}
#one coin flips
do {
cointoss ();
} while ($cointoss == 1);
This is a for a class, and we haven't learned arrays yet, so I need to accomplish this without them.
I understand the concept of loops executing code while a condition is true, but don't understand how to write for when a condition is no longer true.
Printing from inside of "processing functions" is a bad habit to get into. You might like to declare a showCoin($toss) function for printing. In truth, I don't know if I would bother with any custom functions.
You need to declare a variable which will hold the return value from your function.
By storing the current and previous toss values, you can write a simple check if two consecutive "heads" have occurred.
Code: (Demo)
function cointoss () {
return mt_rand(0,1); // return zero or one
}
$previous_toss = null;
$toss = null;
do {
if ($toss !== null) { // only store a new "previous_toss" if not the first iteration
$previous_toss = $toss; // store last ieration's value
}
$toss = cointoss(); // get current iteration's value
echo ($toss ? '<img src="heads.jpg"/>' : '<img src="tails.jpg"/>') , "\n";
// ^^^^^- if a non-zero/non-falsey value, it is heads, else tails
} while ($previous_toss + $toss != 2);
// ^^^^^^^^^^^^^^^^^^^^^^- if 1 + 1 then 2 breaks the loop
Possible Output:
<img src="heads.jpg"/>
<img src="tails.jpg"/>
<img src="tails.jpg"/>
<img src="tails.jpg"/>
<img src="heads.jpg"/>
<img src="heads.jpg"/>

How to select the next number in a loop?

The function for the primes is clear, so I omitted it.
$a=10;
$z=30;
for($prime = $a; $prime<$z; $prime++)
{ if
(Prim($prime) == TRUE)
{ echo $prime."<br/>";}}
Now I want to select the next term of the sequence as well, in order to perform an operation between the variable $prime and $next_prime, as long as the loop goes on - like for example:
$prime_gap=bcsub($next_prime, $prime);
Whatever solutions I find and I try, it's never the proper one. It's surely very simple but I am already desperate.
I would suggest you start by creating a next_prime() function. Like this, for example:
function next_prime($n) {
do {
$n++;
} while (!Prim($n));
return $n;
}
Then you can refactor your code quite easily:
$a=10;
$z=30;
for ($p1=next_prime($a),$p2=next_prime($p1); $p2<$z; $p1=$p2,$p2=next_prime($p2)) {
if (some_function($p1, $p2)) {
echo "I like $p1 and $p2\n";
}
}
The if I add in the for loop is not so nice, but if you want something simple and easy to understand, you can still use it (I switch the name from $prime & $next_prime to $prime & $previous_prime, I think it makes more sense)
$a=10;
$z=30;
$previous_prime = 0;
for($prime = $a; $prime<$z; $prime++)
{
if (Prim($prime) == TRUE)
{
echo $prime."<br/>";
if ($previous_prime == 0) {
$previous_prime = $prime
} else
{
$prime_gap = $prime - $previous_prime;
$previous_prime = $prime;
}
}
}

Calculate Library Fine (PHP)

So, here is the question (https://www.hackerrank.com/challenges/library-fine) I am trying to solve. To solve this, I created a simple function calculateFine and set the conditions to calculate the fine. What's the problem, then? Well, when I run the code on my machine, everything seems fine, but hackerrank won't accept the code. I am new to PHP and concept of functions was a bit confusing for me, but I tried. Below is my code:
<?php
$_fp = fopen("php://stdin", "r");
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
$_a = explode(" ",fgets($_fp));
$_b = explode(" ",fgets($_fp));
// Initialising variable
$_fine = "";
// Calling Function
calculateFine($_a,$_b);
// Defining Function
function calculateFine($actualDate, $returnDate)
{
// Checking various conditions
if ($actualDate[0] <= $returnDate[0] && $actualDate[1] == $returnDate[1] && $actualDate[2] == $returnDate[2])
{
$_fine = 0;
echo $_fine;
}
elseif($actualDate[0] > $returnDate[0] && $actualDate[1] == $returnDate[1] && $actualDate[2] == $returnDate[2])
{
$_late = $actualDate[0] - $returnDate[0];
$_fine = 15*$_late;
echo $_fine;
}
elseif($actualDate[1] > $returnDate[1] && $actualDate[2] == $returnDate[2])
{
$_late = $actualDate[1] - $returnDate[1];
$_fine = 500*$_late;
echo $_fine;
}
elseif($actualDate[2] > $returnDate[2])
{
$_fine = 10000;
echo $_fine;
}
else
{
$_fine = 0;
echo $fine; // Updated (This is the undefined variable causing error )
}
}
?>
It seems there's a newline in $actualDate[2]. So if you trim it you'll get the right answer:
trim($actualDate[2])
But would be better to trim it here already:
$_a = explode(" ",trim(fgets($_fp)));
$_b = explode(" ",trim(fgets($_fp)));
I got it, sorry for the carelessness. The last echo is $fine instead of $_fine. That's why the condition was not matching with some of the test cases. Thankyou.

How do you calculate server load in PHP?

How do you calculate the server load of PHP/apache? I know in vBulletin forums there's the server load displayed like 0.03 0.01 0.04 but it's not really understandable to a average joe. So I thought about a 1-100 percentile scale. I wanted to display a server load visual that reads from a DIV:
$load = $serverLoad*100;
<div class=\"serverLoad\">
<div style=\"width: $load%;\"></div>//show visual for server load on a 1-100 % scale
</div>
<p>Current server load is $load%</p>
</div>
However, I don't know how to detect server load. Is it possible to do turn this server load into a percentile scale? I don't know where to start. May someone please help me out?
Thanks.
I have a very old function that should still do the trick:
function getServerLoad($windows = false){
$os=strtolower(PHP_OS);
if(strpos($os, 'win') === false){
if(file_exists('/proc/loadavg')){
$load = file_get_contents('/proc/loadavg');
$load = explode(' ', $load, 1);
$load = $load[0];
}elseif(function_exists('shell_exec')){
$load = explode(' ', `uptime`);
$load = $load[count($load)-1];
}else{
return false;
}
if(function_exists('shell_exec'))
$cpu_count = shell_exec('cat /proc/cpuinfo | grep processor | wc -l');
return array('load'=>$load, 'procs'=>$cpu_count);
}elseif($windows){
if(class_exists('COM')){
$wmi=new COM('WinMgmts:\\\\.');
$cpus=$wmi->InstancesOf('Win32_Processor');
$load=0;
$cpu_count=0;
if(version_compare('4.50.0', PHP_VERSION) == 1){
while($cpu = $cpus->Next()){
$load += $cpu->LoadPercentage;
$cpu_count++;
}
}else{
foreach($cpus as $cpu){
$load += $cpu->LoadPercentage;
$cpu_count++;
}
}
return array('load'=>$load, 'procs'=>$cpu_count);
}
return false;
}
return false;
}
This returns processor load. You can also use memory_get_usage and memory_get_peak_usage for memory load.
If you can't handle finding percentages based on this... sigh, just post and we'll try together.
This function in PHP might do that trick: sys_getloadavg().
Returns three samples representing the average system load (the number of processes in the system run queue) over the last 1, 5 and 15 minutes, respectively.
function get_server_load()
{
$serverload = array();
// DIRECTORY_SEPARATOR checks if running windows
if(DIRECTORY_SEPARATOR != '\\')
{
if(function_exists("sys_getloadavg"))
{
// sys_getloadavg() will return an array with [0] being load within the last minute.
$serverload = sys_getloadavg();
$serverload[0] = round($serverload[0], 4);
}
else if(#file_exists("/proc/loadavg") && $load = #file_get_contents("/proc/loadavg"))
{
$serverload = explode(" ", $load);
$serverload[0] = round($serverload[0], 4);
}
if(!is_numeric($serverload[0]))
{
if(#ini_get('safe_mode') == 'On')
{
return "Unknown";
}
// Suhosin likes to throw a warning if exec is disabled then die - weird
if($func_blacklist = #ini_get('suhosin.executor.func.blacklist'))
{
if(strpos(",".$func_blacklist.",", 'exec') !== false)
{
return "Unknown";
}
}
// PHP disabled functions?
if($func_blacklist = #ini_get('disable_functions'))
{
if(strpos(",".$func_blacklist.",", 'exec') !== false)
{
return "Unknown";
}
}
$load = #exec("uptime");
$load = explode("load average: ", $load);
$serverload = explode(",", $load[1]);
if(!is_array($serverload))
{
return "Unknown";
}
}
}
else
{
return "Unknown";
}
$returnload = trim($serverload[0]);
return $returnload;
}
If "exec" is activated
/**
* Return the current server load
* It needs "exec" activated
*
* e.g.
* 15:06:37 up 10 days, 5:59, 12 users, load average: 1.40, 1.45, 1.33
* returns
* float(1.40)
*/
public function getServerLoad()
{
preg_match('#(\d\.\d+),[\d\s\.]+,[\d\s\.]+$#', exec("uptime"), $m);
return (float)$m[1];
}
<?php
$load = sys_getloadavg();
if ($load[0] > 0.80) {
header('HTTP/1.1 503 Too busy, try again later');
die('Server too busy. Please try again later.');
}
?>
Its Pretty easy in LAMP environment if you have proper permissions,
print_r(sys_getloadavg());
OUTPUT : Array ( [0] => 0 [1] => 0.01 [2] => 0.05 )
Array values are average load in the past 1, 5 and 15 minutes respectively.
Here is a windows/linux compatible php server load function:
function get_server_load() {
$load = '';
if (stristr(PHP_OS, 'win')) {
$cmd = 'wmic cpu get loadpercentage /all';
#exec($cmd, $output);
if ($output) {
foreach($output as $line) {
if ($line && preg_match('/^[0-9]+$/', $line)) {
$load = $line;
break;
}
}
}
} else {
$sys_load = sys_getloadavg();
$load = $sys_load[0];
}
return $load;
}
function _loadavg()
{
if(class_exists("COM"))
{
$wmi = new COM("WinMgmts:\\\\.");
$cpus = $wmi->InstancesOf("Win32_Processor");
foreach ($cpus as $cpu)
{
return $cpu->LoadPercentage;
}
}
}

Is there a piece of public code available to create a page index using PHP?

I have a MySQL table holding lots of records that i want to give the user access to. I don't want to dump the entire table to the page so i need to break it up into 25 records at a time, so i need a page index. You have probably seen these on other pages, they kind of look like this at the base of the page:
< 1 2 3 4 5 6 7 8 9 >
For example, when the user clicks on the '4' link, the page refreshes and the offset is moved on (4th page x 25 records). Here is what i already have:
function CreatePageIndex($ItemsPerPage, $TotalNumberOfItems, $CurrentOffset, $URL, $URLArguments = array())
{
foreach($URLArguments as $Key => $Value)
{
if($FirstIndexDone == false)
{
$URL .= sprintf("?%s=%s", $Key, $Value);
$FirstIndexDone = true;
}
else
{
$URL .= sprintf("&%s=%s", $Key, $Value);
}
}
Print("<div id=\"ResultsNavigation\">");
Print("Page: ");
Print("<span class=\"Links\">");
$NumberOfPages = ceil($TotalNumberOfItems / $ItemsPerPage);
for($x = 0; $x < $NumberOfPages; $x++)
{
if($x == $CurrentOffset / $ItemsPerPage)
{
Print("<span class=\"Selected\">".($x + 1)." </span>");
}
else
{
if(empty($URLArguments))
{
Print("".($x + 1)." ");
}
else
{
Print("".($x + 1)." ");
}
}
}
Print("</span>");
Print(" (".$TotalNumberOfItems." results)");
Print("</div>");
}
Obviously this piece of code does not create a dynamic index, it just dumps the whole index at the bottom of the page for every page available. What i need is a dynamic solution that only shows the previous 5 pages and next 5 pages (if they exist) along with a >> or something to move ahead 5 or so pages.
Anybody seen an elegant and reusable way of implementing this as i feel i'm re-inventing the wheel? Any help is appreciated.
Zend Framework is becoming a useful collection and includes a Zend_Paginator class, which might be worth a look. Bit of a learning curve and might only be worth it if you want to invest the time in using other classes from the framework.
It's not too hard to roll your own though. Get a total count of records with a COUNT(*) query, then obtain a page of results with a LIMIT clause.
For example, if you want 20 items per page, page 1 would have LIMIT 0,20 while page 2 would be LIMIT 20,20, for example
$count=getTotalItemCount();
$pagesize=20;
$totalpages=ceil($count/$pagesize);
$currentpage=isset($_GET['pg'])?intval($_GET['pg']):1;
$currentpage=min(max($currentpage, 1),$totalpages);
$offset=($currentpage-1)*$pagesize;
$limit="LIMIT $offset,$pagesize";
It's called Pagination:
a few examples:
A nice one without SQL
A long tutorial
Another tutorial
And Another
And of course.. google
How about this jQuery-plugin?
So all the work is done on the clientside.
http://plugins.jquery.com/project/pagination
demo: http://d-scribe.de/webtools/jquery-pagination/demo/demo_options.htm
Heres an old class I dug out that I used to use in PHP. Now I handle most of it in Javascript. The object takes an array (that you are using to split the stack into pages) and return the current view. This can become tedious on giant tables so keep that in mind. I generally use it for paging through small data sets of under 1000 items. It can also optionally generate your jump menu for you.
class pagination {
function pageTotal($resultCount, $splitCount) {
if (is_numeric($resultCount) && is_numeric($splitCount)) {
if ($resultCount > $splitCount) {
$pageAverage = (integer)$resultCount / $splitCount;
$pageTotal = ceil($pageAverage);
return $pageTotal;
} else {
return 1;
}
} else {
return false;
}
}
function pageTotalFromStack($resultArray, $splitCount) {
if (is_numeric($splitCount) && is_array($resultStack)) {
if (count($resultStack) > $splitCount) {
$resultCount = count($resultStack);
$pageAverage = (integer)$resultCount / $splitCount;
$pageTotal = ceil($pageAverage);
return $pageTotal;
} else {
return 1;
}
} else {
return false;
}
}
function makePaginationURL($preURL, $pageTotal, $selected=0, $linkAttr=0, $selectedAttr=0) {
if (!empty($preURL) && $pageTotal >= 1) {
$pageSeed = 1;
$passFlag = 0;
$regLink = '<a href="{url}&p={page}"';
if (is_array($linkAttr)) $regLink .= $this->setAttributes($linkAttr); //set attributes
$regLink .= '>{page}</a>';
$selLink = '<a href="{url}&p={page}"';
if (is_array($selectedAttr)) $selLink .= $this->setAttributes($selectedAttr); //set attributes
$selLink .= '>{page}</a>';
while($pageSeed <= $pageTotal) {
if ($pageSeed == $selected) {
$newPageLink = str_replace('{url}', $preURL, $selLink);
$newPageLink = str_replace('{page}', $pageSeed, $newPageLink);
} else {
$newPageLink = str_replace('{url}', $preURL, $regLink);
$newPageLink = str_replace('{page}', $pageSeed, $newPageLink);
}
if ($passFlag == 0) {
$passFlag = 1;
$linkStack = $newPageLink;
} else {
$linkStack .= ', ' . $newPageLink;
}
$pageSeed++;
}
return $linkStack;
} else {
return false;
}
}
function splitPageArrayStack($stackArray, $chunkSize) {
if (is_array($stackArray) && is_numeric($chunkSize)) {
return $multiArray = array_chunk($stackArray, $chunkSize);
} else {
return false;
}
}
}

Categories