Wednesday, November 19, 2014

Java : Read from Excel (xls) file

Java : Reaf from Excel (xls) file

Reading from a text file is common. But, reading from an excel(.xls) file is not.
Recently, I got to do so. Little bit Google search and experimentation resulted in the following.

I used HSSF from Apache-POI.
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

public void readFromXlsFile (String pathToFile, String sheetName){
    try {
        FileInputStream file = new FileInputStream(pathToFile);

        HSSFWorkbook workbook = new HSSFWorkbook(file);
        HSSFSheet sheet = workbook.getSheet(sheetName);

        Iterator<Row> rowIterator = sheet.rowIterator();
           
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();

            if (row.getRowNum() == 0) {
                continue;// skip first row, as it contains column names
            }

            Iterator<Cell> cellIterator = row.cellIterator();
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                if (cell.getColumnIndex() == 0) {
                    System.out.print(cell.getStringCellValue() + "\t\t");
                } else if (cell.getColumnIndex() == 1) {
                    System.out.print((long) cell.getNumericCellValue()+ "\t\t");
                } else if (cell.getColumnIndex() == 2) {
                    System.out.print((int) Math.round(cell.getNumericCellValue())+ "\t\t");
                }
            }
            System.out.println("");
        }

        file.close();

    } catch (FileNotFoundException fnfe) {
        fnfe.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
To run the above example, create a sheet in excel file with String, Long and Integer columns respectively.

To print column names, run a while loop with cell.getStringCellValue() on every cell in first row.

getStringNumericCellvalue() returns 'double' and you can see from the example that I've type-casted it to 'long' and 'int'.

To get a sheet by its index, use
getSheetAt(index)
in place of
getSheet(sheetName)

Tuesday, November 4, 2014

Mac Yosemite : Ugly turned out to be Uglier and Ugliest

Mac Yosemite : Ugly turned out to be Uglier and Ugliest
You might have read my review on Mac OSX Yosemite, The Good, bad and ugly.
Now it turned out to be UGLIEST.

No more words. Here's the image.
Mac Yosemite : Ugly turned out to be Uglier and Ugliest

If you are on Yosemite, you might be familiar with it.
Most of the times, you get stuck on boot logo.
I've seen complaints regarding it saying that fellow members are ignorant of it and they deny such possibility, even though many are still facing it.

Workarounds suggested by our online friends:
  • Just reboot your mac as many times it takes to your desktop.
  • Boot into safe mode, by holding SHIFT and then reboot.
Comment your workaround below, mine is the first one.

If you are still on Mavericks, be there till Apple provides a fix for this.

Saturday, October 18, 2014

Mac OSX Yosemite : Good, bad and Ugly


Mac OSX Yosemite : Good, bad and Ugly

I can’t start my review with some statement like “yet another operating system”. Because it is still the same with some differences. I will start with my journey so far with Yosemite.

Sometime back when I saw the preview images, it was like WOW. Are they transforming the Mac into iPhone/iPad? Wait, does it look familiar? Is it somewhat like Material Design of Android? Never mind, what we need is a clean and powerful OS. Mac is already clean and Yosemite seemed much cleaner. Fingers-crossed and waited for official launch.

Finally my AppStore said, here is a powerful OS for you, that too for FREE. Lets talk about this FREE tag later. Just remind me if I missed it. It took some time to install (almost an hour after downloading. Pre- and post-installation….).

Warning: What follows is strictly my opinion.

When I looked at the lock screen for my first boot, I literally shouted WOW. It seems like I’m on an iPad. With no delay I logged into my PC and that’s it. Now my expression changed to OH! What was that? Did I just installed the first generation OS? The colour of text and icons, that dark look, its all like oldest and latest combination.

Dock: It is the best thing happened to the Mac users. But now it has lost its charm. I updated iTunes ahead of Mac and the icon suggested that they are trying to take Mac away from Steve. Also the trash. I feel like throwing it into trash. How beautiful the trash used to be!


Dock

That’s it to hate. New look seems refreshing, but the texture of fonts and icons needs an appointment with a stylist. Its time for the good ones.

Spotlight: They surely thrown some spotlight on spotlight, instead of throwing it at corner. It has got everything which you didn’t even asked for. Every result will have a preview and you can play music/movie in background. Wait a minute. If you can’t find where the sound is coming from, just open the spotlight. Its the culprit. Don't forget to look at auto-filling (suggestions) while searching.
Spotlight


Notification Center: It used to push your desktop away, but now it its creeps over it. Along with notifications, there is one more tab “today”, which does what your dashboard does, but in collective manner. Lets see what all can we get from it.
notification

Finder: You won’t find the usual + button. It got replaced with the full screen button. For me, + never behaved properly and I always use Spectacle. Nothing much to say, but it need some styling (colour and texture).

Volume: It doesn’t make those pop sounds while changing levels, which is handy when you are at work.

It seems Yosemite is bit faster than its predecessors. Also it can be integrated with i-devices, which I don’t have.

All these made me say Yosemite is Good, Bad and Ugly.

Oh, the reminder. FREE tag. Again, its completely my opinion. I felt that this free tag is stopping them from giving out their innovations. There might be more in their plate, which they are resisting to serve. If that’s the case, we can expect a complete make over with some GOOD PRICE TAG sometime later.

That’s it form my side. Shower your thoughts below.
Thank you.

Sunday, October 5, 2014

Mac: Write to NTFS partitions

Mac: Write to NTFS partitions
Pre-requisites:
  • XCode
  • Homebrew
To install Xcode,
goto AppStore and install Xcode
To install homebrew:
Open terminal and run following commands
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew doctor
brew update
To enable NTFS write support:
Open  terminal and run following commands
brew install ntfs-3g
sudo mv /sbin/mount_ntfs /sbin/mount_ntfs.orig
sudo ln -s /usr/local/Cellar/ntfs-3g/2014.2.15/sbin/mount_ntfs /sbin/mount_ntfs
brew install osxfuse
brew info osxfuse
Last command will display 2 commands, which will look like following:
sudo /bin/cp -RfX /usr/local/opt/osxfuse/Library/Filesystems/osxfusefs.fs /Library/Filesystems/
sudo chmod +s /Library/Filesystems/osxfusefs.fs/Support/load_osxfusefs
Run them through terminal.

Now plug-in NTFS device and check the info. It will be read and write supported.

Sunday, August 24, 2014

QuickSynergy - Control multiple computers with single mouse and keyboard

QuickSynergy - Control multiple computers with single mouse and keyboard
Sometimes, we may have to access more than one computer simultaneously, and it is not convenient to use multiple mouse and keyboards.
To access multiple (mostly 2) computers at a time, one can use a KVM switch. It is a switch which toggles the access of peripherals between two computers. This is bit costly and KVM switches are not so common in electronics shop in your lane. So, here is an software alternative for KVM.

QuickSynergy:
It is a graphical interface (GUI) for easily configuring Synergy2, an application that allows the user to share his mouse and keyboard between two or more computers.
Also, your clipboard will be shared between the devices. Isn't it cool!!

Enjoy multi-tasking.

Tuesday, August 19, 2014

Mac: Spectacle - Resize windows with ease

Mac: Spectacle - Resize windows with ease
If you've migrated from Windows/Ubuntu to Mac OSX, then you might miss the feature of re-sizing the windows (with keyboard) and aligning them properly on top/left/right/bottom/center of the screen.
Though we can use the + and - on toolbar to resize, we won't get the expected behavior always :(
Recently I came to know about an app, called Spectacle, which comes handy to resize and position the windows with ease.
To know more about it and to get it, click here.

Friday, June 27, 2014

Code for Php based online Treasure Hunt

Code for Php based online Treasure Hunt
Hello guys.
Some time back I organized an online treasure hunt as part of an event at my college. I thought of sharing the code with you, as you might find it useful.
So, I uploaded it on github and here is the link to my repository.

Download it from here, and enjoy organizing the game

Tuesday, June 24, 2014

Ubuntu: Recursively delete multiple files with specific format

Ubuntu: Recursively delete multiple files with specific format

Sometimes we have to delete files of specific format (common extensions, ends with ~, etc) which were spanned over a group of directories. To do so, we follow certain methods.

Lets do it by an example.
In my case, I've o create the temporary files, i.e., the ones ending with ~.

Method 1: Delete them manually
Method 2: Goto each such directory and run the following command
rm *~

Method 3:
rm *~
rm */*~
rm */*/*~
rm */*/*/*~

First two methods need more time and to use third method, we must know the depth of recursion.

Following method will solve our problem.

Method Friendly: Run the following command from the parent directory from which you are deleting the files.
find . -name '*~' -type f -delete
This will delete all files ending with ~, from the current directory and also all its sub-directories.

Thursday, June 12, 2014

PHP : Set document root to be a subdirectory without .htaccess or Virtualhost

PHP : Set document root to be a subdirectory without .htaccess or Virtualhost
Recently I faced a problem with hosting a website on a server to which I have limited access. I was provided with permission only to a sub-directory on the server.
I'm habituated to use relative paths, but my root points to the root of server and not my sub-directory. This forced me to use absolute paths at every point.
I searched for the solution and end up with two results:
.htaccess ot Virtualhost
I never tried to understand .htaccess and I don't have access to set Virtualhost. This forced me to try bit harder and here is the outcome.

I've created a file named rootpath.php on root directory of my website.
(Note: this is not root '/' of the web server, but my sub-directory)
Its contents are as follows:
<?php
    $relative_path = "/subdirectory";
    $server_url = $_SERVER["SERVER_NAME"];

    $root = "http://" . $server_url. $relative_path;
?>
Now, I include this file on top of every file.
Eg: <?php require('rootpath.php'); ?>
and append all paths with <?php print $root; ?>
Eg: <a href="<?php print $root; ?>/index.php">
Note: Initially I used './' and '../' notation, but it won't work always. Consider the following case, which I faced:
/index.php
/header.php
/footer.php
/scripts.php
/contact
--contact/contact.php
I defined a common header for all the pages and stored it in header.php, which in-turn imports all the necessary scripts from scripts.php.
Now, if you import header.php from contact/contact.php, it work work properly because scripts.php is loaded relatively in header.php and now the control searches it in contact directory.

Tuesday, June 3, 2014

Find an old archived link on web

Find an old archived link on web
In recent past, I'm need of a tool, to which the provider no longer provides the link to download. Previously I've blogged about Openlogic, which serves this purpose.
Openlogic contains unofficial fork of the original repository, and to be precise, I haven't found the tool I'm in search of. I found Internet Archive : Wayback Machine, while searching for it.

It has got 412 billion stored pages and you may look into older versions of any website or you can get link to any software/tool which used to be a website.
All you have to do is, provide a link or part of a link to search.

For example, to know how my website used to be in 2013, just type
http://www.thechaithanya.com
and you can see a calender with some of the dates highlighted, on which they had the snapshot of my website.

You can even provide a part of link. For example, to get the link of older version of Android ADT, search using
http://dl.google.com/android/adt/*
You can find a set of links and pick your Magic Wand.

Sunday, May 25, 2014

Mac: AppleIntelCPUPowerManangement Kernel Panic

Mac: AppleIntelCPUPowerManangement Kernel Panic
After upgrading from Mac OS X Mavericks 10.9.2 to 10.9.3, my machine (HP Probook 4530s) ran into AppleIntelCPUPowerManangement Kernel panic, and to my surprise none of the boot flags helped me to boot into the system.
I decided to do a fresh install, but even booting from USB resulted the same. Then I decided to remove AppleIntelCPUPowerManangement.kext, but I can't even access terminal.

Here's the solution:
My machine dual boots Windows and Mac.

  1. I logged into Windows
  2. Installed MacDrive, trial version
  3. Rebooted into windows and opened the drive on which Mac is installed
  4. Did two things, don't know which one helped:
Opened /Extra/org.chameleon.Boot.plist with a text editor and added the following code:
<key>GenerateCStates</key>
<string>No</string>
<key>GeneratePStates</key>
<string>No</string>
And deleted AppleIntelCPUPowerManangement related kexts from this directory:
/System/Library/Extensions/
I found two kext folders related to it and deleted both.

Rebooted without any boot flags and voila. It worked.

Thursday, May 22, 2014

Mac: Access Mac formatted (HFS+) disks from Windows

Mac: Access Mac formatted (HFS+) disks from Windows Mac: Access Mac formatted (HFS+) disks from Windows
Recently I found a very easy and useful tool to access devices (USB, HDD, in-fact drive on which Mac OSX is installed), from windows.

MacDrive:
Once you install MacDrive, it will reboot and all the drives which are Mac-formatted will be mounted alongside the Windows partitions.
Having said that, there is a BIG problem. ITS NOT FREE. But, you can use the trial version, when in need.

Sunday, May 18, 2014

Ubuntu: Directory size from terminal

Ubuntu: Directory size from terminal

In this post we gonna see how to find size of a directory from Terminal. To summarise disk usage of each file, recursively for directories, we can use the following command
du [option]... [FILE/Directory]...
To get the report in human readable format, along with the overall summary, use
du -hs /path/to/directory

To find sizes of directories recursively unto a certain depth (e.g.: depth = 2):
du -h --max-depth=2 /path/to/directory

Friday, May 9, 2014

Ubuntu: Proxy settings for Maven

Ubuntu: Proxy settings for Maven
Recently I faced problem using maven under a proxy network and by little research, found this solution.
Temporary solution:
Add the following options along with your maven command
-DproxySet=true -DproxyHost=myproxy.com -DproxyPort=3128
For example, to run "mvn package":
mvn -DproxySet=true -DproxyHost=my.proxy.host -DproxyPort=3128 package

Permanent solution:
To add the proxy settings permanently, goto {M2_HOME}/conf/settings.xml and find the <proxies> section. Un-comment the required sections and configure accordingly.
To set proxy without password protection, change it as follows:
<proxies>
   <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>proxy.host.net</host>
      <port>80</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
  </proxies>
Change the words in italic format.

Sunday, May 4, 2014

Ubuntu: Recent command history (terminal)

Ubuntu: Recent command history (terminal)
Hello guys,
In this post I'm gonna show you "How to display and play with a list of recent commands in Ubuntu?".
To check history of command or to get info about command executed by user, we can use the following command:
history
It will display the list of all the command executed, along with a serial number indiacating the oerder in which they are executed.

Now you may feel it dificult to find a specific command among them. In order to do so, we can combine the history with grep.
history | grep version
This will display a list of command in which the word "version" has appeared.

We can also execute a specific command by knowing its serial number from this list. After getting the result from history command, just type the number preceeded by ! to execute the command. To execute command which is at number 115 in the list, just type
!115
It will run the 115th command in the history list.

To re-run a recent command that starts with xyz, just type !xyz.
!histo
It may display the recent history, if no other command would have been executed after recent history command.

And the most commonly used reverse search:
Ctrl + R
After typing this command, type a keyword to search. When you found your command, just press enter.

Tuesday, April 29, 2014

Reverse Engineering : Convert class or jar to Java files

Reverse Engineering : Convert class or jar to Java files
Previously, we have seen how to extract contents of .img file and also how to convert dex files to classes/jar.
In this post, I'm going to show a method to covert class/classes/jar file to java file(s).
To do so, we are going to use a tool, JD-GUI. It is a Java Decompiler, which supports all versions of Java, including java-7.
Download the application from here, and extract it to a proper location.
Now, open the terminal (in case of Linux) and run the following command:
./jd-gui
It will open the GUI window of Java decompiler.

Reverse Engineering : Convert class or jar to Java files

Just drag-and-drop a class/jar file into this window. In the left panel, we can find the corresponding java files, arranged in proper package format.
To save a single file, select it and choose "Save Source" from the top menu. And to save entire package, choose "Save all sources".

Troubleshooting:
You may ran into one of these problems, while trying to open jd-gui. Install the packages specified accordingly.
Error 1:
./jd-gui: error while loading shared libraries: libgtk-x11-2.0.so.0: cannot open shared object file: No such file or directory
Solution:
sudo apt-get install libgtk2.0-0:i386
Error 2:
./jd-gui: error while loading shared libraries: libXxf86vm.so.1: cannot open shared object file: No such file or directory
Solution:
sudo apt-get install libxxf86vm1:i386
Error 3:
./jd-gui: error while loading shared libraries: libSM.so.6: cannot open shared object file: No such file or directory
Solution:
sudo apt-get install libsm6:i386
Error 4:
/jd-gui: error while loading shared libraries: libstdc++.so.6: cannot open shared object file: No such file or directory
Solution:
sudo apt-get install lib32stdc++6

Monday, April 28, 2014

Reverse Engineering : Android Dex files to Class files

Reverse Engineering : Android Dex files to Class files
In my previous post, we have seen how to extract the contents of img file.
After extraction, you will find that most of the files have ".dex" extension. These are Compiled Android application code files.
In order to convert them into executable format (.class or .jar), you can use dex2jar tool.
Extract it to a proper location and open the terminal to this location.
Now run the following command:
./d2j-dex2jar.sh <Path-to-dex_file>
It will bundle the dex files into a jar file, and stores it in the current directory.
dex2jar can also be used to convert dex files into variuos other formats.
For detailed info, click here.

Thursday, April 24, 2014

Reverse Engineering : Extract contents from .img file

Reverse Engineering : Extract .img files of Android
Unyaffs is a program to extract files from a YAFFS2 file system image. Currently it can only extract images created by mkyaffs2image.

Download the source from here.

Compiling:
Extract the contents into a suitable place and run the following command
make
Usage:
unyaffs [options] <image_file_name> [<extract_directory>]
Options: -d detection of flash layout, no extraction -b spare contains bad block information -c <chunk size> set chunk size in KByte (default: autodetect, max: 16) -s <spare size> set spare size in Byte (default: autodetect, max: 512) -t list image contents -v verbose output -V print version

Source: Official github repository

Friday, April 18, 2014

Ubuntu: Problem installing flash player

Problem installing flash player
Recently, I installed ubuntu updates and my browser asked me for flash player, which was previously installed. i tried to install using the regular command
sudo apt-get install flashplugin-installer
But, it says
flashplugin-installer is already the newest version
Finally, I found the workaround. Previous installation has to removed first (which anyway is not working)
Run the following commands :
sudo apt-get purge flashplugin-installer
sudo apt-get install flashplugin-installer
Viola!! It works now.

Friday, April 11, 2014

Android: Failure [INSTALL_FAILED_UID_CHANGED]

Failure [INSTALL_FAILED_UID_CHANGED]

Today, I tried to install an application from command line and I found this error:
Failure [INSTALL_FAILED_UID_CHANGED]
After Googling for a while, I found the reason.
This happens when there is application data from older version is still present. To resolve this, clear/delete the following directory:
/data/data/<PACKAGE_NAME>
To do this, open terminal and type the following commands:
adb shell
cd /data/data/
rm -r <PACKAGE_NAME>
exit
Now try to install the application.
Viola.

Friday, March 14, 2014

Ubuntu: Change default location of localhost

localhost
By default, localhost (127.0.0.1) points to /var/www/ directory in Ubuntu. I prefer the location to be in my home directory.
To change the default location, open the file:
/etc/apache2/sites-available/000-default.conf
 and change it to look as follows:
(My wokspace is located at /home/chaithanya/www)

<VirtualHost *:80>
        ServerAdmin webmaster@localhost
        DocumentRoot /home/chaithanya/www

        <Directory /home/chaithanya/www/>
                Options Indexes FollowSymLinks
                AllowOverride All
                Require all granted
        </Directory>
        ErrorLog /var/log/apache2/error.log
        CustomLog /var/log/apache2/access.log common
</VirtualHost> 
Note: This works for Ubuntu 13.10+

Tuesday, March 4, 2014

Ubuntu: Install with video drivers disabled

Ubuntu: Install with video drivers disabled
When I tried to install Ubuntu 12.04 on my PC, it halted with 4/5 dots under Ubuntu. It's stuck at that point and no progress. Sometimes you may see some distorted image or white screen. All these problems are due to incompatible video drivers.

To get pass behind this screen and boot into the system, hold down SHIFT button while booting from CD/USB and press F6. Now select "nomodeset" option to prevent video drivers from loading.

Now you can install Ubuntu successfully. But you may face the problem again while booting (after installation). Then boot in "Recovery Mode" and install graphics drivers from GRUB menu or command line.

Monday, March 3, 2014

Ubuntu: rSync without git subdirectory

Ubuntu: rSync without git subdirectory
Previously I blogged about a good backup/sync tool rSync.

While using it, I faced some problems. It replaced my .git repository and there by affected my git repo settings.
I found a way to exclude sync'ing some files/folders. For this we have to use --exclude option. To exclude git sub-directory:
rsync -a --exclude='.git/'
 And to include some specific files, (Eg: 'c' files)
rsync -a --include='*.c/'

Source

Sunday, March 2, 2014

Ubuntu: Access a usb flash drive from the terminal

Access a usb flash drive from the terminal

 

 

1. Find what the drive is called

You'll need to know what the drive is called to mount it. To do that fire off:
sudo fdisk -l
You're looking for a partition that should look something like: /dev/sdb1. Remember what it's called.

2. Create a mount point

Create a new directory in /media so you can mount the drive onto the filesystem:
sudo  mkdir /media/usb

3. Mount!

sudo mount /dev/sdb1 /media/usb
When you're done, just fire off:
sudo umount /media/usb


Source: StackOverflow

Friday, February 28, 2014

Some Useful Firefox Add-ons

Some Useful Firefox Add-ons
Following are some of my favourite firefox add-ons
1. DoNotTrackMe
Protect your privacy. Stop companies and advertisers from tracking your browsing and sending you spam email.
2. AdBlock Plus
 Blocks annoying video ads on YouTube, Facebook ads, banners and much more. Adblock Plus blocks all annoying ads, and supports websites by not blocking unobtrusive ads by default (configurable).
3. BugMeNot
Tired of creating multiple accounts on various websites, bypass compulsory web registration with the context menu via www.bugmenot.com.
bugmenot

4. DownThemAll
The first and only download manager/accelerator built inside Firefox!

downthemall

5. Flash Video Downloader
Flash Video Downloader helps you to download any video (flv, mp4, HD) from YouTube-like, Facebook, Break, Metacafe and more in one click. You can download mp3, music (iPod), avi and more. Download Flash games. Download Helper.

Friday, January 24, 2014

Ubuntu: Make bootable Windows USB

 Make bootable Windows USB  Make bootable Windows USB

Recently I came across Ubuntu version of WinUSB, a popular tool to make bootable Windows USB.
I found it to be easy and simple.
Here is the official website, where you can get this tool.

Saturday, January 4, 2014

Ubuntu: Rsync

Ubuntu: Rsync

Rsync is a fast and extraordinarily versatile file copying tool. It can copy locally, to/from another host over any remote shell, or to/from a remote rsync daemon. It offers a large number of options that control every aspect of its behavior and permit very flexible specification of the set of files to be copied. It is famous for its delta-transfer algorithm, which reduces the amount of data sent over the network by sending only the differences between the source files and the existing files in the destination. Rsync is widely used for backups and mirroring and as an improved copy command for everyday use.

Rsync is installed in Ubuntu by default. If you need a GUI front-end, install Grsync. It is available in Ubuntu Software Center and also Synaptic package manager.

Usage:
Local backup
sudo rsync -azvv source/ destination/
Remote Backup

sudo rsync --dry-run --delete -azvv -e ssh source remoteuser@remotehost.remotedomain:/path-to-destination/
An explanation of above options to commands:
  • --dry-run This tells rsync to not actually do anything. It will just write a log of what it would do to the screen. Once you've made sure everything will work as you expect, you have to remove this option, and run the command again to perform the actual backup.
  • --delete deletes files that don't exist on the system being backed up.(Optional)
  • -a preserves the date and times, and permissions of the files (same as -rlptgoD).
  • With this option rsync will:
    • Descend recursively into all directories (-r),
    • copy symlinks as symlinks (-l),
    • preserve file permissions (-p),
    • preserve modification times (-t),
    • preserve groups (-g),
    • preserve file ownership (-o), and
    • preserve devices as devices (-D).
  • -z compresses the data
  • -vv increases the verbosity of the reporting process
  • -e specifies remote shell to use 
 Source: Ubuntu Community