Author Archives: admin

How to store result from $http into a variable in angularJS

Lately on I came across to several questions regarding the same argument: “How can I cache remote request”, “how to share information between controllers”, “how to avoid several $http calls”. So I decided to create a small project starting from angular seed ( to show a possible solution.

The idea is to use a service to store the fetched data and to share it between controllers avoiding several calls during the initial request. For this purpose we need two separate view (view1 and view 2), two separate controllers, a main app.js for the application configuration and a service file to create our caching service (not mentioning common Angularjs files).

App directory structure:


App.js is very simple and just bootstrapping the application with the dependencies: ngRoute for the routing the the view’s modules. It defines also the standard view to open in case no route is defined.

   1:  angular.module('myApp', [
   2:          'ngRoute',
   3:          'myApp.view1',
   4:          'myApp.view2'
   5:      ])
   7:      .config(['$routeProvider', function ($routeProvider) {
   8:          $routeProvider.otherwise({redirectTo: '/view1'});
   9:      }])

Views are also very simple, basically just injecting the service and prompting the variable value in the html partial.


   1:  angular.module('myApp.view1', ['ngRoute'])
   3:      .config(['$routeProvider', function ($routeProvider) {
   4:          $routeProvider.when('/view1', {
   5:              templateUrl: 'view1/view1.html',
   6:              controller: 'View1Ctrl',
   7:              controllerAs: 'vc'
   8:          });
   9:      }])
  11:      .controller('View1Ctrl', function (userService) {
  12:          var vm = this;
  13:          userService.getUserInfo().then(function (result) {
  14:     = result
  15:          }, function (err) {
  16:     = err
  17:          });
  18:      });


   1:  <p>This is the partial for view 1!</p>
   3:  <span>{{}}</span>

And the core of the project: the userService. The idea is to use service variables to store the fetched result (cachedUser) and to avoid additional call during the request (promise).

Basically after the first call the promise variable is set and avoids any further remote requests, if the cachedUser variable is not set, we will return the promise, otherwise via angular $q defer service we deliver the promise containing the cached value. In every case we are returning a promise avoiding any data type problem in the controller.

   1:  'use strict';
   3:  angular
   4:      .module('myApp')
   5:      .factory("userService", userService);
   7:  userService.$inject = ["$http", "$q", "$log"];
   9:  function userService($http, $q, $log) {
  10:      var deferred = $q.defer();
  11:      var promise = null;
  12:      var cachedUser = null;
  13:      return {
  14:          getUserInfo: function () {
  15:              if (promise) {
  16:                  $"cached value: " + cachedUser);
  17:                  deferred.resolve(cachedUser);
  18:                  return (cachedUser) ? deferred.promise : promise;
  19:              }
  20:              else {
  21:                  $"initial request");
  22:                  promise = $http.get(
                                .then(function (response) {
  23:                      return cachedUser =;
  24:                  });
  25:                  return promise;
  26:              }
  27:          }
  28:      }
  29:  }

The project is public accessible over github at the following url:, gitclone and try it locally.

Feel free to comment and provide your feedback.

Tagged , , ,

Where is the Laughter from?

Today I would like to write a post different from the other I wrote in the past, I would like to do a reflection about the laugh.


Wikipedia says: “Laughter is a physical reaction in humans and some other species of primate, consisting typically of rhythmical, often audible contractions of the diaphragm and other parts of the respiratory system. It is a response to certain external or internal stimuli. …” and also “Laughter is a part of human behavior regulated by the brain, helping humans clarify their intentions in social interaction and providing an emotional context to conversations.”

Why don’t we laugh more? What is the meaning of it? Following Wikipedia description, we are primate and the laugh is an action which is part of our behavior. There is plenty of studies demonstrating that smiling is positive and healthful, why don’t we laugh more then?chimpa

At young ages we are used to enjoy the laughing freely without any control, getting older it became obscene and we are embarrassed to laugh in public, I’m talking about the guffaws that make you cry and not small timid smiles, of course. But at the end the action itself is coming from the past, is part of our origins and belonging to our ancestors. Monkey do laugh, chimpanzee do, also other animals do.

I’ll deepen into this argument because is charming and interesting, if you have any comment drop me an email or a comment, in the meanwhile my suggestion is just: laugh and smile as much as you can, it’s healthy!

Tagged , , ,

Push news to LinkedIn Stream in your behalf

PrintBack in the past I promised a follow up article to explain how to push data to your LinkedIn stream. The time as come and here we go, so before we take off for this journey maybe you would like to create a LinkedIn fake account for your tests, instead of using your official one.

Just go the official page: and follow the usual steps for the account creation, once done continue with the tutorial.

In my case I don’t care too much about flooding my timeline since I get every now and then annoying spam mail and maybe that could be the right time to taste my revenge.

Jokes a part the core of this tutorial is represented by the developers API: Those API permits you to interface your program to LinkedIn account and perform several actions for example, read/write your profile, share news on the social stream, share on your groups and basically communicate and access Job search.

Okay, more or less simple, let’s move ahead and click on the link, you will land in an almost empty page:


Just click on add new application and fill the form. If everything went well it will be prompted the following page:


Hurrah! Well done, that was the toughest part! Please take note (a screenshot) of those information since you will need them later during the hacking session.

Now the funniest part comes, in command line or in you preferred ruby editor create the ruby file, in my case I call it linkedin.rb. To consume the API we will use a gem called (guess what?) linkedin, so copy:

gem "linkedin"

To your gemfile (in the same directory as the linkedin.rb) and run bundle install in the command line. In case you do not have any gemfile just run gem install linkedin and it will install the gem for you.

Back to our code, first of all require the linkedin and json gems:

#!/usr/bin/env ruby
require 'linkedin' # gem install linkedin
require 'json'

Then setup a configuration hash map containing your keys and your tokens:

config = {
    your_consumer_key: '77ntor37ib7qbp',      #api key
    your_consumer_secret: 'HLFdYIBeA9TTglz3',  #secret key
    oauth_user_token: 'eeabc242-ff1c-474a-a6f2-eb519c967d09', #OAuth Token
    oauth_user_secret: '51ba5c4f-92ef-4e0f-bec0-ac0b1e2937c1' #OAuth Secret:

Instantiate and authorize the client:

client =

And now the final step, define the data that you would like to share on your stream:

    "comment"=&gt;"Check out my article about LinkedIn Share API!",
    "content"=&gt;{"title"=&gt;"LinkedIn Developers API consumed via Ruby",
                "description"=&gt;"Programmatically leverage the Share API to maximize engagement on user-generated content on LinkedIn",
    "visibility"=&gt; {"code"=&gt; "anyone"}

Final step, use the client to share the data:


Run the code and you will be able to find the news in you social stream:


As easy as drinking a glass of water, I hope you enjoyed the article, for any question or suggestions feel free to drop my a couple of lines.

I’ve just updated my professional profile on LinkedIn. Connect with me and view my profile.

LinkedIn Profile

Tagged , , , ,

Push to IMGUR and get tiny url with RUby

After a long absence from blogging snippet of code or anything interesting (lately I was kind of busy with work and personal issues to solve), I’d like to share with you something that I created months ago but I hadn’t the time to publish: a ruby code to publish new images to imgur.

As you can find on WikipediaImgur is an online image hosting service founded by Alan Schaaf in 2009 in Athens, Ohio (not Greece as I imagined first by reading it). Imgur describes itself as “the home to the web’s most popular image content, curated in real time by a dedicated community through commenting, voting and sharing. It offers free image hosting to millions of users a day, and a comment-based social community.

So far so good, but how can we interact with it? Imgur exposes APIs to interact with the entire Imgur infrastructure via a standardized programmatic interface. Using Imgur’s API, you can do just about anything you can do on, while using your programming language of choice, in my case Ruby.

Lets move ahead! First of all you need to register to have an account, then navigate to the imgur API and read the documentation. The following step consist in the creation of the API KEY.

Under settings > applications click on create you own


And register you application:


For tests purposes just pick random values, in my case:

Application name: imgTest
Authorization type: OAuth authentication without callback
Description: test

Fill the captcha and submit the form.


Great! Now you have the Client-ID and the token to perform programmatic access to your account.

#!/usr/bin/env ruby
require 'net/http'
require 'net/https'
require 'open-uri'
require 'json'
require 'base64'
def web_client
  http =, API_URI.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE
API_URI = URI.parse('')
    :image =&gt; '3/image',
    :upload =&gt; '/3/upload'
img ="your-image.jpg", "rb") {|io|}
params = {:image =&gt;  Base64.encode64(img),
          :gallery =&gt; "gallery",
          :name =&gt; "name"
request = + ENDPOINTS[:image])
request.add_field('Authorization', API_PUBLIC_KEY)
response = web_client.request(request)
puts JSON.parse(response.body)['data']['link']

The JSON response contains the tiny URL to the uploaded image:

We can improve the code by adding the album and gallery parameters.

In my next post I’ll explain how to automatic post to linkedin accounts using the imgur script and other libraries.

Tagged , ,

Ruby Koala Gem to Interact with Facebook

Today I started playing around with the Koala gem:

Koala is a Facebook library for Ruby, supporting the Graph API (including the batch requests and photo uploads), the REST API, realtime updates, test users, and OAuth validation.

To install the gem just:

gem install koala
Or put it in the Gemfile and use the bundle command ‘bundle install’:
gem "koala", "~> 1.8.0rc1"
Before we can connect to Facebook, we need to create an access token for the authentication, go on the following link:
And create your key with user_groups and user_photos privileges.
Here the code to post to specific groups, substitute the key with the one you got in the previous step:
#!/usr/bin/env ruby
require 'koala'
oauth_access_token = 'xxxxxxxxxxxxxxxxxx'
group_filtering_words = ['gangofruby', 'gangofrubyII']
image_path = 'ruby.jpg' #change to your image path
message = 'Ruby is the most beautiful gem.' # your message
graph =
# getting groups of interest
groups = graph.get_connections("me", "groups").select do |group|
  group_filtering_words.any? do |word|
    group["name"].downcase.include? word
groups.each_with_index { |group,i|
  puts "[#{i+1}/#{groups.size}] Posting to group #{group["name"]}."
  graph.put_picture( image_path, {message: message}, group['id'])
If it is returning an SSL error like:
/lib/ruby/2.0.0/net/http.rb:918:in `connect': SSL_connect returned=1 errno=0 state=SSLv3 
read server certificate B: certificate verify failed (Faraday::SSLError)
Then you need to download the cacert.pem file from 
Save the file to C:\RailsInstaller\cacert.pem and add it to your system as system variable:

Tagged , , ,

Ruby Gravatar Link generator

Just a simple example of Ruby code to generate a gravatar link, substitute the with the desired address and you will get the something like:

In the second use case you can specify the size of the gravatar, the default image in case no gravatar is found and the rating:


#!/usr/bin/env ruby
require 'digest/md5'
require 'uri'
# this is based on gravatar image API
# options :
# size : <integer> size of image
# default: <string> url of image if email not found or:
# * 404
# * mm
# * identicon
# * monsterid
# * wavatar
# * retro
# * blank
# forcedefault: "y" force default image to load
# rating: <string> one of the values : g, pg, r, x
def gravatar email, options={}
  email_md5 = Digest::MD5.hexdigest email
  params_query = URI.encode_www_form(options) unless options.empty?
puts gravatar('')
puts gravatar('',
              size: 200,
              default: '404',
              rating: 'pg'
Tagged , ,

How to install CouchBase

Introduction to Couchbase Server

Couchbase Server is a NoSQL document database for interactive web applications. It has a flexible data model, is easily scalable, provides consistent high performance and is ‘always-on,’ meaning it is can serve application data 24 hours, 7 days a week. Couchbase Server provides the following benefits:

  • Flexible Data Model

    With Couchbase Server, you use JSON documents to represent application objects and the relationships between objects. This document model is flexible enough so that you can change application objects without having to migrate the database schema, or plan for significant application downtime. Even the same type of object in your application can have a different data structures. For instance, you can initially represent a user name as a single document field. You can later structure a user document so that the first name and last name are separate fields in the JSON document without any downtime, and without having to update all user documents in the system.

    The other advantage in a flexible, document-based data model is that it is well suited to representing real-world items and how you want to represent them. JSON documents support nested structures, as well as field representing relationships between items which enable you to realistically represent objects in your application.

  • Easy Scalability

    It is easy to scale your application with Couchbase Server, both within a cluster of servers and between clusters at different data centers. You can add additional instances of Couchbase Server to address additional users and growth in application data without any interruptions or changes in your application code. With one click of a button, you can rapidly grow your cluster of Couchbase Servers to handle additional workload and keep data evenly distributed.

    Couchbase Server provides automatic sharding of data and rebalancing at runtime; this lets you resize your server cluster on demand. Cross-data center replication providing in Couchbase Server 2.0 enables you to move data closer to your user at other data centers.

  • Consistent High Performance

    Couchbase Server is designed for massively concurrent data use and consistent high throughput. It provides consistent sub-millisecond response times which help ensure an enjoyable experience for users of your application. By providing consistent, high data throughput, Couchbase Server enables you to support more users with less servers. The server also automatically spreads workload across all servers to maintain consistent performance and reduce bottlenecks at any given server in a cluster.

  • “Always Online”

    Couchbase Server provides consistent sub-millisecond response times which help ensure an enjoyable experience for users of your application. By providing consistent, high data throughput, Couchbase Server enables you to support more users with less servers. The server also automatically spreads workload across all servers to maintain consistent performance and reduce bottlenecks at any given server in a cluster.

    Features such as cross-data center replication and auto-failover help ensure availability of data during server or datacenter failure.

All of these features of Couchbase Server enable development of web applications where low–latency and high throughput are required by end users. Web applications can quickly access the right information within a Couchbase cluster and developers can rapidly scale up their web applications by adding servers.

Installing and Upgrading

To start using Couchbase Server, you need to follow these steps:

  1. Make sure your machine meets the system requirements. See Preparation.

  2. Install Couchbase Server. See Installing Couchbase Server.

  3. For more information on Upgrading Couchbase Server from a previous version, see Upgrading to Couchbase Server 2.0.x.

  4. Test the installation by connecting and storing some data using the native Memcached protocol. See Testing Couchbase Server.

  5. Setup the new Couchbase Server system by completing the web-based setup instructions. See Initial Server Setup.

Hardware Requirements

The following hardware requirements are recommended for installation:

  • Quad-core for key-value store, 64-bit CPU running at 3GHz

  • Six cores if you use XDCR and views.

  • 16GB RAM (physical)

  • Block-based storage device (hard disk, SSD, EBS, iSCSI). Network filesystems (e.g. CIFS, NFS) are not supported.

A minimum specification machine should have the following characteristics:

  • Dual-core CPU running at 2GHz for key-value store

  • 4GB RAM (physical)

For development and testing purposes a reduced CPU and RAM than the minimum specified can be used. This can be as low as 1GB of free RAM beyond operating system requirements and a single CPU core.

However, you should not use a configuration lower than that specified above in production. Performance on machines lower than the minimum specification will be significantly lower and should not be used as an indication of the performance on a production machine.

View performance on machines with less than 2 CPU cores will be significantly reduced.

You must have enough memory to run your operating system and the memory reserved for use by Couchbase Server. For example, if you want to dedicate 8GB of RAM to Couchbase Server you must have enough RAM to host your operating system. If you are running additional applications and servers, you will need additional RAM. For smaller systems, such as those with less than 16GB you should for instance you should allocate at least 40% of RAM to your operating system.

Installing Couchbase Server

To install Couchbase Server on your machine you must download the appropriate package for your chosen platform from For each platform, follow the corresponding platform-specific instructions.

If you are installing Couchbase Server on to a machine that has previously had Couchbase Server installed and you do not want to perform an upgrade installation, you must remove Couchbase Server and any associated data from your machine before you start the installation. For more information on uninstalling Couchbase Server, see Uninstalling Couchbase Server.

To perform an upgrade installation while retaining your existing dataset, see Upgrading to Couchbase Server 2.0.x.

Ubuntu Linux Installation

The Ubuntu installation uses the DEB package. To install, use the dpkg command-line tool using the DEB file that you downloaded. The following example uses sudo which will require root-access to allow installation:

shell> cd /tmp

shell> wget

shell> sudo dpkg -i couchbase-server-enterprise_2.2.0_x86_64.deb
Selecting previously unselected package couchbase-server.
(Reading database ... 58859 files and directories currently installed.)
Unpacking couchbase-server (from couchbase-server-enterprise_2.2.0_x86_64.deb) ...
libssl1* is installed. Continue installing
Minimum RAM required  : 4 GB
System RAM configured : 4000408 kB

Minimum number of processors required : 4 cores
Number of processors on the system    : 1 cores
Setting up couchbase-server (2.2.0) ...
* Started couchbase-server

You have successfully installed Couchbase Server.
Please browse to
http://couchBase:8091/ to configure your server.
Please refer to for additional resources.

Please note that you have to update your firewall configuration to
allow connections to the following ports: 11211, 11210, 11209, 4369,
8091, 8092 and from 21100 to 21299.

By using this software you agree to the End User License Agreement.
See /opt/couchbase/LICENSE.txt.

Processing triggers for ureadahead ...
ureadahead will be reprofiled on next reboot

shell> sudo reboot

And voila, couchbase is installed and listening on ports: 11211, 11210, 11209, 4369,
8091, 8092 and from 21100 to 21299.

Go to: http://yourIP:8091/index.html to find the installation-setup page


At this point you can choose to start a new cluster or to join an existing one.


I picked to join an existing server and that what it will be presented to the administrator.

That’s it, now we have a working cluster with two nodes.

Tagged , ,

Last Snow Week End on the mountains

Past week end I had the chance to enjoy a fresh 40cm snow-powder on the alps, here follows a list of breathtaking pictures I took and it will start from the view by exiting the car in Andermatt parking place, the weather was just great and the sun shining like in summer.

Nätschen parking place

The best place to snowboard in that location is situated between Sedrun and Andermatt, is called Oberalp and it is probably one of the most beautiful location in the alps.


To reach it you need to take the Bernina Express which in half hour brings you on the roof of the alps.

Bernina Express


While ascending with this rack railway you can enjoy the view of the Gemstock, one of the most difficult ski place in Switzerland.


The train proceeds thru the valley of the Oberalp and the landscape is something that take you the breath away.


Here is a picture of the train station by Oberalp Pass this is one of the train stop of the Bernina Express.

Oberalp train station

After a 3 minutes uphill walk that is the mountain landscape that has been presented to my eyes.

Oberalp train station

On the right you can see the restaurant which lays on top of the train station… For me that was just a speechless landscape!

Looking to the other side of the valley you can appreciate the beauty of the nature. Fresh, untouched powder that later I surfed with my board.

Ski lift start

I managed to arrive on top of the mountain, at the beginning with the Ski lift and then on foot, the panorama was just wonderful.

Top of the Oberalp

And after a whole day spent surfing the fresh snow I went back to Nätschen (Andermat ski field) and I boarded back to my car.





I hope you will enjoy the pictures and the mountain spirit of the alps.

Tagged , , , , , , ,

Lettera al Corriere del Ticino: È determinante motivare i docenti

Riporto una mia lettera di disappunto per dei commenti fuori luogo del capo della divisione scuola del canton Ticino apparsa in data 21 marzo 2012 sul Corriere del Ticino. Ringrazio il giornale per aver pubblicato interamente il mio scritto.

Scrivo in merito alla trasmissione del 14 marzo apparsa al quotidiano, RSI LA1. In questa trasmissione il capo della divi­sione della scuola Diego Erba invita gli aspiranti insegnanti ticinesi ad una mag­giore capacità di adattamento, dichia­rando che gli insegnati provenienti dal­la vicina penisola sono maggiormente impegnati, più determinati e flessibili, e addirittura sono più preparati degli in­segnati ticinesi. Prima di tutto non capi­sco come il signor Erba riesca a determi­nare che gli insegnati di oltre frontiera siano più flessibili degli autoctoni. Forse perchè fanno tanti chilometri per arriva­re al posto di lavoro? Visto che ci sono in­segnanti che abitano nel Sottoceneri e lavorano nel Sopraceneri e vice versa non mi sembra un buon metro di giudizio. In merito alla preparazione, mi domando se gli insegnanti del bel paese siano co­stretti a frequentare la DFA a Locarno co­me tutti gli insegnanti ticinesi, e questo vale pure per i neo laureati delle univer­sità di oltre S.Gottardo. Se non sbaglio questo obbligo cade nel caso in cui il do­cente frontaliere sia già abilitato; le scuo­le universitarie svizzere sono forse di li­vello inferiore rispetto a quelle italiane? Ultimo ma non per importanza, per quanto riguarda la motivazione, se do­vessimo dire ad un docente ticinese di prendere il triplo del salario per un mag­giore impegno, penso che il consenso sa­rebbe univoco nell’accettare l’offerta, an­che a scapito di qualche ora supplemen­tare e qualche chilometro in più; tant’è vero che molti neolaureati ticinesi scel­gono di lavorare oltre S.Gottardo per del­le paghe che sono del 20-30 percento più elevate rispetto a quelle della Svizzera italiana. Per concludere, il signor Erba fa­rebbe meglio a confrontare i salari dei docenti ticinesi a quelli dei docenti degli altri Cantoni, queste disparità a livello svizzero non sono motivate. Gli alunni ticinesi sono forse più semplici da istrui­re rispetto a quelli del resto della Svizze­ra? Mi permetto un’opinione personale, come laureato, impiegato nel Canton Zu­rigo e ragazzo di una docente delle scuo­le medie. Trovo che il capo della divisio­ne della scuola non dovrebbe lasciarsi andare a certe provocazioni ed illazioni, che non solo disturbano i ticinesi, ma in­fastidiscono e demotivano i bravi inse­gnanti indigeni che si impegnano tutti i giorni per far si che il livello dell’istruzio­ne rimanga sempre ottimo. Magari assu­mendo un frontaliere al suo posto avrem­mo un maggiore impegno nel motiva­re i docenti nel loro operato!

Articolo originale:


Tagged , , , ,

I introduce myself to you

Born in the southern part of Switzerland, I spend my childhood at the feet of the Alps near Lugano’s lake.

After the gymnasium  I moved to Zurich for my studies at the ETH Zurich and finished them in Ticino by the SUPSI Manno as Informatics engineer. I had the chance to work a few months as assistant then I got a job offer in Zurich and I started working as technical consultant for Motive Inc. I traveled24751_376879676386_533451386_3740944_6840910_n around the world and worked for many customers (BT, Telecom Italy, Swisscom, Saudi Telecom and more) where I covered roles as developer, trainer, deployment manager, QA lead as well as technical leader.

Motive got acquired by Alcatel Lucent and therefore I continued delivering my service as before but for a different company.

After 4 years I decided to search new incentives and I changed to a new company: Steria Schweiz AG, where  I’m engaged as software developer and consultant.

285498_10150250932001387_533451386_7528904_5737553_nDuring my spare time I work on, I go to the cinema and I practice sports.

In my sportive career I did the Zurich marathon, the Triathlon in Locarno as well as the “Trittico” (bike marathon) across the Alps.

Tagged , ,