zomgistania

Main page | About | Articles | Previous Posts | Archives

Friday, July 28, 2006

Who said a format/reinstall is the only option?

I wonder how many times in the past I have reinstalled Windows 95, 98, and 98SE because something screwed things up. You probably have done that as well.

Many people kept on reinstalling Windows after MS launched 2000 and even XP, even though they had excellent recovery and repair tools and lost much files and data. Even for minor things like a new graphics card.


I have used Windows 2000 Professional for years. Never had to reinstall it or format the drive. The computer even went through a complete rebuild! Only the harddisk was swapped from the old, and it still kept going! Whoever said Windows isn't stable doesn't know crap about it.


When I switched to XP, I didn't know it would require me to install a patch, namely Service Pack 2, to support big disks like the 200 gig disk I have. It screwed up the partition table on the disk and there went my 200 gigs of data, including the installation of the Windows.

Back then, I used GetDataBack for NTFS to restore my important files. It was a pretty good tool, although some files got a bit corrupted.



Now the disk flattened the partition table. Again. I don't know why, but it happened.
This time I had more important files and didn't want to risk any corruption because it was honestly said pretty annoying.


The Ultimate tools for Windows system recovery

Starting from the Recovery Console on Windows' XP and 2000 disc. It lets you do basic operations in a DOS-like environment like copying and renaming files on the disk. It also lets you fix the boot sector and Master Boot Record (MBR) which is very useful in some situations.

The second tool for recovering a dead system is of course The Ultimate Boot CD. It has a big batch of useful tools ranging from disk formatting utilities to antivirus. There is a very useful tool on the disk called TestDisk which recovers lost partitions. In my case I had two partitions on the 200 gig disk and all I had to do to get them back was boot into UBCD, choose TestDisk, select the 200 gig disk as the target drive and it would do the rest on it's own, only asking me for confirmation or possible changes.


And now let's continue the story for a short moment: after recovering the partitions with TestDisk, I tried to boot back into Windows. Windows XP would start loading... then it would give me the sign in prompt. I thought that was it... until I noticed the keyboard and mouse didn't react to my input!


This time firing up the recovery console, I went into c:\windows\system32\config and backed up system from that dir. Then I copied over c:\windows\rescue\system to the config dir. Back to Windows again... thinking "Did Windows move to C... don't tell me it did.". You see, I had Windows on drive F! I knew it would cause me problems if it had moved to the letter C...


Back to windows again. The keyboard works, mouse didn't. Well, whatever, let's just sign in!
Waiting a while for the things to load... hey wait, why am I being logged out?
I was logged out automatically every time I tried to log in. No matter which user I tried. Same thing happened in Safe Mode as well.


I googled around a bit and found out this could be caused by a file called userinit.exe being looked for from the wrong place. hmm. C:\Windows\userinit.exe... F:\Windows\userinit.exe... See the problem?

and now comes in the third tool for ultimate system recovery!
The Ultimate Boot CD for Windows!

Creating this baby required some help from my buddy, thanks to him. It contains a Windows pre-install environment loaded with recovery and diagnostics tools.
A windows pre-install environment is a shell like Windows so it's pretty easy to use as well.

Now, to fix the partition letters to the correct order!
First I fire up regedit and explorer for the pre-install windows. I check which drive is which from explorer and go to HKEY_LOCAL_MACHINE\SYSTEM\MountedDevices and make a dump of that and open it in notepad.

After this, I opened the Remote Registry Editor on the desktop which lets me edit the registry on the actual windows installation on the harddisk.

I went again to the mounted devices hive in the registry and started looking how the \DosDevices\X: entries were labeled... I renamed them so the drive letters there would match the order they should be in Windows... \DosDevices\C: goes to \DosDevices\F: and so on. Pretty simple stuff.


Okay now I was done. Time to see what happens when I boot to windows!

and... it worked!



Anyway, all in all this took really really many hours to accomplish. Why? Because I didn't have the tools around. If I had had them, it wouldn't have taken very long to fix all this. So.. the next time you encounter a problem... think a bit before formatting, you might learn something in the process, even if you can't fix the problem!

Here are links to the tools I mentioned:
The Ultimate Boot CD
The Ultimate Boot CD for Windows

Saturday, July 22, 2006

Comparing and copying arrays in JavaScript is a pain

Ever wanted to copy an array in JavaScript? Tried the simple var array2 = array1?
Yes, it doesn't work that way.

Apparently with arrays and objects, JS uses references just like C# and in case you want to make a copy of an array...


function CopyArray(a)
{
//Create a new array with the old ones length
var n = new Array(a.length);

//Just copy all the values from the old to the new
for(var i = 0; i < a.length; i++)
n[i] = a[i];

return n;
}

var array2 = CopyArray(array1);


You'll have to use something like that. Of course it gets way more complicated when dealing with jagged arrays, eg. arrays which have arrays in them. You'll have to write a recursive function or something the like of this:


function CopyArray(a)
{
//Create a new array with the old ones length
var n = new Array(a.length);

//Just copy all the values from the old to the new
for(var i = 0; i < a.length; i++)
{
//if the value in the old array is an object (array)
//call the CopyArray function recursively
if(typeof a[i] == 'object')
n[i] = CopyArray(a[i]);
else
n[i] = a[i];
}

return n;
}


With that you can create nice copies of arrays while still keeping them as array objects.


How about comparing arrays? Uh oh, if(a == b) doesn't work like expected!

Yet again we'll have to use a customized function


//Check if two arrays' contents are the same
//returns true if they are, otherwise false
Equals = function(a,b)
{
//Check if the arrays are undefined/null
if(!a || !b)
return false;

//first compare their lengths
if(a.length == b.length)
{
//go thru all the vars
for(var i = 0; i < a.length;i++)
{
//if the var is an array, we need to make a recursive check
//otherwise we'll just compare the values
if(typeof a[i] == 'object') {
if(!Equals(a[i],b[i]))
return false;
}
else if(a[i] != b[i])
return false;
}
return true;
}
else return false;
}

if(Equals(a,b)) { /* ... */ }


ookay!

You might notice that the usual JavaScript naming convention is that function names start with a small letter. I use capital letters just because I'm used to that from C# and it looks better to my eye.

Saturday, July 15, 2006

Object-oriented JavaScript

I'm working on a "World Clocks" widget for Opera 9. It's basically something which can display multiple clocks set in different timezones.

As the widgets in Opera 9 are coded with HTML and the like, the actual funcionality is written in JavaScript. Therefore I was thinking about a way to implement the different clocks and thought about making it a class.

Classes in JavaScript are a thing many don't know of, so I'll write an introduction to them, based on the Clock class I made.


The idea

The idea is to make a Clock class... as we're going to have one or more of them, the time can be taken from a "central location", this time a JavaScript Date object.
Because of this, the Clock itself will not store a time, it will just format the time based on it's settings.

Things we're going to store in the clock for starters: Clock's name/id and the clock's offset from GMT +0. It should also have functions for returning the HTML-element for the clock and updating it's element in the document.


Let's begin!

Creating a class in JavaScript is actually a function definition:


function Clock(name,timeOffset)
{

}



Now we need to add the variables for storing the name and the offset.
To add member variables to the class, the following syntax is used:

function Clock(name,timeOffset)
{
this.name = name;
this.offset = timeOffset;
}


The values required by the Clock function are set to the member variables.
Adding functions to the class works in a very similar fashion:

function Clock(name,timeOffset)
{
this.name = name;
this.offset = timeOffset;

this.Tick = function(time)
{
var h = time.getUTCHours();
var m = time.getUTCMinutes();
var s = time.getUTCSeconds();

if(m < 10) m = '0'+m;
if(s < 10) s = '0'+s;

h = Number(h) + Number(this.offset);
if(h > 23) h -= 24;
if(h < 0) h += 24;

var obj = document.getElementById(name+'_time');
obj.innerHTML = h+':'+m+':'+s;
}

this.GetElement = function()
{
var base = document.createElement('div');
base.id = name;
base.className = 'clock';

var label = document.createElement('h2');
label.id = name+'_label';
label.className = 'label';
label.innerHTML = name;

base.appendChild(label);

var time = document.createElement('span');
time.id = name+'_time';
time.className = 'time';
time.innerHTML = '00:00:00';

base.appendChild(time);

return base;
}
}


Firstly, there's the Tick function. It takes a JavaScript time object as it's parameter.
From the time object we take three values: the UTC hour, UTC minutes and UTC seconds. Then we check whether the minutes or seconds are smaller than 10 and add a zero to the front to make them appear nicer in the formatting.

As UTC equals GMT +0, we just add the GMT offset to the UTC hours to get the time in the desired timezone. Now, if the clock was 23:00 GMT+0 and we added there, say, 6 hours, the clock would obviously show something completely wrong... 29:00 isn't a proper time as you might know. That's why the next thing we do is check whether the time goes out of bounds and add or remove 24 hours for making it correct again.

The the code just gets the element for the clock and sets it to show the time.


Then the GetElement function..
First, we create an empty div element to hold the clock. We give the clocks name for the div as it's ID and set it's CSS class name to 'clock'. Then we create a h2 element for displaying the clock's name. Again we set the id and CSS class name and also the innerHTML is changed to the clocks name. After this, we append the h2 element to the div we created first.
Finally we create a span for displaying the actual time for the clock and add that too to the div. Finally we return the whole div object.



Finally...

Using this class would be simple as this:

//create a new clock
var myclock = new Clock('example',3);

//add the clock's element to the document
document.body.appendChild(myclock.GetElement());

//Update the clock once with the current time
myclock.Tick(new Date());


So there we have the Clock class. There's a bunch of things which could be added, like storing a daylight savings time, so the clock would automatically stay in the proper time in case of DST. Also, the Tick function could check if the passed variable is actually a Date object or not and it could also allow the user to format the time in 12-hour format instead of 24-hour.



In case you want to check out the widget I'm working on, you can download it from Opera Widgets.

Some intresting reading on JavaScript can be found at "JavaScript: the worlds most misunderstood programming language"

Wednesday, July 12, 2006

Feed button generator - graphics with PHP and ImageMagick

On the other day while browsing, an idea struck me... You often see these "RSS Feed", "CSS 2.0" and other buttons in the style of my new RSS feed link. I thought it would be cool to try to make a PHP script which would generate these graphics!

So I present you...

The feed button generator!



The button generator uses PHP and ImageMagick. The interface uses JavaScript for the color picker and for quickly displaying the newly generated image without having the page to refresh or such. It's Web 2.0, baby!

ImageMagick is a quite advanced graphics toolkit which works from the console. There is also an interface for PHP, but as it requires a recompile of PHP, I didn't install it. I used exec() to use the imagick command line tools.


The image generation script itself is quite simple. It checks for $_GET variables which contain the options for the button, like the text on the left side and uses a default value for each if there's no user-defined value.

Each of the GET variables used are ran through escapeshellcmd() to make sure the user can't try anything we don't want him to.

The ImageMagick command used, however, is worth a better look:


$cmd = IMAGICK_PATH.'convert -size '.$w.'x'.$h.' xc:black ';
$cmd.= '-fill white -draw \'rectangle 1,1 '.($w-2).','.($h-2).'\' ';
$cmd.= '-fill "#'.$lsbgcol.'" -draw \'rectangle 2,2 '.$vbarpos.','.($h-3).'\' ';
$cmd.= '-fill "#'.$rsbgcol.'" -draw \'rectangle '.($vbarpos+2).',2 '.($w-3).','.($h-3).'\' ';
$cmd.= '-font lucon.ttf -pointsize 10 -fill "#'.$lstcol.'" -draw "text 5,11 \''.$lstext.'\'" ';
$cmd.= '-fill "#'.$rstcol.'" -draw "text '.($vbarpos+4).',11 \''.$rstext.'\'" ';
$cmd.= $path.'/'.$tmpname;


It probably looks quite complicated with all the inline variables. So let's also display a sample output for that.

/usr/bin/convert -size 80x15 xc:black -fill white -draw 'rectangle 1,1 78,13' -fill "#FF6600" -draw 'rectangle 2,2 30,12' -fill "#898E79" -draw 'rectangle 32,2 77,12' -font lucon.ttf -pointsize 10 -fill "#FFFFFF" -draw "text 5,11 'RSS'" -fill "#FFFFFF" -draw "text 34,11 'Feed'" /wwwroot/projects/feedbutton/1152680468.gif

And it might still look complicated, so let me explain it a bit.

Starting with the IMAGICK_PATH.. it's the path to the ImageMagick binaries, in this case "/usr/bin/". The applications name is convert.

the -size parameter is probably self explanatory. It sets the size of the canvas to 80x15. $w and $h contain the values for this.

xc:black sets the background color of the canvas to black. You could use hexadecimal color values here too, like xc:FFFFFF.

with -fill, you set the fill color for drawing and the text color for drawing text. As you can see from further, you can use hexadecimal values too but they have to be inside quotes.

the -draw parameter draws all kinds of shapes. In this case, we're just drawing a bunch of rectangles and some text.
Draw takes some parameters of it's own which go inside single quotes. The first parameter is the type of the shape to draw, for example, rectangle. When drawing rectangles, you also have to give it the top left corner and the width and the height of the rectangle.

As we want to have the button to have a one pixel border, we set the top left corner of the rectangle at 1,1 and the width and height to 78,13. The rectangle's width and height are determined by width-2 and height-2 as seen in the code.

After drawing the first rectangle, the fill color is switched to the color of the box on the left side. It's drawn in exactly the same fashion as the first one. However, this time we're using the position of the middle bar as the width.

Next, the script draws the right side box. This time the starting position's x position is set to middle bar position + 2 to make the one pixel white bar appear in the middle, thus the name "middle bar". (In the code the variables name comes from "vertical bar position", it's before I figured out a better name for it)


As you can see, drawing rectangles is easy. If you wanted to draw more rectangles, you would just add more -draw parameters and -fill's for changing colors.


Now the only thing left to draw are the texts that appear in the button. This is done in a very similar way as the rectangle drawing.

First, the font is defined with -font parameter. lucon.ttf was stolen from my windows' font directory and moved to the server... it's "Lucida Console".

-pointsize defines the size of the font.

To draw the text, the rectangle parameter is just switched to text. The two numbers are the top left corner of the position of the text and after that comes the text to draw.

Drawing more text is yet again done by adding another draw parameter.

Finally, our newly created button is saved with a temporary file name, which is generated by PHP using date(). The $path variable holds the path of the script so it's saved to the correct directory.
The path can be found by calling substr($_SERVER['SCRIPT_FILENAME'],0,strrpos($_SERVER['SCRIPT_FILENAME'],'/'));



After saving the image to disk, the image.php script calls header('Content-Type: image/gif') and include()'s the temporary file. After this the file is unlink()'d as it's not needed anymore.



The JavaScript color picker is Tigra Color Picker. Other than that, the JavaScript in the page is quite simple, as it only changes the src attribute of the img element which displays the image generated. The page should also work in case JavaScript is unavailable for some reason. In that case, the user gets redirected to the image.php script which will display a graphic with the users' configuration.

Note that you'll have to remove any # characters from an URL if you're using it as an image's src attribute... otherwise you'll end up in trouble and get a very random looking error and random behavior. At least in my case.


You can find more info on ImageMagic, including installation info from their homepage.
Here are many examples of using ImageMagic

Tuesday, July 04, 2006

Traffic simulation

Since I've been very much in trouble because of traffic jams, I've been thinking about how traffic and such is actually simulated in games and applications.

Basically you need to have roads and vehicles. You also want intersections, otherwise it might be a quite useless sim :)


Roads are organized in stretches: a certain speed limit, a certain length and certain amount of lanes. For the sim let's say each stretch also has a starting point and an ending point, which can be connected to other stretches of road or intersections and such.

A lane on the other hand is a piece of a road which has a direction, coming or going, which depends on the point of view but for the sake of simplicity let's just define that "going" means moving from the start point of a stretch to the end point and "coming" the other way around.

Cars drive on lanes. They drive at a certain speed. They can also switch lanes if there are more lanes going to the same direction, so they need to be aware of other lanes and other vehicles around them. They also need to have a size and a position on the lane, so other vehicles can avoid them and such. This should also be used to determine whether a lane is full when a car is in an intersection trying to enter a lane.


There is also another way of thinking the road-lane thing... you could have "just" lanes. They would then hold the begin and end point links to other lanes, have a certain length etc.
I haven't yet determined which one is a better approach, the road-lane or just lanes.


So far code-wise this means something like the following:
A Road class which holds Lane objects, has a speed limit and a length. Also a begin and an end points, which can be references to other Road objects

A Lane class, has a reference to the parent road, a direction (coming/going) and a list of Cars on the lane. They should contain methods for cars entering and leaving the lane.

A Car class which has a speed, size and position in the current lane. It should also hold a variable which marks where it wants to turn in the next intersection so it can navigate to the proper lane and turn in the intersection.
Cars need methods for scanning for other cars, moving, stopping, changing lanes, maybe more.


The whole deal of moving around the lanes could also be left just for the Cars. The lanes wouldn't know about the cars on them. The cars would navigate how they best see to fit and only use the Lanes to help navigate around. This is another thing I haven't yet tried, as I'm still working on implementing the roads, lanes, cars and movement and such.



Intersections. Let's keep it simple for now at least. When a car arrives at an intersection, it must pick the lane where it can continue to the direction it wants to go. Therefore the lanes in intersections need to have target lanes in the road objects which are linked to the intersection. Also, cars should obey some kind of traffic regulations like letting the cars coming from right go first. So to do that the cars will have to be yet again able to see if there are any cars coming to the intersection from the other roads. Other things to note are, of course, traffic lights. Red or green for keeping things simple again. If the light is red, car stops. Green, go!



I made some classes for working some of these things out. I might post them later if I get them doing anything intresting.



Here's a small traffic simulator in Java. It may seem to get stuck when you adjust the sliders but just wait a moment and it'll continue.