Friday, February 16, 2007

Metcalfe's law


While browsing on net, I found out law that particular has some osrt of usage in our day to day activities and applications or services one provide.

Here is the description of the law. Interpret it and try to think in terms of your view, then you will understand the usage.

Metcalfe's law states that the value of a telecommunications network is proportional to the square of the number of users of the system (n2). First formulated by Robert Metcalfe in regard to Ethernet, Metcalfe's law explains many of the network effects of communication technologies and networks such as the Internet and World Wide Web.

The law has often been illustrated using the example of fax machines: A single fax machine is useless, but the value of every fax machine increases with the total number of fax machines in the network, because the total number of people with whom each user may send and receive documents increases.


Revisions

There have been subsequent revisions, however, to the estimated value added; for example, that Metcalfe's law may exaggerate that benefit. Since a user cannot connect to itself, the reasoning goes, the actual calculation is the number of diagonals and sides in an n-gon.

n(n-1)
------
2

Andrew Odlyzko and Benjamin Tilly published a preliminary paper which concluded Metcalfe's law significantly overestimates the value of adding connections. The rule of thumb becomes: "the value of a network with n members is not n squared, but rather n times the logarithm of n." Their primary justification for this is the idea that not all potential connections in a network are equally valuable. For example, most people call their families a great deal more often than they call strangers in other countries, and so do not derive the full value n from the phone service. In the July 2006 IEEE Spectrum, Bob Briscoe, Odlyzko and Tilly state more succinctly: "Metcalfe's Law is Wrong". Robert Metcalfe responded to the IEEE article, defending his namesake law, on a partner's blog.

In contrast, Reed's law asserts that Metcalfe's law understates the value of adding connections. Not only is a member connected to the entire network as a whole, but also to many significant subsets of the whole. These subsets add value independent of either the individual or the network as a whole. Including subsets into the calculation of the value of the network increases the value faster than just including individual nodes.

Applications of Metcalfe's law

Metcalfe's Law can be applied to more than just telecommunications devices. Metcalfe's Law can be applied to almost any computer systems that exchange data. Examples of devices include:

* Telephones
* FAXs
* Operating systems
* Applications
* Social networking websites

Metcalfe's Law frequently predicts whether a single vendor or interface standard will tend to dominate a marketplace. This has implications for whether an innovative solution can enter a marketplace that requires different interfaces.

The same law can be applied to other technological systems, such as personal genome sequencing. As more human genomes are sequenced and tied to personal health information in an interconnected system, the value of the information that a personal genome can contribute to personal health grows.

Thanks to Wikipedia for providing this information.

Thursday, February 08, 2007

Recover... Restore... Rejoice...


May god help YOU in recovering and restoring good health and bring back the rejoice.


Wednesday, February 07, 2007

Good Standards To Follow in PHP

In Software Development, most of the programmers have faced a very familiar situation of understanding other people codes for revamping or optimization. It's really challenging task to work in a maintenance project that demands cracking another programmers logic and thoughts. I equally love working in maintenance/optimization projects as like the new development projects. But as programmer I always strive hard to follow common standard while coding for a project. Coding style can vary by a bit for different project to avoid disinterest. Coding standards can be followed to maintain a consistent programming style throughout the core code base. If programmers follow guidelines it will be easier for others to understand and to maintain what has been developed if the project needs to optimized even after their stint.

I got sometime to work on finalizing standardizing the code styles that needs to be followed for future development... As these are very generic and can be useful for others I'm glad to share those.

Sections:
  • Naming Convention
  • Indentation/Tabs/Space Policy
  • Usage of Parens () with Key Words and Functions Policy
  • Control Structures
  • Function Calls
  • Function Definitions
  • Alignment of Declaration Blocks
  • No Magic Numbers
  • Comments
  • Others
  • Usage of ?:
  • Do Not Default If Test to Non-Zero
  • PHP Code Tags
  • Miscellaneous
Naming Convention

Class Names
  • Use upper case letters as word separators, lower case for the rest of a word
  • First character in a name is upper case
  • No underbars ('_')
  • When confronted with a situation where you could use an all upper case abbreviation instead use an initial upper case letter followed by all lower case letters. No matter what
Example
 class NameOneTwo

class Name

class GetHtmlStatistic

Method Names
  • Use the same rules as class
Example
 Connect()

GetData()

BuildSomeWidget()

Private class members
  • Class members that are intended to be used only from within the same class in which they are declared are preceded by a single underscore.
Example
 private $_mStatus

_Sort()

_InitTree()
Protected class members
  • Class members that are intended to be used only from within the same class in which they are declared or from subclasses that extend it are not preceded by a single underscore.

Example
 protected $mSomevar

protected function InitTree()

Class Attribute Names
  • Class member attribute names should be prefixed with the character 'm'
  • After the 'm' use the same rules as for class names
  • 'm' always precedes other name modifiers like 's' for static
Example
 $mVarAbc

$mErrorNumber

$msVolume

Method Argument Names
  • Methods argument names should be prefixed with the character 'a'
  • After the 'a' use the same rules as for class names
Example

function StartYourEngines($aSomeEngine, $aAnotherEngine, $aAgainOne)

Variable Names
  • Use all lower case letters
  • Use '_' as the word separator
Example
 $error

$an_example_for_var

Array Element
  • Array element names follow the same rules as a variable.
  • Use '_' as the word separator.
  • Don't use '-' as the word separator
  • Access an array's elements with single or double quotes
Example

$myarr['foo_bar'] = 'Hello';

Global Variables
  • Global variables should be prefixed with a 'g'
Example
 global $gLog

global $gTimeOut
Constants
  • Constants should always be all-uppercase, with underscores to separate words
  • Prefix constant names with the uppercased name of the class they are used in
Example
 GLOBAL_CONSTANT_FOR_EX
Static Variables
  • Static variables may be prefixed with 's'
Example
 static $msVolume

static $msVolume
Function Names
  • Use all lower case letters with '_' as the word delimiter
Example
 function some_function()
{
//code block
}
Indentation/Tabs/Space Policy
  • Indent using 4 spaces for each level
  • Do not use tabs, use spaces
Example
 function function()
{
if (something bad){
if (another thing bad){
while (more input){
}
}
}
}
Parens () with Key Words and Functions Policy
  • Do not put parens next to keywords. Put a space between
  • Do put parens next to function names
  • Do not use parens in return statements when it's not necessary
Example
 if (condition){
}

while (condition){
}

strcmp($s, $s1);

return 1;
Control Structures
  • These include if, for, while, switch, etc
  • Control statements should have one space between the control keyword and opening parenthesis, to distinguish them from function calls
  • Always use curly braces even in situations where they are technically optional. Having them increases readability and decreases the likelihood of logic errors being introduced when new lines are added.
Example
 if ((condition1) || (condition2)) {
action1;
} elseif ((condition3) && (condition4)) {
action2;
} else {
defaultaction;
}

switch (condition) {
case 1:{
action1;
break;
}
case 2:{
action2;
break;
}
default:{
defaultaction;
break;
}
}
Function Calls
  • Functions should be called with no spaces between the function name, the opening parenthesis, and the first parameter
  • Give single space between commas and each parameter, and no space between the last parameter, the closing parenthesis, and the semicolon
  • There should be one space on either side of an equals sign used to assign the return value of a function to a variable
Example
 foo($bar, $baz, $quux)

$short = foo($bar);

$long_variable = foo($baz);
Function Definitions
  • Arguments with default values go at the end of the argument list
  • Depends on where you are defining the function(Class or outside), use the appropriate naming convention
Example
 function connect($aDsn, $aPersistent = false)
{
return true;
}
Alignment of Declaration Blocks
  • Block of declarations should be aligned
Example
 var     $mDate

var& $mrDate

var& $mrName

var $mName


$mDate = 0;

$mrDate = NULL;

$mrName = 0;

$mName = NULL;

No Magic Numbers
  • A magic number is a bare-naked number used in source code. It's magic because no-one has a clue what it means including the author inside 3 months.
  • Instead of magic numbers use a real name that means something. You should use define() for example.
Bad Usage Example
 if (22 == $foo) {
start_thread();
} else if (19 == $foo) {
refund();
} else if (16 == $foo) {
infinite_loop();
}else {
blah_blah();
}
Correct Usage Example
 define("TIME_OUT", "22");
define("ROUND_UP", "19");
define("BREAK_DOWN", "16");

if (TIME_OUT == $foo) {
start_thread();
} else if (ROUND_UP == $foo) {
refund();
} else if (BREAK_DOWN == $foo) {
infinite_loop();
}else {
blah_blah();
}
Comments
  • Consider your comments a story describing the system.
  • Expect your comments to be extracted by a robot and formed into a man page.
  • Class comments are one part of the story, method signature comments are another part of the story, method arguments another part, and method implementation yet another part. All these parts should weave together and inform someone else at another point of time just exactly what you did and why.
Example
Comments at top of file:
 /*
* Short description for file
*
* Long description for file (if any)...
*
* @Module ModuleName
* @package PackageName
* @author Original Author
* @author Another Author
*/
Comments at top of class:
 /**
* Short description of class
*
* Long description of class (if any)...
* @Module ModuleName
* @package PackageName
*/
Comments at top of function:
 /**
* Short description of function
*
* Long description of function (if any)...
*
* @param $arg1 short description about first argument
* @param $arg1 short description about second argument
*
* @return short description what function will return
*
* @access specify the access type
* @static true/false
*/
function ShowResults($arg1, $arg2)
{
return 1;
}
Others

Usage of ?:
  • Put the condition in parens so as to set it off from other code
  • If possible, the actions for the test should be simple functions
  • Put the action for the then and else statement on a separate line unless it can be clearly put on one line
Example
 (condition) ? funct1() : func2();

(condition)
? long statement
: another long statement;
Do Not Default If Test to Non-Zero
  • Do not default the test for non-zero
Example
 if (FAIL != f())

is better than

if (f())
PHP Code Tags
  • Use standard approach to mark PHP codes like
Example
 <?php

?>
Miscellaneous
  • Do not do any real work in an object's constructor. Inside a constructor initialize variables only and/or do only actions that can't fail
  • There should be only one statement per line unless the statements are very closely related.
  • Always document a null body for a for or while statement so that it is clear that the null body is intentional and not missing code
Example
 while ($dest++ = $src++)
; // VOID
As usual comments are always welcome to discuss and make corrective measures.

Saturday, February 03, 2007

Part 3: Trip To Shimla

After a brief visit to The Ridge and The Malls road shopping, the first day in Shimla went off fine with heavy dinner at a Punjabi Restaurant in The Mall road.

Next and final day in Shimla was completely scheduled by the Himachal Pradesh Tourism's tour package. We got into their bus in morning 9.45Am. They took us first to Fagu Point, which is one of the highest peak. We spend some time there and from there we went to check out Golf Course Club. We roamed around there for a hour. All the places are covered by thick greenery. Really refreshing to see. Then from there we went to Kufri Point. Actually all the vehicles have to stop some 7 KM's before the point. There is not way vehicles can reach to that steep point. One has to reach either by walk or by riding in Horse. Me and my friend decided to go by walk just to get the feeling of Trekking and as a physical exercise. It took us One hour to reach the Point. It was not a green point actually, but filled with different activities. From Kufri Point you can see the Great China Border, Patiala Palace where the famous Shimla Agreement was signed between India and Pakistan. Also in that Point you can see a small temple called "Himalayan Temple". It was good experience. By this time evening came and we are forced to get back into Bus and returned to our starting point. As a final visit, Me and my Friend decided to visit "Jakoo Temple" which is located at very steep place. Really I should say, I climbed the "road" to reach that place. I wondered how vehicles are moving in that steep roads.

Jakoo Temple is the place where some parts of famous movie "Roja" was filmed. Oops beware of monkeys if you visit there. There is no need for any bandits to rob you, monkeys will do that instead.

Here are the pictures,

Me and Friend Arun

Me in The Ridge and the background is The Ridge Church

Shimla Greens

Statue of Shimla's Founder

Shimla Greenery


Shimla Municipal Corporation


The Ridge

Another View of The Ridge

Another View of The Ridge

Shimla Toy Train

Flower at its Best

Shimla Toy Train AnotherView

Plaque of Shimla's Jakhoo Temple

Hanuman Mandir at Jahkoo Temple

Making a Wish

Me at backyards of the Jakhoo Temple

Entrance to Jakhoo Temple

Beer in its Den

Shimla Greenery

White Fox

Snow Tiger



Me over an Ox in Kufri Point

The same but with some effect to symbolize the arrival of "Yema Tharamraj"

Me at Kufri Point

Taking Rest at Fagu Point


Other Greeneries,









Shimla DGP Office


Part 2: Trip To Shimla

After a wonderful brief stay at Chandigarh, We got bus to Shimla at 9AM. Actually we planned to goto Shimla by the Toy Train. But unfortunately we didn't get ticket and it's running with jam packed crowd. We should have booked it very early, early means some 3 months advance because all the year there large amount of tourists are moving in and out of Shimla. So we need to have paucca plan to have hassle free travel. Okay but even the bus ride in the mountain ride was very interesting. We got into the bus which has a Singh as driver. He was really great driver. He seemed not et al bothered about whether take driving through the congested Kalka roads or lots of hair pin bend mountain roads. He just drive like a King riding Horse. Enjoyed his style of driving and not necessarily to say the beautiful scenes all along the road to Shimla.

It took nearly 3 hours to reach Shimla. Once we got down at Shimla, at least some 10 to 15 people came towards us, initially I thought they were auto walla or tourist agent. But later on only I found out that, they will just give directions to people for some amount. Good type of business. After getting information about the Himachel Pradesh tourist office and lodging places, we paid 20rs for his service. Then we started our novel journey to get the glimse of Queen of Himlayas. We got the first hand experience of mountain terrain. Had to walk through steep roads to goto different places. Then finally we reached our lodge which is just behind the popular place The Ridge. Here you can see statues of famous leaders of India lined up both the side of road.

Here are the pictures,

Me at Most Famous Scandal Point

I cant see any other than flowers... Can you see me there?

Shimla Greeneries

Me Standing In front of Shimla Plaque

Me and Greeneries

Trip to Shimla

Here it comes finally... Yes, the long awaiting pictures of my Shimla trip. I went to Shimla with my friend Arun in the month of October,06. It was a very refreshing and wonderful trip. Also it gave me a first hand knowledge of North India. That was my first trip in North India and travelled through Kurushektra, Ambala, Chandigarh and Kalka.

I got into train at 10Pm at Nizammudin Railway Station, South Delhi. Next day morning we got down in Chandigarh Railway Station at 7AM. From the moment I stepped out of that station I felt, the city Chandigarh has lots in offer to me. From the Chandigarh station I travelled to bus station to get the bus to Shimla. As I expected, It was really a beatifull and wonderful city. Straight roads, more importantly roads were very clean. Really enjoyed the short travel in the city. By the time we reached bus station we are too hungry and wanted to refresh. So from bus station we went to near by Sector 17 market by walk. You will definitely say WoW once you get into that market. It was huge, clean and tidy market. Those old age look buildings lined up at both sides with big space between them added more beauty. After a some search, we found
a age old restaurant. Felt that I was moving back into Gandhian era. That restaurant was named after Gandhi and people worked were all wearing the Nehru style dresses which typically has white Kurda and a type of cap. Luckily they had South Indian items and more surprising fact is they menu have only South Indian items. We had hot and tasty Dosa and Idly with different North Indian cooking flavor.

Here are the pictures of my first stop over on the way to Shimla


Chandigarh Railway Station Entrance

Chandigarh Railway Station

Me at Chandigarh Railway Station

Another View of Chandigarh Railway Station

Beautiful Sector 17 Market

Another View of Market

Friday, February 02, 2007

Trapping Fatal Errors in PHP

Generally most of PHP programmers feels error handling in PHP is cumbersome or they think its just not very programmer friendly and impossible to handle fatal errors. In PHP 4.X.X versions or you can say PHP versions less that PHP 5, its possible to trap the errors with functions like set_error_handler() and trigger_error(). But the possible errors that can be handled by PHP 4 are just Warnings and Notices.

Many programmers have tried to find out ways to handle fatal errors that occur in a program, but never had patience or time to find out a viable solution. Fortunately I encountered a problem in that I must figure out some ways to handle fatal errors in PHP 4 in order to fix the issue. When I started working on this task, I looked all around globe(net) for some clues about how to handle fatal errors, but mostly all of them are either incomplete or not just straight forward that can be understandable instead thay used all sort of tech jerks to make the mud more murkier.

So here I am going to give a clear picture about how to handle fatal errors in PHP 4 with complete lab tested code that will actually work fine in all type of systems.

The main concept behind the logic I used to trap the fatal errors are output buffering. Output buffering is itself a important and big topic to discuss, and if we get into that then we will miss out from the track of our actual destination of trapping errors. So we can move on with first hand information about the output buffering.

The Output Control functions in PHP like ob_start() allows you to control when output is sent from the script. This can be used to control when a script output should be send back to browser.

Okay now I like to go straight into code and later on explain the basics.

FileName1: ErrorHandlerLib.php

<?php
//program to handle fatal errors in PHP 4

//set the error handler to catch unexpected errors
set_error_handler('LowCategoryErrors');
//start the buffering to catch the fatal error msgs
ob_start('FatalErrors');



/**
* function to handle different error types raised by PHP
*
* @return void
*/
function LowCategoryErrors($argErrNr, $argErrMsg, $argFileName, $argLineNr)
{
//initialize local variables
$szErrType = null;
$aErrorType = array(
E_ERROR => 'Error',
E_WARNING => 'Warning',
E_PARSE => 'Parser Error',
E_NOTICE => 'Notice',
E_CORE_ERROR => 'Core Error',
E_CORE_WARNING => 'Core Warning',
E_COMPILE_ERROR => 'Compile Error',
E_COMPILE_WARNING => 'Compile Warning',
E_USER_ERROR => 'User Error',
E_USER_WARNING => 'User Warning',
E_USER_NOTICE => 'User Notice',
);

//check we have value or not, else set default
if(array_key_exists($argErrNr, $aErrorType))
$szErrType = $aErrorType[$argErrNr];
else
$szErrType = "Unknown";

//form the error message string
$argErrMsg = "Caught PHP Error. $argErrMsg in $argFileName at $argLineNr.";

echo "<br>$szErrType: $argErrMsg\n";
}

/**
* function to handle Fatal error type raised by PHP. This works based on output buffering.
*
* @return string
*/
function FatalErrors($argBuffer = null)
{
//intialize local variables
$aMatches = array();
$argErrMsg = $retValue = $szErrType = null;
$tRes = true;

//parse the buffer to check whether there is any error or not
$tRes = preg_match_all("/<b>(.+?)\serror<\/b>:(.*?)<br/i", $argBuffer, $aMatches,PREG_SET_ORDER);

//diff the error and 0 return value
if($tRes===false)
{
$retValue = "<br>Fatal: Failed to evaluate regex pattern while validing the output buffer.\n";
}
elseif($tRes == 0)
{
//if we dont find any error, return the buffer content as it is
$retValue = $argBuffer;
}
else
{
//loop through the reg-ex patterns that is passed through arguments
for($iCount = 0; $iCount < count($aMatches); $iCount++)
{

//form the error message string
$argErrMsg = "Caught PHP {$aMatches[$iCount][1]} Error. Error Message: {$aMatches[$iCount]['2']}.";

echo "<br>Unrecoverable Error: $argErrMsg";

$retValue = "<br>$argErrMsg";
}
}

return $retValue;
}
?>


The function set_error_handler() here is used to register the error handler for warnings and notices. This will take care of lower category.

The second function ob_start() is the real king here. This registers the PHP buffer output handler and through this we are implementing the fatal error handling logic. This function FatalErrors() will called is there is any explicit call to end the buffer or else it will called whenever the PHP script is going to complete its final processing. Remember here, this function is also called whenever PHP going to end its execution. This makes us possible to trap fatal errors and do last minute processing.

FileName2: ErrorHandlerUsage.php

<?php

//program to demostrate the usage of fatal error handler

//include the error handler library
include "ErrorHandlerLib.php";

//error_reporting should be set to show all in order to catch fatal errors.
error_reporting(E_ALL);


echo "<br>Hello world";


/******************************************************************
Section1 : this makes notices and handled nicely by a handler
******************************************************************/

echo "<br>Im going to make some notices";

//the following statement will make the notice
$TestVar = $UndefinedVariable;

//End of Section1

/******************************************************************
Section2 : this makes warnings and handled nicely by a handler
******************************************************************/
echo "<br>Im going to make some warnings";

//the following statement will make the warning
implode('test');

//End of Section2

/*

//Uncomment this Section 3 only if you want to test the Fatal error handler, to test
//other type of error, just run the program.

//*****************************************************************
//Section3 : this makes warnings and handled nicely by a handler
//******************************************************************
echo "<br>Im going to make fatal error by calling undefined function";

//the following call to undefined functions makes fatal error
SomeJunk();

//End of Section3

*/
?>


The above code example is pretty much self explanatory and clearly spells out how trapping fatal errors are easy in PHP.

All this are just an example of single usage. You can customize outputting and last minute actions according to your needs and logics. You can implement this using object oriented programming logic in different way with other set of restrictions like freezing of object attributes by PHP.

If you like to clarify anything about this or just wanted to know one oe other about PHP you can trap me at kramchel-inet +at+ yahoo +dot+ co +dot+ in(replace the words +at+ and +dot+ with @ and . characters respectively). This is secondary mail ID I use to fight against spam. You can get my permanent ID after sending a first mail.

Happy Coding.