Skip to main content

Posts

Dealing with Bad Code !!!

Read this fine article by Joel Spolsky : Things You Should Never Do It is a great article, one that invokes mixed feelings. The article talks against rewriting (large scale) software.....from scratch. Joel was kind enough to consider all those who write software as true programmers ; people who give enough thought and not just code up something that works. However, it is far different in the real world. That said, I am neither completely in disagreement with Joel nor am I advocating to rewrite large scale software once the code is identified as a mess. Most people who are programmers are just people who write code for a living. Nothing wrong but forget the passion part of it. So the quality of the code that is generated is questionable. True programmers are different. They first build those intangible constructs in mind of how the code should be, and then they write code that reflects to the reader the intent of the task being achieved. Hence such code is readable, modu...

Linked List Quiz - Part II !!!

In the last part , we saw the academic (not general purpose) version of a Linked List used to solve the puzzles, and solved the following puzzles on linked list. Reverse the list recursively Reverse the list iteratively Find if a list is cyclic In this part, I will be solving the remaining two puzzles that I listed in the last part. Finding the cyclic node in a cyclic linked list According to my solution, the node which is actually supposed to be the end of the linked list is the cyclic node. Let us call Cn. Taking node Cn as the cyclic one has an advantage wherein you can break the cycle; assign Cn->next = nullptr; But some people take the node after Cn as the cyclic node. The node after Cn is the node somewhere back in the list. This way it is not possible to break the cycle as we would traversed past Cn. LinkedList::Node* LinkedList::FindCyclicNode() const { int iterCount = 0; auto jmpBy1Ptr = root; auto jmpBy2Ptr = root; while (jmpBy1Ptr !...

Offering __FILE__ and __LINE__ for C# !!!

THIS POST USES SYNTAXHIGHLIGHTER AND HAS ISSUES RENDERING CODE ONLY IN CHROME Not the same way but we could say better. Visual Studio 2012 , another power packed release of Visual Studio, among a lot of other powerful fancy language features, offers the ability to deduce the method caller details at compile time. C++ offered the compiler defined macros __FILE__ and __LINE__ (and __DATE__ and __TIME__ ), which are primarily intended for diagnostic purposes in a program, whereby the caller information is captured and logged. For instance, using __LINE__ would be replaced with the exact line number in the file where this macro has been used. That sometimes beats the purpose and doesn't gives us what we actually expect. Let's see. For instance, suppose you wish to write a verbose Log method with an idea to print rich diagnostic details, it would look something like this. void LogException(const std::string& logText, const std::string& fileName...

Linked List Quiz - Part I

A short while back, Azhagu quizzed me on linked list based problems; singly linked list. I am recording those problems, solutions and my experience as a two part series. In the first part, I am introducing the linked list class, which I wrote for packaging the implementation of the solutions. This class pertains to the context of the problem(s) and cannot be used as a general purpose linked list. A std::list  might more pertinent in the context of the general purpose implementation of a list. Here are some of the problems that Azhagu asked me to solve:- Reverse the list recursively Reverse the list iteratively Find if the list is cyclic Find the node that causes the cycle (and break the cycle) Reverse every K nodes in the list I will be solving reversing the list (both iteratively and recursively) and finding if the list is cyclic problems in this episode. #pragma once #include <iostream> #include <vector> using namespace std; template<typename T> clas...

Sms FireWall Update !!!

I gave SMS FireWall a refresh with a couple of features requested by users:- An option 'Allow and Move' in the settings screen, which when checked moves the messages from the quarantine vault when opted to be added to the allowed list. Although it might be clear to you, let me explain it in a few words how it works. When you long press a sender in the quarantine vault, a menu with two options appear - Allow, Delete. When 'Allow' is clicked, the sender is added to the allowed list. And when the 'Allow and Move' setting is checked, the messages from this sender are moved to the inbox. A confirmation dialog prompt when attempted to empty the quarantine vault A few minor (internal) improvements Hope they are useful to others too. And let me know if you need any other features to be in the application.

OrderedThreadPool - Bug Fix !!!

Hugh pointed out a bug in the OrderedThreadPool . I think there is a small window for error in the OrderedThreadPool class. Bascially, if an item of work is queued, then a worker thread runs, takes the item off the queue and is about to call wcb(state) - but at that instant is (say) context switched. Then another item gets queued and another worker thread runs and dequeues the item and then again is about to call wcb(state). There is scope here for the two operations to run concurrently or even out of order... Here is the fixed version of the same. using System; using System.Collections.Generic; using System.Diagnostics; namespace System.Threading { public class OrderedThreadPool { private Queue workItemQ = new Queue(); private bool loopWorkRunning = false; public void QueueUserWorkItem(WaitCallback wcbDelegate, object state) { lock (workItemQ) { workItemQ.Enqueue(new ThreadPoolTaskInfo(wcbDelegate, state)); if (workItemQ.Count == 1 && !lo...

Unique Id Generation !!!

A short while I was engaged in a little project where I had to interact with a third party service provider who required a (30 length) unique id as part of the transaction. I am little dumb and am used to GUIDs for a long time when it comes to unique ids. But GUIDs are more than 30 in length. I was trying out some stupid ways like stripping out the trail part of the GUID to make 30 length unique but my intuition wasn't convinced about the tricks I was working out. Finally, Sriram helped me with it. I am sharing his code for the benefit of others. string GenerateUniqueId(int length) { string asciiChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; char[] chars = asciiChars.ToCharArray(); byte[] randombytes = new byte[length]; RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider(); crypto.GetNonZeroBytes(randombytes); StringBuilder result = new StringBuilder(length); foreach (byte b in randombytes) { res...

Sms Firewall !!!

Tired of prank SMSes. Need a simple way to block them, and keep your inbox clean? Don't worry. You got it! SMS Firewall is a simple and cute (hope you like it!) Android application to block and quarantine unwanted SMS from reaching your inbox. Unwanted are those who are neither in your contacts list nor in the allowed list, which is provided by the application. Phone numbers or sender names such as your bank or mobile service provider can be added to the allowed list. You got an option to either notify you of the blocked SMS or ignore it, in which case you will have check the quarantine vault by yourself. Besides, you have a 'Just Monitor' mode, which is primarily used for debugging purposes or when you don't want to block SMS from unknown sender(s) (for a while). When this mode is switched on, SMS from unknown senders will reach the inbox and also a copy of it is saved in the quarantine vault. Here are a few screen shots to get you attracted... ...

To Ritche !!!

Dennis Ritchie , whom we all know as the creator of the C programming language passed away on Oct 12, 2011. We have lost one of the brilliant minds of mankind. I owe him this post for he has been one of the greatest inspirations in my life and the very reason that I am into programming. Dennis Ritchie (1941-2011) The first time I saw Ritchie's picture, I felt him like Jesus. I would say that the divinity that his face reflected pulled into the world of programming. It was during my college days that I lay hands on his book - The C Programming Language . It is one of the most influential computer books I have read. I had read it at least a couple of times and referred it a thousand times. I felt it like a lecture by Ritchie. And so I had marked a lot of pages with comments and questions as if they are addressed directly to Ritchie himself.  I had the book with me almost all the time. I even hide myself in the last row during other lectures to read the book. I felt excit...

Seinfeld Calendar Update !!!

We have released an update for Seinfeld Calendar with a bunch of some exciting features and defect fixes. I hope they are exciting for you too. NOTES : You can add notes or additional information for a task on a month basis. Again, the notes are maintained month wise and not date wise. It is just to keep it simple, since adding it date wise would require a special selection mechanism for marking a date as completed. REMINDERS : When you create a new task or edit an existing task, you will now be able to add reminders for a task, or disable them too if you added one already. As you might have guessed it, the reminder pops up a notification at the specified time reminding you to do the task. It could be jogging in the morning or taking your pills at night. The tool is now improved to not only keep track of your task status, but also helps you to do it everyday by reminding you. So you will not miss doing it! HOME SCREEN WIDGET : We have added the facility to drop home screen w...

Android meets .NET !!!

It is always fun for me to program in C# (besides C++). If so, how would I feel if I was able to program for Android in C#? You may be wondering what in the world I am talking about. Android development environment is all Java and open source stuff. How could this Microsoft thing fit onto it? Well, it seems that some clever guys had huddled up and ported Mono for Android , developed .NET libraries for the Android SDK, and also supplemented it with a 'Mono for Android' project template in Visual Studio; and called it mono for android . Thus we end up writing C# code happily for Android. After a bunch of installations , fire up your Visual Studio (2010) and you should be seeing a new project template 'Mono for Android' under C#. Create a new 'Mono for Android' project, which by default comes with an activity - C# code. Modified the orginal code to try starting a new activity from the default one... The project layout for most of the part is...

Quiz: Beauty of Numbers

Sriram asked: Imagine there is a queue of people for getting a ticket for a movie or somehing. Where should be standing in the queue to last until the manager or some guy keeps removing people at odd indices. For instance, if the queue has 5 people given a token A to E, first we remove the first set of odd numbered positions in the queue, so A, C and E are gone. Now B and D remain. Again we remove the odd numbered positions. This time B alone is gone, and D is the winner. So in a queue like that, what is the lucky position you should hold so that you survive the wave of removals? I could give you the solution right here in front of your eyes. But that would not give you time to think to solve it on your own. So solve it and\or read the solution here .

To Hold or Not to Hold – A story on Thread references !!!

void SomeMethod(int x, double y) { // some code .... new Thread(ThreadFunc).Start(); } What do you think about the code above? Some may say nothing seems to be wrong. Some may say there is not enough information to comment. A few may say that it is awful to spin off a thread like that (the last line of the method), and that there is a probability for the thread to be garbage collected at an unexpected point of execution. That is something interesting to discuss about. Before presenting my thoughts and supporting facts, the short answer is NO. A thread spun off like that will not be garbage collected as we expect, although one should be morally insane to write such code. Alright, let us discuss. The Thread class is like any other reference type in the BCL. When an instance of a reference type holds no more outstanding references, it is a candidate to be garbage collected. Even worse, it could become a candidate even while it is executing an instance method, while there ar...

Crazy Brackets - [](){}();

What does this cryptic bracket sequence mean? What programming language is it? Is it valid syntax? If there is even a weak chance of this syntax being valid, then what does it mean? Alright, alright, alright.....It is C++. That would calm most people; with all their love (pun) for C++. Specifically, it is C++0x. Amongst many other features that we have been waiting for, C++0x gives us the power of lambdas. The formal definition of a lambda in C++0x is as follows:- [capture_mode] (parameters) mutable throw() -> return_type { body } So a lambda may capture one or more variables in scope by value or by reference, or it may capture none. Specifying return_type is not necessary if the type can be inferred or is void. For instance, a std::for_each 's functor based code could be inlined with a lambda as follows:- std::for_each(v.begin(), v.end(), [](int x) { cout << x << std::endl; }); A lambda definition could be assigned to a variable and then used or in...

Wetting my feet in Android - Seinfeld Calendar

A couple of my colleagues and I huddled up to learn a bit of Android. I think I told you about that a short while back. We developed a very simple application - The Seinfeld Calendar . Seinfeld calendar, or otherwise called the habit calendar, is Seinfeld's productivity secret . The secret of achieving your goal is practising something, whatever your goal is, everyday and make it a habit. And mark it in your calendar each day you practice, and make sure you do not break the chain. Our application helps you keep track of your everyday tasks. Our application does not jog or meditate or quit smoking for you. You have to do your tasks. Our application provides the facility to create tasks for the habits you wish to pursue, which in certain cases like smoking means quitting. And then you mark each day in the calendar if you pursued your task, else you don't mark and break the chain. And no cheating! The application is in very nascent stage and does not provide you (fancy) s...

Anonymous Classes vs Delegates !!!

I am not a java programmer. By that, I do not mean I am against Java. As a programmer by profession and passion, I try to learn things along the way. That includes a little of bit of Java. I should say that my proper encounter, so to say, with Java is a simple application that I am trying out with Android. There might be some hard core differences and/or limitations in the Android version of Java. But I am almost certain that I am using only primary level features of Java. In android, there is this OnClickListener interface, which is used as a callback interface for a button click. So, it is used something like this:- // Create an anonymous implementation of OnClickListener private OnClickListener mCorkyListener = new OnClickListener() { public void onClick(View v) { // do something when the button is clicked } }; protected void onCreate(Bundle bundle) { ... Button button = (Button)findViewById(R.id.someButton); button.setOnClickListener( new OnClick...

Quiz - Where am I?

The question is, in C++, how do detect if an object is allocated on the stack or heap. On Windows, the stack address is in the range of 0x80000000. If the address of the variable is in this range, then you could say that the object is allocated on the stack; else it is allocated on the heap. This technique of detecting is not preferrable since it may not work on other operating systems (such as linux), and deals with the platform specific information making it a non-portable solution. Let us try to use standard C++ stuff to solve the problem. Ok, we want to know where an object is allocated. In C++, new operator is responsible for allocating an object. It was very thoughtful of Stroustoup to keep the object allocation and initialization\construction separate. new operator is responsible only for allocation. The compiler is responsible for woving up the code for allocation and calling the constructor. It was also very thoughtful of being able to specify the location where the ...

Guess Who?

You may not know the guy in black; but you sure should be knowing the guy in green. Don't know him ? I am not a patron of his philosophies against planned design. But he sure is a great guy with lots of good ideas. It was nice having an hour long chat with him.

Invoking methods with out and ref - Finale !!!

Alright, it is a long wait. And I am going to keep it short. Recap of the problem: Why did the ref variable in SomeMethod not get the expected result ( DayOfWeek.Friday ) when called from a different thread? Boxing. Yes, that is the culprit. Sometimes, it is subtle to note. DayOfWeek is an enum - a value type. When the method is called from a different thread, we put the argument (arg3) in an object array, and that's where the value gets boxed. So we happen to assign the resultant value to the boxed value. So how do resolve the issue? Simple.......assign the value back from the object array to the ref variable. int SomeMethod(string arg1, string arg2, ref DayOfWeek arg3) { if (Dispatcher.CheckAccess()) { var funcDelegate = (Func<string, string, DayOfWeek, int>)SomeMethod; var args = new object[] { arg1, arg2, arg3 }; int retVal = Dispatcher.Invoke(funcDelegate, args); arg3 = ...

Invoking methods with Out and Ref !!!

Straight to code..... int SomeMethod(string arg1, string arg2, ref DayOfWeek arg3) { // Wildest implementation! } The above method had to be executed on its dispatcher thread. So let unravel a bit of the wildest implementation above. int SomeMethod(string arg1, string arg2, ref DayOfWeek arg3) { if (Disptacher.CheckAccess()) { var funcDelegate = (Func<string, string, DayOfWeek, int>)SomeMthod; return Dispatcher.Invoke(funcDelegate, arg1, arg2, ref arg3); } // Wilder implementation!! } Before you say anything, yes, the compiler spat the following errors:- Error 1 No overload for 'SomeMethod' matches delegate 'System.Func<string,string,DayOfWeek,int> Error 2 The best overloaded method match for 'System.Windows.Threading.Dispatcher.Invoke(System.Delegate, params object[])' has some invalid arguments Error 3 Argument '4': cannot convert from 'ref System....