Wednesday, 10 October 2012

Javascript Jinx: Parsing 'Infinity' to get a number

Everyone would agree Javascript is an insane language. It is very easy to make a mistake in Javascript.One thing about Javascript that makes it harder to code in it is that it is a very forgiving language. It does not raise errors (except in extreme cases). So, there are high chances of the code behaving weirdly.

Here is one awesome trick in Javascript. We know that in Javascript, there is no divide-by-zero error. Instead, when you try to divide any number by zero, you get a special number called Infinity. And this trick is about parsing Infinity to get a number.

Try to run this code in Javascript:
var result = parseInt(1/0, 19);
console.log(result);
The result is most unexpected. The output would be: 18.

Wondering how? This is what happened:

1. 1/0 gave Infinity
2. The base here is 19, so Javascript tried to convert ‘Infinity’ to a number in base 19
3. In base 19, the letter I corresponds to digit 18 (like F to 15 in hexadecimal)
4. So, it converted I to 18, then ignored rest of the string since n is not a valid string, and thus we reached 18.

Amazing isn’t it? This is why we have to be very careful with Javascript. Another version of the same trick:
var result = parseInt(1/0, 24);
console.log(result);
This time, the base was 24. So, this string is parsed: Infini, its parsed upto t since is it not a valid number in base 24, and then Infini is converted to a number to get 151176378 as the output.

(Courtersy: Stack Overflow)
P.S: This trick is so famous, try to search 'parseInt(1’ in Google, you will get an instant result.

Tuesday, 2 October 2012

Java Jinx: Differentianting Java API classes from other classes

This article is about how to differentiate Java API classes from other (external API) classes. This will require a bit of history in why Java became so popular and some architectural background about it. Java was mainly designed to work across networks. Main advantage of Java is that once complied, it could run anywhere, so computers connected across networks can play around with the complied Java file and run them directly on their computer. This led to popularization of Java over networks.

But with networks, comes security. So, any Java code coming through the network ran in a Sandbox, and all the classes that were loaded during the execution of the code went through a security check. The classes are loaded using a Class Loader instance, which performs all the required checks before loading any malicious files. But, these checks take time. So, a Primordial Class Loader loads all classes that are part of the Java API to speed up the loading process. Hence all Java API classes are loaded using the Primordial Class Loader and do not have a Class Loader instance.

So the logic is this: take any classes and check its ClassLoader instance exists using the getClassLoader() method, if the value is null, it is a class from an in-built Java API, otherwise, it is a class from external API, not part of Java API bundle.

Here is the code snippet demonstrating the use:
import org.codehaus.jackson.map.ObjectMapper;

public class ClassSourceInfo {

public static void main(String[] args) {
Integer a = new Integer(10); //any Java API class
ObjectMapper mapper = new ObjectMapper(); //any external API class

determineClassSource(a.getClass());
determineClassSource(mapper.getClass());
}

private static void determineClassSource(Class clazz) {
if(clazz.getClassLoader()==null)
System.out.println("Class is part of Java API");
else
System.out.println("Class is not part of Java API");
}
}
Now the question comes, where is this useful. Well, that is for programmers to decide. For example, there can be a scenario where every class which belongs to an external API used in the Production Code be logged into a file, just for debugging purposes.

Tuesday, 29 November 2011

One Step Ahead towards Retail

The recent bill passed in the Parliament that allows 51% FDI in multi-brand retail has created controversy in the political space. The opposition parties are threatening to stall the Winter Session, at a time when Parliament cannot afford to miss the session. Although it is the nature of Opposition to vehemently oppose every move taken by the ruling party, this particular discussion has aroused my interest.

The Congress believes that entry of global players into multi-brand retail space will enhance the entire chain and ultimately benefit the “aam aadmi” in multiple ways, by creating many jobs, by easing prices via supply strengthening, and creating an excellent farmer-to-market infrastructure. The government has ensured this by restricting companies to invest at least $100 million and 50% of it in building back-end infrastructure. Given these rules, there is no doubt that there are going to be positive effects of the decision.

These global players were eagerly waiting to tap the potential India has. They have at least 20 years of experience in building end-to-end infrastructure, and flattening the entire retail process. The kind of technology Wal-Mart offers in retailing is second to none. It has such command over its supply chain management that it is bound to create a technology that will amaze customers. In such an age when India is considered to be one of the fastest growing economies in the world, why should India be bereft of witnessing such a transformation in technology?

The most prominent argument that the Opposition is riding on is that entry of such global players in the retail arena will kick out small retailers and famous “kirana stores”. This argument is baseless as I can think of one comparison that will make this clear. Entry of four wheelers into the market does not kick out the two wheeler market. This may sound a very crude comparison, but this is how I justify it. Big retailers and small retailers are entirely different concepts, and they both cater to different markets. People buying from malls also buy from kirana stores, the main reason being they are fundamentally different concepts of retailing.

Shopping in big malls is considered to be a one-time thing, with urban families going once every weekend or fortnight to buy essential and “non-essential” items. Yes, non-essential items, because a trip to a retail mall always brings in many extraneous items along with the essential ones (accept many families). These trips sometimes are also considered an outing or an experience rather than an absolute necessity. While the kirana stores offer customer satisfaction by giving a personal touch, they also offer home delivery, and offer credit facilities also. They are considered a necessity while malls are not, no one would like to drive 2-3 miles just to buy a loaf of bread. Kirana stores deliver items when urgency is a criterion. Also, in such busy professional life, every one would like to buy things on the way home. In such a scenario, kirana stores have still a long way to go.

One thing that amazes me is why don’t players like Big Baazar, D-Mart or Reliance oppose this move. Because they cater to the same market the big foreign players cater to. If Wal-Mart or Tesco or Carrefour enter Indian market, these are the ones who would be sharing the markets. Any customer after deciding he wants to buy a car would choose between Toyota Etios or Maruti Swift but he definitely won’t be making a choice between Bajaj Pulsar and Maruti Swift. In the same way, whenever a customer wants to go shopping in a mall, he will choose between Wal-Mart or Reliance Mart, creating competition to the big Indian players already present in the market. It is surprising to see why no politician is addressing this issue, perhaps because by addressing small retailers they want to win the votes of those people who think their logic is correct.

Either I am missing some issue on this point, or either the whole economy is shrouded by political debates alone. In my opinion, no market should be restricted, Darwin’s theory of struggle also applies to this space. Let the toughest player survive. Opening the market in 1991 has transformed the entire economy, and this is one thing we should thank Congress for - opening up the market. It is trying to do the same thing now. In such economy when inflation is not easing despite million efforts by RBI, why not give a little chance to these players as well. It won’t in any way harm the current prices, that is for sure. Lets all take one step ahead, together.

Friday, 28 October 2011

Are Great people really Great?

Scores of people have come upon this earth and have contributed a lot to mankind, and we remember them as heroes or saints. Their simple acts have had profound effects on the way this world lives and breathes. These people are remembered for their good qualities, selfless nature, extraordinary intelligence, problem solving capabilities and what not. But, one question that comes to my mind is that - what will happen if people come to the know that dark side of these people? Would their opinion change? Should their opinion change?

The recent death of Steve Jobs created a wave of sadness in this world. Everyone hailed the great master and innovator of technology. We all know that without him, we wouldn’t have the digital world at our hands. PCs, iPods, smartphones, tablets - he brought a revolution, followed by millions of other similar products, leading to a price war that ultimately lead to affordability for the mass. He brought the technology of the sci-fi to the hands of the common people. Undoubtedly, in the words of Thomas Friedman, he made the world flatter. But, do we know the dark side of his persona. As the stories are revealed, there are many aspects of his personality that completely changes our perspective towards him. For example, he demanded perfection from every one of his employees. If an employee had worked all night and his work was not good, he would just tell him “what the hell did you do. you are useless”. He didn’t value hard work, he valued only innovation and perfection. And he was also notorious for firing employees in the corridor, when everyone was watching, just to humiliate the employee for his bad work. He also minced foul words for Bill Gates, Larry Page only because he did not like their work. He was selfish, and obsessive about only Apple’s progress.

Take another example, of one person that is near God to every Indian - Mahatma Gandhi. He gave us independence, gave us new weapons like Civil Disobedience, Non-Cooperation, and Satyagraha. He was an icon with a frail body but determination that no one could shake. But, he was not a good family-man. As we dig deeper inside the story of his life, we come to know that he was neither a good husband, nor a good father. He never cared for his wife nor his children. He was so preoccupied in the fight for his nation that he never had time for his family. His sons had always said “He was the father of our nation, but he could not be our father. We had to pay the price”. There are also speculations that he had left Kasturba in South Africa to live with Kallenbach, an architect. Gandhi was deeply overtaken by Kallenbach’s personality. There are also some speculations that Gandhi had slept with some of her nieces. Some people has gone so far as to call Gandhi “a very dangerous, semi-repressed sex maniac”.

Should these facts change our perspective towards Steve or Gandhi? Do these facts diminish the fact that they contributed a lot to the society? The answer is: No. These facts do not change what they gave to the world. But when such people are made icons, the negative facts are purposefully ignored or forgotten. And when such facts are revealed, it leads to protests and furor. The reason for this is that there is negativity in everyone. But people see such icons as epitome of goodness. They try to ignore the negativeness in icons because they get inspired from them. If they are told about the dark side of these personalities, they feel they possess some of that dark side too. And people can never accept their dark side. They think that “if these people can be bad, what about us? So, they cannot be bad”. They cannot accept the fact that someone so famous can have a dark side too. It is absolute denial.

And this was the only reason Dan Brown’s “Da Vinci Code” created such a controversy, because he tried to expose some facts which tarnished the image of Jesus. Great writers, poets, novelists write for one reason - to inspire people to do good from the good of other people. But there are other writers too - who are interested in telling people the dark side also. It is up to us to know both the sides, and follow the good side. The dark side of these personalities simply tells us one thing - there is good and bad everywhere. But what made the people famous and iconic is not the bad thing, but the good thing. And the good things were enough to shadow the bad things into a little corner which everyone ignores. Embrace the truth, and follow the good. That way, everyone will be happy and aware.

Wednesday, 12 October 2011

Steve's Legacy

A Legendary person has left us: Steve Jobs, the pioneer of many technologies we use today, that have changed our lives altogether. Who would have imagined, that one day the research of Steve duo - Jobs and Wozniak, would transform the world and usher in an era of Personal Computing. Yes, I am talking about Apple II - the Mac that changed the world. It is amusing to imagine that someone without a formal college education can do something so wonderful. For normal people like us, its just impossible to imagine the way Steve would have thought.

He was great not only as an innovator, but also an excellent entrepreneur. Under his tenure, Apple grew. Without him, Apple fell. He switched his field to that of Animation, and transformed it too. There is no single person who does not know what Pixar is. Wherever he went, he had one thing in him - his passion for things. In his famous lecture at Harvard, he had told “When I left Apple, it was the best thing that could happen to me. It was like taking a break from all the fame and starting again as a beginner”. This attitude really helps - the world has always an opportunity to grab, just have a vision for it.

iTunes replaced CDs and DVDs, and iPod replaced the players. Bag on the back, earphones plugged and iPod in the pocket became a symbol of modern youth. Music was being “shuffled” on the fingertips. The previous generation can laugh at themselves waiting for their favorite song to come on Doordarshan or on Aakashvani. iPod signified freedom to the youth. It is really inspiring to see that a technological product such as an iPod, can have not only a technological impact, but social and cultural impact as well. iTunes brought the world closer. It just helped making the world flatter.

iPhone is world’s first touch smartphone, and till date, it is the best. Like Apple II introduced the concept of Personal Computers and GUI, iPhone was the foundation for touchscreen technology. Before iPhone, touchscreen was a sci-fi concept, but after iPhone, we never cared when that child sitting on the next seat used touchscreen technology. iPhone was not only a smartphone and a mobile - it was a concept all together. And just when we were coming out of that shock, we suddenly had iPad and iPad 2. And today we have every mom and pop company making tablets suiting to every market.

What is common between Apple II, iPod, iPhone and iPad? Answer: the reaction that followed. Every competitor followed the suit. After Mac introduced type-face font and a rich GUI, Windows followed it. And today, we have no computer that does not use a GUI. After iPod? Every company in the world came up with their own MP3 players. But still, iPods stand above the crowd. Similarly, after iPhone and iPad, every company started making their own smartphones and tablets. Even Google, the company which is known for some of the best brains in the world - had to bow down to Apple. Many companies launch products, few companies start a revolution. And Apple started revolution not once, twice or even thrice - but four times. That is a rare feat. Steve was really awesome.

He was a real Phoenix - he rose from his ashes every time he fell. He kept going on. Although, there is some part of Steve that doesn’t make us want to respect him. He abused is employees, fired them in the corridor, and he disowned his daughter born in a wedlock. But, everyone has some yin and yang. The world wasn’t affected by his firing a few employees or disowning his daughter, but it was surely affected by his innovation. And we will always remember him for that.

Thursday, 6 October 2011

iPhone 4S - wait is over

The long awaited iPhone 4S has been launched. Although people were expecting the launch of iPhone 5. Investors and Apple fans were disappointed by the looks of iPhone 4S, it was the same as iPhone 4. People had expected larger screen size, slightly thinner model, but, well Apple guys thought to delay that to iPhone 5.

Perhaps the best feature in iPhone 4S according to me is Siri, the voice recognition software that virtually talks to you. You can use your voice to send messages, schedule meetings, place phone calls, setting reminders, everything. And you just talk the way you talk. It replies in its own voice. Its the single best innovation in the new iPhone, and it is first step towards the talking computers and robots we see in the sci-fi flicks. Personally, I was amazed by the level of human-like interaction offered by Siri. Hats off to Natural Language Processing.

iPhone 4S has the new Dual-Core A5 chip that promises to be the fastest smartphone processor ever. No comments on that because will have to test out the speed when I lay my hands on it, but the video shows Infinity Blade 2 being played on the phone, and it does look really awesome. The graphics are PSP like, so, they I think the A5 chip will do the trick of a next gen smartphone processor.

The camera has been tweaked too. Apart from the increase in the MPs, it has increased the aperture size and added an extra lens for sharper pictures. It also has advanced face recognition and auto white balance. It boasts of the best 8 MP camera in the phone segment. It can record 1080p videos and use a ‘stabilizing’ feature that can reduce the shaky movements while recording videos. The picture and video editing parts are also cool. You can crop images, auto balance them, edit videos, cut them, add sound effects and what not. It is just another feature of the iOS 5.

Speaking of iOS 5, the three main things they have added are - Notification Centre (copied from Android), iMessage (copied from BlackBerry) and Twitter Integration. iMessage is one reason for BlackBerry fans to move to an iPhone. Every iPhone running on iOS 5 can send unlimited message to each other via data carriers- either 3G or WiFi. People troubled by sending only 100 texts per day in India can take a breather now. Also, Twitter integration is one cool thing for twitterers like me. You can tweet directly from Safari (the browser), Photos, Camera, YouTube and Maps.

Another cool feature is iCloud - Apple’s own cloud technology. With iCloud, you can sync everything directly to the cloud. Pictures, music, videos, messages, contacts, tasks everything stays up on the cloud. The music you buy from iTunes and photos you click on your iPhone go directly to iCloud. If you own another iOS 5 device (another iPhone or iPad), everything gets seamlessly synched to your device. Although cloud is common now, but synching every device automatically still sounds cool. Although this would need good data plans and high speed internet connectivity - both of which still remain a rich person’s paradise in India.

Apart from these main features, they have introduced a new way to talk between two iOS 5 devices via Facetime - face-to-face video chatting. Nothing new though. That winds up the iPhone 4S. Sad it had to come with the death of Steve Jobs. But that is another story to tell. The probable date of launch in India and other countries is 28th October. We are waiting. And NDTV Profit guys are waiting the most.

Tuesday, 27 September 2011

Piracy: is it really bad?

Piracy is highly condemned everywhere. It is the terrorism of software. It eats away the profit of all the developers and makes their efforts useless. The fact that piracy is wicked is even supported by the people who share stuff on torrent, who write that “If you like this game/movie, please buy it. Support the devs man”. It is really disheartening to see that after all the effort one has put into a product, someone just copies it and sells it for free.

Piracy is more of an ethical issue rather than a technological one. For every mind that protects the products from getting copied, there are ten others who have much sharper mind [probably their own co-workers] who want to get the product out for free. According to me, half of the pirated products are the efforts of the employees working on it who can do a little ding-dong and screw their company’s profits. It wouldn’t come as a surprise to me if I’d see a Microsoft employee selling pirated Windows to his neighbor.

In short, its bad. But after giving it much thought [as per what limited knowledge I have], I have found that piracy can help - if tackled like a necessary evil. In a market like India or China, I think piracy has helped Microsoft in the long term. [I’ll use Microsoft Windows to discuss the case because “its obvious”]

In a market like India, when computers were considered magical artifacts and when a Pentium I would cost you nearly Rs. 50,000, a free OS helped a lot. And at that time (the 90s era), Microsoft was slowly gaining popularity as the best OS around, because it had kicked in the concept of GUI. As a result, computer revolution began in India with a PC having Windows. At that time, India had no laws to tackle piracy. [Well, even if it had, I don’t think it would have made much difference].

The result was the rapid expansion of the market with just Windows as the concept of an OS. Pirated versions of Windows 95, 98, 2000, NT and XP [the decade of 1995-2005] did the miraculous work of making Indian people believe that Windows is part of a computer and that a PC and Windows are one and the same. Schools, colleges, universities, cyber cafes - everywhere and everyone - used pirated Windows. No one knew what Unix was. [what if it was like, 100 times better and was developed 20 years prior to Windows].

The result - today with the advent of laptops, the price of Windows is bundled with the laptop. There are many laptops with Unix as the OS, but those are rare. 95% of the laptops sold in India are shipped with the Windows OS. And in the coming years, as long as laptops and branded PCs are to stay, Microsoft has its audience, and they will pay for it. [And believe me, PCs and laptopos are staying, no pesky tablet or smartphone can play Crysis, Call of Duty or World of Warcraft].

Two words that would help me over here are - market penetration and brand building - and piracy helped Microsoft do that, at least in India. And I don’t think it suffered losses in the decade. Now imagine the utopian concept, that Windows had no pirated versions. I don’t think anyone in India would have coughed up anything between Rs 3000-7000 for something they can get for free. The result would have been the emergence of Unix as the OS of choice, Microsoft getting beaten up as “something that charges money for what we get for free”. Because here in India, the concept of good is the concept of free.

Let us take the discussion to a more general perspective of piracy. Piracy helps companies by letting the audience adapt to their products. Once you see people clinging to your products like a pole in a storm, it is time to introduce the money concept, but even that should be done incrementally. For example, music piracy helps people get the song in their head, and when there is a concert of their favorite singer, they are going to cough up money for something that they already know.

In the gaming industry, (PC specifically), the companies shouldn’t battle their pirated version getting around if they want to build a brand in terms of the game. Personally, I would buy the next Call of Duty or Battlefield game if I cannot it pirated. The thing is - for urging people to buy your products, you should arouse their interests. People will pay only if they like it, and no one can like by seeing only the demo or the trailer of the game.

Companies should get one thing straight into their mind - no one will pay for a new thing. Instead of battling against piracy, which is inevitable, the strategy should be - getting people used to your products and charge when they have not alternate definition of the product you’re selling. And then, you are dominating. And I think Microsoft has been successful in many markets by following this endeavor. [Although what we need ponder upon is whether this market strategy was intentional or accidental, and that, is what we’ll never come to know].

Bottom line - even if piracy [or shall we say, free product] hurts you in the short term, cling to it, it may reap you profits in the long term. But as people get adapted to your free product, its the responsibility of the company to manage the brand in such a way that you know how to leverage your customers into paying what they consider best. A little thinking and market research - and piracy is the industry standard for launching their first product. [Now we’re talking about utopia].

P.S: We would never know if companies have already realized this, and that is the reason why pirated products are still floating in the market.