Pages

Linux | How to find a program running on a particular port

I was having problem starting the apache, because ubuntu system auto installs the apache2 web server and it starts on the system startup. And every thing is messed up. I know the concepts of what was happening there, but I forgot the commands. So I am writing this post to find it if I ever again ran into the same problem.

sudo netstat | grep 80

Kill pid

The first command will list the programs and their ids that have patterns that match 80, which might be their name or most likely port numbers for netstat command.
Then kill the command with pid command;
them start the lampp again.


sudo /opt/lampp/lampp restart

If you want to see the list of programs you are running 
ps 
ps -nlp 
The second command will show all the programs that are running on the system.

Build a web Application Tutorial Series

Part 1

Introduction
I have watched tons of tutorials to do different things, like php , java, database, etc. I thought may be why don’t I try to write a tutorial about building a simple web application. I will have a little practice of what I want to be perfect in and other starting guys will have some material to learn the basics. And here we go.

Ok. our application will be a simple user login system. A user will come to the site, sign up, then login, view his profile and change his profile, and then logout. That’s it. It sounds so simple, but it took me two or three days to do it from scratch, mostly because I was trying a new way of arranging things so that I could expand it big. It’s a general part of other application because most of the application have user part.

The purpose of this tutorial is
    1. To teach how to start small building application

    2. To give a good overview of object oriented concept

    3. To teach some design concepts

    4. Not to make the reader perfect in anything and leave them to explore

    5. And this is a very fast forward tutorial, assumptions are that you know or can find out the very basic things.

FEATURES
    Signup page    =>

    forget password

    login page    =>

    verify account page

    account update page


Now first legs think of the database part. Since we are using a login/out and profile, we need minimum two tables.
Database
    #users(id, username, password, email)

    #profile(id, user_id, first_name, last_name, dob, gender)

The queries for creating the database are as follows.

CREATE DATABASE IF NOT EXISTS `user`;
CREATE TABLE `user`.`users`(
            `id` int(11) NOT NULL  AUTO_INCREMENT,
            `username` varchar(64) NOT NULL UNIQUE,
            `password` varchar(128) NULL,
            `email` varchar(64) NOT NULL UNIQUE,
            PRIMARY KEY(id)
        );
create table `user`.`profile`(
    id int(11) not null auto_increment,
    user_id int(11) not null unique,
    first_name varchar(64) not null,
    last_name varchar(64),
    dob Date,
    gender varchar(64),
    primary key(id)
);
ALTER TABLE user.profile ADD FOREIGN KEY (user_id)
    REFERENCES user.users (id)    on update cascade on delete cascade;

The directory structure is as follows
Directory_Hierarchy
    /

        common/
                    base.php
                    header.php
                    footer.php
                    sidebar.php

        configs/
                    constants.php

        forms/
                    abstract.form.php
                    interface.form.php
                    form.login.php
                    form.signup.php
        models/
                    interface.model.php
                    class.user.php

        index.php
        signup.php
        login.php
        forgot_password.php
        verify_account.php
        account.php

        public/
                    images/
                    scripts/
                            script.js
                    styles/
                            style.css


Notice, there are four directories. The commons directory is where the mostly common codes used in several pages will go. All most every page will include them for completing the html. The configs folder is for the files which describes the configurations of our application and those information's, which we might need throughout our application. The models folder is for storing the model classes, like user or the profile, or when you expand it, say item, or some other entity. The form folder is for storing the form handling classes. It is not necessary to separate forms or models for your application to work, but you could never build a large application from that procedural approach. It is a design practice to separate concerns whenever you can. For forms, in frameworks like Zend or some other, there are very good form helpers, which provide lots of easy ways. The approach here is influenced by those concepts. Then the public folder stores all your images , styles, and scripts.
Lets start coding with the commons folder. Lets edit base page like this.
<?php
//session starting should be done early before anything
    session_start();     //including the side wide constants     include_once('configs/constants.php');     // Database handling codes, initiating     try {         $con_string = "MySQL:host=".DB_HOST.";dbname=".DB_NAME;         $db = new PDO($con_string, DB_USER, DB_PASS);     } catch (PDOException $e) {         echo 'Connection failed: ' . $e->getMessage();         exit;     } ?>

Notice, you should include this page on every of your page where you write your application logic. This page handles the session which is to be done on top, and then initiates a php database connection. The header , footer , and sidebar pages are where you write your header footer and sidebar codes. In this first tutorial, we are gonna write some simple working codes.
<!DOCTYPE html>
<html>
    <head>
        <title>     Tutorial | <?php echo $title; ?></title>
        <?php 
                if(isset($style)){
                    echo "<link type='text/css' rel='stylesheet' href='$style' />";
                }
        ?>
    </head>
    <body>
        <div id="wrapper" >
            <div id="header" >
                <?php //echo $header_content?>
            </div>


<?php            ?><div id="footer">
                            <?php echo $footer; ?>
                        </div>
            </div><!-- wrapper -->
    </body>
</html>


It’s a good design practice to define some sitewide constants, which we will use throughout our site in the file configs/constanst.php  -------------------------------------
<?php
    define('DB_HOST', 'localhost');
    define('DB_USER', 'root');
    define('DB_PASS', '');
    define('DB_NAME', 'user');
?>

----------------------------------------------
Now lets start writing our application logic. Lets decide what should happen when the user first time visits our application. There may be two conditions, one he is logged in and another, he is not. For now lets redirect the unlogged user to signup page and the logged in user to account page.

<?php
include_once('common/base.php');
//if the user is not logged in
if(empty($_SESSION['user_id'])){
    header('Location: ./signup.php');
    exit;
}else{
    header('Location: ./account.php');
    exit;
}
?>

---------------------------------------------
So, What will we do on the signup page. One thing is clear that the signup page must have a form for taking the user data. You could submit the form in another page by defining action to another page, but it is not a good practice to increase the number of pages without any reason if you can do it in single page. Here is what I have done. If it is a normal page request, just show the signup form. In the form is submitted, then validate the form, and if the form is valid then create a new account and register the user. Display some congratulation message. Otherwise, if there is so me error, show the error message and the form again. It seems like there is lots of work to do. ------------------------------
<?php
include_once('common/base.php');
/*
*check if the form is submitted, and verify and register
*if not then print the form
*/

$title = "signUp";
include_once('common/header.php');
include_once('./forms/form.signup.php');
$form = new SignupForm($db);
if($form->read()){
         //echo "The form is submitted.";
         if($form->isValid()){
                 //echo "<br/>The form is valid";
                 $fields = $form->getArray();
                 include_once('./models/class.users.php');
                 $user = new UserClass($db);
                 if($user->insert($fields)){
                         echo "<div id='note'>
                                         <p>Congratulation. You are registered.</p>
                                         <p><a href='./login.php'>Login</a></p>
                                     </div>";
                 }
         }else{
             //echo "<br/>form is invalid.";
             $form->display();
         }
}else{
     //echo "The signup is not posted.";
     $form->display();
}

$footer = "copyright &copy; 2012 reserved to rajan prasad upadhyay.";
include_once('./common/footer.php');

?>

--------------------------------------------
It may seem like a pseudo code that form->read(), if(valid) etc, but its not, and its by design.. You can download the code from my github account, I will just concentrate on the process of developing and the logic behind the work.  You can see an include of a form.signup.php where our form class lies. separating the concern of the form to a separate class dedicate to it is a good idea, and lots of frameworks in some way encourage to do so. Similarly, there is also a user class in the models folder, which actually deals with the interaction between the controller and the database of user object. This approach of coding is more practical.
In the second part we will concentrate on the beauty of the application and add some more functionality if only I get some response.
Sorry, Blogger doesn't support file uploads
Please:
1) Change to a different blog provider, then;
2) Save the draft
3) Change to HTML view, then back to the view you were on.

Your files will be ready to upload then.
Download The source files here

Interview Questions LeapFrog

I was in leapfrog this Tuesday, and in spite of I was confident how to deal with them, I got nervous and made lots of silly mistakes. Though I think the Interview was great and I am surely selected. I love tuff interview, especially when I managed to answer some of the questions. Some of the questions I remember are given below:

  • Tell us something about yourself?

This question is intended to forget the initial nervousness of the interviewee. Just tell them your name, your permanent address, school from where you passed SLC. and +2 or so, your scores . Your interest, hobbies, any social good quality etc.

  • What is your interest, …. Why…. your passion etc?

Tell them something related to your job. eg programming. I just find it interesting, or I enjoy solving the problems using programming…etc.

  • What do you like programming the most; favorite language, which type of technology(system programming, application development, web application, web designing/development, etc) why?
  • Any one special feature of the language you liked the most.
  • What is web technology?
  • What is three tiered architecture?
  • Difference between application development and web application development?
  • Difference between Overloading and Overriding?
  • Which of the two is used with the concept of inheritance? How?
  • Describe the concept of OOPS so that a less technical person would understand it clearly?
  • What is open source technology?
  • Which operating systems did you use?
  • Name of the linux version (specific) You used?
  • Name of the person who made linux?
  • Do you have the concept of file permissions in linux? Describe?
  • Why do you switch to windows? (3d games and .net programming)?
  • What do you mean by SDLC in software engineering?
  • What are its types?
  • Which one of them is the best, if you have to recommend one to some one?
  • What are the criteria for choosing a particular model or approach for a software project?
  • What do you mean by version control? Have you used one? Explain?
  • What is the backbone of github?
  • Did you document your codes?
  • Why do you need documentation?
  • How do you document your codes? I mean writing in notes or you use any tools for documentation?
  • Explain touple and list? Immutable and mutable.
  • If a client(technical) come to you and explains his desire to do a software project in python. You or your company only have java experts. You want the project. How will you convince the client to do his project in java. You have to?
  • Do you have any plans for your further studies, I mean, most people from pulchowk start their GRE right after their final exams, an leave with  in one year, How much you can stay here? (Previously, I planned to stay here for one year, but if you want any commitment, I could stay for say one and a half year to two years not more than that)
  • What do you expect from us?
  • Anything you want to ask us? any information?
  • Thanks , we will call you if you got listed. Thanks? Send the next person inside?

Some things to consider while developing a code project

Intruduction
Hello world. Have you ever worked on a code project yet. If not I bet you are planning to develop a project probably a software application, web development etc. And I can say that you are a good developer who always wants to find out new ways to work better.

Description
My first project was not a very great one and I have no knowledge of designing or best practices what so ever. I studied and coaded and studied and coaded and I did it. I was happy about making it work the first time. But as my second year in BE came, that amount of knowledge was not enough. The size and requirement of project got highly increased, and the syntax level of knowledge was totally not sufficient even for starting the second project in C++. Here are a few Requirements I felt...

  • A version Control System
  • Modular Design practices/Concepts
  • Some short of design Patterns
  • Need of Work Division and some sort of iterative process/steps formation
  • ...

I did not have even heard of neither version control system, nor of Design patterns but I was thinking that there must be something because I am feeling it difficult to manage, Others should also feel the same. I messed up my codes four or five times where I could not undo it and I have to start a new project from the beginning. That was totally time consuming and tedious. While going on coding, the project grows too big and deep that I start forgetting the main logic behind the high level project design, and I even forget Why I am working on this particular module/What it had to do with the project.
Here are some of the things I do while developing a code project.

  • Always divide your work into smaller modules
  • Start and complete one module before you go to the next
  • Properly test it

The IP Warrior


Learn how the Ip packets work in the computer and the internet. What happens when you click a link in the browser to the rendering of the page. Here is an awesome video to show you what happens

My Artificial Intelligence Project (The Routine Generator)

Click here for downloading the java project (The routine generator). The code is quiet simple enough that you will learn it easily. Best of luck

However due to the polularity of this page, i am going to descrive the concept of planning of the program in brief in a abstract way, just for helping the interested ones about general concepts of arranging the components.

Modified Eight Queen Problem

Problem
Suppose that you have a chess board and eight queens. The squares of the chess board being (1,1) to (8,8). Now you have to place the queens such that they could not attack eachother(no queen should be able to attack any other).

Solution
/*
 * File:   main.cpp
 * Author: power
 *
 * Created on January 19, 2012, 2:38 PM
 */

#include <cstdlib>
#include <iostream>
using namespace std;
class point{
public:
    point(){
        this->x=0;
        this->y=0;
    }
    point(int x,int y){
        this->x=x;
        this->y=y;
    }
    int x;
    int y;
    void setx(int a){
        this->x=a;
    }
    void sety(int a){
        this->y=a;
    }
    void display(){
        cout<<"("<<x<<","<<y<<")";
    }
}; 

point* p(char x,char y);
void solution(point *p,int size,point *store[],point *a[]);
bool nonattack(point *p, point *q,int size);
void display(point *p);
void solve(point*[]);
bool chkPredefined(point *c,point *pre[]);
int main(int argc, char** argv) {
    point *po[8]={p('1','8'),p('2','4'),p('3','C'),p('4','D'),p('5','E'),p('6','F'),p('7','G'),p('8','H')};
    solve(po);
    return 0;
}
bool chkPredefined(point *c,point *pre[]){
    point *q=c;
    for(int i=0;i<8;i++){
        if(pre[i]->x!=0){
            if(pre[i]->x!=q->x){
                //cout<<"Returning false1"<<endl;
                return false;
            }
        }
        if(pre[i]->y!=0){
            if(pre[i]->y!=q->y){
                //cout<<"returning false2"<<endl;
                return false;
            }
        }
        q+=1;
    }
    return true;
}
void solve(point *a[]){
    point p[8];
    point *store[8];
    //initialization
    for(int i=1;i<=8;i++){
        p[i-1].x=i;
    }
    solution(p,8,store,a);
    //return 0;
   
}
void solution(point *c,int size,point *store[],point *a[]){
    static int st=0;
    if(size==0){
        //display(c-8);exit(1);
        return;
    }else{
        int i=0;
        while(i++<8){
            c->y=i;
            //recdisplay(c,8);
            //display(c);return;
            //display(c);return;
            //cout<<c->y;
            //continue;
            solution((c+1),size-1,store,a);
            if(size==1)
                if(nonattack(c-7,(c-6),7)){
                    if(chkPredefined(c-7,a)){
                        cout<<st++<<" :";
                        display(c-7);
                    }else{
                        continue;
                    }
                }else{
                    continue;
                }
           
        }
    }
}
bool nonattack(point *c, point *others,int size){
    /*returns true if queens are in non attacking condition*/
   
    if(size==0){
        //cout<<size<<endl;
        //recdisplay(others-1,1);exit(1);//display last one
        return true;
    }else{
        int y=c->y;
        int y1=others->y;
        int x=c->x;
        int x1=others->x;
       
        if(y==y1){return false;}//attack
        if((y1-y)==(x1-x)){return false;}
        if((y1-y)==(x-x1)){return false;}
        if(nonattack(c,(others+1),size-1)&& nonattack(others,others+1,size-1)){
            return true;
        }else{
            return false;
        }
    }
}
void display(point *p){
    point *q;//=p;
    q=p;
    for(int i=0;i<8;i++){
        cout<<"("<<q->x<<","<<q->y<<")  ";
        q=q+1;
    }
    cout<<endl;
}
point*  p(char x,char y){
    //cout<<x<<y<<endl;
    int xt=0,yt=0;
    if(x>'0'&&x<='9'){
        xt=x-'0';
    }
    if(y>'0'&&y<='9'){
       yt=y-'0';
    }
    return new point(xt,yt);
}

Text to audio


 Introduction
 One day while sitting and reading a story on my laptop, it occurred to me that how awesome it would be if instead of reading all the text word by word, the computer would read it for me. Even it could generate a audio file (eg:- story.wav ) so that I could transfer it on my mobile and hear it whenever I am free without having to open my Laptop. I could use the same Audio as a dialog for my animation project.
Solution
Well, obviously, the next step was to google, search learn try then again search. There were several interesting solutions. One of them is the command called
espeak
To read a file type,( cd to the directory )
espeak <filename>
The general and simple syntax of the command is
espeak -v <voice_tone_name> -s <speed_per_minute> -f <text_file_name> -w <wave_file_name_desired>
Open a terminal, and type in the command to see/hear the magic.
For command documentation and options
espeak -h
 You can see the list of voices with
espeak --voices
This command has proved to be a great fun to me and hope you will enjoy using it too.

Assignment 3 | A sample firewall rules declaration example



#---------start of pf.conf------------------
intface="em0"
tcp_pass={ 80, 25, 22 }
udp_pass={ 110, 631 }
 table <good_guys> persist file  "/etc/good_guys"
 table <bad_guys> { 192.168.56.102/24 }

ASSIGNMENT 1 LAB 4




Tables provide a way for incresing the performance and flexibility of rules with lare number of sources and destinatio n addresses.
    Deceleration
        table <local> { 192.168.56.10/24,192.168.9.0/32 }
        table <good_guys> persist file "/etc/good_guys"
    Rules