Archive for C Sharp

Yet another Turing Machine quasi-simulator in C Sharp

Posted in Uncategorized with tags , , , , on June 8, 2009 by spinoza1111

Screen 5Screen 7

Screen 6

All implemented simulations of Turing Machines are quasi in the sense (cf. my blog post here “Computer Software as a Philosophical Pathology”) that they run out of time and/or memory space before the “real” TM.

This version experiments with using ideas from practical programming languages to make it easier to program quasi Turing Machines, which are difficult to program. At this point I have implemented a grand total of one feature: states, along with symbols, can have meaningful names. The next step is to implement a macro facility (similar to C’s #define facility) to make it easier to code a Universal Turing Machine.

Turing Machines may have practical applications in nanocomputing or ruggedized computing for space exploration, where the rage for quick results does not obtain as it does down here on earth: perhaps an unmanned space exploration vehicle could use a TM as its onboard computer, as it floated, calculating, through the vastness of interstellar space. But mostly I solve the solved problem because c’est m’amusant.

Paris is cold, rainy and expensive, so I am spending most of my time here working on this project and running. But in the evenings there is a second dawn, since the Northern sun takes a long time to set, and often finds une pays de soleil, far distant, and that sun looks in on a gloomy Paris before it sets, like a careful mother. I never noticed this effect in Chicago, although it exists (it is an artifact of the curvature of the earth in northern lands): but living now, most of the time, near the jungly Equator, I don’t see it. In Fiji and Hong Kong, the sun goes, when it goes, quickly.

Perfect Numbers

Posted in Uncategorized with tags , , on May 17, 2009 by spinoza1111

I selected a solved problem to easily check the output.

“Perfect” numbers are the sum of all numbers that divide them without a remainder, except the “perfect” number itself, but including 1.

The “perfect” numbers are all known up to 10^300 or thereabouts. All known “perfect” numbers are even, and it is conjectured, without a proof at this time, that all such numbers are even.

Euclid developed an algorithm for calculating perfect numbers based on primes which was confirmed and polished by Euler, but I’m sick of prime numbers. I decided to write a C Sharp program that would determine perfecthood reasonably efficiently, and as it turned out, I needed to tune the Windows application running the program for multiple threads. In the latter activity I discovered a better way to handle threading inside traditional Windows forms.

It seemed to make sense to limit the determination of remainderless quotients to the square root of each number as we do in determining prime numbers, because for each n less than or equal to the square root of the candidate number C which divides C, we can get m such that n * m == C at the same time we determine whether its modulus is zero.

It would be elegant, of course, to call a fast divide which returns the quotient as a method value and the remainder by reference (or vice-versa): but I decided not to spend time on this.

Instead, I get reasonable performance by summing all n less than/equal to sqrt(C), therefore it is efficient to grab it when I take n.

I iterate starting above 2 and use shifting to determine whether the candidate is an even number, and add one (which always divides) when testing the sum against the candidate.

This has rounded up all the usual suspects:

screen

If you let it run for a while (or change the source code to start at 33550336 or 137438691328) it displays 33,550,336, or 137,438,691,328. If you change the source code to start at the next number, 2305843008139952128, the application seems to run “forever”.

The further perfect numbers exceed the precision of a Long number (2^64-1) so there’s no point in trying to calculate them with this software. Basically, what we have is a marvelously useless tool which you can run to confirm that there are no odd perfect numbers less than 2^64, because Euclid-Euler calculates even perfect numbers only. But as an example of good C# code IMO, and, as we’ll see below, threading in forms, it might be of interest.

As to threading in forms, then: we know that Windows Forms are not thread safe. The Microsoft C# 2008 documentation recommends a clumsy use of Invoke inside extra form threads (such as the thread in which I calculate perfect numbers) to send all interactions, from the worker thread, back to the main form thread.

I realized that the only elegant way of using Invoke is to wrap it in a little Invoke manager with a dispatching enumerator, and that this could handle the final construction of an array of object arguments.

Ideally, all code in a modern Form would always use this form invoke manager (named formInvoke() here) so that at any time during software maintenance, the software maintainer would not have to worry about what thread was executing code being studied or changed. This is because Invoke simply does the form task directly when it is in the main thread.

However, it is typical, in legacy systems to which advanced features (such as multiple threads) are tacked-on, for programmers to handle new requirements that result from the new “power” by code snippets, taken from a magazine or a workmate sufficiently fat and sufficiently bearded to have a reputation as a technical guru.

(Damn right I’m angry at the lack of craft in American programming: the gloves are off, since the “credit crisis” is in large measure a consequence of sloppy programming.)

I prefer to create a new environment and a new abstraction, whence formInvoke.

Beyond this, I hesitate to tread into extra precision calculations, written in Intel assembler.

Here is the code. I wrote it without any comments although I prefer comments simply to get it done a bit faster. The actual listing as formatted by the code tag loses indentation so the copyable code listing is preceded by an image of the code that calculates perfect numbers to show the overall style.

You should be able to paste the copyable code into a Windows form code window under modern C Sharp enterprise/express, and get results.

code

Oh and by the way. The careful formatting of the above and its use of Hungarian notation used to be a Good Thing. Today, it galvanizes programming thugs who as practical men without illusions have inchoately theorized the strange notion that all such touches indicate, not competence, but its reverse.

Cf. that usenet intellectual slum comp.programming for an example. These are the men Adorno meant in 1948. Afraid that the secret contour of their weakness will be exposed they find it instead in anything, whether English or code, in which any effort has been expended.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace perfectNumbers
{
public partial class perfectNumbers : Form
{

Label LBLoutput;
Label LBLstatus;
Button CMDstop;
System.Threading.Thread OBJcalculationThread;
string STRtext;
CheckBox CHKstatus;

public perfectNumbers()
{
InitializeComponent();
}

private void chkStatus_CheckedChanged
(object objSender,
EventArgs objEventArgs)
{
LBLstatus.Visible = CHKstatus.Checked;
LBLstatus.Refresh();
}

private void cmdClose_Click(object objSender,
EventArgs objEventArgs)
{
closer();
}

private void cmdCalculatePerfectNumbers_Click
(object objSender,
EventArgs objEventArgs)
{
(OBJcalculationThread =
new
System.Threading.Thread
(new System.Threading.ThreadStart
(calculatePerfectNumbers))).Start();
}

private void cmdStop_Click(object objSender,
EventArgs objEventArgs)
{
OBJcalculationThread.Abort();
while (OBJcalculationThread.ThreadState
!=
System.Threading.ThreadState.Stopped) { }
changeFormState(ENUformState.waiting);
}

private void perfectNumbers_Load(object objSender,
EventArgs objEventArgs)
{
Text = Application.ProductName;
STRtext = Text;
if (!customizeForm()) closer();
state2Label(ENUcalculationState.quiescent);
}

private void calculatePerfectNumbers()
{
changeFormState(ENUformState.running);
long lngIndex1 = 0;
long lngIndex2 = 0;
long lngSum = 0;
string strSep = "";
string strTextStart = "Calculating perfect numbers";
formInvoke(this, ENUformInvokeOp.setText, strTextStart);
for (lngIndex1 = 6;
lngIndex1 2;
lngIndex2--)
{
if (lngIndex1 % lngIndex2 == 0)
{
lngSum += lngIndex2;
lngSum += (long)(lngIndex1 / lngIndex2);
}
}
state2Label(ENUcalculationState.iteratingOverCandidates);
if (((lngIndex2 = (lngIndex1 >> 1)) << 1)
==
lngIndex1)
{
lngSum += 2;
lngSum += lngIndex2;
}
if (lngSum + 1 == lngIndex1)
{
formInvoke(LBLoutput,
ENUformInvokeOp.setText,
LBLoutput.Text +
strSep +
lngIndex1.ToString());
formInvoke(this, ENUformInvokeOp.refresh);
strSep = ", ";
}
if (lngIndex1 % 100 == 0)
{
formInvoke(this,
ENUformInvokeOp.setText,
strTextStart + " at " +
lngIndex1.ToString());
}
}
changeFormState(ENUformState.waiting);
}

private enum ENUformState { running, waiting }
private void changeFormState(ENUformState enuNewState)
{
switch (enuNewState)
{
case ENUformState.running:
{
formInvoke(this,
ENUformInvokeOp.enableDisableControlCollection,
false);
formInvoke(CMDstop,
ENUformInvokeOp.enableDisableControl,
true);
formInvoke(LBLoutput,
ENUformInvokeOp.enableDisableControl,
true);
formInvoke(CHKstatus,
ENUformInvokeOp.enableDisableControl,
true);
formInvoke(LBLoutput,
ENUformInvokeOp.setText,
"");
break;
}
case ENUformState.waiting:
{
formInvoke(this,
ENUformInvokeOp.enableDisableControlCollection,
true);
formInvoke(CMDstop,
ENUformInvokeOp.enableDisableControl,
false);
formInvoke(this,
ENUformInvokeOp.setText,
STRtext);
state2Label(ENUcalculationState.quiescent);
break;
}
default:
throw new Exception("Invalid form state");
}
}

private void closer()
{
Application.Exit();
}

private bool customizeForm()
{
ControlBox = false;
Text = Application.ProductName;
FormBorderStyle = FormBorderStyle.Fixed3D;
Width = Width << 1;
CenterToScreen();
int intGrid = windowsUtilities.windowsUtilities.Grid;
Button cmdNew =
windowsUtilities.windowsUtilities.mkButton
("Close",
ClientSize.Width
-
intGrid
-
windowsUtilities.windowsUtilities.defaultButtonWidth(),
ClientSize.Height
-
intGrid
-
windowsUtilities.windowsUtilities.defaultButtonHeight());
cmdNew.Click += cmdClose_Click;
Controls.Add(cmdNew);
Button cmdClose = cmdNew;
cmdNew =
windowsUtilities.windowsUtilities.mkButton
("Calculate perfect numbers",
intGrid,
cmdNew.Top,
cmdNew.Width << 1);
cmdNew.Click += cmdCalculatePerfectNumbers_Click;
Controls.Add(cmdNew);
cmdNew =
windowsUtilities.windowsUtilities.mkButton
("Stop",
cmdNew.Right + intGrid,
cmdNew.Top,
cmdClose.Width);
cmdNew.Click += cmdStop_Click;
Controls.Add(cmdNew);
cmdNew.Enabled = false;
CMDstop = cmdNew;
int intGrid2 = intGrid << 1;
LBLoutput =
windowsUtilities.windowsUtilities.mkLabel
("",
intGrid,
intGrid,
ClientSize.Width - intGrid2,
ClientSize.Height
-
(intGrid2 + intGrid)
-
cmdNew.Height);
LBLoutput.BorderStyle = BorderStyle.Fixed3D;
LBLoutput.Font = new Font(FontFamily.GenericMonospace, 10);
Controls.Add(LBLoutput);
CHKstatus =
windowsUtilities.windowsUtilities.mkCheckBox
("Show status",
CMDstop.Right + intGrid,
CMDstop.Top);
CHKstatus.CheckedChanged += chkStatus_CheckedChanged;
Controls.Add(CHKstatus);
LBLstatus =
windowsUtilities.windowsUtilities.mkLabel
("",
CHKstatus.Right + intGrid,
CMDstop.Top,
windowsUtilities.windowsUtilities.defaultLabelWidth(),
CMDstop.Height);
LBLstatus.BorderStyle = BorderStyle.Fixed3D;
LBLstatus.Font = new Font(FontFamily.GenericMonospace, 10);
Controls.Add(LBLstatus);
CHKstatus.Checked = true;
return true;
}

private enum ENUformInvokeOp
{
enableDisableControl,
enableDisableControlCollection,
queryEnabled,
queryVisible,
refresh,
setBGFGcolor,
setText
}
delegate object DELformInvoke
(Control ctlControl,
ENUformInvokeOp enuOp,
params object[] objOperands);
private object formInvoke(Control ctlControl,
ENUformInvokeOp enuOp)
{
object[] objDummy = null;
try
{
objDummy = new object[1];
objDummy[0] = null;
}
catch (Exception objException)
{
throw new Exception
("Cannot create dummy operand array",
objException);
}
return formInvoke(ctlControl, enuOp, objDummy);
}
private object formInvoke
(Control ctlControl,
ENUformInvokeOp enuOp,
params object[] objOperandsParams)
{
if (ctlControl.InvokeRequired)
{
object[] objInvokeOperandsBase = null;
object[] objInvokeOperandsParams = null;
try
{
objInvokeOperandsBase = new object[3];
objInvokeOperandsParams =
new object
[objOperandsParams.GetUpperBound(0) + 1];
}
catch (Exception objException)
{
throw new Exception("Cannot create operand arrays",
objException);
}
int intIndex1 = 0;
foreach (object objOperand in objOperandsParams)
objInvokeOperandsParams[intIndex1++] = objOperand;
objInvokeOperandsBase[0] = ctlControl;
objInvokeOperandsBase[1] = enuOp;
objInvokeOperandsBase[2] = objInvokeOperandsParams;
return ctlControl.Invoke(new DELformInvoke(formInvoke),
objInvokeOperandsBase);
}
else
{
try
{
lock (ctlControl)
{
switch (enuOp)
{
case ENUformInvokeOp.enableDisableControl:
{
ctlControl.Enabled =
(bool)objOperandsParams[0];
return true;
}
case ENUformInvokeOp.enableDisableControlCollection:
{
int intIndex1 = 0;
for (intIndex1 = 0;
intIndex1 < ctlControl.Controls.Count;
intIndex1++)
ctlControl.Controls[intIndex1].Enabled =
(bool)objOperandsParams[0];
return true;
}
case ENUformInvokeOp.queryEnabled:
{
return ctlControl.Enabled;
}
case ENUformInvokeOp.queryVisible:
{
return ctlControl.Visible;
}
case ENUformInvokeOp.refresh:
{
ctlControl.Refresh();
return true;
}
case ENUformInvokeOp.setText:
{
ctlControl.Text =
(string)objOperandsParams[0];
return true;
}
case ENUformInvokeOp.setBGFGcolor:
{
ctlControl.BackColor =
(Color)objOperandsParams[0];
ctlControl.ForeColor =
(Color)objOperandsParams[1];
return true;
}
default:
throw new Exception
("Invalid op " +
enuOp.ToString());
}
}
}
catch (Exception objException)
{
throw new Exception("Error in Invoked op",
objException);
}
}
}

private enum ENUcalculationState
{
iteratingOverCandidates,
dividingCandidate,
quiescent
}
private const string CALCULATIONSTATE_ITERATINGOVERCANDIDATES =
"Iterating over candidates";
private const string CALCULATIONSTATE_SEARCHING =
"Searching for divisors";
private const string CALCULATIONSTATE_QUIESCENT =
"";
private void state2Label(ENUcalculationState enuState)
{
if (!(bool)
formInvoke(LBLstatus,
ENUformInvokeOp.queryVisible)) return;
Color objBG = Color.White;
Color objFG = Color.Black;
state2ColorScheme(enuState, ref objBG, ref objFG);
formInvoke(LBLstatus,
ENUformInvokeOp.setBGFGcolor,
objBG, objFG);
formInvoke(LBLstatus,
ENUformInvokeOp.setText,
state2String(enuState));
formInvoke(this, ENUformInvokeOp.refresh);
}

private static void state2ColorScheme
(ENUcalculationState enuState,
ref Color objBG,
ref Color objFG)
{
switch (enuState)
{
case ENUcalculationState.iteratingOverCandidates:
{
objBG = Color.Yellow; objFG = Color.Black;
break;
}
case ENUcalculationState.dividingCandidate:
{
objBG = Color.Red; objFG = Color.White;
break;
}
case ENUcalculationState.quiescent:
{
objBG = Color.White; objFG = Color.Black;
break;
}
default:
throw new Exception("Invalid state");
}
}

private static string state2String
(ENUcalculationState enuState)
{
switch (enuState)
{
case ENUcalculationState.iteratingOverCandidates:
return CALCULATIONSTATE_ITERATINGOVERCANDIDATES;
case ENUcalculationState.dividingCandidate:
return CALCULATIONSTATE_SEARCHING;
case ENUcalculationState.quiescent:
return CALCULATIONSTATE_QUIESCENT;
default: return "Unknown state";
}
}

}
}

More prime number kitsch

Posted in Uncategorized with tags , , , , , , , on May 7, 2009 by spinoza1111

output-31

I’ve replaced the label matrix with an Image in a Picture and pixels to display primes as dots up to 1,057,249 while calculating the first million primes (to 15,485,867).

The “roads” (vertical or diagonal, but strangely not horizontal lines where values are congruent to a composite number) appear as do the “hutongs” between the roads, where I call these “hutongs” after alleys in Beijing: the “hutongs” shown are neighborhoods, vertically of infinite length).

Strange clusters appear in addition to roads and hutongs:

output-10-copy

Polon. My Lord; the Queene would speak with you,
and presently

Ham. Do you see that Clowd? that’s almost in shape
like a Camell

Polon. By’th’ Masse, and it’s like a Camell indeed

Ham. Me thinkes it is like a Weazell

Polon. It is back’d like a Weazell

Ham. Or like a Whale?
Polon. Verie like a Whale

Ham. Then will I come to my Mother, by and by:
They foole me to the top of my bent.
I will come by and by

Hamlet gets Polonius in the old play to see “anything”. We can read too much into these prime displays. But if we switch from red and yellow to display prime and nonprime to a “starfield”, a strange periodicity appears: bands of higher-probability prime regions do seem to exist.

output-8

(This display is to me awe-inspiring but it is hard to reproduce on a printer or here).

ON a starr’d night Prince Lucifer uprose.
Tired of his dark dominion swung the fiend
Above the rolling ball in cloud part screen’d,
Where sinners hugg’d their spectre of repose.
Poor prey to his hot fit of pride were those.
And now upon his western wing he lean’d,
Now his huge bulk o’er Afric’s sands careen’d,
Now the black planet shadow’d Arctic snows.
Soaring through wider zones that prick’d his scars
With memory of the old revolt from Awe,
He reach’d a middle height, and at the stars,
Which are the brain of heaven, he look’d, and sank.
Around the ancient track march’d, rank on rank,
The army of unalterable law.

– George Meredith

output-71

The next step is to drive the calculation to the limit of 64 bit precision and to display the primes at the end of this precision to see if anything changes. But this may mean not being able to store a “seive of Eratosthenes” past a bound, and having, when the seive runs out, to use brute force.

I left my Knuth in the United States and I need it now, but I also need to leave off this programming and return to the visual arts.

10ee let me know if you think that “the music and mystery of the prime numbers” to be soduku and kitschy. Adorno thought all math was moronizing because he thought that thought drained of emotion to be tautology, and he may have been right.

Part of your resentment of soduku enthusiasm is that recreational mathematics, with only one exception I know of, is rediscovery of what has been found by first-rate mathematicians and petty-bourgeois kitsch in relation to their haute-bourgeois work, in the way that somewhat pathetic “entrepreneurs” in America regularly go tits up by inventing also-ran software products. The exception that I know of is the fact that John Horton Conway, the Cambridge mathematician, did recreational math when I was there and presented it as part of his regular work.

The music and mystery of the prime numbers

Posted in Uncategorized with tags , , , , , on May 6, 2009 by spinoza1111

output

Here’s the latest output of a program displaying the maddeningly nonrandom patterns made by primes when you display them (starting with 5 for no particular reason) as blue squares.

This could be an aerial view of a mysterious city in a short story by Borges.

Although the pattern is not random, it is partly determined by the arbitrary choice of a rectangle. This choice causes one-lane and two lane roads of infinite length to exist in our city because of course they occupy cells corresponding to nonprime numbers in the first row, and the cells below them are all divisible in turn.

We could then I suppose call the regions BETWEEN the superhighways “Hutongs” after alleyways in Beijing which connect neighborhoods hidden from main roads and analyze the characteristics of the Hutongs to discover what the devil is going on with the prime and “solve Riemann”.

Don’t get me wrong: I am no mathematician, and to me, Riemann is a rumour about numbers. I assisted Nash with programming, not mathematics, where programming is the cruel science of apparati that are finite state in all cases.

The use of Windows “labels”, which are boxes on the screen inside of windows, is crude. I thought to determine the optimal size of a label by defining the available area exclusive of the “list box” at the left, and a “progress bar” at the bottom, and a bit of algebra but could not get it right: here, a label height and width of 8 points happens to fill the area nicely. You cannot use double precision for integer results of any accuracy unless you have time to Think, and there’s a strong possibility that the “smallest label that will just fit inside the big rectangle” does not have a single solution.

It would seem to have to have one if it is a square, but this may have misled me into trying, in code, to solve the equation system

available area = number of labels * label area: label area = w * h; w = h

Actually doing this in the time available on the ferry produced a “solution” in which the labels were TOO BIG to show every number in the range of 1500 primes that is calculated, and displayed on the left.

If there are multiple solutions then the problem may be “dynamic programming” or “tiling”.

Math is harder when you are 58 years of age!

“Why a four year old could do this! Get me a four year old!” – Groucho Marx

The irresponsibility of many systems for “parsing regular expressions”

Posted in Uncategorized with tags , , , , , , on May 1, 2009 by spinoza1111

analects-and-psalm-23

Note: this post is for computer scientists and geeks. Scroll down or use the back and forth blocks to see original poetry and other posts on philosophy, art, and hot French girls, please.

“Regular expressions”, as you know (since you are a computer scientist and/or a geek, and you were not more interested in hot French girls at this time) are simple linear specifications of a formal automaton without much memory and no imagination, which scans mindlessly left to right (or right to left in Israel, or down and to the left in ancient China: it makes no mathematical difference), to find simple facts about a text.

I am developing a regular expression compiler to translate regular expressions into C Sharp code which can then be compiled and run by the codeDoer object, described here.

In this, I’ve noticed a problem. The following regular expression, coded using ordinary re notation in general use, seems acceptable but is not:

( (* “\x13\x10” ) | (* “\x10”) )

Its purpose is to parse a file which uses two conventions for separating lines: the Windows convention (carriage return followed by linefeed) and the unix/linux convention (linefeed).

It’s messed up. “*” on both sides of its major alternation operator means “any character”…including the “handle” of the Windows and unix/linux terminators, ‘\x13’ for Windows, ‘\x10’ for unix/linux.

As you may know, the “handle of a sentential form” is the set of characters that can start the sentential form: it is a useful concept in compilers which scan left to right, or right to left in some lands, or down and to the left in ancient China.

The parsing will depend completely upon the way in which the regular expression processor was implemented.

My purpose, in developing “yet another” regular expression parser, apart from shits, giggles, and ludic fun, is to create a processor that will parse in a predictable form, and provide English-language explanations of what a particular regular expression will do, a goal curiously disregarded in most such tools…which have been mostly just obfuscation. I pretty much ignore existing art since the weight of existing art kills innovation, and I spent thirty years being told not to reinvent the wheel, and, like Sisyphus in consequence, like the souls in Dante’s Inferno, rolling heavy, ill-shapen wheels up and down the hills of Gehenna.

Therefore, in developing the new re parser, I have split the operations of “alternating between two subexpressions” and “sequencing two subexpressions” into three parts:

1. Strict alternation and strict sequencing requires the handles of the sentential forms being alternated to be completely disjoint.

2. OrMaybe alternation, and AndMaybe sequencing, will assume in cases where the handles of the sentential forms overlap, that the left hand side should be favored.

3. OrSurely alternation and AndSurely sequencing, will assume that the overlap characters belong to the right hand side.

Interestingly, this echoes a programming issue that in my experience was flaccidly unaddressed and “solved” by accident for years: evaluating Boolean or and Boolean and, where you know in the case of or that the left hand side is true, or in the case of and that the left hand side is false. Many programming languages had variorum compilers in this regard, and then, circa 1974, hero computer scientist Niklaus Wirth took the bull by the horns in Pascal…and solved the problem the wrong way, declaring that Pascal runtime would evaluate both sides of Boolean operations.

This created hours of fun for the entire family because we could not, in Pascal, test the validity of an operation and its result in the same Boolean expression: the pseudo code “a is numeric and greater than 1” could not be implemented sensibly except by extra if nesting.

Basic was completely all over the map, and then, in the 1990s, Visual Basic solved the problem again the wrong way. Finally, at the turn of the millenium, VB.Net introduced the very cool operators OrElse and AndAlso which evaluated “lazily”, not executing the code compiled for their right hand side when the OrElse’s left hand side was true, or the AndAlso’s lhs was false.

And the people rejoiced, and said, God save .Net. Long live .Net. May .Net live forever.

Most data processing “types” being Platonists who don’t like to code, the problem was remarked upon by mathematical and programming Intuitionists who know that math emerges from labor; the man who pointed out how the Or and And are evaluated, and how this could be used to create partial truth tables, was a brilliant philosopher and teacher of logic who was treated shamefully by his university and grad students precisely because he noticed such things.

It’s interesting that this problem surfaces in regular expressions.

I shall continue to post papers on the development of my regular expression parser amidst other posts on philosophy and containing original no-shit poetry which, I have to explain in many cases, isn’t quotations from anybody else.

Edward G. Nilges 1 May 2009. Moral rights have been asserted, sosumi.

A new Microsoft .Net tool for executing source code at run time

Posted in Uncategorized with tags , , , , , , , , on April 12, 2009 by spinoza1111

screen1

In developing a “laboratory” for messing around with Conway’s Game of Life and other cellular automata (as described elsewhere in this blog), I need to compile rules specified or changed by the user into .Net object code for reasonable efficiency. This involves using “reflection”: access to code as an object in an OO language.

In industry, one is expected to be silent about these distinct and well-defined needs, and quietly hack or copy some clown’s code, and deal with the inchoate results and the self-hatred that comes from doing a bad job. I wake up every morning singing loud Hosannahs that I am no longer in industry for this reason (I am a teacher of English after thirty years in a software industry which produced the credit crisis owing to its deliberate lack of craft and embedded anti-intellectualism).

I therefore have spent some time developing a distinct object for this purpose, codeDoer, the doer of code.

Microsoft .Net supports “reflection” in the form of access to compilers at run time: but actually using it messes up your code.

A “fully interpretive” language such as Rexx, used on IBM mainframes, is fully interpretive because “code” is a thing accessible to code. In Rexx, “code” is a Rexx string, and strings are part of Rexx’s fundamental ontology: everything is a string.

However, in many languages, vendors have long been reluctant to give the programmer access to reflection, since full reflection allows the programmer to essentially steal the vendor’s thunder by providing compilers to third parties.

In my book, “Build Your Own .Net Language and Compiler” (Apress, May 2004), I discuss how to implement a non-object-oriented reflection (in the sense of executing source code represented in strings at run time) in the interpreter.

But in .Net, accessing Reflection out of the box seemed to me to involve a lot of time-consuming and difficult to maintain clap trap, generating code using pathological practices (such as Invoke() in place of simple calls when Invoke() is not needed).

I just wanted to be able to code

CodeDoer objCodeDoer = new CodeDoer(“1 + 1”);
objCodeDoer.compile();
MessageBox.Show(objCodeDoer.run());

where a pre-edit would check the code for one of two forms:

* Expression: no terminating semicolon, no return
* Code: terminating semicolon and/or a final return

so I did.

The compiled object code is available for continual reuse after the first compile.

The codeDoer class executes simple or fancy code and returns its value, having whatever side effects are planned for in the code. Here’s a screen shot of it executing a recursive N Factorial program, which accesses a params array of objects to get the value of N: because C Sharp is strict with conversions, the code includes a characterwise conversion of an object to a string to a Long integer.

screen2

The codeDoerTester form and class tests the codeDoer class, allowing you to try C Sharp expressions and statements out.

The class uses a methodology for reliable and maintainable object oriented design which I discuss in “Build Your Own .Net Language and Compiler”, including self-inspection and the use of XML to dump its state. It also “cooks” C Sharp expressions (adding return and semicolon) and then as needed “bakes” them (adding namespace, class and method wrappers) prior to compiling them using a provider.

I believe Open Source to be a form of virtualized slavery, in which the code worker is enslaved by the theft of his intellectual property by men like Jimmy Wales…who get rich based on free labor. Therefore it is against my religion to give this code away. I ain’t gonna be altruistic to rich people, which creeps like Wales expect.

Instead, if you’re interested in it, contact me at spinoza1111@yahoo.COM to discuss a deal for the DLL and/or the source code. I’m not free but I am cheap. Hell, if you need the code for charity and social work, I’ll probably give you the whole kit and kaboodle for free after all.

The Prime Number “Happy Face”: not a discovery

Posted in Uncategorized with tags , , , , , , , , , on March 15, 2009 by spinoza1111

corrected

An earlier post made reference to a display that was produced erroneously, which contained a “happy face” that was an artifact, not only of the aspect ratio but also of the bug; the orignal post cautioned the reader that the “happy face” meant nothing compared to the truth and beauty of the primes. This is the corrected visual map of the primes from 3 to 11483. A later blog post will describe further discoveries and the availability of this software.