Wednesday, May 2, 2012

Dynamic Function Names in JavaScript

Today we had a problem where we need to generate unique JavaScript methods for various functions which will be in separate ".js" files. A Google search returned no useful result (It may be my mistake bad!). So here is the workaround which I have figured out.

JSP (or any server page) before including the JS

 <script>
    var dynamic = "<%=userName%>"; //for that case, any dynamic value from serverside
 </script>

In JS

window["generic_" + dynamic] = new Function("a", "b", "return alert(a+b)");

refer: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function

Calling it in HTML

<input name type="text" name="any" onchange="generic_<%=userName%>('Hello ' , this.value);">

Got it?!?! Please let me know if you have any queries!

Monday, November 14, 2011

Clear Form with jQuery

Here is a small method that can clear (not reset) all the text, checkboxes, radio, select and multi-select.

function clearForm() {
  $("input:radio, input:checkbox").attr("checked", false);
  $("input:text, input:hidden, textarea").val("");
  $("select").attr("selectedIndex", "0");
  $("select[multiple]").attr("selectedIndex", "-1");
}


Here is a HTML demo of the same which highlights the difference between clear and reset

<html>
 <head>
  <script type="text/javascript" src="jquery.js"></script>
  <script>
  function clearForm() {
   alert(document.forms[0].test4.value);
   $("input:radio, input:checkbox").attr("checked", false);
   $("input:text, input:hidden, textarea").val("");
   $("select").attr("selectedIndex", "0");
   $("select[multiple]").attr("selectedIndex", "-1");
   alert(document.forms[0].test4.value);
  }
  </script>
 </head>
 <body>
  <form name="foo">
   <input type="text" name="test1" />
   <input type="radio" name="test2" />
   <input type="checkbox" name="test3" />
   <input type="hidden" name="test4" value="123" />
   <textarea></textarea>
   <select>
    <option value="123">123</option>
    <option value="456">456</option>
    <option value="789">789</option>
    <option value="1324">1324</option>
   </select>
   <select multiple="multiple">
    <option value="123">123</option>
    <option value="456">456</option>
    <option value="789">789</option>
    <option value="1324">1324</option>
   </select>
   <button onclick="clearForm()">Test</button>
   <button onclick="document.forms[0].reset(); alert(document.forms[0].test4.value);">Reset</button>
  </form>
 </BODY>
</html>

Monday, October 17, 2011

Ability vs Morality


Recently, I was in to some arguments with Apple/Microsoft fanboys. As usual, a lone Linux defender, I was made to fight my own way out. But just one simple argument brought them down. So, I feel, this argument is worth sharing so that similarly trapped open-freaks can use it... No copyrights!!! ;-)

The points put forward by Apple/Microsoft fanboys include, ease of use, eye-candy, availability of third party apps, more choices of games, media, powerful hardware and GUI based tools etc.

Though we can counter the arguments in every front, there is no much room in such arguments when the opposition is deaf to whatever you claim. For example, I quoted that top ten of TOP500 run Linux (ref: http://en.wikipedia.org/wiki/TOP500). But the problem is they are not aware of TOP500! Likewise, they have many misconceptions like Linux = bash. They never heard about Gnome, KDE etc. So let us waste no time in explaining them the more technical aspects of our choice for Linux. Let us attack them using the openness of Linux (i.e. the cornerstone of the entire GNU/Linux/Open Source movement).

Consider this example. Once there lived two archers. One of them is better at shooting arrows than the another. But the better one worked for gang of robbers while the other chose to work for the local scout troop. One day the situation made both of them face each other. The one that was better skilled killed 3 of the men in scout troop, including the lesser skilled archer. But at last, few other men from the scout troop managed to thwart the robbery and killed/chased the gang members. Ultimately, the 3 who sacrificed their life for the public good are real heroes, not the one who was able to kill 3 of the opponents within seconds.

Yes! It is more paying to be in the gang of robbers. And there are some cult like following for evil people like Hitler or Osama, while good people who dared to sacrifice their life for sake of others left unnoticed. How many of you can tell the name of American soldier who shot Osama without Googling? Strictly speaking the one who had more talent ended up in the apt place where his skills are valued, recognized and can be materialized as monetary gains. Survival of the fittest, right? WRONG! This type of silly arguments can be used to justify anything from  petty theft to inhumane crimes like rape or murder. Imagine this "I can beat and tie you up and rape your wife! Survival of the fittest!!" Is that acceptable?

Similarly, technical people should also have some sort of ethics and responsibility towards the tech-community at worst and public at best. It is out of moral responsibility that we should be supporting Free software/Open source. We should choose to be a scout even if we get paid lesser and get lesser visibility. If a doctor claims to have invented cure for cancer by mixing existing pain killer and vitamins (neither of them is invented by him), but patents the same that, anyone who produces or uses the medicine should lick his boots, won't you protest? The same is happening everywhere in the so called "tech giants". That is the exact same reason why death of Dennis Ritchie, who made C and co-invented Unix, is ignored entirely while Steve Jobs, who cheated his friend and his own child, is canonized as patron saint of Technology!

So, it is very bad to just consider the mere outcome, while ignoring the impact in entirety. The locked nature of Microsoft and Apple is causing more harm than good. How much money is wasted in buying laptops where you are forced to pay for a licence of Windows even if you are NEVER going to use it? What about your inability to replace a battery in iPhone? You can't install what you want even after "buying" both the hardware and software?!? Even if you are selling your freedom, they should be paying you! But where in the world and what type of fool will pay for selling his own freedom! If you don't realize what you are missing in Apple/Microsoft products but you can quickly point out that there is something missing here and there in GNU/Linux or BSD, then you are just like saying "I am content with this prison. It is more safe, guarded by police, and I get food on time without doing any hard labor and the cell is painted in the way I wanted"

Monday, July 11, 2011

CYYMMDD (Integer) to DATE in DB2 for iSeries

There is a date format in DB2 for iSeries, CYYMMDD. Technically it is an integer and hence comparison of dates becomes easier and faster job for the machine. The aim of this post is to demonstrate how to convert this CYYMMDD date into a SQL date. This is to ensure that the date is presented to the user in an understandable format and avoid type mismatches while dealing with languages like Java (java.sql.Date).

First, let us understand the format. C YY MM DD. We all can easily get that YY is the last two digits of year, MM is the month and DD is the date. What is that 'C'? As some of you had rightly guessed, it is century. But what century? It is century counted from 1900. So 1900-1999 is 0th century, 2000-2099 is 1st and so on. So, for example, 31st December of 1991 will be written as '0911231'. Likewise 1st of January 2003 will be written as '1030101'. 

So the first three digits from left, added with 1900 will give you the year (1900+103 = 2003)
Next two digits gives you the month
Last two digits gives you the date

One simple approach to this problem is to do substring of the incoming 7 character long string and do the necessary type casting before adding the century-year with 1900, then inserting hyphen (-) at appropriate places, before typecasting the entire thing into SQL DATE format.

Note: SQL DATE typecasting can be done by passing date string in YYYY-MM-DD format to the DATE() function.

But there is a catch here. As the value stored in the database is integer, it needs a pre-typecasting to string before we do the substring operations. OK, let us assume we typecast the integer from a query/parameter in to string and then do substring. Will it work for all cases? Because, preceding zeros are omitted while saving/processing the data as integer and '0911231' will come as a six digit '911231'. Here we can avoid the problem by checking the digits. If it is 7, then do the substring for digits (1,3), (3,5), (5,7). Else do substring for digits (1,2), (2,4), (2,6). Problem solved? The answer is NO!

What about 23rd of February1909? It will come as '90223' a five digit number. Another "else if"? NAH!!! If you are a programmer, please don't consider individual cases and write any code. First understand what is expected and what are all possible inputs we can expect. The best approach to start with is the boundary conditions approach.

As it was explained above, it is a 7 digit integer (positive numbers only). Century is counted from 1900. So dates lesser than 1900 can never come in to the picture and even if some dumbass pass negative values, they deserve to be thrown an incorrect result or error (whatever!). Least possible date is 1st January of 1900 that is '101' (note that it is only three digits, if you take up and proceed with earlier approach, you will end up if/else if/else for 7, 6, 5, 4 and 3 digits and if Linus Torvalds happens to see what you have done, your probability of entering heaven is "nolla".) Now the largest number possible is 31st of December 2899 (999+1900). As the format allows only 7 digits, no further dates can be represented in CYYMMDD format.

So, whatever the input (from 101 to 9991231) I need date. Fine, so I need the century year (that is anything that remains after removing last four digits). So just divide by 10000. Then add it with 1900.

In case of '101' it will be 0+1900=1900 and in case of '1010101' it will be 101+1900=2001. (Integer division NEVER produce decimal results!)

Fine, we got the year. Next let use go for the month. It is in middle (bit tricky here). I find that MOD function in DB2 is handy here. MOD(NUMBER, 10000) will give last four digits and a division by 100 give the first two of the last four digits. So, the formula for month is now MOD(NUMBER, 10000)/100

In case of '101', it will be MOD(101, 10000) = 101. Then 101/100 = 1. This your month. What about 9991231? MOD(9991231,10000) = 1231. Then 1231/100 = 12. This is your month. (again, integer division NEVER produce decimal results!)

So the last two digits, which are date alone remain to be handled now. Again we call upon our trustworthy ally MOD. MOD(NUMBER, 100) will give you the date, whatever may be the case. I think I can safely ignore providing examples on how MOD works with 100 on various digits.

Then we have to place hyphens in between year, month and date and construct a string that will be typecast to date. Did that work?


SELECT DATE(((NUMBER/10000)+1900)|| '-' ||(MOD(NUMBER,10000) /100)|| '-' ||MOD(NUMBER,100)) FROM SYSIBM.SYSDUMMY1;


Where NUMBER is your CYYMMDD integer.

Why don't you write your own custom function to return a DATE for any CYYMMDD date passed as integer?

Monday, May 2, 2011

Let Us Celebrate?

We all remember how was the reaction when the WTC was attacked on 11-Sep-2001. While many of the people and countries condemned the attack and conveyed their condolence to the people who lost their loved ones, there were celebrations in several countries too. It was to the extant that made me wonder "what is there to celebrate in death of thousands?" Today, some people around the world celebrate Osama bin Laden's death. It is incorrect to compare a terrorist and innocents killed in 9/11. But for me, celebrating Osama's death is also morally wrong.

We are humans. There is no joy in death of a fellow human. Whatever maybe the case. Wars and justice end in killing the accused sometimes. A priest can forgive the confession of a sinner in Church. But will that mean the sinner should be left unpunished by the law? What if John David claims that he had confessed his sins and God has forgiven his sins? Will the court also forgive and release him? That is injustice. Likewise, during wars it is a bitter truth that lives are lost on both sides. So, the goodness of war is not in killing someone. It is in establishing peace by eliminating people/things that hinders the same.

Think about this. If I a person is diagnosed with cancer and opts for surgery, he never does that in a mood of celebration. It is done when no other option is left. Though it is painful, it should be tolerated for betterment of health. Even if the surgery is successful and the person is cured, that will give the person a relief. Likewise, it is natural for people who lost their loved ones in 9/11 attacks to feel some relief on hearing Osama's death. They may feel that he had been punished for the crime he did. That is fine. But why people are taking it to street and celebrate it like winning in a football match?

What is the real motive of "war on terror"? Is it to kill each and every terrorist? Is that possible? It is shame on human beings. Even animals fight for three reasons. Food, mate and habitat. But see, for what all stupid reasons we fight and kill each other. In this aspect we make ourselves laughable even for animals. The real victory in any war is not to kill as much enemies as possible. It is in establishing justice and peace. If that is the case, the "war on terror" is yet to start. If and only if we are able to stop terrorists like Osama being formed, we are still losers.

Bible tells that God is strict and stubborn in establishing justice. But the same God is not blasting crackers and giving sweets every time He sends someone to hell. Yes, people are sent to hell for their own sins. It is justice being done. But that NEVER makes God happy.

Do I take any pleasure in the death of the wicked? declares the Sovereign LORD. Rather, am I not pleased when they turn from their ways and live? -Ezekiel 18:23


So this is what God desires. I am not expecting Osama to stop terrorism and start a free school or orphanage. But it will be better if he had repented for his mistakes and come forward to face justice by himself. That doesn't mean that he should be left unpunished for killing thousands of people. But the punishment is made complete when it brings a change in the accused. So the REAL JUSTICE is done when a person's heart changes.

If the person who commit the crime himself confesses that he committed it and accepts the punishment with humility, that is where justice is done. This is true for all type of injustice. From corruption to terrorism, everyone who commit the crime should change. That change should come from within. That is the change we should celebrate. That is the change we need.

"A Christian never rejoices" in the death of any man, no matter how evil, Vatican spokesman Federico Lombardi said, but instead "reflects on the serious responsibility of each and every one of us has before God and before man."

Bible says that we will witness the wicked punished.

You will only observe with your eyes and see the punishment of the wicked. -Psalm 91:8

But we are to observe that. Observe how bad it is to be wicked and how sad the end is for those who intentionally commit acts of evil. We should not cheer for it. We should meditate with tears and fear of Lord in our heart.

Don't rejoice when your enemies fall; don't be happy when they stumble. -Proverbs 24:17


As the above verse commands, Christians should keep themselves from committing sin by rejoicing death or misery happening to anyone they consider enemy. And the following verse is hard to practice in practical life, yet this is what Jesus said.

Love your enemies and pray for those who persecute you. -Matthew 5:44

Friday, March 25, 2011

Calculating Karma of A Meal

According to vegetarians' argument, plants are lesser life because they feel less/no pain and hence they amount of few or no karma when killed for food.

If pain is the only thing that causes karma, then are they ready to eat any animal killed in accident?

If we ask that, then they will say even during accident, the life suffered pain.

If that is the case, are they ready to eat a person/animal in natural coma and can't feel pain during death?

Then they will say the soul of animal is higher than plants and hence there is more bad karma in killing animals.

But their reincarnation crap holds that souls migrate from one life-form to another. That essentially means that souls of plants were once animals/humans or will become animals/human in future.

If the overall suffering caused is what really matters, agriculture lands are made by eliminating all other plants naturally living in the zone. Then agriculture involves in killing insects, mice and other microbes/fungus that attack crops. Even the so called "organic" methods use natural means to kill insects and other unfavorable micro-organisms. So for what ever reason, growing plants also involves in killing of innumerable lives.

Each and every rice grain is a fetus. It can grow in to hundreds of more rice grains (again fetuses) which themselves will again reproduce several folds. That means in some 100 years, every rice will become billions of billions of rice crops. So a bowl of rice is technically killing trillions of trillions of future generation of rice crops.

According to law of infinity,

+a x +infinity = +infinity (given a is not equal to zero)

Let us consider killing of plants cause negligible karma. Whatever, negligible means it is NOT exactly zero

0.0000000000000001 x infinity = infinity

Let us consider killing a chicken that crossed its egg laying term

1000000000 x 1 = 1000000000 (which is far less than infinity and hence lesser karma than a bowl of rice)

Some again argue that killing animals is like killing humans. Come on! You say there IS difference between plant and animal life, but refuse if we say that there is difference between animal and human life. What we believe is that, God created ONLY humans in His image. We don't believe monkey or cow or pig is in image of God. Only humans are. So only distinction in life form is human life and non-human life.

Some even ask, what if human meat is sold in shops like beef or mutton. But the same vegetarians who consume milk will never answer if human milk is farmed and sold in market like cow's milk. Will they drink?

I really don't support killing endangered species and fishing/hunting till it leads to depletion of animal/fish population. But like eating crops from fields and berries from wild in a sustainable manner, people can consume meat from farms and wild in sustainable manner. (more on "meat is sustainable" later)

If you just cut the grass in front of your house no problem. But if you cut a tree that is of rare species, then it is morally wrong. Like wise if you kill a rabbit you grow for food, it is not immoral. But if you kill a panda, then there is a problem. Hope people can see the difference here.

Tuesday, February 15, 2011

An Open Letter to Christian Youths

Disclaimer:

This article is not against any particular religion. It is not even against non-believers in Christianity. The aim of this article is to provide Christians youths some suggestions about choosing their spouse. This is applicable for both love and arranged marriages. I try my best to put together points I feel, Biblically correct. If you find any mistake with my views, please let me know. I will try my best to revisit it and correct it.(Non-believers please don't argue about Christian faith here, this is only towards Christian youths).

Introduction:

In recent years, I see many Christians marrying people of other faiths. This may sound a healthy trend for those who speak false-secularism. But this is a very dangerous trend for both Christians, Christianity and even in some cases, people of other faith too. This type of marriages often happen in the context of "love" marriage. But that doesn't rule out the possibility of same happening in arranged marriages too.

How This Happens?

Most of the inter-religious marriages happen in the context of love marriages. People fall in love with whatever they want now-a-days. From movie stars to politicians, this "love" is available very cheaply. But when it comes to the love between man and women, it is a life-time commitment, or at least, that is how Bible defines it. So Christians should be very careful while choosing their boy/girl friend. Bible warns that a believer should not marry an unbeliever. But most of the youths are carried away by the materialistic concerns and forget about Bible not only in this issue but in almost everything. So they freely "fall in love" with people of other/no faith and marry them even forsaking their religion.

In some other cases, people who stick to the caste system even after conversion to Christianity are ready to give their children in marriage to someone of same caste but an unbeliever. They are not ready to give their children in marriage to a good Christian who is not of their caste. Basically a Christian can not have caste (I lost my caste when I converted). But some people are going to the extant of sacrificing religious affiliation for their stupid caste system.

How it Impacts Christianity?

Most of the cases where a Christian boy marries a non-Christian girl, the girl is asked to convert to Christianity. This may sound good for people who count heads in Church. But this is a very unhealthy trend. These girls are not converting to Christianity for faith in Christ. They just convert for "love" of a Christian. This is not what Bible teaches. We must evangelize people of other faith. Not by these type of dirty means. Let us preach, let us reason, let us have healthy dialogue and let us try in all good means to reach people of other faiths. But let us not ask a girl to convert to our faith for sake or marrying a Christian. Moreover, the children born will be raised in a much lenient manner (as the mother may still have some concerns for her former faith as the conversion is only for society and not a conversion of heart).

On the other hand, when a Christian girl marries a non-Christian boy, most of the time, the girl is forced to leave her religion behind. Moreover, the children (in most cases) will be raised as non-Christians. This is very dangerous. Decision of one girl leads her entire generation in to hell. In some rare cases, the non-Christian men may convert to Christianity or allow the children to be brought up as Christians. Again, the conversion is only for name-sake and the children will not be brought up with strict religious conventions.

How it Impacts Christians?

The Christian parents in most cases feel bad about their children's decision to marry a non-Christian. Some parents may accept happily (though they may accept for the temporary happiness of their children, they must consider their fate in eternity i.e. in after life). I have seen many families broken in to pieces due to these type of marriages.

Even if they ask the other party to convert to Christianity, it spoils the name of our faith and may lead to clashes between people of different faiths. Christians should be makers of peace. Not initiators of riots. So Christians should avoid asking others to convert for marrying their children.

In some cases, the non-believer brings in the practices of their religion in Christian households. This also affects the Christian life. Think about a Christian seeking horoscope for his baby's birth! It is exactly the same which destroyed Israel in the Old Testament. Christians should not learn from other religions (especially falsehoods in other religions).

How it Impacts People of Other Faiths?

When Christians marry a non-Christian and convert them to Christianity (and when the conversion is purely for marrying the Christian), then the non-Christian spouse may feel dominated by the Christian. This is not what Christianity teaches. We should not dominate people of other faith. The competition should be balanced and healthy not by domination and oppression of others.

The non-Christian spouse has to live a fake-life just to please their Christian life-partner. They may have to hide their desires to practice their religion. Sometimes, Christian relatives of one side may attack the faith of the unbeliever which may result in broken marriages, quarrels, lack of understanding etc.

In Case of Arranged Marriages

When Christian parents seek a bride/groom for their children, they should do it Biblically. That is they should throw away things like caste, status, race etc. They should only seek for the devotion, truthfulness, kindness and other Christian virtues. Instead of selecting a rich liberal for few more grams of gold, if they choose a God-fearing person, by that they bring blessing for the entire family.

Christians should not care more about physical beauty, jewels, money, property etc. They should concentrate on culture, family values, ethics and other things that really matters in long run.

My Advice to My Brothers and Sisters

Dear Brother/Sister in Christ,

If you happen to like a person who is unbeliever, there is nothing wrong in it. But keep on guard that the affection doesn't cross to the point of love. Because, it won't workout well for a true Christian to be married successfully to a non-believer. A Christian can even give his/her own life for a non-believer. But that should be out of pure affection for the person and done as Christ done to us. Not for the reason to marry them.

If an unbeliever proposes you, reject it strongly with a "Sorry". Don't go for it hoping to convert them to our faith. God never wanted any deceit conversions. God hates cheating. So don't cheat a person who loves you. Instead, say them the practical difficulties and explain them that you can't forsake the immeasurable love of Christ for a worldly love.

If your parents arrange for a marriage with a person who is not a Christian, protest against it in all peaceful ways. If things go out of your hand, consult your pastor/priest. Even if that fails, seek legal help from forums like human rights commission. Also strictly say your parents not to consider caste while selecting your life-partner. If you are boy, strictly say no to dowry. If you are a girl, don't even consider a man asking money is worth living a God-fearing life. Moreover don't stress on things that are physical instead think about things that prove good in long run.

At last, I know there will be few people who still consider their love more worthy than Jesus' blood and the religion established on His very own sacrifice. My advice is, if you consider something more than Jesus, that moment itself you have become an unbeliever. So why hesitate, convert to some other faith and proceed with what you want. We need a lean and healthy Church (a Church without Christians for name's sake). We don't need a crowded Chruch of people who can compromise our faith for their own needs.

Conclusion:

As I have stated above, this article is not against any religion or people. I feel this may help Christians to live a more peaceful and cooperative life in family as well as in society. This is just to avoid unnecessary clashes between different belief systems. And the most valuable advice I give now is, PRAY!!! PRAY!!! PRAY!!! Read your Bible daily. Attend Church regularly. Build a good community life with Christians around you. Love is not sinful unless you don't reverse priorities. So when you choose a person (who should be a good Christian), ask God to guide you in your decision. Don't delay to share your desire with your parents. Let them know as soon as possible. If some other worthless things like caste/money comes in your way, you always have the option of dialogue to sort it out. God is on your side.

So in one line "Don't ask God for a right person. Ask Him for a right kind of person". Let us pray: "Lord, we humans are no match to you in loving others. You came as a man and gave up Your life for us, sinners. Your love is greater than Heaven. But when we love, let us not stumble. Let us not make mistakes. Show us the right type of person to love. A love that stands firm against all odds and lasts for a lifetime. In the name of Jesus. Amen!"