Friday, April 29, 2011

Screen - detach a process from console

Ever wondered how to start a download from server at night from your laptop and shut it down with out disrupting the download?

Of course there are many ways, use RDP etc but screen is a better choice because its powerful.It gives the power of resuming from where we left.

http://www.howtoforge.com/linux_screen

Friday, April 02, 2010

Perl HowTo: Parsing command line options

Sample program to work with CLI options. Play with this program options and pay
attention to the reported usage errors to better understand how GetOptions() work.

# CODE STARTS HERE
#!perl -w

=head1
 Using GetOptions() to process CLI options
 Ref: http://perldoc.perl.org/Getopt/Long.html
=cut

# Required module
use Getopt::Long;
use strict;

my $grade = 'A';
my $pcile = 0.0;
my $name = '';
my $result = 0;    # Fail by default
my $promote = 0;
my @marks = ();
my %history = ();

sub show_usage()
{
   print "\nUsage: --name name --grade [A|B|C|D] --marks m1 m2 m3\n" .
                "       [--pass] [--promote | --nopromote]\n\n";
   exit( 0 );
}

if ( !scalar( @ARGV ) )
{
   show_usage();
}

if ( !GetOptions( 'name=s'       => \$name,       # =  - mandatory, string
                  'grade:s'      => \$grade,      # :  - optional, string
                  'percentile:f' => \$pcile,      # read float value
                  'marks=i{3}'   => \@marks,      # sequence of 3 numerals
                  'pass'         => \$result,     # optional, flag
                  'promote!'     => \$promote,    # -promote and -nopromote
                  'history:s{2}' => \%history ) ) # sequence of 2 strings
{
   show_usage();
}


print "\n    SUMMARY   \n\n";
print "Name      : $name\n";
print "Marks     : ";
foreach( @marks )
{
   print $_ . " ";
}

print "\n";
print "Grade     : $grade\n";
print "Percentile: $pcile\n";
print "Result    : $result\n";
print "Promote?  : $promote\n";
print "\n";
print "History : ";
foreach( keys( %history ) )
{
   print $_ . " = " . $history{$_} . "; ";
}
print "\n";

0;

# CODE ENDS HERE

Wednesday, February 10, 2010

vim command to delete lines

My fingertips know the command to delete all the lines starting from current line till EOF (that's d + shift g) but I rarely remember the command to delete all the lines up to head of the file.

Luckily, vim offers a simple approach to delete desired lines, all we need to be aware is the following
  • . (dot) - represents current line
  • $ - represents EOF
  • syntax: start_line_num,end_line_num vim_cmd
Some example usages (Note: these commands are run in the editor, hence the beginning colon)
  • Delete all the lines starting from current line : .,$ del
  • Delete lines starting from 1 to so far : 1,. del
  • Delete all lines between 10 and 25 (inclusive) : 10,25 del
  • Delete all lines between 10 and 25 (inclusive) : 10,+14 del
  • Delete next 15 lines including the current : .,+14 del
  • Delete last 15 lines including the current : .,-14 del

Tuesday, November 03, 2009

Open Source Projects and Volunteers

Why only a handful of projects attract attention of developers/volunteers?

Moshe Bar and Karl Fogel in their book Source Development with CVS points that In a system that relies largely on volunteer energy, convenience is not a mere luxury—it is often the factor that determines whether people will contribute to your project or turn their attention to something with fewer obstacles to participation. Projects are competing for volunteer attention on their merits, and those merits include not only the quality of the software itself, but also potential developers’ ease of access to the source and the readiness of the maintainers to accept good contributions.

Point taken.

Saturday, October 10, 2009

Coding standards do no harm

Coding standards aid in picking up new code faster, it can help in debugging too. For example it's almost safe to skip a const qualified method while debugging a problem (just make sure that there are no mutable members).

Lately I had crazy time debugging a problem that eventually boiled down to non adherence of coding standards. Here it goes ...

A new API that looks as simple as below was added to a self sufficient component which compiles clean after the change was made.
    int process_data( const char * str, char delim = '  ' );
Suddenly another component that depends on the modified header fails to compile with error C2143: missing ')' before 'string'. That's a bit of shock!. By the way the other component doesn't use the new API at all.

It turned out that other component has defined a macro which is neither long nor uses UPPER_CASE. Of course it's their choice!
    #define delim TEXT(" ")        // and
#define TEXT( str ) L##str // just token pasting ...
You are punished for using a simple looking identifier (delim) and it takes efforts to understand that you are being punished!

Saturday, August 01, 2009

Defining INT_MIN

It's always better to take a hard look at warnings. Warnings are potential Errors. Recently I came across an interesting warning with VC++.

warning C4146: unary minus operator applied to unsigned type, result still unsigned

A bit of googling revealed that above warning can be dangerous. To understand the underlying problem, here is my own version of INT_MIN.

#define INT32_MIN -2147483648

As 2147483648 is greater than max 32-bit signed int value (MAX_INT), it is treated as unsigned int. With this, type promotion kicks in and would fail the following condition.

if ( 1 > INT32_MIN ) // comparing two unsigned values
std::cout << "I am sure, 1 gt INT32_MIN";
else
std::cout << "Surprse! it says, 1 lt INT32_MIN";

To correctly define our own version of INT_MIN, see how it is defined in limits.h. The trick is to not to let the value to cross (signed) 32 bit int limits. The correct version should look like below.

#define INT32_MIN (-2147483647 - 1) // don't forget to put the braces around

Refrences:

1. More detailed explanation is available here
2.
warning C4146

Tuesday, June 23, 2009

Quote from IBM GTO 2008

Good quote from IBM's Global Technology Outlook 2008.

A computer, like anything else, works best when it is built and used for a specific purpose. Though far more complex than a hammer or saw, a computer is a tool just the same. And all tools must be designed to a task.

Sunday, February 08, 2009

exstr dupms core on lenghty strings

Make messages normally uses exstr to extract strings that needs to be localized. It looks like exstr suffers from buffer overflow vulnerability. It dumps core on Solaris 9 with the following program snippet. exstr doesn't seem to process a lengthy string.


void PrintUsage()
{
std::cout << "#mycmd -option1 -subopt1 -subopt2 -suboption3 \n\
-option2 -subopt1 -sbuopt2 -subopt3 \n\
......................... \n\
......................... \n\
-option15 -subopt1 -subopt2"
<< std::endl;
}


In order to generate message strings, I had to break the above snippet into ugly looking pieces - quite bad, I had to split the options mid way.


void PrintUsage()
{
std::cout << "#mycmd -option1 -subopt1 -subopt2 -suboption3 \n\
-option2 -subopt1 -sbuopt2 -subopt3 \n\
......................... \n\
.........................\n\
-option9 -subopt1 -subopt2";

std::cout << " -option10 -subopt1 -subopt2 -suboption3 \n\
-option11 -subopt1 -sbuopt2 -subopt3 \n\
......................... \n\
.........................\n\
-option15 -subopt1 -subopt2";
<< std::endl;
}

Tuesday, January 06, 2009

VIXIMO's VixML platform for iphone

Looks cool, featuring

- Physics engine
- 2D and 3D visual effects
- Easy to use by non programmers


Tuesday, December 09, 2008

Zoetrope, new concept aimed at providing access to temporal web content. It lest people see how things (any) have evolved over a period of time. One useful thing that can be done using Zoetrope is to spot the best time to buy books on Amazon :-)

Zoetrope in action

Tuesday, November 18, 2008

Really cool stuff

Usability is still an issue with PCs. There are smart people (who works around an issue instead of simply nodding in disgust) out in the world ... proof? check this video



Tuesday, September 02, 2008

Google Chrome

Wish, it comes out soon :-)

http://blogoscoped.com/archive/2008-09-01-n47.html

http://blogoscoped.com/google-chrome/

Un named structures and VS8

With two un-named structures , the linker on Windows has thrown the following error

unnamed_struct.obj : fatal error LNK1179: invalid or corrupt file:
duplicate COMDAT '??1@@QAE@XZ'
NMAKE : fatal error U1077: '"C:\Program Files\Microsoft Visual
Studio 8\VC\BIN\link.EXE"' : return code '0x49b'
Stop.

The above is observed even with the varying number of struct members.

Known Issue: If two unnamed structs both declare a method with the same signature
and both are referenced, the compiler generates the same signature for both methods.
The linker then flags the .obj file as invalid due to duplicate COMDAT records
(More about this issue here)

The solution to this problem is, not to use more than one un-named structures

Sunday, July 27, 2008

Good Stack Overflow Podcasts

These are worth an ear...

Talks about who can be a good Manager, time management techniques, how to benefit out of good code review process, and discussion around attending/preparing for Interviews..

Podcast 15: Jeff Atwood and Joel Spolsky

Saturday, July 19, 2008

Wednesday, June 18, 2008

Beautiful Software

Here is a good article that compares construction work to building software systems. Though it's quite an old article written by Charles Connell, is very much relevant to our times

The key points are
  • Don't let customers compromise on the quality of the software
  • Write small, simple, readable code (even for the complex issues)
  • Strive to provide only the necessary functionality (bang for the buck for both users and developers)
  • Ensure that software works in a co-operative manner (with others resources of the system)
  • Ensure that external functionality of a software can easily be mapped to the code (reduces maintenance or enhancement costs)

Friday, June 13, 2008

Good Tech Videos

NWCPP: Machine Architecture: Things Your Programming Language Neve - Herb Sutter

Wednesday, May 21, 2008

Liskov Substitution Principle (LSP) and Design By Contract (DBC)

Adhering to OCP requires employing abstraction and inheritance. The key concern LSP promises to address is the quality of the inheritance (What? Quality of inheritance? Yes). If inheritance is not applied correctly i.e if any inheritance violates LSP, ends up violating OCP too.

In OO programming IS-A should be thought in terms of object's behavior. Following example should help us understanding it better.

Is rectangle A square? Mathematically yes when width is same as its height. So lets device and interface to work with squares and rectangles.

class RectangualShape {
public:
virtual void SetWidth( int w ) = 0;
virtual void SerHeight( int h ) = 0;
virtual int Area() = 0;
};

class Rectangle: public RectangularShape {
public:
virtual void SetWidth( int w ) { width = w; }
virtual void SetHeight( int h ) { height = h; }
virtual int Area() { return width * height; }

private:
int width;
int height;
};

class Square: public RectangularShape {
public:
virtual void SetWidth( int w ) { side = w; }
virtual void SetHeight( int h ) { side = h; }
virtual int Area() { return side* side; }

private:
int side;
};


int main()
{
int w= 1;
int h = 2;
RectangualShape *rect = new Rectangle();

rect->SetWidth( w );
rect->SetHeight( h );
assert( (w * h) == rect->Area() );

RectangualShape *sqr = new Square();

sqr->SetWidth( w );
sqr->SetHeight( h );
assert( (w * h) == sqr->Area() ); // BINGO, assertion fails

return 0;
}

Why did the assertion fail for square shape? Because a square is behaviorally different from a rectangle (except in one instance). So misusing IS-A relationship results in inheritance that violates both LSP and OCP.

The above example emphasizes the fact that derived classes should behave as advertised in the base class.

The Principle

Inheritance should ensure that any property proved about super type objects also holds for sub type objects -B. Liskov (87)

Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it - R. Martin (96)

A few key things to note about using interface are

  • Its illegal for a derived class to override a base class method with NOP (no operation)
  • Establish and document the interface contracts (DBC)
  • Any inheritance that violates LSP also violates OCP

When inheritance is involved, users of an interface (abstract base class) need not care for how a derived class behaves. Its expected that derived classes also keeps the promise made by the abstract base class. Then how does the users know what an interface is promising? Well by looking at the class, or otherwise through documentation.

Design By Contract (DBC): Its nothing but advertized behavior of an object

  • Advertized Requirements (Preconditons), i.e callers should not assume anything and should always pass valid arguments
  • Advertized Promises (Postconditons), i.e expected behavior or results

To keep the interface promise: When redefining a method in a derived class, you may only replace its precondition by a weaker one and its postcondition by a stronger one - B. Mayer (88)

Key points of DBC

  • Derived class services should require no more and promise no less
  • Document pre and post conditions
  • Because of preconditions, DBC says methods need not do any validations on input arguments
  • Invariants can be used effectively to see whether any derived class violates the base class behavior or not


class RectangualShape {
public:
/**
* Precond: Positive integer < 100
* Postcond: void
*/

// w should have been unsigned, precond should help us
virtual void SetWidth( int w ) = 0;

/**
* Precond: Positive integer < 100
* Postcond: void
*/
virtual void SerHeight( int h ) = 0;

/**
* Precond: void
* Postcond: w * h
*/
virtual int Area() = 0;
};

References:

Liskov Substitution Principle - PDF
Design Principles and Design Patterns - PDF
Principles of Object Oriented Design - PPT
Advanced Principles of OO Class Design - PPT

Thursday, May 15, 2008

C++ tidbit - virtual functions and default arguments

Virtual functions are bound dynamically where as default arguments are bound statically

class Base {
public:
virtual void func( int x = 10 ) {
_x = x;
std::cout << _x;
};

private:
int _x;
};

class Derived: public Base {
public:
virtual void func( int x = 20 ) {
_x = x;
std::cout << _x;
};

private:
int _x;
};

int main()
{
Base *b = new Base();
std::cout << "Default Value in Base: ";
b->func();
std::cout << std::endl;

Base *d = new Derived();
std::cout << "Default Value in Derived: ";
d->func();
std::cout << std::endl;

return 0;
}

Output:

Default Value in Base: 10
Default Value in Derived: 10

Default arguments of virtual methods in the base gets statically bound (in our case Base::func() ), hence never override the default values in derived virtual methods, doing so might confuse us with derived object's default behavior.