Archive for January 2009

EU wants MS to take IE out of Windows

Word is getting around the the EU anti-trust agency is once again taking a stance against Microsoft. This time the target is Internet Explorer. The EU claims that IE is protected from competition by being bundled with Windows.

BBC Coverage

My thoughts:

IE is by far the dominate browser when it comes to number of users. It is the definition ubiquitous. At this same time it is easily the most critisized browser, even with respect to its market share. It seems to me that these two things should not go together. Microsoft has maintained this lead not through the quality of its software but by the precident of its use.

Personally my browser of choice is Opera, the developers of which were the ones to file the initial complaint that triggered the EU’s response. I do, however, still have IE and occasionally use it when it is necessary. This is probably the case with the majority of us who prefer an alternative to IE. So many sites and apps are coded with IE in mind, that giving up on IE entirely is all but impossible. Instead of being coded to the standards these sites are designed to work with IE, even if that means the function poorly or not at all in other browsers. Does this mean that it is impossible to code an application that works in all of the major browsers? Not at all. You can’t blame Microsoft for lazy developers, but you can blame them for not complying with standards. You may be wondering “If Microsoft is to blame for their lack of standards compliance, and that lack of compliance makes it harder to code apps that work in all browsers, isn’t Microsoft to blame for the lack of apps that work in all browsers?”. In my opinion the answer is no. If developers don’t like having to tweak their code to work with IE then don’t. Just make sure it works in Firefox, Opera, Safari, Chrome, or whatever browser you crazy Linux people are using today, and then stick a link on your footer that says “Best viewed in ANYTHING BUT Internet Explorer” and goes to a list of alternative browsers. If this became common practice IE would be up to standards by now.

That beings said, what about the EU and their stance against Microsoft? Should Microsoft have to remove IE from their operating system? In my opinion the answer is it doesn’t matter. The first thing I do when I install a fresh copy of Windows is go to Opera.com, download the browser, and stop using IE from that point on. Clearly, however, this is not the case with the majority of users today. Why? Some of us might think its because people are sheep who don’t know any better and in that case need the EU’s protection. Others would say that it is because IE isn’t that bad and switching to an unfamiliar browser isn’t worth it. I think the answer is that it works. IE works. It works not because Microsoft makes it works. It works because we make it work. We being developers who are willing to bend over backward just so their site looks pristine in IE. For this reason, even if the EU forces Microsoft to offer a version of Windows not bundled with IE, the majority of users will opt to have the version with IE. Even those that don’t will at some point download it because they ran into a site that is coded to not allow users with alternative browsers to view their content.

My point is: Don’t count on the EU to fix all of the problems you have with IE. If you are a developer who is afraid to publish a site that is compliant  to the standards, looks good in all of the alternative browsers, but for whatever reason isn’t quite right in IE then you are to blame. Stop worrying about your adsense revenue (you don’t make that much anyways :P ) and realize that if you act like sheep then Microsoft has no problem herding you. Worse yet, if you are a developer who prevents users who are not using IE from view their site, or happily notifies its users that “this site is bested viewed in Internet Explorer” then you should know that you embody all that is wrong with the world today.

Don’t Fear the Re(cursion)aper

For some reason whenever I see someone post code that cycles through an array or does something repeatedly, that code takes the form of some kind of loop. I admit that I’m guilty of this as well, but when I think about why I’m cannot come up with a reason. I’m comfortable with the alternative (recursion) and in many cases I have to think harder about a problem to formulate the solution in a loop rather than recursion.

For those of you who have not been schooled in the arts of recursion, in simple terms it involves a function calling itself or recursing until it finds a solution. A basic recursion has two portions: the base case, and the recursive case. The base case establishes a condition for returning, without it the recursion would be infinite. The recursive case is the case where the function needs to be called an additional time. To demonstrate this lets say we have an array of ten integers numbered 1 through 10 in order. I’ll write two functions for finding a value within that array, one using a loop and the other using recursion. Assume our array is called myArray and is already initialized.

<?php
function find($value)
{
     foreach($myArray as $x)
     {
          if($x == $value)
               return true;
     }
return false;
}
?>
<?php
function find($value, $position = 0)
{
     //this is an error case
     if($position > 9)
          return false;
     //this is our base case
     if($myArray[$position] == $value)
          return true;
     //this is our recursive case
     return find($value, $position + 1);
}
?>

A few things to take note of: First, our recursive version of the find function has a type of case I didn’t mention, an error case. Not every recursion will have an error case, but it must exist in case the value we are searching for does not exist in the array. Otherwise we would end up indexing outside of our array. A second thing to note is that the recursive version of the find function has a second parameter to keep track of the position in the array. The foreach loop in the loop version does not appear to have a value to keep track of our position but it still exists. Foreach is a shortcut syntax, the position is still being tracked but the programmer does not have to be aware of it (which is good in some cases, and bad in others).

Typically in recursive functions like the one above you want to be able to call it without having to give additional inputs for the recursion. This is possible in the case above because in PHP there exists default values. Above I default the variable position to 0 so even if that parameter isn’t given in the call the search will start at 0. In other languages this may not be possible, but there are alternatives. In java for instance there are no default values so we must rely on another feature: polymorphism. In java functions are identified by their signature, not their name. I can define a method foo that takes as input an integer and another method foo that takes as input a string. I’ll use this feature to implement the same recursive function in java.

public class RecursionTest {

     private int[] myArray; 

     public static void main(String[] args)
     {
          //assume myArray is initialized
          find(5);
     }

     private boolean find(int value)
     {
          return find(value, 0);
     }

     private boolean find(int value, int position)
     {
          //error case
          if(position > 9)
               return false;
          //base case
          if(myArray[position] == value)
               return true;
          //recursive case
          return find(value, position + 1);
     }
}

You may be asking “What’s the point of all this recursion stuff when the loop accomplishes the same thing?”. I have two answers. The first is performance and the second is modeling your problem. When you use a loop to solve a problem, any variables you create are allocated in the heap. Alternatively with recursion, your function calls are all placed in the stack.

Typically stack allocations are cleaner than heap allocations. The stack basically keeps track of function calls and their inputs. When a function is called it and its inputs are placed on the stack. When that function returns it and its inputs are removed from the stack. In this case all of the memory allocation occurs in sequence, the system doesn’t have to worry about searching for free space on the stack and the programmer doesn’t have to worry about making sure that information is deleted from the stack (in a non-garbage collected language I mean).

In the heap on the other hand, the runtime system must find memory large enough for your data to fit in, which could lead to fragmentation. When the data is no longer needed the memory must be marked as free.

Does this mean that loops are inferior to recursion? No. There are cases were a loop would perform better than a recursion.

Now, on to my second point: modeling your problem. Once you get comfortable with recursion you will find that there are some things that seem much simpler to code without loops. Recursion also forces you to create a function or method for a certain task rather than just throwing a loop into your code, which can lead to massive blobs of unorganized code. If you have trouble with organizing your code try recursion for a while and I guarantee you’ll produce code that is easier to deal with.

For the time being I’m going to set out to solve more problems with recursion rather than loops, just for the sake of being an outcast.

P.S. the title is a blue oyster cult reference and I don’t know why.

Intercepting Email with PHP

Here I will show you how to intercept an incoming email through piping. I have also written a guide on How to Access Email in a Mailbox through IMAP

One of the most frequent questions I’m asked, or I see asked on forums is “how do I send out an email using PHP?” The answer to that is fairly simple and well documented. It more or less involves the use of a single function mail().

Something a bit more complicated and, I think, more interesting is how you can intercept an incoming email with a pretty small chunk of PHP code. The answer to how to do this, though not so difficult to find out, is a far less trivial thing.

The Scenario (optional if you don’t feel like reading)

Say we are building a contact form for a web application. This pretty basic contact form takes whatever input  the user gives, to keep things simple we’ll just say its the users email address and a message. This message is then sent to a database where it can be read from an administrative control panel of some sort. This is pretty simple and for the most part effective. Personally I have a problem with this type of setup. If users are not logged in when using the form there is no guaranteed way to respond. The email address they provide may or may not be valid, or they could just be spamming some nonsense because they are anonymous in the Internet and no one can stop them. A simple solution: Force users to log in. But Wait! what if users are having trouble creating an account or logging in and this is the reason why thy need to contact you? OK, to solve this problem we’ll just set up an email address that users can contact us with in addition to the form. This solves the problem of reliable contact information and minimizes the spam problem (the email address can still be spammed but a lot of it can be filtered). So once this is all setup will have a contact form that sends info that can be read by all of our admins in our admin panel… and the occasional email to some email account that all of our admins will need the password to to check regularly.

This may be acceptable to some… but not to us! We know of a better way to consolidate all of our communications with our users while at the same time having our desired setup. OK maybe you don’t or else why would you read this. Here’s how we do it:

The Code(this is where you should start reading if you like to get to the point)

Some of you may be thinking that PHP is so magical that there is a simple function that is going to go out and fetch the email we want from where ever it is on the server. Well you’re wrong (not about the magical part). What we need to do is setup a script that can capture the email when the server recieves it. This is actually pretty simple, all we need to do is extract the email data from standard input (php://stdin).

$file = fopen('php://stdin', 'r');

Once we establish a file pointer to our input stream the rest is the same as reading in any other file. Here’s the complete code:

< ?php
$data = '';
$file = fopen('php://stdin', 'r');
while(!feof($file))
{
     $data .= fgets($file, 4096);
}
fclose($file);
?>

$data now stores the raw content of the email, headers and body. At this point we just need to decide what to do with the email, I’ll leave that for you to decide. So other than that our script is complete correct? False. We have not yet addressed one crucial step. The server needs to be told how to execute this script. You may be wondering, why would we have to tell the server what to do with a .php file… its .php! The main difference between a user requesting a .php file via the internet and what we are doing here is what is handling the request. When a user goes to index.php on your website, apache knows what to do with the file because that is how it has been configured. The server on the otherhand will not necissarily assume that the file should be parsed by php. So how do we tell it to you say? Hashbang. A hashbang tells the server how to handle a file, in our case we will use the following hashbang #!/usr/bin/php -q. Note that this may or may not work for you depending on the path to php on your server. The one I’m using is the default, so if you’re not sure use that one, otherwise contact your hosting provider. Ok so here is our completed, hashbanged code:

#!/usr/bin/php -q
< ?php
$data = '';
$file = fopen('php://stdin', 'r');
while(!feof($file))
{
     $data .= fgets($file, 4096);
}
fclose($file);
?>

Note that the hashbang is outside of the php tags. This is absolutely necissary for the script to work. Save this code and take note of the path to it.

The Setup

Now that we’ve written our script we need to tell the server what to do with incoming email. This setup is going to vary depending on your server configuration, I’ll tell you how to do it on a linux server with sendmail and cpanel but for anything else you’re on your own (or you can post back explaining how and I’ll add it to the tutorial). What we need to do is setup a forwarder. If you have cPanel this is fairly straightforward. In your mail section find the forwarders option and click it. From there click add new forwarder. At this point you’ll have a few different options: you can forward to another address, discard and send an error message, do nothing, or pipe to a program. We want to pipe to a program. Just type in the address that you want piped, select the pipe option and then set the path to the path to the file you just saved. If you have access to your home directory, you can forego using cpanel and use a .forward file. All you have to do is create a file called .forward and add the following line:

email@address.com,”|/path/to/script.php”

Of course replace the email address with the address you want forwarded and /path/to/script.php with the actual path to the script. You can also omit the email address portion to have all mail forwarded to the script. I believe this process is the same using Exim or Qmail.

Well that’s it for the most part. Feel free to post back with any problems you have or additions you’d like to make. I’ll write about taking a raw email and converting it to a more friendly format, in this case an associative array, in the near future.

Stuff that Matters

“What we fight with is so small, and when we win, it makes us small. What we want is to be defeated, decisively, by successively greater things.”

“Focusing on big goals rather than on making money, and on creating more value than you capture are closely related principles. The first one is a test that applies to those starting something new; the second is the harder test that you must pass in order to create something enduring.”

“That’s why a time like this, when the bubble is bursting, is a great time to see how important it is to think about the big picture, and what matters not just to us, but to building a sustainable economy in a sustainable world.”

Those are three quotes I pulled out of an article I came across that I think captures the perceptions and values we must aspire to in order to create a better world at a time when everyone is looking out for themselves. Those of us who are upset with the times, whether it be because of issues that are impacting us in America, or because of the ongoing crises around the world, the pervasive poverty, hunger, and sickness afflicting people who were not so lucky as to be born in a more affluent part of the world, should know that these are at least in part due to people looking out for themselves. This includes companies that focus on profit and the paychecks of their executives, and politicians who put the well being of the people second to the lobbyists. Rather than lament them however, we should focus on the positive. Those of us who are fortunate enough to go on to own a company or be a leader in some industry should remember what I think is the main point of the article:

Short term success comes from short term goals, long term success and building something sustainable requires that we focus on what matters in the in the long run. This means worrying about those around us in addition to ourselves. Companies cannot sustain themselves for long if their focus is not on their customers, governments cannot last forever if their focus is not on the people, and the world will be worse off for having left so many behind.

A professor of mine recently told my class something along the lines of this: We do not deserve what we have. It is only luck that we were born in America while so many others were born in a world where they do not have the opportunities we do. He went on to say that we should be ashamed of ourselves if we do not make the most of what we have while so many others have nothing. I’m paraphrasing, but I hope I captured his point.

…Wow that’s probably the most idealist rant I’ve ever gone on, but I do think that we have a responsibility to others and that an individual can still be successful without pouring all of effort personal gain.

Anyways here is the link  to the article:

Read Me!

Its a good read and it comes of less like a rant that what I just wrote.

Configuring WP for Code Examples and Execution

Since launching this blog a few days ago I have yet to post and code examples or tutorials. In preperation for this, and having decided that plain text code examples just wouldn’t cut it, I went searching for a plugin to format and highlight my code. Not too long afterward I came across the SyntaxHighlighter plugin. After a simple installation I was able to do things like this:

<?php
//this is php code
echo 'hello world';
?>

How is the feat accomplished you say?The plugin allows you to post your code by surrounding it with the tags [/sourcecode], where lang is equal to one of these supported languages:
<ul>
<li>C++ — <code>cpp</code>, <code>c</code>, <code>c++</code></li>
<li>C# — <code>c#</code>, <code>c-sharp</code>, <code>csharp</code></li>
<li>CSS — <code>css</code></li>
<li>Delphi — <code>delphi</code>, <code>pascal</code></li>
<li>Java — <code>java</code></li>
<li>JavaScript — <code>js</code>, <code>jscript</code>, <code>javascript</code></li>
<li>PHP — <code>php</code></li>
<li>Python — <code>py</code>, <code>python</code></li>
<li>Ruby — <code>rb</code>, <code>ruby</code>, <code>rails</code>, <code>ror</code></li>
<li>SQL — <code>sql</code></li>
<li>VB — <code>vb</code>, <code>vb.net</code></li>
<li>XML/HTML — <code>xml</code>, <code>html</code>, <code>xhtml</code>, <code>xslt</code></li>
</ul>
The words following the — are valid arguments for language corresponding to that particular language, meaning that for python code you can set language equal to ‘py’ or ‘python’. Pretty cool right?

But Wait!

There was one catch in my case when it came to getting this plugin up and running. I had previously installed a plugin called <a href="http://bluesome.net/post/2005/08/18/50/" target="_blank">Exec-PHP</a> that allowed me to insert php code into posts that would be executed rather than displayed (this only works for me and it only works in posts so don’t get any ideas). So now all of my code examples would simply be executed, resulting in whatever the output of that example would be (worse potentially, the execution of that code everytime someone loads that page).

I came up with two possible solutions to this problem. The first being just to not use php tags in any of the code I post (NEVER!!!). The second being that I throw away about an hour of my life, dive into the exec-php plugin code, and set things right. Clearly I chose the second of these options.

So far I’ve only found 1 bug with this modification. I can’t display the code I used to impliment it. Any php code containing the strings [sourcecode language='p h p'] or will most likely break the plugin. Here is the link to download the plugin with the modification, feel free to comment back with error reports or improvements:

Download

Artificial Intelligence

Today I had my first discussion for a course on Artificial Intelligence I’m taking. In the week since the course started we really haven’t covered much material (as is to be expected) so the TA gave us a very broad topic to write about.

In short the prompt was: What is Artificial Intelligence

To suppliment we were given two definitions:

Weak AI: Machines can act intelligent.
Strong AI: Machines have minds.

My Thoughts:

In my understanding, Artificial Intelligence is the ability of machines to learn and use what it has learned to draw conclusions. As abstract as this is it still boils down to mapping inputs to outputs, which is what machines do every day. The inputs in the case being not only its perception of the current situation, but the sum of all of its experiential knowledge and the output being its action.

To accomplish this, weak AI is sufficient. Strong AI (based on the definition above) requires a machine to be something that I doubt any machine can be: non-deterministic. Having a mind and being conscious are attributes of sentience; something that humans and animals have. I do not believe that human behavior can be described as deterministic, or at the very least, the amount of inputs that are mapped to an output in a human is too difficult to quantify and infeasable to simulate in a machine.

In short, I do not think that strong AI is attainable. This, however, I do not think that this in anyway is a limitation on artificial intelligence. A turing test, though I do not think is sufficient for intelligence, is an example of this. The test consists of a person communicating with either another person or a machine. The two cannot see each other and interact only through text. If the person cannot determine whether the other entity is a person or a machine, then the machine is said to be intelligent. This can be (and currently is being) accomplished by machines that don’t have minds, conscious, or exemplify human behavior. All the machine needs to do is simulate human behavior. This can even be accomplished without intelligence. If a machine has a massive database of answers to questions and when asked a question simply looks up the answer and spits it out, is it intelligent?

If a machine can analyze a question and based on a database of its previous experience conclude an answer to that question does it have a mind?

Failure to launch…

If you haven’t heard about Windows 7 yet it is time to take note. 7 is the next iteration of windows and it appears that, unlike vista, its going to be a worthy replacement for XP. Those of you who have had to down(up?)grade from vista to xp are probably skeptical, but personally, from what I’ve read I think its going to be the next XP (in the sense that it will be a success, not the sense that it will be around for a decade before something better comes along… I hope).

You don’t have to take my word for it though. So long as you sign up before January 24th (exactly 2,647 days since the release of XP) you can try out the beta of Microsoft’s next OS:

Windows 7 Beta Information and Download

Be Warned! You’ll read on the website that it is not such a great idea to install 7 on your primary machine. I brushed off this warning without much thought and happily decided to install 7 alongside XP. And so begins the (notso) epic tale of how my Windows 7 beta test failed to get off the ground…

Downloading the installation DVD took me just over an hour, which for me is not bad for 2-3.5 GB depending on which flavor of 7 you decide to download. As soon as the dvd was done burning I quickly made a roughly 40GB primary NTFS partition on my hard drive and launched the installer. Unlike XP, which requires you to install by booting from cd (ie furiously tapping F8), 7 is smart enough to begin the install from XP while you sit back and enjoy the progress bar. Law and Order happened to be on TV at the time (There’s a 23/24 chance of that occuring as you are aware if you have basic cable) so I left the room.

A while later my progress-bar-nearly-full sense kicked in and I sprinted into my room to check the install. I caught the computer in the middle of a reboot. After the (new and shiny) load screen every step except was complete except for the very vauge “Completing Install…” step. I sat and watched the trailing dots come and go (. .. … .) until yet another reboot. Thinking its competely done now I watched the boot manager flash by, displaying “Windows 7″ and “Earlier version of Windows”. It defaulted to windows 7 and the low res but still new and shiny background appeared. Distracted, it took me a moment to notice the text “Installation was not successful”.

After this I made my critical error. I rebooted into XP and formatted my testing partition, then rebooted to try another install. If you haven’t realized I missed a step you will soon. After the install (and more Law and Order) I recieve the same message. This is, however, not the problem. Another reboot reveals the options “Earlier version of Windows” , “Windows 7″ , and… “Windows 7″. Thinking Oops I try to boot back into XP (forgetting that Vista and 7 don’t use the boot.ini) to fix the problem. This usually takes about 45 seconds. Three minutes later the screen was still black and I was thinking about the warning on the download page:

“Don’t install the Beta on your primary home or work computer. Microsoft is not responsible for downtime stemming from the Windows 7 Beta.”

A full day of debugging later I managed to get back into XP (thank you bcdedit).

That’s my story. For those of you who still want to do a side by side install here’s a link to a guide on how to do it:
You’ve been warned.
My old laptop is most likely going to be my new test subject. I’ll write again when I have have some first hand experience to share.

Introductions

Other than the lack of content and this un-customized, downloaded template, I’d say this bitch is up and running. Interesting stuff to come soon so check back (talking to myself at this point).