There is something for everyone and everything for someone

Sometimes, you need to swap mouse button quickly especially if you use left-handed mouse. This needs to be done for team members or person with whom you are sharing your system.

In Windows, a simple application can be written which when invoked will swap the mouse button.

#include <Windows.h>

/*
Link with user32.dll
*/
int main(){

printf(“Author: Devender Mishra\n”);
printf(“Program to swap mouse button\n”);

if(SwapMouseButton(TRUE)){
SwapMouseButton(FALSE);
}

return 0;
}

Compile this application with cl and link with user32.dll. You can pin this program to taskbar or desktop where you can access it conveniently. For example, if you pin it at third position in task bar, just press Start-3 to swap mouse button.

This is small program. I hope this will help left-handed mouse users on Windows. I am still figuring out the ways for Mac OS X and Linux.
See my attempt:
https://www.quora.com/To-Apple-i-product-fans-Where-should-I-post-this-question-in-Apple-developers-forum-How-to-swap-mouse-button-programatically-using-Cocoa-or-C-Means-write-a-program-to-swap-the-mouse-button
http://stackoverflow.com/questions/14806687/swap-mouse-button-on-linux-and-macos
http://stackoverflow.com/questions/14811549/use-xgetpointermapping-xsetpointermapping-to-swap-mouse-buttons

On Sunday, I usually get up late (sometimes by 0800 hours). From last few Sundays, it is 0700 hours. But on 12th Oct. 2014, it was 0415 hours I woke up. By 0500 hours, I took auto (as Metro starts the operation from 0600 hours). It was a cold morning (you know it is October in Delhi). After crossing lots of flyovers and underpasses and seeing many Metro viaducts near INA and South Extension and even rear part of Tunnel Boring machine (construction of phase-3 metro is in full swing), auto descends through the last flyover at Bhishma Pitamah Marg and reached JLN Stadium at 0545 hours. JLN Stadium was the starting and finishing point of the Half Marathon.

After getting down from auto and paying its amount, I started walking towards entry gate of JLN Stadium. In approximately 10 minutes, I reached at the entry gate. After security checkup, I entered the stadium. By 0630, everyone reached at the starting line. In the line, I found some senior citizens whose enthusiasm will put young people to shame. They all were geared to complete the race.

At 0647 (although it was scheduled at 0645) after many announcements (like who will cover in less than 2 hours will get medal), 21 km half marathon race was flagged off by Sachin Tendulkar. And then 21 km marathon begun.

Let us go to some retrospect about me who has crossed the starting line, but what about crossing the finishing line. I never run more than 5 km in my life. How can I think of completing this 21 km race? In the name of practice, I just jogged towards my office from a nearest Metro station. Only that much preparation. So, do you think I would have completed the race (winning or getting in top 10 is an out of bound question)?

And the answer is ….

YES and no.

I have completed the 21-km race. Why no? Because, I could not cover it in 2 hours. I took 2 hours 35 minutes to finish the race. The moment I reached finishing line, I was feeling satisfied that I did not give up. This might be serve as a source of motivation where I can give up owing to many excuses (like a first marathon), still I persisted and completed it.

But the story does not end here my friends. There are few lessons which this marathon race taught me.

This is first time, I have run 21 km. After this, I felt lot of pain in my thighs and calf muscles. It was severe pain for at least 3 full days. I was feeling as if I lost my legs. I was not able to step down from stairs. That was why I needed to use elevators in Metro station. I was not able to stand up from the chair without any support. I was not able to bend down to take anything from down. No question of running. No question of vigorous exercise.

Due to this pain, I can sympathize the pain of elder people while walking and running. Still, they took part in half marathon and completed the race. Due to this pain, I can understand the ordeal of the person who have accident and got injured from thighs to toes.

Let us see what are some lessons learnt:
Marathon is not only about physical, but also mental: If you cannot convince your mind to run a long race, you cannot complete no matter how strong you are. Many times, I felt to surrender to tiredness. But a strong determination did not allow this and I completed the race. There are 55+, 60+ and 65+ people in the marathon who completed the race. What do you think that made them to complete the race?

It taught me that no matter how strong or weak you are, if your determination is strong, you can do anything.

Now, my all the pain is gone. It teaches me that pain of a journey or war is temporary. But sense of accomplishment stays forever like the sense of completing the race. So, do not fear about the pain you will get during your journey (journey of anything). Even by someone experience and expertize, you can master the pain. But even in this pain, I did not take any leave from the office and continue my normal routine. When this pain was gone, I felt as if my legs got a new life.

Although, I am not a winner, but I am not a loser either. Losers are those who give up early thinking that they will not see 21km mark.

Finally, for everyone, not matter who are you, half marathon is worth to run. After all, life is a marathon not a sprint, Do you stop running?

But I do not stop here listing the lessons. Some, you can see. I look forward for your comments or edits for further lesson points …

How to Solve Linker Error?

Many times, I faced linker error. You may also when you have used some other library or even in your own code. I have solved some questions in Stack Overflow (user:dbasic) related to linker error.

What is this linker error? Let us first understand what is linking and start from the science of linking.

There are following steps involved in converting the code to an executable entity that is library (static or dynamic) or executable file. Following steps are for C/C++.

  • Preprocessing
  • Lexical analysis (Token generation)
  • Parsing (Compiling)
  • Code generation
  • Linking

Steps 1 to 4 are performed by compiler. But you will not final product by this. And this means

Compilation is not enough

No step is optional. After linking, you will get final product.

As you have know in C/C++, while compiling, if a function call or extern symbol is encountered, compiler looks only for declaration and defer linking of this function till linking.

At the time of linking, linker looks for function definition to link. If it does not, it gives you linker error that symbol is undefined or not found. If it finds multiple definitions, then it gives linker error that duplicate symbol found.

So, the root cause of linker error is that function defintion to be linked is either not found or there are multiple definitions.

By this, I can formulate scientific steps to solve linker error. As there are following causes

  1. Required library is not linked
  2. Or required library does not have required function.

Cause 1 can be analysed by seeing build configuration or build log at the time of linker. If it shows library is not linked, it is not linked.

Sometime, library is linked, still there is linker error. The function you intended is in the library but it may be with different calling convention or different types of parameter. There are few tools like strings, dumpbin and nm which can anlyse the symbols of library. By analysing symbols, you can check whether your function is in the library or not.
You  can also use command such as undname (on Windows) to undecorate the symbol names.

I have encountered following cases for cause 2.

Calling convention case
Sometimes, calling convention difference can cause linker error.

For example. let us take a function in a third party library.

int RAND_seed(int seed);

Suppose, this library is using __cdecl convention. And your program is using some other calling convention. It will cause linker. You have to tell your compiler that for this function you are going to use __cdecl convention.

extern “C” case
Another case is possible when you are going to use a C-based library such as OpenSSL in your C++ program. It may possible that library does not wrap itself under extern “C”. So, C++ code will do name mangling and will try to find that symbol from the library.
So, this will cause linker error. Solution is to wrap under extern “C”.

Implicit linking case
In windows, dll are linked implicitly. It requires lib at the time of linking and dll at the time of loading. To indicate that a function is being imported, __declspec(dllimport) is added to function declaration.
If this is missing, it causes linker error.

What about dynamic library?
Suppose, you linked a dynamic library. And there you face similar problem. What will happen?
If your library is found, your program will not run saying library not found.
If a function is not found and is implicitly linked, program will not run saying that the function not found.

Here, you will get error at the time of loading.

I think above scientific methods will accelerate your linker solving ability. Formulation here is as per my experience. If you find something missing or wrong, please inform in comment so that I can correct with credits.

\r\n Story

Many of us (programmers) heard \r\n.
Have you ever tried to open a text file written on Linux/Unix on Windows’ Notepad? You may have noticed no line breaks.

I came to know about \r\n just two days back (at the time of writing this article) when I was reading a book (The Clean Coder by Robert C Martin aka Uncle Bob).

What is the difference between \r and \n? In the decade of 60s and 70s, monitor was not a common output device. It was a teletype.

It had a print head. Print head was composed of a little cylinder with the characters embossed on it. When a character was to be printed, cylinder rotated to the corresponding character and hammer hit the cylinder to the paper. There was an ink ribbon between the cylinder and the paper.

Print head was mounted on a carriage. With every character, carriage moved by one space to the right. At that time, width of line was 72 characters. When carriage was at 72nd character, carriage must be explicitly returned by sending carriage return character \r. Otherwise, print head would print on 72nd column.

Returning carriage to the first column was not enough. Mere carriage return would continue the print the character in the same line. So, it was necessary to move to next line. So, it was done by sending a line feed character \n.

You would have notices two events involved. Returning print head to first column(\r) followed by moving to next line (‘raising the paper to the next line’ mentioned in the book) which is done by linefeed character (\n).

If you take typewriter as the example, job of \n was done by carriage return lever and job of \r was done by moving carriage to left end.

You may think why \n\r would not work. \r operation took slightly more time (around 100 ms). If \n\r would send, then the next character would be printed when the carriage was returning. So, there would be smudge in the middle of line.

In order to be on safe side, end of line was padded with 0xff character which was a rubout character.

In the 70’s, teletypes began to vanish, Unix shortened the end of line to \n. But DOS continued to use \r\n. Windows followed this legacy. This you will find even in the notepad today.

Many of us see large difference between Win32 and Objective-C. Developers who are migrated from Win32 to Cocoa or some other form of Objective-C generally find Win32 a lot easier. Reverse is also true in the most cases.

However, there are few similarities between Win32 and Objective-C.

Communication to object via message passing

Consider the case of Objective-C first. You have an object of NSWindow. It is a window on the screen and you want to change its title.

Following code snippets does this:
/*Create or get a window*/
NSWindow * win = ...;
/*Change the title*/
[win setTitle:@"New title"]; /*Line 4*/

Whereas on Win32
/*Create or get a window*/
HWND win = ...;
/*Change the title*/
TCHAR * title = TEXT("New title");
SendMessage (win, WM_SETTEXT, 0, (LPARAM)title);

Wait a minute. At one place, you are calling method on the object (at Line 4) and at another place, you are calling a function (SendMessage)! Is it a similarity? Let me explain.

Objective-C adds message passing capability to C. You are sending a message -setTitle to NSWindow object so that it can change the title of window in line 5. On Win32 front, you too are sending a message to the window object by calling SendMessage so that it can change the title.

In Win32, you generally send a message to a Win32 control to change its property or get its property. On Objective-C you call the method on object which actually sends the message to the object.

Can you see the similarity of sending the message to the object?

In objective-C, a class is defined as an interface which declares what are the messages to which this class will respond.

For example:
@interface MyClass: NSObject
{
}
-(id)init;
-(void)dealloc;
-(void)doSomething:(int)number;
@end

It shows that MyClass will respond init, dealloc and doSomething: messages (however, more methods can be added into runtime to MyClass).

In case of NSWindow, a method of NSWindow (a message to NSWindow object) is called by main event loop (say -keyDown: on key down) or explicitly (setTitle in this case).

On Win32, for simplicity, consider a window object only. There is a message proc of a window object which is registered before its creation. This message proc processes the various messages of window object which may be dispatched by message pump or can be send manually by SendMessage. This message proc is similar to this list in case of Win32.

Can I change the way a particular message is handled or customise it?

This leads to next point.

Overriding methods by subclassing

In Win32, we can change the message proc of a window object by changing the value of GWL_WNDPROC of the window. It will change the default message proc and call our message proc. It is subclassing of windows control. In our message proc, we can override an existing message handling as we want. Messages we do not process can be sent to default message proc or old message proc in this case. However, this step is optional but required in most of the cases. This way, we can add as per our requirement into default behaviour (or can abuse it). For more on windows subclassing in Win32, see this.

In this case, let us take an example of textbox or edit control.

HWND editbox = ...;
WNDPROC oldproc;
oldproc = (WNDPROC)SetWindowLongPtr (editbox, GWLP_WNDPROC, MyEditProc);

Inside MyEditProc

LRESULT MyEditProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
//Subclass the control by overriding message handling.
switch(uMsg) {
//If i can handle it, handle it.
case WM_CHAR:
Capitalize (hWnd, wParam,lParam);
return 0;
}
//If do not handle itself, let the old message proc to handle.
return CallWindowProc(oldproc, hWnd, uMsg, wParam, lParam);
}

On Objective-C, a class can inherit another class (like we do in object oriented language C++ or Java) and overrides the methods as per the needs. While overriding a method, subclass can let superclass to handle it if it does not.

For example: Say MyWindow inherits NSWindow and overrides -keyDown to handle the key in its own manner.

@interface MyWindow:NSWindow
{
}
- (void)keyDown: (NSEvent *)event;
@end

In the implementation part

@implementation MyWindow
- (void)keyDown: (NSEvent *)event
{
//Handle Cmd-Q and for other, send to superclass.
if(KeyIsCmdQ(event))
[NSApplication terminate:nil];
else
//let superclass to handle it.
[super keyDown:event];
}
@end

You can see the similarity here too but with a difference. In Win32, you can abuse the subclassing by not letting old proc or default proc to handle the message which you are not handling.

Anyway, are you able to see the similarity between Objective-C and Win32?

Did Win32 copy Objective-C or Objective-C copy Win32 or were they developed independently?

Do you feel anything wrong or requires any correction? Please feel free to comment on it.

Also, if you have to add more, add it by comment.

Before getting into it, let me give a metaphor to programming – it is like building a house. You use many ready-made components (e.g. library code) like you use to build a house. You may use library of other vendors also. Unlike house, software can be infinitely copied.

This is just one metaphor. In some cases, it may not fit appropriately.
Lets get back to the title.
In programming, we depend on other codes. Weather we use the code of our own team-mate or of other vendors. We can check the code of our team-mate to get ensured that it does the job it meant.
But what about the code of other vendors.
In case of open source code, we may cross-check the functionality. Sometimes, code is not open to us due to many issues. We rely on what the documentation says about the code.

How may times you have asked Microsoft, Google or Facebook to provide the source code of their APIs so that you can verify that it is doing the job which they have mentioned?

How many times, you have tested an API of other vendors just to get assured that it is working fine?

If we see the given metaphor, we may trust the vendor by seeing some ISO or ISI (or some other standard). How many times, you have gone to ISI to verify the fact actually?

Well, most important is the heading.
I hope that is also answered. You just trust them what they says.
On this trust, your code works and your customers or users trust on what you say.

This teaches us that this whole world runs on TRUST.

You may say that this is a universal truth. What is new about it? Why is it revealed by Programming?
Programming may reveal many things. We may explore it later.

After solving a problem due lexical analysis, I realised that lexical analyser teaches an important lesson of life.
This may seem to be technical, but it’s not.
Let me brief about lexical analyser. In program (e.g. C program), generally programmer writes comments to explain the logic or for some other reason.
e.g.
int x;
x = x+10; //Increasing x by 10

Here, the sentence “Increasing x by 10” is not the part of the actual program which will
run once this program is compiled successfully. Parser cannot parse this. So, it must not be fetched to the parser. Lexical analyser does this job nicely.
It fetches to the parser only what is meaningful to it.

So, what? How is this related to lesson of life?

Well, what I have to say, I said.
Just correlate something with comments and ignore them.
Imagine those hurdles in the way of your goal. Consider them as comment.
Remove and ignore them (as parser does) and do the meaningful to get closer to your goal.
Because your parser must focus on the goal (solution of the problem) and do what it is meant for, not the problems.

Last, but not the least, it can be befitted in the relationship. However, it is open to open interpretation of the individual.

Have you ever solved 2×2, 3×3 Rubik’s Cube, 4×4 Revenge Cube, 5×5 Professor’s Cube, 6×6 V6, V7 etc.?

No problem, if the answer is NO.
Cube teaches an important lesson of life. When you are very close to the final solution, you make next move cautiously. Next move gets more complicated. Imagine in case of Revenge, when you get last double edge flipped (shown in the picture below), move to uncurl this is quite complicated.

Pic. 1 Last double edge of Revenge is swapped.

And you have to work this move with concentration!!! If you do not, then you may loose the track and you may have to start it again.

So, to conclude, cube teaches following lessons:

1. More closer you are towards your goal, next steps become more complicated. (except in last cases when only one move is left)

2. You should have concentration, consciousness and caution until the last step. Otherwise, you may have to start it again.

3. Sometimes, you have to move backward for the sake of moving forward. Given example also illustrate this. You are just one step away from the solution. But move many moves back to get to final solution.

And LAST but not the least:

It is easy to SCRAMBLE but difficult to UNSCRAMBLE. This goes to the life as well.

Befuddled with ‘&’

This happened to me while work. This article is somewhat technical. So, I apologize to non-programmer people.

There was a C++ function like

void f (int a, int &b) //line 1
{
         f (a, &b); // line 2
}

This initially looked like an infinite recursion. I wondered why program was working.
But, when I saw carefully line 2 (mentioned in the comment), second function f() is actually a different function.

Signature of f() at line 1 is
void f (int, int &); //Note that & in declaration is a reference

and signature of f() at line 2 is
void f (int, int *); // While calling, & is to pass the address
because address of b is passed as a parameter.

This kept me addled for few minutes. This cannot be done in C as C does not allow two functions with same name (no function overloading).

Does not it sound similar to luck by chance?
In this case, there was no situation in which I was made leader owing to no choice left. However, there was a scenario which revealed that I was leader and irony was that even I had no knowledge of it.

It happened last Saturday. People were moving toward bus stand either to get an auto or bus (more suitably a Volvo AC bus). I was also moving to the bus stand to get Volvo AC bus as I had daily pass of AC bus. Owing to my speed I was much ahead of the other people. They were behind me.

Due to my speed I reached bus stand much earlier and was waiting for a bus. After sometime people who were behind me arrived there. They too had to board a bus.

And to my surprise, later I came to know that they all were following me as they were new to the place and did not know the way and did not know the location of bus stand. And that was why they were behind me (actually not behind me but following me).
Since, I travel by bus and most of the time managed to get the shortest path to the nearest bus stand. I knew the way. They believe I knew it. Therefore they were following me.

This revealed me a leader. And I was leader by chance. I sighed as I led them to the right place. I thanked them for their confidence in me.

  • Design a site like this with WordPress.com
    Get started