Category: Everything

find & replace in multiple files using egrep & sed

Posted by – July 1, 2011

Programmers are lazy creatures. Any given programmer would love get things done with lesser keystrokes. For instance, find and replace all in multiple files. I was setting up a project on my localhost that some other guy had done. That guy wasn’t a real programmer otherwise what I did would have not been required at first place. The great soul hard-coded all the hyperlinks. What now? I thought of firing an editor and doing a find and replace all by creating a project. Simple. No. I can use grep/egrep to find things then obviously I can chain it to some other command and replace that text. Yes. I am lazy, so instead of experimenting I did some googling. Here is how to do this. Find all files, recursively of course, in current working directory that contain “teh” and replace them with “the”.

egrep -lRZ "teh" ./ | xargs -0 -l sed -i -e 's/teh/the/g'

egrep/grep takes further arguments like type of files to look for, example egrep “teh” *.txt ./ will search for all text files in current working direcotry that contain “teh”. Cool!

So, you can safely say, I can haz teh Linux power!

Dynamic subdomains using .htaccess or mod_rewrite

Posted by – December 7, 2010

The man page documentation page for Apache mod_rewrite module says, “Welcome to mod_rewrite, the Swiss Army Knife of URL manipulation!”

Believe me, mod_rewrite lets you do cool things with URLs. You can have one script for every URI request. For uninformed a URI is simply a request for a page or a website like: http://www.kumarchetan.com/blog/all-about-lamp-web-development-blog/ or http://www.shameless-self-promotion.org/about/. In both cases, the websites run WordPress blogging platform and use mod_rewrite. mod_rewrite sends URIs like http://www.shameless-self-promotion.org/about/ or http://www.shameless-self-promotion.org/get los to one server side script or program which knows how to deal with good and bad requests.

But mod_rewrite also lets you play with your domain name and you can have sub-domains on the fly. So you can, without messing up your DNS entries, create sub-domains automagically.  Look at the following mod_rewrite which was added to a .htaccess.

Options +FollowSymLinks
#Turn on the engine
RewriteEngine On
RewriteCond %{HTTP_HOST} ([^.]+)\.domain\.com
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ /%1/$1

Event Delegation: Save thou webpage

Posted by – October 3, 2010

To make a web page interactive web developers rely on Events on the page. Event handling could be as easy as reloading the page on click of a button or as complex as following mouse pointer and responding to it. The usual way to do this is onEvent do some thing.

<button name="aButton" id="aButton" onclick="alert('Hello World!')">Cliché</button>

Easy.

There are so many ways to handle events and then do something. Inline, shown above, unobtrusive, shown below.

<button name="anotherButton" id="anotherButton">Another Cliché</button>
<script>
document.getElementById('anotherButton').addEventListener('click', function(){alert('Hello World!')}, false);
</script>

One can add as many as event listeners required for an event occurring for an element. Well, not really a wise idea. Think of Gmail inbox set to display 100 emails in a row. Does that mean100 addEventListener? Not a good idea. Here comes a very simple technique called Event Delegation. Example

<ol id="olElem">
 <li id="li1">One</li>
 <li id="li2">Two</li>
 <li id="li3">Three</li>
 <li id="li4">Four</li>
 <li id="li5">Five</li>
 <li id="li6">Six</li>
 <li id="li7">Seven</li>
 <li id="li8">Eight</li>
 <li id="li9">Nine</li>
 <li id="lin">n</li>
</ol>
<script>
document.getElementById('olElem').onclick = function(e){
 e = e || window.event;
 var target = e.target || e.srcElement;
 var textClicked = document.getElementById(target.id).innerHTML;
 alert('You clicked ' + textClicked);
}
</script>

This is all due to Event Bubbling which simply means that an event bubbles up to document root. So, when I click on “Nine”, the element li9 tells its parent that it got clicked, which in turn informs its parent and so on.

Method chaining

Posted by – October 2, 2010

I love the way CodeIgniter explains method chaining by saying.

Method chaining allows you to simplify your syntax by connecting multiple functions.

As explained above it simply lets you do things like

FileObject->OpenFile('FileName')->AppendLine('Hello World!')->CloseFile()

Its neat. But in PHP, you have to have PHP5.x. This wonderful thing is also available in JavaScript. From jQuery home page

$("p.neat").addClass("ohmy").show("slow");

How to do method chaining?
To have an object chain methods every method in that object must return a reference to itself. Easy. Example?

<?php
class MethodChainingExample{
	public function methodOne(){
		echo __METHOD__." \n";
		return $this;
	}
	public function anotherMethod(){
		echo __METHOD__." \n";
		return $this;
	}
	public function oneMoreMethod(){
		echo __METHOD__." \n";
		return $this;
	}
}
$example =  new MethodChainingExample;
$example->methodOne()->anotherMethod()->oneMoreMethod();

PyGTK Hello World or: How I learned to write my first GUI application on Ubuntu?

Posted by – September 21, 2010

There are so many things I like about Ubuntu and I can write in extent about all those. My focus is in this post is Python. Python is easy to learn. So easy that one can write GUI apps in just 2 minutes. The title for the post has also indicated this(and is somewhat similar to Dr. Strangelove or: How I Learned to Stop Worrying and Love the Bomb ). I am a learn by doing person and this post is for same kind of persons. So first the code, with very little or no explanation, shows a hello world widow:

Hello World using Python & PyGTK

Hello World using Python & PyGTK

#!/usr/bin/python

import pygtk
pygtk.require('2.0')
import gtk

class Whc:
	def __init__(self):
		self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
		self.window.connect("destroy", self.destroy)
		self.window.set_title("Hello world!")
		self.label = gtk.Label("H3ll0 W0rld!")
		self.window.add(self.label)
		self.label.show()
		self.window.show()

	def destroy(self, widget, data=None):
		gtk.main_quit()

	def main(self):
		gtk.main()

if __name__ == "__main__":
	base = Whc()
	base.main()

…and then how I tweaked it

#!/usr/bin/python

import pygtk
pygtk.require('2.0')
import gtk
import os
import commands

class Whc:
	def __init__(self):
		self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
		self.window.connect("destroy", self.destroy)
		self.window.set_title("Your \"fortune\"")
		self.window.set_default_size(200,100);
		f=commands.getoutput("fortune")
		self.label = gtk.Label(f)
		self.window.add(self.label)
		self.label.show()
		self.window.show()

	def destroy(self, widget, data=None):
		gtk.main_quit()

	def main(self):
		gtk.main()

if __name__ == "__main__":
	base = Whc()
	base.main()

…and then output

Displays a random fortune cookied in GUI

Displays a random fortune cookied in GUI

…and now the analysis. :-)

The code given above uses PyGTK, GTK bindings for Python, GTK, OS and Command module. The OS and Command module is just to fetch the output of fortune command. fortune is a Linux command, more can be found here and may have to be installed, the package is fortune-mod. The Python code is plain English, create a TOPLEVEL window, see for more. In the first code listing another GTK widget Label has been added. The Label contains a snippet of readonly text rendered on Window and in first snippet the text string is legendary, “H3ll0 W0rld!” in L33T. The string in 2nd code snippet is replaced by output of fortune command for which I utilised command and os modules. Easy!!!

This post was lying in drafts for more than 15 months.