Programming and general geekiness.

Archive for December, 2011

BASIC is dead, long live Python?

Many years ago I sat down with a program called Liberty BASIC to learn programming. A few weeks later I progressed to Visual Basic and I stayed with VB for over a year before finally moving on to learn C#. As time went by I gradually rejected BASIC and I don’t think I’ve worked with it in at least two and a half years.

In January this year I had a look at Python for the first time and initially rejected it deeming it as a pointless extension of BASIC whilst assuming that C#, C++ and Java were far better languages. However one Sunday earlier this year I decided it would be sensible to learn Python, so I learned it in a morning on a dying Ubuntu computer. That was when I discovered it was quite a good programming language.

Before stepping into why Python will gradually take over from BASIC I would like to first consider how BASIC came into being. It has existed in one form or another for almost fifty years and stands for Beginner’s All-purpose Symbolic Instruction Code (is it sad that I didn’t have to lo0k that up). When the home computer era began BASIC became incredibly common as many people learned it so that they could make simple games for their new computers – it is these people that currently fuel the global programming industry today.

BASIC had its greatest success in 1991 when Microsoft developed Visual Basic which was designed to make it incredibly fast to design applications and this happened with great success, pushing VB skills to become a common business requirement. The aim was, however, unclear. Was BASIC and introduction to programming or serving as a professional language? Today I would suggest that it provides a platform for learning programming. The problem is that it is no longer best.

With time I realized how excellent a programming language Python is. Not only is it simple (and therefore incredibly easy to learn) but it is also speedy and extendable. According to this chart, we can see that Python is currently two times more popular than Visual Basic. There is also a lot more support on the web for Python and many people actually use it to develop complex software and websites.

Python will definitely become more popular over the next few years. In the UK there is certainly the possibility that it will become common knowledge thanks to projects like Raspberry Pi, but I wouldn’t be surprised if it gets onto the curriculum of other countries as well.

The super simple CSS template

I’m bored of people making ugly websites, so as a special new year gift I’ve put together a really tiny layout thingy that is incredibly easy to customize. It is designed to look good and the same in all browsers.

The template is very minimal and has a tiny shadow on the main content area. There is also a small AddThis button bar at the bottom which can be used optionally. If you would like a two column layout I recommend using two <div> elements with the left using float:left and the specific width whilst the right uses float:right and the specific width. You may need to add an empty element immediately afterwards that uses clear:both to ensure that the design doesn’t mess up in some browsers.

If you would like the full source, please go to my Dropbox.

Why HTML5 is the new Java

Java is a good programming language not only because it has everything but also because of the ‘code once, run anywhere’ philosophy that it adopts that allows developers to create cross platform applications easily. However, Java is dying not only because it is getting slower but also because the it is no longer the best when it comes to running anywhere: enter HTML5.

Everyone on the web (I mean developers, 90% of normal people don’t care about HTML5) is behind HTML5 and it seems that the standard is going to continue developing and browser manufacturers are going to continue improving JavaScript performance so that HTML5 apps are faster than normal apps. Chrome’s V8 engine running JavaScript has incredibly high performance.

HTML5 apps are also far easier to design than ordinary applications because creating the UI is child’s play* and incredibly easy to learn. There are also many applications available that make it possible to develop great apps.

HTML5 trumps Java on ‘run anywhere’ because users don’t generally have to install the apps to use them. They are just able to navigate to the appropriate website and run them, making it possible for developers to reach a wider, lazier audience.

Desktop applications haven’t been doing as well recently and there has been much greater focus on HTML5 and the web with good reason because JavaScript really is beginning to gain all of Java’s features. Here’s a short list of major features the languages share:

  • Graphics (via canvas)
  • Audio
  • Video
  • 3D Graphics
  • Complex animation
  • Advanced UIs
  • Database
  • File management
  • Engagement via network

*By this I mean that I code write HTML when I was 9, so therefore it is child’s play

Geek 2012

This is probably going to be a bit of a peculiar post, but I thought I would go over all the geeky things that are going to be happening in the new year. Aside from the end of the world next year is set up to be a pretty average year, so here is some of the stuff that is happening:

  • Alan Turing year: Next year Alan Turing would have been 100 so next year there will be special commemorations
  • China will launch the Kuafa spacecraft
  • IBM will finish Pleiades: Pleiades is a planned supercomputer that will run at 10 petaflops which is, incidentally, faster than your computer
  • Quad-core smart phones: This isn’t really a surprise considering in 2010 we didn’t really have much dual core, but quad core does seem ludicrously fast
  • Microsoft will release Windows 8: Windows 8 should theoretically come out next year, with rumours currently suggesting late summer/early fall
  • Eros on January 31st: NASA have announced that Eros will pass Earth within 16 million miles (not to close, thankfully)
  • Curiosity will land on Mars in mid-August: Having set off a few weeks back it is expected NASA’s new rover will land next August
  • The world will end on December 21st: Obviously.

Basically next year looks like it will be pretty average. Sad that 2011 will be the last full year though…

Which font will take over from Arial/Helvetica?

Arial and Helvetica have arguably been the most used fonts of the last twenty years. They are standard sans-serif fonts that are basically used because they just work and will quite happily work on almost any website. Major websites including Twitter, Google, Facebook, BBC News and YouTube use them. Despite this the fonts are dying and are being replaced by more fashionable easier to read sans-serif fonts.

The aren’t really any fonts that are going to be eat Arial/Helvetica overall however Tahoma has always been a pretty good alternative and whilst it isn’t as commonly used it tends to look better in applications and for small portions of text. Microsoft are also pushing the Segoe font family, or more specifically the Segoe UI font because it used in pretty much all new Microsoft applications from 2007 onwards and it is going to become inescapable  in Windows 8 where it will be literally everywhere.

Open Sans

There is one font, however, that seems to be doing particularly well on the web: Open Sans. In the last few months it has begun to crop up everywhere. It isn’t actually included in any major systems however it can be used very easily on websites using Google Web Fonts which provides tiny snippets of code that you can put in your CSS to get it.

I don’t know why, but everyone seems to use it on new websites. I’m using it in my current project and I would certainly recommend it because it looks better than some of the older fonts.

Building a simple blogging system in PHP – Part 2

In yesterday’s section of the tutorial we considered the basic layout, CSS and database structure. Today we are going to build the initial code that will fetch posts and other information. The previous tutorial ended looking like this:

Clearly there wasn’t any information so we need to begin adding things. The first thing we should do before doing anything else is to add some sample data to the database so that we can begin creating code that works. I added the following:

  • A blog post with the title ‘My first blog post!’ and the link My_first_blog_post along with some basic content
  • I added the category ‘life’ to the category table by adding a row with Id 1, Category life and Post 1 (links with the post table)
  • I added some tags the same way I added categories

The next simple bit of code to be run is to fetch a category list to display on the sidebar. I wrote the following code in code.php:

$pdo = new PDO("mysql:host=localhost;dbname=myblog", "root", "");
$pageTitle = "My Blog";
$pageContent = "";
$categoryList = "<ul class=\"category-list\">";
foreach ($pdo->query("SELECT DISTINCT Category FROM categories ORDER BY Category ASC")->fetchAll() as $cat)
{
 $categoryList .= "<li><a href=\"http://localhost/myblog/category/" . $cat[0] . "\">" . $cat[0] . "</a></li>";
}
$categoryList .= "</ul>";

Here’s a quick walkthrough of the code:

  • First we create a new PHP Data Object which is connected to the database we created. If you haven’t used PDO before it maybe worth looking it up in the PHP Manual
  • We then set default values for the variables and start an HTML list element in the $categoryList variable
  • We then loop through all the unique values in alphabetical order in the categories table and add them as a list item and link
  • We finish the list off

The end result of my sidebar is the following (I added some additional styling and layout stuff):

In the database I had all the category names as lowercase however CSS can style these as an uppercase letter at the beginning of each word. Now we need to look back at how the URLs work.

We have already established that the server will direct everything that doesn’t exist already into index.php to give us clean URLs. We therefore need to write some code that will interpret the requested URL. We also need to consider that we are including an RSS feed feature which will mean that people can subscribe to the site. I have therefore including the code that will generate the feed:

$url = explode("/", substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], "myblog/")+7));
if ($url[0] == "feed" || $url[0] == "rss")
{
 header("Content-type:application/rss+xml; charset=ISO-8859-1");
 echo "<?xml version=\"1.0\"?>\n";
 echo "<rss version=\"2.0\">\n";
 echo "<channel>\n";
 echo "<title>My Blog</title>\n";
 echo "<link>http://localhost/myblog/</link>\n";
 echo "<description>The source of information about my life!</description>\n";
 echo "<language>en-us</language>\n";
 foreach ($pdo->query("SELECT * FROM posts ORDER BY Posted DESC LIMIT 0, 20")->fetchAll() as $row)
 {
 echo "<item>\n";
 echo "<title>" . $row['Title'] . "</title>\n";
 echo "<link>http://localhost/myblog/post/" . $row['Link'] . "</link>\n";
 echo "<description><![CDATA[" . $row['Content'] . "]]></description>\n";
 echo "<pubDate>" . date('D, d M Y H:i:s O', strtotime($row['Posted'])) . "</pubDate>\n";
 echo "</item>\n";
 }
 echo "</channel>\n</rss>";
 exit;
}
else
{
}

I won’t explain what all the code that generates individual items of XML does, but here is roughly what happens:

  • We get everything in the URL after the myblog/ part and split it where there is a forward slash character
  • We check if the first part of the URL is feed or rss and if it is send an XML header
  • Echo the initial required data about the feed
  • Loop through the twenty most recent items and print the required details – note that the date has to be first passed into a PHP date and then into a valid RSS date
  • If the feed wasn’t requested, continue running code.

The next stage of code is rather massive but gives us the core stuff for the blog and goes inside that last else statement. I won’t chunk it out into sections so here is the block:

if (isset($_GET['p'])) $page = ((int)$_GET['p'])-1;
 else $page = 0;
 if ($page < 0) $page = 0;
 if ($url[0] == "post")
 {
 if (isset($url[1]))
 {
 $post = $pdo->prepare("SELECT * FROM posts WHERE Link = :link");
 $post->execute(array(":link" => $url[1]));
 }
 else header("location:http://localhost/myblog/");
 }
 else if ($url[0] == "category")
 {
 if (isset($url[1]))
 {
 $post = $pdo->prepare("SELECT * FROM posts WHERE Id = ANY (SELECT Post FROM categories WHERE Category = :cat) ORDER BY Posted DESC LIMIT " . $page*10 . ", 10");
 $post->execute(array(":cat" => $url[1]));
 }
 else header("location:http://localhost/myblog/");
 }
 else if ($url[0] == "tag")
 {
 if (isset($url[1]))
 {
 $post = $pdo->prepare("SELECT * FROM posts WHERE Id = ANY (SELECT Post FROM tags WHERE Tag = :tag) ORDER BY Posted DESC LIMIT " . $page*10 . ", 10");
 $post->execute(array(":tag" => $url[1]));
 }
 else header("location:http://localhost/myblog/");
 }
 else $post = $pdo->query("SELECT * FROM posts ORDER BY Posted DESC LIMIT " . $page*10 . ", 10");
 if ($post->rowCount() > 0)
 {
 foreach ($post->fetchAll() as $row)
 {
 if ($url[0] == "post") $pageTitle = $row['Title'];
 $pageContent .= "<article>";
 $pageContent .= "<header><h2><a href=\"http://localhost/myblog/post/" . $row['Link'] . "\">" . $row['Title'] . "</a></h2><p>" . date('j F Y', strtotime($row['Posted'])) . "</p></header>\n";
 $pageContent .= $row['Content'];
 $cats = $pdo->prepare("SELECT Category FROM categories WHERE Post = :post");
 $cats->execute(array(":post" => $row['Id']));
 if ($cats->rowCount() > 0)
 {
 $pageContent .= "\n<p>Posted in: ";
 foreach ($cats->fetchAll() as $cat)
 {
 $pageContent .= "<a href=\"http://localhost/myblog/category/" . $cat[0] . "\" class=\"category-link\">" . $cat[0] . "</a> ";
 }
 $pageContent .= "</p>";
 }
 $tags = $pdo->prepare("SELECT Tag FROM tags WHERE Post = :post");
 $tags->execute(array(":post" => $row['Id']));
 if ($tags->rowCount() > 0)
 {
 $pageContent .= "\n<p>Tagged with: ";
 foreach ($tags->fetchAll() as $tag)
 {
 $pageContent .= "<a href=\"http://localhost/myblog/tag/" . $tag[0] . "\" class=\"category-link\">" . $tag[0] . "</a> ";
 }
 $pageContent .= "</p>";
 }
 $pageContent .= "</article>";
 }
 }
  • The first thing that happens is checking if the p variable is set – this tells the user what page they are on
  • If we are looking at an individual post, prepare a query for that post
  • If we are looking at a category, prepare a query for that category
  • If we are looking at a tag, prepare a query for that tag
  • Loop through all the posts and produce the appropriate HTML for them

In reality it is actually relatively simple, it just takes quite a bit of code to work correctly. Here is what the finished result looks like, although you may want to add extra styling:

In the next tutorial we’ll add commenting and a basic admin panel.

Why hand coding HTML5 is still the best method

I downloaded Adobe’s new ‘cool tool’ called Muse today. It is simply an application that is effectively an evolution of Illustrator and Dreamweaver that is designed for creating fluid HTML5 sites that seem to be laid out using a rather peculiar method. Earlier this year Adobe announced Edge, which is a tool that effectively brings all the horrible animation features of Flash to HTML5 by a massive JavaScript library and therefore it is reasonable to assume Muse is an evolution of Dreamweaver.

I’ve used similar tools in the past that are aimed at making it possible to make HTML5 sites based on a drag and drop system but the problem is that it doesn’t work. If you want to build a great HTML5 the future is definitely hand coding. HTML5 doesn’t really bring much that is useful to the website designer (although it is worth pointing out that CSS3 does) because a lot of the new features are related to JavaScript allowing developers to do cool new things on the client.

HTML5 isn’t about creating new websites, it is about building new web apps and apps are created using code. I am currently working on a few HTML5 sites/apps and there is no way that I could build them using a drag and drop tool such as Muse or Edge because they require enormous amounts of code both client and server side to be awesome. I fear that these new drag and drop tools may make people believe that it is easy to create the new HTML5 app.

What software will 2012 bring us?

Loads of people have been talking on the web about new technology, gadgets and Apple products due for release next year however nobody has really considered what software will happen next year and so far it looks like one thing will be ruling above all others: Windows 8.

Aside from Windows 8 Microsoft will no doubt release the developer tools for it, Visual Studio 11, which will allow developers to create cool (?) Metro applications that do stuff that Windows couldn’t do before although it is most important that it will be on tablets. As far as we are aware nothing else is planned by Microsoft (I don’t expect to see a new version of Office before 2013) however it is reasonable to assume that they well be developing many applications that use Kinect as a way of controlling the UI.

Google will probably begin developing new versions of Android and I should imagine that they will develop some new product that takes advantage of Chrome 20 or something ridiculous like that. I don’t anticipate Google developing any more desktop software because they are gradually moving towards web apps so it is possible that applications like Google Earth and Google Sketchup become full Chrome Web Apps.

Apple don’t seem to have anything planned and there certainly won’t be another version of OS X next year however they may be an update either to iOS 5.5 or version 6 depending on what Apple have planned for the ultimate merger of the two OSes. I should imagine iTunes will move to version 12 and Safari to version 6, however.

Adobe will probably launch CS6 which may drop Flash and focus entirely on JavaScript, CSS3 and HTML5 which would be an incredibly smart move. Otherwise I don’t know.

Sadly next year isn’t going to be a big year for many software companies, and it will mostly be Microsoft taking the stage.

I don’t give a damn about the difference between nerds and geeks

The above image was posted by someone I follow on Google+ the other day and it got me wondering. In my social group the general consensus is that dorks are at the bottom and idolize the geeks and nerds for the incredible intellect and knowledge. However, nerds are considered to be the smart people that can program properly and geeks are just the coders that think HTML is a programming language.

I think that we probably need some new terms because I am happy to be considered as a geek by some people and a nerd by others. Ironically I don’t see either as an offence because I can’t really acknowledge the fact that I would be neither; the stuff on this blog kind of shows what kind of person I am.

There is definitely a difference between geeks/nerds and dorks however I genuinely don’t care about geeks and nerds. Regardless they are the smart people at the top that end up being at the top of the big companies.

Building a simple blogging system in PHP – Part 1

Today there are many blogging systems available to create a blog such as WordPress, Blogger and Tumblr however it can be more rewarding to build your own blogging system that you can use directly in your website. This set of tutorials will go through the procedure of building a blogging system with tags, categories and RSS using PHP and MySQL because they are both easily accessible environments. If you do not have either of these available on your system I recommend that you download WampServer and go through some PHP tutorials because that is what I will be using along with NetBeans 7.1 RC2 for coding.

Initial considerations

A blogging system has a few basic requirements. Here is what I think they are:

  • Simplistic two column layout – the left is for posts and the right is for a sidebar including category links, recent posts, RSS and search
  • Ability to fetch many posts or individual posts
  • Ability to tag a post with as many tags as required and as many categories as required
  • RSS feed automatically generated
  • Commenting on posts
  • Admin panel for editing
  • Well structured database for storing data

Clearly a blogging system is quite a large project and it is important to carefully consider how you will build it. In part 1 of this tutorial I shall develop the appropriate tables in a database, setup the server and basic layout of the pages.

Making the database

For simplicity I created a database called myblog in PHPMyAdmin on WampServer. I created the following tables:

  • posts
    • Id INTEGER PRIMARY_KEY AUTO_INCREMENT
    • Title TEXT
    • Link TEXT
    • Content TEXT
    • Posted DATETIME
  • categories
    • Id INTEGER PRIMARY_KEY AUTO_INCREMENT
    • Category TEXT
    • Post INTEGER
  • tags
    • Id INTEGER PRIMARY_KEY AUTO_INCREMENT
    • Tag TEXT
    • Post INTEGER

Incredibly this is all that we need in our database because we will be taking advantage of other web services to manage things like commenting. The next stage involves configuring Apache.

Configuring Apache

Apache is the web server of the web because its free and it does the job. Before we move on it is worth considering how we wish URLs on the blog to appear. One option is to have something like blog/post.php?id=3 to direct to the third blog post in the database however this is a cumbersome old school approach that is not used on many websites. Instead we will have something like blog/post/My_blog_post. Before we do this we first need to do a few things. The first is to ensure that the rewrite_module is enabled in Apache. In WampServer this can be done by clicking the WampServer icon in the taskbar, clicking Apache, clicking Apache Modules and then ensuring there is a tick against the rewrite_module. You then need to navigate to where you intend to put your blog (I’ve created a folder called myblog in C:\wamp\www) and create a new file called .htaccess and put in the following:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.+) - [PT,L]
RewriteRule ^(.*) index.php

These five lines of code basically (I won’t go into detail) cause everything that doesn’t exist on the server (such as image files) in the directory to go through index.php which is where our basic code will be stored.

Creating index.php

For simplicity purposes this is where we are directing the server to for requesting posts. I’ve created the following in the file:

<?php include("code.php"); ?>
<!DOCTYPE html>
<html>
 <head>
 <link rel="stylesheet" type="text/css" href="http://localhost/myblog/css.css" />
 <title><?php echo $pageTitle ?></title>
 </head>
 <body>
 <div id="page">
 <div id="header">
 <h1>My blog</h1>
 <h3>The source of information about my life</h3>
 <div id="header-image">&nbsp;</div> 
 </div>
 <div id="page-content">
 <div id="left">
 <?php echo $pageContent ?>
 </div>
 <div id="right">
 <a href="http://localhost/myblog/rss" id="feed-link">Feed</a>
 <?php echo $categoryList ?>
 </div>
 </div>
 <div id="footer">My blog was created by Programming Thomas</div>
 </div>
 </body>
</html>

There is very little to observed from this other than it defines our basic layout. It is worth noting that the links have to be full lengths because they will not have the same relativity in localhost/myblog/post/My_post_name and localhost/myblog. I also created code.php and gave the variables some default variables so that I could view the page without errors. Here is what it looked like after styling:

I decided to use Google Web Fonts to get the Open Sans font which I thought looked quite nice. The image is from Flickr however I’ve cropped it. Here is the full CSS (I’ve tried to make it as small as possible):

@import url(http://fonts.googleapis.com/css?family=Open+Sans);
body
{
 font-family:"Open Sans", sans-serif;
}
#page
{
 width:750px;
 padding:5px;
 margin:10px auto;
}
#header h1, #header h3
{
 margin:0;
 font-weight:normal;
}
#header-image
{
 background:url(http://farm8.staticflickr.com/7159/6576537579_fcc8f6efd8_b_d.jpg) center center;
 height:175px;
 margin:5px 0;
}
#left
{
 width:490px;
 padding:5px;
 float:left;
}
#right
{
 width:240px;
 padding:5px;
 float:right;
}
#footer
{
 clear:both;
 text-align:center;
}
#feed-link
{
 background:url("http://localhost/myblog/feed-icon-28x28.png") no-repeat;
 padding:0 0 0 33px;
 color:black;
 text-decoration:none;
 width:100%;
 font-size:21px;
}

I think that is all that we will do today, check back tomorrow for Part 2 of the tutorial.

Follow

Get every new post delivered to your Inbox.