Dorothy Sayers, in her excellent book, The Mind of the Maker, divides creative activity into three stages: the idea, the implementation, and the interaction. A book, then, or a computer, or a program comes into existence first as an ideal construct, built outside time and space, but complete in the mind of the author. It is realized in time and space, by pen, ink, and paper, or by wire, silicon, and ferrite. The creation is complete when someone reads the book, uses the computer, or runs the program, thereby interacting with the mind of the maker.
This description, which Miss Sayers uses to illuminate not only human creative activity but also the Christian doctrine of the Trinity, will help us in our present task. For the human makers of things, the incompletenesses and inconsistencies of our ideas become clear only during implementation. Thus it is that writing, experimentation, “working out” are essential disciplines for the theoretician.
In many creative activities the medium of execution is intractable. Lumber splits; paints smear; electrical circuits ring. These physical limitations of the medium constrain the ideas that may be expressed, and they also create unexpected difficulties in the implementation.
Implementation, then, takes time and sweat both because of the physical media and because of the inadequacies of the underlying ideas. We tend to blame the physical media for most of our implementation difficulties; for the media are not “ours” in the way the ideas are, and our pride colors our judgment.
Computer programming, however, creates with an exceedingly tractable medium. The programmer builds from pure thought-stuff: concepts and very flexible representations thereof. Because the medium is tractable, we expect few difficulties in implementation; hence our pervasive optimism. Because our ideas are faulty, we have bugs; hence our optimism is unjustified.
Fred Brooks, The Mythical Man-Month, pg. 15
Archive for category software development
Stages of creative activity
Aug 31
Why programming is fun
Aug 26
Fred Brooks, in his excellent work, The Mythical Man-Month, has this to say about why we enjoy programming.
The Joys of the Craft
Why is programming fun? What delights may its practitioner expect as his reward?First is the sheer joy of making things. As the child delights in his mud pie, so the adult enjoys building things, especially things of his own design. I think this delight must be an image of God’s delight in making things, a delight shown in the distinctness and newness of each leaf and each snowflake.
Second is the pleasure of making things that are useful to other people. Deep within, we want others to use our work and to find it helpful. In this respect the programming system is not essentially different from the child’s first clay pencil holder “for Daddy’s office.”
Third is the fascination of fashioning complex puzzle-like objects of interlocking moving parts and watching them work in subtle cycles, playing out the consequences of principles built in from the beginning. The programmed computer has all the fascination of the pinball machine or the jukebox mechanism, carried to the ultimate.
Fourth is the joy of always learning, which springs from the nonrepeating nature of the task. In one way or another the problem is ever new, and its solver learns something: sometimes practical, sometimes theoretical, and sometimes both.
Finally, there is the delight of working in such a tractable medium. The programmer, like the poet, works only slightly removed from pure thought-stuff. He builds his castles in the air, from air, creating by exertion of the imagination. Few media of creation are so flexible, so easy to polish and rework, so readily capable of realizing grand conceptual structures. (As we shall see later, this very tractability has its own problems.)
Yet the program construct, unlike the poet’s words, is real in the sense that it moves and works, producing visible outputs separate from the construct itself. It prints results, draws pictures, produces sounds, moves arms. The magic of myth and legend has come true in our time. One types the correct incantation on a
keyboard, and a display screen comes to life, showing things that never were nor could be.Programming then is fun because it gratifies creative longings built deep within us and delights sensibilities we have in common with all men.
-Fred Brooks, The Mythical Man-Month, pg. 8-9
I’ve been working on a rather large web application which is responsible for combining data from a variety of sources and presenting the data to the end user in a clean, unified fashion. During this process we sometimes run into cases where multiple related calls are made, each to perform some transformative work on a single set of data. We decided these calls could be made in a more parallel fashion and as such started looking into ways of parallelizing PHP so that relatively expensive operations could be performed at the same time and then the results combined in the end.
We examined a few possible solutions such as Gearman, popen, and multi curl. However all of these methods seemed to require more overhead than they were worth. What I really wanted to see was something more along the lines of POSIX threads to distribute the work load and shared memory for passing data between the parent and child threads.
After some searching through PHP extensions and the official documentation I ran across PHP’s Process Control Extensions suite which contains PCNTL functions, one of which is pcntl_fork. Combined with PHP’s Shared Memory Functions, this promises to fit the bill of inexpensive distribution of processing tasks along with low-overhead inter process communication.
Here is a sample proof-of-concept script. I’ll outline what it does below:
$data = array();
echo "Parent PID: ".getmypid().PHP_EOL;
function forkTest(array &$data) {
$pids = array();
$parent_pid = getmypid();
for($i = 0; $i < 10; $i++) {
if(getmypid() == $parent_pid) {
$pids[] = pcntl_fork();
echo "Forking child, \$pids now has ".count($pids)." elements".PHP_EOL;
}
}
if (getmypid() == $parent_pid) {
/* Parent thread */
echo "Hello from parent: ".getmypid().PHP_EOL;
array_push($data, "parent".getmypid());
/* Process childrens' results as they exit */
while(count($pids) > 0) {
$pid = pcntl_waitpid(-1, $status);
echo "Attempting to open memory with pid: ".$pid.PHP_EOL;
$shm_id = shmop_open($pid, "a", 0, 0);
$shm_data = unserialize(shmop_read($shm_id, 0, shmop_size($shm_id)));
shmop_delete($shm_id);
shmop_close($shm_id);
$data = array_merge($data, $shm_data);
/* Hunt down and remove pid entry */
foreach($pids as $key => $tpid) {
if($pid == $tpid) unset($pids[$key]);
}
}
echo "All children exited, \$data now has:".count($data)." elements".PHP_EOL;
$pids = array();
} else {
/* Children threads */
$pdata = array();
echo "Hello from child: ".getmypid().PHP_EOL;
array_push($pdata, "child".getmypid());
$data_str = serialize($pdata);
$shm_id = shmop_open(getmypid(), "c", 0644, strlen($data_str));
if (!$shm_id) {
echo "Couldn't create shared memory segment".PHP_EOL;
} else {
if(shmop_write($shm_id, $data_str, 0) != strlen($data_str)) {
echo "Couldn't write shared memory data".PHP_EOL;
}
}
sleep(rand(1,10));
exit(0);
}
}
/* Run the test 10 times */
for($f = 0; $f < 10; $f++) {
echo "Running $f forkTest()".PHP_EOL;
forkTest($data);
}
echo "Fork test finished, \$data now contains ".count($data)." elements".PHP_EOL;
echo "\$data:".PHP_EOL.json_encode($data);
This code describes a function that spawns 10 child worker threads, each of which gets a reference to the global $data array. Each child thread pushes a string element containing the child thread’s process identifier into the array, serializes it, and then places it into a shared memory slot with the process id serving as the shared memory id. The parent process waits for each child thread to exit, gathers the data from shared memory, clears the shared memory, and then combines the results into the master $data array. My test application runs through this function 10 times to demonstrate how forking in PHP can be safe and memory efficient. The result should be a $data array with 110 elements in it. I’ve thrown in sleep commands with a random time between 1 and 10 seconds to show how threads can return at different times.
No doubt optimizations can be made but this should serve as at least a rudimentary example of true and efficient threading in PHP. Well, provided that the work you are planning on doing is worth the overhead (which, small as it may be, still exists and should be factored in) and provided that you do not mind locking your application down to a POSIX environment (meaning the above code will not work on windows platforms).
Simple JSON-RPC has been updated to 1.0.0. This new version includes a brand new event messaging system making it possible for classes to react to events generated by the Simple JSON-RPC framework.
Through simple event messaging, your RPC classes are now able to react to and even interact with servlet configuration, context, request, and response objects. To use this facility your class needs to extend the new JSONRPCEventListener interface and implement the messageReceived method, accepting one argument of the JSONRPCMessageEvent type.
Here is an example of how a class could implement a Simple JSON-RPC event listener:
public void messageReceived(JSONRPCMessageEvent me) {
switch(me.message().getCode()) {
case JSONRPCMessage.INIT:
config = me.message().getServletConfig();
break;
case JSONRPCMessage.BEFOREREQUEST:
request = me.message().getRequest();
session = request.getSession(true);
break;
case JSONRPCMessage.BEFORERESPONSE:
response = me.message().getHttpResponse();
response.setContentType("text/html");
break;
case JSONRPCMessage.AFTERRESPONSE:
lastresponse = me.message().getRPCResponse();
break;
}
}
This new feature should also make it easier to implement solutions that use sessions. This should also make it possible for classes to react to the output of other classes, including errors.
Using PHP to write PHP
Jul 29
I ran into a situation recently where I had a very large array object that was not going to change. It was the polygon coordinates for the world countries to be used in KML provided by Thematic Mapping.
I didn’t wan’t to pull this data out of MySQL every time I went to build a map, I wanted to use one giant static array instead. So to write the array back out in a re-usable fashion I developed the following code which can take any array, of any depth, associative or index based, and spit out corresponding PHP that you can copy and paste back into your script.
function phpPrintArr(array $arr) {
echo "array(".PHP_EOL;
$c = 1;
$total = count($arr);
foreach($arr as $i =>$v) {
$iq = is_numeric($i) ? '' : '"';
$vq = is_numeric($v) ? '' : '"';
$e = $c < $total ? ',' : '';
if(is_array($v)) {
echo $iq.$i.$iq.'=>'.PHP_EOL;
phpPrintArr($v);
echo $e.PHP_EOL;
} else {
echo $iq.$i.$iq.'=>'.$vq.$v.$vq.$e.PHP_EOL;
}
$c++;
}
echo ")".PHP_EOL;
}
Oh, and for anyone who is interested in the array of country polygons this produced from the Thematic Mapping Engine data, here is the rather large array. Feel free to use it in your own KML project.
The HBase JSON-RPC bridge has been updated to allow scanning on non-key columns. Now, passing a filter parameter creates a scanner using a RegexStringComparator. Results are returned in 100 block chunks until null is returned, in which case the ResultScanner is closed
Here is an example query that is now possible:
http://localhost:8080/hbasebridge/rpc?debug=true&data={"method":"lookup","params":{"table":"hbasetable","filter":"searchstring"}}
It’s been a while since I released Bible Flashcards version 1.0. Long enough in fact that I started getting emails asking whether I intended on updating past the 1.1.4 release.
Well I am proud to announce version 2.0 which includes a lot of requested features and a lot of bug-fixes and improvements. For this release I decided to take my time and re-factor the way various screens interacted, making them more modular and self-contained which should translate into fewer force closes. I also unleased the monkey on my app which helped me improve my code even more.
So without further ado here are the major features included in this release:
- Ability to mark cards learned/unlearned
- Ability to choose a random card
- Cards now cycle so that if you are on card 1 and you attempt to go backwards, you are taken to the last card. Likewise if you are on the last card and you attempt to go forwards you are taken to the first card.
- Menus also cycle so that if you hit the back button you will go from the active card view to the lesson chooser to the lesson set chooser and back to the card view.
- Preferences to control settings such as card text size, whether to display learned cards, and a button to remove all learned cards from the internal database.
Some interface items had to be chopped to make room for these improvements. So if you are wondering where the next/back buttons are, they have been removed in favor of the more intuitive gesture controls. Swipe right for next card and left for previous card. Tapping the card flips it over.
I also want to give a special thanks to everyone who contacted me with words of encouragement and everyone who brought to my attention things that were broken and things that could be improved upon.
This release also includes a new lesson set, RossWords, which is being put together by Samuel Rogers as he takes Hebrew this year. If anyone else is feeling generous and would like to help out, feel free to contact me about a lesson set that you could help me improve upon or create as Samuel is doing.
Here are some screen shots from the new version:




And as usual, you can find Bible Flashcards in the Android Marketplace by searching for “Bible Flashcards” or by scanning the barcode below:
Learning CSS can be a bit daunting if you’ve never encountered it before. Likewise, if you’ve only had limited exposure to CSS, the various ways browsers implement various aspects of the CSS standard (or make up their own) can leave you with the impression that it is all a giant hairy mess. So to help out, I’ve compiled a list of resources to make the learning curve not quite as steep for beginners and to hopefully help tame the CSS wilderness for novices.
First, here is a pretty good and in-depth video on HTML and CSS basics:
Next we have several handy beginner’s tutorial sites:
- HTML Dog’s CSS Beginner
- Friendly Bit’s Beginner’s Guide to CSS and Standards
- Your HTML Sourse’s Introduction to CSS
- W3 Schools CSS Tutorial (also an excellent reference site)
Finally, here are a few CSS frameworks designed to help make CSS a lot easier by providing a standard system that takes care of much of the common ugly quirks found in CSS:
As a bonus, here are a few inspirational sites to help give you an idea of what CSS can do if applied properly:
Simple JSON-RPC has been updated to 0.9.7. This new version includes the ability to enable using full class names rather than simple method names. This makes using multiple classes with the same public method names possible.
To enable this functionality simply add an init-param to your web.xml file like:
<init-param> <param-name>use_full_classname</param-name> <param-value>true</param-value> </init-param>
With this feature enabled, you then call methods via their full classname + method name separated by a dot (this nomenclature is for both static as well as non-static methods, the framework handles the particulars in the back-end).
Special thanks to Stephan of Cross Pollinate for suggesting this improvement!
Bible Flashcards is an Android application based on the data files provided by the Crosswire Bible Society‘s Flashcard application. It contains flashcards for both Greek and Hebrew along with appropriate fonts for proper display.
I’ve also included an additional lesson set titled “greekBasics” which includes flashcards for the Greek alphabet.
Here are some screenshots:




Additionally, if you are interested in helping out with new lessons or if you would like to provide feedback, please feel free to email me.

