Friday, July 31, 2009

How to work with the HashTable collection in Visual Basic .NET

From
http://support.microsoft.com/kb/307933

I keep forgetting how to test membership or how to retrieve objects from the Hashtable. It's actually too simple to be well-documented :)

You just use

Dim table as New HashSet(Of String)
table("foo") = "foo"

To retrieve, just use
table("foo")

which would return "foo".

Usually you might want to store something more complex under the key, but this is all that's needed to add to a set and test set membership - which is what I usually want.

Thursday, July 30, 2009

Customer Attrition System Patent

When working for a US Bank, I developed a system for predicting customer attrition. As far as such systems go, it was pretty straightforward - construct features, run it through a decision tree, do some pruning, generate predictions, and check the accuracy of the predictions on an on-going basis.

I do remember when time came to apply for the patent that I did insist that I be first inventor as having contributed almost all of the intellectual and programming work for the project. I had done a M.Sc and ABD in machine learning, and published in the area.

There was a program manager on this who had to have cross-validation explained to him.

I see now that my name is at the bottom of the list. Oh well, at least they didn't take me off completely.

http://www.wipo.int/pctdb/en/wo.jsp?wo=2004107121

Effective Generalization of Relational Descriptions

Here's a paper I wrote on inductive learning, now known as inductive logic programming.

I presented the paper at a workshop in Princeton, and Ross Quinlan told me that Steve Muggleton was working on something similar - his GOLEM program - before he coined the term ILP (inductive logic programming).

http://www.aaai.org/Papers/AAAI/1990/AAAI90-131.pdf

Kent Watanabe's videogame Music & improv channel

This is my son's music channel for Videogame Music & Improv. Pretty interesting stuff.

http://www.youtube.com/kentokhromatic

I shouldn't be proud - I had nothing to do with his accomplishments, it's all him. But I am happy for him.

Lance Armstrong - no doping

He may not have won the Tour de France, but his performance has sure silenced his dectractors who accused him of not being clean.

http://www.facebook.com/home.php#/lancearmstrong?ref=nf

Wednesday, July 22, 2009

VB C# .NET connection strings

There is an entire website dedicated to this subject: http://www.connectionstrings.com/
---------------

Using VB 6 and Sql Server 2000.
In my code I am using open dialog control for selecting the database file, once I selected the database(Dual_ACS.mdf) file, it will appear in the textbox (path and filename)
Textbox name = databasetext
My code.Cn.ConnectionString = "Provider=SQLOLEDB.1; Persist Security Info=False;User ID=" & UName & ";Password=" & PWord & ";InitialCatalog=DUAL_ ACS; Data Source=" & databasetext & ""Cn.Open
But it is showing error. How to write a Proper SQL Connection String?
Need VB 6 code help

Tuesday, July 21, 2009

Monitor Graphics Card Usage

Rivatuner - http://www.guru3d.com/category/rivatuner/
RivaTuner is a complete powerful tweaking environment, providing you everything you may need to tune NVIDIA GPU based display adapters. The widest driver-level Direct3D / OpenGL and system tuning options, flexible profiling system allowing to make custom settings on per-application basis, both driver-level and low-level hardware access modes, unique diagnostic and realtime hardware monitoring features and exclusive power user oriented tools like built-in registry editor and patch script engine make RivaTuner's feature set absolutely unmatched. RivaTuner supports all NVIDIA display adapters starting from Riva TNT family up to the latest GeForce 7 series and widest range of NVIDIA drivers starting from the oldest Detonator 2.08 up to the newest ForceWare drivers family.

Monday, July 20, 2009

VB .NET Get table Column Names

A useful snippet found at (strange name for a site with VB code) http://www.java2s.com/Code/VB/Database-ADO.net/GettablecolumnName.htm

' Display the column names
Dim dc As DataColumn
For Each dc In ds.Tables(0).Columns
Console.Write("{0,15}", dc.ColumnName)
Next

Extracting all Characters after last occurrence of a pattern C#

Question posted on Stackoverflow.com: http://stackoverflow.com/questions/1153630/extract-all-characters-after-last-occurrence-of-a-pattern-c

Hello,

The strings are of the following pattern

1.0.0.0 1.0.0.1 1.0.0.2 ... ... ...

I am looking for a code which will read the last created string and increment the last numeral by 1 and save it as a new string.

How do I do it?

Best Regards,

Magic

---

My response:



Imports System.Text.RegularExpressions
Module Module1

Sub Main()
Dim matchC As
MatchCollection = Regex.Matches("111.222.333", "\d+")
Dim i As Integer = 1
For Each x In matchC
Console.Write(i.ToString & " ")
Console.WriteLine(x)
i = i + 1
Next

' remember to check to make sure case no matches occur in your real code.
Console.WriteLine("last number is " & matchC.Item(matchC.Count - 1).ToString)
Console.ReadLine()
End Sub
End Module

Useful reference: http://msdn.microsoft.com/en-us/library/ms972966.aspx
Regular Expressions in ASP.NET

Sunday, July 19, 2009

Why did you choose programming as a profession?

Asked on stackoverflow.com:

http://stackoverflow.com/questions/362376/why-did-you-choose-programming-as-a-profession

My response --

I wanted to be a poet but my poetry sucked.

My Mom wanted me to become a doctor, but I didn't enjoy dissecting the pig in biology class and the thought of doing this on humans was ...a little sickening.

My Dad was a physicist and I had some talent for that, but frankly I had no chance as someone dabbling in pre-med and Engish against guys taking nothing but math and physics courses.

Luckily I remembered a friend told me (a Berkeley EE grad) that I would probably be good at programming, since I liked to play GO and was good at that. I tried a few programming courses and was hooked.

Waterloo Cup Open Go Tournament

Recently I participated in the Waterloo Cup, and managed to come in 5th. Probably because the tournament was so small -- but a university like Waterloo, with lots of students from mainland China can provide a lot of tough competition.

http://hsu.ahed.ca/waterloo/

The tournament was won by a 10 year old second generation Chinese-Canadian. At first I thought that Canadians wouldn't have a chance of winning major Go tournaments, but on reflection I realize that Canada is a very attractive country for immigrants, and that there seems to be a greater passing on of cultural traditions among the Chinese community than there was among the Japanese community. Seeing Jia Ning Gan win gives lots of hope for strong Canadian players in the future.

I once almost won the Quebec open -- as a 3rd dan, I managed to beat 3 5-dans, including the eventual winner, Harry Gonshor a doctor from New Jersey. It became a 5-way tie for first, with the McMahon tie-breaking system determing the actual winner. At the time I regretted not playing better in 1 game against another 3-dan where i was leading for most of the game by a wide margin and finally lost by 1/2 a point.

But now, I am glad that Harry won the tournament. He was an immensely irritating player to play against, constantly talking to himself about the game in a way calculated to provoke his opponents into making emotional mistakes. But, he obviously loved Go a lot, had a great sense of humor, and I'm sure winning the Quebec Open was very satisfying for him. He died a short time later and I think that he got a lot more out of his tournament win than I would have.

Saturday, July 18, 2009

techInterview.org - Joel on Software - array manipulation question - VB solution

This question was asked on the techInterview.org list on Joel on Software:

http://discuss.techinterview.org/default.asp?interview.11.768781.6

array manipulation

Given an array with some repeating numbers. Like 12,6,5,12,6.
output should be printed as 12,12,6,6,5; i.e, all occurences of the no. should come together and nos. should come in the order given in the array. Suggest a optimal solution to this. sanjay kasat

---
Here's my VB solution.

Here's a VB solution, using a Dictionary. Essentially this is a hash solution.

Module Module1

' data structure for recording counts
Public Class Node
Private m_count As Integer = 0
Private m_value As Integer

Public Sub New(ByVal x As Integer)
m_value = x
m_count = 0
End Sub

Public Shadows Function toString()
Return m_value.ToString()
End Function

Public Property count() As Integer
Get
Return m_count
End Get
Set(ByVal value As Integer)
m_count = value
End Set
End Property

Public Property val() As Integer
Get
Return m_value
End Get
Set(ByVal value As Integer)
m_value = value
End Set
End Property
End Class

' to record ordering
Dim m_list As List(Of Node) = Nothing

' to record counts
Dim m_hash As Dictionary(Of Integer, Node) = Nothing

'''
''' Initialize data structures for a new run
'''

Private Sub init()
m_list = New List(Of Node)
m_hash = New Dictionary(Of Integer, Node)
End Sub

'''
''' Add a new element from the input list
'''

Private Sub add(ByVal x As Integer)
Dim p As Node
Try
p = m_hash(x)
p.count = p.count + 1
Catch ex As Exception
p = New Node(x)
p.count = 1
m_list.Add(p)
m_hash(x) = p
End Try
End Sub

Public Sub outputResults()
For Each x In m_list
For i = 0 To x.count - 1
Console.Write(x.val & " ")
Next
Next
Console.WriteLine()
End Sub

Public Sub test1()
Dim x As New List(Of Integer)
x.Add(12)
x.Add(13)
x.Add(12)
x.Add(2)
x.Add(12)
x.Add(2)
x.Add(12)
x.Add(14)
init()
For Each y In x
add(y)
Next
outputResults()
End Sub

Sub Main()
test1()
Console.ReadLine()
End Sub

End Module

Friday, July 17, 2009

Round integer to nearest high number

This was a C language question posed on StackOverflow.com.
(Apologies in advance for the formatting - blogspot.com doesn't format VB or C or any code well - but copy and paste into Visual Studio for formatted version).

I have an array of ints like this: [32,128,1024,2048,4096]

Given a specific value, I need to get the closest value in the array that is equal to, or higher than, the value.

I have the following code

private int GetNextValidSize(int size, int[] validSizes)
{ int returnValue = size;
for (int i = 0; i < validSizes.Length; i++)
{
if (validSizes[i] >= size)
{
returnValue = validSizes[i];
break;
}
}
return returnValue;
}

It works, but is there any better/faster way to do it? The array will never contain more than 5-10 elements.

http://stackoverflow.com/questions/1143451/round-integer-to-nearest-high-number-in-array

Here's my response:


It doesn't work. Here are 3 test cases where it fails. In fact, the function interface doesn't have any return result for failure.

I wrote a corrected version, GetNextValidSize2. Since there is no way to return a failure message, I throw an exception for those cases. Here are the results of the run:

test1 : GetNextValidSize failed test1 : GetNextValidSize2 passed test2 : GetNextValidSize Object reference not set to an instance of an object. test2 : GetNextValidSize2 validSizes is nothing test3 : GetNextValidSize passed test3 : GetNextValidSize2 No items in validSizes

By the way, LINQ may be simpler or easier, but it can hardly be more efficient. It can probably be equally efficient if the query optimizer/CLR optimizer work well.

Here's the code - it's in VB since that's what I'm using at the moment, don't want to switch mental gears:

Module Module1

'''
''' Error - does not work if validSizes is Nothing, or has 0 elements, or if
''' the list contains a validSize that is not the closest one before a closer one,
''' or there are no valid sizes.
'''

Public Function GetNextValidSize(ByVal size As Integer, ByVal validSizes As List(Of Integer)) As Integer
Dim returnValue As Integer = size

For i As Integer = 0 To validSizes.Count - 1 Step 1
If validSizes.Item(i) >= size Then
returnValue = validSizes.Item(i)
Exit For
End If
Next
Return returnValue
End Function

'''
''' Returns the closest item in validSizes that is >= size. Throws an exception if one cannot
''' be found.
'''

Public Function GetNextValidSize2(ByVal size As Integer, ByVal validSizes As List(Of Integer)) As Integer
Dim closestValue As Integer = Integer.MaxValue
Dim found As Boolean = False

If validSizes Is Nothing Then
Throw New Exception("validSizes is nothing")
End If

If validSizes.Count = 0 Then
Throw New Exception("No items in validSizes")
End If

For Each x In validSizes
If x >= size Then
found = True
If x < closestValue Then
closestValue = x
End If
End If
Next
If Not found Then
Throw New Exception("No items found")
End If
Return closestValue
End Function

'''
''' Output the result of a test.
'''

Public Sub outputResult(ByVal testName As String, ByVal result As Boolean, ByVal funcName As String)
Dim passFail As String
If result Then
passFail = " passed"
Else
passFail = " failed"
End If
Console.WriteLine(testName & " : " & funcName & passFail)
End Sub

'''
''' Output the result of a test where an exception occurred.
'''

Public Sub outputResult(ByVal testName As String, ByVal ex As Exception, ByVal funcName As String)

Console.WriteLine(testName & " : " & funcName & " " & ex.Message())
End Sub

'''
''' Test with a list of 3 integers
'''

Public Sub test1()
Dim aList As New List(Of Integer)
aList.Add(5)
aList.Add(4)
aList.Add(3)
Dim result = GetNextValidSize(3, aList)
outputResult("test1", 3 = GetNextValidSize(3, aList), "GetNextValidSize")
outputResult("test1", 3 = GetNextValidSize2(3, aList), "GetNextValidSize2")
End Sub

'''
''' Test with a null reference
'''

Public Sub test2()
Dim aList = Nothing
Try
outputResult("test2", GetNextValidSize(3, aList), "GetNextValidSize")
Catch ex As Exception
outputResult("test2", ex, "GetNextValidSize")
End Try
Try
outputResult("test2", GetNextValidSize2(3, aList), "GetNextValidSize2")
Catch ex As Exception
outputResult("test2", ex, "GetNextValidSize2")
End Try
End Sub

'''
''' Test with an empty array.
'''

Public Sub test3()
Dim aList As New List(Of Integer)
Try
outputResult("test3", GetNextValidSize(3, aList), "GetNextValidSize")
Catch ex As Exception
outputResult("test3", ex, "GetNextValidSize")
End Try
Try
outputResult("test3", GetNextValidSize2(3, aList), "GetNextValidSize2")
Catch ex As Exception
outputResult("test3", ex, "GetNextValidSize2")
End Try
End Sub

'''
''' Run all tests.
'''

Public Sub testAll()
test1()
test2()
test3()
End Sub

Sub Main()
testAll()
Console.ReadLine()
End Sub

End Module

Thursday, July 2, 2009

User friendly framework for personal websites

Filing this for future reference:

http://stackoverflow.com/questions/1072920/user-friendly-framework-for-personal-website

Tips for Making Code Last

This was asked in StackOverflow:

http://stackoverflow.com/questions/1073473/tips-for-making-code-last/1074596#1074596

I have found the following tips useful:

1.Use meaningful variable/member/class/function names, even if your fingers hurt from the typing.

2.Comment each class and function, procedure (unless it is boilerplate e.g. set/get methods) accurately, concisely. If this is not possible or easy then probably your function/sub is too complex.

3.Keep functions/procedures small - 5-10 lines. This helps keep them easy to validate, test, debug, document, and use.

4.When you review your code (usually during the course of bug fixes or further development) and something strikes you as off, document the issue or fix it. Often later you will find a bug and it will be related, or you will use the code in a way that violates some of these assumptions made and the documentation will help you.

5.Keep a working log of the changes you are making throughout the day. When you save to the repository, you can cut and paste the part of the log from the last save to the current place, so your code repository changes are well-documented. Save the logs separately (repository, email, blog).

6.Factor your code into independent, reusable components. There is a fine line here between over-engineering, KISS, and generalization, so you have to weigh the pro's and con's. The advantage of making reusable components is that you tend to design the component better to make few assumptions, to have clean interfaces, to have few dependencies -- all of which makes for better code. Also, the reusable components get used in more places, so the code tends to be better tested.

7.Throw exceptions or use assertions wherever your code might fail depending on how it is called, i.e. parameters passed or dependency on any external factors to the function/procedure. "Never happens" only exists in theory -- the exceptions make narrowing down bugs much easier.

8.Keep a running todo list/bug list for things that need to be done or enhancements as part of your log. Chances are this list will never be completed, because as fast as you can complete items on the list new ones will be added. At some point, the list will consist of low-priority, or deferrable items, and you move to production or to a new release. How many years has MS word been worked on and is it complete now?