Welcome

My name is Jason and I am a software developer in the Bay Area. For fun I like to hike, run, shoot some photos, and take advantage of the many other activities California state has to offer. To the right you will see my resume.

Recent Books
  • Head First Design Patterns
    Head First Design Patterns
    by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra, Elisabeth Robson
Sunday
Oct232011

Redirection of the output streams in DOS scripts

Just like most programming languages, DOS batch files provides you access to 2 types of output streams. The standard out (STDOUT) and standard error (STDERR). STDOUT is where most of your output is directed to. Whereas all error messages should be directed to the STDERR. 

So, before getting into explaining how to use these different streams, you should probably know how DOS presents them. When doing redirection batch files use the number 1 to represent STDOUT and the number 2 to represent STDERR. By default, redirection is capturing the STDOUT stream. So the following statements both capture the STDOUT. 

C:\>dir *.* > output.txt
C:\>dir *.* 1> output.txt

Now, if you're not familiar with the STDERR stream, the following displays how programs output to this stream and not the STDOUT.

C:\>dir NonExistentFile.txt > output.txt
File not found.

See how even though you captured the output, the text “File Not Found” was displayed? This is because it's coming from the STDERR stream and not the STDOUT. If you were to open the output.txt file you see that it's empty since nothing was sent to the STDOUT stream. Now if you wanted to capture the error stream, you could do something like the following examples.

C:\>dir /b NonExistentFile.txt 2> error.txt
C:\>dir /b NonExistentFile.txt 2> error.txt > output.txt

For both examples the error.txt file will contain the text “File Not Found”. The second examples is just illustrating that you can capture both streams to separate files in the same command. This can be useful if you want to capture all the errors to one file and all the other text to another file. But if you want to capture all output to just 1 file, you could do something like this.

C:\>dir /b * > allOutput 2>&1
C:\>dir /b NonExistentFile.txt > allOutput.txt 2>&1

In the first example, all the files and directories found in the C:\ will be listed in allOutput.txt. Whereas the second capture the error message “File Not Found” into allOutput.txt. What's happening here is that 2>&1 is telling the script to direct STDERR stream into STDOUT. This way you're redirecting all output into 1 file. This is very useful for recording information for debugging. You could direct the STDOUT to STDERR similarly by using 1>&2, but this is uncommon.

So far we've only shown examples of where we redirect STDOUT and STDERR to a file. What if we don't want to record the output to a file and would just rather redirect it into an oblivion? Well DOS reserves some file names for special uses. Among them is NUL which represents a null file. Linux scripters will recognize this as /dev/null. When you write to this file the content just disappears into the ether and is never to be seen again. I find this useful testing conditions and don't care about the output. Below are a couple of examples.

if exist logFile.txt del /f /s logFile.txt > NUL

where powershell.exe > NUL 2>&1
if ERRORLEVEL 1 (
   echo ERROR: PowerShell is not installed; stopping.
   goto :eof
)

In the first line I'm redirecting the message “Deleted file – logFile.txt” to NUL since this information has no importance to me. In the following section I don't care about any of the output text from the WHERE command is, I'm just interested in the error code it returns. So I redirect all output to NUL.

Hope you now have a better understanding of how the STDOUT and STDERR streams work in DOS and how they can give you a new level of control over your scripts. If you have any tips or tricks related to these, please post them in the comments below! It would be great to learn what other people are doing with them.

Sunday
Oct092011

Creating a custom docking station with USB

When most of us first got into computers, they were big, heavy, and expensive. We only knew of a few people that had laptops of which most of them were work provided. That was usually the only way a normal household had one. But with time technology has become smaller and cheaper. It's now common place to walk into any coffee shop and see someone browsing the web or blogging on their laptop. And having more than one isn't too out of the ordinary. 

Along with these technological advances came along things like having multiple displays. Being a coder I don't think I can go back to the days of having just one monitor. Having a web browser open to sites like MSDN, Stack Overflow, or some other random forum that Google\Bing directed me to while coding in the other display is no longer just a convenience, but something I can't imagine doing on just a single display.

And in there lies the problem. Everyone today wants portability and therefore purchase laptops. But doing your work on just a laptop with it's single display, often cramped keyboard, and touch pad that you keep hitting instead of the space bar, is understandable when you're on the go, but painful when you're sitting at your desk at home or work. There are docking stations you can purchase for some laptops, but these tend to be expensive and specific to your model and\or brand. When you upgrade your laptop, the station is no longer compatible and you have to buy another.

How I've solved this problem is by creating my own custom docking station. How did I do this? USB. I've got a 7 port USB hub that's connected to external drives, one that's for backups and another for storing large files that I don't need all the time. Having a 2nd monitor is handled by an external USB video card. If you're just using it to browse the web, code, or anything else that doesn't require major video processing power, it works great! And of course I also have a full size ergonomic keyboard and wireless mouse transceiver connected to it.

One of the best parts about doing this is that you're only hardware dependence is on USB. I use the same docking station for my Mac as I do for my work PC laptop. And when I upgrade my computers, there's no new band\model specific hardware I have to pick.

Below is a list of the hardware I used to create my custom docking station. 

 One thing I couldn't get away without purchasing specific to the brand\model of my laptops were extra power supplies that I keep hooked up at my desk for convenience. I could just use the ones that come with the laptops, but I usually keep them in my go bag so they're with me at all times. Plus I don't have to crawl under my desk each time I want to plug them in.

Also, if you're looking for a laptop stand, you may want to check out this IKEA shelve. I first read about it on IKEA Hackers and now use one myself at home and work. For $5.99, it's sure of a lot cheaper than even some of the lowest costing laptop stands.

I hope this helps give you some ideas on how to handle your need for portability and workstation configuration in your office. Do you have any tips or tricks you'd like to share? If so, please comment. I'd love to hear how others handle their setup.

Saturday
Sep172011

Handy Hack: Minimize A Running Batch File Window

Every some often we all come across a problem that there's no real good way to solve. In which case we have to come up with a workaround. They're not always pretty. Sometimes we're surprised they even work at all. We don't even try to gussy them up because putting lipstick on a Frankenstein doesn't make them any less scary. We just call them what they are.

They're hacks.

One reason I started this blog was to post useful things that I came across whether it be hacks, an algorithm, or just some advice. I want this to be the place that has the information I couldn't easily find or has a more in depth explanation on how something works. And with saying that, I'm going to start posting more short entries starting with this one.

Like most random useful tricks and hacks, I figured this out while investigating a completely different problem. I've never found an automated way to minimize, or maximize, a running DOS batch file window. I know I've seen other people searching for methods of doing this as well because I've seen their posts on various forums while searching myself. So to my surprise I ran across this while debugging a PowerShell issue my team was having.

Yes. This does require PowerShell to be installed on your machine. This is a hack. They're not always elegant and they often rely on the behavior of something outside of what you would've expected or wanted to rely on. But to the best of my knowledge PowerShell is installed as part of Vista and up. So it's not reaching too out of the norm to pull this off.

If you look at the options for PowerShell you'll see that there's a -WindowStyle flag. The choices for it are Normal, Minimized, Maximized, and Hidden. Using this flag when you start PowerShell will place the window in the selected state.

“Ok,” you may be saying to yourself, “That's great, but now my batch file is blocked until I quit PowerShell.” And this is true. But PowerShell also has the -Command flag which allows you to run a command and then exit when finished. Why not use this flag to execute the “exit” command so PowerShell quits immediately?

Folks, we have ourselves a hack. Now shake your head in disbelief that someone suggested it, give a sigh of defeat for lack of a better solution, and then copy and paste it into your script.

Below are examples of how to do this which can be ran from a DOS prompt. I'm also using -NoLogo just because it makes things cleaner and -NoProfile to speed up the loading of PowerShell. The ordering doesn't matter exception for -Command which must be the last flag. There's also the -NonInteractive flag. I haven't played with this too much and since PowerShell is only running briefly, it's probably not needed, but doesn't hurt either.

To minimize the window:

C:\>PowerShell.exe -NoLogo -NoProfile -WindowStyle Minimize -Command exit

To maximize the window:

C:\>PowerShell.exe -NoLogo -NoProfile -WindowStyle Maximize -Command exit

To return the window to normal (its default size):

C:\>PowerShell.exe -NoLogo -NoProfile -WindowStyle Normal -Command exit

This next one you have be careful with. It will hide your window, remove it from the Applications tab in Task Manager (it does still shows up under the Processes tab), and at least on Windows 7, no longer show up on the task bar. I haven't played with this enough to figure how to make it visible again. You have been warned.

To hide the window:

C:\>PowerShell.exe -NoLogo -NoProfile -WindowStyle Hidden -Command exit

Now these are shown using the command line, but you can just drop them into a batch file to get the same effect. I added the minimize command to an existing script that's launched by Task Scheduler as me. This way I no longer have a black box jumping out of nowhere, breaking my concentration, causing alarm while I determine what's happening, and then realize it's just copying files so I minimize it.

It's the little things that make life grand.

Happy scripting!

Saturday
Jun052010

The Laptop ‘Go’ Bag

The idea behind any kind of ‘Go’ bag is that it’s something that you can just grab on your way out the door and it has everything you need. Whether it’s a carryall for weekend traveling, a tote for beach day fun, or a duffel for Armageddon, you know your bag has been prepare for whatever your needs may be.

In this post I’ll be discussing things I have in my laptop ‘Go’ bag and why.

Now I’m not going to go deep into everything that I bring up, but I do have to talk a bit about the bag. Obviously it’s all personal preference. I’m a backpack fan myself. I’ve been using a North Face Surge pack for a number of years now and love it. It has plenty of room for all my things and then some for whatever books\magazines I’m currently reading, my lunch, and a spare set of shoes in case I need to swap out my sandals due to a change of weather. When packed I can still fit it under the seat in front of me during flights and gain access to most of it’s pouches while stoled. But, pick a bag that works best for you and your needs. Just keep in mind all things you’ll want to carry in it, the places you’ll take it, and how comfortable it’ll be during travel.

Ok, let's get started listing out things to place in the bag!

Legal pad of paper – I’m a jotter. I’m always scribbling down notes and having a legal pad handy is a must! The Ampad Evidence Dual Pad is nice since it has a think backing making it pretty stiff and easy to use anywhere.

Patch cable – Although it’s a wireless world, sometimes it’s just easier and quicker to just patch in.

Power adapter – If you’re on the go, you’ll need a to be able to charge your laptop. Buying a spare power adapter can be expensive, but you’ll never regret doing it.

Spare thumb drive – Make sure it’s big enough to transfer a gigabyte or so, but cheap enough that it won’t bother you if you lose it or gave it away.

Travel USB hub – You can usually find a compact, unpowered one for pretty cheap.  I carry this Belkin hub that was in a discount bin at Fry’s. Great to have if you only have a couple USB ports on your computer.

Travel sized extension cord – You never know if you’re out at a coffee shop and the person next to you grabbed the only open socket. If you can split it with them then they won’t mind a bit. And many now have USB ports in them that can be handy for other electronics. I carry a Philips SPP2110.

Blank CDs\DVDs – Handy for buring music CDs for the car ride or just a way to hand off some data to someone.

Bootable CDs\DVDs – I tend to be the guy that gets a lot of calls from family and friends to look at their computer issues. Having a Ubuntu, Clonezilla, GParted, and Duke’s Boot’n Nuke bootable discs handy has been a life saver on many occasions.

Head phones – The majority of people like listening to their music, so having a nice pair of headphone handy is always a plus. I recently received a pair of the Sony Noise Cancelling Headphones MDR-NC33 and can’t imagine flying without them now.

Various USB cords – Sadly all my USB devices don’t have the same connection.  Make sure you carry the different types for what you need.

Umbrella – I live in Seattle. Do I have to explain this one? J

Bluetooth mouse – I use a Microsoft Bluetooth Notebook Mouse 5000. Sometimes using a mouse is easier than using the track pad. And since I have a Mac, I prefer having the 2 mouse buttons which the track pad lacks.

Pens\Pencils – Always useful to keep some on hand.

Small pad of paper – Another thing useful for quick notes without having to deal with a full size legal pad.

Video adapters – I usually keep a VGA, a DVI, and an S-video adapter on me. Those cover the majority of the bases.

Aspirin\Floss\eye drops\chap stick – Random medical items that may come in handy. Your wetware needs attention occasionally too.

Car cigarette lighter to USB adapter – This can be handy for charging your USB devices on the go. You can find them for pretty cheap as well.

Business\calling cards – Quick way to pass on your information for future contact.

Audio Y adapter – A way to share the audio of your laptop\MP3 player with someone else. Can be handy when on long flights and sharing the movie on your laptop with your neighbor.

Leatherman – I actually had Leather Squirt in my pack… and then I was stopped by airport security. They were cool about it and let me send it home, but I figured it would be best to leave this out in case I don’t have such nice security people next time.

Nail clippers – This may also be a problem with airport security, but I’d probably just throw it out if questioned about it since they’re so cheap. Hang nails just irritate the heck out of me and would be worth throwing into the bag.

Battery charger – Things like you’re wireless mouse and noise cancelling headphone probably take batteries. It’s probably ideal to have someway to charge them again.

Hopefully this will give you some ideas as to what to place in your ‘go’ bag. Everyone has their own ideas, but it’s best to check out what others have done and why so you can learn from their mistakes and avoid expensive trips to RadioShack while on vacation. Lifehacker also has a great post on this you should check out.

Did I miss anything? What do you have in your laptop go bag?

Tuesday
Apr132010

Interview question: Binary search in a sorted array

One of the questions that will usually come during an interview is related to Big O notation. This is a way for them to see how well you understand the efficiency or resource consideration of a particular algorithm. More importantly, they may be looking to see if you know how to implement a method using different variations of Big O. In this post I’ll show you 2 ways that you can implement a binary search on a sorted array.

Usually the question is presented to you like this; you’re given a sorted array of integers, what’s the best way to find if an integer is within the array? Simply starting from one end and moving towards the other incrementally is O(n). This would be fine except the hint that the array was sorted. Being sorted indicates that you use the divide and conquer method of binary search.

Now you have to decide whether to implement it by recursion or by iteration. Both have their advantages and disadvantages (which you should discuss with the interviewer). Personally, being taught C++ as my first real programming language (sorry BASIC!), I try to avoid recursion when possible. I know that in managed languages like Java and C# stack overflows are not as much of a worry as they are with native languages, but I generally feel that loops are a much safer way of programming. Other things to keep in mind when deciding which method to use are readability and maintenance. I’m sure you can write hotshot code for either one, but will you be able to easily understand what you wrote a year from now when you’re debugging a problem involving your chosen method? Or when someone else takes over your code because you’ve moved onto another project\team? Keep these in mind when deciding upon a method.

With either method the core logic is going to be the same for this task. First we will want to find the lowest and highest array indices. These will be used to determine the initial search location. If the location is not the value we’re searching for, we adjust the minimum or maximum index allowing for the first division of the data. The code will look something like this.

// Checking if the location is valueToFind
currentPos = (maxPos + minPos) / 2;
if (sortedArray[currentPos] == valueToFind)
   return true;

// Calculating a new minPos or maxPos values
if (sortedArray[currentPos] < valueToFind)
   minPos = currentPos + 1;
else
   maxPos = currentPos - 1;

If we’re using iteration we’ll want to keep looping through the core logic while the minimum index is less than or equal to that of the maximum or the value is found.

// Searching for valueToFind in sortedArray
while (minPos <= maxPos) {

   // Checking if the location is valueToFind
   currentPos = (maxPos + minPos) / 2;
   if (sortedArray[currentPos] == valueToFind)
      return true;

   // Calculating a new minPos or maxPos values
   if (sortedArray[currentPos] < valueToFind)
      minPos = currentPos + 1;
   else
      maxPos = currentPos - 1;
}
        
// valueToFind is not in the array
return false;

Similarly with the recursion, the method will continue calling itself until either the value is found or the maximum index is less than that of the minimum.

// Check if the location is valueToFind
int currentPos = (minPos + maxPos) / 2;
if (sortedArray[currentPos] == valueToFind)
   return true;

// Calculating a new value for minPos or maxPos
if (sortedArray[currentPos] < valueToFind)
   minPos = currentPos + 1;
else
   maxPos = currentPos - 1;

// If the new maxPos is less than minPos, we know valueToFind is not in the array
if (maxPos < minPos)
   return false;

// Trying new location since valueToFind was not in the current one
boolean findResult = RecursionMethod(valueToFind, sortedArray, minPos, maxPos);
return findResult;

All right, let’s talk test cases. We should come up with some scenarios that verify the logic in-depth. We’ll want to search for values that are less\greater than the lowest\highest value in the array, search for values not in the array but would fall between values that do exist, and interesting array sizes. Interesting array sizes would include a null array, a single element because the minPos and maxPos values are the same, and an array with 5 elements because it‘s the simplest tree with an odd number of elements that require both the minPos and maxPos to change to find at least 1 value, and finally 6 elements because it’s the simplest tree with an even number of leafs that require both minPos and maxPos to change to find at least 1 value in the array.

And there you have it! A binary search algorithm on a sorted array with interesting test cases. Understand this and when it comes up in an interview you’ll breeze through it.

You can view the full source code here.