add

Saturday, May 4, 2013

2013 may 05 : starting to learn php

8:00 PM => I started learning php from a tutorial of netbeans.link of the tutorial is https://netbeans.org/kb/docs/php/wish-list-lesson2.html.
here i learnt the following
  1. downloaded netbean
  2. downloaded jdk and installed
  3. downloaded wamp and installed
 9:00 PM => started database connectivity through mysql jdbc in netbeans .
  1. created table of wishers
  2. created table of wishes
  3. inserted data in tables
  4. created simple form and posted its value on next page
 ERROR : I had the following errors

CREATE TABLE wishes2(
 id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
 wisher_id INT NOT NULL,
 description CHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
 due_date DATE,
 FOREIGN KEY (wisher_id) REFERENCES wishers2(id)
)
  1. Error code 1005, SQL state HY000: Can't create table 'saqi.wishes2' (errno: 150)
    Line 1, column 1
  • Solution : error was becuase i did not create the parent table for which i was creating a foreign  key and wishers2 table
10:00 PM

Tuesday, March 26, 2013

cell padding and cell spacing in HTML

We can beutify our page by simple cellspacing and cell padding.
just have a look at code and output at the bottom.
<html>
<head>
<title>cell Padding</title>
<style>
div.pageoverflow {
clear: left;
padding-top: 1px;
width: 350px;
overflow: hidden;

}

div.pagecontainer {
background-color: #ececec;
margin: 10px;
padding: 5px;
border: solid 1px #666;
}
p.pagetext {
color: #384654;
float: left;
padding-top: 5px;
padding-right: 5px;
width: 30em;
margin-bottom: 0.5em;
font:Arial, Helvetica, sans-serif;
font-size:12px;
}

</style>
</head>
<body>
<table width="100%" style="background-color: #FFFFFF;">
<tbody><tr>
<td>
<table width="100%" cellspacing="2" cellpadding="7">
<tbody><tr style="background-color:#ECECEC"><td><strong>Date</strong></td><td><strong>Count</strong></td></tr>
<tr style="background-color:#ECECEC"><td>2013-03-20</td><td>2113812</td></tr><tr style="background-color:#ECECEC"><td>2013-03-25</td><td>1042</td></tr>

</tbody></table>
</td>
</tr>
</tbody></table>
</body></html>




cell Padding




DateCount
2013-03-202113812
2013-03-251042

Wednesday, December 12, 2012

Simple Jquery Ajax and getjson call

get some Json Data through a remote API
$(document).ready(function(){
$.ajax({
type: "GET",
url: 'http://ecarobar.com/xyz/api.php',
data: { method: "get", name: "jab", format: "json" },
async: false,
dataType: "json",
beforeSend: function(x) {alert('Not Yet Sent')},
success: function(data){
alert ("AjAx Call"+data.responseBody.id+" "+data.responseBody.views); //further debug
$('#showdata').html("<p>item1="+data.responseBody.id+" item2="+data.responseBody.views+" </p>");
}
});

$.getJSON(
"http://ecarobar.com/xyz/api.php",
{method: "get", name: "jab", format: "json" },
function(data) {
//alert("JSON Data: " + json.users[3].name);
alert ("JSON Call"+data.responseBody.id+" "+data.responseBody.views); //further debug
$('#showdata').html("<p>item1="+data.responseBody.id+" item2="+data.responseBody.views+" </p>");
});
});

Tuesday, November 27, 2012

Compare two files using linux comm command

Comm Command: (to use this command file must b first sorted like cat file|sort > file1)
for Common : comm -1 -2 file1 file2
Ignore
-1 Ignore File1
-2 Ignore File1
-3 Ignore common data
Example:
File1
1
2
3
4
5

File2
3
4
5
6
7


comm -1 -2 file1 file2 => 3,4,5


comm -1 -3 file1 file2 => 6,7

Friday, November 2, 2012

pregmatch for shell script


*     matches any string of zero or more characters
?     matches any single character
[ ]   matches any single character within the set
[! ]  matches any single character not in the set


These can be combined together to form more advanced patterns:
[Yy]* Matches any string starting with an upper or lower case y.

Use quotes or escape/back-slash the special characters if you wish to pattern match them specifically.

Monday, October 22, 2012

memcached using php and perl


Memcached is an in-memory key-value store for small chunks of arbitrary data (strings, objects) from results of database calls, API calls, or page rendering.
The system uses a client–server architecture. The servers maintain a key–value associative array; the clients populate this array and query it. Keys are up to 250 bytes long and values can be at most 1 megabyte in size.
Clients use client side libraries to contact the servers which, by default, expose their service at port 11211. Each client knows all servers; the servers do not communicate with each other. If a client wishes to set or read the value corresponding to a certain key, the client's library first computes a hash of the key to determine the server that will be used. Then it contacts that server. The server will compute a second hash of the key to determine where to store or read the corresponding value.
Perl script for fetching a Memcached result.


use Cache::Memcached;
use Digest::MD5;
use Digest::MD5 qw(md5 md5_hex md5_base64);
my $memcli = new Cache::Memcached {
    'servers' => [ "192.168.0.27:11211" ],
    'debug' => 0
};
my $serviceID=$ARGV[0];
print "Service ID__".$serviceID." **_\n";
my $perlKey='perl_'.$serviceID;
my $result = $memcli->get($perlKey);
#print "already : ___".$result."________\n";
if($result eq "")
{
#hit a php page to set memcache values if this key does not exist.
        use LWP::UserAgent;
        #my $serviceID = 12;
        my $url= "http://192.168.0.27/chargerequest/perlcache.php";
        my $ua       = LWP::UserAgent->new();
        my $response = $ua->post( $url, { 'id' => $serviceID } );
        my $content  = $response->decoded_content();
        $result = $memcli->get($perlKey);
}
else {
        print "\n cached result \n ".$result;
}


Now the php page

include("db.php");
$dbOBJ = new DB();
$conn = $dbOBJ->connectDB();
if ($conn){
$serviceid=$_REQUEST['id'];
$qry='select id, abc, def, ghi, jkl, mno, pqr from table where id='.$id; $memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");
$perlKey='perl_'.$serviceid;
$cache_result = array();
//$memcache->set($perlKey, $perlString, 0, 1);
$cache_result = $memcache->get($perlKey); // Memcached object
if($cache_result)
{
// Second User Request
echo "
caching
";
$dbOBJ->print_rr($cache_result);
$demos_result=$cache_result;
}
else
{
$curser = OCIParse($conn,$qry);
OCIExecute($curser);
OCIFetchInto($curser , $values);
$demos_result[]=$values; // Results storing in array
$memcache->set($key, $demos_result, 0, 100);
$val1=$demos_result[0][0];          
$val2=$demos_result[0][1];
$val3=$demos_result[0][2];        
$val4=$demos_result[0][3];        
$val5=$demos_result[0][4];          
$val6=$demos_result[0][5];
$perlString = $val1.','. $val2.','. $val3.','. $val4.','. $val5.','. $val6;
$memcache->set($perlKey, $perlString, 0, 10);
}
}
else
echo $errorMessage='Other error';
?>




Thursday, October 4, 2012

Fetch files from remote server automatically in PHP using Curl

PHP provides multiple ways to download and upload files to remote servers, such as fopen, fsockopen, cURL library, and other methods. fopen is the simplest but not the best. A while ago I wrote a function to fetch remote file by using fsockopen. However, I found a lot of problems when I use it. Then I read the PHP Cookbook and decided to try cURL library. After I implemented it in the independent class, it works like a charm. The following is the class source code.


// I adopt cURL library to download files
// It is reliable and fast, less hassle than fopen/fsockopen etc.

// this following three lines include testing code
// $file = new Remotefile("http://downloads.pcworld.com/pub/new/patches___drivers/utilities/framxpro.zip");
// $file->save2file("");
class Remotefile
{
 // the url components
 private $url = "";
 // data get back from server
 private $header  = array();
 private $content = "";
 private $extension = "";

 function __construct($url)
 {
  $this->initialize($url);
 }

 private function curl_url()
 {
  $c = curl_init($this->url);
  curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt($c, CURLOPT_HEADER, 1);
  $buffer = curl_exec($c);
  curl_close($c);

  // process data
  $rnrn = "\r\n\r\n";
  $pos = strpos($buffer,$rnrn);

  if($pos === false)
  {
   // string $rnrn NOT found in $buffer
    echo "Something is not correct!
";
  }
  else
  {
   // string $rnrn found in $buffer
   $this->content = substr($buffer, $pos+4);
   $header = substr($buffer, 0, $pos);
   $this->processHeader($header);
  }
 }

 private function initialize($url)
 {
  // initialize all variables
  $this->url = $url;
  // fetch the remote file
  $this->curl_url();
 }

 private function processHeader($header)
 {
  $lines = explode("\r\n", $header);
  $this->header["status"] = $lines[0];
  foreach($lines as $line)
  {
   $data = explode(": ",$line);
   if ($data[1] != "")
   {
    $this->header[$data[0]] = $data[1];
   }
//echo "$data[0] |===| $data[1]
";
  }
 }

 private function redirectedURL()
 {
  return $this->header["Location"];
 }

 private function getMIMEtype()
 {
  // check redirection url
  $rdurl = $this->redirectedURL();
  if ($rdurl)
  {
   $ext = ereg_replace("^.+\\.([^.]+)$", "\\1", $rdurl);
   $this->extension = $ext;
  }
  else
  {
   $mtype = $this->header["Content-Type"];
   $temps1 = split("/",$mtype);
   $temps2 = split(";",$temps1[1]);
   $ext1 = $temps2[0];
   $this->extension = $ext1;
   if (($temps1[0] == "application"))
   {
    $ext2 = ereg_replace("^.+\\.([^.]+)$", "\\1", $this->url);
    if ($ext2)
    {
     $this->extension = $ext2;
    }
   }
       }
       $this->extension = trim($this->extension);
//echo "file extension = ".$this->extension."
";
 }

 function getHeader()
 {
  return $this->header;
 }

 function getContent()
 {
  return $this->content;
 }

 function save2file($folder)
 {
  // write to file
  $this->getMIMEtype();
  $filename = date('YmdHis').".".$this->extension;
  $target_path = getcwd();
  if ($folder)
  {
   $target_path .= "/$folder";
  }
  $target_path .=  "/".$filename;
  $Handle = fopen($target_path, 'w');
  fwrite($Handle, $this->content);
  fclose($Handle);
  return $filename;
 }

}

?>
I adopt cURL library to download files. It is reliable and fast, less hassle than fopen/fsockopen etc. To use the above class, at Ubuntu yot have to install libcurl and php5-curl by the following command:
apt-get install curl libcurl3 libcurl3-dev php5-curl
After this is done, just restart apache2 server by
/etc/init.d/apache2 restart