i am trying to test database speed with php script.
database connect time
database query time/execution time
database basic information like version, port etc
I am using : https://stackoverflow.com/a/39559173
I am trying :
<?php
/**
* Created by PhpStorm.
* User: NEO
* Date: 9/18/2016
* Time: 10:57 AM
*/
/**
* PHP Script to benchmark PHP and MySQL-Server
*
* inspired by / thanks to:
* - www.php-benchmark-script.com (Alessandro Torrisi)
* - www.webdesign-informatik.de
*
* #author odan
* #license MIT
*/
// -----------------------------------------------------------------------------
// Setup
// -----------------------------------------------------------------------------
set_time_limit(120); // 2 minutes
$options = array();
// Optional: mysql performance test
$options['db.host'] = '127.0.0.1';
$options['db.user'] = 'root';
$options['db.pw'] = '';
$options['db.name'] = 'bache3';
// -----------------------------------------------------------------------------
// Main
// -----------------------------------------------------------------------------
// check performance
$benchmarkResult = test_benchmark($options);
// html output
echo "<!DOCTYPE html>\n<html><head>\n";
echo "<style>
table {
color: #333; /* Lighten up font color */
font-family: Helvetica, Arial, sans-serif; /* Nicer font */
width: 640px;
border-collapse:
collapse; border-spacing: 0;
}
td, th {
border: 1px solid #CCC; height: 30px;
} /* Make cells a bit taller */
th {
background: #F3F3F3; /* Light grey background */
font-weight: bold; /* Make sure they're bold */
}
td {
background: #FAFAFA; /* Lighter grey background */
}
</style>
</head>
<body>";
echo array_to_html($benchmarkResult);
echo "\n</body></html>";
exit;
// -----------------------------------------------------------------------------
// Benchmark functions
// -----------------------------------------------------------------------------
function test_benchmark($settings)
{
$timeStart = microtime(true);
$result = array();
$result['version'] = '1.1';
$result['sysinfo']['time'] = date("Y-m-d H:i:s");
$result['sysinfo']['php_version'] = PHP_VERSION;
$result['sysinfo']['platform'] = PHP_OS;
$result['sysinfo']['server_name'] = $_SERVER['SERVER_NAME'];
$result['sysinfo']['server_addr'] = $_SERVER['SERVER_ADDR'];
test_math($result);
test_string($result);
test_loops($result);
test_ifelse($result);
if (isset($settings['db.host'])) {
test_mysql($result, $settings);
}
$result['total'] = timer_diff($timeStart);
return $result;
}
function test_math(&$result, $count = 99999)
{
$timeStart = microtime(true);
$mathFunctions = array("abs", "acos", "asin", "atan", "bindec", "floor", "exp", "sin", "tan", "pi", "is_finite", "is_nan", "sqrt");
for ($i = 0; $i < $count; $i++) {
foreach ($mathFunctions as $function) {
call_user_func_array($function, array($i));
}
}
$result['benchmark']['math'] = timer_diff($timeStart);
}
function test_string(&$result, $count = 99999)
{
$timeStart = microtime(true);
$stringFunctions = array("addslashes", "chunk_split", "metaphone", "strip_tags", "md5", "sha1", "strtoupper", "strtolower", "strrev", "strlen", "soundex", "ord");
$string = 'the quick brown fox jumps over the lazy dog';
for ($i = 0; $i < $count; $i++) {
foreach ($stringFunctions as $function) {
call_user_func_array($function, array($string));
}
}
$result['benchmark']['string'] = timer_diff($timeStart);
}
function test_loops(&$result, $count = 999999)
{
$timeStart = microtime(true);
for ($i = 0; $i < $count; ++$i) {
}
$i = 0;
while ($i < $count) {
++$i;
}
$result['benchmark']['loops'] = timer_diff($timeStart);
}
function test_ifelse(&$result, $count = 999999)
{
$timeStart = microtime(true);
for ($i = 0; $i < $count; $i++) {
if ($i == -1) {
} elseif ($i == -2) {
} else if ($i == -3) {
}
}
$result['benchmark']['ifelse'] = timer_diff($timeStart);
}
function test_mysql(&$result, $settings)
{
$timeStart = microtime(true);
$link = mysqli_connect($settings['db.host'], $settings['db.user'], $settings['db.pw']);
$result['benchmark']['mysql']['connect'] = timer_diff($timeStart);
//$arr_return['sysinfo']['mysql_version'] = '';
mysqli_select_db($link, $settings['db.name']);
$result['benchmark']['mysql']['select_db'] = timer_diff($timeStart);
$dbResult = mysqli_query($link, 'SELECT VERSION() as version;');
$arr_row = mysqli_fetch_array($dbResult);
$result['sysinfo']['mysql_version'] = $arr_row['version'];
$result['benchmark']['mysql']['query_version'] = timer_diff($timeStart);
$query = "SELECT BENCHMARK(1000000,ENCODE('hello',RAND()));";
$dbResult = mysqli_query($link, $query);
$result['benchmark']['mysql']['query_benchmark'] = timer_diff($timeStart);
mysqli_close($link);
$result['benchmark']['mysql']['total'] = timer_diff($timeStart);
return $result;
}
function timer_diff($timeStart)
{
return number_format(microtime(true) - $timeStart, 3);
}
function array_to_html($array)
{
$result = '';
if (is_array($array)) {
$result .= '<table>';
foreach ($array as $k => $v) {
$result .= "\n<tr><td>";
$result .= '<strong>' . htmlentities($k) . "</strong></td><td>";
$result .= array_to_html($v);
$result .= "</td></tr>";
}
$result .= "\n</table>";
} else {
$result = htmlentities($array);
}
return $result;
}
The above script is working fine but it does not have a option to add custom port for testing and it do not show information like execution time etc
Related
I'm trying ta make a program that will ask the user for a number and then show all the prime numbers between 0 to this number in an array.
<?php
class SmallerPrimes{
public function __construct($file){
$this->input_filename = $file;
}
public function Main(){
$smaller_than = (int)$this->readString()[0];
$result = array();
/* YOUR CODE HERE */
function isPrime($n)
{
if ($n <= 1)
return false;
for ($i = 2; $i < $n; $i++)
if ($n % $i == 0)
return false;
return true;
}
function printPrime($n)
{
for ($i = 2; $i <= $n; $i++)
{
if (isPrime($i))
echo $i . " ";
}
}
$n = 7;
printPrime($n);
/*end of your code here */
return $result;
}
public function readString(){
$file = fopen($this->input_filename, "r");
$line = array();
while (!feof($file)){
array_push($line, str_replace(PHP_EOL, "", fgets($file)));
}
return $line;
}
}
$o = new SmallerPrimes($argv[1]);
echo implode(" ", $o->Main()) . PHP_EOL;
This code work, but with a $n fixed.
I don't know how to use an input who ask the user a number
It's a code who verify itself and show us when it's ok
The code that i have to complete is this one (we only have this at first):
class SmallerPrimes{
public function __construct($file){
$this->input_filename = $file;
}
public function Main(){
$smaller_than = (int)$this->readString()[0];
$result = array();
/* YOUR CODE HERE */
return $result;
}
public function readString(){
$file = fopen($this->input_filename, "r");
$line = array();
while (!feof($file)){
array_push($line, str_replace(PHP_EOL, "", fgets($file)));
}
return $line;
}
}
$o = new SmallerPrimes($argv[1]);
echo implode(" ", $o->Main()) . PHP_EOL;
This is your script:
<?php
class SmallerPrimes{
public function __construct($file){
$this->input_filename = $file;
}
public function Main(){
$smaller_than = (int)$this->readString()[0];
$result = array();
function isPrime($n) {
if ($n <= 1) return false;
for ($i = 2; $i < $n; $i++) if ($n % $i == 0) return false;
return true;
}
function printPrime($n) {
for ($i = 2; $i < $n; $i++) if (isPrime($i)) $result[] = $i;
return $result;
}
$result = printPrime($smaller_than);
return $result;
}
public function readString(){
$file = fopen($this->input_filename, "r");
$line = array();
while (!feof($file)){
array_push($line, str_replace(PHP_EOL, "", fgets($file)));
}
return $line;
}}
$o = new SmallerPrimes($argv[1]);
echo implode(" ", $o->Main()) . PHP_EOL;
function getSmallerPrimes($smaller_than) {
if ($smaller_than <= 2) {
return [];
}
$result = [2];
$sqrt = sqrt($smaller_than);
for ($n = 3; $n < $smaller_than; $n += 2) {
$isPrime = true;
foreach($result as $prime) {
if ($n % $prime == 0) {
$isPrime = false;
break;
}
if ($prime > $sqrt) {
break;
}
}
if ($isPrime) {
$result[] = $n;
}
}
return $result;
}
$input = 23;
echo implode(' ', getSmallerPrimes($input));
Result: 2 3 5 7 11 13 17 19
I downloaded apriori algorithm on php from www.vtwo.org but i want to apply it to my CI framework, but the input value won't be called. so it couldn't display the result. is it something wrong on my CI code changes? please help
this is my apriori controller (apriori.php)
class Apriori {
private $delimiter = ',';
private $minSup = 2;
private $minConf = 50;
private $rules = array();
private $table = array();
private $allthings = array();
private $allsups = array();
private $keys = array();
private $freqItmsts = array();
private $phase = 1;
//maxPhase>=2
private $maxPhase = 20;
private $fiTime = 0;
private $arTime = 0;
public function setDelimiter($char)
{
$this->delimiter = $char;
}
public function setMinSup($int)
{
$this->minSup = $int;
}
public function setMinConf($int)
{
$this->minConf = $int;
}
public function setMaxScan($int)
{
$this->maxPhase = $int;
}
public function getDelimiter()
{
return $this->delimiter;
}
public function getMinSup()
{
return $this->minSup;
}
public function getMinConf()
{
return $this->minConf;
}
public function getMaxScan()
{
return $this->maxPhase;
}
/**
1. جدول آیتمها را می سازد
2. کلید دسترسی به هر آیتم را تولید می کند
3. تمامی آیتمها و تکرار آنها را محاسبه می کند - سطح 1
توجه: حداقل تکرار محاسبه میشود
**/
private function makeTable($db)
{
$table = array();
$array = array();
$counter = 1;
if(!is_array($db))
{
$db = file($db);
}
$num = count($db);
for($i=0; $i<$num; $i++)
{
$tmp = explode($this->delimiter, $db[$i]);
$num1 = count($tmp);
$x = array();
for($j=0; $j<$num1; $j++)
{
$x = trim($tmp[$j]);
if($x==='')
{
continue;
}
if(!isset($this->keys['v->k'][$x]))
{
$this->keys['v->k'][$x] = $counter;
$this->keys['k->v'][$counter] = $x;
$counter++;
}
if(!isset($array[$this->keys['v->k'][$x]]))
{
$array[$this->keys['v->k'][$x]] = 1;
$this->allsups[$this->keys['v->k'][$x]] = 1;
}
else
{
$array[$this->keys['v->k'][$x]]++;
$this->allsups[$this->keys['v->k'][$x]]++;
}
$table[$i][$this->keys['v->k'][$x]] = 1;
}
}
$tmp = array();
foreach($array as $item => $sup)
{
if($sup>=$this->minSup)
{
$tmp[] = array($item);
}
}
$this->allthings[$this->phase] = $tmp;
$this->table = $table;
}
/**
1. مقدار سوپریموم را با توجه به ورودی شناسه آیتمها شمارش می کند
**/
private function scan($arr, $implodeArr = '')
{
$cr = 0;
if($implodeArr)
{
if(isset($this->allsups[$implodeArr]))
{
return $this->allsups[$implodeArr];
}
}
else
{
sort($arr);
$implodeArr = implode($this->delimiter, $arr);
if(isset($this->allsups[$implodeArr]))
{
return $this->allsups[$implodeArr];
}
}
$num = count($this->table);
$num1 = count($arr);
for($i=0; $i<$num; $i++)
{
$bool = true;
for($j=0; $j<$num1; $j++)
{
if(!isset($this->table[$i][$arr[$j]]))
{
$bool = false;
break;
}
}
if($bool)
{
$cr++;
}
}
$this->allsups[$implodeArr] = $cr;
return $cr;
}
/**
1. ترکیب دو آرایه و حذف مقادیر اضافی
**/
private function combine($arr1, $arr2)
{
$result = array();
$num = count($arr1);
$num1 = count($arr2);
for($i=0; $i<$num; $i++)
{
if(!isset($result['k'][$arr1[$i]]))
{
$result['v'][] = $arr1[$i];
$result['k'][$arr1[$i]] = 1;
}
}
for($i=0; $i<$num1; $i++)
{
if(!isset($result['k'][$arr2[$i]]))
{
$result['v'][] = $arr2[$i];
$result['k'][$arr2[$i]] = 1;
}
}
return $result['v'];
}
/**
1. نام آیتم را با توجه به شناسه آیتم یا آیتمها بر می گرداند
{1,2,3,4} => {A,B,C,D}
**/
private function realName($arr)
{
$result = '';
$num = count($arr);
for($j=0; $j<$num; $j++)
{
if($j)
{
$result .= $this->delimiter;
}
$result .= $this->keys['k->v'][$arr[$j]];
}
return $result;
}
//1-2=>2-3 : false
//1-2=>5-6 : true
private function checkRule($a, $b)
{
$a_num = count($a);
$b_num = count($b);
for($i=0; $i<$a_num; $i++)
{
for($j=0; $j<$b_num; $j++)
{
if($a[$i]==$b[$j])
{
return false;
}
}
}
return true;
}
private function confidence($sup_a, $sup_ab)
{
return round(($sup_ab / $sup_a) * 100, 2);
}
private function subsets($items)
{
$result = array();
$num = count($items);
$members = pow(2, $num);
for($i=0; $i<$members; $i++)
{
$b = sprintf("%0".$num."b", $i);
$tmp = array();
for($j=0; $j<$num; $j++)
{
if($b[$j]=='1')
{
$tmp[] = $items[$j];
}
}
if($tmp)
{
sort($tmp);
$result[] = $tmp;
}
}
return $result;
}
/**
1. آیتم ستهای تکراری را بر می گرداند
**/
private function freqItemsets($db)
{
$this->fiTime = $this->startTimer();
$this->makeTable($db);
while(1)
{
if($this->phase>=$this->maxPhase)
{
break;
}
$num = count($this->allthings[$this->phase]);
$cr = 0;
for($i=0; $i<$num; $i++)
{
for($j=$i; $j<$num; $j++)
{
if($i==$j)
{
continue;
}
$item = $this->combine($this->allthings[$this->phase][$i], $this->allthings[$this->phase][$j]);
sort($item);
$implodeArr = implode($this->delimiter, $item);
if(!isset($this->freqItmsts[$implodeArr]))
{
$sup = $this->scan($item, $implodeArr);
if($sup>=$this->minSup)
{
$this->allthings[$this->phase+1][] = $item;
$this->freqItmsts[$implodeArr] = 1;
$cr++;
}
}
}
}
if($cr<=1)
{
break;
}
$this->phase++;
}
//زیر مجموعه های مربوط به مجموعه های بزرگتر را حذف می کند
foreach($this->freqItmsts as $k => $v)
{
$arr = explode($this->delimiter, $k);
$num = count($arr);
if($num>=3)
{
$subsets = $this->subsets($arr);
$num1 = count($subsets);
for($i=0; $i<$num1; $i++)
{
if(count($subsets[$i])<$num)
{
unset($this->freqItmsts[implode($this->delimiter, $subsets[$i])]);
}
else
{
break;
}
}
}
}
$this->fiTime = $this->stopTimer($this->fiTime);
}
/**
1. قوانین نهایی را با توجه به مقدار حداقل کانفیندس محاسبه می کند
**/
public function process($db)
{
$checked = $result = array();
$this->freqItemsets($db);
$this->arTime = $this->startTimer();
foreach($this->freqItmsts as $k => $v)
{
$arr = explode($this->delimiter, $k);
$subsets = $this->subsets($arr);
$num = count($subsets);
for($i=0; $i<$num; $i++)
{
for($j=0; $j<$num; $j++)
{
if($this->checkRule($subsets[$i], $subsets[$j]))
{
$n1 = $this->realName($subsets[$i]);
$n2 = $this->realName($subsets[$j]);
$scan = $this->scan($this->combine($subsets[$i], $subsets[$j]));
$c1 = $this->confidence($this->scan($subsets[$i]), $scan);
$c2 = $this->confidence($this->scan($subsets[$j]), $scan);
if($c1>=$this->minConf)
{
$result[$n1][$n2] = $c1;
}
if($c2>=$this->minConf)
{
$result[$n2][$n1] = $c2;
}
$checked[$n1.$this->delimiter.$n2] = 1;
$checked[$n2.$this->delimiter.$n1] = 1;
}
}
}
}
$this->arTime = $this->stopTimer($this->arTime);
return $this->rules = $result;
}
public function printFreqItemsets()
{
echo 'Time: '.$this->fiTime.' second(s)<br />===============================================================================<br />';
foreach($this->freqItmsts as $k => $v)
{
$tmp = '';
$tmp1 = '';
$k = explode($this->delimiter, $k);
$num = count($k);
for($i=0; $i<$num; $i++)
{
if($i)
{
$tmp .= $this->delimiter.$this->realName($k[$i]);
$tmp1 .= $this->delimiter.$k[$i];
}
else
{
$tmp = $this->realName($k[$i]);
$tmp1 = $k[$i];
}
}
echo '{'.$tmp.'} = '.$this->allsups[$tmp1].'<br />';
}
}
public function saveFreqItemsets($filename)
{
$content = '';
foreach($this->freqItmsts as $k => $v)
{
$tmp = '';
$tmp1 = '';
$k = explode($this->delimiter, $k);
$num = count($k);
for($i=0; $i<$num; $i++)
{
if($i)
{
$tmp .= $this->delimiter.$this->realName($k[$i]);
$tmp1 .= $this->delimiter.$k[$i];
}
else
{
$tmp = $this->realName($k[$i]);
$tmp1 = $k[$i];
}
}
$content .= '{'.$tmp.'} = '.$this->allsups[$tmp1]."\n";
}
file_put_contents($filename, $content);
}
public function getFreqItemsets()
{
$result = array();
foreach($this->freqItmsts as $k => $v)
{
$tmp = array();
$tmp['sup'] = $this->allsups[$k];
$k = explode($this->delimiter, $k);
$num = count($k);
for($i=0; $i<$num; $i++)
{
$tmp[] = $this->realName($k[$i]);
}
$result[] = $tmp;
}
return $result;
}
public function printAssociationRules()
{
echo 'Time: '.$this->arTime.' second(s)<br />===============================================================================<br />';
foreach($this->rules as $a => $arr)
{
foreach($arr as $b => $conf)
{
echo "$a => $b = $conf%<br />";
}
}
}
public function saveAssociationRules($filename)
{
$content = '';
foreach($this->rules as $a => $arr)
{
foreach($arr as $b => $conf)
{
$content .= "$a => $b = $conf%\n";
}
}
file_put_contents($filename, $content);
}
public function getAssociationRules()
{
return $this->rules;
}
private function startTimer()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
private function stopTimer($start, $round=2)
{
$endtime = $this->startTimer()-$start;
$round = pow(10, $round);
return round($endtime*$round)/$round;
}} ?>
my welcome controller (welcome.php)
class Welcome extends CI_Controller {
function __construct() {
parent::__construct();
include 'class.apriori.php';
}
// input page
public function index() {
$this->load->view('welcome_message');
}
// minSup, minConf, maxScan value as input
public function ambilinput() {
$minSup = $this->input->post('minSup', true);
$minConf = $this->input->post('minConf', true);
$maxScan = $this->input->post('maxScan', true);
redirect("welcome/apriori/$minSup/$minConf/$maxScan");
}
//APRIORI on system
public function apriori($minSup, $minConf, $maxScan) {
$Apriori = new Apriori();
$Apriori->setMaxScan($maxScan);
$Apriori->setMinSup($minSup);
$Apriori->setMinConf($minConf);
$Apriori->setDelimiter(',');
$dataset = array();
$dataset[] = array('A', 'B', 'C', 'D');
$dataset[] = array('A', 'D', 'C');
$dataset[] = array('B', 'C');
$dataset[] = array('A', 'E', 'C');
$Apriori->process($dataset);
echo '<h1>Frequent Itemsets</h1>';
$Apriori->printFreqItemsets();
echo '<h3>Frequent Itemsets Array</h3>';
print_r($Apriori->getFreqItemsets());
//Association Rules
echo '<h1>Association Rules</h1>';
$Apriori->printAssociationRules();
echo '<h3>Association Rules Array</h3>';
print_r($Apriori->getAssociationRules());
}
}
my view file to input minsup, minconf, and maxScan value
(welcome_message.php)
<head>
<meta charset="utf-8">
<title>Input 1</title>
</head>
<body>
<div>
<form action="<?php echo base_url(); ?>index.php/welcome/ambilinput" method="post">
<input type="number" name="minSup" placeholder="Minimal Support dalam %"/></br></br>
<input type="number" name="minConf" placeholder="Minimal Coff dalam %"/></br></br>
<input type="number" name="maxScan" placeholder="Jumlah Transaksi"/></br></br>
<button type="submit" name="submit">Hitung Apriori</button>
</form>
</div>
</body>
When the following PHP script executes:
<?php
include "imageManager.php";
include "imageHandling/spritesheet.php";
include "updateWindow.php";
include_once "dbConnection.php";
class deleteSoftware{
private $conn;
private $tableName;
public function __construct($name){
//Database Connection
$this->connectDatabase();
//Delete the Icon from the image pool
$tempFileManagerObject = new fileManager();
$tempFileManagerObject->setSrc("../ICONS/");
$deletedImageName = $tempFileManagerObject->getImageNameFromSoftwareName($name);
$tempFileManagerObject->delete("../ICONS/", $deletedImageName);
$tempFileManagerObject->deleteImageRenaming($deletedImageName);
//Deleting the record from the database
$prio = $tempFileManagerObject->getPriorityFromSoftwareName($name);
$subCategory = $tempFileManagerObject->getSubCategoryFromSoftwareName($name);
$this->tableName = $subCategory;
$this->conn->query("delete from ".$subCategory." where priority=".$prio);
$this->decrementPriorityInTable($prio);
//Delete from updateWindow if exist
$updateObject = new updateWindow();
$updateObject->deleteUpdate($name);
//Making sprite Sheet and moving to home directory
echo "step-0";
$spriteSheetObject = new spriteSheet(18, 18, 5, "../ICONS/", "../");
echo "step-1";
for ($x = 1; $x <= $spriteSheetObject->getImageCount(); $x++){ $tempFileManagerObject->copy("../ICONS/", "../Processing/", $x); }
echo "step-3";
$spriteSheetObject->setImagesFolder("../Processing/");
echo "step-4";
$spriteSheetObject->setOutPutFolder("../");
$spriteSheetObject->processSpriteSheet();
$spriteSheetObject->processSpriteSheetCss($this->getTotalSoftwaresCount());
for ($x = 1; $x <= $spriteSheetObject->getImageCount(); $x++){ $tempFileManagerObject->delete("../Processing/",$x); }
$tempFileManagerObject->setSrc("../Processing/");
$tempFileManagerObject->setDes("../");
$tempFileManagerObject->rename("tempArea", "home");
$tempFileManagerObject->move("../Processing/", "../", "home");
}
public function connectDataBase(){
$temp = new dbConnection();
$this->conn = $temp->connectDb();
}
public function getTheImageNameOfNewlyInsertedIcon($subCategory, $pri){
//First of all calculate the iconName of newly inserted image
//-Get the total number of rows for each subCategory table and add it untill we reach at the subCategory table where software to be inserted (Not add subCategory table rows count)
//- RowCounts + maxPriority in that table + 1
//- If there is already software for
//Calculating the total number of rows upto subCateogryTable excluding the subCategoryTable and then add up
$temp = false;
$rowCount = 0;
$this->tableName;
$this->conn->query("use windows");
$softwareTable = $this->conn->query("select * from software order by priority");
foreach ( $softwareTable as $row ) {
$categoryTable = $this->conn->query("select * from ".$row["tableName"]." order by priority");
foreach ( $categoryTable as $row2 ) {
$subCategoryTable = $this->conn->query("select * from ".$row2["tableName"]." order by priority");
if (!strcmp($row2["category"], $subCategory)){
$this->tableName = $row2["tableName"];
$temp = true;
break;
}
$rowCount = $subCategoryTable->rowCount() + $rowCount;
}
if ($temp){break;}
}
$rowCount = $pri + $rowCount;
return $rowCount;//This will be the name of the image
//Navigate to Tables
//According to priority set the iconName
//Record the iconName please
//Insert the record in table
//Execute the spritesheet
//make css
//finally iterate the whole database and send a string
}
public function decrementPriorityInTable($pri){
$this->conn->query("use windows");
$softwareTable = $this->conn->query("select * from ".$this->tableName." order by priority");
foreach ( $softwareTable as $row ) {
if($row["priority"] >= $pri+1){
$this->conn->query("update ".$this->tableName." set priority=".($row["priority"]-1)." where priority=".$row["priority"]);
}
}
}
public function getTotalSoftwaresCount(){
$softwareCount = 0;
$softwareTable = $this->conn->query("select * from software order by priority");
foreach ( $softwareTable as $row ) {
$categoryTable = $this->conn->query("select * from ".$row["tableName"]." order by priority");
foreach ( $categoryTable as $row2 ) {
$subCategoryTable = $this->conn->query("select * from ".$row2["tableName"]." order by priority");
foreach ($subCategoryTable as $row3){
$softwareCount++;
}
}
}
$softwareCount++;
return $softwareCount;
}
}
?>
The line $spriteSheetObject = new spriteSheet(18, 18, 5, "../ICONS/", "../"); stops executions without any error.
The spriteSheet class comes from this library:
<?php
require("lib/WideImage.php");
//All the images size must first be set to be placed on canvas
//Depends on only 1-Image "canvasArea.jpg"
//image processing folder is by default a "imagesToBeProcessed"
//output folder is empty by default
class spriteSheet{
private $canvasWidth;
private $canvasHeight;
private $eachImageWidth;
private $eachImageHeight;
private $imagesFolder = "";
private $outputFolder = "";
private $imageCount = 0;
private $maxImageInARow;
function __construct($imgW=43,$imgH=43, $maxInRow=5, $src, $des){
$this->imagesFolder = $src;
$this->outputFolder = $des;
$this->imageCounter();
$this->eachImageWidth = $imgW;
$this->eachImageHeight = $imgH;
$this->canvasWidth = $imgW * $maxInRow;
$this->canvasHeight = $imgH * ceil($this->imageCount/$maxInRow);
$this->maxImageInARow = $maxInRow;
}
public function setImagesFolder($src){
$this->imagesFolder = $src;
}
public function setOutPutFolder($des){
$this->outputFolder = $des;
}
public function imageCounter( ){
for ($x=1; true; $x++){
if (!file_exists($this->imagesFolder.$x.".jpg") and !file_exists($this->imagesFolder.$x.".png") and !file_exists($this->imagesFolder.$x.".gif")){
$this->imageCount = $x;
break;
}
}
$this->imageCount--;
}
public function setCanvasSize( ){
$canvas = WideImage::load($this->imagesFolder."canvasArea.jpg")->resize($this->canvasWidth, $this->canvasHeight, "fill");
$canvas->saveToFile($this->imagesFolder."tempArea.jpg");
}
public function resizeAllIcons( ){
$loopEnable = true;
for ($x=1; $loopEnable == true; $x++){
if (file_exists($this->imagesFolder.$x.".jpg")){
$iconImage = WideImage::load($this->imagesFolder.$x.".jpg")->resize($this->eachImageWidth, $this->eachImageHeight, "fill");
$iconImage->saveToFile($this->imagesFolder.$x.".jpg");
}
else if (file_exists($this->imagesFolder.$x.".png")){
$iconImage = WideImage::load($this->imagesFolder.$x.".png")->resize($this->eachImageWidth, $this->eachImageHeight, "fill");
$iconImage->saveToFile($this->imagesFolder.$x.".png");
}
else if (file_exists($this->imagesFolder.$x.".gif")){
$iconImage = WideImage::load($this->imagesFolder.$x.".gif")->resize($this->eachImageWidth, $this->eachImageHeight, "fill");
$iconImage->saveToFile($this->imagesFolder.$x.".gif");
}
else{
$loopEnable = false;
}
}
}
public function processSpriteSheet( ){
$this->resizeAllIcons();
$this->setCanvasSize();
$row=0; $col=0; $tempImageCounter = 1;
while ($tempImageCounter<=$this->imageCount){
$icon;
if (file_exists($this->imagesFolder.$tempImageCounter.".jpg")){
$icon = WideImage::load($this->imagesFolder.$tempImageCounter.'.jpg');
}
else if (file_exists($this->imagesFolder.$tempImageCounter.".png")){
$icon = WideImage::load($this->imagesFolder.$tempImageCounter.'.png');
}
else if (file_exists($this->imagesFolder.$tempImageCounter.".gif")){
$icon = WideImage::load($this->imagesFolder.$tempImageCounter.'.gif');
}
else{
break;
}
$canvas = WideImage::load($this->imagesFolder."tempArea.jpg");
$canvas->merge($icon, $row*$this->eachImageWidth, $col*$this->eachImageHeight, 100)->saveToFile($this->imagesFolder."tempArea.jpg");
$tempImageCounter++;
$row++;
if ($row == $this->maxImageInARow){
$row=0;
$col++;
}
}
}
public function processSpriteSheetCss($maxImageCss){
echo "maxImage:".$maxImageCss;
$imgCommon = "img.common{
width: ".$this->eachImageWidth."px;
height: ".$this->eachImageHeight."px;
background-image:url(home.jpg);
}";
$imgS=""; $y=0; $tempImageCounter = 1;
for($x=0; $tempImageCounter<=$maxImageCss; $x++){
$imgS = $imgS."img.s".$tempImageCounter."{background-position:".-1*($x*$this->eachImageWidth)."px ".-1*($y*$this->eachImageHeight)."px;}";
if ($tempImageCounter%$this->maxImageInARow == 0){
$x = -1;
$y++;
}
$tempImageCounter++;
}
echo "SpriteSheetCSS".$imgS;
$handle = fopen( "../css/sprite.css", "w" );
fwrite($handle, $imgS);
}
public function getImageCount(){
echo "total number of images-->".$this->imageCount;
return $this->imageCount;
}
}
?>
My script stops execution at that line without any error.
This file works perfectly on localhost but when I put this online and execute it then this problem happens.
I have installed Mosquitto on the server, and it's running, and working fine.
I have installed Paho mqtt client plugin to check.
and I wrote the code for android and it's working fine on the emulator.
now in my own computer everything works fine, I run the php code and my app in android receives the message and Paho client receives that message too.
but when I upload the file on the server and run it nothing happens, although the php code runs everything successfully, and publishes the message without any error.
and even the mosquitto's publisher executable works fine and clients receive the message.
only this php code on the server doesn't do anything.
$mqtt = new phpMQTT("localhost", 1883, "server");
if ($mqtt->connect()) {
echo"connected\n";
for($i=0;$i<4;++$i){
if($mqtt->publish("new","Hey . ".$i,2)){
echo "published\n";
}
else{
echo "not published\n";
}
}
$mqtt->close();
}
else{
echo"couldn't connect\n";
}
Bluerhinos phpMQTT:
<?php
/* phpMQTT */
class phpMQTT {
private $socket; /* holds the socket */
private $msgid = 1; /* counter for message id */
public $keepalive = 10; /* default keepalive timmer */
public $timesinceping; /* host unix time, used to detect disconects */
public $topics = array(); /* used to store currently subscribed topics */
public $debug = true; /* should output debug messages */
public $address; /* broker address */
public $port; /* broker port */
public $clientid; /* client id sent to brocker */
public $will; /* stores the will of the client */
private $username; /* stores username */
private $password; /* stores password */
function __construct($address, $port, $clientid){
$this->broker($address, $port, $clientid);
}
/* sets the broker details */
function broker($address, $port, $clientid){
$this->address = $address;
$this->port = $port;
$this->clientid = $clientid;
}
/* connects to the broker
inputs: $clean: should the client send a clean session flag */
function connect($clean = true, $will = NULL, $username = NULL, $password = NULL){
if($will) $this->will = $will;
if($username) $this->username = $username;
if($password) $this->password = $password;
$address = $this->address;
$this->socket = fsockopen($address, $this->port, $errno, $errstr, 60);
if (!$this->socket ) {
error_log("fsockopen() $errno, $errstr \n");
return false;
}
stream_set_timeout($this->socket, 5);
stream_set_blocking($this->socket, 0);
$i = 0;
$buffer = "";
$buffer .= chr(0x00); $i++;
$buffer .= chr(0x06); $i++;
$buffer .= chr(0x4d); $i++;
$buffer .= chr(0x51); $i++;
$buffer .= chr(0x49); $i++;
$buffer .= chr(0x73); $i++;
$buffer .= chr(0x64); $i++;
$buffer .= chr(0x70); $i++;
$buffer .= chr(0x03); $i++;
//No Will
$var = 0;
if($clean) $var+=2;
//Add will info to header
if($this->will != NULL){
$var += 4; // Set will flag
$var += ($this->will['qos'] << 3); //Set will qos
if($this->will['retain']) $var += 32; //Set will retain
}
if($this->username != NULL) $var += 128; //Add username to header
if($this->password != NULL) $var += 64; //Add password to header
$buffer .= chr($var); $i++;
//Keep alive
$buffer .= chr($this->keepalive >> 8); $i++;
$buffer .= chr($this->keepalive & 0xff); $i++;
$buffer .= $this->strwritestring($this->clientid,$i);
//Adding will to payload
if($this->will != NULL){
$buffer .= $this->strwritestring($this->will['topic'],$i);
$buffer .= $this->strwritestring($this->will['content'],$i);
}
if($this->username) $buffer .= $this->strwritestring($this->username,$i);
if($this->password) $buffer .= $this->strwritestring($this->password,$i);
$head = " ";
$head{0} = chr(0x10);
$head{1} = chr($i);
fwrite($this->socket, $head, 2);
fwrite($this->socket, $buffer);
$string = $this->read(4);
if(ord($string{0})>>4 == 2 && $string{3} == chr(0)){
if($this->debug) echo "Connected to Broker\n";
}else{
error_log(sprintf("Connection failed! (Error: 0x%02x 0x%02x)\n",
ord($string{0}),ord($string{3})));
return false;
}
$this->timesinceping = time();
return true;
}
/* read: reads in so many bytes */
function read($int = 8192, $nb = false){
// print_r(socket_get_status($this->socket));
$string="";
$togo = $int;
if($nb){
return fread($this->socket, $togo);
}
while (!feof($this->socket) && $togo>0) {
$fread = fread($this->socket, $togo);
$string .= $fread;
$togo = $int - strlen($string);
}
return $string;
}
/* subscribe: subscribes to topics */
function subscribe($topics, $qos = 0){
$i = 0;
$buffer = "";
$id = $this->msgid;
$buffer .= chr($id >> 8); $i++;
$buffer .= chr($id % 256); $i++;
foreach($topics as $key => $topic){
$buffer .= $this->strwritestring($key,$i);
$buffer .= chr($topic["qos"]); $i++;
$this->topics[$key] = $topic;
}
$cmd = 0x80;
//$qos
$cmd += ($qos << 1);
$head = chr($cmd);
$head .= chr($i);
fwrite($this->socket, $head, 2);
fwrite($this->socket, $buffer, $i);
$string = $this->read(2);
$bytes = ord(substr($string,1,1));
$string = $this->read($bytes);
}
/* ping: sends a keep alive ping */
function ping(){
$head = " ";
$head = chr(0xc0);
$head .= chr(0x00);
fwrite($this->socket, $head, 2);
if($this->debug) echo "ping sent\n";
}
/* disconnect: sends a proper disconect cmd */
function disconnect(){
$head = " ";
$head{0} = chr(0xe0);
$head{1} = chr(0x00);
fwrite($this->socket, $head, 2);
}
/* close: sends a proper disconect, then closes the socket */
function close(){
$this->disconnect();
fclose($this->socket);
}
/* publish: publishes $content on a $topic */
function publish($topic, $content, $qos = 0, $retain = 0){
$i = 0;
$buffer = "";
$buffer .= $this->strwritestring($topic,$i);
//$buffer .= $this->strwritestring($content,$i);
if($qos){
$id = $this->msgid++;
$buffer .= chr($id >> 8); $i++;
$buffer .= chr($id % 256); $i++;
}
$buffer .= $content;
$i+=strlen($content);
$head = " ";
$cmd = 0x30;
if($qos) $cmd += $qos << 1;
if($retain) $cmd += 1;
$head{0} = chr($cmd);
$head .= $this->setmsglength($i);
if((fwrite($this->socket, $head, strlen($head)))&&(fwrite($this->socket, $buffer, $i))){
echo "done: ".$this->socket."<br>";
return true;
}
else {
echo $head;
return false;
}
}
/* message: processes a recieved topic */
function message($msg){
$tlen = (ord($msg{0})<<8) + ord($msg{1});
$topic = substr($msg,2,$tlen);
$msg = substr($msg,($tlen+2));
$found = 0;
foreach($this->topics as $key=>$top){
if( preg_match("/^".str_replace("#",".*",
str_replace("+","[^\/]*",
str_replace("/","\/",
str_replace("$",'\$',
$key))))."$/",$topic) ){
if(function_exists($top['function'])){
call_user_func($top['function'],$topic,$msg);
$found = 1;
}
}
}
if($this->debug && !$found) echo "msg recieved but no match in subscriptions\n";
}
/* proc: the processing loop for an "allways on" client
set true when you are doing other stuff in the loop good for watching something else at the same time */
function proc( $loop = true){
if(1){
$sockets = array($this->socket);
$w = $e = NULL;
$cmd = 0;
//$byte = fgetc($this->socket);
if(feof($this->socket)){
if($this->debug) echo "eof receive going to reconnect for good measure\n";
fclose($this->socket);
$this->connect(false);
if(count($this->topics))
$this->subscribe($this->topics);
}
$byte = $this->read(1, true);
if(!strlen($byte)){
if($loop){
usleep(100000);
}
}else{
$cmd = (int)(ord($byte)/16);
if($this->debug) echo "Recevid: $cmd\n";
$multiplier = 1;
$value = 0;
do{
$digit = ord($this->read(1));
$value += ($digit & 127) * $multiplier;
$multiplier *= 128;
}while (($digit & 128) != 0);
if($this->debug) echo "Fetching: $value\n";
if($value)
$string = $this->read($value,"fetch");
if($cmd){
switch($cmd){
case 3:
$this->message($string);
break;
}
$this->timesinceping = time();
}
}
if($this->timesinceping < (time() - $this->keepalive )){
if($this->debug) echo "not found something so ping\n";
$this->ping();
}
if($this->timesinceping<(time()-($this->keepalive*2))){
if($this->debug) echo "not seen a package in a while, disconnecting\n";
fclose($this->socket);
$this->connect(false);
if(count($this->topics))
$this->subscribe($this->topics);
}
}
return 1;
}
/* getmsglength: */
function getmsglength(&$msg, &$i){
$multiplier = 1;
$value = 0 ;
do{
$digit = ord($msg{$i});
$value += ($digit & 127) * $multiplier;
$multiplier *= 128;
$i++;
}while (($digit & 128) != 0);
return $value;
}
/* setmsglength: */
function setmsglength($len){
$string = "";
do{
$digit = $len % 128;
$len = $len >> 7;
// if there are more digits to encode, set the top bit of this digit
if ( $len > 0 )
$digit = ($digit | 0x80);
$string .= chr($digit);
}while ( $len > 0 );
return $string;
}
/* strwritestring: writes a string to a buffer */
function strwritestring($str, &$i){
$ret = " ";
$len = strlen($str);
$msb = $len >> 8;
$lsb = $len % 256;
$ret = chr($msb);
$ret .= chr($lsb);
$ret .= $str;
$i += ($len+2);
return $ret;
}
function printstr($string){
$strlen = strlen($string);
for($j=0;$j<$strlen;$j++){
$num = ord($string{$j});
if($num > 31)
$chr = $string{$j}; else $chr = " ";
printf("%4d: %08b : 0x%02x : %s \n",$j,$num,$num,$chr);
}
}
}
?>
Follow this library publish example and see what happens both logs: the localhost broker and the php log
https://github.com/bluerhinos/phpMQTT/blob/master/examples/publish.php
I have small matrix of +-100 points/values, results of test and their distances (0-10, 10 is the closest) to each other: http://vis.arcs.cz.
I would like to visualize it in 2D to quickly find a groups of close values. So I need to process this matrix and get the coordinates of points in 2D.
The way is propably multidimensional scaling but I wasnt able to find an algorithm, library or extension nor use the math formulas into PHP code.
Im googling last two days and the closest results of it is
http://www.php.net/manual/en/lapack.leastsquaresbysvd.php - ?
(cant share more links as novice)
I'll be grateful for any solution applicable in php project (compiled MathLab code in C++...).
index.php:
<?php
require("data.php");
require("Mds.php");
$mds = new Mds();
$mds->prepareData($data);
//cislo udava pocet iteraci algoritmu,
//idealne by melo mit hodnotu pocetUzlu na druhou, prakticky muze byt o dost mensi, 5 az 10 krat pocet uzlu.
$mds->scale(100);
//mira splneni podminek - vraci cislo < mensi nez 1. Cim blizsi k 1, tim lepe vyhovuji vzdalenosti
//z vypocteneho rozlozeni zadanym vzdalenostem.
//v nemetrickych datech ovsem dochazi rychle k poklesu az do zapornych hodnot, protoze ve 2D neexistuje
//pro nektere body zadne spravne misto.
echo $mds->getRSquared();
?>
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "MDS",
fontFamily: "arial black",
fontColor: "black"
},
axisX: {
title:"",
titleFontFamily: "arial"
},
axisY:{
title: "",
titleFontFamily: "arial",
titleFontSize: 12
},
data: [
{
type: "scatter",
toolTipContent: "<span style='"'color: {color};'"'><strong>{name}</strong></span> x: {y}, y: {y}",
dataPoints:
<?php
echo $mds->printCoords('{x: %X, y: %Y, name: "%LABEL"}');
?>
}]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 600px; width: 600px;">
</div>
mds.zip
</body>
</html>
data.php:
$data = array(
array ("Jablko", "Voda", 2),
array("Jablko", "Ohen", 7),
array("Jablko", "Cervena", 3),
array("Jablko", "Zelena", 2),
array("Voda", "Ohen", 8),
array("Voda", "Cervena", 8),
array("Voda", "Zelena", 2),
array("Ohen", "Cervena", 1),
array("Ohen", "Zelena", 5),
array("Cervena", "Zelena", 3)
);
Mds.php:
<?php
class Mds {
//node - pole tvaru [[x, y, label], ...]
public $nodes = array();
//tvaru [source][target]=distance
public $givenDistances = array();
public $currentDistances = array();
public function prepareData($data) {
$nodesMap = array();
$xxxx = 10000;
$xxx= 1000;
// $xxxx = 5000;
// $xxx = 600;
foreach($data as $link) {
$source = $link[0];
$target = $link[1];
if(!isset($nodesMap[$source])) {
$nodesMap[$source] = true;
$this->nodes[]=array((float) rand(1,$xxxx) / $xxx, (float) rand(1,$xxxx) / $xxx, $source);
}
if(!isset($nodesMap[$target])) {
$nodesMap[$target] = true;
$this->nodes[]= array((float) rand(1,$xxxx) / $xxx, (float) rand(1,$xxxx) / $xxx, $target);
}
}
//vytvori matici pro ulozeni vzdalenosti
foreach($this->nodes as $node) {
$this->givenDistances[$node[2]] = array();
$this->currentDistances[$node[2]] = array();
}
foreach($data as $link) {
$source = $link[0];
$target = $link[1];
$distance = $link[2];
$this->givenDistances[$source][$target] = $distance;
$this->givenDistances[$target][$source] = $distance;
}
}
protected function countCurrentDistances() {
$mean = 0;
$i = 0;
foreach($this->nodes as $nodeA) {
foreach($this->nodes as $nodeB) {
$dist = sqrt(($nodeB[0]-$nodeA[0])*($nodeB[0]-$nodeA[0]) + ($nodeB[1]-$nodeA[1])*($nodeB[1]-$nodeA[1]));
$this->currentDistances[$nodeA[2]][$nodeB[2]] = $dist;
if($nodeA[2]!==$nodeB[2]) {
$mean += $this->givenDistances[$nodeA[2]][$nodeB[2]];
}
}
}
// echo "<pre>";
// var_dump($this->currentDistances);
// echo "</pre>";
$check = array();
$nodesCount = count($this->nodes);
$this->mean = $mean/($nodesCount*$nodesCount);
}
public function getRSquared() {
$this->countCurrentDistances();
$sum = 0;
$SStot = 0;
$SSres = 0;
foreach($this->nodes as $nodeA) {
foreach($this->nodes as $nodeB) {
$aLab = $nodeA[2];
$bLab = $nodeB[2];
if($aLab===$bLab) {
continue;
}
$given = $this->givenDistances[$aLab][$bLab];
$computed = $this->currentDistances[$aLab][$bLab];
$SSres+=(($given-$computed)*($given-$computed));
$SStot+= ($given-$this->mean)*($given-$this->mean);
}
}
return 1 - ($SSres/$SStot);
}
protected function iterate($inverseCoefStrenth=1) {
for($i=0; $i<count($this->nodes); $i++) {
$nodeA = $this->nodes[$i];
$move = array(0,0);
$moves = 0;
for($j=0; $j<count($this->nodes); $j++) {
if($j===$i) {
continue;
}
$nodeB = $this->nodes[$j];
$dist = $this->givenDistances[$nodeA[2]][$nodeB[2]];
$AB = array($nodeB[0]-$nodeA[0], $nodeB[1]-$nodeA[1]);
$lAB = sqrt(($AB[0]*$AB[0])+($AB[1]*$AB[1]));
$coef = ($lAB - $dist)/$lAB;
$AA1 = array($AB[0]*$coef, $AB[1]*$coef);
$moves++;
$move[0]+=$AA1[0];
$move[1]+=$AA1[1];
}
if($moves>0) {
$resultingMoveX = $move[0]/($moves*$inverseCoefStrenth);
$resultingMoveY = $move[1]/($moves*$inverseCoefStrenth);
$this->nodes[$i][0]+=$resultingMoveX;
$this->nodes[$i][1]+=$resultingMoveY;
}
}
}
public function scale($iterations, $coefIncrease=0) {
$basicCoef=1;
for($i=0; $i<$iterations; $i++) {
$this->iterate($basicCoef);
//echo $this->getRSquared();
//echo " | ";
$basicCoef+=$coefIncrease;
}
}
public function coordsAsString() {
$coords = array();
foreach($this->nodes as $node) {
$coords[]="[{$node[0]}, {$node[1]}]";
}
$res = join(", ",$coords);
return "[$res]";
}
public function printCoords($pattern='[%X,%Y,"%LABEL"]') {
$coords = array();
foreach($this->nodes as $node) {
$x = $node[0];
$y = $node[1];
$label = $node[2];
$res = str_replace('%X', $x, $pattern);
$res = str_replace('%Y', $y, $res);
$res = str_replace('%LABEL', $label, $res);
$coords[]=$res;
}
$res = join(", ",$coords);
return "[$res]";
}
public function pointsCoords() {
$coords = array();
foreach($this->nodes as $node) {
$res['x'] = round($node[0]*100);
$res['y'] = round($node[1]*100);
$res['label'] = $node[2];
$coords[] = $res;
}
return $coords;
}
}