You are invited to Log in or Register a free Frihost Account!

A Programmers Thoughts

Created on Tue Sep 04, 2007 4:17 am with 13 blog posts
About programming, development tools and software development in general. And sometimes just about me and the projects I am working on.

The many Differences between Java and JavaScript in Diversions with 0 comments on Sun Jun 22, 2008 4:28 pm

JavaScript, despite the name, is essentially unrelated to the Java programming language, although both have the common C syntax, and JavaScript copies many Java names and naming conventions. The language was originally named "LiveScript" but was renamed in a co-marketing deal between Netscape and Sun, in exchange for Netscape bundling Sun's Java runtime with their then-dominant browser. The key design principles within JavaScript are inherited from the Self programming language.

Thanks to this marketing-deal, a lot people think JavaScript is related to Java. It is not. Yes, (some of) the syntax is similar, but that's where the similarity ends. Here are the most important differences between Java and JavaScript:

  • Developed by
    Java: Sun Microsystems
    JavaScript: Netscape
  • Language paradigm
    Java: Class-based OOP
    JavaScript: Prototype-based OOP
  • Main influenced
    Java: Objective-C and C++
    JavaScript: the Self programming language (
  • Typing discipline
    Java: static, strong
    JavaScript: dynamic, weak
  • Application domain
    Java: general purpose, desktop applications, serverside
    JavaScript: embedded scripting
  • Execution type
    Java: Compiled (to bytecode or native code)
    JavaScript: Interpreted
  • Objects are...
    Java: instantiated classes
    JavaScript: associative arrays
  • First-class functions?
    Java: No
    JavaScript: Yes
  • Block-level scoping?
    Java: yes
    JavaScript: no (!)
  • Closures? (
    Java: no
    JavaScript: yes
  • Variadic functions?
    Java: no (limited support for variadic functions since J2SE 5.0)
    JavaScript: yes

and some more:

  • Semicolons mandatory?: Java: yes, JavaScript: no
  • Runtime code evaluation?: Java: no, JavaScript: yes
  • Size of standard libraries: Java: very, very large, JavaScript: very small
  • Native regex support: Java: no, JavaScript: yes
  • Global code (code outside class definitions): Java: no, JavaScript: yes
  • Thread support: Java: yes, JavaScript: no
  • Sparse arrays?: Java: no, JavaScript: yes
  • Exception handling support?: Java: yes, JavaScript: since version 1.4
  • Generics?: Java: since JDK 1.5, JavaScript: would make no sense
  • Original name: Java: "Oak", JavaScript: First "Mocha", later "LiveScript"
  • Reason for picking the final name: Java: random word, JavaScript: marketing
Small Diabetes FAQ in Diversions with 0 comments on Sun Jun 01, 2008 1:18 pm
What are the causes of diabetes?

The following factors increase the risk of developing diabetes:

  • Genetics. People who belong to a family background having a history of diabetes are 25% more prone to develop diabetes.
  • Overweight. Obesity is one of the main causes for Diabetes 2 in developed countries.
  • Emotional stress
  • Virus infections can also lead to diabetes.

About the causes of Diabetes 1 we currently don't know much, altough it seems that there might be a genetic factor to it.

See also:

Is diabetes infectious?

You cannot get diabetes through contact with people who have diabetes, nor by having intercourse with them, sharing food or exchanging blood.

See also:

Can eating a lot of sugar cause diabetes?

But eating a lot of sugar can cause overweight, which in turn can cause diabetes.

Can diabetics have sugar?

In the past it was believed that sugar had a different effect than other carbohydrates, and diabetics were advised to avoid sugar. Today we know that there is no difference between sugar and other carbohydrates, and therefore there is no special reason for diabetics to avoid sugar.

See also:

Should diabetics eat special (so-called 'diabetic') food?

No. In modern diabetic practice it is not adviced to eat 'diabetic' food. It has no real benefit, tastes bad, is expensive, gives false security and often contains ingredients which are bad for your health.


Special diabetic foods: These are not recommended. They may contain more fat or energy than other foods and may be low in fibre.

Source: Diabetes care in General Practice, M. MacKinnon

See also:

Can diabetics drink alcohol?

Yes. Altough alcohol can cause the blood glucose level to decrease, and it is therefore advised to consume some food while drinking alcohol, there are no special risk attached to alcohol for diabetics (other than the risks alcohol consumption might have in general, diabetic or not).

See also:

Can diabetes be cured?

No. At the moment there is no cure for diabetes. Sometimes, in extreme cases, a pancreas or a kidney-pancreas transplant is performed, after which the diabetes is gone. Still, the patient generally remains on long-term immunosuppressive drugs and there is a possibility that the immune system will mount a host versus graft response against the transplanted organ. Technically such an operation is not a cure.

See also:

What are the symptoms of diabetes?

They differ per person and situation, but common symptoms are:

  • Increased thirst
  • Going to the loo (for a wee) all the time – especially at night
  • Extreme tiredness
  • Weight loss
  • Blurred vision or sudden vision changes
  • Genital itching or regular episodes of thrush
  • Slow healing of wounds
  • Extreme hunger

See also:

What should I do if I think I might have diabetes?

Go to your general practitioner to have yourself tested. Even when in doubt.

See also:

Is diabetes deadly?

Type 1:: Untreated diabetes type 1 almost always leads to dead within 1 or 2 years.
Type 2:: Untreated diabetes type 2 might be deadly on the long term, but is doesn't have to be. You can even live very long with untreated diabetes 2, but you will propably get several nasty complications.


Diabetes was the sixth leading cause of death listed on U.S. death certificates in 2002. This ranking is based on the 73,249 death certificates in which diabetes was listed as the underlying cause of death. According to death certificate reports, diabetes contributed to a total of 224,092 deaths.

Source: (PDF)

What is the difference between Type 1 and Type 2 diabetes?

In type 1 diabetes no insuline is produced. In type 2 diabetes insuline is produced, but it does not work like it should. About 5% to 10% of diabetics have type 1. In some ways they are very different diseases.

(There is also a 3rd type of diabetes: Gestational Diabetes, which some women develop during pregnancy.)

See also:

Type 2 diabetes is mild diabetes?

There is no such thing as mild or borderline diabetes. All diabetes is equally serious, and if not properly controlled can lead to serious complications.

Can a diabetic fast (abstaining from eating for some time)?

Yes. Muslims, christians, buddhists, etc. with diabetes can fast. But care must be taken, and you need to be aware of potential problems and risks. In general, diabetics should consider not to fast (According to Islamic jurisprudence (Fiqh), a diabetic Muslim is exempt from fasting).

How many people have diabetes?

According to the NDIC (National Diabetes Information Clearinghouse) and the American Diabetes Association, in 2005 in the USA 20.8 million people (7% percent of the population) had diabetes, of which 6.2 million people where undiagnosed.

According to Diabetes UK, in the UK there are 2.3 million people with diabetes and there are more than half a million people with diabetes who have the condition and do not know it.

In 2006, according to the World Health Organization, at least 180 million people worldwide suffer from diabetes. The WHO estimates that by the year 2030, this number will be more than double.

According to the International Diabetes Federation, diabetes currently affects 246 million people worldwide and is expected to affect 380 million by 2025. In 2007, the five countries with the largest numbers of people with diabetes are:

  • India (40.9 million)
  • China (39.8 million)
  • the United States (19.2 million)
  • Russia (9.6 million)
  • Germany (7.4 million).

See also:
Why Perl isn't easy to learn in Diversions with 0 comments on Thu May 22, 2008 3:54 pm
"...Perl is easy to start learning--and easy to keep learning."
- The PerlFAQ

"We think that Perl is an easy language to learn and use, and we hope to convince you that we're right."
- Programming Perl (Larry Wall, Tom Christiansen, Jon Orwant)

I disagree. Perl is not easy to start learning. And it's not easy to use until your at least past the Beginner level. This is not a Bad Thing (tm). There is no reason why a programming language should be easy to learn. History even seems to indicate that easiness is not a Good Thing when it comes to programming languages (PHP, Basic). Why is Perl not easy to get started with?


In Perl, every expression is evaluated in scalar or list context (well, these are the most important 2 contexts), and the resulting value can be very different and sometimes not what you expected.


($x) = (1,3,2);                 # $x = 1
$y   = (1,3,2);                 # $y = 2
@l = (1,3,2);
$z = @l;                        # $z = 3

The fact that the expression in a return statement is evaluated in the context in which the function is called can easily throw an unsuspecting newcomer off. This prints "b":


sub f() {
   return undef;

print "a" if ($a = f());                # $a = undef, nothing is printed
print "b" if (@b = f());                # @b = (undef) !! prints "b"

List flattening

When a list is evaluated, each element of the list is evaluated in a list context, and the resulting list value is interpolated into the list just as if each individual element were a member of the list, to paraphrase "Programming Perl" (the Camel Book).
What does this mean? Lists within lists are flattened:


my @a = (1,2,3);
my @b = ();
my @c = (4,5,6);
my @d = (@a, @b, @c);

@d now contains the list (1,2,3,4,5,6), and not ((1,2,3), (), (4,5,6)) as you might expect.
List flattening also occurs with arguments to functions and their return values. All function parameters are passed as one single, flat list of scalars, and multiple return values are likewise returned to the caller as one single, flat list of scalars:


sub f {
   my (@first, @second) = @_;
   print "First list: @first, ";
   print "Second list: @second";

my @list1 = (1,2,3);
my @list2 = (2,4,6);
f(@list1, @list2);

This prints "First list: 1 2 3 2 4 6, Second list:".
Now consider a Perl novice who wants to write a functions which substracts the length of the second list it is given from the length of the first. So, given @list1 and @list2, the function should return the value of @list1-@list2.


sub f {
   return @list1-@list2;   

my @list1 = (1,2,3,4);
my @list2 = (2,4);
print f( ... );

But how to get the two arrays into f() without them becoming flattened to one array? A solution obvious to seasoned Perl programmers, like this:


sub f {
   my ($list1, $list2) = @_;
   return @$list1-@$list2;   

my @list1 = (1,2,3,4);
my @list2 = (2,4);
print f(\@list1, \@list2);

isn't exactly, well..., beginner-friendly.

More Than One Way to Write It
Perls motto is TIMTOWTDI, but there is also often more than one way to 'write' (express) the same thing:

(one => 1, two => 2, three => 3)
is the same as
('one', 1, 'two', 2, 'three', 3)

("one", "two", "three")
is the same as
qw|one two three|

display { find Critter "Fred" } 'Height', 'Weight';
if Critter is a class and find a method which returns an object, this is the same as
Critter->find("Fred")->display('Height', 'Weight');

is the same as



print while (<STDIN>)

does the same as


while ($x = <STDIN>) {
      print $x;

Symbol Table and Variable Peculiarities

Global variables and local (lexical) variables are totally diffent things. To really understand the differences you need to know about how they are implemented. For example: global variables are implemented using 'typeglobs', which means you can alias them. Local variables are not.


$a = 4;
$b = 3;

   print ($a+$main::a);                     # prints 8
   my $a = 5;
   print ($a+$main::a);                     # prints 9
   local $b = 1;
   print ($b);                              # prints 1
   print ($main::b);                        # prints 1 too!!


print ($main::b);                                # now prints 3 again!!

Parsing Peculiarities
The way Perl parses a program is sometimes (often?) confusing when you are not an advanced perl hacker (yet).


print (3*4)+2;          # prints 12
print 2+(3*4);          # prints 14

Other Oddities

  • Perls prototypes look like, and often behave like, parameter specifications in other languages. But they are not, and they change the way your function calls are parsed and executed.

  • A lot of functions and operators use the scratchpad variable $_. AFAIK there is no other language with such a functionality.


    # print all input with all letters in uppercase
    while(<STDIN>) {                        # put input lines in $_
       tr/a-z/A-Z/;                    # change string in $_
       print;                          # print $_

  • The relation between the compile phase and interpreter phase is complicated. It is possible (and often practical or necessary) to have the compiler call the interpreter during compiling (for example using BEGIN) or have the interpreter call the compiler at runtime (for example using eval).

  • Methods on objects are just ordinary function with a reference to the object passed in as first parameter. new is just another method. Classes are 'just' packages. Objects are 'just' arbitrary pieces of data, with a blessed reference pointing to them.

  • An assignment expression is a lvalue:


    ($a = 4) = 5;
    print $a;         # prints 5;

  • Autovification. This prints "2":


    print 1 if (defined($a));
    $b = $a->{x};
    print 2 if (defined($a));

  • Using the same notation for different things:
    This leads to confusion by people who are new to a language.
    For example: "use strict" is a compiler pragma, "use CGI" imports the CGI module. <FILE> is a filehandle, <*.txt> returns a list of txt files in the current directory.

  • Endless Flexibility
    Flexibility is nice. And Perl takes this to the extreme. But nice as it may be, flexibility does not necessarally makes a language more transparant and/or easier to master (that's an understatement).


    sub f() {
       return \$x;

    ${ f() } = 3;                   # using a block statement instead of variable name
    print $x;                       # prints '3'

Google Power in Tips and Tricks with 0 comments on Sat Jan 12, 2008 2:01 am
Google can do a lot more than just searching for words in websites. Here are some tricks I like to get more out of Google:

  • Local Search

    Some sites do not have search functionality, and a lot of sites have an inferior search: it finds too much, too little or too slow. Often it is more effective to search the site using google, by using the site: directive. For example: to search wikipedia for information on 'root beer', use:



    You can not only use this with domain names, but also with subdomains (as in the example above) and even with top level domains:


    area 51 site:gov

  • Specifying the URL

    To let google return only URLs which contain a specific term, use the url: directive. For example, to search the blogs at frihost, use:


    hello inurl:/blog/

  • Site info

    If you want quick info about a site, use the info: directive. It provides you with the relevant info google has about the site: Similar sites, pages that link to this site and a link to the latest google cache of the site (if there is one):


  • Google as a thesaurus

    If you want to know the meaning of a word, you can often get a list of short definitions from google, by using the define: directive:



  • Finding open directories

    I'm not going to tell you why browsing through open directory's is usefull and/or fun, but finding opendirs using google isn't very hard:


    intitle:"index of" "parent directory" "last modified" funny  .jpg

  • Specialized Google search engines

    Not everybody knows Google also has some specialized search engines for searching in a specific area.

    • Music

      It seems Google's musicsearch is online since about 2005, but (AFAIK) Google does not link to it anywhere. To use it, use this URL (with the search term of your choice):


      Use a plus (+) instead of space. It searches for artists, albums and songtitles matching your search term.

    • Movies

      The movie search has it's own page at google: It searches for movies related to your search, and gives links to reviews including a rating.

    • Google Scholar

      Google Scholar searches peer-reviewed papers, theses, books, abstracts and articles, from academic publishers, professional societies, preprint repositories, universities and other scholarly organizations. Be sure to check the advanced search options.

    • Photo share

      Search for photo's shared by Picasa users (Picasa is Google's free image manager) at

    • Some more...

      These are more well-known:

      BOOKS, BOOKS, BOOKS: The book lovers wet dream:
      Find colleges and universities:
      U.S. Government related:

    • Other stuff

      Which music is hot at the moment? Check it at

      Google Answers: It is closed, so no new questions can be asked, but the archive can be viewed and searched. People could ask questions, and pay for the most helpful answers, which led to relatively high quality answers (at least, that was the intend):

  • Alternative (non-official) interfaces to Google

      In 2005 Google launched Google X, but took it down the next day. It consisted of an alternative Google interface which had more eyecandy, based on the looks of OS X. It inspired several non-official alternative Google interfaces, and this is one of them.

      A lot of search options combined in one form. A nice page for advanced googlers.

      An interface to Google's calculator. Unit conversion, trigonometry functions, interest rates, etc.

  • Man pages

    If you want to look up a Unix man-page, you can use google to quickly have it displayed in your browser. No need to start a shell, and manpages are easier to read from your browser. Just type man fopen and click the I'm feeling lucky-button.
    You can look up perldoc items the same way: perldoc open, and click the lucky-button. Nice when you are working on a remote Perl script on a computer without Perl installed.
    For the Java API reference, use javadoc LinkedList. Ruby: rdoc Net::Http. Haskell: haskell foldr. Etc..

  • Finding web proxy's

    Google is also great for quickly finding some webbased (anonymous) proxy's. The results often contain some dead links and slow servers, but hey, it's free and easy. Try one of these searches:


    "Remove all scripts (recommended for anonymity)"
    allinurl:nph-proxy .cgi
    allinurl:nph-proxy .pl
    inurl:phproxy filetype:php
    "include mini URL-form on every page"

  • Reversing md5 hashes

    You can also use google to reverse md5 hashes, for example when you don't remember your password and it is stored in one of your databases md5-encrypted. If you don't have access to rainbow tables, you can try:



    You will find that your password was "password". Tsk tsk, that's not very safe. If google doesn't return any results, try it without inurl::



    Looking at the results for a while, you can see that this time your password was "passw0rd". Better, but still not very safe. Be more creative! Wink

Automating your Forum Signature with Perl in In Command with 0 comments on Thu Dec 27, 2007 8:48 pm
A few days ago, I thought it would be nice to put the three most recent headlines from Slashdot in my forum signature (Don't ask me why). This can be done using a cronjob which runs every hour and executes a little program which gets the 3 newest headlines from slashdot and changes my signature. The program is short and simple. I wrote it in Perl, using Perl's WWW::Mechanize library, which allows you to automate all kinds of web related tasks: following links, filling in forms, downloading and uploading, etc.

First the script has to fetch the latest headlines. Although you can take them from the frontpage at, this file contains all kinds of HTML and other stuff which is of no interest in this case. Of course slashdot also offers serveral RSS-feeds, and the feed located at is exactly what I want: it contains both the titles and links of the articles, and it is short and easy to parse.

First I use get($url) to get the source of the page. Get() is provided by the module LWP::Simple and simply returns the HTML source of the URL as a string. Next, a regexp is applied to the string to get the titles and links of the first 3 items, and they are used to create the new sig:


sub headlines() {
    my $source = get("");
    $source =~ /<item>.*?<title>(.[^<]*?)<\/title>.*?<link>([^<]*?)<\/link>.*?{3}/si;
    return "Now on slashdot:\n[url=".$2."]".$1."[/url]\n[url=".$4."]".$3."[/url]\n[url=".$6."]".$5."[/url]";

Next, the script has to put the new sig into my profile, located at (this URL of course depends on the site at which the forum is located). Before the script can make changes, it first has to log in. To log in we have to fill out the form at (or something like that) and submit the form:


    my $mech = WWW::Mechanize->new();
   $mech->field("username", "Monkeys");
   $mech->field("password", "Bananas");
   $mech->click_button( name=> "login" );

That's all. WWW::Mechanize takes care of the details. It also stores the cookies it receives after logging in for the remainder of the session. Now that we are logged in, and have a cookie, we can change the profile page:


   $mech->field("signature", headlines());
   $mech->click_button( name=>"submit");

And that's it. Here is the entire script:


use strict;
use WWW::Mechanize;
use LWP::Simple;

my $mech = WWW::Mechanize->new();

sub headlines {
   my $source = get("");
   $source =~ /<item>.*?<title>(.[^<]*?)<\/title>.*?<link>([^<]*?)<\/link>.*?{3}/si;
   return "Now on slashdot:\n[url=".$2."]".$1."[/url]\n[url=".$4."]".$3."[/url]\n[url=".$6."]".$5."[/url]";

sub changesig {
   $mech->field("username", "Monkey");
   $mech->field("password", "Bananas");
   $mech->click_button( name=> "login" );
   $mech->field("signature", headlines());
   $mech->click_button( name=>"submit");


Of course there is some room for improvement. Instead of using a regular expression to get the headlines from the feed, it might be better to use a module which provides a parser for XML or RSS. Some error checking might also be useful. Finally it would be nice to have the script keep the cookie after login, and only have it login again when it turns out the cookies has been invalidated by the server. I leave this as excercises for the reader. Smile
--> All blog posts (13)

© 2005-2011 Frihost, forums powered by phpBB.