Wednesday, March 6, 2013

The Hong Kong guide to the Paris guide to IT infrastructure

There are many metaphors for enterprise architecture. The most common one I've heard is that enterprise architects are the glue between an organisation's strategy and execution. This reads well as a LinkedIn status update or tweet, but you could say the same about project managers responsible for executing strategic projects, or CFOs who pick strategic projects and ensure they're funded. Whenever someone asks for my view on the role of enterprise architects, I like to say I'm a student of the "Paris" school of enterprise architecture.

The Paris Guide to IT architecture was an article published in the McKinsey Quarterly in 2000. It talks about the history of Paris and how the city's architecture and buildings have a consistent feel and theme despite architects who've had over 200 years to "improve" it. The consistency of Paris is used as a metaphor for IT architecture: just as the roads and public transport of Paris unite the buildings, define the landscape and set the terms for evolution (Laartz, 2000), enterprise architecture involves the systems and frameworks that unite applications and provide a way of integrating and accommodating disparate systems in a coherent way. Although it doesn't say it, the article hints that enterprise architects are the town planners of IT. I've never visited Paris, but the concept resonates when I compare Hong Kong or Singapore to lesser planned cities in Asia.

The IFC check-in service in Hong Kong strikes me as an example of a system that exists because other systems have been architected well. The Hong Kong International Airport (HKIA) allows you to check-in to your flight and drop your bags in the city, leaving you with a boarding pass and the opportunity to spend your day shopping and exploring the city instead of waiting in an airport lounge surrounded by stereotypes. While you do your shopping, your bags are securely transported to the airport, saving you the stress of carrying them or having to stop at your hotel before the airport.

International Finance Center (IFC): the building Batman jumps from in The Dark Knight.



The architecture for IFC check-in relies on the availability and openness of other systems like
  • airline systems, to facilitate check-in at IFC.
  • airport systems, to provide airport services including security, timetabling, messaging, alerting.
  • the Airport Express rail system which provides mass transit from IFC (or any station) to HKIA
  • luggage transport systems that move traveller luggage securely from IFC to the airport and provide handoff to the airport luggage routing system
  • network systems, to facilitate secure and reliable communication with the airport
  • et cetera
The actual specifics behind system integration isn't enterprise architecture: that's application architecture. The fact the required functionality and systems were available was because of enterprise architecture. During the architecture of the baggage system, the application and infrastructure architects may have developed the best solution for accepting baggage from an on-premise airline check-in desk and delivering it to a plane. But was their solution service-oriented? Was it open? How flexible would the solution be if a new requirement for bag drop from off-premise sources (such as the IFC check-in) was introduced? Or if bag drop from hotels was introduced? Upfront completeness of requirements is important, but part of enterprise architecture is knowing when to keep the door open and how to do it.

A town planner might know that every premise requires lines for sewage, electricity, water, gas and telephone, but they still might keep the door open for future services by requiring ducting infrastructure from streets to the home. If a new technology came along to replace copper telephone lines, existing ducting infrastructure would make the job a heck of a lot easier. And like in the real world, if you don't think ahead, rectification could either be costly or impossible.

Sunday, December 16, 2012

Error code 0x80070017 when installing Windows 8 (it means your CD is bad!)

If you're burning a Windows 8 ISO with anything other than ImgBurn, chances are you're going to make a coaster. Symptoms of a coaster include error 0x80070017, which is technical gibberish for "Y'all DVD is broken". This might not seem right because hey, how hard is it to burn a DVD?!

None of these people used ImgBurn. 

The error message has the description:

Windows cannot install required files. The file may be corrupt or missing. Make sure all files required for installation are available, and restart the installation. Error code: 0x80070017.

I'm not saying you don't know how to burn a CD, only that some CD burning tools have a greater chance of making frisbees. If your'e using a Mac, don't use Apple MacOS X's Disk Utility: it burns unusable Windows 8 coasters 100% of the time. Swallow your pride and burn it on a Windows 7 PC.

The answer: burn your Windows ISO on a Windows 7 PC using ImgBurn. It's 100% free! In fact, if this blog post was useful to you and you're feeling charitable, please PayPal the ImgBurn author a dollar. Oh, and kudos to Microsoft for being charitable and giving free copies of Windows 8 to all RMIT students!

Thursday, November 29, 2012

My VMware VCAP5-DCA exam advice: lab it up!


I passed the VCAP5-DCA back in May when it was in beta. I forgot how many questions are on the VCAP5-DCA but come to think of it, it doesn't really matter. What matters is your ability to perform administrative tasks quickly, and how quickly you can use Ctrl+F to find out how to perform administrative tasks from the VMware (the official VMware documentation is provided). With this exam, there is no way you’ll know how to do every task on the exam (unless you’re some sort of VMware robot from Palo Alto sent to destroy our dignity by scoring 100%). The good news is, you don’t need to know how to do everything, because the official VMware PDFs are made available!

 
I passed the VCAP4-DCA and VCAP5-DCA. Check back next year for my VCAP6-DCA advice.

Rote memorisation will help you pass the VCP5, design acumen will help you pass the VCAP5-DCD, but only practice will get you through the VCAP5-DCA. My advice for the VCAP5-DCA exam is to practice until you get sick of it.
  
How do you know you’re ready?

If you've been living in fluffy architect land drawing on whiteboards, you’ll definitely need to study before taking the exam. If you've spent the last weeks setting up a new vSphere environment from scratch or troubleshooting, you’re ready to go.

Here’s an example task (I guarantee it’s not on any exam I did!): Add the Cisco Nexus 1000V VIB to a VMware install bundle. Can you do it? If so, congratulations: stop reading this blog post and book the exam before you accidentally watch television and forget the knowledge. If you’re not sure how to add a VIB, find the VMware documentation PDF that explains how to do it. Do you understand the steps? Could you do it in under 6-8 minutes? If so, you’re probably ready. If it takes you 10-15 minutes, do a bit more practice: time is limited you’ll only be able to refer to the documentation 3-4 times before you start running out.

Here are some suggestions to improve your administration skills.
  • Lab it up! Your lab doesn’t need to be representative of the exam lab, just the features you’re unfamiliar with. Unfamiliar with storage? One ESXi host and Openfiler will do! Unfamiliar with virtual distributed switches? Sounds like you’ll need at least two ESX hosts.
  • Watch the vBrownbags: if it has VCAP-DCA in the title, watch it!
  • Sit the VMware official training: the Install, Configure, Manage along with Fast Track will cover everything you need in the exam. I prefer classroom training because you get to make friends in your local VMware community and share experiences.
If you do the VMware courses, you'll get binders full of slides and exercises. BINDERS FULL.
To be honest, I'd rather have the videos from TrainSignal handy.
  • TrainSignal VMware vSphere 5 training: This is the cheaper alternative to the courses. If you have the will to self-study, this is good. If not, don’t bother. The relevant courses are VMware vSphere 5 Training and vSphere Advanced Networking Training. There’s over 24 hours of videos, but you should be able to study it all in a week. Skip over what you’re familiar with (you’re already a VCP: do you really need to watch a video on how to create a resource pool?) and cover your weak points.
  • Read the blueprint with the mindset of the test writer: while reading it, ask yourself “If I was writing the exam, how would I test if somebody knew this?” about each point. If you were writing an exam question to test someone's competence with resource pools, how would you test it? Perhaps you'd create a resource pool hierarchy and VM reservations such that a VM wouldn't be able to power on. Then you'd ask the student to make a single change to the hierarchy that would allow it to power on.
As with most technical training, you’ll start to forget knowledge as soon as you walk out of the training room and you'll lose the test mindset within a week. I suggest you book the exam no more than 3-5 days after finishing whatever study path you've set yourself. There's a lot of administrative tasks covered on the exam, and you won't have done them all before, but that's no reason for a professional like you (who has already achieved VCP5) to be scared.

Saturday, November 24, 2012

Chess in C (Part 3) - Rook, Rooks, Rookies, Wookies, same thing

Today's blog post will be short like the sentences of a language I'm learning. ¿Comprendes? I'm not learning Spanish, I've just wanted to use one of those upside down question marks. Twenty years I've been waiting to use those question marks.

I'll cover one chess piece, and one chess piece only! I'm assuming you've read Chess in C parts one and two. In part one, we covered the chess board and how to represent pieces. In part two, we covered how to model moves of pawns as well as a general approach to calculating whether a square is a potential destination for piece. Before we begin today, grab the code at the end of part two and compile it. We're going to make some modifications to this code, and I'm assuming you're ready for some hacking.

Today's piece is a rook. In chess, a rook is a piece that can move up, down, left or right any number of squares. Here's what a rook looks like.

It's also the logo of about 642 financial services companies worldwide.

And here are the potential moves of a rook. We're going to write code to calculate the potential moves.

The rook is in (3, 4). Remember, we start counting at 0. And it's not a regular Cartesian plane.

The castle represents the rook and the X represents the potential moves. The diagram assumes there aren't any obstructions in the way like other pieces or a banana peel. So, for any given square, how can we calculate whether there is it is a possible move for a rook?

Here's the aid again. Each cell is represented by a pair of integers (X and Y). X represents row and Y represents column. The first square (0,0) is in the top-left corner. Don't get it confused with a Cartesian plane (the ones you probably learnt in math class) where (0,0) is in the bottom-left corner.

Made in Microsoft Word.


In our example, the rook is in (3, 4). That means

  1. every square on that row (row 3) is a possible move.
  2. every square in that column (column 4) is a possible move.
Now, get some paper and write every potential move if the rook is in (3,4). Come on! It may seem obvious, but you need realise that something will be missing. STOP READING THIS BLOG POST AND ACTUALLY WRITE THEM DOWN!

You done? Alright, you should have written down coordinates covered by the Xs. Let's check.



Maybe you started writing down the columns, maybe the rows. Doesn't matter. You should have written down the following:

Squares in column 4: 
(0,4), (1,4), (2,4),        (4,4), (5,4), (6,4), (7,4)


Squares in row 3:
(3,0), (3,1), (3,2), (3,3),        (3,5), (3,6), (3,7)

If you wrote down these coordinates, congratulations! If you wrote down (3,4), then you're wrong! Square (3,4) isn't a potential move because that's where the rook is! As I said, it seems obvious. But keep it in mind when we write some conditional (if) statements. That's what I wanted you to realise: we're going to need to come up with a way to ignore the current square

I'm going to grab the code for iterating through the chess board from part one and modify it a little. You should understand this code and be able to write it without stressing.


For the purposes of demonstration, I'm going to make two variables that contain the row and column of a rook. This isn't how you'd store the location of a rook: it's just a quick way of showing you how to detect a rook in the current row or column.


This consists of two compound if statements within the nested for loop.

The first if statement checks the row for the rook, and the second if statement checks the column for a rook. The first if statement tests for two conditions:

  1. Whether the current row (iterated through by variable i) is equal to the row that contains the rook (pieceRow). If this statement is true, then every square is marked as a potential move EXCEPT if the square is in the column containing the rook (pieceColumn). If it didn't check this, every square in the row would be a potential move (even the piece containing the rook!). We know this isn't true from our exercise above: the piece cannot move into its own square.
  2. Whether the current column (iterated through by variable j) is equal to the column that contains the rook (pieceColumn). If this statement is true, then every square is marked as potential move EXCEPT if the square is in the row containing the rook (pieceRow). If it didn't check this, every square in the column would be a potential move (even the piece containing the rook!) We know this isn't true from our exercise above: the piece cannot move into its own square.
If you're confused, the best way to understand is to write the code and see what happens, then break the code and see what happens. In fact, let's do this. Copy and paste this code.

Now compile it. If all went to plan, your board should look like this.

Lookin' good! (rook is in (3,4) - remember, start counting from 0)

Let's test a few more possibilities! Replace the pieceRow and pieceColumn with 5 and 5. You should get this.

Also lookin' good! (rook is in (5,5) - remember, start counting from 0)

You might also want to test some edge cases like (0,0) and (7,7) to make sure the algorithm works.

Now, let's break this thing! If you haven't broken anything while coding, make sure you're actually coding because making mistakes is part of the process. Remember before how I said we had to make sure not mark the rook's current position as a possible move? We tested for that condition by putting a != pieceColumn and != rowColumn in the appropriate if statement. Let's remove that and see what happens!

The rook no longer exists. It has been clobbered!
So, I think we have the code nailed down for calculating possible rook moves. Of course, it's not in a usable form. You have to manually put the position of the rook into pieceRow and pieceColumn. So I'm going to set some homework for you: try and modify the code so that when you specify a rook in the initial start position, the code will pick that up and automatically draw it. I'll write the answer in my next blog post (this year, I promise!)

Other posts in this series

Chess in C (Part 1)
Chess in C (Part 2) - Insert Pawn Pun Here
Chess in C (Part 3) - Rook, Rooks, Rookies, Wookies, same thing
Chess in C (Part 4) - I'm asking for input
Chess in C (Part 5) - Potential moves of a bishop: up-left, cardinal, pope

Friday, November 23, 2012

My VMware VCAP5-DCD exam advice: don't study for the exam


I passed the VCAP5-DCD (that's an acronym for VMware Certified Advanced Professional - Data Center Design)! To be honest I didn't study and had no sleep, which makes it similar to my first year of college. At college, I even got the Dean's Commendation for High Achievement! The achievement was for my high marks, not for my sleeping. Anyway, I've never been worried about whether I would fail an exam. Like most college exams, the result was determined before I walked in. The exam just showed me the result.

And that result was a PASS!

Everyone's learning style is different, so what works for me may not be relevant to your style of learning. But my advice is, don't study for the exam. Instead, focus on becoming a better designer. The VCAP5-DCD tests your application of knowledge, and you won't learn that from memorizing the content on the exam blueprint. The blueprint isn't a list of topics to study, it's a list of skills and abilities you should have. Rote memorization will help you pass the VCP5, practicing administration tasks will help you pass the VCAP5-DCA, but only design ability will help you pass the DCD exam.

What are these abilities?

You need to be able to ask why and understand why. Let me give you an example.

Objective 3.5 states that you should be able to "Design a vApp catalog of appropriate VM offerings (e.g., templates, OVFs, vCO)." Anybody can open the vCenter client, make a new vApp, add some VMs and set the startup order. But have you developed an opinion on vApps? Do you understand their advantages, disadvantages and their limitations? Which limitations have stopped VMware from packaging their own applications as vApps? Would any of these limitations apply to an application your company is developing? What application would you most like to see as a vApp? What application can't you believe isn't already a vApp? Instead of learning about vApps, the more helpful skill to learn is to ask why something is the case.

Pick any skill listed on the blueprint, say, storage design. You probably know what the different types of multi-pathing are. Why would you use one or the other? If there are Microsoft clusters in your environment, how does that affect which method of multi-pathing you use?

Being ready

If you can whiteboard a VMware design and explain the why behind every box and line you draw, you're probably ready. Try whiteboarding the following scenarios.
  • A small customer wants the cheapest implementation required to support high-availability
  • A large customer wants a solution that has no single point of failure.
  • That large customer just acquired the small customer. Design the migration strategy.
  • Remove one of the lines between storage and compute. What is the implication of this?

Probably a little too simple. But give it a go: explain what the red double-headed arrow
between the public cloud and private cloud is. How does it work?


(Note: Any similarity to an exam question living or dead is purely coincidental. I agreed to an NDA so I'm not disclosing anything other than the fact I signed an NDA, which isn't covered by my NDA!)

You don't even need to have experience whiteboarding in front of a client. Try whiteboarding in front of somebody who knows nothing about VMware, or even enterprise IT! I've found that some of the trickiest questions I've got have been from beginners.

Exam quirks

With most other IT exams, you can skip between questions. In the VCAP5-DCD, you can only go forward. There's no ability to flag questions and return to them later. Consider this a blessing: once you've answered the question, you're locked in! You'll only need to focus on the question at hand. Control the things you can control and don't worry about the rest.

Resources

I can't recommend you anything that will help pass the exam, because I didn't revise or study for it. However, I can recommend some resources that can help you become a better designer.

  • vBrownbags are free regular online meetings run by experienced VMware architects. If you want to know how experienced designers and architects think, watch some of these.
  • The Feynmann technique involves pretending to teach the idea to a new student. This forces you to understand the concept which should make you a better designer (and consultant).
  • Download the products and use them. Don't just do the usual VCP style labs: go off the rails! What happens to a VM when you power the destination host off during a VMotion? Do you understand what happened? If not, read up on VMotion! When should you stop reading? When you can explain it to someone who doesn't know anything about VMotion! Don't be afraid to go off-topic.
Anyway, I thought that would be the last VMware exam for me, but VMware have just VCP-Cloud and VCAP-CID. Time to book some more exams. The certification treadmill never ends!

Thursday, August 23, 2012

50% VMware VCP 5 exam voucher for Australia and New Zealand non-VCPs!

If you're a VMware professional who has sat the VMware ICM (Install, Configure Manage) course but hasn't certified on VMware 5, why the heck not?!

VMware voucher ANZH65VCP5 - 50% off!

Now is the perfect time to certify! Get 50% off your exam by using the voucher code ANZH56VCP5. The exam usually costs $230.00. I'm no mathematician, but that's at least a $27.83 saving!

Don't put it off for any longer: go to the Pearson VUE VMware login page and register for the exam. If you're certified for VMware 4, don't get certified for VMware 5 and get certified for VMware 6, you'll have also certified how lazy you were!

Reversing a string in C

I was asked today if I could write a C function that reversed a string without knowing the string size. What a boring question! I don't think they were particularly interested in whether I could reverse strings. I had told them I could write C, and I think they were trying to verify this by handing me some rope. Here's what I whiteboarded.



Let's assume the string is HELLO BURGER!. Why hello burger? Because "Hello World!" is overdone and I like burgers. Burgers from Grill'd, to be specific. Grill'd is a faux-90's Australian hamburger chain aimed at Sydney hipsters with too much disposable money. To be clear, I'm not a hipster and I don't have much disposable income unless you count pocket lint as disposable income, I just like their burgers.

HELLO BURGER in a table with corresponding index numbers
I recommend the Zen Hen.

I've placed an index grid above the phrase. Keep in mind that in C, we start counting at 0. So even though there are 13 letters in "HELLO BURGER!", the final character (an exclamation mark) is at index 12. 

If we were to print the string with the statement printf("%s", input)then "HELLO BURGER!" would appear. The statement printf("%c", input[0]) would print "H" and printf("%c", input[6]) would print "B". Pretty straight forward. You might have noticed there's a \0 in the end: in C, this is a "end of string" terminator. In C, a string is defined as a...err..string of letters followed by a \0. The \0 tells C that the string has ended. If a string consists only of \0 then it's empty.

The empty string is a \0 in string position 0
This is an empty string. If input[0] is \0, it's empty.

The following is not a string. And because it's not a string, functions like strlen() that iterate until they see the terminator won't work.

BURGER as a string without \0
Not a banana either.

Let's go line by line through this application.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

First of all, let's get the basics out of the way: include string.h along with your usual libraries: you'll need it to calculate the length of an input string. The reason why this is required will become obvious later.

char* reverseString(char* input) 

In our function signature, we'll be accepting string input. Since we're accepting a string, the type of the input will be a character pointer (char*). We'll also be returning a reversed string, which is why we return the same type. Remember, there's no string datatype in C, which is a reason why the language is unsuited for any quick and dirty string manipulation.

int length = strlen(input);
int i = 0;
int j = 0;

To reverse a string in C, we'll be using a for loop. We'll need to iterate through each character in the string which will require us to know how long the string is. We'll use the variable i to iterate from the end of the string, and j to iterate from the beginning. This will make sense later.

char* newString = malloc(sizeof(char)*length+1);

This line allocates some memory for the string. malloc() allocates memory by giving you a pointer to a block of memory you can play with. To do this, malloc() needs to know how much memory you want: do you want 1kb? 2TB? I can't think of a string that would require 2TB of memory (maybe an e-mail from my mother, if she knew how to send e-mails).

We know how many characters we want: this in the variable length. However, malloc() needs to know how much memory you need, not the string length. To figure this, we use the function sizeof() which returns the amount of memory used by a type. On most computers, a char is 1 byte. But this isn't guaranteed, so we need to use sizeof(). If we multiply the size of the unit we need (a char) by the length (and add one char for the \0), we'll get the size of memory we need.

for (i=length-1, j=0; i>=0; i--, j++) {}

To reverse the string, the end is a good place to start! The final character in the string (an exclamation mark) is at input[12]. Using input[length] results in position 13 (which is the \0 and definitely isn't what we want), so our start position i should be length-1. We want to iterate until we reach index 0: the H, so we continue while the statement i>= 0 is true. After every iteration, we decrease i. In a normal for loop, you increase your loop control variable, but in our case we're iterating through the string backwards so we decrease the loop variable.

HELLO BURGER in a table with corresponding index numbers
Did I mention the fries at Grill'd? Do yourself a favour and upsize.

We'll use j as the loop control variable to write the reversed string. When writing the new string, j will start at index 0 and increment for each new character written.

newString() is ready to be written to...
newString[] is ready to be written to...

newString[j] = input[i];
This takes the current position of input[i] and writes it to the position of newString[j]. Because i starts from the end of the input string and j starts from the beginning of the new string, we are writing the reverse of the input string!
return newString;
We return a character pointer to the reversed string. This pointer points to a block of memory containing the reversed string. Because it was allocated by malloc(), the memory needs to be returned with free() once you're done with it.

Done! You can give it a try by pasting the code into Eclipse.

Why didn't you just use an array to store the reversed string?
Variable length arrays like char newString[strlen(input)] are illegal in C89 standard C. In C89, the memory structure required to store an array is allocated at compile time and not runtime. This means we needed to use a function that allocates memory at runtime, like malloc().

Why didn't you use a large array like char newString[50000]?
Because the string could have 50001 elements! Plus, that's a waste of memory: you'd be allocating sizeof(char)*50000 bytes instead of just sizeof(char)*strlen(input)+1 bytes. If you were running this function once, nobody would care. If this function were being called 20,000 times a minute (say, if you were writing some sort of function to parse every song lyric even written to see if there were any hidden backward messages), you'd want it to be efficient. In fact, there are more efficient ways of writing this function.

Are there any other ways to reverse a string?
Heaps, this isn't Python!

Tuesday, June 19, 2012

Chess in C (Part 2) - Insert Pawn Pun Here

I'm glad you could make it to the second instalment of Chess in C! In my last blog post, we made a chessboard out of an array (board[i][j], where i represented rows and j represented columns), put some pieces on the board, and found out that if you have a picnic on a farm that cows, chickens, dogs and ducks will come to share your food.

Sure, invite yourself along.

When we left off, the chess board was looking like this.


Today I'm going to discuss how we can chart the possible moves of pieces. To do this, we need to do some housekeeping. I'm going to add some macros/#define's so that we can mark a square being a potential move for a piece. If you're playing with this code and compiling as we go, take a moment now to stop, copy and paste! If you haven't got this code already, open your IDE and download the code at the end of my previous blog post so you can start modifying it.


I'm also going to update the board display code with extra case statements so that we can display the potential moves. Potential moves will be represented with +.


To simply things, I'll start by removing every piece on the board except for two pawns.


To comment out a line in C, simply surround it with /* and */, or put a // in front of it. If a line is commented out, the compiler will ignore it. Alright, now we're ready to start! Let's take a look at our board now.

Hapless losers!
Let's model a pawn's move. In this exercise, we will assume that the two hapless pawns are in their starting position, and moving forward means they will move downward.

According to the Wikipedia article on chess pawns, there are three valid moves:
1) A pawn can move to the square directly in front of itself, if that square is clear.
2) A pawn on its starting rank can move forward two squares
3) A pawn can move front-left diagonally or front-right diagonally to capture another piece.

We're going to keep it simple and only implement the first and second pawn moves. We can always add functionality later.

If a pawn is in its starting position at board[1][1], then there are two valid moves: board[2][1] (if the pawn moves forward one square) and board[3][1](if the pawn moves forward two squares). You can confirm on the board below: place your finger (or pencil or assorted pointing apparatus) on the board square represented by board[1][1]. Now move your finger down one square to simulate a pawn moving forward once: you're now at board[2][1]. If you move your finger down one square again, you will reach board[3][1]. Easy!

Use this as an aid. Wipe after use.

Obviously, we can't code every permutation of move into our chess application. If we had infinite time, we could write a million if statements for each square and piece. But I don't have that sort of time: Crust Pizza closes in an hour! Instead, we can write a simple algorithm that calculates possible moves for a piece. If we represent the board row as i, we could say that the valid move for any pawn at board[i][j] is board[i+1][j]. If a pawn is in its starting position, it can move forward two squares, we could say the pawn's valid move would be board[i+2][j].

So how do we code this in C?

There are a few ways of doing this, and they're all a variation of our board zero'ing code: we 1) iterate through every square in the board, 2) check if there's a pawn in that square, and 3) if there is a pawn in that square, mark the potential moves.

Cast your mind back to my last post. There was a nested for loop which let us iterate through every position on the board to mark it empty. Here it is below.



Let's modify it a little. We'll start by getting rid of that board zero'ing code and...*pulls out chainsaw*...done! Let's look.


The if statement checks whether the current square contains a pawn. If the if statement evaluates to true (ie. there is a pawn in the current square), then we will mark the square below it as a potential pawn move. Let's run it and see what happens.

Two pawns in their starting position.

Looks good! We can add a second if statement to determine the potential move if the pawn is in its starting position (row 1 - remember, in C we start counting from 0!) and allowed to move forward two squares (to board [i+2][j]).


Looks good? Let's see what happens.

That's two pawns and their potential moves, not a
game of Minesweeper.

If you've made it this far, that's great! You've made a simple chess board and calculated the position of a few pieces. You've also unintentionally created one of the most common bugs in the history of programming: an out of bounds errors. Don't feel bad: I intentionally led you down this path. You've got to experience the problem before you can know how to prevent it.

So what is a out of bounds error? Well, it makes demons fly out of your nose. Let me explain.

Our pawn move calculator doesn't take into account what happens if the pawn is on the final row. What if the pawn was on the final row? According to rules of chess, the pawn can be promoted to a Queen, which is helpful. But ignore that for now. If our pawn is on the final row of the board (i == 7), then the next line of code (board[i+1][j] = POTENTIAL_MOVE_PAWN) will modify a board position that doesn't exist: board[8][j]. Look at the aid: there is no row 8! If your program modified row 8, I kid you not: you would be modifying THE MATRIX. This is an out of bounds error.


The people you'll annoy if you don't bounds check your arrays.


C is an unsafe language. In a smarter language like Java, Java would pick up an invalid statement like board[8][j] = POTENTIAL_MOVE_PAWN and say "NO YUO! That doesn't exist! Go back to programming school" then crash your program. But C will happily let you make your mistake. The catch is, your bad statement won't modify the board. You'll modify the variables whose memory is stored after the board, which causes undefined behaviour. Undefined behaviour could be anything: if you're lucky, the undefined behaviour will cause your program to crash and you'll find your mistake. If you're unlucky, the undefined behaviour won't do anything...for now. This well written post by jalf (someone smarter than me) on stackoverflow.com describes undefined behaviour well:

Welcome to every C/C++ programmers bestest friend: Undefined Behavior. 
There is a lot that is not specified by the language standard, for a variety of reasons. This is one of them.
In general, whenever you encounter undefined behavior, anything might happen. The application may crash, it may freeze, it may eject your CD-ROM drive or make demons come out of your nose. It may format your harddrive or email all your porn to your grandmother.
It may even, if you are really unlucky, appear to work correctly.
The language simply says what should happen if you access the elements within the bounds of an array. It is left undefined what happens if you go out of bounds. It might seem to work today, on your compiler, but it is not legal C or C++, and there is no guarantee that it'll still work the next time you run the program. Or that it hasn't overwritten essential data even now, and you just haven't encountered the problems that is going to cause yet.

So let's modify our code and do a simple bounds check. All we need to do is write an if statement that prevents the code from being executed if the row (i) is the final row (7).


There we go. All fixed! If the row is 7 (the final row), there's no way the code modifying the contents of the next row (which doesn't exist) which prevents undefined behaviour from occurring (demons flying out of your nose).

That's it for today! I thought I'd get to some more interesting parts (like calculating potential moves of bishops and horses), but we gotta nail the simple stuff down first.

Thanks for reading so far. Here's a full copy of the code so you can play around with it. Remember kids, always bounds check your arrays!

Other posts in this series

Chess in C (Part 1)
Chess in C (Part 2) - Insert Pawn Pun Here
Chess in C (Part 3) - Rook, Rooks, Rookies, Wookies, same thing
Chess in C (Part 4) - I'm asking for input
Chess in C (Part 5) - Potential moves of a bishop: up-left, cardinal, pope

Thursday, May 31, 2012

Feather duster PowerCLI scripts!

I've been cleaning out script repository and found a file full of PowerCLI scripts I found useful. Hopefully they'll be of use to you too.

What is my consolidation ratio? (number of VMs divided by number of hosts)
(Get-VM | Measure-Object | Measure-Object -Sum Count).sum/(Get-VMHost | Measure-Object | Measure-Object -Sum Count).sum
38.278925790328472

What is my consolidation ratio rounded to two decimal places?
[Math]::Round((Get-VM | Measure-Object | Measure-Object -Sum Count).sum/(Get-VMHost | Measure-Object | Measure-Object -Sum Count).sum,2)
38.27

How many hosts in my cluster aren't ESX 5.0?
Get-Cluster myCluster | Get-VMHost | Where-Object {$_.Version -ne '5.0.0'} | Select-Object Name

What's versions of ESX do I have in my cluster, and how many?
Get-Cluster myCluster | Get-VMHost | Group-Object Version

Count Name     Group
----- ----     -----
    2 5.0.0    {esx01.test.lab, esx02.test.lab....
    1 4.1.0    {esx03.test.lab....

Which VMs in this cluster have SCSI bus sharing set to physical, and what hosts are they on?
Get-Cluster myCluster | Get-VMHost | Get-VM | Get-ScsiController | Where-Object {$_.BusSharingMode -eq 'Physical'} | Select {$_.Parent.Name}, {$_.Parent.Host}, BusSharingMode | Sort {$_.Parent.Host}

$_.Parent.Name  $_.Parent.Host  BusSharingMode
--------------  --------------  --------------
mySQLServer     esx01.test.lab  Physical


How many VMs are on each of my ESX hosts?
Get-VMHost | ForEach-Object {$_.Name; Get-VM -Location $_ | Measure-Object | Select-Object count}

Create a new VMFS datastore on a SAN LUN given a disk's NAA
New-Datastore -Vmfs -VMHost (Get-VMHost esx01.test.lab) -Name myNewDatastore -Path "naa.10000038275027693935893472859354"

Rename a datastore
Get-Datastore BurgerHut | Set-Datastore -Name HungryBurger

Total space consumed by VMs in TB
((Get-VM | Get-HardDisk | Measure-Object -Property CapacityKB -Sum).sum/(1024*1024*1024)).ToString() + " terabytes consumed"
519128.167283058 gigabytes consumed


Total number of datastores that are X KB in size
Get-Datastore | Where-Object {$_.CapacityMB -eq 500} | Measure-Object | Select-Object Count

Total number of VMs
Get-VM | Measure-Object | Select-Object Count

Monday, May 7, 2012

Chess in C (Part 1)

I recently finished writing a chess application in C. I've been trying to spend a greater percentage of my day programming: with all the cool social websites and iPhone apps out there, I've felt a little left out in these past years working in the infrastructure space. Sure, cloud is the coolest thing to happen to infrastructure, but I've always envied the people who write the awesome applications on top of the cloud. zCloud is an amazing piece of infrastructure, but the Zynga games programmed on top of it are much more fun!


The chicken in this picture is happier than your average infrastructure architect.

The best way to write a chess application (or any application) is to split it into several smaller discrete parts. In this blog post, I'll describe how to setup a chess board, put some pieces on the board and print the board. My next blog post will deal with the algorithms used to calculate possible moves.

Setting up the board


I may not be a chess grandmaster, but if I recall correctly, boards have 8 rows and 8 columns. Each square on the board can have a piece. The obvious data structure to represent this would be a two-dimensional array of integers which we can declare as follows.




That was easy. One line of code and we have a chess board! Done! Here's a diagram of what we've created.

A visual representation of int array [8][8]. It ain't pretty, and neither is C.

The first square on the board is 0,0. The last square on the last row is 7,7. Remember, in C, array elements start counting at 0 and not 1, even though the statement we used to create the board was [8][8]. Confusing, I know. Remember this lesson when it comes to writing for loops.

This chess board is neat, but it's not much use without any pieces on it This chess board is an array of integers, which means each array element can hold a number between 0 and 65536. This is more than enough: there are only six types of pieces in chess (assuming a single player for now). Let's define these pieces upfront.




By defining (or should I say, #define'ing) these pieces, we can refer to them freely through our program as BISHOP or KING, instead of having to remember obscure numbers. This will come as a relief to the dyslexics reading this blog post, and the dyslexic writing it.
Now, we'll need a function to print the chess board.



This code might look long, but it's fairly simple. Let's go through it line by line.



We have two for loops that iterate through each element of the board[][] array. Notice how the for loops begin at 0 and stop at 7? This is because in C, we begin counting from 0. Remember this: if you tried to view the contents of array[0][8] (column 9 when the array only 8 columns), you'll get an array out of bounds error. If you're lucky, you'll get garbage, your program will crash, and you'll only have to bang your head against a wall once or twice. If you're unlucky, it'll introduce subtle bad behaviour to your program and you'll die never understanding why your code behaved that way.



If any given element matches a piece, we print the piece. Unfortunately, you can't do a switch() on an array value, which is why I've made a new variable called boardValue and performed a switch() on that. Ignore the BREADCRUMB: I'll explain that later. Let's run the code so far and see what we get.

This is not the chess board I grew up with.

That doesn't look too good. It looks more like a chess board designed by an alcoholic. Where's our chess board?! What happened to our 8x8 one-line wonder?! When an array is instantiated in C, all array elements are filled with garbage. You'll need to write code to "zero out" the board.



This code will iterate through each square in the array and set the value to 0. Let's try that again.
Now THAT'S a chess board!

Fantastic! If you ever get strange array results, make sure you've zeroed out your array. Now let's place two bishops on the board in their starting positions and see what happens.



Two lonely bishops.

Amazing! Two bishops have arrived! Let's go one step further and make an ARMY



Let's look at the chess board now.
An army looking for a fight.

We can even put one hapless opposing pawn on the board with board[6][4] = PAWN;
Advice for pawn in (6,4): RUN

Here's the code if you want to compile it for yourself.



Other posts in this series

Chess in C (Part 1)
Chess in C (Part 2) - Insert Pawn Pun Here
Chess in C (Part 3) - Rook, Rooks, Rookies, Wookies, same thing
Chess in C (Part 4) - I'm asking for input
Chess in C (Part 5) - Potential moves of a bishop: up-left, cardinal, pope