Fibonacci in Erlang

August 11th, 2011

We’ve seen the fibonacci example in multiple languages, but none of them purely functional. Erlang is a functional language that is growing in popularity due to the ease in which you can create concurrent programs. It has a number of paradigms that may be foreign to developers that are used to working in scripting or object oriented languages, but rather than a hindrance, things like immutable variables and the lack of loop constructs encourage an elegance in implementation that becomes second nature once you change your mindset.

In this example, we’re using three of these features together to create a very simple version of our fibonacci function.

  • Multiple function clauses – In erlang, you can define a function multiple times – and depending on the arguments passed to the function the correct version of that function is executed.
  • Pattern matching – To determine which function clause is executed, variables declared in the head can be matched against a pattern. In this example, we’re using the same variable name in the first clause for the third and fourth variables. Because variables are immutable, they can only ever equal one value when they are set. That means that when we are looking for “Count” twice in the function head – we are really looking for those variables to contain the same value.
  • Tail recursion – Instead of for or while loops, erlang uses a mechanism called tail recursion. By calling itself multiple times with incremented values, our fibonacci function is in effect executing a loop; and because we have multiple function clauses, we can end the loop when a certain condition is met.

 

Simple Model CRUD with PHP 5.3

September 2nd, 2009

I’ve been wanting to mess around with some of the new features in PHP 5.3, so I took the opportunity to write a base model class that can be used for simple db based models. This isn’t really production type code, more of an example of “look what php can do now”, although with some error handling and tweaking, it might be a good start to a lightweight active record type base class.

One of the biggest new changes to 5.3 is late static binding. It has never been possible in PHP to get the name of the calling class when you called a static method inherited from a parent. Now with late static binding, this is possible. This is what works the “magic” in this base class.

The Assumptions

Models represent an entity stored in the database (think active record):

  • In one table per class named the same as the model class, but all lower case
  • With one column for each property
  • With a primary key column named ‘id’

In addition, a global variable $db should contain a PHP PDO object.

The Base Class

One of the things I’d like to be able to do is create an object from an array of parameters, whether they come from a database or not. I might want to create from a set of parameters and be able to act on it immediately, without having to reload it. I use reflection here to ensure that all the class properties are set, throwing an exception if any are missing.

Note also in the get and getAll methods, the calls to new static(). What this does is create an object of the class you are calling, rather than the class that the method exists in. This wasn’t possible until PHP 5.3, and is really the key to being able to use static inheritance.

In addition, there is a lambda function in the save method, this is new to 5.3 also. And there are a few examples of a new php function “get_called_class()” which will return the name of the class that was called.

 

Now, you’ll probably notice that this is an abstract class, meaning that we can’t create any Base objects, but must extend the class. Here is an example of a child class that holds name / value pairs:

Once I’ve created the matching db table, I’m ready to get some CRUD done.

Creating an object

To create an object, I simply pass the parameters as an associative array of properties and their values.

Getting objects

Getting is simple. Either get by ID or get an array of all the objects. It would be fairly trivial to add a find method.

Updating

You can update multiple parameters at once by passing an associative array as you did in the create method, or update a single parameter by using the updateProperty method and passing the name and value.

Deleting

 

Image Index

September 2nd, 2009

Notice the icons are all the icons themselves, not just a standard image icon.

Download Image Index

Have you ever opened up a apache directory listing page for a directory full of images and been frustrated that all you see is the same little icon next to each one? I bring you Image Index, a firefox plugin that replaces that icon with a thumbnail of the image itself.

Using Selenium RC With Multiple Users

March 13th, 2008

So you may be testing with selenium already, you may even be using selenium RC to automate your testing and integrate it with your other unit tests, and you may already be doing so in a shared development environment, but if you aren’t using selenium RC with multiple users, you may not know that you can start the RC server on any port you wish, allowing multiple clients to connect at the same time.

To start the selenium RC server, you would typically run this command:

Which will start it on the default port of 4444. If you want to start it on another port, simply add -port <portnumber> to the command like this:

This command would start the server on port 1234.

Great, now I can start the server on multiple ports, so what?

So here is the good news for those of us in shared development environments. Say you have a windows virtual machine running selenium with your test browser installed. Things get complicated when multiple clients are testing at the same time. Tests can fail unexpectedly, developers begin fighting for time on the test server, and all hell breaks loose. By running multiple servers on different ports, we can avoid the third world war. Everyone can connect at the same time to their personal server, and we have peace and harmony in our testing environment.

Wow, setting up a different port everytime must suck.

Not really. There are many ways that you can automate the process so that it’s completely transparent to your development team. A lot will depend on your environment, but in our case, we created a .bat file that starts the servers in our virtual machine and placed it in the start-up folder.

With this in place, we now have 4 selenium RC servers running at all times. If one or more crashes for any reason, running the batch file again will start any that are missing. The selenium RC server will not start if its port is in use, so only the ones missing will run, and you’ll have them all up and running again.

Ok, what about the client side? I don’t want to have to edit another file in my development environment.

On the client side, we are using phpunit with Testing_Selenium. Of course all of our selenium test classes extend a parent class, so it was easy enough for us to create some dynamic logic there to decide which port to use.

PHP Mail Class

February 3rd, 2008

This is a very simple mailer class that is also easy to use.

Usage

Using the mail class is easy. Simply create a new ZFmail object, passing the parameters $to,$from,$subject, and $body, then call the method send on the object that you created. It’s as easy as pie. The following example is for a simple form mail script.

Example

Vim Color Improved – Syntax Highlighting for WordPress

January 8th, 2008

Vim Color Improved is a syntax highlighting plugin that allows you to include code from local or remote files in your WordPress posts. I started using vim to syntax highlight my code samples based on a couple of searches that turned up this page here. However, since I started my new project that involves posting even more code, I thought it’s about time to come up with another solution. The only other vim highlighting plugin that I found was old, required a Perl library from cpan, and didn’t seem to work in the version of WordPress I’m running here. So I set out to create my own.

Download Vim Color Improved

It uses the same tag and parameter parsing as the popular codeviewer 1.4, and should be compatible with it’s options. In addition, any of the optional parameters from codeviewer 1.4 can be set as defaults, which can then be overriden by parameters in the tag. Vim Color Improved outputs code in <pre> formatted blocks, rather than ordered lists, which can be difficult to copy and paste, and can syntax highlight any language which vim supports.

Vim Color Improved contains a sophisticated caching system that stores the generated html to the filesystem. This greatly reduces the time required to display the code. In addition, it checks the modified time on both local and remote files to ensure that cached information is up-to-date. If it is unable to access the source code, and there is a cached version available, it will display the cached version with a notice.

Using Vim Color Improved

(These instructions basically parallel those for CodeViewer 1.4)

Vim Color Improved searches your post for a custom tag named [viewcode ] [/viewcode], that tells the server to look at an external file and parse it into syntax higihlighted html. It can be placed anywhere a block-level tag is valid but the tag must be properly closed.

Note that there should not be a white space character after viewcode and before ].

Parameters
[viewcode ] src=”URI or path to local file” link=yes|no lines= scroll=yes|no scrollheight=valid css height showsyntax=yes|no cache=yes|no[/viewcode]

Default values for all of these parameters, other than src can be set in the options page.

The src attribute is required.
src – string – The URI or path to a local file of the code to display. Note that relative paths are in relation to the default_path set in the options page. This default value is set to the directory your blog is installed in.

The link attribute is optional.
link – string – Should the link to the code be displayed (yes), or not be displayed (no). If the link attribute is left out of the tag completely, the value defaults to no.

The lines attribute is optional.
lines – string – Which line numbers shall be visible in the output. Use , and – to separate line numbers. Example: lines=1,3-5,10-12,16-18,22.

The scroll attribute is optional.
scroll – string – Should the scrollbar be displayed (yes), or not be displayed (no).

The scrollheight attribute is optional.
height- string – Height of the scrollbar. Any valid css height declaration can be used. Example: 100px or 50em

The showsyntax attribute is optional.
showsyntax – string – Should the syntax used of [viewcode ] be displayed (yes), or not be displayed (no).

All attribute values can optionally be surrounded with double quotes (“) or single quotes(‘).

Installation

  1. Download Vim Color Improved
  2. Unzip the archive and copy the entire vim-color-improved folder to the wp-content/plugins directory
  3. Vim Color Improved needs a directory to store the cached files and to use as a temp directory. Please make sure that your web server can write to and read from the vim-color-improved/tmp directory.
  4. Activate the plugin from the Plugins page in your WordPress administration console.
  5. Vim Color Improved also provides an options page for you to set the default options. While the plugin will work without any intervention, you may wish to review these at (Options->Vim Color Improved. You may also see a list of cached files and clear the cache there.

Frequently Asked Questions

Why are there no FAQs?

This is the first release.

Example

Here is an example of Vim Color Improved in action. We can see here the parameters that were passed in the tag by looking at the showsyntax block above the html code block.

[viewcode]src=http://www.zacharyfox.com/blog/wp-content/plugins/vim-color-improved/css/vci-style.css cache=yes showsyntax=yes[/viewcode]

pre.vci_code{
	background:#333;
	color:#fff;
	padding:5px;
	font-size:12px;
	margin-bottom:0;
	margin-top:0;
	overflow-x:auto;
}

pre.vci_code .c14 { color: #ff40ff; }
pre.vci_code .c26 { color: #8080ff; }
pre.vci_code .c27 { color: #ff6060; }
pre.vci_code .c28 { color: #ff40ff; }
pre.vci_code .c30 { color: #ffff00; }
pre.vci_code .c31 { color: #ff40ff; }
pre.vci_code .c32 { color: #00ff00; }

pre.vci_code .Constant { color: #ff6060; }
pre.vci_code .Identifier { color: #00ffff; }
pre.vci_code .Statement { color: #ffff00; }
pre.vci_code .PreProc { color: #ff40ff; }
pre.vci_code .Type { color: #00ff00; }
pre.vci_code .Comment { color: #8080ff; }
pre.vci_code .Special { color: #ff40ff; }

p.vci_info, p.vci_warning{
	background:#eee;
	color:#666;
	font-size:80%;
	padding:3px;
	margin-top:0;
	margin-bottom:0;
	text-align:right;
}

p.vci_warning{
	background:#fee;
	font-weight:bold;
	text-align:left;
}

HTML code generated by vim-color-improved v.0.4.0.Download this code: vci-style.css

Requirements

This plugin may not work on all php installations. Specifically, there are some access needs that may be locked down on your web server.

  1. Your web server must be able to exec(vim) through php
  2. If you want to use remote files, your web server must be able to open the files through http using file()

To Do List

  1. Add the ability to use vim’s options, such as using css, using xhtml, etc…
  2. Add the ability to use WYSIWYG editor for posts, including file selection box for local files.

Version History

v.0.4.0 Bug fixes and new features

  • Fixed problem with files not being found not displaying an error
  • Fixed vim command, was missing last quit
  • Added vcihtmluse_css parameter and option
  • Added vim classes to style.css
  • Refactoring of vci_color(), created new methods to decrease the main method size
  • Added vci_link for a default value
  • Added more vim options to the vim command to help performance
  • Added functions.php to include additional functions not directly related to vci
  • Moved temporary directory to the system temp dir to ease installation – no longer need to chmod a directory
  • Attempt auto-detect of vim path using exec(‘which vim’)
  • Added admin css, moved css files to css directory
  • Added management page for cache management
  • Added ability to clear single files from the cache
  • Changed to scroll horizontally by default if code is too wide

v.0.3.2 First Public Version

License

Copyright 2008 Zachary Fox (email : ecommerceninja at gmail dot com)

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

Fibonacci in Java

January 6th, 2008

So we’ve seen lots of examples of our Fibonacci program in scripting languages, but other than C, I haven’t touched on many compiled languages. So here is a version in Java, probably one of the most common and popular languages in use today. Considered by advocates to be the among the best enterprise application development languages, we’ll see here how to write our simple program.

Fibonacci in Ruby

January 5th, 2008

So finally we get to Ruby. Is it a ghetto? I don’t know about that, but I do know that writing our simple Fibonacci program in Ruby was a piece of cake. Before we get to the good stuff, though, I’d like to recap where we are, and what we’ve done so far. Here’s a list of the Fibonacci project programs so far:

So this is our sixth version of the simple sequence generator, this time in Ruby

The next installment will be another popular language. Stay tuned to see Fibonacci in Java.

Fibonacci in Python

January 5th, 2008

In our latest installment of the Fibonacci project, we’ll write our simple program in Python. For those of you who are unfamiliar with what we are doing here, please read the first post here. Python is a newer, but increasingly popular scripting language. I suppose the most interesting difference here is that Python is dependent on indentation to define blocks, rather than braces or other language constructs.

Fibonacci in Perl

January 3rd, 2008

So this is our fourth post of the Fibonacci project, and in this installment, we are going to take on Perl. For those of you who don’t know about the Fibonacci project, you should read the first post, Fibonacci in C. Also, you may want to check out the other posts in the series. The comments in the code will make more sense if you have seen the other examples.

Any Perl gurus want to critique my work here? Like most of the examples, this is a simplified version, but one that works.