Sunday, April 27, 2014

Install Nagios3 in Ubuntu



Nagios:
http://www.nagios.org/
Nagios can be used to monitor your entire IT infrastructure, such as network, switch, database, CPU and security in any of your computers.
In Ubuntu,
1) sudo apt-get install nagios3
2) To avoid error in service nagios3 start
sudo /etc/init.d/nagios3 stop
sudo /etc/init.d/nagios3 start

3) Remember nagiosadmin and its password
4) In you hostname/nagios3, for example
http://192.168.56.101/nagios3/
to start
nagios monitoring
Note: the following may need to be changed before nagios start
edit /etc/nagios3/nagios.cfg
change
 check_external_commands=0
to
check_external_commands=1
edit /etc/groups
add www-data at the end of nagios group
chmod g+x /var/lib/nagios3/rw/
chmod g+x /var/lib/nagios3

Video:  Install Nagios3 in Ubuntu

Sunday, April 20, 2014

Reversing linked list iteratively and recursively in C++



Reversing linked list iteratively and recursively in C++
 A) iteratively
 1) need three pointers parent, cur and child
 2) break the forward link: parent->next = NULL;
 3) point cur->next =parent
 4) move to next element for all three pointers
         parent = cur;
        cur = child;
        child = child->next;
code:
struct Node* reverse_iterate(struct Node** head)
{
    Node *parent = *head;
    Node *cur = parent->next;
    Node *child = cur->next;

    /* break forward link */
    parent->next = NULL;
    while(child) {
        cur->next = parent;
        parent = cur;
        cur = child;
        child = child->next;
    }
    cur->next = parent;
    *head = cur;
    return *head;
}

 B)    recursively
code:
void reverse_recursion(struct Node*& cur )
 {
     if (cur==NULL) return;
     Node* rest = cur->next;
    if (rest==NULL) return;
     reverse_recursion(rest);
     cur->next->next = cur;
    cur->next = NULL;
    cur = rest;
 }

Full code:
#include <iostream>
using namespace std;
struct Node {
    int data;
    Node* next;
};
// only for the 1st Node
void initNode(struct Node *head,int n){
    head->data = n;
    head->next =NULL;
}
// apending
void addNode(struct Node *head, int n) {
    Node *newNode = new Node;
    newNode->data = n;
    newNode->next = NULL;
    Node *cur = head;
    while(cur) {
        if(cur->next == NULL) {
            cur->next = newNode;
            return;
        }
        cur = cur->next;
    }
}
/* reverse the list */
struct Node* reverse_iterate(struct Node** head)
{
    Node *parent = *head;
    Node *cur = parent->next;
    Node *child = cur->next;

    /* break forward link */
    parent->next = NULL;
    while(child) {
        cur->next = parent;
        parent = cur;
        cur = child;
        child = child->next;
    }
    cur->next = parent;
    *head = cur;
    return *head;
}
void reverse_recursion(struct Node*& cur )
 {
     if (cur==NULL) return;
     Node* rest = cur->next;
    if (rest==NULL) return;
     reverse_recursion(rest);
     cur->next->next = cur;
    cur->next = NULL;
    cur = rest;
 }

 void display(struct Node *head) {
    Node *list = head;
    while(list) {
        cout << list->data << " ";
        list = list->next;
    }
    cout << endl;
}
int main()
{
    struct Node *head = new Node;
    initNode(head,1);
    addNode(head,2);
    addNode(head,3);
    addNode(head,4);
    addNode(head,5);
    display(head);
    cout<<"Reverse the list iteratively"<<endl;
    reverse_iterate(&head);
    display(head);
    cout<<"Reverse the list recursively"<<endl;
    reverse_recursion(head);
    display(head);
}

Running results
Process started >>>
1 2 3 4 5
Reverse the list iteratively
5 4 3 2 1
Reverse the list recursively
1 2 3 4 5
<<< Process finished.
Video: Reversing linked list iteratively and recursively in C++


Saturday, April 19, 2014

Remove Nth Node From End of List in a Singly linked list in C++



Remove Nth Node From End of List  in a Single linked list in C++
For example,
   Given linked list: 1->2->3->4->5, and N = 2.
   After removing the second node from the end, the linked list becomes 1->2->3->5.
   Algorithm:
   Use two pointers *fast and *cur
   1)  Move pointer *fast  N step
   2)  Move pointer *fast and *cur the same step until *fast reaches end
   3) Now *cur point to next will be in the nth node counted from end of list
   4) Use  cur->next=cur->next->next;  to remove nth node from end of list
The code
struct Node *removeNthFromEnd(struct Node *head, int n) 
{
     Node *fast=head;
     Node *cur=head;
     for(int i=0;i<n;i++) fast=fast->next;
    if(fast==NULL) return head->next; //head node need to be removed
    while(fast->next!=NULL){
        fast=fast->next;
        cur=cur->next;
    }
    cur->next=cur->next->next;
    return head;
 }

Complete example code
#include <iostream>
using namespace std;
struct Node {
    int data;
    Node* next;
};
// only for the 1st Node
void initNode(struct Node *head,int n){
    head->data = n;
    head->next =NULL;
}
// apending
void addNode(struct Node *head, int n) {
    Node *newNode = new Node;
    newNode->data = n;
    newNode->next = NULL;
    Node *cur = head;
    while(cur) {
        if(cur->next == NULL) {
            cur->next = newNode;
            return;
        }
        cur = cur->next;
    }
}
struct Node *removeNthFromEnd(struct Node *head, int n) 
{
     Node *fast=head;
     Node *cur=head;
     for(int i=0;i<n;i++) fast=fast->next;
    if(fast==NULL) return head->next; //head node need to be removed
    while(fast->next!=NULL){
        fast=fast->next;
        cur=cur->next;
    }
    cur->next=cur->next->next;
    return head;
 }
 void display(struct Node *head) {
    Node *list = head;
    while(list) {
        cout << list->data << " ";
        list = list->next;
    }
    cout << endl;
}
int main()
{
    struct Node *head = new Node;
    initNode(head,1);
    addNode(head,2);
    addNode(head,3);
    addNode(head,4);
    addNode(head,5);
    display(head);
    cout<<"Remove  the second element from end"<<endl;
    removeNthFromEnd(head, 2);
    display(head);
}

Output
1 2 3 4 5
Remove  the second element from end
1 2 3 5
Video: Remove Nth Node From End of List  in a Single linked list in C++


Friday, April 18, 2014

An example of binary search in C++




Binary search:
1) the array should be arranged in ascending or descending order.
Here using  ascending order
2) In each step,  compares the search key value  to the middle element of the array

Example
double a[]={1.1,1.2, 1.4, 1.6,1.8, 2.0,2.2};
Search 2.0
Create BinarySearch class

code:
#include <iostream> 
using namespace std; 
class BinarySearch //for  ascending order
{
private:
double *Plist;
public:
         BinarySearch(double *list, int listlength);
         void BSearch(int begin, int end, double target);
         ~BinarySearch();  
};
BinarySearch::BinarySearch(double *list, int listlength)
{
Plist= new double[listlength];
for(int i=0; i<listlength;i++)
Plist[i]=list[i];
}
BinarySearch::~BinarySearch()
{
delete []Plist;
}
void BinarySearch::BSearch(int begin, int end, double target)
{
int m;
m=(begin+end)/2;
if(Plist[m]==target)
{
cout<<" The Element   "<<target<<" is found at postion  "<<m+1<<endl;
}
else if(begin>=end){
   cout<<" The Element   "<<target<<" is not found.  "<<endl;
exit(-1);
}
else if(target>Plist[m])
    BSearch(m+1, end, target);
else
    BSearch(begin, m-1, target); 
}

int main()
{
double a[]={1.1,1.2, 1.4, 1.6,1.8, 2.0,2.2};
double target=2.0;
BinarySearch bs(a,7);
bs.BSearch(0, 6, target);
}


Running result:
The Element   2 is found at postion  6
Video: An example of binary search in C++ 

pocketcpp - c++ interface with notepad++



pocketcpp - c++ interface with notepad++, which can be downloaded from:
 http://code.google.com/p/pocketcpp/

pocketcpp  integrates Notepad++ and MinGW Distro (GCC 4.8.1).
For example, I installed it in
C:\Users\jiansen\Downloads\Desktop\software\pocketcpp\pocketcpp
run
Pocket C++.bat
A notepad++ will show up and you  can use F9 key to compile C++ files,  and Ctrl+F9 to execute the compiled program, which can also be seen from Plugins->NPPExec

Change file font size of Notepad++
Settings->Style Configuration-> Global style, set font size 14, font name Arial

Change console font size of Notepad++
Plugins->NPPExec->Change console font

Another alternative  application is IDEOne. You can compile and run C++ (also PHP and more) online using IDEone
http://ideone.com

Video: pocketcpp - c++ interface with notepad++

Understand recursion in C++ programming



Recursion method is widely used in computer programming.  Sometimes it is confusing. In this video a, factorial example is used to study how recursion works in C++ programming.
Example code:
#include <iostream> 
using namespace std; 
int Factorial( int n)
{
int m;
cout<<"n="<<n<<endl;
if( n == 1)
return 1;
else {
  m = n * (Factorial(n-1));
  cout<<"m="<<m<<endl;
       return (m);
       }

int main() //n!=n*(n-1)*.....*2*1

     cout<<"result="<<Factorial(4)<<endl;
 }
Output:
n=4
n=3
n=2
n=1
m=2
m=6
m=24
result=24
You can see
  cout<<"m="<<m<<endl;
is ignored before
m = n * (Factorial(n-1));
 recursion finished, Only n=4, 3,2, 1 are printed out.
After recursion finished,
 cout<<"m="<<m<<endl;
is printed from bottom to top.
Video: Understand recursion in C++ programming

Wednesday, April 16, 2014

Example of intermediate table in many to many relationship in MySQL



For example, in pubmed database, we have article database. An article can have one or more authors and an author can be listed for one or more papers (many-to-many).  The intermediate  table "author_article" table is used to establish this relationship. The diagram is shown as follows:

Command for Creating `author` Table

CREATE TABLE `author` (
`author_id` int NOT NULL AUTO_INCREMENT,
`author_name` varchar(100) NOT NULL,
PRIMARY KEY (`author_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


Command for Creating `article` Table

CREATE TABLE `article` (
 `pubmed_id` int NOT NULL,
 `article_title` varchar(100) NOT NULL,
`journal_title` varchar(100) NOT NULL,
`publication_year` date,
`article_abstract` text,
PRIMARY KEY (`pubmed_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 

Command for Creating intermediate table `author_article` 

CREATE TABLE `author_article` ( 
 `author_id` int NOT NULL, 
 `pubmed_id` tinyint NOT NULL,
`id` int NOT NULL AUTO_INCREMENT,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Once relationships are stored, you can fetch data like below.

SELECT a.author_name, c.article_title FROM `author`
AS a LEFT JOIN `author_article`
AS b ON a.author_id = b.author_id LEFT JOIN `article`
AS c ON b.pubmed_id = c.pubmed_id;

Video: Example of intermediate table in many to many relationship in MySQL

 

Tuesday, April 15, 2014

How to fix the Heartbleed Bug




As you may be aware, a security issue in OpenSSL known as Heartbleed has affected servers and services across the entire Internet.  If you used old version of OpenSSL, there is the potential  that all data including usernames and passwords was leaked. Fixed OpenSSL has been released and now it has to be deployed.
To be safe you should change passwords on any service AFTER it has been updated with new versions of OpenSSL.

Detail of  the Heartbleed Bug:
 http://heartbleed.com/

Fixed OPenSSL:
https://www.openssl.org/news/secadv_20140407.txt

Sunday, April 13, 2014

An MVC example in PHP CodeIgniter



URLs in CodeIgniter: example.com/class/function/ID

    The first segment represents the controller class that should be invoked.
    The second segment represents the class function, or method, that should be called.
    The third, and any additional segments, represent the ID and any variables that will be passed to the controller.

.htaccess should be modified as:

RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]


An MVC example in PHP CodeIgniter
Visit the your site using a URL similar to this: example.com/index.php/blog/
1) Controller:
application/controllers/blog.php

<?php
class Blog extends CI_Controller {

public function index()
{

    $this->load->model('blogmodel');

    $data['query'] = $this->blogmodel->get_last_ten_entries();

    $this->load->view('blogview', $data); }
}
?>


Note: Class names must start with an uppercase letter.
2) View
application/views/blogview.php

<html>
<head>
<title>My Blog</title>
</head>
<body>
    <h1>Welcome to my Blog!</h1>

   Last ten entries:

 <?php echo $query; ?>

</body>
</html>

3) Model
application/models/blogmodel.php

class Blogmodel extends CI_Model {

    var $title   = '';
    var $content = '';
    var $date    = '';

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }
   
    function get_last_ten_entries()
    {
        $query = $this->db->get('entries', 10);
        return $query->result();
    }

    function insert_entry()
    {
        $this->title   = $_POST['title']; // please read the below note
        $this->content = $_POST['content'];
        $this->date    = time();

        $this->db->insert('entries', $this);
    }

    function update_entry()
    {
        $this->title   = $_POST['title'];
        $this->content = $_POST['content'];
        $this->date    = time();

        $this->db->update('entries', $this, array('id' => $_POST['id']));
    }

}

Note: Class names must start with an uppercase letter.
Reference:

PHP CodeIgniter tutorial

Friday, April 11, 2014

PHP CodeIgniter tutorial



CodeIgniter is an open source, agile proven PHP web application framework based on the popular Model-View-Controller (MVC) development pattern, which can be downloaded from:
http://ellislab.com/codeigniter

The detail user guide can be found:
http://ellislab.com/codeigniter/user-guide/toc.html

For installation
1) After you download the package, unzip it and upload to the server. 
2) Open the application/config/config.php file with a text editor and set your base URL
3) If you intend to use a database, open the application/config/database.php file with a text editor and set your database settings, ie. server name, user name and password, database name.

As  CodeIgniter follows MVC modles, there are model, view and controller folders
  • The Model represents your data structures. Typically your model classes will contain functions that help you retrieve, insert, and update information in your database.
  • The View is the information that is being presented to a user.
  • The Controller serves as an intermediary between the Model, the View, and any other resources needed to process the HTTP request and generate a web page

 Video playlist :  CodeIgniter from scratch (total 16 videos)

Monday, April 7, 2014

PHP, upload multiple files and add progress bar



 The difference between upload one file and multiple files in PHP is that we put array in name in
input, example, for upload a single file
 <input type="file"  name="file_single">
for upload multiple files, add [] in name, example
<input type="file" name="file_array[]">
 Complete example for uploading multiple files in PHP:
main.html
<!DOCTYPE html> 
<html>
 <head>
 <meta charset="UTF-8">
 </head> 
<body> 
<form action="upload.php" method="post" enctype="multipart/form-data">
 <p><input type="file" name="file_array[]">
 <input type="submit" value="Upload all files">
 </form> 
</body>
 </html>

upload.php
<?php /
 if(isset($_FILES['file_array'])){
 $name_array = $_FILES['file_array']['name']; 
$tmp_name_array = $_FILES['file_array']['tmp_name']; 
 $type_array = $_FILES['file_array']['type'];
 $size_array = $_FILES['file_array']['size']; 
$error_array = $_FILES['file_array']['error']; 
for($i = 0; $i < count($tmp_name_array); $i++){
 if(move_uploaded_file($tmp_name_array[$i], "test_uploads/".$name_array[$i]))
{ echo $name_array[$i]." upload is complete<br>"; }
 else {
 echo "move_uploaded_file function failed for ".$name_array[$i]."<br>"; } }
 } ?>

About  add upload progress bar:
Video: File Upload Progress Bar Meter Tutorial HTML5 Ajax PHP


Reference:
http://www.developphp.com/view.php?tid=1351

Tuesday, April 1, 2014

Install IIS and run ASP .net in Windows 7

ASP .net in Windows
http://www.w3schools.com/asp/asp_install.asp

Stop Apache if any
Control panel ->Programs ->Programs and Features ->Turn Windows features on or off
Check  Internet Information Services, check ASP ASP.NET under development features as follows and click OK, it will take a few minutes.

Run localhost to check IIS running
http://localhost/

Under
C:\inetpub\wwwroot
create test1.asp
<!DOCTYPE html>
<html>
<body>
<%
response.write("Hello World!")
%>
</body>
</html> 

http://localhost/test1.asp
Output
Hello World! 
Default file for site reference:
http://www.iis.net/configreference/system.webserver/defaultdocument 
To configure a site ( see the following iamge), go to IIS manager, under site, click add site ( for example wwwroot),  Physics path: C:\inetpub\wwwroot, Application pool using  ASP .NET V4.0,(I  found ASP .NET classic has issue to display default page), click Default Document to see a list of default document. I create a default file called Default.asp. ( I copy test1.asp to Default.asp)
http://localhost/
Output
Hello World! 
Video: Install IIS and run ASP .net in Windows 7