Bug Vanquisher

29 June 2007

One day I’ll ask someone

Filed under: Fun — Tanveer Badar @ 11:54 PM

The day will come when I will be sitting across the desk, asking someone interview questions.

In preparation for those far, far-away, distant future days, here is a question I read yesterday.

“An array of ‘n’ items where each cell contains a number from the set [1,n-1] with every number in the set occurring at least once. Since, the set has n-1 members and the array is n item long, one number is duplicated. Give a linear time, constant space algorithm to search for this duplicate number.”

28 June 2007

Finally someone tells me!

Filed under: Windows Vista — Tanveer Badar @ 2:11 PM

I never knew why my Windows Vista Enterprise edition ever showed anything in restore previous version tab. Now, I know why.

25 June 2007

The game ends!

Filed under: Things in life — Tanveer Badar @ 12:27 PM

It ends on 21st July, 2007 of what started on 30th June, 1997.

I am talking about Harry Potter. The magnificent seven part series of spell binding (no pun!) literature. It has been foretold that Harry will die at the end of last chapter of his life ‘to prevent others from building on the popularity’. Though, it was already very hard to deal with Dumbledore dying at the end of ‘The half blood prince’. I am eagerly waiting to get my hands on this last book.

Happy Turing Day

Filed under: Computer Theory — Tanveer Badar @ 11:52 AM

It’s a bit late (actual date is 23rd June), but better late than never.

16 June 2007


Filed under: Personal — Tanveer Badar @ 9:37 AM

I wrote previously that I refused last outstanding job offer here. Turns out, my decision was well timed and exactly what I would have done two weeks later if I had chosen to join them.

I say this because another friend who waited for them for four months and finally appointed left them two weeks ago because he did not like it that much. Work pace was slow and we did not get the upper hand on the required knowledge in university and actually working on that field necessitated that you already knew most of the things. Now, he is working for the company who offered me a job back in January. Meanwhile, those who made their choices six months earlier have six months of experience and no one will ever raise and eye-brow on five months of unemployment and two jobs in such a short period of time.

I’ll be paying dear old university a visit in a couple of days and I’ll make it known to those well connected what a horrible course we had for verilog. The main reason my friend did not have much experience in practical things is due to him. Now that he is teaching a compulsory course, it is rumored that he leave classroom when students even so much as ‘try to become out of control’. Not a very good excuse for final year!

14 June 2007

The road not taken

Filed under: Decontamination — Tanveer Badar @ 6:33 PM

Last night, I was watching SG-1, “The road not taken”. There was one dialog which offended me. Rodney Mckay was referred to by Major Lorne as dot-com jerk in the alternate universe Samantha Carter found herself.

Now, the thing is it is due to these dot-com jerks and generations of geniuses before them who enabled the technology to advance to the point where such misinterpretation of science (especially physical science) is possible and series like SG-1 can be made. I am talking about CG environments and animations. You should really compare the quality of some 60’s series with that of SG-1 and say your thanks to all those “dot-com jerks” who made it possible in the first place.

10 June 2007

Don’t use this cure. It worsens the symptoms!

Filed under: Things in life — Tanveer Badar @ 12:14 PM

Tired of load shedding? Constantly interrupted with power failure in the middle of that important chat? Finally, you convinced dad to install a UPS to fight all those chance of assignment not being completed on time? Wishing you had a laptop or owned KESC? You are that victim of constant power failure who couldn’t prepare for that DIFFICULT paper next morning? It is time to ride the band wagon to load shedding free summers in Karachi. You have three options, curse KESC all the time and do nothing else, not likely. Get a generator to fulfill your deepest desires. Buy a handy UPS for all you home, you are that generous person, you are. And in the meantime, get a small UPS for your computer too so that it does not suffer from jerks (electric and human included. It would be better if you could keep your hands off it for a moment.).

UPS come in all sizes in rating. They are for things as big as an entire office. They can provide power to an entire home if need be. Or they can be for things like computer we mortals have come to love. My office has a UPS that supports all machines in it and has a battery life of 15 minutes. The one at my home has a battery life of 6 hours and can power almost everything at once. Thankfully, they are designed such that battery life and load bearing capabilities are independent of each other. You can have as much battery life as you want if you add enough batteries. Load bearing can be as high as you want (well up to a certain point) by using power electronics and devices.

These preliminaries aside, have you ever given thought to what happens when power goes out, UPS begins its life as a power source and when power comes around, recharges itself for next cycle? For the illustration take my home as an example. Here is a typical day, 24 hour power consumption cycle for my home.


Initial surge starting at 6 AM is due to everyone waking up. Things cool down a little from 9 AM to 12 PM. Then, those who don’t have a full day job return and the consumption surge begins. We have highest demand from 4 PM to 10 PM. Finally, one by one, we starting getting to bad, our share of electricity now served to someone else and a new cycle begins. 

Add UPS to the mix and see what happens.


The baseline power consumption for constant recharging and losses accounts for a couple of watt every day. This adds a certain amount to electricity bill each month. This is one part of the cost we pay for having power all day round. 

Overall, power consumption is increased by this base line UPS power consumption above what would be otherwise.


Each day, we are consuming 24x/1000 units of electricity with no obvious gain. It is just like insurance, if the loss you have anticipated does not happen, you do not get all your money back, there is some amount taken. The operating charges and risk factor in case that catastrophe had happened.

From the last picture, can you guess what would happen when power fails?

power failure

UPS lost external power somewhere around 12:50 PM – 1:00 PM. This power out period lasts for about two hours. During this time, UPS’ internal power consumption has reduced to a bare minimum, sort of only for housekeeping jobs. So has total power consumption. It is very near what would be baseline power consumption in the absence of UPS. When power finally comes back around 3:00 PM, a sudden increase in power consumption happens. Difference of area under total power consumption from 1:00 PM to 3:00 PM in the last two pictures must be less than increased power consumption. What is the reason? UPS begins charging back itself and it is common knowledge that the energy it handed out during the last two hours must be more than compensated in the next few hours. UPS power consumption jumps to about double its baseline level. Similarly total power consumption stays at a high level for some hours. When UPS charging rate finally starts to come down, the solid curve assumes its normal profile. 

Now, do you see what the problem is? As more and more people install UPS in their homes, offices power consumption may be low for a part of the city while it is experiencing load shedding, but after that period is over, the amount that was conserved will be more than compensated by recharging devices. At the end, load shedding has not helped anyone conserve power but caused disruption for some and increased load on the system in the ensuing hours.

9 June 2007

Runtime Code Generation in C++ 6

Filed under: C++ — Tanveer Badar @ 3:38 PM

As I said last time, no discussion of a language is complete without statements and expressions. We talked about expressions in CppCodeProvider last time. Today’s topic is statements. Everything in C++ is a statement. You declared a function or a variable, it is a declaration statement; define a class, it is another declaration statement; define a function, another declaration statement; write a loop, iteration statement; use if-else or switch, conditional statement; perform any type of jumping by goto, return, break or continue all are jump-statements; declare variable on a for-loop, a for-loop init statement; label something or write case or default inside a switch, labeled statement; surround a piece of code with braces, compound statement; use a semi-colon after an expression, expression-statement!

In short everything is a statement in C++. There is simply no escaping this fact of life. My life is complicated by the compound statement thing. Since anything can be a statement and come after anything in either braces or otherwise, every class to represent a type of statement must derive from same base class, Statement.

First there is an ExpressionStatement, which takes an Expression as an argument and turns it into a Statement. There is a UsingStatement, which declares an identifier to be visible in another scope. We are used to jumping all over the place, all our lives. JumpStatement captures the essence of jumping. It takes either a string to generate a goto, a member of JumpType except goto, or an optional expression to generate a return. It is illegal to specify Goto as an argument to second constructor because a goto requires a label to jump to. The expression passed to the third constructor must not be null because for a simple return with no value you should pass JumpType::Return to the second constructor. To accompany the goto of JumpStatement, we have a LabelStatement which takes a string and another statement and applies that string as a label to that statement.

We have discussed all the single statement constructs for statements. It is time to move on to statement blocks. It is legal to have a single statement block, but it will be surrounded by { } and introduces a new lexical scope. For compound statement, you use StatementBlock. StatementBlock can be instantiated with a collection of statements which will be part of it or default initialized. All statements which are part of one StatementBlock can be accessed through Statements( ). This class is the base class for almost every other kind of statements.

A catch block is essentially a compound statement with one optional exception variable declared and initialized before the scope is entered by execution. CatchClause represents this structure in code graph. It optionallly takes a VariableDeclaration or default initialized if this catch block is a catch-all type. The exception variable is accessible through CatchType and since it inherits from StatementBlock all statements are also accessible.

We use CatchClause to build higher level construct, namely try-catch block. A try-catch block has a body of statements surrounded by try and a list of catch clauses which catch exceptions thrown by try block. TryCatchCaluse is always default initialized and you add statements to try block with Statements( ) and catch blocks through CatchClauses( ). Both of these functions return an appropriate collection where you can call push_back to add new items.

A case statement also inherits from StatementBlock. It takes an optional bool parameter to indicate if case block should begin in a new lexical scope because it contains variable declarations. If you provide a PrimitiveExpression to Instantiate it becomes the label for case, otherwise, a default is generated. Although it is illegal to have more than one default or same case in a switch statement, these checks are more high level than any code dom. Therefore, it is the responsibility of client to ensure it does not happen, otherwise, deal with it when the compiler whines on the source code :). Also, there is no check to see if the PrimitiveExpression is really a compile time integral constant or not, you will have to face your compiler if you do contrariwise.

Similar to CatchClause, we use Case to build a higher level construct, SwitchStatement. A switch is essentially an expression which is evaluated at runtime and a bunch of case blocks crammed together in one lexical scope. You construct a SwitchStatement by providing an Expression and adding case blocks through Cases( ). An alternative to switch is the if-else clause. Sometimes there is no option other than if. e.g., if want to test for a range, want to check for a floating-point value, value is not a compile time constant etc. If-else clause is used as ConditionClause. You provide it with only the expression which is checked in if( ). Statements which will be part of if block are accessed through Statements( ), those which will be part of else block are accessed as a StatementBlock with Else( ). Condition can be retrieved with Condition( ). Special treatment for else block is necessary only because it is not possible to inherit from StatementBlcok twice directly. Therefore, else block is exposed as a StatemntBlock object and statements in if block are inherited through Statements( ).

All loops are clumped in the base class of IterationClause which inherits from StatementBlock. Since all statements of loop body are already accessible through Statements( ), IterationClause only introduces a Condition( ) to access loop condition. The class is abstract as there is no way to realize a loop without telling whether it is a for, while or do-while loop. A ForLoop specializes IterationClause with two additional expressions for ‘for-initialization statement’ and increment expression. If none of these three expression is given, an infinite for loop is generated. WhileLoop and DoWhileLoop specialize IterationClause to generate different forms of loop with a body and condition only.

Runtime Code Generation in C++ 5

Filed under: C++ — Tanveer Badar @ 3:34 PM

Sorry for such a long discontinuity in posts related to CppCodeProvider. I have been really busy and barely had time to do anything apart from my project. Till last time, we have discussed type support in CppCodeProvider. Also, I am sorry about the bout of C++ I am having recently. I really annoys me to stick to one topic too but it had to be finished sooner or later.

You cannot use a type without statements and expressions. Apart from types, a language is entirely built from expressions and statements. C++ has a rich support for expressions, which are the topic of this post.

Since it is possible to mix any type of expression with any other from compiler’s point of view, all expressions derive from one base class Expression. Let’s begin from the simplest of expressions, a literal expression. A literal is represented by PrimitiveExpression which is built from a string. Next, consider integral compile time constants. They are encapsulated by IntegralExpression. This expression is currently only used in case labels, although it is possible to use it in non-type template parameters too.

When adding namespaces and classes to the mix, we need some way to resolve an identifier to its scope, for this we need ScopeResolutionExpression. A ScopeResolutionExpression expression can take one argument, for global identifiers or two arguments; one string and second another ScopeResolutionExpression to refer to one particular scope. Then, consider how to reference a variable declaration in code, and for similar purposes argument reference. For these, ArgumentReference and VariableReference are provided which respectively allow you to refer to an argument or variable defined previously. We can also refer to a function for function pointers, so there is a MethodReference too. A MethodReference can refer to any function. Therefore, there are smarts built into writetext to handle the special cases of free standing and member functions.

In order to allocate objects on heap, you can use NewExpression and its corresponding DeleteExpression. A NewExpression can be an array new or a scalar new. It can allocate a multi-dimensional array variable. In case of scalar new, it calls the constructor with the given number of arguments. A DeleteExpression can be a scalar delete or an array delete, with the difference given by member function Array.

We also need casts to change from one type to another. Cast expression takes another expression which will be cast to another type, the target type and type of cast to apply to given expression. Possible types of casts are c-style casts, reinterpret_cast, dynamic_cast, static_cast and const_cast.

No discussion of expressions is complete without expressions with operators. A BinaryExpression takes two other expressions and an operator Type to apply infix to the given expressions. All types of binary operators can be given. Similarly, UnaryExpression allows us to apply a unary operator to some variable. There are two types of unary expressions. PrefixExpresison applies any of the prefix operators to the given expression and PostfixExpression applies any of the postfix operators to the given expression. It is possible to provide names of some operators instead of their types as defined in the standard.

We can change precedence of operators by applying parenthesis with the help of ParenthesizedExpression to an expression and producing a new expression. This class takes an Expression as argument and surrounds it with parenthesis. Another handy expression in the conditional operator. This operator is provided in the class ConditionalExpression. This class takes three expressions and uses the first one to decide between the last two expressions to presents as result.

To cover exceptions, a ThrowExpression is also provided. Since we can throw an object or rethrow a previous exception, it is possible to instantiate ThrowExpression without any argument to realize rethrowing a previous exception.

A function call qualifies as an expression. A MethodInvoke takes a reference to either a Function or a MemberFunction. Second argument is an Expression which will be used as the object reference for the MemberFunction call or in place of function name for Function. For the MemberFunction, it is possible to specify whether the object is a reference or a pointer. Argument list is accessible through Arguments( ).

Next time, it will be statements.

8 June 2007

A comparison of CPlusPlusCodeProvider to System.CodeDom

Filed under: C++ — Tanveer Badar @ 6:26 PM

I thought these were deficiencies in CppCodeProvider. Namely,

· It is very difficult to partially specialize a user-defined type.

· Union does not write anything at this point.

· It is not possible to initialize enumerators with values.

· A user defined type does not write anything at this point.

· Pointers to function, member function and member variables are very hard to work with.

· Friends cannot be declared at this point.

· Forward declarations are not possible.

But it turns out, some of these are feature which are really difficult to represent in any code graph for C++. CodeDom has much serious limitations, addressed here. A short listing is.

  • No unary operators like -,+,++,– etc.
  • No readonly for fields in a class/struct.
  • No break/continue in a loop/switch statement.
  • No type cast support in the form of as/is.
  • No while loop.
  • No switch statement.
  • Attributes on set/get of a property.
  • No default indexer in VB.Net.
  • Main always has void return type in C#.
  • No == operator.
  • No internal virtual functions.
  • No way to apply [field:] attributes to an event.
Older Posts »

Create a free website or blog at WordPress.com.