Monday, 15 April 2013

Java: Insert values into table using prepared statement Derby


Following method adds a record to the database table:
  
public void addPerson(Person p) {
        if (p == null || p.getName().equals("")) {
            return;
        }

        String name = p.getName();
        String address = p.getAddress();
        String phone = p.getPhone();

        Connection con = null;
        try {
            con = getConnection();
            if (con != null) {

                String sql = "INSERT INTO APP.ADDRESS_BOOK("
                        + "NAME,"
                        + "ADDRESS,"
                        + "PHONE) "
                        + "VALUES(?,?,?)";

                PreparedStatement pStmt = con.prepareStatement(sql);

                // Set the values
                pStmt.setString(1, name);
                pStmt.setString(2, address);
                pStmt.setString(3, phone);

                // Insert
                pStmt.executeUpdate();
            }
        } catch (SQLException ex) {
            Logger.getLogger(PersonDAO.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println(ex.getMessage());
        } finally {
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException ex) {
                    Logger.getLogger(PersonDAO.class.getName()).log(Level.SEVERE, null, ex);
                    System.out.println(ex.getMessage());
                }
            }
        }
    }

Java: how to check in servlet which html button was pressed


We can define two buttons in the html page:

<input type="submit" value="Add" name="addbutton">
<input type="submit" value="Search" name="addbutton">



Then in the servlet in the get or post method get the values for the buttons. Button pressed will have a value and the one not pressed will be null:

 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String add = request.getParameter("addbutton");
        String search = request.getParameter("searchbutton");

        if (add != null) {
            response.sendRedirect("addperson.html");
        } else if (search != null) {
            response.sendRedirect("searchperson.html");
        }
    }

Java: Connect to Database (Derby)


public class PersonDAO {

//AddressBookDB is the database name to which we want to connect
    private final String url = "jdbc:derby://localhost/C:/Users/Administrator/.netbeans-derby/AddressBookDB";

    PersonDAO() {
    }

    private Connection getConnection() {
        Connection con = null;
        try {
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            con = DriverManager.getConnection(url, "test", "test"); // test, test are the //user name and password for the database.
        } catch (Exception e) {
            System.out.println("Exception occured while connecting to the database: " + e.getMessage());
            e.printStackTrace();
        }
        return con;
    }
}

Thursday, 20 December 2012

Written Numerous Times but Still Not Believed:



Written Numerous Times but Still Not Believed:
Having competed years of democracy and “truly” democratic system, people have-not yet been convinced it’s the best system available. The simple answer is the study of this government’s performance on vital matters like economy, governance, peace and development. Surely the results are not much encouraging.

The history has shaped numerous systems and the great Empires have been built and declined in the vicissitudes of time. What is commonly concluded that the better systems prevail, like today’s democracy and democratic systems have developed the limits to control the world. Undoubtedly it has become a benchmark and every other country is trying to imitate, in the suitable way it can.

Pakistan as a case study has done same it has been democratized repeatedly to move forward and even the anti-democratic agents have used the democratic skin to accumulate the rationale for their rule. In today’s time the countrymen have fought and won the democratic system for them, but with a capital “BUT”. Democracy is not an end in itself but it’s only a platform to acquire development, equity, justice and so on. The capital “BUT” suggests that this system didn’t help us at all to develop anyway. The proponents argue the continuity of system to deliver etc. but practically speaking the state of matters has not even stabled on the point where “non-truly” democratic system was wrapped. It has gone far worse and dejection prevails the horizons.

The purpose here is not to scream out political criticisms or hurl acquisitions, but to gauge some reason of situation. In my view all systems developed over time thoughtfully have enough good reasons to deliver but systems are not self start or automatically run. The people if are dishonest or disloyal, the system would collapse, this is exactly what happened to the Romans, the Bezentinians and Muslims to say. The ball is in our court. The exact time for us to separate ourselves from blind race of materialism. Honesty is hard earned wealth, truth pays late but worth’s believing. Satisfaction is the bride for those who choose tough ways to lead their lives. Our system is too good to believe, we have huge machinery to implement our policies and develop. What we need is only to be vigilant against what we should not do while walking on road, travelling, dealing with the family of God (the people around).

Usman Akhlaq
white.snowpeaks@gmail.com

Wednesday, 28 November 2012

Spiritual Policy Planning


A plethora of articales written and speeches have been delivered on the importance of spiritual development along with the development in the physical world. Scholars having thoughts and ideology of this “style” often have a religious disposition. This is the reason why many modern people don’t consider it worthwhile as we have made religiosity a separate entity. But this matter is a grave one and deserves a serious thought in real life.

If we look at the ramifications of not considering spiritual building in our society we realize that this negligence has wreaked havoc in our society. Today our nation has an obvious outlook of a crowd, or a mod exaggeratingly. There are several reasons for this menacingly odd situation, all spiritual in nature. This is not because we have less developed roads and buildings, less jobs or less education, rather because we have less clarity of our objectives, and aimless beings. Nation states are made by common ideology, sacrifice, law abidingness and truthfulness. All these qualities are spiritual in nature not material and require justice, equality, opportunity and inspiration to flourish. Unless and until these trends hold ground in a society, it can’t prosper.

It’s the philosophy of spiritual development that compels individuals to become moral beings. Spiritual strength makes men to overcome the material hurdles and keep working honestly on their ends otherwise they are lured and tempted to mould their ambitions towards wealth accumulation as they enter practical life. This is why the innocent and competent students wishing to join medical for helping miserable humanity get status sick after passing out of medical colleges and same for army officers and the likes. There may not be much difference in the actions of a spiritual and material being but difference of view as what a materialistic man does for his personal gain, a spiritually developed man dose the same for the betterment of humanity. When the stress of society is upon the wealth as the social symbol of superiority then every individual would enter the same race even unknowingly.

The question arises what ought to be done on government and social level. I leave this question unto you to think, to ponder and prove to yourself because as much we think about a matter, its importance its reality is engraved in our heart to help change us for ourselves.

Usman Akhlaq
(white.snowpeaks@gmail.com)

Saturday, 24 November 2012

Java: Converting millisecond to hours and minutes


I was looking at the way and found it in the stackoverflow website:

public String convertMS(float ms) {
   int seconds = (int) ((ms / 1000) % 60);
   int minutes = (int) (((ms / 1000) / 60) % 60);
   int hours = (int) ((((ms / 1000) / 60) / 60) % 24);


String sec, min, hrs;
    if(seconds<10)  sec="0"+seconds;
    else            sec= ""+seconds;
    if(minutes<10)  min="0"+minutes;
    else            min= ""+minutes;
    if(hours<10)    hrs="0"+hours;
    else            hrs= ""+hours;


   if(hours == 0)  return minutes+":"+seconds + " MM:SS";
   else    return hours+":"+minutes+":"+minutes + "HH:MM:SS";

}

Here is the conversion:


x = ms / 1000
seconds = x % 60
x /= 60
minutes = x % 60
x /= 60
hours = x % 24
x /= 24
days = x

Monday, 19 November 2012

Android: Starting new Activity with custom object through Intent


public class TaskActivity extends Activity
{

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.task);
Intent i = getIntent();
Task task = (Task) i.getSerializableExtra("task");

if (task != null) displayValues(task);
configureButtons();
}
}


For the part that how it gets this object from the intent and how was it set to the intent please view my previous post . This post is in continuation of the previous

Android: OnItemClickListener Example in a ListView


public class TaskListActivity extends Activity implements OnItemClickListener
{
private TaskListAdapter adapter = null;

private ArrayList<Task> taskList = null;

private ListView list = null;

@Override
public void onCreate(Bundle savedInstanceState)
{

                super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
setContentView(R.layout.task_list);

fillTaskList();
adapter = new TaskListAdapter(this, taskList);
list = (ListView) findViewById(R.id.task_listview);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
TaskListAdapter adp = (TaskListAdapter)parent.getAdapter();
Task task = adp.getItem(position);
System.out.print(task.getAddress());
Intent i = new Intent(view.getContext(), TaskActivity.class);
i.putExtra("task", task);
this.startActivity(i);
}
}

Sunday, 18 November 2012

Android: Center align a button in a Linear layout xml

            <TableRow
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:weightSum="1" >

                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:layout_weight="1"
                    android:weightSum="1">

                    <Button
                        android:id="@+id/working_hours_exit_btn"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:layout_weight=".2"
                        android:background="@drawable/exit"
                        android:hint="@string/working_hours_exit_btn_hint" />
                </LinearLayout>
            </TableRow>

Saturday, 17 November 2012

Randomly


Since several years I have been witnessing the passing of time getting swift day by day, night to night. All that discussed is that time has become quick, much quick indeed. The people who have experienced the slow times and the calmness associated can only take a deep sigh to recall the past but cannot alter their schedules and activities to re-attain that grace, lost. Actually it can be possible, but certainly on a cost.

First of all we need to check and think what has caused such an overwhelming change. The answer is that the number of increased activities has rendered this happen. Today in every walk of life people have several things to deal with. To the foremost is the mobile or the cell phone (rightly christened in both cases). Every single person receives 20-200 written messages daily and frequent calls from people all over the society and all around the world, every caller having his matters and dealings. This implies in simple as that u have to work for all those people in some manner or the other as all have contacted you for some of their personal matters, that they feel you can help in.

Second in the row is the easy access to the newest appliances that have been made to make your life easier. It will be quite satirical to say but the reality is that most of the people (me included) press their clothes because an educated Englishman has invented the Iron. Most of the government institutions send you to the photocopier not because they want to solve your problem but for the reason that . . . . . . . they don’t know themselves exactly. We are using different perfumes, cosmetics, soaps, shampoos and all of different brands available at distant and different stores. Quite interestingly men (and the better half of course), living at this end of city get their desired shopping form the other end and vice versa. People in the twin cities have their favorite mechanics, hotels and shopping markets in their twin city, sadly not in their own.

Thirdly the rise of urban societies has created uncountable opportunities for the people of every class and section, be him a student, businessperson, graduate seeking a job and whatsoever. A student (be him of primary or a university) has uncountable educational institutions and fields to be chosen from. And same is for the other segments.

All what we are doing must not be for its sake but purposeful, all these activities must be selfless and disciplined. In fact this is the materialistic and capitalist society in which everything we are doing or wanting to do is for some sort of materialistic gain. Where this factor comes in the calmness, serenity, beauty and satisfaction excuses itself. Although the point remains that we have made our lives difficult in these manners that needs to be reconsidered and pondered deeply by every individual, what for am I running (like a horse), but the other more sophisticated and spiritual subject lays here. Fate is we destined for, nothing more nothing less, no one ever carried anything from the world then such a haste, greed and efforts for what? When the effort is objective the person remains calm, and when the end becomes the objective he gets frustrated, and efforts respite. The roles we are given must be played well instead of longings for the other roles. Experience is that when you make your position your passion, you become satisfied of life and the Nature recognizes your selflessness in its own manner, making you different and superior to all others seeking promotions.

(Usman Akhlaq)
white.snowpeaks@gmail.com

Thursday, 4 October 2012

Ubuntu Commands

Clear terminal Screen: clear

Shutdown command frrom Terminal: shutdown -h now

Monday, 1 October 2012

How to check instances of the MS SQL Server on the local machine

If you have installed the SQL Server 2008 client utilities, you can get a list of the DB Engine instances on the local computer using the SQL Server PowerShell provider.

Launch the Windows Run... command and specify sqlps. That will open a window that looks like a command prompt window, but is a PowerShell window that has loaded the SQL Server PowerShell provider. You should be sitting on a prompt:

PS SQLSERVER:\>

Run these commands:

cd SQL\localhost
dir

That will display the instances on the local computer. If you have a default instance, it will be displayed with the name DEFAULT.

For example, when I do that on my computer with a default and named instance, the dir returns:

Instance Name
-----------------
DEFAULT
TESTINST

Thursday, 9 August 2012

Java: Adding days to a date

package basics;

import java.util.Calendar;
import java.util.Date;

public class DateIncrementer
{

    public static Date addDays(Date date, int days)
    {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, days);
        return cal.getTime();
    }

    public static void main(String[] args)
    {
        Date currentDate = new Date();
        int days = 2;
        Date date = addDays(currentDate, days);

        System.out.println("Current Date = " + currentDate + "\nNew date = " + date + "\nDays added = " + days);
    }
}

Tuesday, 31 July 2012

Friday, 27 July 2012

Converting char to String in Java

public class ConvertCharToString {
 
 public static void main(String[] args) { 
        String name = "Sardar"; 
 
        //get the first character from the string
        char firstChar = name[0];
        // convert the character to string again
        String temp = Character.toString(firstChar);

        // check if the char is converted correctly 
        if ( "S".equals(temp) )
        {
            System.out.println("String Matched");
        }
     }
}

Friday, 13 July 2012

Count and Display non empty lines in a file Java

Count and Display nun empty lines in a file Java

public class FileLineCounter
{
    public static int countAndDisplayNonEmptyLines(String path) throws IOException
    {
        int lineCount = 0;
        InputStream is = null;
        try
        {
            is = new FileInputStream(path);
            InputStreamReader in = new InputStreamReader(is);
            BufferedReader _input = new BufferedReader(in);

            String line = _input.readLine();
            while ( line != null )
            {
                if ( !line.trim().isEmpty() )
                {
                    System.out.println(lineCount + ". " + line);
                    lineCount++;
                }
                line = _input.readLine();
            }
        }
        finally
        {
            if ( is != null )
                is.close();
        }
        return lineCount;
    }

    public static void main(String args[])
    {
        try
        {
            countAndDisplayNonEmptyLines("C:\\Users\\Desktop\\help.log");
        }
        catch ( IOException e )
        {
            e.printStackTrace();
        }
    }
}

Get words or characters from a string Java

Get all the words in a string in a simple java program.

  public List  getWords(String line)
    {

     char delimiter = ' ';
     StringTokenizer tokenizer = new StringTokenizer(line, delimiter );
     if ( tokenizer == null )
            return null;

     List result = new ArrayList();

     while ( tokenizer.hasMoreTokens() )
           result.add(tokenizer.nextToken());

     return result;
    }


Count number of Characters in a word

public static int countCharacters(String str)
    {
        int charCount = 0;

        if ( str == null || str.trim().isEmpty() )
            return charCount;

        int length = str.length();
        for ( int i = 0; i < length; i++ )
        {
            if ( str.charAt(i) != ' ' )
                charCount++;
        }
        return charCount;
    }


public static void main(String[] args)
{
        String word = "LI FE";
        System.out.println("Number of characters in '" + word + "' = " + countCharacters(word));

}

Counting number of spaces at the beginning of the string JAVA

Count the number of spaces at the beginning of a string in a Java program
   
private int countSpaces(String s)
    {
        int spaceCount = 0;
        if ( s == null || s.trim().isEmpty() )
            return spaceCount;

        int length = s.length();
        for ( int i = 0; i < length; i++ )
        {
            if ( s.charAt(i) == ' ' )
                spaceCount++;
            else
                break;
        }
        return spaceCount;
    }

Thursday, 5 July 2012

Sorting List or Lists in Java

Sorting a List> using Collections.sort(List, Comparator)
Example Program:

List> persons;

Collections.sort(persons, new Comparator>()
        {

            @Override
            public int compare(List o1, List o2)
            {
                if ( o1 == null || o2 == null || o1.size() == 0 || o2.size() == 0 )
                    return 0;

                Person item1 = o1.get(0);
                Person item2 = o2.get(0);
                if ( item1 == null )
                {
                    int size = o1.size();
                    for ( int i = 1; i < size; i++ )
                    {
                        item1 = o1.get(i);
                        if ( item1 != null )
                            break;
                    }
                }
                if ( item2 == null )
                {
                    int size = o2.size();
                    for ( int i = 1; i < size; i++ )
                    {
                        item2 = o2.get(i);
                        if ( item2 != null )
                            break;
                    }
                }
                Date d1 = null;
                Date d2 = null;
                if ( item1 != null )
                    d1 = new Date(item1.getTime());
                if ( item2 != null )
                    d2 = new Date(item2.getTime());
                int result = 0;
                if ( d1 != null && d2 != null )
                {
                    if ( d1.before(d2) )
                        result = 1;
                    else if ( d1.after(d2) )
                        result = -1;
                }
                return result;
            }

        });

Monday, 19 April 2010

Latex

How to use Latex and some commands are listed in this section.

Newline : \newline
Making a section :
\section{Write your heading for the section}
\label{sec:givenametothesection}
Making a subsection :
\subsection{Write your heading for the subsection}
\label{sec:givenametothesubsection}
Making Bullet Points :
\begin{itemize}
\item Write your first bullet point here
\item Write your first bullet point here 
\end{itemize}
Ordered list by number :  
\begin{enumerate}
\item Write your first bullet point here
\item Write your first bullet point here 
\end{enumerate}

Thursday, 15 April 2010

Linux Commands

Search in Terminal: find . -exec grep "Words to be Searched" '{}' \; -print
Checking the Running Processes:
top
Check the current directory Path: pwd
List all the files in the current directory: ls
View a text file in the terminal: cat file_name
Goto previous Directory: cd ..
Goto home: cd ~
Remove File or Folder : rm filename OR
rm directory name
Remove non empty Folder : rm -r directoryname
Removing everything from the directory without warning : if you are inside the directory then use
rm -rf * OR
rm -rf ./*
Deleting Hidden Files : rm –rf .??*

For help or more information about rm use:
info rm
man rm
rm --help
Find a text: There are different commands that can be used to find text
1. find . -exec grep "Text to be searched" '{}' \; -print
How to open / view a Pdf from console:
1. gpdf filename.pdf
2. kpdf filename.pdf
3. xpdf filename.pdf
4. evince filename.pdf

Extract .tar.gz files:

tar xvf packagename.tar.gz

Decompress .gz files:
gunzip file.gz
 
setting a file as executable: 
sudo chmod +x filename
 

Thursday, 19 November 2009

Emacs Commands

Select: keep the cursor in the right place from where to copy then press
ctrl space and then use arrow keys to select text of any length.

Copy: alt + w

Cut: ctrl + u

Undo: ctrl + _
OR
ctrl + x u

Paste: ctrl + y
Select all: ctrl + x h
Indenting region: Select the region or the complete text and then type the following command in the mini buffer.
indent-region

Accessing Mini Buffer: Mini buffer can be accessed by different commands which are as follows:
1. press meta key OR
2. alt + x
3. esc + x

Kill line: ctrl + k
this command will kill the complete line following the cursor. A line can be killed and the pasted on another place.

Save: ctrl + x + s

Open File: ctrl + x + f

Open two(2) vertical buffers: It can be done by multiple commands

1. f2 2
2. ctrl + x 3

Open more then two(2) vertical buffers:
ctrl + x 3 
Open two(2) horizontal buffers: ctrl + x 2

Switch From one to the other Buffer: ctrl + x o

Keep one buffer and close all others:
1. f2 1.
2. ctrl +x 1

Syntax Highlighting: goto options in the menu bar and select the first option "syntax highlighting (Global Font Lock Mode)"

Commenting Multiple lines: first select the lines and then press ctrl + cc

Search: press ctrl + s and then type the word in the mini-buffer. Press ctrl + s and it will go to the found word. pressing ctrl + s will go to the next similar word.

Move one(1) char Backward: ctrl + b

Move One(1) char Forward: ctrl + f

Move One(1) Word forward:
1. esc + f
2. Alt + f

Move One(1) Word backward:
1. esc + b
2. Alt + b

Replace all next occurrences of a string: 
Type the command: query-replace
Enter the string to be replaced and then substitute. This will replace all the next occurrences of the string to be replaced. 

Close Emacs: ctrl + x + c

Compile C++ Program within Emacs: Perform the following commands
1. Atl+x  Or esc x (To access mini buffer)
2. compile
3. g++ -o anyname program_name.cc