Welcome
Welcome to the website of Dennis Hedegaard, computer entusiast and open source supporter.
This blog is the center of the webserver, which hosts gitweb repositories, some abandoned svn repositories and random public files.
Welcome to the website of Dennis Hedegaard, computer entusiast and open source supporter.
This blog is the center of the webserver, which hosts gitweb repositories, some abandoned svn repositories and random public files.
I finally found some inspiration for doing the .netcat gui, the library and CLI was done a long time ago.
The gui has a focus on being small, fast and efficient. Escape closes all windows and enter sends data or goes to the next input. I decided to do it in WPF, which is a new gui toolkit in .net starting from .net 3.0, it is to replace the aging windows forms. In fact WPF is not exclusive to .net, since SWT (Standard Widget Toolkit) from eclipse has a WPF library that works quiet well. I used the WPF implementation in SWT back when I ported my XkcdReader project to SWT.
I’ve made a small site, where the binaries are hosted. They should work for anything .NET 3.5 and above, since mono doesn’t support WPF yet, you’re probably better off with the CLI (or just regular netcat, if you’re on unix).
The connection dialog:
The main window (HTTP example):
Get it while it’s hot, bug reports, pacthes and feature requests are welcome =]
Git repository: http://git.neo2k.dk/?p=cs/dotnetcat.git
Project site: http://pub.neo2k.dk/dotnetcat/
The old xkcdreader project, which originally was made to better myself in parsing xml with stax, is now extended with a SWT gui. It is still possible to use the old swing gui.
SWT is the Standard Widget Toolkit and is a part of the eclipse projects, it uses native controls instead of painting (or emulating) the look of a specific platform, that is the way swing does it.
That also means that there’s a library for SWT, that differs from platform to platform, however this I believe is easily overcome with ant. SWT uses an event driven system as well, it enforces GUI updates to the thread, where the Display object is first created. For now I’ve made jars with the libraries for 7 different platforms:
The old swing version can be found here:
The ant script is easily extendable and can be found here:
In C and many other languages the float and double types exists, they’re the primary means for decimal types, however they can sometimes vary quiet a bit. For instance if you try to divide 1 by 3, you often get a result of: 0.33333333333333331.
The reason for this result is of course the floats lack of precision, a float is normally implemented in 32-bits, just like a 32-bit integer, it has it boundaries.
To show how bad these limits can be, I wrote some sample code in C, to check if an unsigned long as a float is equal to the same number + 1.
#include <stdio.h>
#include <limits.h>
int main() {
unsigned long i = 0, count = 0;
printf("A list of bad floats from 0 to %lu:\n", ULONG_MAX);
for (i = 0; i < ULONG_MAX; i ++) {
if (((float) i) + 1 == (float) i) {
// \033[E is move cursor to beginning of line.
// \033[K is clear line from cursor and to end of line.
printf("\033[E\033[K%12ld: (float) %15ld + 1 == (float) %15ld\n", ++count, i, i);
fflush(stdout);
}
}
printf("We counted %ld bad floats.\n", count);
return 0;
}
The result is pretty scary, however it’s rather easy to explain how this happens. Like the signed integer, a float has a signed bit at highest bit, after that comes an exponent of 8 bits, the exponent is of course binary exponentially. Last is the mantissa (or fraction), it fits the last 23 bits of the 32 bits.
Now it’s funny to see that some number actually derive more than +/- 1, for instance 1/3. Now this is not entirely game breaking for most calculations, but if you take some inaccuracy through many calculations, the loss of precision will accumulate more and more.
Now, it might be unclear of how we would express decimals, however the exponent is a signed byte, so it goes from -128 to 127, if the have a negative exponent, we get a mantissa * some number between 0 and 1.
Now for the double, it’s more precise, since it’s 64-bits and not 32 like the float. This means we still have 1 bit for the signed bit. For the exponent we now have 11 bits and for the mantissa we have 52. This means the lack of precision is smaller, and that this lack accumulates slower.
There’s of course no way to express all values accurately, as that would required unlimited memory.
I’m used to implement tree structures in object oriented languages, which of course is a nice thing to be able to do. For some time now I’ve been doing some coding in C, first the shell to learn more about pipes, forks and so on, this time it’s about implementing a tree structure in C, each node in the tree has 2 parents (a left and a right) and 2 children, the idea is more of a grid where a nodes left child can be the left parents, left childs, right child (if that makes sense).
The idea of this, is to try and take the maximum sum of a path, from the top to the bottom.
More over I’m parsing the tree structure from a file, where the structure is a bit like this (without the spaces at the beginning):
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
So for instance if we take 35, which is in the 4. line, it has 17 as left parent, 47 as right parent, 4 as left child and 82 as right child.
The struct I use for this is pretty basic:
struct node {
int value;
int sum;
struct node *parentleft;
struct node *parentright;
struct node *left;
struct node *right;
};
The sum is used to keep intermediate calculations, the value is the number the node repressents, the rest is pretty self self explainatory.
The parsing is done using a pointer for the current node, and a pointer to the top. There are 3 cases, which are all explained here:
Now for the recursive iteration through the tree:
The recursion is pretty basic, it simply calculates the sum of the child node to the left and right, returning the maximum of these upwards, the sum variable here stores the result, so if we encounter the same node again (which we will in big trees), we don’t have to calculate the sum again. This gives an extreme speed increase, since all sums only have to be calculated once:
int recursivesum(struct node *node) {
if (node->sum == 0) {
int left = 0, right = 0, sum;
if (node->left != NULL)
left = recursivesum(node->left);
if (node->right != NULL)
right = recursivesum(node->right);
sum = (left > right ? left : right) + node->value;
node->sum = sum;
return sum;
}
else
return node->sum;
}
Now there’s an apparent problem here, if the sum of a deep subtree is 0, it’ll get recalculated without the sum.
Now then, since I use malloc for the tree, it means everything in the tree is allocated on the heap. For this I made a function that frees a tree (or subtree), it’s pretty basic since it just checks if both children are NULL, if not we call recursively, then we make sure that the parents (if any) aren’t pointing to this node anymore. Then we free the current node and return.
void freetree(struct node *node) {
if (node->left != NULL)
freetree(node->left);
if (node->right != NULL)
freetree(node->right);
if (node->parentleft != NULL)
node->parentleft->right = NULL;
if (node->parentright != NULL)
node->parentright->left = NULL;
free(node);
}
Now this is how I chose to solve a problem found at project euler, which is why I don’t link the code in it’s full version.
Now, some time ago I wrote about a project I’m doing in my spare time, it’s called xkcdreader and is an example of how StAX, persistency and some network stuff can be used in java. Since I began the project I chose db4o for persistency. Db4o is an object database, which means it stores objects directly in the database without mapping, this is however not what the majority of databases today use. In the world today most dbms systems are relational, this is where JPA (Java Persistence API) comes into the picture.
JPA is a specification for mapping objects into relational databases and back again, this is normally known as Object/Relational-Mapping (or ORM for short). The reference implementation of the JPA specification is known as EclipseLink, EclipseLink is build on the old Oracle TopLink codebase. The new JPA 2.0 specification is not bound to EJB 3.0 (Enterprise JavaBeans) like the 1.0 specification was.
I took the old xkcdreader project and converted the database backend from using db4o to use JPA2 with EclipseLink in something like 5-10 minutes, all I did was annotate the Comic class, make a persistence.xml with a persistence-unit and implement the XkcdDao interface with the EntityManager from EclipseLink.
One of the backsides of using JPA2 and EclipseLink is that it’s around 5-6 mb in size, then you can add the size of the jdbc driver on top of that. I know it’s not alot, but compared to db4o or just a jdbc driver, it’s quiet a difference.
For the backend I chose SQLite, since it’s embedded, it uses SQL, it’s rather light, I do alot of my other programming with it, and it’s not particular bound to any platform. The SQLite JDBC driver I use is the one found here.
Here’s the persistence.xml I made in the short timeframe:
<?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0"> <persistence-unit name="Comics" transaction-type="RESOURCE_LOCAL"> <class>model.data.Comic</class> <properties> <property name="javax.persistence.jdbc.driver" value="org.sqlite.JDBC" /> <property name="javax.persistence.jdbc.url" value="jdbc:sqlite:xkcdreader.db" /> <property name="eclipselink.logging.level" value="WARNING" /> <property name="eclipselink.ddl-generation" value="create-tables" /> </properties> </persistence-unit> </persistence>
The driver is just the jdbc-driver, the url is the connection string used by DriverManager.getConnection(), logging and ddl-generation is specific to eclipselink, logging level is pretty self explaning, ddl-generation makes it possible to generate tables automatically. Some of the properties that I did not specify (for JPA) is user and password.
Some mandatory links:
Now, I know assert.h is not meant for unit testing, I know it’s got alot of limitations (like stopping the process on error, no easy way to organize, isolate or initialize test cases alone and so on). But for small function test driven development it’s rather decent, here’s an example of a function that checks if the first string (s) end with the same chars as the second string (t):
#include <assert.h>
#ifndef NULL
#define __DEF_NULL
#define NULL 0
#endif
/**
* Takes 2 strings, if s ends with t, returns 1, else 0.
*/
int strend(const char *s, const char *t);
int main() {
assert(strend(NULL, NULL) == 0);
assert(strend(NULL, "test") == 0);
assert(strend("test", NULL) == 0);
assert(strend("hej", "dav") == 0);
assert(strend("hejsa", "jsa") == 1);
assert(strend("hej", "davhej") == 0);
assert(strend("davs", "davs") == 1);
assert(strend("hejsa", "hejsb") == 0);
assert(strend("hejsa", "heisa") == 0);
assert(strend("hejsa", "hejba") == 0);
assert(strend("jeg er glad", "r glad") == 1);
assert(strend("hejsa", "ejs") == 0);
return 0;
}
int strend(const char *s, const char *t) {
const char *ptrs = s, *ptrt = t;
if (s == NULL || t == NULL)
return 0;
while (*ptrs != '\0')
ptrs++;
while (*ptrt != '\0')
ptrt++;
while (*ptrs == *ptrt) {
if (ptrs == s)
return ptrt == t ? 1 : 0;
else if (ptrt == t)
return 1;
else {
ptrt--;
ptrs--;
}
}
return 0;
}
#ifdef __DEF_NULL
#undef NULL
#endif
For real unit testing capabilities in c, I’ll have a loop at cunit or similar.
I’ve used the last week or so programming a simple shell in c, for now it features some internal commands like cd, ls, environ, help, quit, etc.
One of the big challenges in the future of the project is to make it compile on more systems than linux, for instance if reads the absolute executable path with readlink() from /proc/pid/exe, which is very specific.
The shell should still be filled with bugs here and there, I’ll start bug hunting tomorrow.
you can find the project on git as usual, keep in mind that I use cmake instead of autotools.
This is my first real code written in perl, and I must say it’s rather satisfying, it’s a simple fibonacci calculator using a hashtable (hash value).
So, here’s the code:
#!/usr/bin/perl
%table = (0 => 1, 1 => 1);
for ($i = 0;$i < 30;$i++) {
print "fibo for ".$i.": ".fibo($i)."\n";
}
sub fibo{
my($f) = $_[0];
if ($f < 0) {
print "Input is less than 0: ".$f."\n";
return -1;
}
if (exists $table{$f}) {
return $table{$f};
}
else {
if (not exists $table{$f - 2}) {
$table{$f - 2} = fibo($f - 2);
}
if (not exists $table{$f - 1}) {
$table{$f - 1} = fibo($f - 1);
}
$table{$f} = $table{$f - 2} + $table{$f - 1};
return $table{$f};
}
}
What's interesting is the use of my($var) for reassigning parameters to the function to internal variables. Moreover the if and else statements demands {} after the condition, which I mostly like as optional. Besides that it looks like a neat language for writing scripts and regex statements.
One thing I'm lacking at the moment (should be obvious) is a way of concatenating things into a string, to avoid mass printing everything in a separate function call.
Edit: Concatenation is done by using the '.', the code has been updated to reflect this.
One of the great things about java was the logging framework under java.util.logging, it was simple, extendable and efficient. I’ve tried to take those properties and implement a logging framework for the .net platform in c#, for now it features a logger with some logging level, these determine if a log event should get filtered, there are the usual: fine, info, warning and severe. For the actually logging you implement something called a handler with a Write method, this method takes a log event with a time, level and message.
This is very similar to java’s implementation, but why change something that works well ?
I’ll be updating it with features (new ready-made handler implementations, info about the method that made the logging etc) and tweaks from time to time, for now it works.
The DEFAULT_LOGGER on the Logger class can be used to log to stderr, without having to create a logger and implement your own handler.
Feel free to try it, feedback is welcome.
I’m used to the java way of xml, which is using StAX. In C# there are some default namespaces for xml, these are:
For this post I’m only going to use 2 classes from the System.Xml namespace, namely XmlTextWriter and XmlTextReader. These can be used to read and write xml in a way very close to what I’m used to in StAX.
The writer works just as you’d expect, there’s a WriteStartDocument() for witing the xml header, WriteStartElement() for writing start elements, WriteAttributeString() for writing attributes to elements. When closing elements simply used WriteEndDocument() and WriteEndElement().
For the reader there’s a bit of a iterative touch to it, just as with StAX, for instance you usually have an outer while loop, which iterates on Read(). Whenever read is true, you can switch the result with a XmlNodeType. To get elements simply use the Element type, to get an end of an element use EndElement. When inside an element with attributes you go through the attributes with a for loop, counting to the number of attributes, the number is the AttributeCount property on the reader. You move the reader through the properties with the method MoveToAttribute(int i), where i is the number of the attribute (starting from 0 of course).
The reader has a Name and Value property, these change depending on what element the reader currently is at, if the current element is an attribute, then the name and value is the name and value of that attribute. For elements the element name is Name.
Here’s a simple example using this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
namespace xmltest {
class Program {
static void Main(string[] args) {
XmlTextWriter writer = new XmlTextWriter(new StreamWriter("test.xml"));
writer.WriteStartDocument();
writer.WriteStartElement("users");
writer.WriteStartElement("user");
writer.WriteAttributeString("name", "svend");
writer.WriteAttributeString("pass", "1234");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
System.GC.Collect();
Console.WriteLine("all done.");
XmlTextReader reader = new XmlTextReader(new StreamReader("test.xml"));
while (reader.Read()) {
switch (reader.NodeType) {
case XmlNodeType.Element:
Console.WriteLine("start: {0}", reader.Name);
if (reader.AttributeCount > 0)
for (int i = 0;i < reader.AttributeCount;i++) {
reader.MoveToAttribute(i);
Console.WriteLine("attrib: {0} - value: {1}",
reader.Name, reader.Value);
}
break;
case XmlNodeType.EndElement:
Console.WriteLine("end: {0}", reader.Name);
break;
}
}
reader.Close();
Console.WriteLine("done");
Console.Read();
File.Delete("test.xml");
}
}
}
The code makes a users element, with a user element with 2 attributes (user and pass). The reads it back, since the user element is empty, it does not contain an end element.
i’ve heard you can dump stuff from ado.net to xml, read entire xml documents with XmlDocument and XmlDataDocument. I suspect the System.Xml.Serialization namespace contains some way to serialize objects to xml, but I’ll have to test that some other time.