What is Currying?

Being a (fairly) little-known concept in programming, currying seems worthy of its own blog post.

In general

Simply put, currying is where:

Methods may define multiple parameter lists. When a method is called
with a fewer number of parameter lists, then this will yield a function
taking the missing parameter lists as its arguments.
scala-lang.org

In PHP

Currying is not a built-in feature of PHP. However, as outlined in quite some depth in this excellent post over at Zaemis’ blog, it is possible to emulate much of the functionality of currying in PHP (or at least, in PHP v5.3 and above) through use of closures.

An example

My favourite example from Zaemis’ blog post (which I recommend you read) is as below:

  $userPercent = 0.5;   $userList = array_filter($percentVowels,       function($percent) use ($userPercent) {           return ($percent >= $userPercent);       });
It showed an anonymous function being used with array_filter() to filter an array. The array is filtered based on a dynamic value, and a closure is used to “inject” the threshold rather than using a global statement. The same could also be accomplished with currying.

The problem is array_filter() expects a callback function that accepts one argument–the current array element. Currying will allow us to prepare the function with the sorting threshold, and the intermediate function can be used as the callback.

  function callback($userPercent) {       return function($percent) use ($userPercent) {           return ($percent >= $userPercent);       };   }   $userList = array_filter($percentVowels, callback(0.5));

Cheers, Dan Phillimore

About the author

  • Dan has spent the past 10 years developing specialist software, using everything from x86 assembly to C++ and VB. For the past few years he has focused on JavaScript development of high-performance virtual machines for the modern web and developing bespoke modern websites using the LAMP stack.
  • When he is not working on the next web-based OS, he spends his time out with friends, his girlfriend Jen or planning to buy an American muscle car.

Why isn’t my code being executed in IE?

The problem

if ( !window.TestClass ) {  function TestClass() {    // ...  }  TestClass.prototype.go = function () {    alert("gone");  }; } var test = new TestClass(); test.go();

In IEv6, v7 & v8, the above test case fails. This is probably an example of IE’s JScript engine getting ahead of itself: the function “TestClass”, a class constructor here, appears to be defined ahead-of-time (ie. before the if (...) is reached), resulting in the if (...) test failing and the prototype method not being set. The error then occurs on line 10 because there is no defined method “go”.

The solution

Many of you will probably never encounter the above problem: it only seems to be an issue when the function is defined in the global scope. If defined in a closure (as is common for module patterns), the problem goes away. Example below:

(function () {  if ( !window.TestClass ) {   function TestClass() {     // ...   }   TestClass.prototype.go = function () {     alert("gone");   };   // (Of course, this line is now needed in order to expose   //  the class to the global object)   window.TestClass = TestClass;  }  var test = new TestClass();  test.go(); })();

This problem will affect any logic (in the global scope) that defines functions in IE – use of functions as class constructors is just one example. Assuming you use a proper module pattern to encapsulate the code you write, you should not encounter this problem. Gotcha!


Update 27/07/2011

It appears that this problem affects more than just Internet Explorer: further testing in Google Chrome reveals that the following code will create issues:

// You would expect that DOMParser would only be created if it wasn't already defined; //  unfortunately, the function declaration below is always executed, overwriting //  any native implementation. The fix, as mentioned below, is to wrap this code //  in a closure to give it a private scope, then expose the class outside. if ( !window.DOMParser ) {  function DOMParser() {   // ...  } }

This is a simplified example (of the job I was solving before in IE, that of emulating the W3C-defined class DOMParser ), but it demonstrates the problem again. The idea is to define a DOMParser class only if one does not already exist (leaving a native implementation alone). Unfortunately, ECMAScript is counter-intuitive in this respect: the class/function DOMParser is defined regardless of whether the if (...) passes, overwriting Chrome’s own native DOMParser class/function.

Once again, the fix is simple: to properly wrap the code in a closure for a module pattern:

(function () {  // Now DOMParser is hidden inside this private scope, stopping it from overwriting  //  any native implementation if one exists. Note the need for an additional  //  instruction at the end to expose the class/function to the global scope once again.  if ( !window.DOMParser ) {   function DOMParser() {    // ...   }   // See above: expose to global scope   window.DOMParser = DOMParser;  } })();

Cheers, Dan Phillimore

About the author

  • Dan has spent the past 10 years developing specialist software, using everything from x86 assembly to C++ and VB. For the past few years he has focused on JavaScript development of high-performance virtual machines for the modern web and developing bespoke modern websites using the LAMP stack.
  • When he is not working on the next web-based OS, he spends his time out with friends, his girlfriend Jen or planning to buy an American muscle car.

IE X-UA-Compatible Multiple Versions & Conditional Comments

Internet Explorer v9 will include includes a great many performance & compatibility enhancements over its predecessors. For IE8, it has been useful to limit its rendering engine to display as IE7′s: for this, the X-UA-Compatible header is used,
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
as documented at MSDN.

To target different versions of IE with different engines, for example when needing IE8 to use IE7-mode but leaving IE9 to use the latest engine, MSDN states to use the following syntax, eg:

<!-- MSDN-recommended syntax (warning: see note below) --> <meta http-equiv="X-UA-Compatible" content="IE=7;IE=9" />

However, as stated in this post at stackoverflow, this does not work: instead, use a comma to separate the values (“,”), rather than a semi-colon (“;”):

<!-- Correct (working) syntax --> <meta http-equiv="X-UA-Compatible" content="IE=7,IE=9" />

In theory, an alternative would involve wrapping the X-UA-Compatible <meta> tag with some of IE’s proprietary conditional comments (condcoms). Unfortunately, this would present a “chicken-and-egg” problem, as the effective browser version (ie. v8 for IE8, v7 if EmulateIE7-mode) must be determined before any condcoms are evaluated: this means the X-UA-Compatible tag cannot then change the browser version (for example, to “EmulateIE7″).

Modes for “IE=” component of X-UA-Compatible:

IE=7
IE7 – forced mode, rendering will always be as for 7
IE=EmulateIE7
IE7 – emulated mode, rendering will be determined as it would in IE7 itself, using <!DOCTYPE …>, choosing between IE5-compatible “quirks” mode or IE7′s “standards-compliant” mode
Cheers, Dan Phillimore

About the author

  • Dan has spent the past 10 years developing specialist software, using everything from x86 assembly to C++ and VB. For the past few years he has focused on JavaScript development of high-performance virtual machines for the modern web and developing bespoke modern websites using the LAMP stack.
  • When he is not working on the next web-based OS, he spends his time out with friends, his girlfriend Jen or planning to buy an American muscle car.

Windows Live (Hotmail) POP3/SMTP settings for Mozilla Thunderbird (and others)

Having been plagued by error messages from the Hotmail/Webmail extension for Thunderbird, I finally decided to try and fix the problem.

It turns out that the extension is no longer supported (see also here) – as Hotmail is now available for POP3/SMTP use, details (set up for Thunderbird) are:

POP3 (incoming) settings:

POP3 Server:
pop3.live.com
Port:
995
User Name:
(Hotmail email address)
Connection security:
SSL/TLS (which is odd: see below)
Authentication method:
Normal password

SMTP (outgoing) settings:

SMTP Server:
smtp.live.com
Port:
25 (or 587)
Connection security:
STARTTLS (SSL/TLS does not work for Hotmail!)
Authentication method:
Normal password

As noted above, it took me several hours to figure out that Thunderbird‘s SSL/TLS option is not compatible with Hotmail (but this only applies to SMTP) – I had to use STARTTLS.

Cheers, Dan Phillimore

About the author

  • Dan has spent the past 10 years developing specialist software, using everything from x86 assembly to C++ and VB. For the past few years he has focused on JavaScript development of high-performance virtual machines for the modern web and developing bespoke modern websites using the LAMP stack.
  • When he is not working on the next web-based OS, he spends his time out with friends, his girlfriend Jen or planning to buy an American muscle car.

Basic website workflow

In this post I would like to outline the basic workflow I follow when designing and building a website from the ground up. This is by no means a complete list, its intention is to clarify for myself, if anything, the basic steps required and hopefully to give some pointers to aspiring developers on how to design their own workflow. I also intentionally leave out stages where server-side scripting is involved, for example, for simplicity.

Step 1. Determine that a WWW site is the solution.

This step is far too complex to explain fully here: suffice to say that you must always decide on the optimum way to proceed with a project, before actually embarking on it. Are you a locally-based business who would find it difficult to work outside a 100-mile range? If so, perhaps a world-reaching website is not the best solution to advertise your business: you may find that, at least in the short term, your resources would be better spent setting up billboard/on-vehicle (eg. bus) or local radio advertising, for example. Once you know you want a website, put some resources into it: remember, first impressions count, so you want your new website to impact hard, or those potential customers might leave and never come back. Pool your resources, bring together any information which might help you organise your site, be it photos, your company logo/coat of arms, letterheads, posters and other promotional gear, and use those to make sure your website forms an extension of your existing promotional material (and reduce how much time you need to lean on your graphics designer.)

Step 2. Draw-up a spider diagram

Nobody can visualise the perfect website in their head: design, colour scheme, layout, content, categories, tags – these should all be noted down and linked together, in much the same way your site’s pages will need to link to each other. Do you need to design a new logo for the site? If you have a colour scheme in mind, you should use it in the logo to bring the look together: if not, you should design your logo and then derive the basic colour scheme from there (see below.)

Step 3. Content is King

Now that you know what kind of content you need on your site, your best next move is to get some content written down: use an existing editor, such as WordPress, even if you plan on building your own CMS, to quickly set those wheels in motion and generate unique, relevant and useful content for your site. Link early, link often: outbound links should direct the user to further information, in the same way you would (hopefully) direct your customers elsewhere if you did not have the item they wanted. You might not have their custom this time, but they are likely to gratefully remember your helpful advice and recommend you to others.

Remember: Content is King. In the past, design was involved and tied to the editing process, as <font> tags and <b>/<i> etc. were used to style the content. Fast and effortless, but changing the layout later, or even just keeping it consistent, quickly becomes laborious. Instead, use modern techniques. Mark up those articles in a semantic way, using <p> for paragraphs, <h1> etc. for headings, <ol> for lists of items where the order matters, <ul> for lists where it does not, etc. These allow CSS to be utilised later to apply your chosen design to the content, at the same time enabling future changes in design to be implemented right across the site with ease.

Step 4. Decide on a colour scheme

Your colour scheme will usually have little to no bearing or effect on the content of your site, so you can safely leave this part until now provided you semantically mark up your content. I always recommend the following basic guidelines when choosing a colour scheme: black and white can of course be combined with anything, so these are the first two items in your colour scheme. Now choose around 4 other colours: there are many excellent tutorials on the web for this, aPaddedCell article here being a good example.

Step 5. Basic HTML structure

Aim for either HTML 4.01 or XHTML 1.0 compliance. Which to choose depends on many factors, personally I prefer the strictness of XHTML where possible. Once decided, begin building your basic code structure template: use a <!DOCTYPE>, include the <html> tag, include the <head> and <body> and try to close elements where possible (eg. <p> tags, but never <img> tags) to eliminate the possibility of a “tag soup” as this post explains.

Try to avoid writing any CSS until you have the HTML structure laid down. When building a house, the foundation must be solid before you start building the walls. With HTML/CSS, you follow a similar pattern: this also allows users with outdated browsers, or those with CSS disabled, to continue to use your site: allow for “graceful degradation”. Make allowances in the code for the CSS to be applied, though: if there is no suitable semantic element for a block of content, a <div> will of course be used – It would be a good idea to assign these semantic, relevant classes so styling rules can easily be pointed at them later. Use <div class=”links_wrapper”>…</div> instead of <div class=”blue”>…</div> so that classnames reflect the purpose or function of an element, rather than their styling. For sections which will only exist once on the page, it may be more suitable to use an id, eg. <div id="footer">...</div> . Avoid use of the style attribute: it has much the same drawbacks as <font>...</font> or <b>/<i> tags.

Step 6. Begin styling your site

This stage of the development is where the fun (and headaches) begin. With so many browsers out there, each with its own quirks, it is virtually impossible to make your site look the same across all browsers, possible user configurations and eg. MS ClearType and similar settings. There have been major improvements in this area, particularly with the advancement of standards-compliant browsers, and it is clear that websites should be developed to accommodate the user’s settings, rather than compensate for or override them. Using ems for measurements (where applicable) is preferable as it allows proportional scaling of the page’s text by the user (a good comparison of units em, pt, px and % is available here, be sure to read the comments too.)

Once you have your layout looking acceptable in modern, compliant browsers (Firefox, Chrome, Opera, Safari etc.) and have your semantically marked-up pages easily styled consistently, it is then time to test for Internet Explorer. There have been many articles on IE-related headaches and workarounds, too many to count or list here, but my own technique is to begin with the latest (currently IE8, although an IE9 RC (Vista+ only) is currently in the works), apply any fixes in a separate stylesheet included using conditional comments:

<!-- ... --> <head> <!-- ... --> <!--[if lte IE 8]>         <link rel="stylesheet" href="css/ie_lte_6.css" /> <![endif]--> </head> <!-- ... -->

… and then move back a version & add fixes for IE7. I often find it useful to apply the fixes as shown before, so all IE8-related fixes are applied to 7 & 6, as this usually results in less work and less CSS, but YMMV.

Step 7. Review, Rinse, Repeat

So you have your basic website: but are you happy with it? By now you will undoubtedly have identified some problems with either your own workflow or the way in which your content is marked up, so go ahead and correct those errors now while there are few changes to make: it will save you time in the long run. Remember: build a solid website first and then publicise it: you want your first impression to impact your audience hard, draw those customers in and keep them there, but you want to build solid, useful content first and not concentrate on link building to begin with – after all, what use is a high-ranking site with many inbound links and a high PageRank if your customers have nothing to read when they get there?


This post is by no means complete, I intend to improve on it at a later date, but please feel free to leave a comment.

Cheers, Dan Phillimore

About the author

  • Dan has spent the past 10 years developing specialist software, using everything from x86 assembly to C++ and VB. For the past few years he has focused on JavaScript development of high-performance virtual machines for the modern web and developing bespoke modern websites using the LAMP stack.
  • When he is not working on the next web-based OS, he spends his time out with friends, his girlfriend Jen or planning to buy an American muscle car.

Fix Firefox Button Padding

As we all know by now, consistently styling form elements with CSS is virtually impossible. However, with a few tweaks and after reading Firefox’s user-agent CSS file forms.css, I discovered the following:

button::-moz-focus-inner,  input[type="reset"]::-moz-focus-inner,  input[type="button"]::-moz-focus-inner,  input[type="submit"]::-moz-focus-inner, input[type="file"] > input[type="button"]::-moz-focus-inner {     border: 1px dotted transparent;     padding: 0 2px; }

… Firefox uses pseudo-elements within the button elements themselves for drawing. As you can see above, this means that padding of 2px is added to the top and bottom of this inner pseudo-element, therefore it may be removed as follows:

button::-moz-focus-inner, input[type="button"]::-moz-focus-inner, input[type="submit"]::-moz-focus-inner, input[type="reset"]::-moz-focus-inner {     padding: 0 !important;     border: 0 none !important; }

… thereby removing the padding (and in this case, the inner border too, as it was extra spacing not required; however I suspect it is used for the dotted selection border visible when a button has the focus.)

For completeness, I generally enclose such Firefox-specific code as below, more as a descriptive markup than anything else, however it serves to stop the rules being interpreted by any other browser, also being useful for targeting Firefox-only CSS:

/* Used within FF chrome to target CSS to specific URLs: being FF-specific, it is also useful for targeting FF-only code */ @-moz-document url-prefix(http://) {     button::-moz-focus-inner, input[type="button"]::-moz-focus-inner, input[type="submit"]::-moz-focus-inner, input[type="reset"]::-moz-focus-inner {         padding: 0 !important;         border: 0 none !important;     } }

Cheers, Dan Phillimore

About the author

  • Dan has spent the past 10 years developing specialist software, using everything from x86 assembly to C++ and VB. For the past few years he has focused on JavaScript development of high-performance virtual machines for the modern web and developing bespoke modern websites using the LAMP stack.
  • When he is not working on the next web-based OS, he spends his time out with friends, his girlfriend Jen or planning to buy an American muscle car.

Useful Intel x86 emulator development links

After looking over the many piles of paper lying around with hastily-scribbled notes on, some of which were starting to fall behind cupboards or collect numerous coffee rings, I decided to start noting things down on this blog instead. This post is mainly intended to serve as an aide-mémoire, used in a recent project of mine which should see the light of day this year.

Ralf Brown’s Interrupt List (RBIL)

At time of writing, RBIL is currently in Revision 61, July 17, 2000 and is almost 8 MB in ASCII text (see Wikipedia’s article.)

Common, well-supported x86 emulators

Bochs

Highly portable, open source PC emulator, written in C++. Bochs is/was much-referenced during the development of a recent project of mine, as mentioned above.

QEMU

A generic and open source machine emulator and virtualizer, QEMU is open source and extremely fast during emulation thanks to its dynamic translation engine.

Cheers, Dan Phillimore

About the author

  • Dan has spent the past 10 years developing specialist software, using everything from x86 assembly to C++ and VB. For the past few years he has focused on JavaScript development of high-performance virtual machines for the modern web and developing bespoke modern websites using the LAMP stack.
  • When he is not working on the next web-based OS, he spends his time out with friends, his girlfriend Jen or planning to buy an American muscle car.

Smoothly scale images in IE (-ms-interpolation-mode: bicubic)

Today I discovered a much-improved method to fix IE7′s default image-resizing behaviour: as described in this Flickr post it is possible to tweak IE7 into applying the (much smoother) Bicubic interpolation method when scaling images.

The result is depicted in this archived post here (which also happens to provide a solution for IE6, using the infamous AlphaImageLoader).

This is definitely an improvement on my previous method: after copying the client’s images over, I used GD on my own server (as they happened to be stuck with Windows shared hosting) to perform the smooth downsampling (think imagecopyresampled) before presenting to the user. A nice effect, but cost me (and my client) precious bandwidth – this solution is much more acceptable.

Microsoft’s hidden -ms-interpolation-mode CSS property

This little gem kicks IE7′s rendering engine into touch: “-ms-interpolation-mode: bicubic;”

Possible values for those interested (from MSDN) :

/* ... */   /* (Default) - Always use nearest neighbor interpolation mode. */ -ms-interpolation-mode: nearest-neighbor;   /* --- OR --- */   /* Always use <strong>high-quality</strong> bicubic interpolation mode. */ -ms-interpolation-mode: bicubic;   /* ... */

Cheers, Dan Phillimore

About the author

  • Dan has spent the past 10 years developing specialist software, using everything from x86 assembly to C++ and VB. For the past few years he has focused on JavaScript development of high-performance virtual machines for the modern web and developing bespoke modern websites using the LAMP stack.
  • When he is not working on the next web-based OS, he spends his time out with friends, his girlfriend Jen or planning to buy an American muscle car.
Powered by WordPress | Design by OVMS, based on AnimeStar (Best MMORPGs | Thanks to MMORPG List, VPS Hosting and Website Hosting)