Solving an interesting TimeZone Problem#

Let’s say you have a customer base spreaded across several time zones i.e. from Hawaii to Alaska, all the way across mainland US and even some remote parts of Europe. You want a service to deliver a particular message at certain time via email, in that time zone. How would you do that?

 

This problem recently came up and was discussed with some colleagues. I found it to be pretty challenging; even though it sounds simple, it gets a bit tricky if you’d want to find out things like

 

  • At what time in your local timezone the message should be sent out so it will reach the target timezone at the given local time (at target timezone say 8:00 AM)
  • Relative to your current timezone, when did the target time for message delivery occurred in the destination timezone locale?

etc etc.

 

Therefore, I started experimenting with the following data

 

96811    P        Honolulu D        Honolulu 15003    HI       15       3320     808      Hawaii   -10

99850    P        Juneau   D        Juneau   02110    AK       02       0000     907      Alaska   -9

97840    S        Oxbow    D        Baker    41001    OR       41       0000     541      Pacific  -8

59821    S        Arlee    D        Lake     30047    MT       30       0000     406      Mountain -7

78028    S        Kerrville        DKerr    48265    TX       48       0000     830      Central  -6

48852    P        McBrides D        Montcalm 26117    MI       26       0000     989      Eastern  -5

00627    S        VISTA Verde      NCamuy   72027    PR       72       0470     787      Atlantic -4

 

A simple no brainer equation for time calculation in a particular locale is

 

LocalTime = GMT + Offset

 

where offset is the value by which a local time differs from UTC or coordinated universal time.

 

Hence, it can be said that

PacificTime = GMT + (-8)

HawaiianTime = GMT + (-10)

 

Equating both equations we get

 

PacificTime + 8 = HawaiianTime + 10

And hence

 

PacificTime = HawaiinTime + 10 – 8

 

Considering Pacific time as local timezone and Hawaiian timezone as the target one, this can be generalized as

 

LocalTimeZone = TargetTimeZone + TargetGMTOffset – LocalGMTOffset

 

I did a C# implemention of this idea which, AFAIK, provides pretty accurate results.  Like for the following PR zip 00627.

 

Local Time is 12/31/2005 12:46:31 AM Which is UTC-8
Universal Time (GMT) is 12/31/2005 8:46:31 AM
Target time is 12/31/2005 8:00:00 AM
Time in zipcode 00627 is 12/31/2005 4:46:31 AM which is UTC-4
Required Time 12/31/2005 8:00:00 AM in zipcode 00627 is in 3.00 Hrs 13.00 Mins.
Time difference between Local and Remote Zone is -4
According to local time, alert has to occur at 12/31/2005 4:00:00 AM to be seenin target locale at 12/31/2005 8:00:00 AM

 

And hence comes the following code:

class TimeZoneCalibrator
{
public static string[] strzipcode = {"96811", "99850", "97840", "59821", "78028", "48852", "00627", "IG119XW"};
public static int[] offset = {-10, -9, -8, -7, -6, -5, -4, 0};

/// <summary>
///
The driver - traverse through different time zones including GMT
/// </summary>

[STAThread]
 static void Main(string[] args)

{
DateTime RequiredRemoteTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 8, 0, 0, 0);
for (int cnt=0; cnt<strzipcode.Length; cnt++)
CalibrateTime (RequiredRemoteTime, strzipcode[cnt]);
Console.ReadLine ();
}


//Returns the local time in that time zone
public static DateTime CalibrateTime (DateTime RequiredRemoteTime, string zipcode)
{
int strIndex=0;
int strNumber = 0;
for (strNumber = 0; strNumber < strzipcode.Length; strNumber++)
{
strIndex = strzipcode[strNumber].IndexOf(zipcode);
if (strIndex >= 0)
break;
}
DateTime localDateTime = DateTime.Now;
System.DateTime univDateTime = localDateTime.ToUniversalTime();
double GMTDifferenceTimeSpan = localDateTime.Subtract(univDateTime).TotalHours;
//Find out the remote time
DateTime RemoteDateTime = univDateTime.AddHours (offset[strNumber]);
TimeSpan TimeDifference = RequiredRemoteTime.Subtract (RemoteDateTime);
//Localtime relative
DateTime LocalTimeAnticipated = RequiredRemoteTime;
int LocalRemoteTimeDiff = (int)(TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).TotalHours - offset[strNumber]);
LocalTimeAnticipated = LocalTimeAnticipated.AddHours (LocalRemoteTimeDiff);
Console.WriteLine ("Local Time is " + localDateTime.ToString () + " Which is UTC" + TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).TotalHours);
Console.WriteLine ("Universal Time (GMT) is " + univDateTime.ToString ());
Console.WriteLine ("Target time is " + RequiredRemoteTime.ToString ());
Console.WriteLine ("Time in zipcode " + zipcode + " is " + RemoteDateTime.ToString ()+ " which is UTC" + offset[strNumber]);
//Just for fancy printing.
if (TimeDifference.TotalHours < 0)
Console.WriteLine ("Required Time " + RequiredRemoteTime + " in zipcode " + zipcode + " was "
+ Math.Abs (TimeDifference.Hours).ToString ("N") +" Hrs " + Math.Abs (TimeDifference.Minutes).ToString ("N")+" Mins ago.");
else
Console.WriteLine ("Required Time " + RequiredRemoteTime + " in zipcode " + zipcode + " is in "
+ Math.Abs (TimeDifference.Hours).ToString ("N") +" Hrs " + Math.Abs (TimeDifference.Minutes).ToString ("N") +" Mins.");
Console.WriteLine ("Time difference between Local and Remote Zone is " + LocalRemoteTimeDiff);
//According to local time, it would occur at
Console.WriteLine ("According to local time, alert has to occur at " + LocalTimeAnticipated.ToString () +" to be seen in target locale at " + RequiredRemoteTime.ToString ());
Console.WriteLine ("--------------------------------------------------------------");
return LocalTimeAnticipated;
}

DateTime Structure


12/31/2005 12:57:28 AM (Pacific Standard Time, UTC-08:00) #    Comments [0]  |  Trackback

 

K iteration steps simulation in Ruby#

Adi Oltean reported an interesting problem in his blog.

Say that you have an array of N boolean values, with all values initially set to FALSE. At each iteration step, you arbitrary pick an element in the array and set it to TRUE. What is the average number of elements set to TRUE after K iteration steps?

Soon there were solutions posted by Nicholas Allen and ReuvenLax in the comments  section. The nerd who actually wrote a simulation of this was Neal Hardesty! Following is his code.

# Usage: ruby testrand.rb <loops> <N sized array> <K rand elements>

loops=ARGV[0].to_i
n=ARGV[1].to_i
k=ARGV[2].to_i
runningTotal = 0

loops.times { |iLoop|
        a = []
        n.times { a[ (rand * 1000).to_i ] = 1 }
        total = 0
        k.times { |iK| total += 1 if a[iK]}
        runningTotal += total
}

puts "avg for #{n} sized array, #{k} rands, #{loops} iterations: " + (runningTotal / loops).to_s

and don't forget to try ruby! (in your browser)


12/31/2005 12:16:11 AM (Pacific Standard Time, UTC-08:00) #    Comments [0]  |  Trackback

 

Patterns & Practices Live#

livev2.jpg

From PNPLive website

"Let's face it, some webcasts are just plain boring while others are nothing but fluff.  There's one thing you can say for sure about our webcasts - they're both live and lively.  We record them at Microsoft Studios and have a great time doing it.  Join in the fun and register for a webcast today!"

Read More

 


12/28/2005 8:32:56 AM (Pacific Standard Time, UTC-08:00) #    Comments [0]  |  Trackback

 

Playing Piano with SOAP Messages#

I just finished seeing Don Box and Chris Anderson's MSDN TV Special Holiday Episode III - Connecting People, Programs and Devices Using WinFX which gave the term CGI Joe completely new meanings. Their Holiday song which was sung with notes produced by XBOX Controller sending SOAP Messages to piano is as follows.

code they told me
pa-rum-pu-pum-pum

a new platform to use
pa-rum-pu-pum-pum

the finest apps we'll bring
pa-rum-pu-pum-pum rum-pu-pum-pum rum-pu-pum-pum

simple code                    (code they told me)
can it be                          (pa-rum-pu-pum-pum)
(the) xaml life                  (a new platform to use)
is all I see                        (pa-rum-pu-pum-pum)

see the day of glory        (the finest apps we'll bring, pa-rum-pu-pum-pum)
see the day when            (code they told me) 
programs connect via soap          
via x-m-l                        (pa-rum-pu-pum-pum rum-pu-pum-pum)

simple code                   (a new platform to use, pa rum pum pum pum)
--- can it be                   (when we code)

every app must be made aware
every app must be made to care
'bout the network and service bus
to bring the programs to us

I pray my wish               (code they told me)
will come true                (pa-rum-pu-pum-pum)
for my code                   (a new platform to use)
and your code too         (pa-rum-pu-pum-pum)

see the day of glory        (the finest apps we'll bring, pa-rum-pu-pum-pum)
see the day when            (code they told me) 
programs connect via soap          
via x-m-l                        (pa-rum-pu-pum-pum rum-pu-pum-pum)

simple code                   (a new platform to use, pa rum pum pum pum)
--- can it be                   (when we code)

--- can it be


12/26/2005 2:50:23 PM (Pacific Standard Time, UTC-08:00) #    Comments [0]  |  Trackback

 

Software People - Why Good Developers are so important.#

While reading David West’s Object Thinking, I came across some valuable quotes elaborating on “People’s Issue” from Robert Glass’s “Facts and Fallacies of software Engineering”.

 

  • The most important factor in software work is not the tools and the techniques used by the programmers, but the quality of the programmers themselves.
  • The best programmers are up to 28 times better than the worst programmers.  Since their pay is never commensurate, they are the best bargains in the software field.
  • Nearly everyone agrees, at a superficial level, that people trump tools, techniques, and process. And yet we keep behaving as if it were not true. Perhaps it's because people are a harder problem to address than tools, techniques, and process.
  • We in the software field, all of us technologists at heart, would prefer to invent new technologies to make our jobs easier. Even if we know, deep down inside, that the people issue is a more important one to work.

Facts and Fallacies of Software Engineering by Robert L. Glass

Review of "Object Thinking by David West"; Microsoft Press ...

Rockford Lhotka - What I got out of Object Thinking


12/25/2005 5:07:01 PM (Pacific Standard Time, UTC-08:00) #    Comments [0]  |  Trackback

 

Frequently asked Questions about my screens#

This post is definitely going under the narcissism category.

Normally when people enter AdnanoTopia (it's in reference to Dilbertopia, Dilbert's cube), their first question is usually, "why on earth do you need three monitors"?

AdnanOfficeCubicle.jpg

I casually reply that It's because I'm so cool. They'd insist on knowing it "No Seriously?, why? Ok fine, I'll disclose the secret.

  • My primary monitor is laptop's screen.
  • The CRT monitor is used for reading Sharpreader/Outlook/SQL Query Analyzer without losing the IDE focus and where I'm in code.
  • The vertically aligned LCD is for my MSDN lab machine. It has the virtual PC running all kinds of things. Yes, I do remote into it but at the same time it's much easier and faster to start ubuntu or Vista right from the original console.

Now for the cubicle's picture, hopefully this won't happen to me.

Does increasing available screen space increases productivity? Not necessarily but it helps multitasking a lot. I've got a similar setup and home as well. The gateway LCD TV  / Monitor; gives a false satisfaction perspective of doing too much.

AdnanDesk.jpg

Now if I can only plug-in an XBOX 360 to it...


12/25/2005 4:24:19 PM (Pacific Standard Time, UTC-08:00) #    Comments [2]  |  Trackback

 

Some interesting .NET interview "Answers"#

I recently came across some real amusing/humorous/sad (depending on your context) answers from a candidate; please don't try these in your interview as it's quite difficult for interviewer to bite the tongue and try not to laugh.

What is the difference between HTTP GET, POST and SOAP protocols?
Answer:When you visit a web page, it's GET. When you click the button to post data, its POST. If you stay on the page long enough, its SOAP.

What is the difference b/w Server.Transfer and Response.Redirect?
Answer: Server.Transfer is for moving forward to the next page and Response.Redirect is for moving back to the original page.

What is the difference between int and Integer (same question was repeated for string and String to id the understanding of value type/reference type/primitive types)?
Answer:  int can only have 32 bit int values while Integer can hold float, double and everything else too.

what is Globalization/Localization in Microsoft Framework perspective for building multi-cultural applications? 
Answer: If u declare a variable locally, it's localization. If you declare it globally, its globalization.

What is public key token attribute of an assembly?
Answer:It's the version of the assembly.

Ok, then what is version attribute of an assembly?
Answer:It's the REAL version of an assembly.

What is GAC and what problem does it solve. Compare and contrast it with System32 and DLL hell problem?
Answer: GAC..hmmm..I've read it somewhere...

 


12/25/2005 3:11:06 PM (Pacific Standard Time, UTC-08:00) #    Comments [3]  |  Trackback

 

BBC News Documentary @ Google video#

My BIL Ken Nign once said that everything which makes you smart is usually pretty expensive; it was in context of prices of documentaries, history channel tapes, Mythbuster DVD's and such. However, with Google video, things are getting better. A friend recently recommended this documentary which I found to be very interesting and thought provoking.


12/25/2005 2:46:38 PM (Pacific Standard Time, UTC-08:00) #    Comments [0]  |  Trackback

 

MIX - the next web now#
From Mix's site

"A 72-hour conversation, the Pitch.

As the web enters its second decade, the old barriers are blurring or breaking down completely. Media is transforming technology and technology is transforming media. Web “designers” are starting to write a little code, while Web “developers” are learning to twiddle pixels. AJAX is redefining the boundaries between client and server. RSS and web services give you the power to recreate the web the way you want it.

Everything is getting a little MIXed up. "

Click here to read more.

Register now



12/23/2005 11:44:48 PM (Pacific Standard Time, UTC-08:00) #    Comments [0]  |  Trackback

 

My issues with IE December 2005 Security Update#

I usually try to mimic the ideology of "If you’re not living on the edge, you’re taking up too much space" while our architects are mostly like "If there is no SP1 yet, no way it's going to production" so you can see the difference of opinion here.

Recently in order to follow the cutting edge philosophy, I used Windows update to download the December 2005 security updates and started having all kinds of issues. The fixes were for

  • File Download Dialog Box Manipulation Vulnerability - CAN-2005-2829
  • HTTPS Proxy Vulnerability - CAN-2005-2830
  • COM Object Instantiation Memory Corruption Vulnerability - CAN-2005-2831
  • Mismatched Document Object Model Objects Memory Corruption Vulnerability - CAN-2005-1790

But it ended up causing

  • Frequent IE hang ups
  • A zillion IE windows will open up and won't go away unless you close them via task manager.
  • Default browser change to firefox will cause IE to redirect all requests to open FF.

And as defined on google groups

  • Opening an Internet shortcut from Windows Explorer opens a blank IE window, which then hangs
  • typing a URL in the "Start -> Run" dialog box opens a blank IE window, which then hangs
  • Clicking the "More Information" link in the Windows Error Reporting dialog opens a blank IE window, which then hangs.
  • Typing a URL in the IE address bar opens that URL in a new window.
  • Opening an Internet shortcut from within IE either opens the link in a new window, or causes IE to hang.
  • Right-clicking on a link and choosing "Open in new window" results in two new windows, one with the link and one blank.

As well as in Microsoft IE Blog

  • Opening link from Outlook give blank page with popup-error and second page with correct info.
  • Typing URL in address bar opens at least one new, blank page (sometimes more) with popup-error and another new page which loads the URL requested.

So, what fixed it? In my case a registry key change since I was running IE 7 beta 1 side by side.

Richard All of the problems I was seeing were due to a registry key created by running IE7 Beta 1 in side-by-side mode. Deleting the registry key has resolved all of the issues.

IE December Security Update – addressing scattered reports of odd browser behavior

So did I learn the lesson? nah.... Life is good at the edge.


12/22/2005 6:57:09 PM (Pacific Standard Time, UTC-08:00) #    Comments [0]  |  Trackback

 

Hamachi Rocks!#
One of Neal Hardesty's Friend (NHF) gave a raving review about Hamachi when we were attending San Diego .NET developers group summit so I decided to try it out. NHF (sorry, I can't seem to remember your name, so you are NHF from now on) is using it for gaming but I found Hamachi to perform pretty well as VPN/TS/RDP mediator. If you have tried setting up terminal services and had firewall blues, give Hamachi a spin. It's probably the best firewall defiance money can buy (No, Hamachi is free...that was just an expression).

From their website

With Hamachi you can organize two or more computers with an Internet connection into their own virtual network for direct secure communication.
Hamachi is fast, secure and simple. It is also free.
  • Think - LAN over the Internet.
  • Think - Zero-configuration VPN.
  • Think - Secure peer-to-peer.
Access computers remotely. Use Windows File Sharing. Play LAN games. Run private Web or FTP servers. Communicate directly. Stay connected.

woo hoo. But if it turns out to be having an evil genius trying to sniff all your traffic or automated malware update, you only have yourself to blame.


12/20/2005 7:43:45 AM (Pacific Standard Time, UTC-08:00) #    Comments [0]  |  Trackback

 

We Prefer MSN – (Microsoft Anti-spyware beta 1 bug)#
Microsoft Anti Spyware beta is a cool product; however, as usual I found something to complain about. This is about a key-value change issue I encountered last night. To reproduce, do the following steps.

Tools ->Advanced tools ->SystemExplorers->IESettings

Select the start page and click on “Change URL/Page”

Type a new URL and press OK

   MSAntiSpywareBug.JPG

After this, it will even tell you that the URL is changed.

MSAntiSpywareBug2.JPG


But it actually is not! Not even in the display window. I wonder how well MadDog is doing. (Videos about Test Case Management System used at Microsoft (Maddog)


Microsoft Windows AntiSpyware (Beta) Home

PS. Just realized that I can't do Ctrl-K for adding a hyperlink in FreeText box in Firefox. oh bummer!

12/20/2005 7:34:03 AM (Pacific Standard Time, UTC-08:00) #    Comments [0]  |  Trackback

 

Game Theory and Modeling Consumer Behavior #

“Every game ever invented by mankind, is a way of making things hard for the fun of it!” –John Ciardi

 

After being free from exams, I started catching up on my readings and was browsing through November’s Forbes when I saw Allison Fass’s article on game theory in marketing section. This article discusses the simulation of consumer behavior via mathematical modeling to create a predictable model of marketing strategy. Interestingly enough, Lorry was watching deal or no deal at the same time, a game show premiered today based on the game theory; quite a coincidence eh?

 

Game Theory, like every other CS grad, was taught to me during Statistics and “Stochastic process & inference” courses. Interesting stuff but did I ever thought it would actually be useful in everyday development? Not really. It was most likely the lack of vision as I later found it to be a widely used technique in simulation and modeling in the “real world”, and SIM city of course. It’s even in Hollywood since Beautiful Mind highlighted the life of John Nash, who is the Nobel Prize-winning economist informing nation benefits of economic game theory.

 

Some quotes from David McAdams’s lectures.

 

  • “Game Theory, long an intellectual pastime, came into its own as a business tool.” Forbes, July 3, 1995, p. 62.
  • “As for the firms that want to get their hands on a sliver of the airwaves, their best bet is to go out first and hire themselves a good game theorist.” The Economist, July 23,1994 p. 70
  • “Game theory is hot. “The Wall Street Journal, 13 February 1995, p. A14 

The modeling company in the article is Decision Powers which has punch line slogans as

 

  • “Did you know he was going to choose that? We did”
  • “Did you expect this kind of response? We did”
  • “Did you know he was going to recommend that? We did”

 

They claim the model replicates the way consumers are making decisions. The agents are programmed to interact and act by rules with a %age of randomization, probability and intuition. In the article, techniques are said to be used effectively from vending machine placement to advertising niche shift.

 

Game Theory can be formally defined as

 

“The modeling of strategic interactions among agents, used in economic models where the numbers of interacting agents (firms, governments, etc.) is small enough that each has a perceptible influence on the others” [1]

 

And

 

“The Game Theory studies winning strategies for parties involved in situations where their interest conflict with each other. Developed by John von Neumann, the theory has applications to real games (cards, chess, etc.), economics, commerce, politics and some say even military.” [2]

 

For further details, industry usage and implementations, check out Wikipedia – Game Theory

MIT Open courseware provides a great course on 15.040 Game Theory for Managers, spring 2004; I’m planning to take it once I complete the Machine learning one.

 

ACM Papers on game theory

 

Everything you always wanted to know about game theory: but were afraid to ask

Daniel D. Garcia, David Ginat, Peter Henderson January 2003           ACM SIGCSE Bulletin , Proceedings of the 34th SIGCSE technical symposium on Computer science education SIGCSE '03,  Volume 35 Issue 1

Satisficing Equilibria: A Non-Classical Theory of Games and Decisions

W. C. Stirling, M. A. Goodrich, D. J. Packard

September 2002   Autonomous Agents and Multi-Agent Systems,  Volume 5 Issue 3

 

Game Theory and Decision Theory in Multi-Agent Systems

Simon Parsons, Michael Wooldridge

September 2002 Autonomous Agents and Multi-Agent Systems,  Volume 5 Issue 3

 

Incentives in practice: Experiences applying game theory to system design

Ratul Mahajan, Maya Rodrig, David Wetherall, John Zahorjan

September 2004  

Proceedings of the ACM SIGCOMM workshop on Practice and theory of incentives in networked systems

 

 

[1] www-personal.umich.edu/~alandear/glossary/g.html

[2] math-terms.org/g.html


12/19/2005 10:12:30 PM (Pacific Standard Time, UTC-08:00) #    Comments [0]  |  Trackback

 

Free ASP.NET 2.0 Learning Course Online#

Via Scott Guthrie's blog

"Microsoft Learning Online Course Available on ASP.NET 2.0 Brad from the Microsoft Learning team just pointed me at a cool offer.  Basically it allows you to take a 3-hour ASP.NET 2.0 Training course for free if you register for it before January 4th (note: you then have up to 90 days after you register to take it).

You can learn about the various ASP.NET 2.0 courses being offered here."

In other news NY Times ran this several days ago; nice to see investment in nonproprietary and freely licensed R&D.

Three Technology Companies Join to Finance Research


12/19/2005 12:39:04 AM (Pacific Standard Time, UTC-08:00) #    Comments [0]  |  Trackback

 

Yahoo Email Revamped#

Yahoo mail got a new look; not just a face lift but more like a major organ transplant!. Equipped with DHTML and AJAX providing an outlook style interface, looks and works really neat. Gmail, you're on.

What's New With Yahoo! Mail

Yahoo mail beta gets mostly rave reviews | News.blog | CNET News.com


12/19/2005 12:11:50 AM (Pacific Standard Time, UTC-08:00) #    Comments [0]  |  Trackback

 

Hippocratic Oath for Software Developers#

Dr. Phillip A. Laplante, Ph.D., associate professor of software engineering at the Penn State Great Valley School of Graduate Studies, expresses the need for software professionals to have a similar oath as doctors and nurses. Following is his recommendation.

"I solemnly pledge, first, to do no harm to the software entrusted to me; to not knowingly adopt any harmful practice, nor to adopt any practice or tool that I do not fully understand. With fervor, I promise to abstain from whatever is deleterious and mischievous. I will do all in my power to expand my skills and understanding, and will maintain and elevate the standard of my profession. With loyalty will I endeavor to aid the stakeholders, to hold in confidence all information that comes to my knowledge in the practice of my calling, and to devote myself to the welfare of the project committed to my care. "

He also talks about "What's wrong with taking our profession a little more seriously?" in his article; pretty interesting.

First, Do No Harm: A Hippocratic Oath for Software Developers

Computer Ethics at Cambridge

Professionalism in Computing

PS. I forgot to mention earlier that this posting was on request of a friend who was interested in knowing about existence of a Hippocratic Oath for Software Developers.


12/18/2005 7:21:05 AM (Pacific Standard Time, UTC-08:00) #    Comments [0]  |  Trackback

 

U-M develops scalable and mass- producible quantum computer chip #

via University of Michigan news service

ANN ARBOR, Mich.—Researchers at the University of Michigan have produced what is believed to be the first scalable quantum computer chip, which could mean big gains in the worldwide race to develop a quantum computer.

Read More