Pages

Search This Blog

Friday 23 November 2012

HTML to PDF using PHP

Instructions HTML to PDF Using HTML2FPDF


    • 1
      Download the HTML2FPDF Class Library files (see Resources).
    • 2
      Paste the following code in Notepad:
      <?php
      require('html2fpdf.php');
      $pdf=new HTML2FPDF();
      $pdf->AddPage();
      $fp = fopen("yourfile.html","r");
      $strContent = fread($fp, filesize("sample.html"));
      fclose($fp);
      $pdf->WriteHTML($strContent);
      $pdf->Output("yourfile.pdf");
      echo "PDF file is generated successfully!";
      ?>
      Replace "yourfile.html" with the name of the HTML file you wish to convert and "yourfile.pdf" with your desired PDF file name.
    • 3
      Save it as a PHP file.
    • 4
      Upload your PHP file, the HTML2FPDF Class Library files, and the HTML file that you wish to convert in the same directory on your site.
    • 5
      Access the PHP file on your website to convert the HTML file to PDF.

    HTML to PDF Using DOMPDF

    • 6
      Download DOMPDF (see Resources).
    • 7
      Paste the following code in Notepad:
      <?php
      require_once("dompdf_config.inc.php");
      $html =
      '<html><body>'.
      '<p>Put your html here, or generate it with your favourite '.
      'templating system.</p>'.
      '</body></html>';
      $dompdf = new DOMPDF();
      $dompdf->load_html($html);
      $dompdf->render();
      $dompdf->stream("yourhtml.pdf");
      ?>
      In the section that indicates "Put your html here," paste the HTML code that you wish to convert to PDF.
    • 8
      Save it as a PHP file.
    • 9
      Upload your your PHP file and the DOMPDF files you downloaded within in the same directory on your site.
    • 10
      Access the PHP file on your website to convert HTML to PDF.

    Convert HTML to PDF Using PDFonFly

    • 11
      Go to pdfonfly.com.
    • 12
      Click on the "Text/HTML to PDF" link.
    • 13
      Click on "Source" in the text editing tool and paste your HTML.
    • 14
      Click on the "Create PDF" button.

Thursday 1 November 2012

Google Maps

<!--
Google Maps
Author: Zuh@ir Mirza
 -->
<html>
<head>
<script
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySYM&sensor=false">
</script>

<script>
var myCenter=new google.maps.LatLng(51.508742,-0.120850);

function initialize()
{
var mapProp = {
  center:myCenter,
  zoom:5,
  mapTypeId:google.maps.MapTypeId.ROADMAP
  };

var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);

var marker=new google.maps.Marker({
  position:myCenter,
  });

marker.setMap(map);
}

google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>

<body>
<div id="googleMap" style="width:600px;height:380px;"></div>
</body>
</html>

Saturday 20 October 2012

Find total number of code lines


<?php
 error_reporting(0);
/**
* Counts the lines of code in this folder and all sub folders
* You may not sell this script or remove these header comments
* @author Hamid Alipour, http://blog.code-head.com/
**/

define('SHOW_DETAILS', true);

class Folder {

var $name;
var $path;
var $folders;
var $files;
var $exclude_extensions;
var $exclude_files;
var $exclude_folders;


function Folder($path) {
$this -> path = $path;
$this -> name = array_pop( array_filter( explode(DIRECTORY_SEPARATOR, $path) ) );
$this -> folders = array();
$this -> files = array();
$this -> exclude_extensions = array('gif', 'jpg', 'jpeg', 'png', 'tft', 'bmp', 'rest-of-the-file-extensions-to-exclude');
$this -> exclude_files    = array('count_lines.php', 'rest-of-the-files-to-exclude');
$this -> exclude_folders = array('_private', '_vti_bin', '_vti_cnf', '_vti_log', '_vti_pvt', '_vti_txt', 'rest-of-the-folders-to-exclude');
}

function count_lines() {
if( defined('SHOW_DETAILS') ) echo "/Folder: {$this -> path}...\n";
$total_lines = 0;
$this -> get_contents();
foreach($this -> files as $file) {
if( in_array($file -> ext, $this -> exclude_extensions) || in_array($file -> name, $this -> exclude_files) ) {
if( defined('SHOW_DETAILS') ) echo "#---Skipping File: {$file -> name};\n";
continue;
}
$total_lines += $file -> get_num_lines();
}
foreach($this -> folders as $folder) {
if( in_array($folder -> name, $this -> exclude_folders) ) {
if( defined('SHOW_DETAILS') ) echo "#Skipping Folder: {$folder -> name};\n";
continue;
}
$total_lines += $folder -> count_lines();
}
if( defined('SHOW_DETAILS') ) echo "\n Total lines in {$this -> name}: $total_lines;\n\n";
return $total_lines;
}

function get_contents() {
$contents = $this -> _get_contents();
foreach($contents as $key => $value) {
if( $value['type'] == 'Folder' ) {
$this -> folders[] = new Folder($value['item']);
} else {
$this -> files[]   = new File  ($value['item']);
}
}
}

function _get_contents() {
$folder = $this -> path;
if( !is_dir($folder) ) {
return array();
}
$return_array = array();
$count  = 0;
if( $dh = opendir($folder) ) {
while( ($file = readdir($dh)) !== false ) {
if( $file == '.' || $file == '..' ) continue;
$return_array[$count]['item'] = $folder .$file .(is_dir($folder .$file) ? DIRECTORY_SEPARATOR : '');
$return_array[$count]['type'] = is_dir($folder .$file) ? 'Folder' : 'File';
$count++;
}
closedir($dh);
}
return $return_array;
}

} // Class

class File {

var $name;
var $path;
var $ext;


function File($path) {
$this -> path = $path;
$this -> name = basename($path);
$this -> ext  = array_pop( explode('.', $this -> name) );
}

function get_num_lines() {
$count_lines = count(file($this -> path));
if( defined('SHOW_DETAILS') ) echo "|---File: {$this -> name}, lines: $count_lines;\n";
return $count_lines;
}

} // Class

$path_to_here = dirname(__FILE__) .DIRECTORY_SEPARATOR;
       
    $test= dirname($path_to_here);        
    $path_folder =  $test.'/linecount/Apps'.DIRECTORY_SEPARATOR;
$folder  = new Folder($path_folder);
echo 'Total lines of code: ' .$folder -> count_lines() ."\n\n";

?>

How we delete folder and all files in PHP


<?php
/**
*
* @author Zuh@ir Mirza <zuhair_mirza@yahoo.com>
* @param string $dirname Directory to delete
* @return bool Returns TRUE on success, FALSE on failure
*/
function smartDelete($dirname)
{
// Sanity check
if (!file_exists($dirname)) {
return false;
}

// Simple delete for a file
if (is_file($dirname)) {
return unlink($dirname);
}

// Loop through the folder
$dir = dir($dirname);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == '.' || $entry == '..') {
continue;
}
// Recurse
smartDelete($dirname.DIRECTORY_SEPARATOR.$entry);
}

// Clean up
$dir->close();
return rmdir($dirname);
}

$dir_path = 'F:\xampp\htdocs\dev\test\ip_com\delete';
echo smartDelete($dir_path);

?>

Friday 12 October 2012

Directory Listing Script in PHP

<?php
/*
Directory Listing Script - Version 3
====================================
Author: Zuh@ir Mirza <zuhair_mirza@yahoo.com>

REQUIREMENTS
============
This script requires PHP and GD2 if you wish to use the
thumbnail functionality.

INSTRUCTIONS
============
1) Unzip all files
2) Edit this file, making sure everything is setup as required.
3) Upload to server

CONFIGURATION
=============
Edit the variables in this section to make the script work as
you require.

Include URL - If you are including this script in another file,
please define the URL to the Directory Listing script (relative
from the host)
*/
$includeurl = '';

/*
Start Directory - To list the files contained within the current
directory enter '.', otherwise enter the path to the directory
you wish to list. The path must be relative to the current
directory and cannot be above the location of index.php within the
directory structure.
*/
$startdir = '/dlf';

/*
Show Thumbnails? - Set to true if you wish to use the
scripts auto-thumbnail generation capabilities.
This requires that GD2 is installed.
*/
$showthumbnails = true;

/*
Memory Limit - The image processor that creates the thumbnails
may require more memory than defined in your PHP.INI file for
larger images. If a file is too large, the image processor will
fail and not generate thumbs. If you require more memory,
define the amount (in megabytes) below
*/
$memorylimit = false; // Integer

/*
Show Directories - Do you want to make subdirectories available?
If not set this to false
*/
$showdirs = true;

/*
Force downloads - Do you want to force people to download the files
rather than viewing them in their browser?
*/
$forcedownloads = false;

/*
Hide Files - If you wish to hide certain files or directories
then enter their details here. The values entered are matched
against the file/directory names. If any part of the name
matches what is entered below then it is not shown.
*/
$hide = array(
'dlf',
'index.php',
'Thumbs',
'.htaccess',
'.htpasswd'
);

/* Only Display Files With Extension... - if you only wish the user
to be able to view files with certain extensions, add those extensions
to the following array. If the array is commented out, all file
types will be displayed.
*/
/*$showtypes = array(
'jpg',
'png',
'gif',
'zip',
'txt'
);*/

/*
Show index files - if an index file is found in a directory
to you want to display that rather than the listing output
from this script?
*/
$displayindex = false;

/*
Allow uploads? - If enabled users will be able to upload
files to any viewable directory. You should really only enable
this if the area this script is in is already password protected.
*/
$allowuploads = false;

/* Upload Types - If you are allowing uploads but only want
users to be able to upload file with specific extensions,
you can specify these extensions below. All other file
types will be rejected. Comment out this array to allow
all file types to be uploaded.
*/
/*$uploadtypes = array(
'zip',
'gif',
'doc',
'png'
);*/

/*
Overwrite files - If a user uploads a file with the same
name as an existing file do you want the existing file
to be overwritten?
*/
$overwrite = false;

/*
Index files - The follow array contains all the index files
that will be used if $displayindex (above) is set to true.
Feel free to add, delete or alter these
*/

$indexfiles = array (
'index.html',
'index.htm',
'default.htm',
'default.html'
);

/*
File Icons - If you want to add your own special file icons use
this section below. Each entry relates to the extension of the
given file, in the form <extension> => <filename>.
These files must be located within the dlf directory.
*/
$filetypes = array (
'png' => 'jpg.gif',
'jpeg' => 'jpg.gif',
'bmp' => 'jpg.gif',
'jpg' => 'jpg.gif',
'gif' => 'gif.gif',
'zip' => 'archive.png',
'rar' => 'archive.png',
'exe' => 'exe.gif',
'setup' => 'setup.gif',
'txt' => 'text.png',
'htm' => 'html.gif',
'html' => 'html.gif',
'fla' => 'fla.gif',
'swf' => 'swf.gif',
'xls' => 'xls.gif',
'doc' => 'doc.gif',
'sig' => 'sig.gif',
'fh10' => 'fh10.gif',
'pdf' => 'pdf.gif',
'psd' => 'psd.gif',
'rm' => 'real.gif',
'mpg' => 'video.gif',
'mpeg' => 'video.gif',
'mov' => 'video2.gif',
'avi' => 'video.gif',
'eps' => 'eps.gif',
'gz' => 'archive.png',
'asc' => 'sig.gif',
);

/*
That's it! You are now ready to upload this script to the server.

Only edit what is below this line if you are sure that you know what you
are doing!
*/

if($includeurl)
{
$includeurl = preg_replace("/^\//", "${1}", $includeurl);
if(substr($includeurl, strrpos($includeurl, '/')) != '/') $includeurl.='/';
}

error_reporting(1);
if(!function_exists('imagecreatetruecolor')) $showthumbnails = false;
if($startdir) $startdir = preg_replace("/^\//", "${1}", $startdir);
$leadon = $startdir;
if($leadon=='.') $leadon = '';
if((substr($leadon, -1, 1)!='/') && $leadon!='') $leadon = $leadon . '/';
$startdir = $leadon;

if($_GET['dir']) {
//check this is okay.

if(substr($_GET['dir'], -1, 1)!='/') {
$_GET['dir'] = strip_tags($_GET['dir']) . '/';
}

$dirok = true;
$dirnames = split('/', strip_tags($_GET['dir']));
for($di=0; $di<sizeof($dirnames); $di++) {

if($di<(sizeof($dirnames)-2)) {
$dotdotdir = $dotdotdir . $dirnames[$di] . '/';
}

if($dirnames[$di] == '..') {
$dirok = false;
}
}

if(substr($_GET['dir'], 0, 1)=='/') {
$dirok = false;
}

if($dirok) {
$leadon = $leadon . strip_tags($_GET['dir']);
}
}

if($_GET['download'] && $forcedownloads) {
$file = str_replace('/', '', $_GET['download']);
$file = str_replace('..', '', $file);

if(file_exists($includeurl . $leadon . $file)) {
header("Content-type: application/x-download");
header("Content-Length: ".filesize($includeurl . $leadon . $file));
header('Content-Disposition: attachment; filename="'.$file.'"');
readfile($includeurl . $leadon . $file);
die();
}
die();
}

if($allowuploads && $_FILES['file']) {
$upload = true;
if(!$overwrite) {
if(file_exists($leadon.$_FILES['file']['name'])) {
$upload = false;
}
}

if($uploadtypes)
{
if(!in_array(substr($_FILES['file']['name'], strpos($_FILES['file']['name'], '.')+1, strlen($_FILES['file']['name'])), $uploadtypes))
{
$upload = false;
$uploaderror = "<strong>ERROR: </strong> You may only upload files of type ";
$i = 1;
foreach($uploadtypes as $k => $v)
{
if($i == sizeof($uploadtypes) && sizeof($uploadtypes) != 1) $uploaderror.= ' and ';
else if($i != 1) $uploaderror.= ', ';

$uploaderror.= '.'.strtoupper($v);

$i++;
}
}
}

if($upload) {
move_uploaded_file($_FILES['file']['tmp_name'], $includeurl.$leadon . $_FILES['file']['name']);
}
}

$opendir = $includeurl.$leadon;
if(!$leadon) $opendir = '.';
if(!file_exists($opendir)) {
$opendir = '.';
$leadon = $startdir;
}

clearstatcache();
if ($handle = opendir($opendir)) {
while (false !== ($file = readdir($handle))) {
//first see if this file is required in the listing
if ($file == "." || $file == "..")  continue;
$discard = false;
for($hi=0;$hi<sizeof($hide);$hi++) {
if(strpos($file, $hide[$hi])!==false) {
$discard = true;
}
}

if($discard) continue;
if (@filetype($includeurl.$leadon.$file) == "dir") {
if(!$showdirs) continue;

$n++;
if($_GET['sort']=="date") {
$key = @filemtime($includeurl.$leadon.$file) . ".$n";
}
else {
$key = $n;
}
$dirs[$key] = $file . "/";
}
else {
$n++;
if($_GET['sort']=="date") {
$key = @filemtime($includeurl.$leadon.$file) . ".$n";
}
elseif($_GET['sort']=="size") {
$key = @filesize($includeurl.$leadon.$file) . ".$n";
}
else {
$key = $n;
}

if($showtypes && !in_array(substr($file, strpos($file, '.')+1, strlen($file)), $showtypes)) unset($file);
if($file) $files[$key] = $file;

if($displayindex) {
if(in_array(strtolower($file), $indexfiles)) {
header("Location: $leadon$file");
die();
}
}
}
}
closedir($handle);
}

//sort our files
if($_GET['sort']=="date") {
@ksort($dirs, SORT_NUMERIC);
@ksort($files, SORT_NUMERIC);
}
elseif($_GET['sort']=="size") {
@natcasesort($dirs);
@ksort($files, SORT_NUMERIC);
}
else {
@natcasesort($dirs);
@natcasesort($files);
}

//order correctly
if($_GET['order']=="desc" && $_GET['sort']!="size") {$dirs = @array_reverse($dirs);}
if($_GET['order']=="desc") {$files = @array_reverse($files);}
$dirs = @array_values($dirs); $files = @array_values($files);


?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Directory Listing of <?php echo str_replace('\\', '', dirname(strip_tags($_SERVER['PHP_SELF']))).'/'.$leadon;?></title>
<link rel="stylesheet" type="text/css" href="<?php echo $includeurl; ?>dlf/styles.css" />
<?php
if($showthumbnails) {
?>
<script language="javascript" type="text/javascript">
<!--
function o(n, i) {
document.images['thumb'+n].src = '<?php echo $includeurl; ?>dlf/i.php?f='+i<?php if($memorylimit!==false) echo "+'&ml=".$memorylimit."'"; ?>;

}

function f(n) {
document.images['thumb'+n].src = 'dlf/trans.gif';
}
//-->
</script>
<?php
}
?>
</head>
<body>
<div id="container">
  <h1>Directory Listing of <?php echo str_replace('\\', '', dirname(strip_tags($_SERVER['PHP_SELF']))).'/'.$leadon;?></h1>
  <div id="breadcrumbs"> <a href="<?php echo strip_tags($_SERVER['PHP_SELF']);?>">home</a>
  <?php
  $breadcrumbs = split('/', str_replace($startdir, '', $leadon));
  if(($bsize = sizeof($breadcrumbs))>0) {
  $sofar = '';
  for($bi=0;$bi<($bsize-1);$bi++) {
$sofar = $sofar . $breadcrumbs[$bi] . '/';
echo ' &gt; <a href="'.strip_tags($_SERVER['PHP_SELF']).'?dir='.urlencode($sofar).'">'.$breadcrumbs[$bi].'</a>';
}
  }

$baseurl = strip_tags($_SERVER['PHP_SELF']) . '?dir='.strip_tags($_GET['dir']) . '&amp;';
$fileurl = 'sort=name&amp;order=asc';
$sizeurl = 'sort=size&amp;order=asc';
$dateurl = 'sort=date&amp;order=asc';

switch ($_GET['sort']) {
case 'name':
if($_GET['order']=='asc') $fileurl = 'sort=name&amp;order=desc';
break;
case 'size':
if($_GET['order']=='asc') $sizeurl = 'sort=size&amp;order=desc';
break;

case 'date':
if($_GET['order']=='asc') $dateurl = 'sort=date&amp;order=desc';
break;
default:
$fileurl = 'sort=name&amp;order=desc';
break;
}
  ?>
  </div>
  <div id="listingcontainer">
    <div id="listingheader">
<div id="headerfile"><a href="<?php echo $baseurl . $fileurl;?>">File</a></div>
<div id="headersize"><a href="<?php echo $baseurl . $sizeurl;?>">Size</a></div>
<div id="headermodified"><a href="<?php echo $baseurl . $dateurl;?>">Last Modified</a></div>
</div>
    <div id="listing">
<?php
$class = 'b';
if($dirok) {
?>
<div><a href="<?php echo strip_tags($_SERVER['PHP_SELF']).'?dir='.urlencode($dotdotdir);?>" class="<?php echo $class;?>"><img src="<?php echo $includeurl; ?>dlf/dirup.png" alt="Folder" /><strong>..</strong> <em>&nbsp;</em>&nbsp;</a></div>
<?php
if($class=='b') $class='w';
else $class = 'b';
}
$arsize = sizeof($dirs);
for($i=0;$i<$arsize;$i++) {
?>
<div><a href="<?php echo strip_tags($_SERVER['PHP_SELF']).'?dir='.urlencode(str_replace($startdir,'',$leadon).$dirs[$i]);?>" class="<?php echo $class;?>"><img src="<?php echo $includeurl; ?>dlf/folder.png" alt="<?php echo $dirs[$i];?>" /><strong><?php echo $dirs[$i];?></strong> <em>-</em> <?php echo date ("M d Y h:i:s A", filemtime($includeurl.$leadon.$dirs[$i]));?></a></div>
<?php
if($class=='b') $class='w';
else $class = 'b';
}

$arsize = sizeof($files);
for($i=0;$i<$arsize;$i++) {
$icon = 'unknown.png';
$ext = strtolower(substr($files[$i], strrpos($files[$i], '.')+1));
$supportedimages = array('gif', 'png', 'jpeg', 'jpg');
$thumb = '';

if($showthumbnails && in_array($ext, $supportedimages)) {
$thumb = '<span><img src="dlf/trans.gif" alt="'.$files[$i].'" name="thumb'.$i.'" /></span>';
$thumb2 = ' onmouseover="o('.$i.', \''.urlencode($leadon . $files[$i]).'\');" onmouseout="f('.$i.');"';

}

if($filetypes[$ext]) {
$icon = $filetypes[$ext];
}

$filename = $files[$i];
if(strlen($filename)>43) {
$filename = substr($files[$i], 0, 40) . '...';
}

$fileurl = $includeurl . $leadon . $files[$i];
if($forcedownloads) {
$fileurl = $_SESSION['PHP_SELF'] . '?dir=' . urlencode(str_replace($startdir,'',$leadon)) . '&download=' . urlencode($files[$i]);
}

?>
<div><a href="<?php echo $fileurl;?>" class="<?php echo $class;?>"<?php echo $thumb2;?>><img src="<?php echo $includeurl; ?>dlf/<?php echo $icon;?>" alt="<?php echo $files[$i];?>" /><strong><?php echo $filename;?></strong> <em><?php echo round(filesize($includeurl.$leadon.$files[$i])/1024);?>KB</em> <?php echo date ("M d Y h:i:s A", filemtime($includeurl.$leadon.$files[$i]));?><?php echo $thumb;?></a></div>
<?php
if($class=='b') $class='w';
else $class = 'b';
}
?></div>
<?php
if($allowuploads) {
$phpallowuploads = (bool) ini_get('file_uploads');
$phpmaxsize = ini_get('upload_max_filesize');
$phpmaxsize = trim($phpmaxsize);
$last = strtolower($phpmaxsize{strlen($phpmaxsize)-1});
switch($last) {
case 'g':
$phpmaxsize *= 1024;
case 'm':
$phpmaxsize *= 1024;
}

?>
<div id="upload">
<div id="uploadtitle">
<strong>File Upload</strong> (Max Filesize: <?php echo $phpmaxsize;?>KB)

<?php if($uploaderror) echo '<div class="upload-error">'.$uploaderror.'</div>'; ?>
</div>
<div id="uploadcontent">
<?php
if($phpallowuploads) {
?>
<form method="post" action="<?php echo strip_tags($_SERVER['PHP_SELF']);?>?dir=<?php echo urlencode(str_replace($startdir,'',$leadon));?>" enctype="multipart/form-data">
<input type="file" name="file" /> <input type="submit" value="Upload" />
</form>
<?php
}
else {
?>
File uploads are disabled in your php.ini file. Please enable them.
<?php
}
?>
</div>

</div>
<?php
}
?>
  </div>
</div>
</body>
</html>

jQuery Monitor Plugin


<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
/**
* @Name: jQuery Monitor plugin
* @Version: 1.0.0
* @License: MIT
* @Copyright: Andrei Razumkou
* @Date: 07 Aug 2011
* @Author: Andrei Razumkou nix.d3v(at)gmail.com
* @Description: Simple generic monitoring plugin. Created to track changes in values
* returned by any user defined callback function.
*/

(function(factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else {
        // Browser globals
        factory(jQuery);
    }
}( function( $ ) {
  var interval = 100;//milliseconds
var callbacks = [];
var started = false;
var stop = false;
var startMainLoop = function(){
(function() {
/*
* Checking if value has changed.
*/
var len = callbacks.length;
for(var i=0;i<len;i++){
var newVal = callbacks[i][1]();
if (callbacks[i][0] !== newVal) {
callbacks[i][0] = newVal;
callbacks[i][2]();
}
}

/*
* Starting the loop automatically if not yet started.
*/
if(!stop) {
setTimeout(arguments.callee, interval);
} else {
started = false;
}
})();

started = true;
}

var methods = {

/*
* @param execCallback - function to execute when valCallback changes
* @param valCallback - function that return a value to be compared to the previous value
*/
add : function(valCallback, execCallback) {
var valueNow = valCallback();
var newElem = [valueNow, valCallback, execCallback]
callbacks.push(newElem);
if(started === false){
stop=false;
startMainLoop();
}
},

/*
* Stort polling (if was stopped before for some reason)
*/
start: function() {
stop = false;
if(started === false){
startMainLoop();
}
},

/*
* Clear the callbacks and stops the loop
*/
clear: function(){
callbacks = [];
stop=true;
},

/*
* Stop polling
*/
stop : function() {
stop = true;
}
};


/*
* Entry point - generic functions
*/
$.monitor = function( method ) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else {
$.error( 'Method ' +  method + ' does not exist on jQuery.monitor' );
}
};
}));
</script>
<script>
    $.monitor('add', function(){return $("#site-logo").val()}, function(){
                 
        alert("i change");

    });                                            
</script>

<input type="input" name="site-logo" id="site-logo" placeholder="Browse your image" />                          
<div id="uploaded-img-preveiw"><img style="max-width:400px" id="logo-preview" src="<?php echo "test" ?>" alt="image preview"/></div>

Encryption Decryption in PHP


<?php
/*
* Author: Zuh@ir
* Encryption Decryption in PHP
*/

$encrypt=encrypt("zuhair_mirza@yahoo.com", "testkey");

$decrypt=decrypt($encrypt, "testkey");

var_dump($encrypt,"2",$decrypt);

function encrypt($string, $key) {
$result = '';
for($i=0; $i<strlen($string); $i++) {
$char = substr($string, $i, 1);
$keychar = substr($key, ($i % strlen($key))-1, 1);
$char = chr(ord($char)+ord($keychar));
$result.=$char;
}

return base64_encode($result);
}

function decrypt($string, $key) {
$result = '';
$string = base64_decode($string);

for($i=0; $i<strlen($string); $i++) {
$char = substr($string, $i, 1);
$keychar = substr($key, ($i % strlen($key))-1, 1);
$char = chr(ord($char)-ord($keychar));
$result.=$char;
}

return $result;
}
?>

Find weather in PHP


<?php
/*
*Author : Zuh@ir
*Find weather using Yahoo weather API By Zipcode
*/
if(isset($_REQUEST['zipcode'])) {
if(isset($_POST['zipcode']) && is_numeric($_POST['zipcode'])){
    $zipcode = $_POST['zipcode'];
}else{
    $zipcode = '50644';
}
$result = file_get_contents('http://weather.yahooapis.com/forecastrss?p=' . $zipcode . '&u=f');
$xml = simplexml_load_string($result);

//echo htmlspecialchars($result, ENT_QUOTES, 'UTF-8');

$xml->registerXPathNamespace('yweather', 'http://xml.weather.yahoo.com/ns/rss/1.0');
$location = $xml->channel->xpath('yweather:location');

if(!empty($location)){
    foreach($xml->channel->item as $item){
        $current = $item->xpath('yweather:condition');
        $forecast = $item->xpath('yweather:forecast');
        $lat = $item->xpath('geo:lat');
        $lng = $item->xpath('geo:long');
        $current = $current[0];
        $output = <<<END
            <h2 style="margin-bottom: 0">Weather for {$location[0]['city']}, {$location[0]['region']}</h2>
            <div>{$current['date']}</div>
            <h2>Current Conditions</h2>
            <p>
            <span style="font-size:42px; font-weight:bold;">{$current['temp']}&deg;F</span>
            <br/>
            <img src="http://l.yimg.com/a/i/us/we/52/{$current['code']}.gif" style="vertical-align: middle;"/>&nbsp;
            {$current['text']}
            </p>
            <h2>Forecast</h2>
            {$forecast[0]['day']} : {$forecast[0]['text']}.  High: {$forecast[0]['high']}&#176;F,  Low: {$forecast[0]['low']}&#176;F
            <br/>
            {$forecast[1]['day']} : {$forecast[1]['text']}.  High: {$forecast[1]['high']}&#176;F,  Low: {$forecast[1]['low']}&#176;F
            </p>
END;
    }
}else{
    $output = '<h1>No results found, please try a different zip code.</h1>';
}
}else{
 
    $output = '';
}
?>
<script>
    function validateZipcode(){ //alert("test");
        if (!/^\d{5}$|^\d{5}-\d{4}$/.test(form.zipcode.value)) {
            alert("Please enter valid Zip Code");
            form.zipcode.focus()
            return false;}
    }
</script>

<form id="form" method="POST" action="">
<label>Please Enter Your Zipcode:</label> <input type="text" name="zipcode" size="8" value="" /><input onClick="return validateZipcode();" type="submit" name="submit" value="Lookup Weather" />

</form>
<hr />
<?php echo $output; ?>

Sunday 5 August 2012

Data Structure Interview Questions and Answers


1. What is data structure?
A data structure is a way of organizing data that considers not only the items stored, but also their relationship to each other. Advance knowledge about the relationship between data items allows designing of efficient algorithms for the manipulation of data.

2. List out the areas in which data structures are applied extensively?
1.    Compiler Design,
2.    Operating System,
3.    Database Management System,
4.    Statistical analysis package,
5.    Numerical Analysis,
6.    Graphics,
7.    Artificial Intelligence,
8.    Simulation

3. What are the major data structures used in the following areas : RDBMS, Network data model and Hierarchical data model.
1.    RDBMS = Array (i.e. Array of structures)
2.    Network data model = Graph
3.    Hierarchical data model = Trees

4. If you are using C language to implement the heterogeneous linked list, what pointer type will you use?
The heterogeneous linked list contains different data types in its nodes and we need a link, pointer to connect them. It is not possible to use ordinary pointers for this. So we go for void pointer. Void pointer is capable of storing pointer to any type as it is a generic pointer type.

5. Minimum number of queues needed to implement the priority queue?
Two. One queue is used for actual storing of data and another for storing priorities.

6. What is the data structures used to perform recursion?
Stack. Because of its LIFO (Last In First Out) property it remembers its 'caller' so knows whom to return when the function has to return. Recursion makes use of system stack for storing the return addresses of the function calls.
Every recursive function has its equivalent iterative (non-recursive) function. Even when such equivalent iterative procedures are written, explicit stack is to be used

7. What are the notations used in Evaluation of Arithmetic Expressions using prefix and postfix forms?
Polish and Reverse Polish notations.

8. Convert the expression ((A + B) * C - (D - E) ^ (F + G)) to equivalent Prefix and Postfix notations.
1.    Prefix Notation: - * +ABC ^ - DE + FG
2.    Postfix Notation: AB + C * DE - FG + ^ -

9. Sorting is not possible by using which of the following methods? (Insertion, Selection, Exchange, Deletion)
Sorting is not possible in Deletion. Using insertion we can perform insertion sort, using selection we can perform selection sort, using exchange we can perform the bubble sort (and other similar sorting methods). But no sorting method can be done just using deletion.

10. What are the methods available in storing sequential files ?
1.    Straight merging,
2.    Natural merging,
3.    Polyphase sort,
4.    Distribution of Initial runs.

11. List out few of the Application of tree data-structure?
1.    The manipulation of Arithmetic expression,
2.    Symbol Table construction,
3.    Syntax analysis.

12. List out few of the applications that make use of Multilinked Structures?
1.    Sparse matrix,
2.    Index generation.

13. In tree construction which is the suitable efficient data structure? (Array, Linked list, Stack, Queue)
Linked list is the suitable efficient data structure.

14. What is the type of the algorithm used in solving the 8 Queens problem?
Backtracking.

15. In an AVL tree, at what condition the balancing is to be done?

If the 'pivotal value' (or the 'Height factor') is greater than 1 or less than -1.

16. What is the bucket size, when the overlapping and collision occur at same time?
One. If there is only one entry possible in the bucket, when the collision occurs, there is no way to accommodate the colliding value. This results in the overlapping of values.

17. Classify the Hashing Functions based on the various methods by which the key value is found.
1.    Direct method,
2.    Subtraction method,
3.    Modulo-Division method,
4.    Digit-Extraction method,
5.    Mid-Square method,
6.    Folding method,
7.    Pseudo-random method.

18. What are the types of Collision Resolution Techniques and the methods used in each of the type?
1.    Open addressing (closed hashing), The methods used include: Overflow block.
2.    Closed addressing (open hashing), The methods used include: Linked list, Binary tree.
3.    19. In RDBMS, what is the efficient data structure used in the internal storage representation?
4.    B+ tree. Because in B+ tree, all the data is stored only in leaf nodes, that makes searching easier. This corresponds to the records that shall be stored in leaf nodes.
5.    20. What is a spanning Tree?
6.    A spanning tree is a tree associated with a network. All the nodes of the graph appear on the tree once. A minimum spanning tree is a spanning tree organized so that the total edge weight between nodes is minimized.
7.    21. Does the minimum spanning tree of a graph give the shortest distance between any 2 specified nodes?
8.    No. The Minimal spanning tree assures that the total weight of the tree is kept at its minimum. But it doesn't mean that the distance between any two nodes involved in the minimum-spanning tree is minimum.
9.    22. Which is the simplest file structure? (Sequential, Indexed, Random)
10.  Sequential is the simplest file structure.
11. 23. Whether Linked List is linear or Non-linear data structure?
12.  According to Access strategies Linked list is a linear one. 
According to Storage Linked List is a Non-linear one.
Mix Questions:

Q: What's the major distinction in between Storage structure and file structure
 and how?
A: The expression of an specific data structure inside memory of a computer system is termed storage structure in contrast to a storage structure expression in auxiliary memory is normally known as a file structure.

Q: Explain whether Linked List is actually linear or Non-linear data structure?
A: Link list is definitely obviously linear data structure simply because each and every element (NODE) acquiring specific place and as well each and every component has got its unique successor in addition to predecessor. furthermore, linear collection of data objects referred to as nodes and also the linear order is provided by means of pointers. Every node can be separated into two parts. First part includes information of the element and another part includes the address of the subsequent node in the list.

Q: Explain simulation?
 A: Simulation is the procedure for developing an fuzy model from a real situation so as to understand the effects of modifications and the effect of introducing a variety of techniques on the situation. It is a rendering with real life system by another system, which represents the important characteristics of real system and allows experiments on it.

Q: Does the minimum spanning tree of the graph provide the shortest distance between any two given nodes?
A: Minimal spanning tree ensures that the total weight of the tree is actually kept at its minimum but it really would not signify the distance between any two nodes involved in the minimum-spanning tree is actually minimum.

Q: In an AVL tree, at exactly what situation the balancing will be done?
A: If the pivotal value (or the Height factor) is above 1 or less than 1. If the balance factor of any node is other than 0 or 1 or -1 then balancing is completed. The balancing factor will be height. The variation in height of the right subtree along with right subtree need to be +1, -1 or 0

Q: What is the significant difference between ARRAY and STACK?
A: Stack ensues LIFO. Thus the item that is certainly first entered would be the last removed. In array the items could be entered or removed in any order. Basically each and every member access is done making use of index and no strict order is to be followed here to remove a particular element. Array could be multi dimensional or one dimensional but stack really should be one-dimensional.
Size of array is fixed, while stack may be grow or shrink. We can say stack is actually dynamic data structure.