Bytes for lunch

Visions of a web developer about software creations

JSAutoCaption: a simple JQuery plugin to automatically show alt and title image attributes

leave a comment »

Some days ago, I’ve been talking to a friend of mine when he gave me a nice idea. He was looking for a jQuery plugin to automatically extract alt and title attributes from an IMG tag and display them under the image.

Wow, such a funny task!

So I did it. It’s simple, and it plays right!

Here’s a couple of screenshots

JSAutoCaption-in-action

The text under the image has been automatically extracted from alt and title attributes of your image.

JSAutoCaption-in-action-html

HTML code

Like it? You can get it!

I’m so happy when I give even a little contribute to the open source community.

I release this plugin under the terms of the MIT License. So have fun.

Source code and live example available here, at the great JSFiddle.

Written by bytesforlunch

February 21, 2013 at 6:29 pm

Finest Tools: introducing AppleScript

leave a comment »

I bought my first Apple computer ten months ago, and a day doesn’t pass without discovering new exciting features of my Macintosh.

A few weeks ago I wrote a post about HyperCard, a great piece of software born from Bill Atkinson, Dan Winkler and Apple.
A few days after, I happily discovered that something similar already existed in my Mac, under a different name: AppleScript. In this post I’m gonna show you how to accomplish basic tasks with it.

Introducing AppleScript

ApplesScript is used to automate actions of the Macintosh operating system. You can script commands to run applications, open documents, browse the web, copy files, store informations, etc. Furthermore, AppleScript is perfectly suitable for database applications, searching and organizing data. One of the coolest things in AppleScript is it can be programmed in plain english, and best of all, it’s a built-in software that comes with your Macintosh.

How it works

A set of instructions is called “Script”. An interpreter executes the commands to interact with the applications and the system. These commands are written in AppleScript, an english-like computer language that contains verbs, nouns, adjectives, articles and other English elements we use everyday.

A script is created in AppleScript Editor, a free tool included wih the platform. It’s extremely simple to use, with a clear toolbar.

An important point to remember is that AppleScript considers everything an object, with properties that can be changed to model the behavior of your script.

Make your computer talk

Let’s try to create our first script. First, launch the AppleScript editor. A window like that one shown in figure will appear.

Now, write this command

SAY “Hello”

and press Run. Nice! Your computer talks.

Now let’s do something useful. Write this:

tell application “Finder” to open home

and press Run.

A window displaying your Home folder content will appear.

Now let’s see how to play with Google Chrome. We’re gonna open it and load a website.

tell application “Google Chrome”
    activate
    set theUrl to “http://www.pixcone.com”
end tell

Pushing a tool to the max

Even if we just scratched  the surface of AppleScript, I hope to stimulate users to be serious about pushing their expensive computer to the max.

As a practical example, I use AppleScript to automate the process of starting tools for coding. It’s a great accomplishment to automate the tedious process of opening your IDE, your browser with some preferred urls, a couple of Finder windows and a MAMP server.

Here my very simple script for starting coding tools:

tell application “TextMate”

   activate

   open “/Applications/MAMP/htdocs”

end tell

tell application “Cyberduck”

   activate

end tell

tell application “MAMP”

   activate

end tell

tell application “Google Chrome”

   make new window

   set URL of active tab of window 1 tohttp://localhost:8888/pixcone/”

   set myTab to make new tab at end of tabs of window 1

   set URL of myTab tohttp://www.pixcone.com”

   set musTab to make new tab at end of tabs of window 1

   set URL of musTab tohttp://www.stereomood.com”

end tell

say “Happy coding”

Enjoy Applescript!

Written by bytesforlunch

December 5, 2012 at 12:07 am

Posted in AppleScript

Parsing JSON string in javascript

leave a comment »

All we know how JSON is good at describing objects. It is compact and clear, and brings a lot of benefits when used as a transport vehicle for informations between applications. When I say JSON my mind immediately think about REST. Yes, such a great DUO: REST+JSON.

That being said, using JSON requires for an application to parse JSON strings.
In this post I’m gonna talk about parsing strings to JSON objects.

Option 1: Eval() (is not always the evil)

When parsing json strings, a common choice is using the javascript function Eval().

A lot of programmers consider using the  function eval a bad practice. All around the Internet, it seems there’s a psychosis about it.
I argue that this is not always the truth. Actually, it depends on the context. As everything in software, you must know it before use it.

Eval is a javascript function that evaluates an expression. It can be used to run a piece of code, or to evaluate an expression.
Calling Eval to parse a json string invokes the compiler, and the result is a native javascript object that is naturally understood by javascript.
Yes, Eval has some points to be taken in consideration.

First, there’s a security issue. Invoking Eval on a piece of code means to execute it. So be sure that code is trusted. Consider where that json is coming from, and do the math.

var myObject = eval('(' + myJSONtext + ')');

I think  eval() is a good choice to parse json string, especially when you trust the origin of the string.

Option 2: JSON.parse

This is the most suggested way to parse json strings.
Please note that JSON.parse uses the eval() at its core, but it does some control on the input, so it’s considered better.
JSON.parse is supported by the majority of today’s browser, but if you need to provide a backward compatibility, you can download the famous Douglas Crockfors’s library.

Option 3: JQuery

JQuery has a solution for almost everything in the javascript world. Check this:

jQuery.parseJSON(json-string);

Do you wonder if JQuery uses eval() internally?

Well, we just need to see the JQuery code.


parseJSON: function( data ) {
if ( !data || typeof data !== "string") {
return null;
}

// Make sure leading/trailing whitespace is removed (IE can’t handle it)
data = jQuery.trim( data );

// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}

// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, “@” )
.replace( rvalidtokens, “]” )
.replace( rvalidbraces, “”)) ) {

return ( new Function( “return ” + data ) )();

}
jQuery.error( “Invalid JSON: ” + data );
}

(taken from JQuery.com)

Ok, as we can see, JQuery used JSON.parse except for old browsers, where it uses this construct:

return (new Function(‘return ‘ + data))();

Using new Function makes the code operating only on its local variables, giving it a more secure context.

Conclusion

JSON support is officially part of JavaScript since Decembre 2009, when ECMAScript Programming
Language Standard – Fifth Edition was adopted by the ECMA General Assembly.

Even if we would like our users to be using modern browser, sometimes we need to cope with backward compatibility. For most cases, json2.js is the best choice.

Written by bytesforlunch

November 15, 2012 at 9:12 pm

Posted in Javascript, JQuery

A taste of Semantic Web

with one comment

For sure, Semantic Web is one of the most heard word on the Internet.
But how many people can really use it? Due to its steep learning curve and its manifold nature, penetration of semantic techniques in web development is still poor.
In this post I’m gonna show you how to implement simple Semantic techniques in a web page.

Why the Semantic Web?

Everyday, the most of information we get from the web comes by algorithms that mainly look at text. This is because the majority of web pages are made up by human-readable words.

The base principle of the semantic web is to provide metadata for giving text a meaning. Several techniques are on the table, the one we’re gonna see is Microdata.

Microdata consists of annotating the DOM of a web page with  scoped key/value pairs, that give meta-informations about the thing they’re related to.

Let’s see an example.

Some days ago I’ve published a web application (PixCone) and I wanted to add information about myself using semantic definitions.

As a side note, please keep in account that on summer 2011 the big three (Google, Yahoo and Bing) launched an initiative to endorse Schemas and Microdata as key technologies for their search algorithms. You do the math…

A simple example: the author section

Before to dig into the example, we should spend a few words on defining the concept of Schema.

Annotating html tags with microdata means to add new attributes to describe the entity. Most of times these attributes already exist, and must be conformed to a particular Schema. A schema is a definition of an object. See here to read more.

In the next piece of code we’re going to add semantic data to the author section of a page. This is a relevant chunk of informations because tells the world who created what.

Let’s give a look at the code

<div>
<div itemscope itemtype=”http://schema.org/Person”&gt;
<span itemprop=”name”>Francesco Ricceri</span><br>
<span itemprop=”title”>Software Developer</span><br>
<span itemprop=”worksFor”>Pix Cone</span>
</div>
</div>

Job completed! We have defined a few properties of a “Person” schema.

The line n.2 declares the schema which the object belongs to. In this case we’re giving informations about the author, which is a Person.
Person is defined as a schema. More info here.

Lines 3-4-5 are pretty easy to understand.

With a few lines of code, we made this section to be understood by machines. Great! This is your first step in the world of semantic web.

Microdata in action

One of the Chrome plugins I find absolutely useful is Semantic Inspector. It allows to find semantic data in a web page.

Here’s what I see in the Pixcone homepage.

PixCone-Using-Semantic-Inspector-plugin

By clicking on the Semantic Inspector, we’ll see semantic informations sniffed by the plugin:

pix-cone-with-semantic-data

Linkography

Now some links I consider a good starting point.

Schema.org

Microdata

Written by bytesforlunch

November 6, 2012 at 11:46 pm

Posted in Semantic Web

When computer programmers were heroes – Bill Atkinson and Hypercard

with 5 comments

Bill-Atkinson-demonstrating-Hypercard

Bill Atkinson demonstrating Hypercard in an episode of Computer Chronicles

In this post I’m going to talk about the golden era of computer, when programmers where heroes.

They spent their days crafting great software, giving all their skills and attitudes to the computer science.
They simply loved what they were doing, just for the sake of building quality and innovative products.

Most of them, are still loving computer programming today and making great stuff.

Today, what are we doing as computer people? We have huge computational power, great machines, all the documentation we need, but we don’t use it at all.

Furthermore, it seems  the majority of software strategies are driven only by money and profit, despite of programmers creativity and software quality.

Go back to the 80′s: introducing HyperCard

Wow, such a lot of time has passed from  1985, when Bill Atkinson started the development of HyperCard. That time, HyperCard was a disruptive innovation. It was a software built for the Apple Macintosh and the Apple II GS.

The idea at the heart of HyperCard was simple and  clever: a stack of virtual cards. Each card contains clickable objects, hyperlink, text and images, buttons, table and charts. By clicking on an object, user could perform an action, such as execute a piece of code or go to another card. This was the principle behind the hypertext.

The result was a cool piece of software, where users could navigate from a card to another to extract information, find cards that provide calculations, or that show images and texts. Common applications of HyperCard were  database oriented systems with an high level of interaction.

Why the name HyperCard? The name came from the rolodex, a popular object where a stack of circular cards hold hand-written information.

One of the crucial features of HyperCard was the script section, where a user could write instructions to the software. Instructions were in english, making the task of query the system very natural and easy.

I saw a video presentation of HyperCard (link is provided below) where Bill Atkinson queries HyperCard by writing “find horse” and the system returns the first card with an horse on top of it.
I got impressed by the high level of User-Experience quality that emerges  by that video. For example, once you find a card, if the user clicks on the top of the card then the system presents the next card, and so on.

Simple, clever, amazing.

Since HyperCard was a programmable system, a huge community of developers emerged, bringing to light tons of fresh software for various fields: accounting, estimation, retail and sales package, even videogames.

The language at the core of HyperCard was HyperTalk, created by Dan Winkler, and it was object oriented and easily extensible. Hypertalk was thought for non professional, and its easy-to-use nature was the reason of its big success. Thousands of stacks where written, originating a class of software known as “Stackware”.

A little bit of history

The work started in 1985, with the first release in August 1987. Apple managed to time the release of HyperCard to coincide with the MacWorld Conference in Boston, Massachusetts, and it was a great success.

Between 1989 and 2000, a couple of new versions were made (HyperCard 2.0 and 3.0), then the project was stopped.
Apple ceased selling HyperCard on March 2004.

A lesson of quality and creativity for today programmers and entrepreneurs

The story of HyperCard is one of passion and heart, that brought more than a great software: a whole ecosystem of software, where other people could work on. It’s a story of success from a brand that made the excellence as its core flagship, despite of costs.

In the official biography of Steve Jobs, I read that one day he decided to rewrite the heart of their operating system. Programmers told him: “Hey Steve, this is simply unrealizable. It’s impossible, there’s high risk of errors, it’ll take too much time to get done.”

Then, Steve simply said the guys. “Ok, I understand. We must do it”.

And today we have Apple OS X.

References

To see the complete tv episode of Computer Chronicles, where HyperCard was presented (I really suggest you to see, it’s a piece of computer history!):

Computer Chronicles tv episode, HyperCard (on archive.org)

Wikipedia article on HyperCard

Wikipedia article on HyperTalk

Who is Bill Atkinson?

Written by bytesforlunch

October 23, 2012 at 11:03 pm

Dottor REST and Mister SOAP: two faces of the same medal

leave a comment »

Having a well knowledge of what REST and SOAP are, could be not easy. The Internet is full of “REST vs SOAP” post, but in my opinion, they aren’t really useful to point out the key concepts behind them. While REST is an architecture, SOAP is a format specification.  So it could not make sense to make a comparison.
In this post I’m going to outline the main concepts of the two worlds.

These days I’m facing the need of architecting a system where mobile devices interact with an application acting as a server.

This is a pretty challenge that inevitably brings me to consider the oxygen of the web: the http protocol, and the ways I can use it profitably, at a reasonable effort.
After years of fighting with old school web-services, and after I found myself fighting with them, I decided to consider a pure REST oriented application.

I’ve been asked several times about the differences between REST and SOAP, and why they should choose one over the other.

Well, while there’s no a one-size-fits-it-all recipe, in this post I will try to outline the differences between the two.

Giving REST and SOAP a simple definition

REST (Representational State Transfer) is a paradigm that consist of exposing an API or services on the web, via pure http calls reachable via a known URI.

SOAP (Simple Object Access Protocol) is the specification of a protocol, with a complete definition of how data must be formatted.

While they both use http as transport protocol, there are some notable differences in the way they work.

Example of a REST call:

http://bytesforlunch/getArticles/2012

Example of using a SOAP web service

…is more complicated. You must send to the server a piece of XML that respects the given specification, and you’ll get an XML response.

Considerations

In my opinion REST should be considered as a first choice communication paradigm for modern applications to talk each other over http.
REST it’s simple to implement, and it’s universal. Every language that allows to perform http call, is REST compliant.

On the other side, SOAP forces you to know exactly the specification of the service, and imposes the use of XML. Furthermore, REST is easier to understand,  and permits any type of data, while SOAP uses only XML (remember the big advantages of JSON over XML, in terms of lightness). We should say that today, a lot of applications are written in javascript, and using JSON is an invaluable advantage.

Well, it seems I would to talk only about REST. It really is, but, sometimes, adopting SOAP is still a good choice. SOAP protocol gives a better security, as it supports SSL and WS-Security.
Further, the intrinsic level of details of data specification  (wsdl), makes it hard to break the security of transmissions: this adds another level of safety.  Another thing to say about security is the use of ACID transactions, fully supported in SOAP.

Final thoughts

In this post I tried to provide a quick introduction to the concepts of REST and SOAP.
Hope this can be helpul, anyway, due to the vastness of the topic, you should consider to do a little drill down.
For those whom are seeing REST and SOAP for the first time, I propose Wikipedia as a good starting point:

REST, on Wikipedia

SOAP, on Wikipedia

Has this post been helpful? You readers are invited to share comments and thoughts here, @ Bytes for Lunch.

Written by bytesforlunch

July 24, 2012 at 10:33 pm

Posted in Architecture

Tagged with ,

Which runs faster: C# vs C++ – the eternal dispute

with 2 comments

First, I’m convinced that if used correctly, both language are enough fast to accomplish a wide range of common tasks.

In my experience as a software developer, I’ve heard so many times developers talking about which is faster between C# and C++. And, I must say, I always heard a lot of misunderstandings and unproven statements.

Even if C++ is faster in many cases, saying it is “always faster than C#” is an incomplete view of the picture.

A lesson from experience

In this post I will propose my point of view, in an informal way. I will focus on what I’ve learnt (and I still learn) from my daily programming tasks.

First, I’m convinced that if used correctly, both language are enough fast to accomplish a wide range of common tasks.

Second, we must take in consideration that the dot.net framework brings several benefits, that pure C++ doesn’t offer. For example, bytecode optimization. The Framework does it for us. The generated IL code is largely optimized, according to the system where it will run. On the other hand, reaching a certain grade of compiled code optimization in pure C++ would mean adapt the code to different cpu and architecture. Doing this in C++ is an extra effort, and makes your code prone to bugs as well as hard to mantain.
I have seen cases where C# run faster than C++, causing suprise in people. In many cases the reason was pretty clear: bytecode optimization brought by the dot.net framework (this is particularly true for the latest versions of CLR runtime, that is more mature than years ago).

Does one-o-one comparison make sense?

Considering the differences between JIT and static compilation, I have doubts about making a speed comparison between both world. Does it make sense?

In many cases, I found that when a software is slow, the programming language isn’t even the bottleneck. I’ve always solved performance issues working at code-architecture level.

So, a good programmer should be enough to have a fast software.

Fundamental is choosing the right tool, and having the required expertise

Despite of the eternal dispute on which language performs better, we should instead set the focus on choosing the right tools to accomplish our needs and using it well. Second, take care about  the architecture design.

Nowadays, a software developer must code at high speed with minimal effort. So take care about choosing a tool that makes you faster. Here, C#, with the richness of the underlying framework, is undoubtedly the winner.

At this point, talking about advantages of C# is quite trivial… but a little reminder helps:

1) First, thanks to its Jit nature, C# is cross platform. Mono is the living proof of this.

2) The richness of dot.net framework allows developers to do everything, at the minimum effort.

3) Automatic memory management, aka garbage collection, frees the developer from a lot oh headaches with memory.

Need more?

Key concepts summary

  1. C# is compiled twice. First time when the compiler produces the IL (intermediate language), second when is translated to machine code. In this second passage, the dot.net framework does optimizations depending on the architecture of CPU (so for example, the generated machine code can get benefits of cpu hardware  as number of cores, instructions set, etc.C++ is compiled once. Often, compilers adopt the Lowest Common Denominator principle. This means the machine code is balanced for the lowest architecture available (poor optimized executable)
  2. Extra-safety doesn’t come for free. Since the dot.net framework  executes code in sand-box mode, that makes it able to automatically recover memory, this undoubtedly has a payload.
  3. Design is the most important factor.
    A well designed software doesn’t suffer of performance issues.
  4. C++ is still a first class choice when your application has a lot of  critical workload (see math operations, simulations, etc.) or when dealing with hardware (programming drivers, microprocessors, etc.)

I would like to end my post with the metaphore of the plane and the car.

Which is faster to cover a short distance (let’s say 10 Km): a Boeing 747 or a Ferrari? Keep in consideration that the plane must do the take-off and landing.

But which is faster, over a distance of 500 km?

Written by bytesforlunch

July 2, 2012 at 9:54 pm

Posted in Development

Follow

Get every new post delivered to your Inbox.