Monday, February 23, 2015

How to create a maven project

mvn -X  archetype:generate -DarchetypeArtifactId=maven-archetype-quickstart -DgroupId=com.hordine  -DartifactId=hordineCmdTwitter
 
 
mvn eclipse:eclipse
 
 
mvn package
 
mvn clean install  


Thursday, February 12, 2015

Parsing JSON string in Java

Here is the fully working and tested corrected code:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ShowActivity {


  private final static String JSON_DATA =
     "{" 
   + "  \"geodata\": [" 
   + "    {" 
   + "      \"id\": \"1\"," 
   + "      \"name\": \"Julie Sherman\","                  
   + "      \"gender\" : \"female\"," 
   + "      \"latitude\" : \"37.33774833333334\"," 
   + "      \"longitude\" : \"-121.88670166666667\""
   + "    }," 
   + "    {" 
   + "      \"id\": \"2\"," 
   + "      \"name\": \"Johnny Depp\","          
   + "      \"gender\" : \"male\"," 
   + "      \"latitude\" : \"37.336453\"," 
   + "      \"longitude\" : \"-121.884985\""
   + "    }" 
   + "  ]" 
   + "}"; 

  public static void main(final String[] argv) throws JSONException {
    final JSONObject obj = new JSONObject(JSON_DATA);
    final JSONArray geodata = obj.getJSONArray("geodata");
    final int n = geodata.length();
    for (int i = 0; i < n; ++i) {
      final JSONObject person = geodata.getJSONObject(i);
      System.out.println(person.getInt("id"));
      System.out.println(person.getString("name"));
      System.out.println(person.getString("gender"));
      System.out.println(person.getDouble("latitude"));
      System.out.println(person.getDouble("longitude"));
    }
  }
}
 
 
 
 
Here's the output:
C:\dev\scrap>java -cp json.jar;. ShowActivity 1 Julie Sherman female 37.33774833333334 -121.88670166666667 2 Johnny Depp male 37.336453 -121.884985
 

Wednesday, February 11, 2015

Parse JavaScript with jsoup

Document doc = Jsoup.parse(html);

Element script = doc.select("script").first();

Sunday, February 8, 2015

how to extract zip file in linux

Use unzip command:


Code:
unzip file.zip
many time unzip is not installed by default so install it before using it, use rpm or apt-get/yum command to install unzip

How to open link in new tab on html?

Set the 'target' attribute of the link to _blank:

<a href="#" target="_blank">Link</a>
 
Edit: for other examples, see here: http://www.w3schools.com/tags/att_a_target.asp

(Note: I previously suggested blank instead of _blank because, if used, it'll open a new tab and then use the same tab if the link is clicked again. However, this is only because, as GolezTrol pointed out, it refers to the name a of a frame/window, which would be set and used when the link is pressed again to open it in the same tab).

First Login: HTTP Status 500 - Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException

It appears that MySQL or a firewall is killing off your inactive connections that are hanging around in your jdbc connection pool for long periods of time:

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure 
The last packet successfully received from the server was 4,665,488 milliseconds ago.

Check the value of wait_timeout on MySQL.

You can play around with DBCP settings e.g. validationQuery, testOnBorrow and testWhileIdle.

A a confuguration that is 'belt and braces', and will probably solve your problem at the expense of performance is:
 
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
  <property name="driverClassName" value="${jdbc.driverClassName}"/>
  <property name="url" value="${jdbc.url}"/>
  <property name="username" value="${jdbc.username}"/>
  <property name="password" value="${jdbc.password}"/>
  <property name="validationQuery" value="SELECT 1"/>
  <property name="testOnBorrow" value="true"/>
</bean>
The above will test connections every time you borrow from the pool.

Thursday, February 5, 2015

Solving the mySQL “The security settings could not be applied” error

Yesterday I got this error message during the last step of the MySQL Windows installer: “The security settings could not be applied to the database because the connection has failed with the following error”.

The issue can be solved issue this procedure from the MySQL website.

First, cancel the wizard and make sure that the MySQL service is stopped.

Then, create a text file using a SQL query that will reset the root password.

1
2
UPDATE mysql.user SET Password=PASSWORD('admin') WHERE User='root';
FLUSH PRIVILEGES;

Then, launch mySQL using the following command line:

1
mysqld --defaults-file="C:\Program Files\MySQL\MySQL Server 5.5\my.ini" --init-file="C:\mysql-init.txt" --console

Note: it’s better to use the ”–console” option so that error messages are correctly displayed.

Finally, open a new DOS shell and execute the following command line to shutdown mySQL:

1
mysqladmin -u root -p shutdown

You can now restart the mySQL installer and choose the “Repair” option:


2 solution of java.lang.OutOfMemoryError in Java

ava.lang.OutOfMemoryError now and then, OutOfMemoryError in Java is one problem which is more due to system's limitation (memory) rather than due to programming mistakes in most cases though in certain cases you could have memory leak which causing OutOfMemoryError. I have found that even though java.lang.OutOfMemoryError is quite common basic knowledge of its cause and solution is largely unknown among junior developers. In this article we will explore what is java.lang.OutOfMemoryError; Why OutOfMemoryError comes in Java application, different type of OutOfMemoryError and How to fix OutOfMemoryError in Java. This article is purely meant to provide basic knowledge of java.lang.OutMemoryError and won't discuss profiling in detail.


What is java.lang.OutOfMemoryError in Java

java.lang.OutOfMemoryError in Java, PermGen space or heap spaceOutOfMemoryError in Java is a subclass of java.lang.VirtualMachineError and JVM throws java.lang.OutOfMemoryError when it ran out of memory in heap. OutOfMemoryError in Java can come any time in heap mostly while you try to create an object and there is not enough space in heap to allocate that object. javavdoc of OutOfMemoryError is not very informative about this though.

Types of OutOfMemoryError in Java

I have seen mainly two types of OutOfMemoryError in Java:

1) Java.lang.OutOfMemoryError: Java heap space
2) Java.lang.OutOfMemoryError: PermGen space

Though both of them occur because JVM ran out of memory they are quite different to each other and there solutions are independent to each other.

Difference between "java.lang.OutOfMemoryError: Java heap space" and "java.lang.OutOfMemoryError: PermGen space"

If you are familiar with different generations on heap and How garbage collection works in java and aware of new, old and permanent generation of heap space then you would have easily figured out this OutOfMemoryError in Java. Permanent generation of heap is used to store String pool and various Meta data required by JVM related to Class, method and other java primitives. Since in most of JVM default size of Perm Space is around "64MB" you can easily ran out of memory if you have too many classes or huge number of Strings in your project. Important point to remember is that it doesn't depends on –Xmx value so no matter how big your total heap size you can ran OutOfMemory in perm space. Good think is you can specify size of permanent generation using JVM options "-XX:PermSize" and  "-XX:MaxPermSize" based on your project need.

One small thing to remember is that "=" is used to separate parameter and value while specifying size of perm space in heap while "=" is not required while setting maximum heap size in java, as shown in below example.

export JVM_ARGS="-Xmx1024m -XX:MaxPermSize=256m"


Another reason of "java.lang.OutOfMemoryError: PermGen" is memory leak through Classloaders and it’s very often surfaced in WebServer and application server like tomcat, webshere, glassfish or weblogic. In Application server different classloaders are used to load different web application so that you can deploy and undeploy one application without affecting other application on same server, but while undeploying if container some how keeps reference of any class loaded by application class loader than that class and all other related class will not be garbage collected and can quickly fill the PermGen space if you deploy and undeploy your application many times. "java.lang.OutOfMemoryError: PermGen” has been observed many times in tomcat in our last project but solution of this problem are really tricky because first you need to know which class is causing memory leak and then you need to fix that. Another reason of OutOfMemoryError in PermGen space is if any thread started by application doesn't exit when you undeploy your application.
These are just some example of infamous classloader leaks, anybody who is writing code for loading and unloading classes have to be very careful to avoid this. You can also use visualgc for monitoring PermGen space, this tool will show graph of PermGen space and you can see how and when Permanent space getting increased. I suggest using this tool before reaching to any conclusion.
Another rather unknown but interesting cause of "java.lang.OutOfMemoryError: PermGen" we found is introduction of JVM options "-Xnoclassgc". This option sometime used to avoid loading and unloading of classes when there is no further live references of it just to avoid performance hit due to frequent loading and unloading, but using this option is J2EE environment can be very dangerous because many framework e.g. Struts, spring etc uses reflection to create classes and with frequent deployment and undeployment you can easily ran out of space in PermGen if earlier references was not cleaned up. This instance also points out that some time bad JVM arguments or configuration can cause OutOfMemoryError in Java.
So conclusion is avoid using "-Xnoclassgc" in J2EE environment especially with AppServer.


Tomcat to Solve OutOfMemoryError in PermGen Space

From tomcat > 6.0 onward tomcat provides memory leak detection feature which can detect many common memory leaks on web-app perspective e.g ThreadLocal memory leaks, JDBC driver registration, RMI targes, LogFactory and Thread spawned by web-apps. You can check complete details on htp://wiki.apache.org/tomcat/MemoryLeakProtection you can also detect memory leak by accessing manager application which comes with tomcat, in case you are experiencing memory leak on any java web-app its good idea to run it on tomcat.

How to solve java.lang.OutOfMemoryError: Java heap space


1) Easy way to solve OutOfMemoryError in java is to increase the maximum heap size by using JVM options "-Xmx512M", this will immediately solve your OutOfMemoryError. This is my preferred solution when I get OutOfMemoryError in Eclipse, Maven or ANT while building project because based upon size of project you can easily ran out of Memory.here is an example of increasing maximum heap size of JVM, Also its better to keep -Xmx to -Xms ration either 1:1 or 1:1.5 if you are setting heap size in your java application

export JVM_ARGS="-Xms1024m -Xmx1024m"

2) Second way to resolve OutOfMemoryError in Java is rather hard and  comes when you don't have much memory and even after increase maximum heap size you are still getting java.lang.OutOfMemoryError, in this case you probably want to profile your application and look for any memory leak. You can use Eclipse Memory Analyzer to examine your heap dump or you can use any profiler like Netbeans or JProbe. This is tough solution and requires some time to analyze and find memory leaks.

How to solve java.lang.OutOfMemoryError: PermGen space

As explained in above paragraph this OutOfMemory error in java comes when Permanent generation of heap filled up. To fix this OutOfMemoryError in Java you need to increase heap size of Perm space by using JVM option   "-XX:MaxPermSize". You can also specify initial size of Perm space by using    "-XX:PermSize" and keeping both initial and maximum Perm Space you can prevent some full garbage collection which may occur when Perm Space gets re-sized. Here is how you can specify initial and maximu Perm size in Java:

export JVM_ARGS="-XX:PermSize=64M -XX:MaxPermSize=256m"

Some time java.lang.OutOfMemoryError  in Java gets tricky and on those cases profiling remain ultimate solution.Though you have freedom to increase heap size in java, it’s recommended that to follow memory management practices while coding and setting null to any unused references.
That’s all from me on OutOfMemoryError in Java I will try to write more about finding memory leak in java and using profiler in some other post. Please share what is your approach to solve java.lang.OutOfMemoryError in Java.


Important Note: From Tomcat > 6.0 onward tomcat provides memory leak detection feature which can detect many common memory leaks on Java application e.g ThreadLocal memory leaks, JDBC driver registration, RMI targes, LogFactory and Thread spawned by webapps. You can check complete details on htp://wiki.apache.org/tomcat/MemoryLeakProtection. You can also detect memoy leak by accessing manager application which comes with tomcat, in case you are experiencing memory leak on any java webapp its good idea to run it on tomcat to find out reason of OutOfMemoryError in PermGen space.

Tools to investigate and fix OutOfMemoryError in Java

Java.lang.OutOfMemoryError is a kind of error which needs lot of investigation to find out root cause of problem, which object is taking memory, how much memory it is taking or finding dreaded memory leak and you can't do this without having knowledge of available tools in java space. Here I am listing out some free tools which can be used to analyze heap and will help you to find culprit of OutOfMemoryError
1) Visualgc
Visualgc stands for Visual Garbage Collection Monitoring Tool and you can attach it to your instrumented hostspot JVM. Main strength of visualgc is that it displays all key data graphically including class loader, garbage collection and JVM compiler performance data.
The target JVM is identified by its virtual machine identifier also called as vmid. You can read more about visualgc and vmid options here.
2) Jmap
Jmap is a command line utility comes with JDK6 and allows you to take a memory dump of heap in a file. It’s easy to use as shwon below:
jmap -dump:format=b,file=heapdump 6054
Here file specifies name of memory dump file which is "heapdump" and 6054 is PID of your Java progress. You can find the PDI by using "ps -ef” or windows task manager or by using tool called "jps"(Java Virtual Machine Process Status Tool).
3) Jhat
Jhat was earlier known as hat (heap analyzer tool) but it is now part of JDK6. You can use jhat to analyze heap dump file created by using "jmap". Jhat is also a command line utility and you can rum it from cmd window as shown below:
jhat -J-Xmx256m heapdump
Here it will analyze memory-dump contained in file "heapdump". When you start jhat it will read this heap dump file and then start listening on http port, just point your browser into port where jhat is listening by default 7000 and then you can start analyzing objects present in heap dump.
4) Eclipse memory analyzer
Eclipse memory analyzer (MAT) is a tool from eclipse foundation to analyze java heap dump. It helps to find classloader leaks and memory leaks and helps to minimize memory consumption.you can use MAT to analyze heap dump carrying millions of object and it also helps you to extract suspect of memory leak. See here for more information.

Wednesday, February 4, 2015

Rename a file in Linux with simple command line options

Linux is a very popular operating system and is widely used today on servers and also on standalone systems. It is based on UNIX and is a free OS. There are many people who love to work on it and consider it the most reliable and robust of all the operating systems available today. Working in Linux requires some prior knowledge as the commands have to be given through command line text. In this tutorial, we’ll show you how to rename files in Linux, with different commands. Linux has several ways of renaming files and directories in Linux like cp (copy), rm (remove), mv (move or rename),etc. We’ll walk you through them shortly.

Renaming a file

In order to rename a file in Linux you can use either of two approaches
1.    Create a copy of the existing file with the new desired name and then delete the old file.
2.    Rename the file by moving it with the mv command.
Lets take up some examples one by one:

Rename with copy and delete

$ cp oldfile newfile
This creates a copy of the same file with a new name in the same location.
$ rm oldfile
This will delete the old file keeping the newfile intact.

Rename by moving

$mv old-file-name  new-file-name
This just moves the old file, to a new name.

Renaming multiple files

This is extremely easy case when we are dealing with one file but the complexity increases when we are dealing with multiple files, and this is something with which we encounter very often in real life.
Lets take an example where we want to rename multiple files.
In order to rename multiple files at once we can make use of wildcard characters (for ex: ‘*’). In the below example we will rename all the files with .txt to .dat.
We can achieve this by simply typing the following command:
$ mv *.txt *.dat
Now, let us assume you have a file whose name is misspelled or if there is an alphabet missing from the name of the file then in order to fix this we can leverage the mv command with other wildcard characters.
For example: we have a file with a name RR#.txt, whereas the filename should contain only alphanumeric values instead of any special characters. This can be fixed with the following command:
$ mv RR?.txt RR1.txt
Where ? is the wildcard character used in place of the unknown character.

Interactive renaming

Many times during your day to day work you may make a mistake you cannot undo. For example, moving or renaming a file accidentally. To avoid this problem Linux provides an interactive renaming option wherein the user will be prompted  for confirmation before overwriting the file name. This empowers the end user to choose an option “Y” or “N” from the keyboard in order to finalize the action. In order to leverage this capability one must use -i option with mv command in the following manner.
$ mv -i RR1.txt ST1.txt
Once we run this command the Linux will prompt the end with following line:
mv: overwrite ‘RR1.txt’ ?
User can choose “Y” to continue or “N” to abort this action.

Renaming a directory

Renaming a directory in Linux and Unix is similar to renaming a file. All we need to do is replace the file name with the directory name that is to be renamed.
For example, if we wanted to rename the directory “RR1″ to “ST1″, then we can use the following command.
$ mv RR1 ST1

Rename file to different location

If you want to change not only the name of the file, but also it’s location, use the following command:
$ mv RR2 newdir/.
This command moves the file RR2 from its current location and places it under the directory newdir/.

Track what’s happening with Verbose option

If you’re renaming a number of files, or doing other mass operations, you may want to track what is happening. Linux has an easy way of doing that with the -v or -verbose option. Here is the syntax
$ mv -v source.txt new_source.txt

Mass move and rename

Linux has another command, mmv, which stands for mass, move and rename. This is extremely helpful for renaming multiple files at a go. Its utility is not just limited to renaming of files. It can be used for moving, linking and appending multiple files as well. The reason why I like it most because it is the safest way to do these tasks. mmv does it all without any sudden destruction of files due to collisions of target names with existing file names. Moreover, before doing anything, mmv tries to identify any errors that would result from the entire set of actions specified and equips the user with the option of either terminating before beginning, or proceeding by avoiding the offending parts.The syntax for this command is:
$ mmv [options]
This should give you a good insight into how to rename files in Linux. If you want to try out more options, just use the ‘man’ command, and Linux will list out all the options, along with how to use them.
$ man move

Tuesday, February 3, 2015

From PHP to Tomcat server

http://stackoverflow.com/questions/2865289/php-redirection-with-post-parameters

Configure mod_jk with Apache 2.2 in Ubuntu

1. Install mod_jk: To install mod_jk in ubuntu execute the following command on the command line.

sudo apt-get install libapache2-mod-jk

2. Enable mod_jk loading: Create a link in /etc/apache2/mods-enabled/jk.load which points to /etc/apache2/mods-available/jk.load. This will enable loading mod_jk module in apache when apache is restarted.

3. Create mod_jk conf file:
Create a mod_jk conf file and place it in /etc/apache2/mods-available/jk.conf

# Where to find workers.properties
# Update this path to match your conf directory location
JkWorkersFile /etc/apache2/jk_workers.properties

# Where to put jk logs
# Update this path to match your logs directory location
JkLogFile /var/log/apache2/mod_jk.log

# Set the jk log level [debug/error/info]
JkLogLevel info

# Select the log format
JkLogStampFormat "[%a %b %d %H:%M:%S %Y]"

# JkOptions indicate to send SSL KEY SIZE,
JkOptions +ForwardKeySize +ForwardURICompat -ForwardDirectories

# JkRequestLogFormat set the request format
JkRequestLogFormat "%w %V %T"

# Shm log file
JkShmFile /var/log/apache2/jk-runtime-status
4. Enable mod_jk configurations: Create a link in /etc/apache2/mods-enabled/jk.conf which points to /etc/apache2/mods-available/jk.conf. This will enable mod_jk configuration in apache when apache is restarted.

5. Create a worker properties file: Create a workers properties file and place it in /etc/apache2/jk_workers.properties

# Define 1 real worker named ajp13
worker.list=ajp13

# Set properties for worker named ajp13 to use ajp13 protocol,
# and run on port 8009
worker.ajp13.type=ajp13
worker.ajp13.host=localhost
worker.ajp13.port=8009
worker.ajp13.lbfactor=50
worker.ajp13.cachesize=10
worker.ajp13.cache_timeout=600
worker.ajp13.socket_keepalive=1
worker.ajp13.socket_timeout=300

6. Configure url forwarding in apache to tomcat: Put the following lines in you apache virtualhost to forward requests to tomcat.

<VirtualHost *:80>
    ...
    # Send everything for context "/context" to worker ajp13
    JkMount /context/ ajp13
    JkMount /context/* ajp13
    ...
</VirtualHost>
7. Configure AJP in tomcat server. Put the following line in $TOMCAT_HOME/conf/server.xml file under the Servies tag.
<Service name="Catalina">
     ...
    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
    ...
</Service>

8. Restart the tomcat and apache server: Relax you are done.

How to move files in Linux/Unix

Unix/Linux move files.

Move file syntax:
$ mv [options] sourcefiles destdir

Move main.c def.h files to /home/usr/rapid/ directory
$ mv main.c def.h /home/usr/rapid/

Move all C files in current directory to subdirectory bak
$ mv *.c bak

How to find and replace in Unix vi editor

Vi and Vim Editor: 12 Powerful Find and Replace Examples

 

This article is part of the on-going Vi / Vim Tips and Tricks series. Vim is commonly mentioned as text editor, not text creator. Why ? Because we spend lot of time editing an existing text than creating new text.  In the text editing, text/pattern substitutions becomes a vital part.

In this article, let us review how to perform both basic and advanced text and pattern substitution features in Vi and Vim Editor. These features are explained using 12 very practical and powerful text substitution examples.

Syntax of the text substitution inside vim editor:
:[range]s[ubstitute]/{pattern}/{string}/[flags] [count]

Following are three possible flags.
  1. [c] Confirm each substitution.
  2. [g] Replace all occurrences in the line.
  3. [i] Ignore case for the pattern.

 

Example 1. Substitute all occurrences of a text with another text in the whole file

This is the basic fundamental usage of the text substitution inside Vi editor. When you want a specific text to be replaced with another text in the entire file then you can use the following sequence.

 
:%s/old-text/new-text/g

  • %s – specifies all lines. Specifying the range as ‘%’ means do substitution in the entire file.
  • g – specifies all occurrences in the line. With the ‘g’ flag , you can make the whole line to be substituted. If this ‘g’ flag is not used then only first occurrence in the line only will be substituted.

Example 2. Substitution of a text with another text within a single line

When you want a specific text to be replaced with another text within a single line in a case insensitive manner. Specifying no range means, do substitution in the current line only. With the ‘i’ flag, you can make the substitute search text to be case insensitive.
 
:s/I/We/gi

Example 3. Substitution of a text with another text within a range of lines

With the range, you can make only a range of line to be affected in the substitution. Specifying 1, 10 as range means, do substitution only in the lines 1 – 10.
 
:1,10s/helo/hello/g

Example 4. Substitution of a text with another text by visual selection of lines

You can also select a specific lines by visually selecting those lines. Press CTRL + V in command mode, use navigation keys to select the part of the file you want to be substituted. Press ‘:’ which will automatically formed as :’<,’> Then you can use the normal substitute as


:'<,'>s/helo/hello/g

Example 5. Substitution of a text with another text only the 1st X number of lines

Using count in substitution, If you specify the count N in the substitution then it means do substitution in N lines from the current position of the cursor. do substitution in 4 lines from the current line.
 
:s/helo/hello/g 4

Example 6. Substitute only the whole word and not partial match

Let us assume that you want to change only the whole word ‘his’ to ‘her’ in the original text mentioned below. If you do the standard substitution, apart from changing his to her, it will also change This to Ther as shown below.

Standard Subsitution

Original Text: This is his idea

:s/his/her/g

Translated Text: Ther is her idea

Whole Word Subsitution

Original Text: This is his idea

:s/\<his\>/her/

Translated Text: This is her idea
Note:: You should enclose the word with < and > , which will force the substitution to search only for the full word and not any partial match.

Example 7. Substitute either word1 or word2 with a new word using regular expression

In the following example, it will translate any occurrences of either good or nice will be replaced with awesome.
Original Text: Linux is good. Life is nice.

:%s/\(good\|nice\)/awesome/g

Translated Text: Linux is awesome. Life is awesome.

You can also do substitution by specifying regular expression. Following example does the substitution of hey or hi to hai. Please note that this does not do any substitution for the words ‘they’, ‘this’.
 
:%s/\<\(hey\|hi\)\>/hai/g

  • \< – word boundary.
  • \| – “logical or” (in this case hey or hi)

Example 8. Interactive Find and Replace in Vim Editor

You can perform interactive find and replace using the ‘c’ flag in the substitute, which will ask for confirmation to do substitution or to skip it as explained below. In this example, Vim editor will do a global find the word ‘awesome’ and replace it with ‘wonderful’. But it will do the replacement only based on your input as explained below.
:%s/awesome/wonderful/gc

replace with wonderful (y/n/a/q/l/^E/^Y)?
  • y – Will replace the current highlighted word. After replacing it will automatically highlight the next word that matched the search pattern
  • n – Will not replace the current highlighted word. But it will automatically highlight the next word that matched the search pattern
  • a – Will substitute all the highlighted words that matched the search criteria automatically.
  • l – This will replace only the current highlighted word and terminate the find and replace effort.

Example 9. Substituting all lines with its line number.

When the string starts with ‘\=’, it should be evaluated as an expression. Using the ‘line’ function we can get the current line number. By combining both the functionality the substitution does the line numbering of all lines.
 
:%s/^/\=line(".") . ". "/g

Note: This is different from the “:set number” where it will not write the line numbers into the file. But when you use this substitution you are making these line number available inside the file permanently.

Example 10. Substituting special character with its equivalent value.

Substituting the ~ with $HOME variable value.
Original Text: Current file path is ~/test/

:%s!\~!\= expand($HOME)!g

Translated Text: Current file path is /home/ramesh/test/
You can use expand function to use all available predefined and user defined variables.

Example 11. Alter sequence number in a numbered list while inserting a new item

Assume that you have a numbered list like the following inside a text file. In this example, let us assume that you want to add a new line after Article 2. For this, you should change the number of all other articles accordingly.
vi / vim tips & tricks series
Article 1: Vi and Vim Editor: 3 Steps To Enable Thesaurus Option
Article 2: Vim Autocommand: 3 Steps to Add Custom Header To Your File
Article 3: 5 Awesome Examples For Automatic Word Completion Using Ctrl-X
Article 4: Vi and Vim Macro Tutorial: How To Record and Play
Article 5: Tutorial: Make Vim as Your C/C++ IDE Using c.vim Plugin
Article 6: How To Add Bookmarks Inside Vim Editor
Article 7: Make Vim as Your Bash-IDE Using bash-support Plugin
Article 8: 3 Powerful Musketeers Of Vim Editor ? Macro, Mark and Map
Article 9: 8 Essential Vim Editor Navigation Fundamentals
Article 10: Vim Editor: How to Correct Spelling Mistakes Automatically
Article 11: Transfer the Power of Vim Editor to Thunderbird for Email
Article 12: Convert Vim Editor to Beautiful Source Code Browser

3rd Article “Make Vim as Your Perl IDE Using perl-support.vim Plugin” got missed. So when you want
to add it, then you want to change “Article 3″ to “Article 4″, “Article 4″ to “Article 5″, upto “Article 12″ to “Article 13″.

This can be achieved by the following vim substitution command.
:4,$s/\d\+/\=submatch(0) + 1/

  • Range: 4,$ – 4th line to last line.
  • Pattern to Search – \d\+ – digits sequence
  • Pattern to Replace – \=submatch(0) + 1 – gets the matched pattern and adds 1 to it.
  • Flag – as there is no flag, by default it substitutes only the first occurrence.

After executing the substitute statement the file will become like this, where you can
add the 3rd Article.
vi / vim tips & tricks series
Article 1: Vi and Vim Editor: 3 Steps To Enable Thesaurus Option
Article 2: Vim Autocommand: 3 Steps to Add Custom Header To Your File
Article 4: 5 Awesome Examples For Automatic Word Completion Using Ctrl-X
Article 5: Vi and Vim Macro Tutorial: How To Record and Play
Article 6: Tutorial: Make Vim as Your C/C++ IDE Using c.vim Plugin
Article 7: How To Add Bookmarks Inside Vim Editor
Article 8: Make Vim as Your Bash-IDE Using bash-support Plugin
Article 9: 3 Powerful Musketeers Of Vim Editor ? Macro, Mark and Map
Article 10: 8 Essential Vim Editor Navigation Fundamentals
Article 11: Vim Editor: How to Correct Spelling Mistakes Automatically
Article 12: Transfer the Power of Vim Editor to Thunderbird for Email
Article 13: Convert Vim Editor to Beautiful Source Code Browser
Note: Check the substitution changed the 3 to 4, 4 to 5 and so on. Now we can add a new line mentioning it as Article 3, and no need to do any manual changes.

Example 12. Substituting the sentence beginnings with upper case. ( i.e title case the entire document ).

While formatting a document, making the title case is also an important thing. It can be done easily with substitution.
:%s/\.\s*\w/\=toupper(submatch(0))/g

  • \.\s*\w – Search Pattern – literal . ( dot ) followed by Zero or more space, and a word character.
  • toupper – converts the given text to upper case.
  • submatch(0) – returns the matched pattern.

Text before substitution:

Lot of vi/vim tips and tricks are available at thegeekstuff.com. reading
these articles will make you very productive. following activities can be
done very easily using vim editor.
        a. source code walk through,
        b. record and play command executions,
        c. making the vim editor as ide for several languages,
        d. and several other @ vi/vim tips & tricks.

Text after substitution (Changes are in bold)

Lot of vi/vim tips and tricks are available at thegeekstuff.com. Reading
these articles will make you very productive. Following activities can be
done very easily using vim editor.
        a. Source code walk through,
        b. Record and play command executions,
        c. Making the vim editor as ide for several languages,
        d. And several other @ vi/vim tips & tricks.

How to uncompress a tar.gz in another folder on linux

gzip -dc archive.tar.gz | tar -xf - -C /destination

or, with GNU tar
 
tar xzf archive.tar.gz -C /destination

How to determine whether a given Linux is 32 bit or 64 bit?

Try uname -m. It seems like the uname -m actually gives

x86_64 ==> 64-bit kernel
i686   ==> 32-bit kernel
 
lscpu will list out these among other information regarding your CPU:

Architecture: x86_64 CPU 
op-mode(s): 32-bit, 64-bit

Another useful command for easy determination is as below:
Command:
getconf LONG_BIT
Answer:
  • 32, if OS is 32 bit
  • 64, if OS is 64 bit

 
In Bash, using integer overflow:
if ((1<<32)); then
  echo 64bits
else
  echo 32bits
fi
It's much more efficient than invoking another process or opening files.

How do I reload .bashrc without logging out and back in?

You just have to enter the command:
source ~/.bashrc
 
 
or, you can use the shorter version of the command:
. ~/.bashrc
 
or you could use;
exec bash
does the same thing. (and easier to remember, at least for me)
 

How to Set JAVA_HOME / PATH variables Under Linux Bash Profile

You can set this given below in .bash_profile file,

JAVA_HOME=/etc/jdk1.7.0_07/
export JAVA_HOME
export PATH=$PATH:$JAVA_HOME/bin
 
It seems like it works just for while, 
but after closing console have to do this again.. 
 
How to install it permanently?
 
You should add these lines to ~/.bashrc
which is sourced by interactive shells, 
while ~/.bash_profile is only sourced by interactive login shells. 

To verify, open a new shell and echo "$JAVA_HOME".
 
 

How to rename a table column in MySQL

ALTER TABLE table_name
CHANGE COLUMN old_column_name new_column_name DATATYPE NULL DEFAULT NULL;

rename a table in mysql

RENAME TABLE  `oldTableName` TO  `newTableName`

How to get database structure in MySQL via query


To get the whole database structure as a set of CREATE TABLE statements, use mysqldump:

mysqldump database_name --compact --no-data
 
For single tables, add the table name after db name in mysqldump.
 You get the same results with SQL and SHOW CREATE TABLE, 

SHOW CREATE TABLE table;

 To read from schema. 

SELECT * FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_SCHEMA = 'test' AND TABLE_NAME ='products';  




other commands which may be helpful 

1. Login to Mysql, 

-> mysql -u [username] -p 


2. To see all databases inside mysql, 

mysql -> show databases;  

3. To go inside a particular database, 

mysql -> use [database_name];

4. see all tables inside database,
 
mysql -> SHOW TABLES;

5. Just to look at details of column listing,

mysql -> DESCRIBE table;
 

Monday, February 2, 2015

check running ports on local windows system

netstat -a -n

to check state of port,
 
netsh firewall show state

grant remote access of MySQL database from any IP address

GRANT ALL PRIVILEGES
ON database.*
TO 'user'@'yourremotehost'
IDENTIFIED BY 'newpassword';

Hibernate: Automatically creating/updating the db tables based on entity classes

!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create</property>
or,  
 <property name="hbm2ddl.auto">update</property>

or,
<prop key="hibernate.hbm2ddl.auto">create</prop>
or, 

<property name="hbm2ddl.auto" value="create"/>

ERROR 2003 (HY000): Can't connect to MySQL server on localhost (10061)

You don't need a restart your windows. The easiest way to achieve this is
  1. Goto /bin/
  2. Run mysqld (service)
  3. close the cmd prompt
  4. Run mysql.exe or the better way to do is add the location to PATH environment Variable