## Bad words: “Refactoring”

December 21, 2014 at 3:10 PM

Also “Code refactoring”. A verb used in programming, the official meaning is

the process of restructuring existing computer code without changing its external behavior

the actual meaning is

the process of restructuring existing computer code hopefully without changing its external behavior

I think the original meaning was quite specific, referring to thorough changes in the internal structure of code, but now it is used for any and all internal changes that are not meant to change functionality. For example, under ‘refactoring’ Microsoft Visual Studio lists trivial changes like renaming or reordering parameters:

So when someone says ‘I refactored such and such’ it might mean more or less anything, including just changing some method names.

Posted in: Opinion | Programming

Tags: , ,

## Bad words: “Leverage”

December 13, 2014 at 5:58 PM

Used extensively in programming as a verb, it comes up 47 times in my current e-mail:

given that most of the services that leverage this today already have SomeService dependency

I suggest implementing a way to short circuit this loop and leverage it by overriding Cancel() in the derived sensor class

I imagine fairly soon in the future we'll want to leverage this for the SomethingApp as well

It means simply ‘use’ – that is even shorter. ‘Leverage’ implies (at least) some kind of multiplication, that does not means much when speaking about software modules or functions.

…but of course it sounds better to use ‘leverage’: we just don’t randomly ‘use’ things here, we actually ‘leverage’ them.

See also Microspeak.

Posted in: Opinion | Programming

Tags: , ,

## Slow Surface Pro 2 WiFi connection

March 16, 2014 at 3:10 PM

Recently I switched from a Dell Latitude to a Surface 2 Pro. The Dell always reported excellent WiFi signal strength (all bars) whereas the Surface reported only good connection (2/3 bars). Testing the network speed I was getting 8+ Mbps download with the Dell and around 5 Mbps with the Surface.

I have a Linksys E2500 dual-band router. Apparently the Dell laptop uses the 5 GHz band, whereas the Surface uses the slower 2.4 GHz one. I solved the problem changing the router configuration so that it publishes two different network – one for each frequency, and then connected explicitly the Surface to the 5 GHz network.

In this way the download speed went up and it is now similar to the Dell laptop one.

I am still getting a reported poorer signal from the Surface than from the Dell, and I am not 100% sure that the network speed is actually the same.

Posted in: Programming

## Preventing Skynet

December 17, 2013 at 9:38 AM

Weird things you find following links: MIRI, a research institute devoted to prevent future artificial intelligence to take over the world.

Maybe they are actually right, and I should not define them ‘weird’, but ‘taking over the world’ AI seems a bit farfetched considering were we stand now with software development.

Posted in: Opinion | Programming

## HTML5

December 10, 2013 at 5:31 PM

Selected HTML5 technologies:

• Canvas (2D drawing) – like Windows GDI
• WebGL (3D drawing) – like Windows OpenGL
• WebSocket – like Windows Winsock
• Indexed Database – like Windows MSDE
• Offline Web applications – like Windows normal applications
• File API – line Windows NTFS
• Font support – like Windows GDI font handling
• Video/audio support – like Windows Media Player and associated APIs
• Web Workers – like Windows threads

So we are re-developing all this stuff (and more) in various browsers running on different platforms – and then develop (or re-develop) applications on top of it.

Tell me again, why are we doing all this? Wouldn’t have been simpler just to stick with Windows?

Posted in: Programming | Opinion

Tags:

## Project Rosalind

November 6, 2013 at 3:38 PM

I was never particularly attracted by biology – my bent is definitely more towards physics/math. Genetics always picked my curiosity though, as a biology subject that looks a lot like math or computer science. Having said that, I know next to nothing about genetics, and the little I know is pretty confused.

Looking on-line for some enlightenment I came across Rosalind, that is a set of bioinformatics problems that can be solved directly on-line.

Each problem include an explanation of the biological background – with links to further reading and resources, a description of the problem itself and a test data set. A button on the page downloads a new input data-set and requires to post the corresponding answer, that is then automatically checked. The problems (100+) are organized in a tree, solving the easier ones ‘unlocks’ the more complex.

It is very nice resource: you learn some biology/genetics, and you solve related problems at the same time – learning specific programming techniques along the way.

The language of choice is Python (the site includes a Python tutorial), but the problems can solved in any language because the site checks just the results. (Users can optionally upload the program code as well as the results, but it is not required).

I started working on the Rosalind problems back in the summer and so far I solved 26 of them. I am using F# – its interactive mode is perfect for quickly writing and testing code, and most problems lend themselves quite well to a functional solution.

Recently I posted the code I wrote so far on GitHub. The solution of the problems requires writing not only bioinformatics specific functions but also functions doing graph manipulation, combinatorics/probability and general string handling. I tried to write these function as generic as possible, and I placed then in different modules, hopefully they could be of help not only for the specific Rosalind problems.

Posted in: Programming

Tags: ,

## Sequence expressions and side-effects in F#

September 6, 2013 at 4:11 PM

I discovered an interesting problem when using sequence expression to read a text. The original case was more complex, but here is a simple example to reproduce the problem – a function reading all the lines of text from a text stream, returning them as a sequence of string using a sequence expression:

let readlines (reader: System.IO.TextReader) =
seq {
let line = ref (reader.ReadLine())
while !line <> null do
yield !line
line := reader.ReadLine()
}

Reading a two-lines text:

readlines (new System.IO.StringReader"A
B") 

produces as expected:

val it : seq<string> = seq ["A"; "B"]

Now define a simple function that checks if a sequence is empty and return either the string “Empty” or the string “XX items”:

let test s =
if Seq.isEmpty s then
"Empty"
else
sprintf "%d items" (Seq.length s)

Apply it to the same sequence as above:

readlines (new System.IO.StringReader"A
B") |> test

and the result is

val it : string = "1 items"

that is very wrong: the sequence contains 2 lines, not 1.

The problem is that the call to Seq.isEmpty reads the first line, moving the text reader to the second line (i.e. causing a side-effect) – and so causing subsequent uses of the sequence to skip the first line.

In this case the problem is with a text reader, but any call causing side-effects within a sequence expression is bound to cause the same unexpected behavior.

One possible solution is to cache the resulting sequence:

let readlines (reader: System.IO.TextReader) =
seq {
let line = ref (reader.ReadLine())
while !line <> null do
yield !line
line := reader.ReadLine()
} |> Seq.cache

that prevents double calls to read the same element in the sequence, fixing the problem.

Another solution is to create the reader within the sequence expression:

let readlinesStr str =
seq {
use reader = new System.IO.StringReader(str)
let line = ref (reader.ReadLine())
while !line <> null do
yield !line
line := reader.ReadLine()
}

that causes a new reader to be created each time sequence is accessed, avoiding side-effects.

Posted in: Programming

## jQuery UI widget: a slider displaying its value

August 6, 2013 at 11:47 AM

For the billiard simulation user interface I wanted to select a value with a slider, displaying it at the same time – so I created a new jQuery UI custom widget based on the standard slider one. It is used to edit the coefficients of restitution and the rolling resistance coefficient here.  The Javascript source code is here, and the TypeScript definition file is here.

The widget is pretty basic: it supports only one value, the slider must be horizontal and the value is always displayed on the right of the slider.

Some problem I had writing the widget:

Case of the widget name

I originally called the widget ‘sliderWithValue’ using camel case. The name of the widget is used by default as the prefix for the complete name of the widget events – but converted to lowercase – so the name of the change event is ‘sliderwithvaluechange’ and NOT ‘sliderWithValuechange’. The documentation does not mention this conversion to lowercase.

I renamed the widget ‘valueslider’ to avoid this problem.

Setting the width of a ‘span’ element.

To space correctly the label containing the value I needed to convert a width from ems to pixels, to do this the only way I found is to create a dummy HTML element, setting its widths in ems and then getting its pixel width. The problem is that using Internet Explorer 10 this trick works fine using ‘span’ element, whereas in Chrome and Safari attempts to set the width of  this empty ‘span’ elements are ignored – it is necessary to use a ‘div’.

Events and widget ‘destroy’ method

The jQuery UI documentation instructs to wire events either directly in the widget options:

$( ".selector" ).slider({ change: function( event, ui ) {} }); or using the ‘on’ function: $( ".selector" ).on( "slidechange", function( event, ui ) {} );

but they are not exactly equivalent: event handlers defined using ‘on’ are bot removed by the ‘destroy’ method of the widget, so if the code creates and destroys widgets dynamically it has to take care of removing the handlers defined using ‘on’.

Posted in: Programming

Tags: , , ,

## Billiard simulation improvements

August 6, 2013 at 10:17 AM

I just uploaded a new version of the billiard simulation with various improvements. The source code is on GitHub.

Scaling

Previous versions did not properly scale the simulation, 1 pixels was equivalent to 1 meter and so the balls (and their speed) were actually gigantic. The new version correctly scales dimensions: the balls are the size of real billiard balls and the table size is standard as well.

The correct scaling produces a noticeable difference in the time required for the balls to come to a complete stop: rolling resistance causes a constant deceleration, so with the original high speeds the balls took a very long time to stop, now with realistic speeds the balls stop quite quickly.

Initial balls configuration

It is possible to choose between a list of possible initial balls configuration using a drop-down, and also to directly select the initial configuration in the URL using an ‘init=<configuration name>’  option – e.g. ‘/rpool/?init=fromLeftTwoVertical

Start/stop and velocity display

The simulation can be stopped and re-started using the ‘Start’ and ‘Stop’ buttons. When it is stopped the ‘Step’ button executes a single update step at each click.

By default the simulation starts automatically, but this can be changed adding a stop=’ option to the URL – e.g. ‘/rpool/?init=fromLeftTwoVertical&stop=’.

When the simulation is stopped the velocity of each ball is displayed as an arrow:

Double collisions

The simulation can now optionally handle double collision as described in a previous post. To enable it use either the ‘Handle double collisions’ check-box in the page or the ‘double’ option in the URL – e.g. ‘/rpool/?init=fromLeftTwoVertical&double=

Parameters

It is possible to change the value of the coefficients of restitution and of rolling resistance used in the simulation. Setting the coefficients of restitution to 1 gives perfect elastic collisions, and setting then to 0 gives perfect inelastic ones: balls ‘stick’ to each other and to the table’s side when they collide.

Posted in: Programming

Tags: ,

## State machine using recursive functions

July 8, 2013 at 7:58 AM

I had a log file containing sequences of operations descriptions like this:

/*
DBLoadSchema
2013-06-21T15:01:46.222-04:00
. . .

and I needed to extract just the name (‘DBLoadSchema’) and date-time of each operation, plus their line number within the log file.

The ‘standard’ way would be to use a loop processing all the lines one by one, using some variables to keep track of the current state: ‘found /*’, ‘found operation name XXX’ etc. – a state machine.

The scripting language I use now is mostly F# – but using mutable variables to keep track of the state like that feels ‘wrong’ in a functional language like F# – a solution without mutable variables would be preferable.

Half-remembering something I read in a blog (or maybe was a book?) I came up with using separate functions – each representing a state of the state machine – that simply call each other to transition between states:

let rec processStart (log: StreamReader) lineNumber =
if log.EndOfStream then
Seq.empty
else
let line = log.ReadLine()
let lineNumber = lineNumber + 1
if line="/*" then
processStartComment log lineNumber
else
processStart log lineNumber
and processStartComment (log: StreamReader) lineNumber =
if log.EndOfStream then
Seq.empty
else
let line = log.ReadLine()
let lineNumber = lineNumber + 1
processProc (line.Trim()) log lineNumber
and processProc procName (log: StreamReader) lineNumber =
if log.EndOfStream then
Seq.empty
else
let line = log.ReadLine()
let lineNumber = lineNumber + 1
let dateTimeString = line.Trim()
let (ok, dateTime) = DateTime.TryParse(dateTimeString)
seq {
if ok then
yield (lineNumber, procName, dateTime)
yield! processStart log lineNumber
}

The source stream and the current line number are passed as a parameter to each function, and the state variables are parameters as well – in this case just the name of the operation, that is passed from ‘processStartComment’ to ‘processProc’. The functions return the result as a sequence of triplets line number, operation name, operation date-time. To process a log file simply open it and call ‘processStart’:

let filterLog (path: string) =
use log = new StreamReader(path)
processStart log 1`

All in all this ‘functional’ way requires a little bit to get used to – coming from a procedural background – but looks much simpler to use, especially if the state machine gets more complex. The use of sequences is nice as well: once you have a sequence of the parsed values it is easy to create pipelines to do further processing.

Posted in: Programming

Tags: ,