Pages

Monday, 28 November 2011

Restoring GRUB

Restoring GRUB on Ubuntu

How many times have you lost your GRUB after installing Windows on a system that has Ubuntu (or any other distro) already installed?

The bootloader sector of the hard disk stores the information about all the operating systems installed on your system. When you install Linux, it probes for any existing operating system and adds an entry in the GRUB list. On the other hand, when you install Windows, it overwrites the bootloader and erases all the entries, leaving no way to access your Linux.

To restore GRUB, you will need Ubuntu mounted on any removable drive (CD/DVD/Pen drive) will can be used as a live CD. After booting from the external media, select "Use as Live CD" option. Open the terminal and type the following commands:

Also, you should know where you have installed Ubuntu (in this example sda3)

~$ su # mount /dev/sda3 /mnt
# mount --bind /dev /mnt/dev
# mount --bind /proc /mnt/proc
# mount --bind /sys /mnt/sys
# chroot /mnt
# grub-install /dev/sda

Close the terminal and reboot. Your GRUB should be restored.

Monday, 21 November 2011

How to fix ‘$MFTMirr does not match $MFT (record 0)’

Sometimes, when you are executing a file transfer between your computer hard drive and an external drive and your computer shutdowns for some reason it’s pretty common to get some errors on external drives that uses NTFS as their file system.

The error message may be:

Error mounting: mount exited with exit code 13: $MFTMirr does not match $MFT (record 0).
Failed to mount ‘/dev/sdc1′: Input/output error
NTFS is either inconsistent, or there is a hardware fault, or it’s a
SoftRAID/FakeRAID hardware. In the first case run chkdsk /f on Windows
then reboot into Windows twice. The usage of the /f parameter is very
important! If the device is a SoftRAID/FakeRAID then first activate
it and mount a different device under the /dev/mapper/ directory, (e.g.
/dev/mapper/nvidia_eahaabcc1). Please see the ‘dmraid’ documentation
for more details.


The easiest solution is to use 'ntfsfix' command from the terminal
~$ sudo ntfsfix /dev/partitionName


The output should be similar to:

~$ sudo ntfsfix /dev/sdc1
Mounting volume... FAILED
Attempting to correct errors...
Processing $MFT and $MFTMirr...
Reading $MFT... OK
Reading $MFTMirr... OK
Comparing $MFTMirr to $MFT... FAILED
Correcting differences in $MFTMirr record 0...OK
Processing of $MFT and $MFTMirr completed successfully.
Setting required flags on partition... OK
Going to empty the journal ($LogFile)... OK
NTFS volume version is 3.1.
NTFS partition /dev/sdc1 was processed successfully.


And you are done!

After this step you should be able to access your external drive partition as usual, mount or use nautilus to access your files.

Saturday, 19 November 2011

JSP and MySQL Connectivity


I remember when I first started using Tomcat, it took me a while to make my JSP script connect to MySQL using Connector/J.

1. Tomcat is a free, open-source implementation of Java Servlet and JavaServer Pages technologies developed under the Jakarta project at the Apache Software Foundation. Download and install Tomcat.

2. Install MySQL.

3. Create a database, say 'ProductSpec', and a table 'products' with three fields- id, name, brand.

CREATE DATABASE  `ProductSpec` ;

CREATE TABLE  `products` (
 `id` INT( 3 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
 `name` VARCHAR( 50 ) NOT NULL ,
 `brand` VARCHAR( 50 ) NOT NULL
) ENGINE = INNODB;

4. I populate the the database with a few values next:

INSERT INTO  `ProductSpec`.`products`
VALUES ( 1 ,  'Hard Disk',  'Seagate');

INSERT INTO  `ProductSpec`.`products`
VALUES ( 2 ,  'iPhone 3G',  'Apple');

5. Set up two environment variables as follows:
(a) Right click on Computer, go to Properties. Click on 'Advanced System Settings on the left. A dialog box appears as shown below. Go to the 'Advanced Tab' and click on 'Environment Variables'.



(b)Under User Variables, add the two new variables. The first is the path to your jre folder, the second is the path to the the Tomcat folder. For instance, if your jre folder path is D:/jdk1.6.0_12/jre, add the following-

Variable Name: JAVA_HOME, Variable Value: D:/jdk1.6.0_12/jre

Variable Name: TOMCAT_HOME, Variable Value: C:\Program Files\Apache Software Foundation\Tomcat 7.0



6. Download Connector/J at "http://dev.mysql.com/downloads/connector/j/5.1.html">http://dev.mysql.com/downloads/connector/j/5.1.html
Unzip or Untar the file, and copy the file mysql-connector-java-5.1.6-bin.jar to Tomcat/lib or Tomcat/common/lib

This completes the setup! Now for the jsp program that connects to the database and retrieves and displays values. Make sure Tomcat and wamp are running!

7. Here's db.jsp:


<%@ page import="java.sql.*" %>

<%

String connectionURL = "jdbc:mysql://localhost:3306/ProductSpec?username=root;password=";

Connection connection = null;

Statement statement = null;

ResultSet rs = null;

%>

<html><body>

<%

Class.forName("com.mysql.jdbc.Driver").newInstance();

connection = DriverManager.getConnection(connectionURL, "root", "");

statement = connection.createStatement();

rs = statement.executeQuery("SELECT * FROM products");

while (rs.next()) {

out.println(rs.getString("name")+" "+rs.getString("brand")+"<br />");

}

rs.close();

%>

</body></html>


Change your database name, username and password on line 3: (Default username for wamp is root and password is blank.

String connectionURL = "jdbc:mysql://localhost:3306/ProductSpec?username=root;password=";

8. Add db.jsp to Tomcat\webapps\ROOT folder.

9. Now go to your browser and type localhost/db.jsp
If you had set a port number for Apache during installation like I had (8088), type localhost:8088/db.jsp


Wednesday, 14 September 2011

Formulae in Data Structures - Quick Revision

Most written technical tests have at least one question that goes - "How many Binary Search Trees can you form with n distinct numbers?" or "Number of internal nodes in an m-ary/k-ary tree?"
And I know for a fact, most of us draw small trees in the corner of our sheets. That
1. wastes precious time.
2. leaves out important cases.

So here's a list that is definitely not exhaustive, it'll be great if you could figure them out as you go along, helps remember. I'll keep adding more formulae as I come across them.  But for now, this should do:

1. To answer the first question above,

No of BSTs using n numbers is  2nCn / (n+1)                                                         (i)

For those of you who haven't seen this before, this gives the Catalan sequence, and the number of binary search trees can be found using the Catalan Sequence too, if you know it. For instance, if n=3, C(3) = 5 which is the number of BSTs you can form from three nodes.

2. The number of Binary Trees that can be formed, however, is given by the nth catalan number * n! The formula given above (i) calculates the nth catalan number.

No of Binary trees from n numbers is    n! * 2nC/ (n+1)


Here's a small example for the two formulae given above with n = 3 (say the nodes are 1, 2 and 3):

Binary Search Trees



6C3 / 4 = 5

1      1      2      3      3
 \      \    / \    /      /
  2      3  1   3  1      2 
   \    /           \    / 
    3  2             2  1




Binary Trees


3! * 5 = 30


  1      1      2      2       3      3      
 / \    / \    / \    / \     / \    / \    
2   3  3   2  1   3  3   1   1   2  2   1 

    1   1   1   1    1   1   1   1
   /   /    /   /     \   \   \   \         
  2   3    2   3       2   3   2   3        
 /   /      \   \     /   /     \   \              
3   2        3   2   3   2       3   2             

    2   2    2   2   2   2   2   2
   /   /    /   /     \   \   \   \         
  1   3    1   3       1   3   1   3        
 /   /      \   \     /   /     \   \              
3   1        3   1   3   1       3   1   

    3  3     3   3   3   3   3   3
   /   /    /   /     \   \   \   \         
  2   1    2   1       2   1   2   1        
 /   /      \   \     /   /     \   \              
1   2        1   2   1   2       1   2 

Saturday, 25 June 2011

Enabling Query Cache for fast query execution in MySQL

1. Open the MySQL Console

2. Enter SET GLOBAL query_cache_size = 1048576;
(Size is in KBs, 1GB = 1x1024x1024=1048576)

3. Other Cache Related Settings includes
SET GLOBAL query_cache_type=1;
(To Enable Query Cache)
SET GLOBAL query_cache_limit=1024;
(Per User 1MB 1x1024)

4. Caching speeds up the fetching of queries, the size must be chosen according as the RAM size

5. To check their values, you can run command
SHOW VARIABLES LIKE 'query%';

Note: To run mysql in terminal: mysql -u root -p

Tuesday, 14 June 2011

Animation Effect on your Splash/Welcome Screen on iPhone

In this tutorial, I'll give an example of how to have your own welcome image, and add the fade and zoom effect to it. When the iPhone launches your application, it looks for an image named Default.png in the resources directory. In the following example, Default.png is being replaced by a UIImageView which zooms and then fades away. (Consider abc to be your project name)

1. To abcAppDelegate.h, add the function declaration

- (void) welcomeScreen

2. To abcAppDelegate.m, add the function definition


- (void) welcomeScreen
{
//Welcome Screen
UIImageView* welcome = [[[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,480)]autorelease];
welcome.image = [UIImage imageNamed:@"img.png"];
[window addSubview:welcome];
[window bringSubviewToFront:welcome];
//Animation Effects (zoom and fade)
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:2.0];
[UIView setAnimationTransition:UIViewAnimationTransitionNone forView:window cache:YES];
[UIView setAnimationDelegate:welcome];
[UIView setAnimationDidStopSelector:@selector(removeFromSuperview)];

//set transparency to 0.0
welcome.alpha = 0.0;

//zoom effect
welcome.frame = CGRectMake(-60, -60, 440, 600);
[UIView commitAnimations];

}

3. Call the method welcomeScreen

From applicationDidFinishLaunching method in abcAppDelegate.m, invoke welcomeScreen.

- (void)applicationDidFinishLaunching:(UIApplication *)application {
[window addSubview:viewController.view];
[window makeKeyAndVisible];
[NSTimer scheduledTimerWithTimeInterval:1.0/30. target:self selector:@selector(welcomeScreen) userInfo:nil repeats:NO];

}

And it's a wrap! Cheers!



Monday, 6 June 2011

JDBC and MySQL

Steps to connect to a MySQL database from Java


1. Import

import java.sql.*;
import javax.sql.*;

2. Declare a Connection type in the class:

Connection conn;

3. Add a method to establish connection. Assume the name of the database is GameIF, and the username/password are the default values i.e username is root and there is no password.


private void connect()
{
String dbUrl = "jdbc:mysql://localhost/GameIF";
String dbClass = "com.mysql.jdbc.Driver";
String username="root";
String password="";

try
{
Class.forName(dbClass).newInstance();
conn = DriverManager.getConnection(dbUrl,username,password);
}
catch(Exception e)
{
System.out.println(e);
}
}



3.  Add a function that tears down the connection:


private void disconnect()
{
if (conn != null)
{
try
{
conn.close();
}
catch (Exception e) {}
}
}


4. Writing/Executing a query: A query may be of two types:

(a) One that returns a result set (e.g: SELECT query)

(b) One that returns no result set (e.g: DROP, CREATE, INSERT, UPDATE)

We'll see examples for both types:

(a) SELECT

connect( );

String uname, steps;

String query = "select * from `scores`";
try
{
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next())
{
uname = rs.getString("username");
steps = rs.getInt("steps");
System.out.println("Username: "+uname+"\tSteps: "+steps);
}
rs.close();
st.close();
}
catch(Exception e) {
System.out.println(e);
}


disconnect( );


(b) INSERT


connect( );


Statement s;
String query = "insert into `scores` (`game` , `username` , `steps`) values ('NUMBERJUMBLE','Tups',56)";
try
{
s = conn.createStatement( );
s.executeUpdate(query);
s.close( );
}
catch(Exception e)
{
System.out.println(e);
}


disconnect( );




And, we're done!
However, a very common exception is encountered if you are building a standalone application:

java.lang.ClassNotFoundException

To fix this:
1. Download the mysql connector jar files (A straightforward google search!)
2. Add the jar files (format mysql-connector-java-<version>-bin.jar) to the following two folders:
         <your jdk directory>/jre/lib
         <your jdk directory>/jre/lib/ext

If you are using netbeans or another IDE, copy the files and restart!

Cheers!


Saturday, 4 June 2011

Add sound on Jbutton click in Java

To add a sound on JButton click event, follow three simple steps:
1. Import the following:

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.Clip;
import javax.sound.sampled.AudioSystem;

2. Add the following function to your class:

public void playSound(String soundName)
{
try
{
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(soundName).getAbsoluteFile( ));
Clip clip = AudioSystem.getClip( );
clip.open(audioInputStream);
clip.start( );
}
catch(Exception ex)
{
System.out.println("Error with playing sound.");
ex.printStackTrace( );
}
}

3. In your actionPerformed function for the JButton, just call the function with the filename as string:

public void actionPerformed(ActionEvent ae)
{

//do something
playSound("buzzer.wav");
}




About

I often came across broken or unhelpful snippets while working on projects. A small feature required by a project needed hours of surfing on the net. Just wanted to make things a tad simpler for you!