Skip to content

Making fun things from the knowledge of evolution

Evolution is a powerful mechanism, and the powerful source that is behind it is decent with modification plus selection. In nature, it has taken us from simple chemical reactions to complex self-aware organism over billions of years. The structure of any living mammal is very complex, and biology is filled with complicated concepts, and nothing would make any sense if we didn’t know about the very simple concept of evolution. In nature, evolution explains why fossils of different ages look different, and it explains the origin of very complex structures like the cell, the immune system and the human brain, and this knowledge casts light over areas that doesn’t have anything to do with biology, like computer science and computer programming.

Designed structures are usually simple and have one or a few purposes, while evolved structures usually are complex and have multiple functions. Designed structures usually are things. Obstacles, roads, walls, jugs. Evolved structures usually work as things. Pipes, connections, obstacles, skeletons. This is because evolved structures come about without a given purpose, but are maintained and further developed if the structure is useful.

Can we use the knowledge of our origin get some fun out of our computer? Yes! I have mentioned John Conway’s game of life earlier.

This is EvoLisa. It is a program that draws polygons and compares them to a picture. Then it changes the polygons slightly, and again compares them to a picture. Changes that make the polygons look more like the picture are kept, other changes are discarded. The result is a computer generated vector based pictures that looks like the original picture. More generations of change and selection, gives a computer generated picture that is more like the original picture. Here, selection is based on comparison to the original picture, in nature, selection is based on what organisms till survive and reproduce.

Categories: Science.

Tags:

The simplest query tool ever

A colleague wanted to do a database query from a computer without any database client. He needed a tool that allowed him to type in a SQL query, and receive a sortable grid with the result set. All of these features are built-in in the .NET Framework, and it didn’t take me more than 2 minutes to do an exe file with these features using Visual Studio 2010. I used .NET 2.0 because these basic features are available in that version, and he did not want to install a newer version of the .NET Framework.

This is the user interface: A tab strip with three tabs. One for a connection string, one for the query and one for the result grid. The first two contains a textbox each, and the third contains a DataGridView control. Also, the program has a status bar with a label and a toolstrip with two buttons; one for testing the connectionstring that the user enters in the textbox of the first tab, and one for executing the query and presenting the result in the grid.

The program consist one variable and four event handlers in one form. The variable holds the result set.

Private Ds As DataSet

The first function responds to the Load event of the form. This function restores the last values that from the textboxes. This is just for user convenience.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles MyBase.Load
    txtCn.Text = CType(Application.UserAppDataRegistry.GetValue("Cn", ""), String)
    txtQuery.Text = CType(Application.UserAppDataRegistry.GetValue("Query", ""), String)
End Sub

The second function responds to the Close event of the form. This function saves the values from the textboxes so that they can be restored (in the Load event) in the next session. Also, if needed, it disposes the dataset variable.

Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) _
Handles Me.FormClosed
    Application.UserAppDataRegistry.SetValue("Cn", txtCn.Text)
    Application.UserAppDataRegistry.SetValue("Query", txtQuery.Text)
    If Not Ds Is Nothing Then
        Ds.Dispose()
    End If
End Sub

This is the handler for the test button. It simply connects to the given data source, and tells if it succeeds or fails.

Private Sub btnTestConnection_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles btnTestConnection.Click
    'Jump to the connection tab (the first one).
    TabControl1.SelectedTab = tabConnection

    'Do the test.
    Me.Cursor = Cursors.WaitCursor
    Dim Success As Boolean = False
    Try
        Using Cn As New SqlClient.SqlConnection(txtCn.Text)
            Cn.Open()
            Success = (Cn.State = ConnectionState.Open)
            Cn.Close()
        End Using
    Catch ex As Exception
    End Try
    Me.Cursor = Cursors.Default
    If Success Then
        lblStatus.Text = "Connection test succeeded."
        MessageBox.Show("Connection test succeeded.", Me.Text, _
            MessageBoxButtons.OK, MessageBoxIcon.Information)
    Else
        lblStatus.Text = "Connection test failed."
        MessageBox.Show("Connection test failed.", Me.Text, MessageBoxButtons.OK, _
            MessageBoxIcon.Error)
    End If
End Sub

Finally, this is the handler for the execute button.

Private Sub btnExecute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles btnExecute.Click
    'Remove the current data table as data source of the grid.
    DataGridView1.DataSource = Nothing

    If Not Me.Ds Is Nothing Then
        'If there is an old data set in memory, dispose that.
        Me.Ds.Dispose()
        'To remember that no data is present, set the variable to NULL.
        Me.Ds = Nothing
    End If

    'Jump to the result tab (the third one).
    TabControl1.SelectedTab = tabResult

    'Do the query and bind the result. Quick and dirty error "handling".
    Me.Cursor = Cursors.WaitCursor
    Try
        Using Cn As New SqlClient.SqlConnection(txtCn.Text)
            Cn.Open()
            Using Cmd As New SqlClient.SqlCommand(txtQuery.Text, Cn)
                Using Da As New SqlClient.SqlDataAdapter(Cmd)
                    Ds = New DataSet()
                    Da.Fill(Ds)
                    If Ds.Tables.Count > 0 Then
                        DataGridView1.DataSource = Ds.Tables(0)
                        If Ds.Tables.Count > 1 Then
                            Me.Cursor = Cursors.Default
                            MessageBox.Show("More than one dataset was returned.", "Query", _
                                MessageBoxButtons.OK, MessageBoxIcon.Information)
                        End If
                    Else
                        Me.Cursor = Cursors.Default
                        MessageBox.Show("No dataset was returned.", "Query", _
                            MessageBoxButtons.OK, MessageBoxIcon.Information)
                    End If
                End Using
            End Using
            Cn.Close()
        End Using
        lblStatus.Text = "Success."
    Catch ex As Exception
        lblStatus.Text = "Failed. " & ex.Message
            Me.Cursor = Cursors.Default
        MessageBox.Show(ex.Message, "Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
    Me.Cursor = Cursors.Default
End Sub

So, making a personal query tool doesn’t have to take more than a couple of minutes in .NET.

Categories: Visual Basic 10.

Tags: ,

ASP.NET 4.0: Diagrams

To get your hands on this new and cool feature, create an ASP.NET 4.0 application or web site from within Visual Studio 2010. Check the Data section of the Toolbox window for a new control called Chart. Dragging out a Chart onto a web page creates the following code:

<asp:Chart ID="Chart1" runat="server">
  <Series>
    <asp:Series Name="Series1">
  </asp:Series>
  </Series>
    <ChartAreas>
      <asp:ChartArea Name="ChartArea1">
    </asp:ChartArea>
  </ChartAreas>
</asp:Chart>

There is a huge amount of properties available for the chart. They control the look of the chart, the chart type among other things. I don’t have any databases installed on this computer, so to get some data to do a chart from; I connect the control to a data source that represents the system database master. I use the following query to get a bunch of large numbers:

SELECT [name],[number] FROM dbo.spt_values WHERE [number]>17000

I use number as Y value member.

This is what I have to do to get the fully functional chart! Fooling around with chart types and visual properties is dangerously amusing.

If you haven’t got a database server at all, you can quickly create an object data source in Visual Basic, and assign that to your chart. Connection this code…

Public Class MyChartData

    Private mValue As Integer

    Public Sub New(ByVal Value As Integer)
        Me.mValue = Value
    End Sub

    Public ReadOnly Property Value() As Integer
        Get
            Return Me.mValue
        End Get
    End Property

    Public Shared Function GetItems() As MyChartData()
        Dim Ret As New List(Of MyChartData)()
        Ret.Add(New MyChartData(10))
        Ret.Add(New MyChartData(20))
        Ret.Add(New MyChartData(15))
        Ret.Add(New MyChartData(25))
        Return Ret.ToArray()
    End Function

End Class

…gives you this beautiful result:

Ah, the simplicity! Aaaaah, the power!

Categories: Visual Basic 10.

Lite tramsande med GDI+ i Visual Basic

Detta ser inte speciellt vackert ut, men jag är mycket imponerad över vad man kan göra med namnrymden System.Drawing och lite GDI+ i Visual Basic.

Detta är några futtiga kodrader som ritar på två image-objekt. Det ena ritas ny grafik på ovanpå den befintliga (lite sinuskurvor), och den andra bilden rensas innan en gul boll, en svart text och en vit text ritas på. Innan bilden med sinuskurvorna sparas, ritas bilden med texterna och bollen ovanpå den första. Om inte annat kan man fundera på vilka möjligheter System.Drawing egentligen har.

Categories: General.

The ups and downs of Visual Studio 2010: Fonts and scaling

The first time I head of the zoom feature of VS2010 was in a talk by Dag König at Microsoft. The level of readability is a very important question for me, and the font rendering of Windows (Clear Type) is superb compared to the blurry font rendering that Macintosh has. The big question, does the zoom feature affect the font rendering of the text editor? To the left, Visual Studio 9 with Consolas 8. To the right, Visual Studio 2010 with Consolas 8.

VS2010 still uses clear type, and the readability is still there. The hue is slightly reduced, if the anti aliasing is too gray, the text will appear blurry as it does on a Macintosh that only uses a gray scale for smoothing edges. The upper side of reducing the hue is that smoothing works better with text in different colors.  In VS2010, the default color for a class keyword in Visual Basic is cyan as opposed to black in VS9.

And the zooming feature: Hold down Ctrl and use your mouse wheel. Not a feature I use every day – I use a font size that I can read without zooming, but really cool to use in presentations.

The .NET Framework lets you control how text is rendered in your programs. The property of the Graphics object you use to control this is called TextRenderingHint. Examine this code:

Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) _
    Handles Me.Paint
    Using B As New System.Drawing.Bitmap(300, 300)
        Using G As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(B)
            Using F As New System.Drawing.Font("Consolas", 10)
                G.FillRectangle(Brushes.White, 0, 0, 300, 300)

                'Regular smoothing
                G.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAlias
                G.DrawString("Hello", F, Brushes.Black, 10, 10)

                'Regular smoothing with grid fit
                G.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAliasGridFit
                G.DrawString("Hello", F, Brushes.Black, 10, 25)

                'Clear Type smoothing with grid fit
                G.TextRenderingHint = Drawing.Text.TextRenderingHint.ClearTypeGridFit
                G.DrawString("Hello", F, Brushes.Black, 10, 40)

            End Using
        End Using
        e.Graphics.DrawImage(B, 0, 0)
    End Using
End Sub

The option called AntiAlias renders text in a similar way to the Macintosh. The text appears blurry, but the outcome has true proportions, meaning that what you see on screen is a blurrier version of what you would see on a printed version. This option works best in high resolutions and for print previewing.

The AntiAliasGridFit makes the text less blurry, because letters align to the pixel grid of the screen. The downside is that character spacing is incorrect, but readability is much higher. This option works best with CRT screens.

The ClearTypeGridFit also aligns characters to the pixel grid, but it uses clear type. This option works best with a flat screen.

The output from the above code is shown here:

Categories: Visual Studio 10.

The ups and downs of Visual Studio 2010: Call Hierarchy

The function that finds all references to a function or a variable has been in Visual Studio for a few versions now. VS2010 has a similar feature called Call Hierarchy. Right click on any function definition or function call, and click View Call Hierarchy. This shows the Call Hierarchy window with a tree structure that displays what other functions are called from the function you clicked on, and who is calling it. This can help discover unused code and understanding the call stack of a program. In C#, not in Visual Basic. The View Call Hierarchy isn’t there if you right click on a Visual Basic function in VS2010 Beta 2. A quick look at Microsoft Connect tells me that the subject has been brought up, but nothing else has happened yet.

One thing that does work, is the automated generation of sequence diagrams. VS2010 not only does this automatically, but the output is also editable. Objects on the diagram can be resized, moved or deleted, and new items can be added. All you have to do is click Generate Sequence Diagram.

Categories: Visual Studio 10.

Make a HTML gallery from your photos

The latest feature in PhotoName: Make a HTML gallery from a bunch of photos!

Download PhotoName from here. If you have a previous version installed, remember to uninstall that first (from the Windows Control Panel).

Categories: General.

Tags:

PowerShell and Windows 7

I should have posted this long ago, but here it is. I did not manage to install PowerShell 2.0 on Windows 7. Windows complained about a newer version that already was supposed to exist on the system. And yes, just open the Run dialog (Win+R) and type powershell, and there it is.

To start the graphical version, type powershell_ise in the Run dialog.

If you want to be able to start it without doing any typing, you can right click on it in the taskbar, and select Pin this program to taskbar.

Categories: PowerShell.

Tags:

Dual coordinate systems

This picture illustrates the different coordinate systems that Monkeybone is using. Both lines are drawn from 0, 0 to 30, 30. The yellow line is drawn using the coordinate system of the image itself, and the green line is drawn using the coordinate system of the diagram.

The syntax is the same for DiagramLine and Line, the coordinate system is the only difference. This means that you can choose to use named arguments or points encapsulated by parenthesis. This is the source for the above image:

//Set size and background color.
Clear 320x200 #667788

//Just to make it more visible, set line thikness to 3 pixels.
Set Line Thikness To 3

//Create a diagram.
Diagram #8899aa X:20 Y:20 W:280 H:160

//Draw a yellow line on the image from 0,0 to 30,30.
Line #ffff00 (0,0) (30,30)

//Draw a green line on the diagram from 0,0 to 30,30.
DiagramLine #00ff00 (0,0) (30,30)

Note: A line can be anything from one to 1000 pixels wide.

Categories: General.

Tags:

Compressing Genesis

From here, I have downloaded Genesis to see what the GZip stream is good for. GZip is suitable for compressing text, because the file format is totally clean (uncompressed) and the Deflate algorithm manages therefore to compress text to a high ratio. And I like the simile that deflating Genesis leaves very little left. It sort of works with my naturalistic worldview.

The function, CompressText is unchanged, so I only show the Main subroutine.

Sub Main()

    'Load genesis.
    Dim S As String
    Using Sr As New System.IO.StreamReader("genesis.txt", System.Text.Encoding.UTF8)
        S = Sr.ReadToEnd()
        Sr.Close()
    End Using

    Console.WriteLine("{0} characters, {1} bytes.", S.Length, S.Length * 2)

    'Compress it, and display the result.
    Dim B() As Byte = CompressText(S)
    Console.WriteLine("Compressed to {0} bytes.", B.Length.ToString())

    Console.WriteLine("Difference: {0}%", (((S.Length * 2) / B.Length) * 100).ToString("n0"))
End Sub

In this case, the uncompressed version is 588% of the size of the compressed version.

Categories: Visual Basic 9.

Tags: