Sunday, October 2, 2011

WT..! Where's my recovery? ;)

Now, the title explains it all! You have taken great pains and care to put a nice and warm recovery into the recovery partition only to reboot your phone and find it missing! :)

That's the feeling that rises out of this situation! Fret not! Not your mistake. That's how Android boot process works!

It took me some digging to find this out and overcome this feeling I mentioned! :) So here goes!

As part of the boot process and init, android runs a script that erases any custom bootloader and replaces it with Google, not much helpful recovery (or should I even call a scary, exclamated picture, a recovery?! :))


The script being at /system/etc/install-recovery.sh
and the patch at /system/recovery-from-boot.p

Now that you're God, nothing prevents you from killing these two little mortals.
Install ES file manager, an open source, root enabled file manager from the market and delete these two files and your reign is now safe! or you could run this zip from the recovery to do this deletion for you.

Being a rooted phone, you can henceforth install the ClockWorkMod recovery from Android market itself. It's called ROM Manager. And from within it, you can flash the recovery whenever you need. You can explore ROM manager to find more useful tools (rom installation, fixing file permissions, flashing any other versions of the recovery, etc.)

Now why not install CyanogenMod and have some fun!? huh?

3. Install the super user binary

After you are done with

1. Unlocking the bootloader
2. Flashing a custom Recovery into Nexus S,
follows the final step in the rooting process!

1. Download super-user app (a zip file) from my dropbox (v2.3.6.1). This's just a backup, in case you can't find it's latest version online.

2. Move it to the root of the SD card

3. Reboot the phone into the recovery, by shutting down and turning on with Vol Down + Power button.

4. On boot screen, select recovery with vol down and confirm with power button.

5. Once into the recovery, select 'Install zip from SD card'.
(Remember, the only button you can use are vol up/down and power buttons.)

6. Select the super-user zip file (su-2.3.6.1-ef-signed, in my case) and confirm installation.

Kudos! You've successfully rooted you Nexus S! Give yourself a tap on your back! :)

Into your phone, you will find the Super User app in your Appdrawer (for your use) and the super user binary will be in the path of your device (for other apps requiring root permissions to use)

Now for the tiny glitch - loss of custom recovery after reboot!




Monday, September 19, 2011

Numbered buffers in Vi

Been so long since the last post on Vi! Now time for another post! especially after my colleagues had trouble with named and numbered buffers!

If you haven't already taken a look at the earlier posts on Vi, here's what you need!

Named buffers are already discussed. It's now time for the numbered ones. I haven't  elucidated on the numbered ones.. so here goes!

Unlike named buffers, in numbered ones you can't decide, into which of the numbered (1-9) buffers your text goes. Because it's done automatically. When you delete or yank(copy) text without mentioning the named buffers, it automatically gets pushed into the 1st buffer referred by 1. So the recent buffer is always 1.

When another operation of yanking or deleting follows at a later time, whatever was already in 1, goes to 2 and the most recent one gets to 1. More like a stack!

Good! Now what if whatever was in 1 has gone down to 9... after 9 successive cuts/copies?! The 10th ie the recent most copy will move to 1 as said and whatever was in 9 gets lost, since 8 has now moved over to 9! Now that end is a FIFO!

Why do I need something over which I don't have control of! "What use?" you shall ask?! Now it's very much useful because if you happen to need your 2nd to recent cut/copied text... (previous to the recent cut)

Simple!

"2p

Done! third?!

"3p

and down to 9! Happy coding! or rather editing (who says vi is for coding only ;) )! 

2. Flashing a Custom Recovery into Nexus S

A typical Android device contains a few partition, the most important being
  1. boot
  2. recovery
  3. system
  4. cache
  5. userdata
The recovery partition can be flashed with a .img file. The basic recovery that comes with stock android has nothing more than the android mascot image with an exclamation symbol!

Replacing this with powerful recoveries like Amun-Ra or Clockwork Mod(CWM) gives you opportunities beyond imagination to play with your device!

The procedure mentioned below uses CWM. You can obtain it for free from the official site. Just get the latest version for 'crespa' the code name of Nexus S.

Flashing custom recovery from within Android requires the phone to be rooted and it's no more different and installing an app from the Android market itself. You could search and download it off Google Android market and follow the simple UI provided.

Although since now, we consider the phone out-of-the-box unrooted, it requires the phone to be in fastboot mode as mentioned in the previous post. (Unlocking the bootloader)

Once in fastboot mode, run the following command on your desktop's terminal.
 
fastboot flash recovery path_to_recovery

That should do the magic. Once done, you can scroll down to the 'recovery mode' in the bootloader menu using the volume button and selecting it with the power button.

Voila! There's you CWM recovery.
 
btw fastboot reboot on your terminal will also remote reboot your phone just like the 
reboot on your bootloader menu.




Just a word of caution: This recovery isn't going to remain here forever. After a complete reboot, this recovery will be lost due to an android-script that runs at boot time, which will replace the stock recovery. A couple of system files will have to be deleted to prevent that. That can be achieved after rooting the device.








Tuesday, September 13, 2011

Google Bookmarks in chrome

If you are like me, using a hell lotta bookmarks and use the ALL POWERFUL Google bookmarks (the same one Google toolbar uses in firefox, ie etc), then you probably hate Google's move to Google docs for chrome's bookmark sync. Sync could be good, but I can't lose my old ones at Google bookmarks.

Now, you want to use the super-chrome's super features :) and toolbar of firefox which sadly is not available with chrome. Here's the solution to all!


To Google bookmark a page in Chrome

To bookmark the current page, I click myBookmarks button. (You can see in the screenshot that I file it under Send to, but you can put it anywhere.) I optionally edit the title and add tags to make it easy to find later, and click Add bookmark.
At this point, my Google bookmark is saved and I can access it later from anywhere.

To return to a Google bookmarked page in Chrome

To find a Google bookmark page, I use search, naturally. In the address bar (a.k.a. the omnibox), I type gb (for Google Bookmark), press Tab orSpace, type search word(s) that match the bookmark name or tags, and pressEnter. On the results page, I click the bookmark I wanted.

To add these customizations to Google Chrome

To create the Bookmarks button, drag this bookmarklet to the Google Chrome bookmarks bar: Google Bookmark (or do the same thing from Google’s help page Bookmarks: Using Google Bookmarks, which is where I got it).
You can, of course, add the bookmarklet to a folder, as I did.
To add Google Bookmark search to the Chrome address bar, right-click in the address bar, choose Edit search engines…, click Add, fill out the form as follows, and click OK:
Name:
Google Bookmarks
Keyword:
gb
URL:
http://google.com/bookmarks/find?&q=%s
(In the Search Engines window there is also an option to make this the default search, if you wish.)

Rooting the Nexus!

Rooting:

Rooting is a process that allows users of mobile phones and other devices running the Android operating system to attain privileged control (known as "root access") within Android's Linux subsystem with the goal of overcoming limitations that carriers and manufacturers put on some devices. It is analogous to jailbreaking on devices running the Apple iOS operating system.

That's how Wikipedia defines it! In short, you become the admin user a.k.a God! :) and mess up things the way you love!

I understand that the word Jailbreak sounds more like an illegal activity than 'Rooting' does. And actually their intentions are similar to their phonetics and so are the companies' views on them! Apple wants to prevent Jailbreaking on their devices while Google support rooting theirs! :)

Google is in fact urging it's partners, the hardware manufacturers to impose less restriction on the hardware/software and encouraging them to let the users decide how they want their phones. Although Android is now running more than just phones. For instance Android now runs Barnes & Nobles' e-Reader 'Nook', Sony's new Z-series Music Player, just to mention a few.

On that front, HTC has now officially released instructions along with the required tools, on their websites, to help customers unlock their phones.

The Nexus S comes with an awesome bootloader from Google that makes unlocking and rooting the devices the easiest! Easier than on any other phone.

Rooting the phone requires installation of a super user application on the device. Now the super user tool comes in two pieces - the binary which does the rooting and then the app that lives in the App drawer of the phones that gives and GUI to manage grant and revocation of SU rights to any other app as and when required.

The following is the breakup of the steps and each step is explained in detail in separate posts. This is to enable you to understand what you're upto and hence not again read the lines "Don't do this if you don't know what you're doing"!!!
  1. Unlock the bootloader
  2. Install custom Recovery
  3. Install the super user binary (& app).

1. Unlocking the Bootloader

The bootloader of the Nexus S is locked initially. You'll have to unlock it using a tool called fastboot. Warning: Since unlocking the bootloader and rooting the phones gives access to all the private data, by circumventing the Android's security model based on Unix, all your phone's data and data on the internal SD card will be erased for security reasons. Hence take a backup of the important data into your computer before you proceed.


You should have Android SDK installed in your machine. For this tutorial, I use a mac. Post Android SDK installation, download and place fastboot (which is just a single binary file) in your path or if you're comfortable, run it from any directory, using a terminal.

I would prefer you to place fastboot in the 'tools' directory of your android SDK installation.

Step 1. Reboot your phone into the bootloader by shutting it down and then turning it on by holding the volume up button + power button and you should see this.

Step 2. When on the bootloader screen, connect your phone to PC/Mac and run the command

fastboot devices
which should give an output similar to

List of devices attached 
HTXXXXXXXXXX	device


Step 3. Once, it's confirmed that your device is recognizable by fastboot, run the following command to unlock the bootloader. 

fastboot oem unlock
 
Read the warning on the phone and accept it.  That's it! Now you have an unlocked phone or bootloader, perhaps! :D This can be confirmed by seeing noting the last line on the first paragraph of the bootloader screen that reads

LOCK STATE - UNLOCKED

Next you shall run  

fastboot reboot
reboot your phone. Another hint to know that your bootloader is unlocked is to reboot your phone into the os and you can notice that beneath the Google logo appearing while it boots, there should appear an unlocked-lock icon!

It should be no surprise that you can run

fastboot oem lock
to lock the bootloader if you wish!

Wednesday, May 18, 2011

Keep Apple trailers with you!

If you're like me and love watching trailers over and over especially in HD, it's frustrating to watch them online at Apple trailers.  You would want to use a Download manager but what better than wget?!

And it's not that easy when you are a mouse-hater! Yes I know how frustrating it is to reach for the mouse/trackpad when you love the keyboard! So here's a shell script I made to ease it! (You'll need to have wget installed though)

It's not 100% perfect. I've still got more options to add and make it better. But for now...

(I'll be adding explanation soon...)
Credits for whoever wrote that Regex for the url!

An eg:  Enjoy an awesome Harry potter trailer here!
atget http://trailers.apple.com/movies/wb/harrypotterandthedeathlyhallowspart2/harrypotterhallows2-tlr1_720p.mov



#!/bin/bash
# atget - download trailers from Apple trailers


# Usage if no parameters given
if [ $# -eq 0 ]; then
  echo "     Download Trailers from Apple iTunes website"
  echo "     usage: atget [-c] "
  echo "     where "
  echo "            -c    Resume incomplete download" 
  exit
fi


#Should resume download with wget?
wgetc=


if [ "$1" = "-c" ]; then
  oldurl=$2 
  wgetc="-c"
else
  oldurl=$1


  filename=$(basename $oldurl)
  save_location=$HOME/Movies/$filename
  if [ -f $save_location ]; then
  echo -n "File exists with same name already! Overwrite (o) / Resume (r)? "
  read result
wgetc="-c"
  if [ "$result" = "o" ] || [ "$result" = "O" ]; then
wgetc=
fi
# exit
  fi
fi


# Prepend 'h' before resolution to create a valid url
newurl=$(echo $oldurl | sed 's/_\([0-9]*[0-9][0-9][0-9]\)p.mov/_h\1p.mov/g')


filename=$(basename $oldurl)
save_location=$HOME/Movies/$filename


# Download trailer and save to Movies folder of the user
wget $wgetc -U QuickTime "$newurl" -O $save_location



Thursday, January 27, 2011

Android Hello, NotePad tutorial

If you have been following the notepad tutorial at Android's developer page here, everything would go fine until you reach Part 2. It spits out quite a lot of errors, when you import the example code given for the second section. There is no solution in one place for the errors you encounter. Worse, the solutions found around the web, put together also doesn't work at times. So following is what has been missing - A one stop solution!



Warning: This's not for you, if you're completely new to Android. You must be ready for the Notepad tutorial with quite the basic knowledge of resources, build targets etc.

Problem 1: String types
To start with, the part 2 of the Notepad tutorial (hence referred as N2), is built against API level 8 (Froyo).
If you are adamant to only work with the API version your phone is running (mine being 7 - Eclair) and not even install the higher versions, then BANG, that's the cause of 

Error: String types not allowed (at layout_height with value 'match_parent')
Error: String types not allowed (at layout_width with value 'match_parent')

Solution 1:
Install a new build target 'API level 8' using the Android AVD and SDK manager, change the build target  property of the project. 

or You only want to stick with Eclair, change the layout properties (in note_edit.xml) from match_parent to fill_parent. Match_parent is a new attribute added in API 8.

Problem 2: R resolution

The resource file R that has to be generated by Android SDK for you, is not being generated.

Solution 2:
A) Manually clean the project in Eclipse (Project > Clean)
and re-build the project. If 'Build Project is disabled, Force build the project, by unchecking 'Build Automatically'.

If that doesn't work,
B) Delete the 'gen' folder and create new 'source folder' named 'gen' in the project. Re-build project.

Problem 3: 

"The project cannot be built until the build path errors are resolved"

Occasionally this error might also crop up. In that case, modify the build path of the project. I understand, that's confusing! Although you don't need an external library, just add any third party jar file in the build path and save the settings and later remove it.

This's to force eclipse to refresh it's Build-path settings.

Happy Programming!!!


Saturday, July 24, 2010

Take a bite off the elixir

I always get this question: Why a mac? Why pay so much for that piece of gadget (or contraption as most feel it is)?

Now I think it's high time I etched down the answer to that.

Firstly, I admit, it's almost impossible to convey certain emotions. (No kidding) You need to experience it to really understand that. Similar is my state with a mac. So, I'll try my best at it.

Before I even start, shall we clear the fog surrounding some 'Apple' 'terms'?

Mac: The hardware and software both are called Mac. There are a myriad of hardware designed and manufactured by Apple. Let me just list the computers.

      iMac: A desktop computer with your CPU tower built into the monitor itself. 
      Mac Mini: A BYODKM computer. Display, Keyboard,  Mouse separate.
      MacBook: A notebook (laptop)
      MacBook Pro: Notebook with extra cost ;-), extra cosmetic value, extra power
      (nowadays macbooks are equally powerful)
      Mac Pro: A BYODKM computer again but a very high end machine, with a form factor like the
      usual CPU towers we get and very costly too.


OS X: Jargon for mac OS version 10 which is the latest series of the OS
  1. Version 10.0: Cheetah
  2. Version 10.1: Puma
  3. Version 10.2: Jaguar
  4. Version 10.3: Panther
  5. Version 10.4: Tiger
  6. Version 10.5: Leopard
  7. Version 10.6: Snow Leopard ( The lastest as of Jul 24, 2010 )
PC: Apple Inc. has chosen to call the computers running windows as PCs and their products as Mac. But in common terms, you can always call any computer you use at home or office (if you alone use it) a Personal Computer :-). Blame Apple for that!

With that done, let me start with myth-breaking...

A mac is difficult to use. It's for the geeks.
      Never. It can be used by anyone. Anyone who thinks can use a PC can use a mac. But yes, designers and developers use more of mac. That's because Mac is a blend of power and elegance. Power for geeks and elegance for noobs.

There isn't lotta software that is compatible with mac
      That was true when Apple stuck to its in-house PPC processors. Now that they are using Intel's Processors, times have changed. Almost any software you run on a PC (grrr. See that's how Apple's vocabulary infects you. Results from prolonged Mac usage) err..., Windows machine has a Mac counterpart. Most times, a better alternative is available on a mac.

A Mac can't run Windows
     Similar the previous myth. Now you can either run it natively like on a PC ( Forgive me. Honestly, it's difficult to adapt to this new vocab. Hence, PC = Windows machine in this post). or on a Virtual Machine like VMWare. Dual boot is very simple too. You can have both OS with no restriction. Apple gives you all required drivers too. Although I'll bet, you wont use windows once you use a Mac. 

A mac is costly
      That's INITIALLY true. It IS costly compared to other hardware that's available in the market. But believe me, it's WORTH IT. For the performance, the productivity, the life style, the peace of mind you get, YOU CAN PAY IT, actually more too. That's the thing that helps Apple have the nerve to price it so high. People fall in love with the mac. It's not everyday you buy a computer, is it?

If you ask a mac user a question: One mac or 4 PCs? What do you want?
An easy to guess answer: ONE MAC!!!

Now some personal advantages from my vantage point:

1. No crashes: Yeah. No crashes. It just works!!! Of course nothing is perfect. Software on macs crash too. But not even once in a blue moon. Even more rarely. 'Crash' is off your dictionary => No every- month-format-and-OS-reinstall.

2. No Viruses: Since, Mac OS under the hood runs over a flavor of Unix, (For more info, read abt Darwin) windows viruses are petrified in it.

3. Stable everything: Since the hardware and software are from Apple, it's the perfect marriage. So no incompatibilities. Almost all external hardware available in the market - printers, etc work well too.

4. Developer's haven: For software people like me, it's like having a Linux installation inside my everyday OS. I don't need a separate installation of Linux. You have the BASH and everything a developer needs already in here. Apache server, PHP, SNMP daemon etc. are already in there. For other tools, you can CONFIGURE, MAKE AND MAKE INSTALL from sources! Now you know why almost almost all conference videos have glowing Mac logos on the podium. Google geeks love Macs too.

Buying a mac was one of the best choices of my life. Actually, I wouldn't hesitate to say, if you are intelligent, YOU WOULD BUY A MAC.

யாà®®் பெà®±்à®± இன்பம் பெà®°ுக à®‡à®µ்வையகம்!
No. No kidding. I don't hesitate to pester my friends into buying one because which good friend wouldn't want his mates to enjoy the same life he does - trouble free. It's not an exaggeration when I say, "A mac changes your LIFE STYLE!"

That is why, I call a mac, An Elixir! An elixir to all the viral infections you might expect. A real macintosh for the crap rain you are in!

 Many people around me mistake me for an Apple evangelist. Unfortunately, I don't go behind brands. Never. I just go behind the best that every brand has to offer! :)

Wednesday, June 23, 2010

'Move' with automator

Automator : Create automations without programming

As simple as it might be, yes automator is a over looked, under estimated tool available in Mac OS X. 
Any one with no programming knowledge too can with point-and-click knowledge can create workflows to achieve almost anything. Although personally, I'd recommend it as a great tool for repetitive tasks such as renaming, etc! Or some task that's not repetitive in a single stretch but something that you might perform now and then like backing up your data, etc.

Here are the basics. You create a workflow that's more like flow chart. Top to bottom, the actions that you define are executed, with one's output being sent to the next on the line.

Actions are categorized on the left most (library) pane, shown in the screenshot below. The actions under the selected category are in the pane to the right of it.

Nothing gets easier than using an example: the one that I quoted in my previous post: Moving files under multiple folders into a single folder.


In our scenario, the folder named 'Jdownloads' contains 11 folders named as

Ubisoft E3 2010 Conference [Part 1 of 11] - Child of Eden(HQ)
...
Ubisoft E3 2010 Conference [Part 11 of 11] - Michael Jackson The Game

The contents of these must be moved to 'E3 Conference'. A mundane task that I hate to do with all those mouse clicks or key board hits (I mostly use the keyboard). Whichever way, I HATE to do this!

So define the 3 actions shown in Fig. 1. 
  1. Find Finder Items     ---- (A1)
  2. Get Folder Contents ---- (A2)
  3. Move Finder Items   ---- (A3)
A1:
This action can be customized with the search options it provides. It under the hood just uses the 'search' Mac provides. So am gonna just search for the 11 folders. How do I do that? 

Look under the Jdownloads folder, for 'folders' that contain the text 'e3' in the name. The action and it's results on single-stepping are shown below. Don't be flabbergasted by the result: 12 folders. The extra 12th is the output folder. No harm done. It's empty anyway :)



A2:
Iterate through all the folders of the previous result and get their contents. In this case, 1 file in each foler adding up to 11 files.



A3:
Move the items to the specified folder!

As simple as that. Now, I could've also deleted the source folders after the move. But why don't you just try that, hands-on!


Thursday, June 17, 2010

Automator to the rescue

    The long awaited E3 conference is here and I couldn't wait to watch Ubisoft's stall & developers staging its latest mind-blowing games! Wow! Assassin's creed bloodlines is going to awesome & a new Michael Jackson game for fans is rolling out soon! (For those of you wondering what this E3 conf is... it's all about games - Hardware & software. Why don't you follow the wiki link or E3's link?)

Jdownloader helped me persist the youtube videos in my HDD to watch later. The low quality videos (all except AC Brotherhood in HD ;-)) were downloaded, thanks to JD. Problem popped up when each single video was individually downloaded into a separate folder. Now I have to move every little file into some folder, say 'E3 Conference'. Or..... why not use automator of Mac OS X!

For newbies, Automator is an app that can be used to automate your jobs. (Now, Cool down! I know that didn't help! ;-)) A simple example: Remember that hundreds of pics that you captured on a tour and wanted to rename them one by one. It must've been exhausting... You thought of completing it later. Only that later never came.  Things like that can be done easily.

Our problem definition again: 11 videos. 11 separate files in 11 different folders. I hate too much branching (folders here).

Expected results: 11 videos in 1 folder.

You know the usual solution of course(Drag, drop, delete)! Now to the automator kinda solution!

To give you a clear picture: Here's how the folder looks before running the automator workflow.



And here's how it looks after moving them!




Here's the tiny workflow with just 3 actions that achieved this!


If that doesn't make sense, no worries! The following post will clear the fog!

Wednesday, June 2, 2010

Python: Module search path



When a module named spam is imported, the interpreter searches for a file named spam.py in the current directory, and then in the list of directories specified by the environment variable PYTHONPATH. This has the same syntax as the shell variable PATH, that is, a list of directory names. When PYTHONPATH is not set, or when the file is not found there, the search continues in an installation-dependent default path; on Unix, this is usually .:/usr/local/lib/python


Actually, modules are searched in the list of directories given by the variable sys.path which is initialized from the directory containing the input script (or the current directory), PYTHONPATH and the installation- dependent default.

Now what if you have not specified PYTHONPATH during installation? How do I edit it?

Suppose, I have my module spam.py in ~/geekcode/python. I have my other program user.py that needs to the aforementioned module.

This module search path is comparable to CLASSPATH in java.

To add ~/geekcode/python to PYTHONPATH, in your interactive mode of the Python interpreter, edit the path variable in the sys module.

>>> import sys
>>> sys.path

Printing sys.path as shown above will show up your current PYTHONPATH.

This sys.path is just another mutable python list. Hence you can easily edit it using the usual list methods, here, the append method.

sys.path.append("/Users//geekcode/python")

The only drawback of this method is that, this setting is forgotten once you restart the interpreter. 

To persist this setting, you can use the '.pth' file.  A '.pth' file with any name like 'foobar.pth' can contain any number of newline separated list of paths you need to add to PYTHONPATH aka path aka sys.path variable. It is similar to .bash_profile or .profile files of Unix systems. The paths in .pth files are added automatically to the PYTHONPATH variable whenever the interpreter restarts.

All said, now the question is, "Where do I place this .pth file?". It can be placed in any path that is already mentioned in sys.path! EASY!

Tuesday, April 13, 2010

Eclipse - code formatting for Beginner!

First things first! Eclipse is a Open source IDE, an Integrated Development Environment for development using languages like C, C++, PHP (both dynamic and static) for different platforms like mobile, embedded, thick and thin servers!

Two Myths broken!
1. It doesn't come with the development kit unlike Visual studio!
2. It is not for just Java.

So, with the SDK pre-installed on your machine, run your copy of eclipse that you can download for free at the eclipse project website.

This post will hence discuss about the Eclipse for J2SE although most features are same in J2EE version too!

One most important issue most developers like me spend time on is not on the code-logic but the alignment of the code! :)

So here's what you hate when you write your code in Eclipse - The alignment of the braces!

class HelloWorld{
   public static void main(String[] args){
       System.out.println("Hello World");
   }
}

which we always like to see as,


class HelloWorld
{
   public static void main(String[] args)
   {
       System.out.println("Hello World");
   }
}


Eclipse says YES to you! Go to the preferences dialog (Cmd + , in the mac) and search for 'formatter' in the filter text-box or browse your way through Java > Code Style > Formatter.




There you have it! Click edit and you can change EVERY aspect of code formatting from indentation to how your comments appear in your code window!

You might be interested in setting your braces as shown below: (The changes your make are immediately reflected on the preview pane on the right. This comes real handy!)

Also for beginners, this might be useful!

Unlike Visual studio, the code that you type in Eclipse is not auto formatted when you type the code, letting the choice to be yours!

If you want a section formatted properly, after typing in a hurry, you can at anytime select just the section  and hit cmd+shift+f to format it or without a select, if you perform the same command, the entire code is formatted.

You can also correct indentations alone with cmd + i. You can find these under the source menu in Eclipse!

Sunday, April 11, 2010

Some handy vi args!

Say you compiled a program called test.cpp and the compiler spitted the error
"test.cpp:97: error: ‘itoa’ was not declared in this scope" 
at you!

Mostly, you do one of the following!
Open the file and 
a) Scroll through it!  (See line numbers with :set number  or   :set nu )
b) Jump to line 97 which you can achieve by 
i) 97G   (vi command itself)
ii) :97 enter  (ex editor command inside vi)

You can achieve this easily with the command line args itself (those that are supplied when you open vi. The file name itself is one such arg)!

vi +97 test.cpp will open file with cursor at the 97th line!

Now what if you are like me and are bad with numbers? Can't remember 97?

vi +/itoa test.cpp will perform a pattern matching and will open the file at the first match. You can then use n or N to skim through the matches until you land on your line! 


Bonus tip! :) 

Ever wished vi has alt+tab (on windows/linux) or cmd+tab (on mac) to switch between two files? It has it too! :D

Just open two or more files with all the names as args to the command!

vi file1 file2 file3 file4 file5

You will be editing file1 initially!
Check which file you are editing with ex command :args or :ar 
Vi will print
[file1] file2 file3 file4 file5 
showing the current file in brackets and the entire list that you supplied!

Move around the list with :n and :N. To jump to the first file on list use :rewind or :rew and :last for the last file!

Ooops! Now to issue of concern alt+tab! 
Once you have at least once switched between the 2 files that you need to edit alternatively, use :e # to switch between files!
or simply ^^ (Ctrl + caret)
What if you have find that you need to edit file1 and file7 alternatively but forgot to open file7??? Wait! Don't quit vi!
When you are editing file1 just call in file7 with :e file7 (e for edit) and there you have it! Now use ^^!  

As mentioned in an earlier post, you can use the clipboard to move text around the files!

Though the y (yank) and p(put/paste) commands are handy you can't easily do that for multiple lines!
use :line1,line2ya  c for copying/yanking multiple lines (where line1 = starting line number; line2 = ending line number; cn = a-z one letter clipboard name)

Switch to your file you want now without exiting vi and

then :pu c will put that clipboard c's content into the new file!
(A word of caution! The switching between files can happen only if the file you are editing is saved)

Now that's why vi is a Very Interactive editor!

Saturday, April 3, 2010

vi has a clipboard too!


The very interactive(vi) editor has all that your GUI based editor has! Actually, it has more! Adding to all the basics, here are some key-taps that can help u tap the power of VI.

When you hit 'd' based delete commands like 'dd', 'nd' ... or 'y' based yank commands all that's is deleted or yanked is stored in a buffer. (Ssh! Deleting with d is not delete, it's actually 'cut'. Try 'p'-ing to paste after 'd' :) )

So where does it actually get stored? It's not one but 2 buffers!

Deleted lines are stored in a numbered buffer, named from 1 to 9. (stack like. recent entry is 1, oldest being 9)
You can yank/delete into alphabetically named buffers too (a-z).

"(double quote) is used to access this a-z buffer.

" is the simple syntax

Eg: "c5dd will delete/cut 5 lines in to buffer named 'c'

(simply 5dd will not cut into the buffer)

Interesting part is "C3dd will append your now-deleted 3 lines to your previously present contents of buffer 'c'. (Note the upper case.) You can't do this even in MS word!!!

Paste the buffer using "cp     ( "c for accessing buffer and p for paste/put )


Same works for yanking too!

To access the numbered, deletion buffer, use "np where n is number 0-9 similar to a-z.

Ain't that something!!!!

Tuesday, March 23, 2010

Algorithm to convert given SQL Query to Relational Algebra

For the benefit of those who were looking for a logic on how to go ahead and implement this for lab exercise.

- My program will take a SQL Query as one whole string in the command line.
- splitInputQuery will split the SQL Query based on space.
- parseSQLQuery will take one word at a time from the SQL Query and set some global flags.
- decideRelAlgebra will make a decision on what could be the Relational Algebra equivalent based on the flags set in parseSQLQuery.

Eg:
SQL: "select * from E"
RA: PROJECT E

SQL: "select name from student"
RA: PROJECT name student

SQL: "select * from student where name=neo"
RA: SELECT name=neo student

SQL: "select name,roll_no from student where name=neo"
RA: PROJECT name,roll_no(SELECT name=neo student)

Having shown the examples above, I am giving the algorithm(in the form of pseudocode) below. Hope its useful. Questions are welcome.

/Algorithm/
Algorithm used to convert simple SQL query to Relation Algebra:

/**********************************************************************************
* Description: This program is intended to take simple SQL queries and
* convert them to equivalent Relational Algebra
*
* Input: SQL Query as a single string Eg: "select emp_name from E"
*
* Output: Equivalent Relational Algebra Eg: PROJECT emp_name E
*
*********************************************************************************/
main(String[] args)
if (args.length <0)
return 0;
else {
/* args[0] will have the SQL Query */
if (splitSQLQuery(args[0]) == 0) {
call parseSQLQuery()
}
call decideRelAlgebra()
}

/**********************************************************************************
* Description: This procedure takes a simple SQL queries and split it based on space
* and stores them as a array of string
*
* Input: SQL Query as a single string Eg: "select emp_name from E"
*
* Output: split SQL Query as a array of Strings Eg: {"select" ,"emp_name","from","E"}
*
*********************************************************************************/

splitSQLQuery(inputSQLQuery) {
if (inputSQLQuery != null) {
/* if input is valid then split based on " " and save it in global array splittedInputQuery
splittedInputQuery = inputSQLQuery.split(" ");
} else {
return 1; /* return non-zero on error */
}
return 0;
}

/**********************************************************************************
* Description: This procedure takes split SQL Query array and parse them to find the
* equivalent Relational Algebra
*
* Input: Splitted SQL Query array
*
* Output: global flags are set to make a decision
*
*********************************************************************************/

parseSQLQuery() {
/* for all the strings in the splitedInputQuery do this */
for(int i 0 to no_of_strings in query) {
/* querystring is the current string form the splittedinputquery array */
if (querystring matches "select") {
/*then it could be select or it could be project in RA*/
set maybeProject to 1
continue to get next string;
}
if(querystring matches "*") {
set selectall to 1;
continue to next string;
}

if (querystring is of the pattern [a-zA-Z_]*) and (selectall != 0) {
set maybeAttribs to 1;
attribs = querystring;
continue to next string;
}
if (querystring matches "from") {
set maybeFrom to 1;
continue to next string;
}

if(querystring is of pattern [a-zA-Z-]*) and (maybeFrom is set) {
set maybeTable to 1;
tableName = queryString;
continue to next string;
}

if(querystring matches "where") {
set maybeSelect to 1
set gotWhere to 1
continue to next string;
}
/* to match with where patterns like Eg: name=N or roll_no=100 and so on
if(queryString is of pattern [a-zA-z_< > = <= >= !=0-9*]*) and (where is set to 1) {
set maybeConditions to 1
conditions = queryString;
continue to next string;
}
}
}

/**********************************************************************************
* Description: This procedure decides on the equivalent relational algebra for the given
* SQL Query based on the flags set by parseSQLQuery
*
* Input: SQL Query as a single string Eg: "select emp_name from E"
*
* Output: Equivalent Relational Algebra Eg: PROJECT emp_name E
*
*********************************************************************************/

decideRelAlgebra() {
if (gotWhere is not 1) {
set confirmedProject to 1
set relAlg to PROJECT
}
if (selectAll is 1) and (gotWhere is not 1) {
set confirmedProject to 1
set relAlg to PROJECT
}
if (gotWhere is 1) and (attribs is not null) {
set projectwithselect to 1
set relAlg to PROJECT (SELECT )
}

if (gotWhere is 1) and (selectall is 1) {
set confirmedproject to 1
set relAlg to SELECT
}
}

Friday, March 19, 2010

Very Interactive(VI) editor commands

This has been a request from couple of people, putting it down for them and for everyone who is looking for frequently used vi editor commands.

Edit commands:
-------------------
x - delete one character at a time
nx - delete n characters at a time, replace n with number you want
dd - delete/cut a line
ndd - delete/cut x lines (replace n with number you want Eg: 10dd would delete 10 lines)
yy - yank a line(copy to clipboard)
nyy - yank n lines(replace n with number you want Eg: 10yy would yank 10 lines)
p - paste from the clipboard(deleted lines are like copy too, they will be in clipboard, so p after dd or yy will paste whats there in the clipboard)

*Remember: All the above commands are relative to the current cursor position. i.e. If you are at line 20 and performing dd, line at that position will be deleted/cut. Similarly p operation will paste after 20th line.

More Edit commands:
--------------------------
dw - delete/cut a word
ndw - delete/cut n words (replace n with number you want Eg: 3dw will delete 2 words)
cw - change or replace word (move the cursor to the word you want to change and give cw, then type in the replacement word)
ncw - change n words at a time(Eg: 2cw will help you replace two words)
o - to insert a line below the line where the cursor is positioned
shift+o - to insert a line above the line where the cursor is positioned

Cursor positioning or movement:
---------------------------------------
<- or h - to move left -> or l - to move right
up arrow or k - to move up
down arrow or j - to move down
0(zero) - to move to the first character of the current line
$ - to move to last character of the line
w - to move cursor to the beginning of the next word
b - to move cursor to the first character of the preceding word
:0 - to move to the first line of the file(what you see here is zero)
:n - to move to the nth line of the file(replace n with number of your choice)
:$ - to move the cursor to the last line of the file

* CR- carriage return/Enter key in the keyboard

Scroll commands:
---------------------
^d (ctrl+d) - scroll half screen down
^u (ctrl+u) - scroll half screen up
^f (ctrl+f) - scroll full screen down
^b (ctrl+b) - scroll full screen up

(do it for yourself to see the difference, choose a bigger file to see the difference between these scrolls for yourself)

Search commands:
-----------------------
/string - to search for a string (replace string with your search string)
(n to find the next match, shift+n to find the previous match.

Search and Replace:
------------------------
:s/old_string/new_string - replaces the first occurrence of "old_string" with "new_string" in the current line (Eg:- :s/import/export will replace first occurrence of the word import with export in the current line)
:s/old_string/new_string/g - will replace all occurrences of "old_string" with "new_string" in the current line
:%s/old_string/new_string/g - will replace all occurrences of old_string with new_string in the file.

(**Remember everything is case sensitive here, to make your search & replace case insensitive see below)
:s/old_string/new_string/i
:s/old_string/new_string/gi
:%s/old_string/new_string/gi

see the 'i' at the end makes it case in-sensitive.

To perform search and replace between selected lines, you can use the commands below.
:l1,l2s/old_string/new_string/g - replace l1 and l2 with line numbers you want. (Eg:- :1,10s/import/export/g you know what this means... isn't it?)

Undo:
--------
u - to undo previous commands

Switching modes:
----------------------
i - insert mode
a - append mode
esc - to get out of any mode you already chosen

I will stop with these basic commands you would need to start.

In case if people need more useful commands at advance level, I will put a separate post later.

Happy VI'ing :))