# Smoky Cogs

Thoughts on programming, life and anything else that floats through my brain

### Archive

Category: Tutorials

## Drawing spirals in C#

Mar 2

Spirals are a relatively easy shape to draw, but in order to draw a good spiral we need a bit of simple trigonometry.

The basics of the spiral are the radius of a particular point from the origin, at a particular angle, and for the code below, the radius increases as the angle increases. The exact relation between angle and radius determines the type of spiral.

In the simplest case, the radius will increase linearly with the angle, thus
Radius = Angle * ScalingFactor

We can also use quadratic or cubic equations to define the realtionship
Radius = Angle2 * ScalingFactor
Radius = Angle3 * ScalingFactor

The most interesting spiral, however, is the exponential spiral, which is found in nature most famously in the nautilus shell.
Radius = Anglee * ScalingFactor

Now that you can determine the relationship between radius and angle, it is a simple matter to draw the spiral.

Starting at the origin, with angle 0, we need to increment the angle by a certain amount – in the code below by 0.5 degrees per iteration – and then calculate the radius, and then using the radius and the angle, we are able to calculate the x and y coordinates of the point by using simple trigonometry, since sin(angle) = y/r and cos(angle) = x/r.

Now after finding the coordinates of the point, we simply need to draw a line segment from our previous point to the new point. The smaller the angle increment, the smoother the curve which is drawn will be, but it also means that more points need to be calculated to draw the same curve, which consumes more processing time.

One good way of speeding up the calcution of the curve, is to use a lookup table for the cos and sin values instead of calculating them with each iteration, but that is a topic for another post.

```      public void drawSpiral(double scale, double delta, double revolutions, int centreX, int centreY, SpiralType spiralType, int width, int height, Color color, Graphics g)
{
Pen p = new Pen(Color.Blue, 1);

double prevX = centreX;
double prevY = centreY;
double X = centreX;
double Y = centreY;
double theta = 0;
double radius = 0;

while (theta <= (revolutions * 360))
{
theta += delta;
if (spiralType == SpiralType.Linear)
{
radius = theta * scale;
}
else if (spiralType == SpiralType.Quadratic)
{
radius = theta * theta * scale;
}
else if (spiralType == SpiralType.Cubic)
{
radius = theta * theta * theta * scale;
}
else if (spiralType == SpiralType.Exponential)
{
radius = (Math.Pow(theta / 180 * Math.PI, Math.E)) * scale;
}

prevX = X;
prevY = Y;
X = (radius * Math.Cos(theta / 180 * Math.PI)) + centreX;
Y = (radius * Math.Sin(theta / 180 * Math.PI)) + centreY;
g.DrawLine(p, (float)prevX, (float)prevY, (float)X, (float)Y);
}

}

public enum SpiralType
{
Linear,
Cubic,
Exponential
}
```

## A simple city autocomplete field

Sep 10

I was playing around with some code recently, and came across a very easy way to create a city lookup field using jQuery’s UI components and a very useful webservice provided by Geonames.

How the autocomplete functionality in jQuery works, is by wrapping the functionality around a standard html text input field, populating a dropdown list of values from an ajax call to a webservice, in this case, the Geonames webservice.

When supplied with a partial city name, the GeoNames webservice returns back a list of information for cities matching the partial city name supplied, allowing you to display, and keep track of, the country, province, full city name, and a host of other info. Full documentation is provided on the GeoNames site.

```\$( "#city" ).autocomplete({
source: function( request, response ) {
\$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
//Display city name, state name, country name
response( \$.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
\$('#city').val(ui.item.value);
return false;
}
});
```

## Using jQuery to find JavaScript events

May 31

One of the most frustrating things about JavaScript is being able to determine what events are being fired for a particular element, especially in a complex web application where a single element might have several different functions attached to a particular event.

Well, jQuery comes to the rescue.

jQuery has a very useful, and rather unknown, method to return all the events attached to an element, which is particularly useful when used in the web browser’s console while debugging a web page.

All this needs is one single line of code, and hey presto!

```\$(element).data('events');
```

## Focus in jQuery

Jan 25

To focus on an element using jQuery is really easy, since all it takes is one function – .focus(). There are cases though were it is just a little bit trickier.

Let’s take the scenario where after entering a field, you need to validate it, and if the validation fails, you need to return focus to the field. You would expect the following code to do the job:

```\$(elem).blur(function(){
if (do some validation fails) {
\$(this).focus();
}
});
```

This code, logically, should work, and indeed it does in Internet Explorer, but Firefox stubbornly refuses to set the focus.

The problem is that the event is firing at the wrong time for Firefox, and therefore the focus event is being lost.

The solution for this is to delay the focusing by a small bit, which then yields a solution that works in all browsers

```\$(elem).blur(function(){
if (do some validation fails) {
var \$this = \$(this);
setTimeout(function () { \$this.focus(); }, 10);
}
});
```

## Some interesting (but basic) Batch-file Fu

Apr 21

I haven’t made much use of Windows batch files for many, many years. I just haven’t had a need for it, but I learnt a few interesting titbits of Batch file use that I never really knew before today.

Putting IFs into FOR loops
Firstly, batch files support FOR loops as well as IF statements, and therefore putting this together, I would expect this piece of code to work:

```for /D %%d in (*) do (
if "%%d" == "a" goto A
if "%%d" == "b" goto B

echo "Default - %%d"
goto CONTINUE

:A
echo "A - %%d"
goto CONTINUE

:B
echo "B - %%d"
goto CONTINUE

:CONTINUE
)
```

At first glance this code should work. It is merely a few IF statements inside the for loop, which loop through all the directories inside the current directory, and then prints a message following the logic of the if statements.

This code fails (at least while running on Windows 7) because, while it will work for the first item, after the goto statements, the for loop decides to stop working.

To get around this, the solution I used was to move the logic inside the for loop into a separate batch file, and then using the CALL command to execute the second batch file from within the FOR loop. This works a charm

First batch file

```for /D %%d in (*) do (
CALL SecondFile.bat %%d
)
```

Second batch file

```if "%1" == "a" goto A
if "%1" == "b" goto B

echo "Default - %1"
goto CONTINUE

:A
echo "A - %1"
goto CONTINUE

:B
echo "B - %1"
goto CONTINUE

:CONTINUE
)
```

Substring in Batch files
What I also wanted to do, was only compare a portion of the directory name, so then discovered that Batch files have a very simple method of substringing.

The basic format is %varname:~[x],[y]%, where [x] is the starting index in the string, and [y] determines the number of characters to select, which is optional

If the first parameter is positive, then it denotes the index from the start of the string, while if it is negative, it will denote the index from the end of the string.

So let us use an example

```set var=teststring

echo %var:~0,5%
echo %var:~-3%
echo %var:~-5,2%
echo %var:~4%
```

This will output the following output

```tests
ing
tr
string
```

## Faster string concatenations in JavaScript

Apr 20

With AJAX being the norm for websites these days, and JavaScript taking on more a more central role in building up web content, you are more than likely going to find yourself having to build up strings containing html to display in a webpage using JavaScript.

This does come at a price though. String concatenations can be rather slow, especially if there is a lot of data that needs to get processed, such as a large table. Unsurprisingly, this is most noticeable in Internet Explorer.

A colleague of mine came up with an alternative way of creating the new html string, using an array to build it up instead of a string.

So using the traditional method you would write:

```var htmlStr = '<table>';
for(i = 0; i < data.count; i++){
htmlStr += '<tr><td>' + data[i] + '</td></tr>';
}
htmlStr += '</table>';
document.getElementById(elemId).innerHTML = htmlStr;
```

Using an array though, this can be rewritten as

```var htmlArray = [];
htmlArray.push('<table>');
for(i = 0; i < data.count; i++){
htmlArray.push('<tr><td>');
htmlArray.push(data[i]);
htmlArray.push('</td></tr>');
}
htmlArray.push('</table>');
document.getElementById(elemId).innerHTML = htmlArray.join('');
```

In some tests, my colleague found that speed improvements of up to 80x-400x were shown using the array method, varying on the complexity of the concatenations. The biggest improvements were shown in Internet Explorer, with less gains measured in Firefox and Chrome, although quick results were measured in each one.

## Iterating over char values in C#

Oct 17

In C#, the char data type represents a text character. Internally though, this value is pretty much a numeric value.

Think here of Ascii or Unicode values. These codings essentially map a character to a particular numeric value, which is what the char data type stores.

One rather interesting side effect of this is that you can iterate through character values in exactly the same way as you would for an int or long.

In the sample code below, the code loops through all the capital letters of the alphabet, adding each letter to a string.

```string alphabet = "";
for (char c = 'A'; c <= 'Z'; c++)
{
alphabet += c.ToString();
}
```