Abolish the Union in C

The General, who is a five star manager, is conducting a code review with his test developers.  “I’m looking at your code here boys.  I do very much admire your use of union utterings,” he says.

#include <stdio.h>

union yankee {
        int   bulletInt;
        float bulletFloat;
};

int main() {
        union yankee soldier;
        soldier.bulletInt = 111;
        printf("Int: %i\n", soldier.bulletInt);
        soldier.bulletFloat = 222.333333;
        printf("Float: %f\n", soldier.bulletFloat);
        /* clobbered by the float as expected */
        printf("Int: %i\n", soldier.bulletInt);
        return 0;
}

He continues, “However, I am a Yankee soldier with sympathetic tendencies towards the southern cause.  We’uns don’t put on our best suits when we go out and kill hogs; therefore, I do declare that we abolish the union in such a rightly manner as prescribed here.”

#include <stdio.h>

union yankee {
        int   bulletInt;
        float bulletFloat;
};

typedef union yankee confederate; 

int main() {
        confederate soldier;
        soldier.bulletInt = 111;
        printf("Int: %i\n", soldier.bulletInt);
        soldier.bulletFloat = 222.333333;
        printf("Float: %f\n", soldier.bulletFloat);
        /* clobbered by the float as expected */
        printf("Int: %i\n", soldier.bulletInt);
        return 0;
}
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
 

Use Heredoc as a Function Argument in PHP

Source: Telovation.com

Is it possible to use a heredoc as a function argument in PHP?  Yes.

Let’s say that you have a function that prints out the <head> section of an HTML page.  You want to use this function on all of your web pages since it helps keep things standardized; however, some pages may require additional things like JavaScript and/or CSS includes.

The heredoc string is a great way to insert custom text into a function without creating a separate variable for it.  Some pages may not need the additional text so it’s best to define the $includeText variable as optional as seen below.

/* Here is our example function */
function PrintHeader($title, $includeText=’’)
{
	print <<<HEREDOC
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>${title}</title>
<meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
${includeText}
</head>\n
HEREDOC;

	return;
}

/* Here is how we can call it with heredoc as an argument */

PrintHeader('www.fleischkuekle.com’, <<<HEREDOC
<script language="JavaScript" type="text/javascript"
src="js/share/Ajax.js"></script>
<style type="text/css" media="screen">
	body {
		font: 11px arial;
	}
	.ajax_link {
		background-color: #FFFFFF;
		padding: 2px 6px 2px 6px;
	}
	.ajax_link_over {
		background-color: #3366CC;
		padding: 2px 6px 2px 6px;
	}
	#ajax_suggest {
		position: absolute;
		background-color: #FFFFFF;
		text-align: left;
		border: 1px solid #000000;
	}
</style>
HEREDOC
);
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
 

JavaScript Module Pattern Template

Object-oriented (OO) JavaScript syntax is a bit convoluted for those coming from other OO languages.  Feel free to use this template to get you started.  To understand what’s going on, do a web search for JavaScript and the following keywords:

  • OO JavaScript
  • Object Literals
  • Anonymous Functions
  • Module Pattern
  • JSON
  • Douglas Crockford
  • Fleischkuekle
var MyClass = function(str) {

 	/* Private Stuff (Old-Skool Style) */
 	var aPrivateString = str;
 	var aPrivateArray = new Array();

 	function myPrivateMethod1() {

 		/* Access private field (above) */
 		aPrivateArray.push(str);

 		/* Access public field (below) */
 		publicCode.aPublicString = "slammy";

 		/* Access public method (below) w/private field
                   as arg (above) */
 		publicCode.myPublicMethod1(aPrivateString);
 	}

 	function myPrivateMethod2() {
 		alert("This is private method 2");
 	}

 	/* Public Stuff (Object Literal Style) */
 	var publicCode = {

 		aPublicString : "",
 		aPublicArray : [],  /* Note: JSON style */

 		/* Make private method publicly accessible */
 		accessPrivateMethod2 : myPrivateMethod2, 

 		myPublicMethod1 : function(str) {

 			/* Access a private field from above */
 			aPrivateString = str;

 			/* Access a private method from above */
 			myPrivateMethod1();

 			/* Access public variable from above
                           w/this keyword */
 			this.aPublicString = str;
 		},

 		myPublicMethod2 : function() {
 			alert(aPrivateString);
 		}
 	}

 	/* Return the public object literal code only */
 	return publicCode;
 }

 /* Client code demonstration */
 var myObj1 = MyClass('somestring');
 myObj1.myPublicMethod2();  // Allowed
 myObj1.aPublicArray.push('fleischkuekle'); // Access public field
 var myObj2 = MyClass('someotherstring');
 myObj2.myPublicMethod2(); // New instance means data is unique
 myObj2.accessPrivateMethod2(); // Allowed
 myObj2.myPrivateMethod2(); // Not allowed

The MyClass variable is assigned an anonymous function. The function encapsulates the code; therefore, all of the code inside of it is private (just make sure to use the var keyword to prevent the inner fields from being global). If you want any of the inner code to be public, then define it in an object literal, like publicCode, and return it to the caller. Some examples I have seen skip assigning the object literal to a variable, but rather define it in a return{} block instead. Either way works just fine.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
 

Reno

Source: Compression Project

A well-written DOS batch file should always check the number of command line arguments passed to it even if it doesn’t require any arguments.  If the actual number of arguments doesn’t match the expected number of arguments, then display a usage message to ensure that the user understands what the batch file is supposed to do.

The DOS batch file below shows you how to determine the total number of command line arguments given by the user during invocation.  In this example, we expect two arguments only, but the user provides three.  A usage message is displayed and an exit status of 1 is returned to the operating system.  We run the batch file again, but this time with the correct number of arguments.  No usage message is displayed and an exit status of 0 is returned instead.

[CODE]:

@echo off

set _exitStatus=0
set _argcActual=0
set _argcExpected=2

echo.

for %%i in (%*) do set /A _argcActual+=1

if %_argcActual% NEQ %_argcExpected% (

  call :_ShowUsage %0%, "Bad human...bad args."
  
  set _exitStatus=1
  
  goto:_EOF
)

REM Your code goes here

goto:_EOF

:_ShowUsage
  
  echo [USAGE]: %~1 arg1 arg2

  echo.
  
  if NOT "%~2" == "" (

    echo %~2
    
    echo.
  )
  
  goto:eof

:_EOF
 
echo The exit status is %_exitStatus%.

echo.

cmd /c exit %_exitStatus%

[OUTPUT]:

c:\>countargs.bat 1 2 3

[USAGE]: countargs.bat arg1 arg2

Bad human...bad args.

The exit status is 1.

c:\>countargs.bat 1 2

The exit status is 0.

c:\>
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
 

Source: Marcel Duchamp, Mile of String

There are more string types in C++ than the Boston Symphony Orchestra.

Audience laughs

There are so many different string types in C++ that it’s easier to master string theory in physics.

More laughter

I try to write simple, cross-platform software whenever possible, particularly for helper functions that I find myself using often no matter if I am running under Windows or Linux.  When it comes to strings, I prefer to keep it simple with the ISO standard <string> class along with a few STL classes for manipulation.  I know that there are many other string types in VC++ that are optimized to perform better and offer more features, but most of them run on Windows only.

The two functions below will handle these conversations quite nicely.  Converting a number into a string is straightforward, but converting a string into a number can have a few pitfalls, especially if the string is not a number.  Make sure to check for these conditions before or during the conversion.  One other thing, you may want to consider using a template to handle the various number types—long, short, float, etc.  The examples below are for integers only.

Audience now can’t stop laughing for no apparent reason

#include <string>
#include <iostream>
#include <sstream>

using namespace std;

// Convert an integer into a string
string convertIntToString
(
  int iNum
)
{
  ostringstream sStr;

  sStr << iNum;

  return sStr.str();
}

// Convert a string into an integer
int convertStringToInt
(
  string sStr
)
{
  int iNum = 0;

  // Maybe do a custom trim() call first to 
  // eliminate leading and trailing white-spaces

  istringstream sTmpStr(sStr);

  // If returns false, then the string is not a number

  if ( !(sTmpStr >> iNum) )
  {
     // Throw some exception here because     
    // string was not a number…e.g.:
    throw ( ... );
  }

  return iNum;
}

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Tagged with:  
Page 1 of 3123

Random Site Quotes

“Quality starts with the person, not the product”
© 2009-2011 TestDeveloper.com
Powered by WordPress
Content provided by John L. Whiteman and his Slam Carrot Long Ears Gang