Amazon.com Widgets October 2012

Fun Code of the Week #6: Primality Checking

By Nick at October 27, 2012 09:02
Filed Under: Delphi, Fun Code

 

I decided to give KhanAcademy a spin, and watched this set of videos:

Level 1: Primality Test

And that let to me writing this code:

function IsPrime(const x: integer): Boolean;
var
  i: integer;
begin
  i := 2;
  repeat
    if X mod i = 0 then
    begin
      Result := False;
      Exit;
    end;
    Inc(i);
  until i > Sqrt(x);
  Result := True;
end;

I know that this can be optimized (which I'll do if I end up watching the next video :-) ), but I don't often write really geeky code like this, so I thought I'd post it so you all can write lots of comments like you always do when I post code. ;-)

UPDATE #1: There was a bug if you passed in a negative number. 

function IsPrime(const x: integer): Boolean;
var
  i: integer;
begin
  if (x <= 2) then
  begin
    Result := False;
    Exit;
  end;
  i := 3;
  repeat
    if X mod i = 0 then
    begin
      Result := False;
      Exit;
    end;
    Inc(i);
  until i > Sqrt(x);
  Result := True;
end;

UPDATE #2:  Took the Sqrt() call out of the loop.

function IsPrime(const x: integer): Boolean;
var
  i: integer;
  Wall: double;
begin
  if (x <= 2) then
  begin
    Result := False;
    Exit;
  end;
  i := 3;
  Wall := Sqrt(x);
  repeat
    if X mod i = 0 then
    begin
      Result := False;
      Exit;
    end;
    Inc(i);
  until i > Wall;
  Result := True;
end;

UPDATE #3:   The learning and optimizing continues!  I updated the code based on more suggestions, but the special case of 2 is irritating me.  I confess I thought a while (I’m not cheating by looking up implementations on Google…) and so I came up with something of a hack.  Also, just for Julian, all the x’s are lowercase now.  Smile with tongue out  Also, I learned/re-learned that 1 is not a prime either, by definition.  Interesting.  Any more optimizations out there?  Is there a “correct” way to handle 2?  The end goal here is to have a really nice, really efficient IsPrime function. 

function IsPrime(const x: integer): Boolean;
var
  i: integer;
  Wall: integer;
begin
  if x = 2 then
  begin
    Result := True;
    Exit;
  end;
  i := 3;
  Result := not ((x < i) or (x mod 2 = 0));
  if not Result then Exit;
  Wall := Trunc(Sqrt(x));
  repeat
    Result := not (X mod i = 0);
    if not Result then Exit;
    Inc(i, 2);
  until i > Wall;
  Result := True;
end;

Flotsam and Jetsam #68

By Nick at October 27, 2012 04:16
Filed Under: Flotsam and Jetsam, Delphi
  • Is it me, or does it seem like there are more Delphi conferences happening in Europe than there has been in the past?
  • I totally get the notion of being on hold to wait for customer service.  I usually put the call on speaker phone and wait that way.  They usually play music and go about my business.  What bugs me, though, is when they break in every ten seconds to say “All our representatives are currently assisting other customers.  Please continue to hold.”  That’s all well and good, but every time they do it, I have to sort of stop what I’m doing and see if it is recording or the real person coming on.  Irritating.
  • Apparently, my man Frank Borland has a blog
  • I was happy to find this interesting, insightful, and marvelously written answer by Danny Thorpe to the question “Why did Borland fail?”.
  • I’m feeling a bit out of it, as I just discovered and joined Quora – and gave my first answer.  I’d never really heard of it before, but found out that many of you folks are already there using it.  Now to think of a question to ask…..
  • I made a few more changes to the website – easily enabled by Less.  I put slightly rounded corners on the little side boxes, as well as a bit of a shadow.  Both are easily adjustable thanks to Less. 
  • I also added a new advertiser – Lake Quincy Media.  They specialize in Developer Tools, so hopefully what you see should be more of interest.

Fun Code of the Week #5

By Nick at October 24, 2012 12:39
Filed Under: Delphi, Fun Code

What is your FizzBuzz solution?  Any comments on mine?

If this is an interview question, what are you looking for?

Here is FizzBuzz in over 150 languages.

For the record, I spent no more than three minutes to write this. :-)

program FizzBuzz;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

var
  i: integer;
  WriteNumber: Boolean;

begin
  try
    for i := 1 to 100 do
    begin
      WriteNumber := True;
      if i mod 3 = 0  then
      begin
        Write('Fizz');
        WriteNumber := False;
      end;
      if i mod 5 = 0 then
      begin
        Write('Buzz');
        WriteNumber := False;
      end;
      if WriteNumber then
      begin
        Write(i);
      end;
      WriteLn;
    end;
    Readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

Less is More for your CSS

By Nick at October 24, 2012 10:34
Filed Under: Delphi, Software Development, Tech Stuff

As you may have noticed, I made a few changes to the website here at good ol’ nickhodges.com.  I added a column of boxes on the left, with the idea being to make stuff more accessible without so much scrolling.  And, well, yeah, okay, I’ve used that space to add a few more advertisements.

And while I was at it, I cleaned up a few things with the layout and the CSS.  It’s what I did with the CSS that I’d like to talk about today.

The main thing that I did was to start using the CSS pre-processor called Less.  Less allows you to do a lot of things “right” when writing CSS.  The first thing you notice when you start writing CSS is that it is a horrible violator of the DRY principle – Don’t Repeat Yourself – and Less solves a bunch of those problems.  It’s hard to write “clean CSS code”.  Less can help.  Less allows you to:

  • Create a *.less file that is then processed into your CSS file.  You can do this manually with a command line preprocessor, or you can do it on the client-side with Javascript.  Below, I’ll discuss how I pre-processed my *.less file automatically
  • Declare variables for colors and other things.  Say you have a color that you use in a number of different places.  You can declare

         @WidgetBorderColor: green;

    and then everywhere you had to type green, you could put @WidgetBorderColor instead.  Then, if you want to change from green to red, you only have to do it in one place.  That is really nice. 
  • You can also declare mixins – or chunks of CSS code that are commonly used.  For instance, if you have a bunch of places that use  

         {padding: 0px; margin: 0px}

    then you can declare

         .p0m0 {padding: 0px; margin: 0px}

    and use that as an “alias” in your *.less files

       body {
        .m0p0;
        font-family: Verdana;
        font-size: 13px;
        color: @Black;
        background: @White ;
       }

  • You can also use parameters to pass in to your mixins if you want, an other more complex constructs, though none of it is terribly difficult.   The Less page has all the documentation in one place.  The two features above were what I used in an effort not to repeat myself in my CSS.

Once you have your less file set up, you can process it via the command line, or using a GUI compiler tool.  Because Less is written in Javascript, you can use node.js to run it on your local machine.  To do that, you can download the Node Package Manager and then install  Less by simply executing

npm install less

npm is kind of interesting – it’s an online registry, so when you issue the above command, it goes out to a public registry and finds the Less package and simply installs it – there’s nothing for you to install. I guess it is much like Nuget in that regard. 

After that, you can then execute the lessc compiler. 

So the workflow at this point is:

    1. Write CSS and Less code in a *.less file
    2. Compile the *.less file into a *.css file.  (For instance, I use a batch file with:  c:\Code\node_modules\.bin\lessc C:\NickHodges\themes\nick\style.less c:\NickHodges\themes\nick\style.css
    3. Deploy the new CSS file with my site
    4. Repeat as necessary

Step 2 is kind of a bother, though.  You have to shell out to the command line to do the compile.  Who wants to do that if you don’t have to?

Well, I sure don’t.  So I found a cool tool called WinLess which does a nice thing – it automatically compiles your Less code into CSS every time you save your *.less file.

image

It works great – you just point it to your *.less files, and whenever you save changes, it automatically compiles the Less code down to CSS.  That way, your CSS is always up to date, and you just have to worry about your Less code.  Maintaining the CSS file is totally painless.  So now the workflow is:

  1. Update your *.less file as desired
  2. Save
  3. Deploy your *.css file.

That’s a lot easier, eh?

Now what I really want is a tool to find patterns in your CSS and automatically turn them into Less entries.  That would rock.

CSS is powerful and cool, and you can’t create a well-designed website without it.  But as a language, it’s not really very “best coding practices friendly”.  Less makes it much more so.  If you set things up correctly, you can do your styling in Less and forget about CSS altogether.

What do you guys do with your CSS?

Flotsam and Jetsam #67

By Nick at October 20, 2012 00:12
Filed Under: Flotsam and Jetsam, Delphi, Software Development
  • For those of you who still cling to the archaic notion that “Delphi Marketing Sucks”, you should know that I can’t go anywhere on the internet without seeing an add for RAD Studio XE3.  One of the things I appreciate about Google Adsense is that it knows the kinds of ads I want to see and what I am interested.  And it has very astutely determined that I like Delphi.  And Embarcadero marketing has very astutely provided ads to let me know that RAD Studio XE3 exists and that I can buy it.   That’s what marketing is all about.
  • How have I managed to miss this page of cool stuff all these years --  Delphi Inspiration? I’m particularly intrigued by the Delphi pre-processor.
  • Cool Thing Built With Delphi of the Week: dbConstructor
  • A bunch of you have ordered Delphi XE3 from me. I am very grateful. Thanks.  It's a great release -- I'm really enjoying using all the cool new language and RTL features, and I think you should too.

My Take on TypeScript

By Nick at October 17, 2012 12:43
Filed Under: Delphi, Tech Stuff, Software Development

Microsoft has been keeping the renowned Anders Hjelsberg busy on a new language called TypeScript.  Typescript is an open-source project (using the Apache 2.0 license) that allows you to write a super-set of Javascript that allows for a stronger typing system.  You can watch Anders’ original launch presentation

I’ve said a million times that I’ve said a million times that Javascript is the new Assembler – that Javascript will become the thing that everyone compiles higher level code into.  You’ll write your web apps in a higher order language, and then compile them to Javascript for execution in the browser. 

I refuse to believe that any rational person actually likes to write Javascript, and as it is designed currently, it really isn’t a language for developing the kind of large-scale applications that people seem to be wanting to use it for.  In the deep, dark past, Assembler used to be all there was, and we created higher order solutions that compiled to assembler.  And in the same way, for a while, Javascript was all there is for the browser.  Now, however, we are beginning to see higher order languages being brought to bear to produce Javascript for us. 

If Javascript is the “new Assembler”, then the Browser becomes the “new operating system”.  The cool thing about that is that the “new OS” is ubiquitous.  Just about every computer in the world – computers running Windows, OS X, Linux, Unix, whatever – has a browser that runs Javascript.  That means your application can run on any computer.  That’s a very compelling idea.

You can actually do that today with Delphi using a very cool tool called Smart Mobile Studio.  There is also the Elevate Web Builder tool from Elevate Software.  Both have the same idea – leverage the power of Delphi to produce Javascript-based applications.  Pretty cool, really.

Anders talked to Scott Hanselman about Microsoft’s offering in the “Language to compile down to Javascript” arena in the latest episode of Hanselminutes.  Anders is always a good interview – I love a guy who thinks and speaks as clearly as he does.  (That’s why I always loved a Danny Thorpe presentation.  Danny is pretty quiet and mellow, but his talks were always so clear and well organized – every single word he said was worth listening to – that they were always excellent and enormously educational.  Anders is the same way….) He does a great job discussing the notion behind TypeScript.

Here are some of my thoughts on what Anders said and on TypeScript in general.

  • TypeScript seems to exist for two reasons – to make Javascript “tool-able” and scalable. 
    • First, the type annotations, classes, modules, and other enhancements exist to allow Visual Studio and other IDEs to do things like Code Completion (the RAD Studio term that Anders used in the podcast instead of Intellisense – I loved that.  Smile  ), refactoring, and other language-based features that modern IDE’s do.  Javascript doesn’t provide enough information to let development tools do all the things that we expect, but TypeScript does. 
    • Second, TypeScript is also a way to make Javascript scale. By providing the notion of typed classes and modules, you can create larger, well-organized TypeScript applications which then compile to Javascript.   TypeScript is a language ready to do the heavy lifting that Javascript cannot.
  • Since TypeScript is a super-set of Javascript, it follows that pure Javascript is valid TypeScript.  Anders points out that you can use your existing Javascript as is inside of TypeScript.  The idea, though, is that TypeScript becomes the language you’d use instead of Javascript because of all the tooling support, and because it can be used to build applications via modules (units, for you Delphi folks).    Typescript doesn’t have any runtime or virtual machine – it literally just compiles to Javascript. 
  • You can create an external declaration file to define the types in your *.js file, so that means that existing Javascript libraries like Node.js and jQuery.js can be “typed” and thus used in the TypeScript environment.  I think that is a pretty cool idea – and I’m sure that Microsoft will be delighted if the community follows their lead and “converts” the existing popular libraries.
  • Anders also points out that TypeScript puts a “dial” on the typing level of your code.  Pure Dynamic advocates can leave everything untyped, and the strong-typing zealots can type everything if they want, and the folks who want to type some things and not type others can do that if they want.  That’s a very interesting notion – a language with a variable level of type-safety.

Now one thing to note is that tools like Smart Mobile Studio and Elevate Web Builder offer pretty much all these features as well.  There isn’t any reason that Embarcadero couldn’t make Javascript be something that is output by the Delphi compiler.  Heck, there is even a project out there to get LLVM to produce Javascript.  TypeScript would integrate well into HTML5 Builder. Whatever higher-end language you want to use, it seems pretty clear to me that Javascript will be the thing our compilers will be producing in the not-to-distant future.

Are you going to give TypeScript a look, or are you more interested in the Delphi-to-Javascript solutions?  I’ll probably check out both.  Either way I have to use a different IDE, so I’m guessing I’ll lean towards the Delphi-based solutions.  Plus, I frickin’ hate curly braces.  Winking smile

What do you guys think?

Frank is Back

By Nick at October 12, 2012 09:43
Filed Under: Delphi

This is posted without comment, because I really don’t know what to think or say.

Flotsam and Jetsam #66

By Nick at October 11, 2012 23:42
Filed Under: Flotsam and Jetsam
  • I’ve talked about my Ooma.  I love it – I has cut my phone bill from $50 a month to $5 a month.  It works great, and I get unlimited calling in the US, and $0.01 a minute to Canada.  (That’s important to me, as my wife is from Saskatoon and calls her family there.) In fact, the phone bill is $0, and the $5 is just taxes.  It is paying for itself in four months.  And right now, you can save $40 on the unit, meaning it will pay for itself even faster.  And if you buy from this link, I get a commission.  It’s a win for everyone. 
  • Blog Sightings:   There’s been a bunch of activity on the Embarcadero Blog site:
  • The Embarcadero MVP program is “official” now in that there is a web page and everything.  I’m honored to be included among the list of amazing, skilled, and knowledgeable folks.  Know someone who should be on the list?  You can nominate them
  • One of the cool new features in Delphi Xe3 is helpers for intrinsic types.  The most noticeable one is TStringHelper which lets you do things like MyStringVar.Length and MyStringVar.ToUpper.  However, I find it curious that they didn’t include a “standard” helper for integers.  I supposed it is because there are so many different integer types, but I seems that they could solve that through some form of inheritance, right?  I don’t know.  I just know that I’d like to be able to go MyIntegerVar.ToStringSmile
  • Here’s a blog post after my own heart: Why you should use Delphi’s Unit Testing – DUNIT.  In fact, there is a bunch of great stuff on the India Delphi User Group blog
  • Is it just me, or is it weird that Send To|Clipboard as Name isn’t a default behavior for a file in Windows Explorer?  I must use that twenty times a day.  I have to add a plug-in to have that feature. 

My Book

A Pithy Quote for You

"When buying and selling are controlled by legislation, the first things to be bought and sold are legislators."    –  P. J. O'Rourke

Amazon Gift Cards

General Disclaimer

The views I express here are entirely my own and not necessarily those of any other rational person or organization.  However, I strongly recommend that you agree with pretty much everything I say because, well, I'm right.  Most of the time. Except when I'm not, in which case, you shouldn't agree with me.