« May 2005 | Main | July 2005 »

June 30, 2005

pu daily and p hourly

Tcl is a command based language - everything you do uses a command that starts with a command word such as puts to output information or set to assign a value to a variable. The while command (yes, it really is a command) lets you define a block of code that's to be run repeatedly while a condition is true, and so on.

As well as storing Tcl programs in a file, you can type Tcl commands in at an interactive prompt ... and if you do so, you're allowed to shorten the name of your commands provided they remain non-ambiguous. This is why Tcl will let you pu but not p ....


earth-wind-and-fire:~ grahamellis$ tclsh
% pu daily
daily
% p hourly
ambiguous command name "p": package pid proc puts pwd
% exit
earth-wind-and-fire:~ grahamellis$

Please excuse the - err - lavatorial sense of humour this example shows. It came up (I confess I originated it) on a Tcl Course that I've just completed in Scotland.

Posted by gje at 03:53 PM


Related topics: via article database
More about Graham Ellis of Well House Consultants

June 29, 2005

Greetings from Edinburgh

I slept in this morning ... woke at 06:30 and - yikes - had two hours of work to do before training, so "The Mouth" is shorter and later in the day. And, yes, I'm fighting the Edinburgh traffic each morning from shore where I'm staying to mountain top where I'm working.

Posted by gje at 02:31 PM


Related topics: via article database

June 28, 2005

The ireallyreallywanna operator

In Tcl, any character (yes - any character) can appear in a variable name, though making use of variable names that contain - for example - spaces adds a needless complexity to your coding. Groups of special characters can be protected from the Tcl interpreter by wrapping them in curly braces, and individual characters protected by preceding them with a backslash character. That's a more general rule - it applies not only to variable names, but also to any single parameter string.

You could say that { } and \ are the "ireallywanna" operators ... in the same way that you can say that [ ] is the "choose me first" operator and that $ is the "contents of" operator.

Posted by gje at 07:18 AM


Related topics: via article database

June 27, 2005

Binary Large Objects or bars

When designing a MySQL table, it's vital to choose the correct data type to hold your information. One such possible is a Blob - a binary large object - which can hold any byte stream that you like (choose the subtype based on maximum size). Ideal for data like images which you won't want to search for any particular content (use seperate columns in your database for descriptions if you need to ) and may contain any bit pattern at all.

In Lancaster yesterday, I learnt that the "Blob Shop" is also a bar ....

Posted by gje at 06:36 AM


Related topics: via article database

June 26, 2005

Spring turns to Summer

Taken yesterday in the Herefordshire countryside - a little further from home than most of the pictures that I put up on "The Horse's Mouth". This will be forming part of my "clickable map" demo - where I'm putting up pictures from all around the UK.

See ... Work in progress (Click on map ;-) ... then on highlighted place names in table or at top - the "flow" through the pages needs some work and Other new pictures

Posted by gje at 07:46 AM


Related topics: via article database

Chicken soup without the religion

Lisa's just back from a trip to the USA and was commenting on how strong the religious right is becoming there. I celebrate the fact that in our lives / in the UK we can take different views and positions on politics and religion from our neighbours, yet still get along well with them and hold them in the utmost respect.

Even when I stray away from technical subjects here, you'll rarely find me getting on to religion. I have great admiration for those throughful people who choose to follow such a religious path on traditional grounds. I can understand why others follow religion without giving it any real thought. I confess I have little time for anyone who organises religion primarily as a means of gaining control or authority.

So why "Chicken Soup" without religion. If you've not read the "Chicken Soup" series of books you may be puzzled; they're paperbacks that are very popular in some quarters of the USA - short, positive stories with a moral and a thoughtful or happy ending. They're written (at least the ones I have looked at) with a strong Christian coating which (personally) rather passes me by; I would enjoy them that much more were they suitable for everyone to read, irrespecttive of their religion.

So ... why "Ch....".? Because, yes, I do try to give good suggestions here, nice litte stories that are thought provoking and positive. How best you use a language, what a lovely country, give this some thought ...

Posted by gje at 07:26 AM


Related topics: via article database

June 25, 2005

Use standard Perl modules

If you're writing a piece of code and you think "surely someone has done this before", then you're probably right. Chances are that someone has written the code, debugged it, tested it, documented it, and may even maintain it and have a lot of facilities that you would love to have but cannot justify in terms of your development time. And with Open Source, chances are that you'll be able to use the code that's already been written by someone else!.

As well as built-in functionallity, Perl is supplied with a wide range of very commonly required modules - things like Time::Local for converting times from seconds, minutes, hours, day, month, year into a number of seconds from 1.1.70 (so that you can calculate with times). There's a further wide variety available on the CPAN at www.cpan.org, and probably even more in your own organisation. And don't forget standard appliactions either - such as YaBB which we use for our forum and Movabletype which I use for these daily writings.

Posted by gje at 07:04 AM


Related topics: via article database

Useful link: Perl training

June 24, 2005

Where do Perl modules load from

When you're writing a Perl program, you're strongly encouraged to use existing code that's already been written to perform common functions. Not only does this save you time re-coding, but it also means you get code that's already tested and proven, and there's only one piece of code to be maintained for each piece of functionallity thereafter rather than two.

Shared (re-used) code may come as part of the Perl distribution - modules like Carp and File::Compare. It may be more specialist code that you download from the CPAN - for example DBI and DBD. Or it may be code that's just shared within your organisation or even just your department or between your personal applications. And in all cases, you "pull" the code into your program with a use statement:

use Carp;
use File::Compare;
use toothbrush;

Where does your Perl program load these modules from? It uses the list @INC which is prepopulated with each of the directories where Perl should look in turn. If you want to add some directories from the command line too, you can use the -I option to perl (see man perlrun for details. But what if you want to add an extra directory or two in your program? You're allowed to change @INC right enough, but even if you do so ahead of your use statement you'll be too late because the use is interpretted at compile time.

Solution? Modify your @INC list in a BEGIN block, since BEGIN blocks are interpretted at compile time too. Here's an example:

BEGIN {
push @INC,"extrabitz";
}

use toothbrush;

The directory "extrabitz" (a subdirectory of the current directory when the program is run) is added onto the end of the list of places for Perl to look ... and in this case, that's probably where it will find "toothbrush".

And if you even wonder what your Perl program has loaded from where, the information is available to you in the %INC hash. Perhaps that should be another day's story!

Posted by gje at 08:48 PM


Related topics: via article database

Useful link: Perl training

June 23, 2005

Sudoku helper or sudoku cheat

Have you seen the sudoku puzzles that are being published in the Daily Telegraph and (I think) the Los Angeles times? There's a whole group of addicts out there and helper and forum web sites too. Lisa pointed the puzzle out to me recently (no, she's not an addict!) with the thought of providing a helper spreadsheet and wondered what I could do on algorithms.

The puzzle is easily explained. You're given a 9 x 9 grid of cells with some of them already filled in with a single digit in the range 1 to 9 and you have to complete the puzzle by adding further 1 to 9 digits such that each row, each column and each cluster of 9 cells contains each digit just once. Here's a blank board:


on which I've numbered the cells just for reference.

Here's that same game board completed. I filled in the numbers that you now see in red on the form above (try it out if you like) and when I submitted it to my program, it completed the other cells ... in this example right through to a complete solution.

I've not personally spent a huge amount of time on this - just played with the algorithms and I think that my program will solve most (but not all) puzzles. Furthermore, it's what I describe as a "spike solution" - the code is poorly written as it grew during my research. Bits of code are duplicated (I should have used a loop or functions), documentation and comments are lacking, and it's pretty poorly inset. You can see the code in this shocking state if you like and rightly criticise me. My defence is that it's a spike solution - a proof of context that needs re-engineering.

Two questions

Have I provided a "helper" or a "cheat"? Is a program such as this one a helper in the spirit of the game, or does it go to far and provide an unfair advantage? If that's the case, where's the limit?

Should I publish code like this? I'm quite happy with my spike solution and I don't think it opens any security holes on our site. So should I say "hey - look at this and use it if you like", should I publish it with a copyright statement, or should I be ashamed of myself for even typing code this p*sspoor in the first place?

Two more sample solutions - tests of my algorithm (I'll come back and replace one with a demo of what happens when someone submits a puzzle that can't be fully resolved).

Posted by gje at 06:32 AM


Related topics: via article database

June 22, 2005

Context in Perl

If you write a Perl program, you refer to lists with an "@" symbol in front of the list variable name. But depending on the context of how you write it, the program may interpret it as

  1. The list contents (if the operation is normal for a list)
  2. The length of the list (i.e. the element count) if that's the only thing that makes sense
  3. A space separated string with all the items in the list joined together (if it's in double quotes)

For example:

@salad = ("apple","banana","cherry");
$salad[3] = "tomato";
$salad[8] = "fig";

print @salad,"\n"; # list context
print @salad."\n"; # scalar context
print "@salad.\n"; # double quote context

will display:


applebananacherrytomatofig
9
apple banana cherry tomato     fig.

Posted by gje at 07:54 AM


Related topics: via article database

Useful link: Perl training

June 21, 2005

Ballooning from Bath

I don't know how to describe the sound. A sort of rumbly hissing from the sky, duration about 3 seconds. Not loud enough to make me jump, not long enough to turn and follow the sound to its source with my eyes. I turned around and scanned the sky; or rather, I scarcely needed to scan the sky as this great yellow inverted yellow tear drop passed close overhead.

On long summer evenings, the balloons of Bath fly over our home / training centre; here's a view taken just yesterday evening. We've more pictures in our pictures of Melksham Wiki.

Posted by gje at 04:31 AM


Related topics: via article database

June 20, 2005

Wimbledon Neck

What use is the "+=" operator? Why did the language designers bother to provide it? Yet they did ...

In Perl and PHP

$number_on_bus = $number_on_bus + $goton_here;
becomes
$number_on_bus += $goton_here;

In Python

number_on_bus = number_on_bus + goton_here
becomes
number_on_bus += goton_here

In C and Java

number_on_bus = number_on_bus + goton_here;
becomes
number_on_bus += goton_here;

The += operator adds the result of evaluating the expression to the right into the variable named on the left.

The code is shorter, but there's more too it than that. It makes the code easier to maintain - it saves what we call "Wimbledon Neck" which is very appropriate for me to be writing about this week as the tennis championships are just about to start. If I write
$longvariablename = $longthingummyname + $some;
then anyone coming along to maintain the code has to take a careful look on both sides of the assignment to see whether or not the information is being saved in the same slot from which it was loaded or not; can you visualise the maintainer turning his neck to the left, to the right, to the left, to the right rather like watching a tennis volley from the side line? If the element being used is a member of an array (= list in Perl) or hash (= dictionary, = associative array) then that's all the more checking to do.

So - it may not come natural to you to code += (or -= *= /= etc) but please do so ... you're making life easier for those who follow behind!

Posted by gje at 08:58 AM


Related topics: via article database

June 19, 2005

Improved mining techniques!

We count web site visits by the number of hits per minute these days ... rather than the number of hits per hour or day. Where do those visitors arrive? All sorts of places ... and not always the most relevant to their search, or at a page with the most relevant of links to them either.

We're fortunate that the Web provides us ... not only with a note of the IP address from which our visitor arrives (and hence we can make an educated guess at their country) but also with details of the page that initially provided a link to us and - usually - details of what they were searching for there if it was a search engine. With this extra information, we're now providing a handful of extra links on our pages (top right, where they'll be noticed) to new arrivals.

The extra code (script) is in PHP; it's not really in a shareable state at the moment (I think it's what they call a "spike" solution), but I'm sure I'll be talking about it during the next PHP course and enhancing my more detailed technical note in the near future.

Posted by gje at 01:36 PM


Related topics: via article database

June 18, 2005

Is photoajustment an addiction?

I used to wonder ... when I saw Lisa, head down, cropping and adjusting pictures through Photoshop ... I used to wonder how it could be so addictive. Ah - I think I'm getting to know; a few hours out in Bristol (just down the road from here) and some pictures. Each to be cropped, so to be colour adjusted (I'm not yet into removing cars and cables) and the day is turning to dusk.

A sample for the day:


which I've chosen because it represent three different sides of Bristol - the Industrial in the form of the Crane that's framing the picture, the religious in Bristol Cathedral, and leisure in the form of the yacht on the Floating Harbour.

I'm keeping my latest pictures in our shared page system on a test area page. Today I can tell you that you'll see Bristol, Severn Beach and the Severn Crossings. But this is a lovely country so the picture will be changing through the summer; some I'll share here.

Posted by gje at 09:07 PM


Related topics: via article database

June 17, 2005

Want to be one better

I'm told that I'm competitive - that I want to be one better. That's not always a compliment as it can mean that I tend to come in and "cap" your story with what I think is a better one - but at least I'm aware of this tendency and tell my good friends to alert me when I do it.

But this competitiveness is often a great asset when running a training company and course. I want to provide you with a better course, in a more appropriate venue, with a smaller group size and a more knowledgeable tutor using the most up-to-date notes. You wanna come on one of our courses?

Posted by gje at 01:20 PM


Related topics: via article database

June 16, 2005

Comments in Tcl

It's always a good idea to comment your programs. OK - I know you know that, but I find it's always a good idea to remind people too!

In Tcl, you add a comment starting with a # character and really what you're adding is a "do nothing" command .... in other words, the # must appear where a command would normally start (at the
beginning of a line, after a ; or after a { ) and the command will be terminated at the end of the line, but can be continued on to another line with a \

# comment \
puts hello
puts world

will just print out "world"! .....

Posted by gje at 11:15 PM


Related topics: via article database

Useful link: Tcl training

June 15, 2005

Graveyard pages

What do you do if you want to remove a web page from your site? Let's say that a product has been replaced by an improved model with (logically) a different page name, or you've restructured your web site so that an old URL is now illogical.

Obvious, easy answer ... search for all links to the old page and remove them. Yes - that's a good answer ... as far as it goes.

Is your search indexed by the search engines? Are your pages so good that other people have added in links to them? If you answer YES to either of those questions, then by withdrawing a page you'll be disappointing a proportion of your best traffic (that which is recommended to you) and your future (people who didn't know you until they did a search)

What you need for each withdrawn page is a "Graveyard page".

It works like this. You replace the retired page with a page that contain none of the keywords that the original was listed under - indeed has no useful displayed content. It simply says that "this page has been retired". BUT it provides a link on to the replacement page ... or on to a new destination if there's no exact replacement. And you also include a "meta refresh" tag in the header such as
<meta http-equiv="Refresh" content="5; URL=/net/recents.html">

How does it work?

Human arrivals, following links from other web sites or links provided by search engines won't get a "404" - they'll get a polite page that shows them that you don't let you web site get stale (good news!) and they'll get diverted on - automatically in 5 seconds, or manually, to the page that you now want them to see.

Search engines will still visit the page, but won't be impressed and it will slip down the ranking quite quickly. They will see the onward link, so they'll get to know of your new pages quicker than if you hadn't had the graveyard page there.

Posted by gje at 05:47 PM


Related topics: via article database

June 14, 2005

Frightening and from-friend viruses and spams

Viruses and spam get more and more clever at getting through! The authors of these pieces of rogue software know that their victims are more likely to open emails that come from colleagues or - better - from their web administrator. It's very easy indeed to guess the account names for administrators, and also to harvest email addresses from web sites. It's also easy to send an email from one internet connection and pretend to be someone who has no connections whatever with that connection.

Suggested action

Make a presumption that all unsolicted emails that ask you to open something or validate an account are forged and attacks. However, these attacks make it very hard for the real administrator to get through to you. If you think an email might be genuine, I suggest that you email the administrator by TYPING IN HIS EMAIL ADDRESS into your mail program and not by following a link in the email you have received (again, that may be forged).

DO NOT open any enclosures until you hear back.
DO NOT click on anything that looks like a link ... especially if it ends in .com - it could be a Dos executable program.

You might be wondering if spam and email filters and virus checkers can help you. To some extent they can - we've already got email filtering in place and yet a proportion of these things get through. The particular problem with the messages highlighted in this article is that they're designed to look as close as possible to the genuine article, so they're hard for filters to deal with. We do recommend a virus checker on your own system, and that you use the virus checkers / filters provided by the ISP from whom your download.

Example of a rogue email

Here (for example) is an email I received within the last hour ....

Dear user graham,

You have successfully updated the password of your Wellho account.

If you did not authorize this change or if you need assistance with your account, please contact Wellho customer service at: administrator@wellho.net

Thank you for using Wellho!
The Wellho Support Team

+++ Attachment: No Virus (Clean)
+++ Wellho Antivirus - www.wellho.net

<enclosure called email-password of 31k, type .zip>

"Clearly" from someone who doesn't know us, for example ...
- We're "Well House Consultants" not "wellho"
- We don't style ourselves as "support team"
- We don't actually have an "administrator" email address

And what would be the point in sending out an attachment to someone who's correctly updated their email anyway? Ah - it's an attempt to get the recipient to open the .zip file which will infect his computer!

Posted by gje at 09:39 AM


Related topics: via article database

June 13, 2005

No Smoking Pubs

I've noticed a trend towards no smoking pubs recently ... and I applaud the idea.

No-one should have to indulge in passive smoking if they want to go out for a meal - I wouldn't even wish it on a dog.

See our Malmesbury page to locate the "Smoking Dog" Pub.

Posted by gje at 06:19 AM


Related topics: via article database

June 12, 2005

Spotting a denial of service attack

Our web site traffic rose from 37000 hits last Wednesday to 64000 hits on Thursday. Good sales and marketing activity on our part? No - it's a potential problem; all the extra traffic came from a single location and my immediate concerns included:

* Possible denial of service, where all the bandwidth was being eaten up by the visitor.
* What use were they making of what was approaching a complete copy of the site?
* Potential extra costs if we were to hit our traffic ceiling

On this occasion, I noticed that we had a problem on Friday when I looked at the previous day's log analysis and spotted the problem sticking out like a sore thumb. I spent a couple of hours yesterday investigating more thoroughly, and putting a filter in place to cap aggressive browsing as it happens - a piece of PHP some 30 or 40 lines long. PHP's a powerful language, so in those lines I'm also able to add a permanent record of the potential abuse to a database ...

If you want to read more, I've put a technical analysis and sample PHP script in our solution centre.

Posted by gje at 07:17 AM


Related topics: via article database

June 11, 2005

Walk in Bath

Last night after the course was over, we drove to Bath with one of our students who's not travelling home until today, had a look around, took some picture, had a meal and ... a very pleasant time.

Plenty more pictures of the area are available too. Just click on a highlighted location on this map and you'll see what I mean.

Posted by gje at 11:35 AM


Related topics: via article database

June 10, 2005

Should I use structured or object oriented?

There's no "one size fits all" answer to "what's the best way for me to meet this application requirement", and if you're writing code there will be a number of different approached / methodologies you can use. I'm going to have a look at some of the possible choices and relate it to PHP today ... it's rather on my mind as I'm teaching an Object Oriented PHP course.

If your application is tiny, you can just write a single block of code. Let's face it, if you've just got a regular HTML web page on which you want to include today's date, a simple PHP print(date( ... is all you need. If the application is not tiny (but remains small), you would be well advised to split out the logically separate elements into functions. Taken to the extreme, you're looking at structured programming design where everything's in a function and each function performs a single logical task.

As applications grow, structured programming gets unwieldy too and you'll be best advised to use an Object Oriented approach. That's a great way to compartmentalise your code, allowing for easy extensability and code testing unit by unit.

As applications grow still further, from medium size to "large" or "huge", another trend may become apparent. While the development team is a tight little community, all the members know and share knowledge and will only call up pieces of code through appropriate ways - what I describe as a Trusted Object Oriented system, where the programmers are trusted to know what they're doing. But grow the thing massively, and there will be times that team members call up a piece of code in a way that the team leader would really rather they didn't. At this stage, you'll want to be using what I call a "Policed Object Oriented" system where externally visible components are marked with words such as "private", "public" and "protected".

PHP in various versions supports single code blocks, trusted OO and policed OO:

Application sizeMethodologyWeb language
SmallNot OOPHP - any version
MediumTrusted OOPHP4 or PHP5
LargePoliced OOPHP5

Bear in mind that if you want a policeman at the end of each street to protect you from the villains, you're going to have to pay for it in your taxes. The same thing applies with OO in PHP - a policed OO system may slightly extend development time, but you may feel that it's worth it. Certainly, when you're doing your initial coding practise you should use the trusted approach so that you're not hauled over the coals for every tiny error while you learn.

Posted by gje at 12:39 PM


Related topics: via article database

June 09, 2005

The evening after the course

I'm having a great week running a public PHP course - a near-perfect (from a teaching viewpoint) group of 4 trainees - enough for there to be plenty of interaction, and few enough for everyone to be getting the very best of attention and tailoring of the course. This week, everyone's fit and is a keen walker, and is staying in a local B&B or hotel ... so we took the local OS map and walked out to Seend, on the Kennet and Avon Canal and ate at "The Barge" - one of the lovely country pubs near Melksham.

There are many public footpaths in the area (map) and we saw a good selection - from urban through Bowerhill and well-defined across the field, to the cycleway beside the canal and some more adventurous paths on our return - along the railbed of the old Iron Plateway (Seend was quite an industrial spot) to the site of Seend Station - through a field of cows, then over a field of wheat back to the main road. Now who was it who commented "I didn't know I was coming on a teambuilding exercise ;-) "

Posted by gje at 07:30 AM


Related topics: via article database

Happy Birthday, PHP

PHP is 10 years old; it's ten years since Rasmus Lerdorf announced version 1.0 of Personal Home Pages on the comp.infosystems.www.authoring.cgi newsgroup. Announcement of 8th June 1995

Posted by gje at 07:19 AM


Related topics: via article database

Useful link: PHP training

June 08, 2005

Code and code maintainance efficiency

Three maxims of coding and system development; I'm reminded of these this week as I run a PHP course which is heavily biased towards good coding standards / writing robust and maintainable web sites, but they apply to other languages / coding systems too!

"If you find yourself repeating something, then there must be a better way of doing it".

Have you even copied and pasted a block of code? I know I have, and then I've probably modified the duplicate. If you're copying and pasting, think again. Perhaps you should be incorporating the block of code into a loop, or perhaps it should become a function? If you're copying and pasting, but then altering the copy, you can still use a loop or a function - the bits that you change will become the loop control variables, or the parameters to the function.

"If you think to your self 'surely someone else has done this before', they probably have"

Don't re-invent the wheel! You'll very rarely be the first person ever to want to do "x" or "y", so have a look for a function / procedure / command that does what you want. In the Open Source world especially, where code develops with a multitude of enthusiastic contributors, you'll find rich picking by browsing the manuals in the area around what you're looking for. On our Python course, I tell a story against myself. In a live application, I wanted to re-arrange a list into a random order. Great - wrote the code, tested it, and it worked well. Then I discovered that there's already a shuffle method in the random module that's a part of the standard distribution ...

And in PHP we have a saying - "There's a function to do that".

"Each component should perform a single task"

Keep each logical task in its own component. Why? Because, later on, you may wish to use that task again and if it comes bundled with a second task with which it's not logically connected, it may be non-trivial to separate out. Again, an example; the images on the left hand side of our web site are 132 x 300 pixels, and they're all bundled with a white band 8 pixels wide on the right to separate off the text from the margin. Great ... until I want to change the colour of the band. Because I've bundled the band and the picture in the same image file, there's no easy way.

Posted by gje at 05:36 AM


Related topics: via article database

June 07, 2005

Passing information into and out of PHP functions

In PHP, named blocks of code are referred to as "functions". By default, variables within functions are created each time the function is run, and do not conflict with any other similarly named functions elsewhere in your code. That's good news for coders of medium sized and larger applications, who want to be able to pull in code from included files written by others without the need to avoid any variable names that the others may have used, but it does mean that the language has to provide mechanisms to get information into and back from functions so that they don't run in complete isolation from one another.

Here's a review of the ways of sharing data between functions, or saving data from one use of a function to the next.

Parameters. Parameters are passed in to functions in a list in round brackets after the call, and the names that will be used for the parameters are declared in a similar length list within the function definition. Note that by default the values passed to a function are COPIED in to those variables, so that any changes made are NOT reflected in the source variable in the main code.

Return Values. At the end of a function, you can choose to return a variable or an expression, and that will be saved into a variable in the main code is you choose to assign it, or you can test it in a conditional statement or include it in another expression if you wish. Although only one variable can be passed back, it can be an array - so that in effect you can pass back a collection of values.

Parameters and return values are the recommended way of passing most information in and out of functions. The other facilities listed below all have their uses, but they should not be used to excess.

Default parameters. If you declare a function with a defaulted parameter (e.g. if you say $abc=17.5 rather than just $abc in the function definition), you're then allowed to call the function omitting the parameter and if you do it will assume the value given. Very useful if you have a function that has parameter(s) that are only needed on some occasions.

Parameters by name. If you declare a function with a leading & character in front of the $ - so &$abc rather than $abc for example - then the parameter will not be copied in to the function, but rather the internal variable name will be used as another name for the same piece of data in the calling code. This means that if you alter the variable in the function, you're also altering the variable with which it is connected in the main code. A very useful facility, but very dangerous if the calling programmer isn't aware that your function may change his settings.

Globals. If you declare a variable to be global in a function, then that variable is the same as the variable of the same name in your main code. There's no need to declare anything as global in the main code - things always ARE global there. Use this facility sparingly, as it can cause functions to be less portable now that they work with fixed name values, and it can bring variable name conflicts one step closer. If you want to share variables between several functions, you can declare them to be global in each function and it will work - just be careful you don't use the same variable name for something else in the main code!

Super-Globals. PHP provides you with a number of variables such as $_SESSION and $_REQUEST which as known as "superglobals". They're always available in any functions without the need to declare them, and a reference to a superglobal within a function is the same as a reference to a superglobal in the main code.

Statics. Usually, a function's local variables are lost when you exit from a function and then they'll be re-initialised next time the function is called. That's usually the behaviour that you want, since most of the time you're likely to be calling functions several times with each of the calls being unrelated to previous calls. However, if you want a variable to persist from once call to the nest, you can declare it as static.

Posted by gje at 08:19 AM


Related topics: via article database

Useful link: PHP training

June 06, 2005

OO techniques are hard to teach

Spam from my inbox a few minutes ago ... "OOD (object-oriented design) is a topic that is notoriously difficult to teach because the design priciples are so abstract. Fortunately, we, [[name or organisation deleted ]] (a non-profit organization funded by the Macau government), have found a way to teach it effectively."

I agree that it's very hard to teach OO principles ... but I've been doing it for a number of years and feel well tuned to doing so - especially on courses such as python and C++ where the languages are "pure" OO.

Of course, we have something over the spammers mentioned above for the European market - we have a training centre to teach you face to face in Melksham, rather than being an offshore operation from the Far East.

Posted by gje at 08:48 AM


Related topics: via article database

the array returned by preg_match_all

PHP supports two regular expression handlers - the "ereg" series that uses POSIX style regular expressions, and the "preg" series that uses Perl style. Why? Because both have their uses - the POSIX style makes for easier-to-read expressions and are said to be easier to learn, and the Perl style is more powerful and quicker in operation ... at the price of being harder to learn and follow.

I was updating some code in our Wiki yesterday and needed to search for all words in a string that start with a capital and include an embedded capital, since we use them as links - visit our shared data system to see what I mean. But then I hit a curious bug - introduced myself - where there were multiple hits. Turned out to be a good reminder that preg_match_all returns an ARRAY of ARRAYs - with each array contained being a list of each of the elements matching the revelant "interesting bits" in the regular expression given. Hmm - that might be clear as mud when I describe it, so here's an example:

<?php
$demo = "SwinDon ChippenHam MelkSham TrowBridge and WestBury";

preg_match_all('/([A-Z][a-z]+)([A-Z][a-z]+)/',$demo, $gotten);

foreach ($gotten as $set) {
foreach ($set as $item) {
print "$item ... ";
}
print ("<br>");
}
?>

You would EXPECT to get five arrays back - one for each of the place names. But actually you get just three - one for the complete names of the places, one for the start of the place name, and one for the end of the place name.


SwinDon ... ChippenHam ... MelkSham ... TrowBridge ... WestBury ...
Swin ... Chippen ... Melk ... Trow ... West ...
Don ... Ham ... Sham ... Bridge ... Bury ...

Once you've come across this for the first time, it's easy enough to handle in your program - but I just felt it was worth a Beware - counterintauative feature warning here. And there are flag options to the command that let you alter its behaviour if you wish

Posted by gje at 05:40 AM


Related topics: via article database

June 05, 2005

Targetted Advertising




Who? Me??
Charlie (the cat) sends her best wishes to all of the trainees that she's met on Well House Consultants courses and looks forward to meeting you again in the future. She's particularly keen to tell you about the new C Programming and C++ Programming courses that we're running as from August

Posted by gje at 10:39 AM


Related topics: via article database

June 03, 2005

Sad priorities

I was just watching the gentleman who was the US's ambassador to Ethiopia from 1996 to 1999 on the TV. He was saying that we shouldn't expect the USA to fund any new plans for poverty relief in Africa that are proposed at the forthcoming G8 summit, as the USA is already stretched economically. He reminded us that they're busy spending their money on fighting wars in Afganistan, Iraq, and "The global war against terrorism".

Isn't it sad that we live in a world where the priorities have been set as such, for whatever reason.

Posted by gje at 05:45 PM


Related topics: via article database

June 02, 2005

Symbolic links and hard links

Files are arranged in directories (or folders if you prefer that term), and each file can be reached through a series of directories and sub-directories from the root - correct? Yes ... BUT ... there are some times that the same file can be reached through several names, and on Unix and Linux systems this is known as a "link".

There are two ways a link can be set up.

A Hard Link is where a file has two names which are both on an equal weighting, and both of the file names in the "inode table" point directly to the blocks on the disc that contain the data. See diagram to the left.

You set up a hard link with an ln command without options - if the file ab.txt already exists and you want to give an additional name (hard link) to it, you'll write
ln ab.txt cd.txt
and then both names will have equal ranking. The only way you'll know that there's a link there is by doing a long listing and you'll see a link count of 2 rather than 1, and if you need to find out what's linked to what, use the -i option to ls.

A Symbolic Link is where a file has one main name, but there's an extra entry in the file name table that refers any accesses back to the main name. This is slighly slower at runtime that a hard link, but it's more flexible and much more often used in day to day admin work.

Symbolic links are set up using the ln command with the -s option - so for example
ln -s ab.txt cd.txt
will set up a new name cd.txt that points to the (existing) file ab.txt. If you do a log listing (ls -l) of a directory that contains a symbolic link, you'll be told that it's a symbolic link with an "l" in the first column, and you'll be told where the file links to in the file name column. Very easy to spot!

Linux Administrators need to be aware of both symbolic and hard links; some of the operating system's files have two names and are installed as hard links, and if the administrator's installing software and wishes to do so under a generic name, there are good arguments for him to do so via a symbolic link.

Symbolic links are also a relatively painless way of placing files onto a disc partition (slice) that's not the one you would expect from the name through which you reference them - which is great if one of your partitions has got nearly full but there's space elsewhere, or if you want to position something on a partition that's got a different backup strategy / system in place to the one of the default location.

Posted by gje at 05:17 AM


Related topics: via article database

June 01, 2005

Do NOT follow links or read attachments in these emails

A word of warning. If you get emails with these subject lines or anything like ... DO NOT click on the embedded links in them. These are what are called "Phishing emails" and are looking to steal your identity by have you enter your name, password and other information on a fake site.

Update And Verify Your PayPal Account
Your eBay account could be suspended!
eBay Fraud Mediation Request
Unauthorized Access To Your Marshall & Ilsley Internet Banking Account
Official information for all People's Bank clients.

Beware - these emails can look VERY convincing!

A further word of warning. If you get emails that have these subject lines or anything like ... DO NOT open the enclosures within the email as they contain nasties - files that will infect you machine with a virus, trash your system, send your system information to a third part on the net of some other obnoxious action.

*WARNING* Your Email Account Will Be Closed
Your Email Account is Suspended For Security Reasons
Important Notification
*DETECTED* ONLINE USER VIOLATION
RETURNED MAIL: DATA FORMAT ERROR
Notice of account limitation
ACCOUNT ALERT
Re: My details
Re: Your archive
Error
Notice: **Last Warning**
Account Alert
*WARNING* Your Email Account Will Be Closed

Beware - these emails can frighten you into opening them - don't!!!

I know - most people are already aware of these emails, but please don't be taken in however convincing they look. And if you get an email that says it's from me but you're not convinced, please email me to ask.

Posted by gje at 06:04 PM


Related topics: via article database

Looking up IP addresses

Browsers, mail clients, ftp and ssh and telnet clients and the rest are for ever converting fully qualified names such as www.sheepbingo.co.uk into IP addresses such as 212.227.118.78. How can you do such a lookup manually?

Firstly, there are numerous web sites out there that will help you - I'm nit supplying any links here because I'm sure you already have your own favourite. But did you know that there are ... not one ... not two ... but three utilities under Linux to do the job for you?

The host command does a quick and dirty lookup:

[trainee@saturday trainee]$ host www.sheepbingo.co.uk
www.sheepbingo.co.uk has address 212.227.118.78
[trainee@saturday trainee]$

The dig command tells you a lot more:

[trainee@saturday trainee]$ dig www.sheepbingo.co.uk

; <<>> DiG 9.2.1 <<>> www.sheepbingo.co.uk
;; global options: printcmd
;; Got answer:
;; ->>HEADER<<<- opcode: QUERY, status: NOERROR, id: 31254
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;www.sheepbingo.co.uk. IN A

;; ANSWER SECTION:
www.sheepbingo.co.uk. 10476 IN A 212.227.118.78

;; Query time: 17 msec
;; SERVER: 158.152.1.43#53(158.152.1.43)
;; WHEN: Wed Jun 1 08:42:54 2005
;; MSG SIZE rcvd: 54

[trainee@saturday trainee]$

And the deprecated nslookup give interactive facilites too

[trainee@saturday trainee]$ nslookup www.sheepbingo.co.uk
Note: nslookup is deprecated and may be removed from future releases.
Consider using the `dig' or `host' programs instead. Run nslookup with
the `-sil[ent]' option to prevent this message from appearing.
Server: 158.152.1.43
Address: 158.152.1.43#53

Non-authoritative answer:
Name: www.sheepbingo.co.uk
Address: 212.227.118.78

[trainee@saturday trainee]$

Posted by gje at 08:44 AM


Related topics: via article database