Chip's Tips for Developers

Contains coding, but not narcotic.

Tee utility in Ruby that works on Windows

June 28th, 2008 1:37:07 pm pst by Sterling Camden

I often check my referrer logs to see how people found my site.  Chip’s Tips gets the vast majority of its traffic from search engines.  Sometimes I’ll see a search that didn’t quite reach its intended result, and that will inspire a new post.

Quite often I see “ruby tee windows” or something similar, which leads people to my tee utility for Windows.  That seems fair enough, except that it isn’t written in Ruby.  It’s written in C#, which means that it has 12 source files and the “real” code requires 29 lines.  Furthermore, since it’s a .NET executable, it won’t run if it’s installed in a folder that isn’t “trusted”.  Talk about red tape.

Besides, this application is trivial with a capital TRIV in Ruby, using the ’shell’ library.  Heedless of its impact on page load time, I’m including the entire source file right here:

require 'shell'
Shell.new.tee(ARGV[0]) < STDIN > STDOUT

Save that to tee.rb, and then you can perform the canonical basic test:

echo hello world | tee.rb "hello.txt"

See “hello” echoed to the console, and check out the contents of hello.txt.  Naturally, this utility is far more useful for trapping the log of a long build procedure or some other process that generates tons of output, but which you’d like to see echoed to the console at the same time.

Of course, you could also do the whole thing at the command line:

echo hello | ruby -e "require 'shell';Shell.new.tee('hello.txt') < STDIN > STDOUT"

But I like having it saved in a file so I don’t have to remember it.  This should also work just fine on *nix systems, but heck you’ve got the native tee there.

Tags: , , ,

Posted in Ruby, UNIX, Windows | 1 Comment » RSS 2.0 | Sphere it!

Subscribe to comment edits plugin for WordPress

June 23rd, 2008 4:20:36 pm pst by Sterling Camden

For blog surfers who still rely on their email Inbox, the Subscribe to Comments plugin (originally by scriptygoddess, updated by Mark Jaquith) is truly a goddesssend.  Just by ticking a box, commenters can be notified by email whenever additional comments are added to a post.  But, it doesn’t notify them when comments are edited.

OK, you’re thinking “Why do I care to know when user ‘teratroll’ corrects his/her misspelling of ‘turd-for-brains’?”  Ah, but that’s not all the “edit comment” functionality can be used for.

The ever so conversational Teeni uses the “edit comment” facility to respond to comments.  She adds her response in bold right underneath the original.  While I prefer to use Brian’s Threaded Comments and take my place among all the other respondents, Teeni’s technique does feel more intimate.  The only problem with it, from a commenter perspective, is that the “Notify me of followup comments via e-mail” checkbox would notify me of all the comments except those from Teeni herself.  That is, until now.

I created the “Subscribe to Comment Edits” plugin (which you can download below) to piggyback on the “Subscribe to Comments” plugin.  It adds notification to all subscribers whenever a comment on a subscribed post is edited.  It does nothing if “Subscribe to Comments” is not activated.

Even though PHP is mostly a baling-wire and bubblegum excuse for a programming language, it does support some dynamic programming features – a couple of which can be seen in the few lines of code that comprise this plugin.  For instance, function_exists is used to determine whether the “Subscribe to Comments” plugin has been activated.  And create_function does just what its name implies — it creates an anonymous function to pass as a parameter.  That’s nice, because the anonymous function doesn’t introduce any possible name collisions — but on the other hand, if the original function had been named I wouldn’t have to duplicate it here.

I would have also made the ‘init’ function anonymous, but the escaping of quotes gets ridiculous.  That’s one case where less dynamic, more functional would be preferable.  In languages like Javascript and Ruby (and of course Lisp), you can write functions in-line wherever a datum can go, without any quoting.   But in PHP, functions aren’t really first-class objects — they’re always passed by name, and create_function returns a generated name.

Also note that the fact that $sg_subscribe is a global object (yuck) is exactly what makes it possible for me to piggyback onto its functionality without modifying the original plugin (yay).

Posted in PHP, Web, WordPress | 3 Comments » RSS 2.0 | Sphere it!

Automatically saving del.icio.us tags as WordPress tags

May 23rd, 2008 4:59:36 pm pst by Sterling Camden

Over on Chip’s Quips, I use the “daily blog posting” feature of del.icio.us to post links on my blog.  These posts automatically contain links to each of the del.icio.us tags that I assigned to each link.  But I also use tags in WordPress, so I wanted to have a way to combine these taxonomies (that’s a megalellenicologism for classification systems) automagically.

Hence and forthwith, I present the Taglicious plugin for WordPress (not to be confused with the taga.licio.us plugin for WordPress), which you can download below.  Whenever a post or page is saved, the content is scanned for any del.icio.us tags, and the corresponding WordPress tag is added to the post if it doesn’t already exist.  There’s also a management page in the admin panel (Manage/Taglicious) that contains a single button to update all existing posts and pages.

The regex for detecting del.icio.us tags bears some discussion.  It looks like this:

|<a href="http://del.icio.us/(\w*/)+([^"#]*)|

(using | as the delimiter to avoid having to escape /).

We look first for a link to the del.icio.us site, followed by one or more word-like URL “folders”, followed by anything up to but not including an end-quote (terminating the link) or # (which is used for specifying a starting date, etc.).  This means that any del.icio.us link will get translated into a tag, even if it is someone else’s link.  So be warned.

Posted in PHP, Web, WordPress | 1 Comment » RSS 2.0 | Sphere it!

99 bottles of Ruby

May 16th, 2008 3:43:49 pm pst by Sterling Camden

Inspired by a post from Chad Perrin, I became a little bit obsessed with the 99 bottles of beer problem again.  Specifically, how to reduce it to the fewest number of characters possible in Ruby.  I came up with beer2.rb in the download below, which uses 231 characters to generate the entire song strictly according to the lyrics given at 99-bottles-of-beer.net, including capitalization.

I submitted my version to 99-bottles-of-beer.net.  A few days later, I received the following response:

Dear Chip Camden,

we would like to thank your for your contribution to the ‘99 bottles of beer’ website. Unfortunately we couldn’t accept your submission for the following reason:


Not a minimal code contest.

The team of http://www.99-bottles-of-beer.net/

:(

But still, I thought my minimal version was an interesting demonstration of the power of Ruby.   It can even be combined onto one line.  That means that using ‘ruby -e’ you could generate the entire song from the shell prompt.

The flexibility of the Ruby language can be seen by comparing the other Ruby versions that have already been submitted, especially the example from Victor Borja that uses continuations.  Wrap your head around that one, and you’ll feel like you drank 99 bottles of beer.

In the download below, I’ve also included what I feel to be the most readable version so far – in beer.rb.  It’s simple, concise, and clear.  See what you think.

 

 

Posted in Ruby | 3 Comments » RSS 2.0 | Sphere it!

Scoping a wait cursor in Synergy/DE

May 5th, 2008 11:23:28 am pst by Sterling Camden

On Windows, Synergy/DE provides access to the mouse cursor via the WP_CURSOR subfunction of W_PROC. Because this API is purely imperative, managing a wait cursor properly becomes a recurring problem in non-trivial applications. Typically, it begins like this (in pseudo-code):

set wait cursor
do lengthy process
clear wait cursor

But what happens if “do lengthy process” throws an exception that’s caught outside this code? You’ll skip right over “clear wait cursor” and leave the user unable to click anything. What you’d like to do is more like this:

begin
  set wait cursor
  do lengthy process
end

… and have the cursor reset whenever and however you exit the code block.

The downloadable code below demonstrates how to do this with the new object syntax in Synergy/DE version 9. The WaitCursor class sets the wait cursor in its constructor and resets it in its destructor. So you can code it like this:

begin
  data wait, @*, new WaitCursor()
  do lengthy process
end

The data statement declares a variable that has the scope of its containing begin-end block. The variable wait is declared as an object (@*). We could have more precisely declared it as @WaitCursor, but that’s just more typing (pun intended). It’s initial value is returned by the “new” expression, creating a new WaitCursor object. This invokes its constructor, setting the wait cursor. When wait goes out of scope, the last reference to the object is lost, and the destructor is invoked and the cursor is reset — no matter how you get out of the code block. If you want to preserve the cursor instead, you can just pass a reference to the object out of the block in another variable, and clear that variable when you no longer want the wait cursor.

But what happens if you have nested operations that, agnostic of each other, each want to set a wait cursor? When the inner one finishes, it will reset the cursor to normal. That’s not what you want at all. I solved this by adding a static counter to the class, so we only reset the cursor if our count of active WaitCursor objects gets back to zero.

Of course it’s possible that other code is manipulating the cursor without using our class. That could definitely interfere with our scheme, and should be avoided if possible. One common case is the set of message box routines in the UI Toolkit (U_MESSAGE, U_MSGBOX, U_WAIT). These routines always reset the cursor to the normal pointer so the user can use the mouse to click the buttons. If you want to have the cursor go back to what it was before these routines were called, then you’ll probably need to wrap them in your own version that saves off the current cursor state, calls the original, and then restores the cursor.

Posted in SynergyDE, UI Toolkit, Windows | 2 Comments » RSS 2.0 | Sphere it!

Mixin modules for Synergy/DE

April 26th, 2008 5:26:39 pm pst by Sterling Camden

The new object-oriented syntax for Synergy/DE version 9 is pretty closely modeled after C#, because Synergex plans to create a CLR version of the language and they don’t want the syntax supported on the various platforms to differ by much.

That means, of course, that when we hear “Multiple Inheritance” we are supposed to close our eyes and ears, hold up a cross, load up with silver bullets, and make it go away.

And it’s true that MI has probably caused more problems than it solves in languages that support it. Sometimes the “need” for MI is really a symptom that you should have used composition instead of inheritance (the object “has a” <whatever you’re deriving from> instead of “is a”).

But sometimes MI can be useful. There are abstractions that apply to an object itself that cut across normal inheritance lines. For instance, there are lots of classes that you could compare for equality in some manner more abstract than comparing the identity of the objects. So, you’d like to overload the ==, !=, >, <, >=, and <= operators with methods that compare the objects in some custom way specific to the class. But why write all of those methods for every class that needs them? If each class had one method to compare the objects and return a value indicating less than, equal, or greater than — then all the operator overload methods could call that method, and they’d be essentially identical for each class. If you could inherit that code from a common source, you’d save yourself a lot of typing — and possibly a lot of paste and modify errors.

This idea comes to me from Ruby, which has the concept of “mixin modules” — code that can be added to any class to extend its functionality, without regard for its inheritance hierarchy. It creates a form of MI without all the screaming.

The downloadable code below includes a module in Comparable.dbl. Don’t compile that module, but if you include it within a class definition it will define the comparison operator overloads for you. These methods assume that your class contains a “compare” method that it can call to determine the appropriate result for each operation. Because Synergy/DE is a statically typed language, you also have to give it the types to work with, via .defines. So, for instance, in Person.dbl we have:

class Person
.define COMPARE_CLASS Person
.include "Comparable"

This creates the op_Equality, op_Inequality, and related methods that call the compare method to compare Persons. How do you compare Persons? Why, by their likability, of course:

protected static method compare, int
in req obj1, @Person
in req obj2, @Person
proc
using obj1.likability select
(< obj2.likability), mreturn -1
(> obj2.likability), mreturn 1
endusing
mreturn 0 ;==
endmethod

You might expect that the compare method will look pretty similar from class to class as well, so I also added the ability to generate the compare method automatically to compare a specific member (data or method). Just define COMPARE_MEMBER, as shown in SalesPerson.dbl:

.define COMPARE_CLASS SalesPerson
.define COMPARE_MEMBER annual_sales ;Compare their annual sales
.include "Comparable"

It’s also possible to have different comparisons for mismatched operand types. Just define COMPARE_TYPE2 (and optionally COMPARE_MEMBER2), as when comparing a SalesPerson to a Person.

.define COMPARE_TYPE2 @Person
.undefine COMPARE_MEMBER ;Don't generate "compare"
.include "Comparable"
protected static method compare, int
in req obj1, @SalesPerson
in req obj2, @Person
proc
mreturn -1 ;a SalesPerson is always less than a Person
endmethod

You may wonder why the second argument needs to have the “@” included in the definition, and why I called it COMPARE_TYPE2 instead of COMPARE_CLASS2. This is so you can define comparisons against primitive types like “int” or “string” as well.

The Programmer class in Programmer.dbl shows how the COMPARE_MEMBER definition can resolve to a member function:

.define COMPARE_CLASS Programmer
.define COMPARE_MEMBER geekQuotient()
.include "Comparable"

private method geekQuotient, decimal
proc
begin
data quotient, decimal
quotient = (num_languages * num_languages) * years_coding
if (ever_used_VB) quotient /= ^x(dead)
mreturn quotient
end
endmethod

See testComparable.dbl for examples of usage.

Naturally, you can use the same technique to create comparison operators for any class. As long as your comparison operators have complementary meaning (which I would recommend), you should never have to write your own overloads for them again.

You can expand on this idea to create other inheritable traits that cross inheritance boundaries. For instance, in Ruby, anything that acts vaguely like an array or collection includes “Enumerable” to get a whole host of useful methods.

So SalesPerson “is a” Person, but it also “is a” Comparable object. So is Programmer. Any other class into which you include Comparable also “is a” Comparable, without necessarily being a Person. We’ve achieved MI (Multiple Inheritance) via MI (MixIns), blurring the line between inheritance and composition.

UPDATED 4/28/2008 to add support for comparisons against primitive types, and to automatically undefine COMPARE_TYPE2 and COMPARE_MEMBER2 at the end of Comparable.dbl.

Posted in SynergyDE, Wildly popular | 4 Comments » RSS 2.0 | Sphere it!

OPML Blogroll widget 1.3 for WordPress adds tooltips

April 17th, 2008 1:47:33 pm pst by Sterling Camden

Thanks to a suggestion from Diego, I have added tooltips to each entry in the OPML Blogroll widget for WordPress.  These tooltips display the content of the “description” attribute of each outline entry, if one exists, when the user hovers the mouse over the entry.

Note that this is not an update to the OPML Browser plugin, although I plan to add the same feature to that plugin as well (along with a ton of other enhancements).

I used JavaScript to pop up and remove the Tooltips.  I decided to roll my own (with much help from Shelley Powers’ book Adding Ajax) rather than use an existing library, in order to keep the widget lean and to avoid conflicts with other libraries that might be in use on your blog.

Thanks to Internet Explorer, this seemingly simple enhancement required about twice as much JavaScript code as as a Firefox/Opera/Safari-only version would have.  Here are the differences that required special code for IE:

  1. Of course, events don’t get passed to event handlers.  So you use window.event.  No big deal.
  2. And we all know about addEventListener vs. attachEvent.  Not a problem, just wrap it in a function.
  3. If you attach a property to a DOM object, lose the reference, and then reacquire that same element from the DOM later, it doesn’t have the property you added any more.  Apparently IE gives you a new object each time.  So in IE, this plugin has to look up the tooltip for the current item every time it wants to be displayed.
  4. Not having the “currentTarget” property on the Event object in IE really sucks.  You can use “srcElement”, but it isn’t the same element as “currentTarget”.  For instance, if you have a “mouseover” event on an element that contains a link around an image, “currentTarget” gives you the element on which the event was specified, whereas srcElement will give you whatever contained element the mouse was actually over.  So this plugin accesses parentNode until it finds the one that’s meaningful.

Another nice “feature” of Internet Explorer keeps the tooltips from displaying at all in my theme – perhaps due to the use of float on nearby div’s.  I tried the fix outlined here to no avail.  It does work using the WordPress default theme, though, so there is hope.  Let me know how it works with your theme.

I also fixed a problem with the auto-discovery link in which the ending quote on the href was missing. :oops:

Linking to earlier versions for pingback.

 

Posted in CSS, Javascript, OPML, PHP, RSS, Web, WordPress | 11 Comments » RSS 2.0 | Sphere it!

Fun with global objects in Synergy/DE

April 11th, 2008 1:04:17 pm pst by Sterling Camden

I’m not a big fan of globals, but sometimes they make sense.  If you have a singleton object that’s needed by a lot of different code, you don’t want to have to pass it around everywhere.  Unfortunately, in Synergy/DE you cannot declare an object in global scope (common or global data section) — it’s disallowed by the compiler.  Tod Phillips, a Synergy/DE consultant, asked me about this limitation today and whether I knew any way around it.  Well, it turns out that you can declare static members in a class to do the same thing.  I sent him the following example, in which “wife.wilma” is the static member accessible from anywhere:

namespace fred
    public class wife
          public static wilma, @wife ;Here’s our “global” object


          public method nag, string
          proc
              mreturn “Now fred…”
          endmethod


    endclass


    main test_nagging
    proc
          u_start
          wife.wilma = new wife()
          barhop()
          u_finish
    end

    subroutine barhop
    proc
          u_message(wife.wilma.nag())
          xreturn
    end

 

endnamespace

To which Tod responded:

That’s great! (and I mean both the snippet and the subject matter)

I assume that I could also add :

                Public static betty, @wife
                Public static Teresa, @wife
                Public static…, etc.

without any data collisions/overwrites from one wife to the next? (This will be very important for the Flirt() and Liaison() methods).

-Tod

Me:

Absolutely.  You could even have a static array of type wife - though I’d recommend using the class girlfriend instead of wife.  Both classes should be derived from significant_other, and girlfriend implements the methods you mentioned more effectively with fewer side-effects when handling multiple instances.  You might also want to make those private, accessed via discreet methods.

Tod:

Uh-oh…

Be careful with the Bigamy() method. There’s a hidden system call that alerts the Feds. So I think you’re right re: girlfriend class – it doesn’t seem to contain any such calls, though the Gossip() method is so convoluted there’s no telling what will happen if it fires with other Girlfriend objects instantiated in adjacent memory…

Me:

True – that would likely cause a failure, since Synergy doesn’t support multiple threads.

Posted in SynergyDE | 4 Comments » RSS 2.0 | Sphere it!

Associative array (hash, dictionary) class for Synergy/DE

March 16th, 2008 1:29:29 pm pst by Sterling Camden

One of the more useful features found in many scripting languages is the concept of an associative array.  It goes by the name of a hash in Perl and Ruby, or a dictionary in Python.  A hash lets you associate key values with data, and later retrieve a datum using its key — often via a syntax similar to an array element reference.  On this lazy Sunday morning it occurred to me that Synergy/DE could benefit from such a facility.

The downloadable code below contains a Hash class that acts as an array of untyped objects with an alphanumeric index.  You can control the case-sensitivity of the key by setting the CaseSensitive property (which defaults to false) before adding the first item.  Because this uses the new Synergy class syntax, it requires at least version 9 of Synergy/DE.

Usage:

myhash = new Hash()
myhash['key'] = anyobject
anyobject = myhash['key']

If a key is not found, then ^null is returned.  Thus, to clear an item, just set its entry to ^null.  This hash does not reclaim any array entries, so it will eventually grow to the size of all keys that have ever been used to store a value.

As you can see in the code, the class uses an internal ArrayList to store the object references, and associates the keys with array indices using the built-in Symbol Table functions in Synergy/DE.  If the Symbol Table API could take objects as associated data then we wouldn’t need this class at all — but it doesn’t.  The Symbol Table API can only take primitive types for data, so we have to introduce this extra layer of reference in order to support objects.

Synergy/DE’s static typing gets in our way in usage as well.  Because the elements are typed as System.Object, client code must cast any returned element to the type expected.  If a primitive type is to be stored in the hash, then it must be cast as an object in order to box it.  Even though you can store a hash as an element of a hash to created nested arrays, you cannot dereference a nested element using a single statement, because you must first store the nested hash element into a variable of type Hash.  And we don’t get any benefit at all from static typing here.  Of course, you could create a derived class of Hash that expects and returns a specific object type.  That would better be a job for generics, which have not yet been implemented in Synergy/DE.  Personally, I’d like to suspend static typing altogether for a class like this, but that’s just the Ruby talking.

UPDATED 3/22/08: Added an iterator and Count property.

Posted in SynergyDE, Wildly popular | 11 Comments » RSS 2.0 | Sphere it!

Stopwatch application in C#

February 29th, 2008 1:51:12 pm pst by Sterling Camden

As an independent consultant who bills by the hour, I have to keep track of how much time I spend on projects for different clients.  When various emergencies arise, that can get pretty confusing to reconstruct at the end of the day.  I needed an easy way to monitor my time with just a few mouse clicks.  So a few years ago I created the simple stopwatch application that you can download below.  One click to start, another to stop.  You can enter a description, and previously entered descriptions are remembered in a dropdown.  You can run multiple instances to keep track of time for multiple clients.  At the end of the day, you’ve got a total for each.

I wrote this as a C# Windows application using Visual Studio 2003.  Converting it for VS 2005 introduced a challenge, because accessing a control from another thread (the timer’s) is now considered unsafe and throws an exception.  So as you’ll see in the SetText method, I adopted a work-around from the MSDN documentation.

Back when I wrote this application, the code seemed quite concise.  Now that I’m older and wiser and have been exposed to Ruby, I can’t get over how verbose it is.  I can’t help but think that to do the same thing in JavaScript would be pretty trivial.  Maybe I’ll give it a go one day.

Posted in .NET, C#, Wildly popular, Windows | 9 Comments » RSS 2.0 | Sphere it!

RC4 encryption in C

January 24th, 2008 11:49:44 am pst by Sterling Camden

RC4A couple of years ago, I published a routine to perform RC4 encryption in Synergy/DE, translated from the original VBScript of Mike Shaffer with his permission.  Lots of people searching for the RC4 algorithm have landed on that post, most of them not knowing the Synergy/DE language.  A couple of days ago, a reader going by the alias “crazysoccer” asked if I could provide an example in C.
 
The download below contains a straight C version of the famous “EnDeCrypt” function, along with a simple “main” test program.  The flavor of C I used is vendor and platform neutral.  It only presumes the availability of stdio and malloc.  Naturally, you could tweak this code to use whatever I/O and memory allocation mechanisms your development framework prefers.
 
I’ve been asked before about the legality of publishing cryptographic algorithms on the web.  According to Wikipedia (which is not a lawyer, nor do I think it has ever played one on TV), rules for exporting cryptography have been relaxed in recent years, including “the effective elimination of export controls on … open source software containing cryptography.”  Since I’m making this freely available to all, and I welcome any contributions to improving  the code, I’ll consider this “open source”.  Besides, I wasn’t the first one to publish this algorithm on the web, and if the Bureau of Industry and Security wants to come after me, it’ll have to go get 4GuysFromRolla, too.  But if you plan to use this algorithm in software that will be exported from the US or other nations with similar rules, you might want to consult your lawyer on any restrictions you need to follow.
 
UPDATE: Changed the API to include a specified length, since the encrypted data can contain a null.
 

Posted in C and C++, Wildly popular | 18 Comments » RSS 2.0 | Sphere it!

ElapsedTime class for Synergy/DE

January 7th, 2008 2:15:57 pm pst by Sterling Camden

For all of you Synergistas out there just getting familiar with the new object syntax in version 9, I’ve provided a simple but useful example of how to use a class to encapsulate reusable functionality (translate: make your life simpler).

When tuning code for performance, it’s often useful to be able to get the elapsed time of a specific operation.  Sure, you can use the Unix “time” command, but that gives you the execution time for the entire process.  Usually you want to narrow it down to a specific section of code, and you might even want to subtract out overhead caused by looping structures or other code that’s required just to get to the code in question.

Enter the ElapsedTime class.  When you create a new instance of this class, it makes a note of the current time and date.  You can reset the starting time at any time by calling its “reset” method.  When you want to find out how much time has gone by, you can either query the “nSeconds” property for a decimal value, or call the “ToString” method to get a formatted result.  For example:



import CamdenSoftware.ChipsTips

record
        timer ,@ElapsedTime

proc
        timer = new ElapsedTime()         (do something here you want to time)         writes(ttchn, “Elapsed time ” + timer.ToString())

To subtract out additional overhead, set the object’s “Overhead” field to the number of seconds to subtract from the overall time.  See the example program in the download below showing how to time a looping structure and then use that result as the overhead for timing operations within the loop.

Posted in SynergyDE | No Comments » RSS 2.0 | Sphere it!

Chart mixer for prototyping Google Chart API

December 11th, 2007 5:10:59 pm pst by Sterling Camden

Sample chartIn a recent article I wrote on [Geeks are Sexy] Technology News about the new Google Chart API, I mentioned that the only thing that’s not simple about this API is the data encoding. So, I set to work to remedy that and I whipped up the little tool you can download below to help prototype Google charts and generate the URL.

It doesn’t include all of the options in the API, but I did provide an “Additional qualifiers” field where you can append anything you want to the chart’s URL.

For now, it only supports Simple Encoding. I may add Text and Extended Encoding at some point in the future.

Next in line is to add some JavaScript to make this more interactive, as well as to wrap the Chart object in a WordPress plugin.

You can see this in action (and use it all you want) at http://chipstips.com/demo/chartmixer.php.

Posted in CSS, PHP, Web | 1 Comment » RSS 2.0 | Sphere it!

WiPeD away the class constants for PHP 4 compatibility

November 15th, 2007 10:06:21 am pst by Sterling Camden

Tony Peak (aka Rirath) helped to identify an incompatibility with PHP version 4 in my WiPeD plugin for WordPress.  Now, if back-porting to version 4 had involved a major rewrite I would have said “Routta Ruck, Rirath” — but it turned out to be pretty easy.  I had used class constants for the values in the database fields to indicate types of entries, and class constants weren’t supported in PHP 4.  Luckily, there’s a simple replacement:  define.  So, if you want to debug WordPress on PHP 4, download version 1.2 below.

Posted in PHP, Web, Wildly popular, WordPress | 2 Comments » RSS 2.0 | Sphere it!

Overlapping sidebar problem solved

November 7th, 2007 12:51:44 pm pst by Sterling Camden

A few days ago I started reading Shelley Powers’ new book, Adding Ajax, a free copy of which Shelley generously sent me.  In the very first chapter, Shelley said something that helped me solve a nagging problem that I’ve had for months.

Readers of this blog and my other one may have noticed (and some of you have remarked) that when my sidebar length exceeded the content length, the sidebar overlapped the footer and extended into dark space.  How amateurish.  But I had spent way too many hours tweaking the HTML and CSS trying to remedy the situation, and had finally given up.  The thing is, I knew how to avoid this aberrant behavior, but not without either displaying the sidebar first or making the content section fixed-width.  What I wanted was to have the content size fluid, the sidebar size fixed, and to display the content before the sidebar (for the benefit of all readers, but especially those using a screen reader or mobile device).  So I used a large right margin on the content and applied an absolute position to the sidebar.  But with that arrangement, clear:both on the footer ignored the sidebar’s length.  For someone who cut their web teeth using tables (or dare I admit it, frames) for layout, it was enough to drive me crazy.

In Shelley’s book, she gives a very clean and simple example that applies float:left to the content and float:right to the sidebar, drawing the latter last and applying clear:both to the footer — which works fine, except that in that case a fluid content section will take up all the available space, forcing the sidebar to appear beneath it.  But Shelley hinted that this was possible with fluid layouts, and said something even more useful at the end of her example:

For additional reading on CSS layouts, search the web for “fluid fixed elastic CSS layouts”.

Now, I had previously googled until my googler was sore trying to find a solution to this problem, but I hadn’t used those exact search terms before.  Since I’m not interested in fixed or elastic layouts, I omitted those words and googled anew.  This led me to the Holy Grail of web design.  Matthew Levine explains a simple but unique approach to making fixed-width sidebars float either left or right of a fluid center section, with a footer below them all.  In brief:

  1. Enclose all three sections within a container section, using position:relative and float:left to keep them from stacking vertically.
  2. Apply padding to the left and right side of the container for the desired size of your sidebars.  This restricts the fluid center section to the remaining space.
  3. Use negative margins on the sidebars, to move them back out over the container’s padding.
  4. For the left section, specify the position.  The right section gets bumped out automatically by the size of the center section.
  5. Use clear:both on the footer, to position it beneath all three sections.

Since I don’t have a left sidebar, I was able to do this even more simply:

  1. Enclose the content and sidebar sections within a container section, using position:relative and float:left.
  2. Apply padding to the right side of the container for the space to reserve for the sidebar.
  3. Use a negative right margin on the sidebar.
  4. Apply clear:both to the footer.

Naturally, this didn’t work the first time (when does it ever?) — I had issues with inherited padding, prematurely closed div’s, and other such nonsense that had accumulated like dust in my theme files over the course of many tweaks.  These were relatively easy to hunt down using the Web Developer toolbar for Firefox (which Shelley also recommends in her book), using the Display Block Size and Display Div Order options on the Information menu.  One issue that I suspect would have taken me much longer to hunt down had it not been for this feature was a conflict between div class names — my theme used “content” for the class of the main content section, and the Brian’s Threaded Comments plugin uses the same class name for the section that includes the contents of each comment.  So when I added float:left to ”.content”, the comments section went haywire.  That’s a good example of why, when writing a plugin, you shouldn’t use common class names or ids for elements it produces — you should always prefix them with something to make them unique, because you never know who else might be using that name as well.  To work around it, I just renamed my “content” class to “blogcontent”.

Over the years, I’ve learned CSS and Javascript on an “as needed” basis.  Shelley’s book seems well targeted for an audience of people like me, because it’s all about bringing existing sites forward to these newer approaches.  I’m sure that it will fill in some gaps for me — and that this won’t be the last solution that gets sparked from reading her pages.

Posted in CSS, Web, Wildly popular, WordPress | 2 Comments » RSS 2.0 | Sphere it!

WiPeD out trying to debug WordPress XMLRPC

October 15th, 2007 4:40:15 am pst by Sterling Camden

So I was coding along one fine day, happily using my WiPeD debugger for WordPress, when I suddenly stumbled on a problem with it.  I was attempting to debug a function that was hooked to an action that was supposed to be triggered by the MetaWebLog API (’save_post’, when posting from a blog authoring tool), and none of my debug messages were being displayed!  Suddenly the heel of my hand went *bonk* on my forehead — of course I couldn’t retrieve any messages from XMLRPC processing, because I was saving the messages in a session variable, and the client in that case is my authoring tool instead of my browser – so the sessions aren’t the same.  Duh, time to rethink.

The downloadable version below saves the debug messages to the database instead of to a session variable.  Obviously, that means that multiple users will mix their output in the log.  Of course, you’d expect to be debugging on a private site, but just in case I added an options page where you can exclude users based on their capabilities — with the default being ‘level_9′ (administrators only).  I also added options to allow you to customize when the debug log is displayed, as well as when it’s cleared.  Spin it up, and check out the Readme-WiPeD.txt file.

UPDATE: get the latest version here.

Posted in PHP, Web, Wildly popular, WordPress | 10 Comments » RSS 2.0 | Sphere it!

More OPML Browser corrections

September 26th, 2007 1:19:04 pm pst by Sterling Camden

Shack Dougall spotted several HTML coding errors in the latest verion of my OPML Browser plugin.  Get the version 1.3 below.

Pingbacks to previous posts.

Posted in OPML, PHP, Web, WordPress | 23 Comments » RSS 2.0 | Sphere it!

Wiping the mystery out of WordPress debugging

September 24th, 2007 4:33:52 pm pst by Sterling Camden

Speaking of the deficiencies of PHP, another one is the complete lack of built-in debugging capabilities.  Sure, you can find debuggers for PHP, if you’ve got the time and ability to configure them on your server.  I guess if I was really serious about PHP I’d have to get one of those, but so far I only use PHP for WordPress customization, so it hardly seems worth the effort.

Some people will tell you that you shouldn’t need a debugger.  That it’s a sign of lazy programming.  But PHP has so many pitfalls, and WordPress has so many actions and interactions between plugins and themes provided by so many different developers, that I think you’re excused if you need a little help figuring out just what the heck is going on in your code.

When writing a plugin or modifying a theme for WordPress, usually all I need to know is the order of events and the values in various variables.  Sometimes you can get away with inserting “echo” statements in your code — but sometimes you can’t, like when your code executes ahead of a “wp_head” action that wants to add headers.  Besides, randomly placed “echo” statements can easily get lost from view in the whirl of words and images that comprise your theme and content.

So, I developed a simple little plugin that collects debug statements and prints them out nicely above the footer of your theme, or below the admin footer, whichever gets executed first.  I call it WiPeD, for “Wordpress Printf Debugger”.  Anywhere in your code, you can call WPD_print() and pass it whatever text you want to output.  The lines of text are aggregated in a session variable until they are output together (in separate divs, surrounded by a single containing div).  Thus you can use styling to set the messages off from the rest of your blog, if you desire.

Here’s an example, from a project I’m currently working on.  My plugin was producing no results, and I couldn’t figure out why.  So I added some calls to WPD_print():

Then, when I executed the code to trigger this action, here’s what I saw at the bottom of my page:

That tells me that I got into my function and passed the tests, but the post has no content at that point.  Now I just need to figure out why.

See the enclosed readme file for more details.  Have fun debugging your PHP!

UPDATE: get an updated version here.

Posted in PHP, Web, Wildly popular, WordPress | 12 Comments » RSS 2.0 | Sphere it!

OPML browsing just got better

September 22nd, 2007 1:21:03 pm pst by Sterling Camden

 Version 1.2 of the OPML Browser plugin for WordPress has just been released!  This version includes some significant upgrades, including:

  1. You may now have up to 9 opml-browser widgets. When upgrading, the options from your existing opml-browser widget are copied to the first opml-browser widget.  Thanks to Mark Barnes for suggesting this enhancement.
  2. The option to exclude your domain now ignores differences in case when comparing domain names.  Thanks to Tony Lindskog for finding that one.
  3. You can now override the title for the OPML link by entering text into the “OPML title override” field.  I didn’t want mine to read “FeedDemon Subscriptions”, so I added that for myself.
  4. Added the ability to embed the browser within a page or post using a special [opml-browser] element in the text.  See the readme.
  5. Added a “Get this widget” link at the bottom of the widget.  Thanks to TDavid for suggesting that little bit of self-promotion.

Download version 1.2 via the button below.  Pinging back to all previous posts for those following comments.

UPDATE: More corrections here.

Posted in Javascript, OPML, PHP, Web, Wildly popular, WordPress | 20 Comments » RSS 2.0 | Sphere it!

PHP messiness: zero isn’t false, or is it?

September 18th, 2007 12:02:14 pm pst by Sterling Camden

Several years ago, Gary Hart said something that has stuck with me ever since: “just because it’s messy doesn’t mean you don’t want to do it.”  We were discussing plans for driving throughout the UK while there on business — but time and again I find this principle applies to other situations as well.  Besides the obvious, um, recreational possibilities, I can think of many more: eating sloppy sandwiches, parenting, electing public officials, starting a relationship, and coding in PHP.

PHP powers a lot of the web, including such popular frameworks as WordPress, so you really need to have it in your programming portfolio.  But it’s a messy language.   I’m not just talking about the way that PHP tends to sprawl like semicolon-laden vines around your HTML, earning an alternative interpretation of “Page Hacked to Pasta”.  Nor am I referring (this time) to its sucky object model.  The language itself contains many little gotchas and “almost right”s that wait like snares for the feet of the unwary coder.

One I ran into yesterday (not for the first time) is PHP’s partial distinction between false and zero.  In PHP, false is boolean, and zero is numeric.  Fine and good.  But if you treat a zero value as a boolean expression, the zero gets converted to a boolean false.

This seems innocent and helpful enough until you get to a function like strpos, which returns the position of one string within another.  If the target is not found in the source, it returns boolean false.  So, to make sure that one string doesn’t contain another, you’d think you’d do something like this:

if (!strpos($source, $target))

But there’s a problem here.  If $target starts at the beginning of $source, strpos will return 0.  Because it’s in a conditional, that gets converted to boolean false, and the test passes.  So, you need to explicitly test for false instead, right?

if (strpos($source, $target) == false)

Wrong.  Because you’re comparing it against a boolean value, the zero still gets converted to a boolean false.  The only right way to do this is:

if (strpos($source, $target) === false)

The triple equal sign tells PHP to only evaluate to true if both operands have the same type and the same value, so no conversion takes place.  Granted, the PHP docs have a great big warning on strpos to this effect, but the net result is something less than intuitive coding.

Languages like Java and C# solve this problem by not allowing automatic conversion between numeric and boolean values.  That’s sort of like castrating the entire population to prevent birth defects.  So why doesn’t this create problems for other languages?

In Synergy/DE, indices start at 1, so the instr function returns zero for not found:

if (!instr(1,source, target))

Quite logical and linguistically elegant (except for having the starting index as the first parameter), but then you don’t get to have the secret handshake.

Even though Ruby uses a starting index of 0, it prevents confusion in routines like String#index by returning nil instead of a number for not found.  Zero is treated as an object — and thus is not false — while nil does evaluate to false.  Thus,

print "good" if ("abcde".index("a"))
print “bad” if (”abcde”.index(”f”))

prints “good”, even though the index of “a” within “abcde” is 0.  Why should 0 be false anyway?

In C and C++, indices start at 0, and 0 can be used as a stand-in for false (in fact, all falses are zero), yet I hardly ever make the mistake of “if (strpos(…))” in C.  Why?  Because the documented return value for “target not found” isn’t FALSE, it’s -1.  I immediately know that to test for this return value I must say:

if (strpos(source, target) < 0)

The significance of the result does not rely on a distinction between returned values that can be automatically converted from one to the other.  PHP, on the other hand, requires the programmer to explicitly prevent that conversion from happening.  Automatic conversions are supposed to be a convenience for the programmer, not a trap.

Maybe PHP stands for Purposely Hampers Programming.

Posted in C and C++, C#, Java, PHP, Ruby, SynergyDE, Wildly popular | 47 Comments » RSS 2.0 | Sphere it!