Friday 7 September 2012

Import data into MySQL database using mysqlimport

The below example shows how to import data into mysql database using mysqlimport utility. We are importing data from a text file to mysql database.

mysqlimport utility is a stand-alone command line utility program which comes with MySQL.

First you have to connect to mysql server.
1. open command prompt
2. change directory to the path of mysql bin folder (for example C:\xampp\mysql\bin)











Create a database employee and use that database.







create a table employee with 2 fields id and name







create a text file for employee table with fields delimited by tab.This file is used for importing data into employee table.

employee.txt

1    Tom
2    pinky
3    Ram

put the employee.txt file into C:\xampp\mysql\data\employee folder.
In mysqlimport, the name of the data file should match the name of the table.  

close the mysql connection by typing exit






open a new command prompt and change directory to the path of mysql bin folder (for example C:\xampp\mysql\bin)
Type mysqlimport command 









This will import the employee details from the text file into employee table.

 

Thursday 26 July 2012

MySQL said: Documentation #2002 - The server is not responding (or the local MySQL server's socket is not correctly configured)

After successfully installed  xampp and type http://localhost/phpmyadmin/ it opens up a page with erroe message:

MySQL said: Documentation #2002 - The server is not responding (or the local MySQL server's socket is not correctly configured)


Fix for the issue:
1. open the file config.inc.php in the folder C:\xampp\phpMyAdmin
2. add the following code in the file
   $cfg['Servers'][$i]['socket'] = '/var/run/mysql/mysql.sock';
   (don't forget to save a local copy of config.inc.php before editting)
3. Clear the history of the browser and refresh it.

Thursday 24 May 2012

Install Python

python installation instructions

1. Download python from
2. Choose the installer for your machine (For window 7 (64 bit) click Python 2.7.3 Windows X86-64    Installer.  for windows 32 bit click Python 2.7.3 Windows Installer).
3. It starts downloading and  save it in a local folder.
4. Double the downloaded exe file ( python-2.7.3.amd64.exe.)
5. Follow the installation instructions.
6. Choose a directory for installing python.(eg: C:\python2.7.3 )
7. Click the finish button. Now Python is installed in your machine.

Running Python

To check python is properly installed, open a command window(Start -> Programs -> Accessories -> Command Prompt.) Enter the command "python" and hitting return.
If the python command, instead of displaying the interpreter prompt >>>, gives you a message like:










Then you need to make sure that your computer knows where to find the Python interpreter. To do this you will have to modify a setting called PATH, which is a list of directories where Windows will look for programs.

To set PATH variable
start-> right click My Computer -> click properties -> Click Advanced System Setting
A pop up will open .





















Click Environment variables.
Environment variables pop up will open. Under System variables in that popup select "Path" . click Edit button.






















Add the python path (eg:C:\python2.7.3\) at the end of Variable Value.
Click ok .













Now you have successfully add Python’s installation directory to to the PATH variable.


Close the command prompt and again open it and type python.
now you can see python python below message, indicates python is successfully installed. 










For running python you can use command prompt or Python IDLE. It is easy to use Python IDLE than command prompt. IDLE integrated development environment (IDE) is for  editing and running Python 2.x or Python 3 programs.

How to open python IDLE (Python GUI)

1. Start->All programs->Python 2.7 click IDLE (Python GUI). 
You will see windows entitled "Python Shell" .










2. From the Python Shell window, select New Window from the File menu.
3. A window entitled "Untitled" will open.
4. From the File menu, select Save As, and  save your Python file to a folder
5. In the File name: text box, type: hello.py (The type of file should be Python)
6.In the hello.py file type print "hello" and save the file.








7.To run hello.py, select Run Module from the Run menu
8. Then you can see the output of hello.py in a Python Shell window.














Wednesday 2 May 2012

Install standalone blast for windows

BLAST allows you to compare your sequence against a database of sequences and informs you if your sequence matches any of the sequences in the database.

The ncbi-blast-#.#.#+-win32.exe is compatible with PCs running Windows XP, 32-bit Vista or Windows 7.
ncbi-blast-#.#.#+-win64.exe is compatible with PCs running  Windows XP 2003, 64-bit Vista or Windows7. "#.#.#" denotes the current version number of the package.

Installation steps

1. Download blast((ncbi-blast-2.2.26+-win32.exe) from
    ftp://ftp.ncbi.nlm.nih.gov/blast/executables/LATEST/

2. Double click the ncbi-blast-2.2.26+-win32.exe . Accept the license agreement.Then the installer will     prompt for an installation directory. The default installation directory is "C:\blast-2.2.25+".
(you can choose any other destination folder)

3. click the install button. It will install blast in C:\blast-2.2.25+

4. Next step is to configure the environment variable.
   Go to Start -> My Computer
   Right click My Computer and click Properties.
   System Properties pop up will open.
   In the popup, click on the Advanced tab
   Click the "Environment Variables" button
   Click the "New" button under the "User variable for ..." panel.
   add
       variable name : Path
       variable value: C:\blast-2.2.25+\bin
click ok button.

5. Create the Blast database

The blast+ installer automatically creates a BLASTDB environment variable, which points to the "C:\blast-2.2.25+\" directory. For more effective database management, a "db" subdirectory should be created under the "C:\blast-2.2.25+\".
The value of BLASTDB environment variable must be modified to "C:\blast-2.2.3+\db\".
Pre-formatted NCBI BLAST databases is available as compressed archives from NCBI ftp site.You can download the database and put in the db folder. The second option is you can create a custom database. Databases can be prepared from custom FASTA sequences locally using the makeblastdb utility.

To create a custom BLAST database, you need a simple FASTA file say nuclic.fasta. Put all your FASTA sequence in it. Put the nuclic.fasta file in C:\blast-2.2.25+\db folder. The custom sequence's fasta file (nuclic.fasta)is then converted into BLAST database by a tool called makeblastdb.(you can see makeblastdb.exe file in C:\blast-2.2.25+\bin folder)

To create blast database file
Open the command promt.
The below image show the execution of makeblastdb command.














the command is
makeblastdb -in db/nuclic.fasta -dbtype nucl -out db/nuclic

It will create 3 files nuclic.nhr, nuclic.nin, nuclic.nsq in  C:\blast-2.2.25+\db folder
.nsq, .nhr, and .nin files are blastn database files.

6. Create  test.txt file which contains the FASTA sequence to be compared.

This file is used as an input query in a test blastn search with the following command line:

blastn -query db/test.txt -db db/nuclic -out db/output.txt

which performs the following tasks:
    1. calling blastn to run a nucleotide query vs nucleotide database search
    2. using sequence contained in test.txt file as input query
    3. searching against nuclic database
    4. saving the result in output.txt
The below image show the execution of blastn command.















A new file output.txt is created in C:\blast-2.2.25+\db folder.



Thursday 12 April 2012

How to implement CAPTCHA in PHP?

CAPTCHA is used to prevent spam abuse on the websites.

If we have a public submission form on our website (contact Us page), we can use CAPTCHA.
We can discuss how we can implement CAPTCHA in PHP

1. Create a php file that generates image.(say CaptchaImages.php)

<?php
session_start();
class CaptchaSecurityImages {
    var $font = 'Teen Bold.ttf';
    function generateCode($characters) {
        /* list all possible characters, similar looking characters and vowels have been removed */
        $possible = '23456789bcdfghjkmnpqrstvwxyz';
        $code = '';
        $i = 0;
        while ($i < $characters) {
            $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
            $i++;
        }
        return $code;
    }

    function CaptchaSecurityImages($width='120',$height='40',$characters='6') {
        $code = $this->generateCode($characters);
        /* font size will be 75% of the image height */
        $font_size = $height * 0.75;
        $image = @imagecreate($width, $height) or die('Cannot initialize new GD image stream');
        /* set the colours */
        $background_color = imagecolorallocate($image, 255, 255, 255);
        $text_color = imagecolorallocate($image, 20, 40, 100);
        $noise_color = imagecolorallocate($image, 100, 120, 180);
        /* generate random dots in background */
        for( $i=0; $i<($width*$height)/3; $i++ ) {
            imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
        }
        /* generate random lines in background */
        for( $i=0; $i<($width*$height)/150; $i++ ) {
            imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height),

$noise_color);
        }
        /* create textbox and add text */
        $textbox = imagettfbbox($font_size, 0, $this->font, $code) or die('Error in imagettfbbox function');
        $x = ($width - $textbox[4])/2;
        $y = ($height - $textbox[5])/2;
        imagettftext($image, $font_size, 0, $x, $y, $text_color, $this->font , $code) or die('Error in imagettftext

function');
        /* output captcha image to browser */
        header('Content-Type: image/jpeg');
        imagejpeg($image);
        imagedestroy($image);
        $_SESSION['security_code'] = $code;
    }
}
$width = isset($_GET['width']) ? $_GET['width'] : '120';
$height = isset($_GET['height']) ? $_GET['height'] : '40';
$characters = isset($_GET['characters']) && $_GET['characters'] > 1 ? $_GET['characters'] : '6';
$captcha = new CaptchaSecurityImages($width,$height,$characters);
?>



2. Copy paste “Teen Bold.ttf” font in the same directory as the CaptchaImages.php file. (Alternatively you can replace the line var $font = ‘Teen Bold.ttf’; with the name of whatever font you want to use)
You can download the font from http://www.webpagepublicity.com/free-fonts-t.html#Free%20Fonts


3. Put the below code in the form.
    <input id="security_code" name="security_code" type="text" />
    <img src="CaptchaImages.php?width=100&height=40&characters=5" />
    (you can specify the width and height of the image)

4. Put the below code in the form . It check the generated captcha image with the image you have submitted in the text box.

   <?php
      session_start();
   if( isset($_POST['submit'])) {
   if( $_SESSION['security_code'] == $_POST['security_code'] && !empty($_SESSION['security_code'] ) ) {      
        unset($_SESSION['security_code']);
           if($_SERVER["REQUEST_METHOD"] == "POST"){
             // process email
        }
     } else {
            // validation message
               unset($_SESSION['security_code']);
   }
  }
?>

************************************************************************************
Php example which contains the contact form:


 <?php
 error_reporting(0);
 session_start();
if( isset($_POST['submit'])) {
   if( $_SESSION['security_code'] == $_POST['security_code'] && !empty($_SESSION['security_code'] ) ) {
       
        unset($_SESSION['security_code']);
           if($_SERVER["REQUEST_METHOD"] == "POST"){
               $to = "someone@example.com";
            $subject = $_POST['subject'];
            $message = $_POST["textarea"];
            $from = $_POST["email"];
            $headers = "From:" . $from;
            mail($to,$subject,$message,$headers);
        }
     } else {
        echo "<br/>";
        echo "<b>";
        echo "<div align='left'>";
        echo "<font color='red'>". 'Sorry, you have provided an invalid security code'."</font>";
        echo "</div>";
        echo "</b>";
        unset($_SESSION['security_code']);
   }
 
}
?>
 <form name="form1" id="form1" method="post" action="">
                                  <table border="0" width="350" style="font-size:12px;">
                                    <tbody>
                                    <tr>
                                      <td>
                                        <label for="label"> <strong>Email</strong></label>
                                        <label for="label">:</label>
                                       *</td>
                                       <td >
                                          <input type="text" id="email" name="email">
                                       </td>
                                    </tr>
                                    <tr>
                                      <td height="28"><label for="txtemail"> <strong>Subject:</strong>
                                      </label>
                                       *</td>
                                       <td height="28">
                                          <input type="text" id="subject" name="subject">
                                      </td>
                                    </tr>
                                                                       <tr>
                                      <td height="30">
                                      <label for="label2"> <strong>Message:</strong></label>
                                       *</td>
                                       <td>
                                          <textarea id="textarea" name="textarea" rows="5" cols="17"></textarea>
                                     </td>
                                    </tr>
                                         <tr> </tr>
                                    <tr>
                                      <td>
                                      <label for="security_code"><Strong>Security Code:</Strong> </label>
                                      *
                                    <br/></td>
                                    <td>
                                            <input id="security_code"

name="security_code" type="text" /><br />
                                        </td>
                                       
                                    </tr>
                                    <tr>
                                      <td><div align="left">
                                          <img src="CaptchaImages.php?width=140&height=40&characters=5" />
                                           
                                        </div></td>
                                    </tr>
                                  
                                  
                                   
                                    <tr>
                                      <td height="32"><div align="center"><strong></strong></div></td>
                                    </tr>
                                    <tr>
                                      <td><div align="center">
                                          <input type="submit"   value="Send Message" name="submit">
                                      </div></td>
                                    </tr>
                                  </tbody></table>
                                </form>

Wednesday 11 April 2012

Table sorting in php using javascript?

The below example sort the table using java script. you can populate the table data from database using php.
You need to create 2 folders css and js. put the table.css in css folder and table.js in js folder.
copy paste the below code and save it as sort.php and put it in pages folder.

Download table.js and table.css

<html>
<head>
    <meta charset="UTF-8" />
    <title>Php table sort</title>
    <link rel="stylesheet" type="text/css" href="../css/table.css" />
    <script src="../js/table.js" type="text/javascript"></script>
</head>
<?php
error_reporting(0);
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("genedb", $con);
$sql="SELECT * FROM gene";

$result = mysql_query($sql);
       ?>
       <div id="content">
        <div id="blog">
        <div id="articles" style="width:692px;padding:0;">
<table width="250" border="1" class="example table-autosort table-autofilter table-autopage:10 table-stripeclass:alternate table-page-number:t1page table-page-count:t1pages table-filtered-rowcount:t1filtercount table-rowcount:t1allcount" id="t1">
<thead>
    <tr style="height:35px">
        <th class="table-sortable:default table-sortable table-sorted-desc">Symbol</th>
        <th class="table-sortable:numeric table-sortable  " title="Click to sort">Id</th>
        <th class="table-filterable table-sortable:default table-sortable" title="Click to sort">Location</th>
        </tr>
</thead>
<tbody>
    <?php
    while($row = mysql_fetch_array($result))
  {     
       ?>
 <tr>
 <td><?php echo $row['symbol']?></td>
 <td><?php echo $row['id']?></td>
 <td><?php echo $row['location']?></td>
  <?php
  }
  mysql_close($con);
?>
 </tbody>
 <tfoot>
   
    <tr>
        <td style="cursor:pointer;" class="table-page:previous">&lt; &lt; Previous</td>
        <td style="text-align:center;" colspan="1">Page <span id="t1page">1</span>&nbsp;of <span id="t1pages">11</span></td>
        <td style="cursor:pointer;" class="table-page:next">Next &gt; &gt;</td>
    </tr>
    <tr>
        <td colspan="3"><span id="t1filtercount">105</span>&nbsp;of <span id="t1allcount">105</span>&nbsp;rows match filter(s)</td>
</tr></tfoot>
</table>

Output :




                                                                                technorati claim code :A8CRZ8P6MW44 

Thursday 5 April 2012

Get the value of t:inputCalendar if readonly is true


<t:inputCalendar id="cal" value="#{backingBean.date1}"
        renderAsPopup="true"
        popupDateFormat="MM/dd/yyyy"
        popupTodayDateFormat="dd-MMM-yyyy"
        popupWeekString="Week"
        popupTodayString="The date today is :"
        renderPopupButtonAsImage="true"
        helpText="MM/DD/YYYY"
        readonly="true"/>

To get the value in the backing bean just add the below code.
When readonly attribute is true, the component cannot be edited by the user.(ie the text box in the calendar cannot be edited.)

bodyId:id of body tag
formId:id of form tag
String dateString = (String) getExternalContext().getRequestParameterMap().get("bodyId:formId:date1");

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy",
                 getCurrentLocale());