mercoledì, novembre 07, 2012

So it has come to this

So, it has come to this.

It's been a long time since I last wrote anything on this blog, mainly because I was too busy with real life problems to focus on javascript and programming in general.

Most of you probably has already notice that I'm now listed in the http://mootools.net/developers page,
while after the hackathon I didn't contribute as much as the past I'm proud to be one of the developer for this marvelous framework.

I will move soon to London (as in 2 days from now), where I'll join a new Company, after 8 years in the old one.

In this 8 years I learnt a lot, I got the chance to develop on multiple platforms, learn new programming languages, learn good patterns, made some good stuff (and some less good).

London will be surely the best place to improve my english, that kinda sucks right now, also London is the best place to further improve my skills, since there are lot of talk and meetup to visit, and maybe giving a talk as soon as my english improve a bit.

Once there I'll start again writing about javascript, MooTools and stuff like that.

About MooTools, stay tuned because there are really awesome stuff quite ready to be showed and talked about, so I will have lot of things to write in the next month, this blog will be alive once again \o/

See you soon ;)

martedì, ottobre 11, 2011

Mootools AOP and how to use AOP for Profiling Mootools Classes

In my last post about Mootools private pattern mutator, I've show how to use keeto's patternmutator to inject a private object into mootools methods.
Using this private object it is then possible to add private properties and methods which are accessible only to methods decorated with 'private'.

As noted by coda in the comment section, pattern mutators is now included in mootools 2.0.
PatternMutator is also the base of my kenta.AOP Class for Mootools that I'm going to introduce, and as a bonus I will show how to use kenta.AOP to create a simple Mootools Class Profiler.
What kenta.AOP is?
kenta.AOP is simple way to handle AOP in MooTools for debugging purpose.
In particular kenta.AOP handles method invocation by rewriting all Mootools class, allowing you to intercept these methods before and after the execution.
You can then use the event parameter to cancel the method's execution or hijack the method's return value.
kenta.AOP uses Mootools Events in a Publish-Subscribe pattern to let you write any modules you want.
In this post I will show you kenta.AOP.Profile to better demonstrate what kenta.AOP can do.

I wrote kenta.AOP as a little project to better understand patternmutator and AOP myself, but since it might be useful for other people I will share this snippet. piece of code.
What kenta.AOP is not? It is not a complete AOP Framework. In particular kenta.AOP can't handle property access and it doesn't perform exception handling by design; it also overwrites all MooTools class methods, so I advise against using it for production-code :)

the complete code of kenta.AOP is here:
kenta.AOP provides a global AOP object that fire two events: 'pre' and 'post', that you can use to listen and hijack methods.
Even if kenta.AOP listens all Mootools class method, it is designed to fire only if the Class has a 'Aspect' property

I guess you are wondering what kenta.AOP can be useful for, so here's a little example of how this code can be useful for debugging:
with an example:

Since Profiling don't require to overwrite the return value I will show you another example:

and another one in which we cancel the method execution:

domenica, ottobre 09, 2011

MooTools private pattern mutator

UPDATE: I created a MooTools forge repository for Private. There you will find any kind of improvement ;) /UPDATE Not too long ago I wrote this gist to add a sort of private properties / private methods to MooTools 1.2.x:

As of MooTools 1.3 this gist won't work anymore, but I've wrote another one as alternative, it requires Mark Obcena's PatternMutators.js that you can find here: keeto.PatternMutators.js:
How it works?

In the first version, the one for the 1.2.x branch of MooTools, if you Implements Private, what happens under the hood is that it create a property using MooTools $uid to get a unique-id per istance on a not-accessible outside of Class.Mutators.Private function, then it rewrote all the method of your instance passing the associated property as the last parameter of your function so that you can use it to store/retrieve private properties or even methods.

Since there's no way to automate the cleaning of all the objects/methods you can add, it need also to add a '~' method that you need to call on your destructor so it will not leak memory. I decided to use this ugly syntax: ['~']() because it need to stand out of your code, in a way to remember you that you are using an ugly hack to create privates and because is easier to remember something so strange ;)

For the 1.3 and upper branches of MooTools(yep, still work on 1.4.x) I decided to use a different, not compatible, way to achieve the same objective, so I based my mutators on keeto's patternMutator, for a number of reasons, basically cleaner syntax, re-using of existing code (keeto's one), and only methods marked with 'private' are now overwritten. You can see an example right here:

The code is slighly different, instead of Implements:[Private], you have to explicity mark the method you would like to use private properties or methods by adding 'private ' ahead of your method name, but other things remains unchanged.

mercoledì, febbraio 02, 2011

Post Mortem of a big js project (Part I)

Well, it seems ages since the last time I updated my blog, I really think is time to shove some dust off my blog.

Where did I'm vanished?

I was really busy on a project, in which I put lot of effort, I'm now to a point where I can consider the project to be quite stable so I can finally relax and return back here to write something about this.

I thought it was a good idea to write a post-mortem of this project.

Well. Let's start.

I was told to rewrite a really complex application originally written in vanilla javascript, because it needs to change it's UI.

After a little talk to the original application writer we comes to the conclusion that we can't only extend the old application to support the new UI but we need a total rewrite from scratch.

We only had something like 6 months to rewrite an application that was written in the span of 3 years with lots of features, in the meanwhile we even need to introduce more feature that wasn't expected to be introduced 3 years ago.

We immediately thought that we need to plan ahead what we will have to develop.

So we split the project in 2 big parts, the front-end and the back-end using an "MVC/MVP" approach,
in this way while he was concentrating on his parts, I could developing the new UI.

Both of us were sure that we needed to use a framework or a library to ease our work.

So we start to seek for the framework / library that was better suited for our needs.

He was quite sure to take jquery, but I was confident that we needed a better way to write our code, because, after all, it was one of our biggest problem.

The old application teach us that it was extremely important to write our code in a future proof way.

So, since I saw the benefits of good Object Oriented in my C# experience, I thought that we needed something that could force both to write more reusable code, enforcing the Object Oriented way to write javascript code.

With OO code we could have easily apply the TDD techniques that we both wanted.

After this considerations, It was pretty natural to me to follow the MooTools path, and I can tell you now that was a wise choice :)

Immediately after we started writing our firsts objects we feel the needs to automatize some tasks, like the merging of our little class file into a big script.

So I start to wrote the tool (a c# page) to merge together the classes, and to run our JSSpec page.
In the process of writing this page I included JSCoverage to made the code coverage of our tests, and I think this move was really smart, because we discovered that JSCoverage fails if it finds a syntax error in the code.
So technically it was as if we had a javascript compiler, that tells us that something was wrong even before running the page, not only that but it was amazing because JSCoverage returns the row where the syntax error was founded!

With a few tools we have TDD, BDD, Code coverage and syntax error applied to our js project. Marvelous.

Speaking of tools I found mootools really handy when we need to do a profiling of our application, it was as simple as writing a mootools mutator (https://gist.github.com/570711)

... but I'm seeing that this post is becoming too long, so I think I will continue it another day. bye ;)

lunedì, dicembre 28, 2009

Recensione Irex Iliad (1a edizione)

Ho recentemente acquistato tramite simplicissimus questo magnifico lettore di e-book (ad un prezzo fortemente scontato), la scelta è caduta su di lui principalmente per un solo motivo: la dimensione del display.



Infatti, a differenza di altri, questo lettore ospita uno schermo da ben 8 pollici con tecnologia e-ink a 16 tonalità di grigio e una risoluzione di 768x1024 pixel.
A suo favore dispone di una penna wacom per scrivere, questo significa due cose:


  • non è un dispositivo touchscreen, senza pennetta non potete usare le caratteristiche touch

  • non ha strati aggiuntivi al di sopra dello schermo e-ink e quindi non avrete problemi di riflessi


Come si può vedere dall' immagine qui sotto è molto sottile, molto più di un libro anche se come peso è di poco più leggero (pesa circa 450 grammi)






Sicuramente in un e-book reader conta come prima cosa la leggibilità del testo, ed è questo il punto di forza dell’ Iliad, la grandezza del monitor, e l’ ottimo supporto di base ai pdf, permette di leggere in maniera agevole questo formato.
E' possibile zoomare, ed effettuare il pan (lo spostamento) del pdf usando il pennino, è possibile anche vedere il pdf in landscape, inoltre aprendo un qualsiasi documento si ricarica l' ultima pagina visitata
Molto comoda la funzione di annotazione sui pdf tramite pennino per prendere appunti mentre si legge.



Oltre al pdf il lettore supporta una manciata di altri formati utili quali testo (.txt) e pagina web(.html) quest’ ultima utilizzando minimo (la build di firefox per dispositivi pocket) e mobipocket (.prc) supporta inoltre immagini e permette di annotare su di esse (jpeg,bmp e png)



Dispone di piccole casse integrate (e uscita cuffie ;) ) e ha il wifi integrato (supporta fino al WPA 1)



Inoltre è possibile interagire con il sistema operativo sottostante (linux) per installare applicazioni, ce ne sono poche ma buone, le più utili sono sicuramente:
pViewer : un lettore pdf alternativo che permette di fare il reflow del testo contenuto in un pdf anziché usare lo zoom normale contenuto nel lettore di default
iNewsStand: permette di sincronizzarsi con il proprio account feedbooks (gratuito) per scaricare diverse news da internet come fossero giornali (basta un feed rss)
FBReader che permette all’ Iliad di supportare svariati formati aggiuntivi
la triade calendario – agenda contatti e todo list
sono disponibili inoltre per gli smanettoni un file manager, una shell, un server ssh
ed altri ancora che si possono reperire a questo indirizzo



Diverse persone hanno messo mano ai sorgenti del lettore pdf di base (ipdf) creando delle modifiche ad hoc ed è possibile usare questi lettori andando a sostituire l’ originale con uno di questi (consiglio di utilizzare questo script da me creato prima di procedere all’ installazione di un lettore diverso)



L’ interfaccia grafica è pensata per poter accedere ai vari menù utilizzando semplicemente i tasti funzione dell’ Iliad, evitando di usare il pennino per risparmiare batteria e non dover staccare le mani dal dispositivo.






Il pennino risulta comunque utilissimo per interagire con le finestre dei vari programmi aggiuntivi e per prendere note sui pdf o sulle immagini, con un precisione che è ottima.



Parliamo ora dei difetti:
Una durata della batteria breve rispetto ad altri dispositivi e, in particolare, della seconda versione dell’ Iliad anche se per una persona normale, ovvero che legge soprattutto alla sera, o in pausa pranzo, il difetto è “poco sentito”, nel senso che ci si può veramente godere di lunghe sessioni di lettura senza paura che la batteria si esaurisca, e comunque il lettore è utilizzabile mentre è in carica (anche se, per colpa dell’ adattatore, potrebbe risultare un po’ scomodo se non si ha una presa vicina) e una carica si completa in circa 3 ore.



Come tutti i dispositivi di questo tipo esiste un effetto di persistenza residua a video (chiamato effetto ghosting), faccio però notare che è praticamente impercettibile mentre si legge, infatti il problema è maggiore quando il display usa tutta la gamma di grigio (per esempio per mostrare un’ immagine) e subito dopo si passa in una pagina normale (scritte nere su pagina bianca), oppure quando ci sono grosse intestazioni scure e la pagina successiva ha un carattere più piccolo, ma tra una pagina e l’altra di un testo questo effetto è nullo o praticamente impercettibile.



Il difetto più grande è forse il fatto che la barra a sinistra può risultare scomoda per persone che hanno difficoltà ad usare la mano sinistra;
si riesce comunque ad utilizzare il dispositivo però si deve appoggiarlo per cambiare pagina.



L’ iliad sembra attirare la polvere e di conseguenza, inevitabili ditate



Il software base dell’ Iliad è scarno, ma con un paio di link è facile sapere quali applicativi installare e la procedura da eseguire per installarli, che richiede però alcune conoscenze tecniche che per alcuni può essere un ostacolo.


Ma passiamo ora alle cose interessanti, ovvero come si vede nell' Iliad:

Questa è la pagina iniziale del romanzo "Abissi d' acciaio" di Isaac Asimov così come viene visualizzata con il lettore di default (da notare un leggero effetto ghosting, non vi preoccupate, la fotocamera è più sensibile dell' occhio umano :P ):






Zoomando attorno al testo si vedrà così:






Mentre usando il lettore ipdf fullscreen, usando lo stesso zoom si vede in questo modo:






Siccome usare il pan è molto scomodo non vi mostro lo zoom su una porzione di testo (che comunque è perfetto), invece vi propongo come si vede utilizzando pViewer con il livello 1 di zoom (a livello 0 è identico alla prima immagine)






pViewer livello 2 di zoom







pViewer livello 3 di zoom






pViewer livello 4 di zoom





Conclusioni:


Monitor molto grande che permette un lettura agevole anche se perde la tascabilità (ma è sempre pur meglio di portarsi addietro un netbook solo per leggere), scarsa durata della batteria (anche se esiste il metodo per potenziare la batteria perdendo ovviamente la garanzia), pennino per scrivere e annotare sui pdf ma pochezza di software di base (nessun supporto ai segnalibri multipli, nessun supporto al fullscreen) fanno dell' Iliad un lettore ebook formidabile per gli smanettoni, ma un po fastidioso, soprattutto all' inizio per i neofiti che non hanno voglia di cercar in internet come colmarne le lacune e che preferirebbero solo accendere e leggere.

martedì, novembre 10, 2009

Problemi ADSL? Non c’è problema! Li ignoriamo!

Scrivo questo post per sfogarmi un po’ dalla rabbia accumulata in questi giorni.

Sono abbonato con il mio operatore ADSL da circa 3 anni ormai l’ attivazione è avvenuta infatti il 21 febbraio 2007, e considerando che avevo fatto la richiesta in data 9 novembre 2006 posso considerarmi fortunato, poco più di tre mesi per tirare un cavo solo dati :)

C’è da dire che mi sono orientato verso questo operatore per una tanto decantata banda minima garantita che mi avrebbe permesso di utilizzare la linea di casa per un uso professionale, e devo ammettere che per i primi due anni non ho avuto granché problemi, se non forse due o tre guasti nel suddetto arco temporale risolti in meno di ventiquattro ore.

I veri problemi sono iniziati da quando quest’ azienda ha cambiato politica, infatti ha introdotto nel suo listino delle linee, passatemi il termine, “castrate” del p2p introducendo, per altro, delle policy di QoS (Qualità del Servizio) che hanno, dal mio punto di vista, peggiorato la situazione, non tanto per il fatto del QoS in se, quanto per via che fornendo linee a minor prezzo si è creata una situazione per cui le linee sono di fatto sature.

Ciò che affermo è facilmente riscontrabile dai grafici che tale azienda mette a disposizione di tutti, questo avrebbe dovuto far scattare un fanalino d’ allarme in chi gestisce l’azienda e far si che si prendesse provvedimenti.

Evidentemente di provvedimenti non ne sono stati presi o comunque sia non in modo significativo visto che il problema è cresciuto, per ciò che mi riguarda, in maniera esponenziale.

Nell’ ultimo periodo, infatti, ho un guasto che mette down la mia linea anche per lungo tempo, in particolare sono in una situazione dove la mia linea ADSL (che, da contratto, dovrebbe viaggiare a 7 Mega) o non viaggia proprio, o quelle volte che riesco ad accedere ad internet va a velocità risibili, ciò mi impedisce l’ uso professionale di cui sopra, ma non solo, mi crea dei disagi notevoli dal momento che non riesco di fatto ad utilizzare i seguenti servizi:

  • Mail: il servizio basilare per chi è nel campo dell’ IT, il serviizio di mail non mi è accessibile
  • Banking: Ho un conto online è mi è necessario poterci accedere in qualsiasi istante, poiché è il mio unico modo di gestire il mio conto corrente, quindi ho difficoltà nel mandare pagamenti tramite bonifico, fare trading online, fare ricariche telefoniche ecc..
  • Videoconferenza: Mi è impossibile chiamare tramite Skype non solo la mia ragazza che sento ogni sera (che adesso sono costretto a sentirla solamente per telefono), ma anche con persone che mi permettono di lavorare o di approfondire tematiche relative al mondo IT e che aumenterebbero il mio know-how
  • Tutte le risorse IT disponibili in internet (google gruppi, stackoverflow, reddit, ecc): non avendo accesso alla documentazione relativa ai strumenti informatici che utilizzo per programmare mi viene fortemente limitata la mia produttività casalinga :)
  • Servizi di blogging: Non posso accedere ad HTML.it, per cui non riesco a scrivere nel Blog in cui collaboro, questo mi crea un danno d’ immagine: potrebbe sembrare che io abbia voluto prendere un impegno che non rispetto
  • Servizi di connessione remota: non posso utilizzare ne VNC o RDP ne tantomeno servizi minori come ssh e telnet


Ricapitolando ho danni economici, danni dal punto di vista lavorativo, danni di immagine e danni morali, nonché perdite di tempo, tempo che ho perso inutilmente per cercare di capire se il problema era mio oppure no (cambio di router, cambio di cavi, cambio di configurazione dei router, test su diversi sistemi operativi ecc...)
Per tutti questi motivi e considerato che avevo aperto il guasto il cinque ottobre e a tutt’ oggi (più di un mese!) il guasto si ripresenta tale e quale e da allora ad oggi ogni giorno la linea va in DOWN (numerosi LCP down visibili dal log del router) per diverse ore, spesso quando ne ho bisogno, i pacchetti che “pingo” vengono persi sistematicamente, la velocità non si avvicina minimamente a quella contrattuale, ho deciso di inviare la qui sotto riportata diffida ad adempiere:

Diffida ad adempiere ( avvalendosi della risoluzione di diritto concessa dall' art.1454 del codice civile )
Alla spettabile
Signora Ditta che mi porta l’ adsl in casa

Io sottoscritto
Cristian
Carlesso
Via dei matti numero 0

con la presente Vi INTIMO di provvedere all'adempimento del contratto con Voi
stipulato relativo alla linea adsl associata al numero contratto che poi sarebbe il mio riguardante il servizio di fornitura in modo continuativo del servizio ADSL Specifico del mio caso.

Adempimento che da parte vostra è venuto meno con il guasto verificatosi in data 05/10/2009 e regolarmente segnalato al
vostro Servizio Clienti contattato tramite form on-line
in data 05/10/2009. Ma nonostante tale segnalazione ad oggi sono spiacente di
constatare che non avete ancora provveduto alla relativa riparazione.

Visto che gli usi non prevedono termini più lunghi, per il ritorno da parte
Vostra all'adempimento del contratto già citato con la presente è richiesto un termine
massimo di 15 giorni dalla Vostra ricezione della presente intimazione, facendo fede il timbro postale.
Decorso inutilmente tale termine il contratto di fornitura del servizio adsl Specifico del mio caso stipulato con Voi sarà considerato risoluto di diritto, ai sensi
dell'art. 1454 del codice civile, con la cui presente intendo avvalermi.
Chiedo inoltre la massima celerità nel rendere disponibile dopo la risoluzione
del contratto il numero di linea ad oggi impegnato dal contratto ADSL in essere con Voi.


Adesso se entro quindici giorni dal ricevimento della raccomandata non mi aggiustano la linea il contratto si risolverà per l’ articolo 1454, articolo che impone il rispetto dei vincoli contrattuali, ora vedremo se mi aggiusteranno la linea, comunque sia vi terrò aggiornati, poiché sembra che scrivere un po’ di righe sulla cosa mi abbia aiutato a far calmare i bollenti spiriti, si , perché anche in questo momento (da un paio di ore) sono sconnesso da internet (sfilza di LCP down nel router)…

Speriamo bene! ;)

mercoledì, luglio 08, 2009

So, I want to learn at least a functional languag....hey, wait! I already know it! XSLT!

So, latelly on the web I've read about functional languages and how they will simplify the way to write complex multithreading/multicore programs, so I think that for be a good developer I need to learn at least one functional language, just for understand what is all this about.

WHY FP?
The bigger benefit from Functional Programming is that since in this style of programming the output depends only from the input parametesr, function have no side effects, and this allow simpler multithreading.

HOW FP WORKS?
Basically you describe a set of function ad tell the function what output give based on its input parameters.


but, hey! wait! if in the last sentence you substitute set of function with set of templates and input parameters with matches you can get that the concept here is very similar of how XSLT works...

In fact, in xslt a given template when feeded with the same input always produce the same output!
Xslt,by the way, under the hood use multithreading so seems that xslt have a lot in common with functional programming language...

mmm...

So, to recap, you can say that XSLT templates are the equivalent of FP functions...
... not quite really, since XSLT templates can't be passed across templates by refence ...

TILL...

... I found this paper !

The examples are not very clear (and font-size are weird on that site), so I write a little Example XSLT here:

<?xml version="1.0"?>
<!-- Here I define a defn namespace, we will need it to define our function-->
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:defn="my-functional-xslt-example"
>

<xsl:output method = "text" />

<!-- here I will define 2 functions add3 and add4 -->

<defn:add3 />
<xsl:template match="defn:add3">
    <xsl:param name="parameter" />
    <xsl:value-of select="3+$parameter" />
</xsl:template>

<defn:add4 />
<xsl:template match="defn:add4">
    <xsl:param name="parameter" />
    <xsl:value-of select="4+$parameter" />
</xsl:template>

<!-- ok, now I will define a function that accept a reference of another function and execute that -->
<xsl:template name="execute">

<xsl:param name="function" select="/.."/>
<xsl:param name="parameter" />

<xsl:variable name="result">
    <xsl:apply-templates select ="$function" >
        <xsl:with-param name="parameter" select="$parameter" />
    </xsl:apply-templates>
</xsl:variable>

<xsl:value-of select="$result" />
</xsl:template>

<xsl:template match="/">

<!-- ok, now I will obtain the reference of our function, and I will store that in two variables -->
<xsl:variable name = "add3" select = "document('')/*/defn:add3" />
<xsl:variable name = "add4" select = "document('')/*/defn:add4" />

<!-- and this is how call the function passing add3 -->

<xsl:call-template name="execute" >   
    <xsl:with-param name="function" select="$add3" />
    <xsl:with-param name="parameter" select="10" />
</xsl:call-template>

<!-- and this is how call the function passing add4-->

<xsl:call-template name="execute" >   
    <xsl:with-param name="function" select="$add4" />
    <xsl:with-param name="parameter" select="20" />
</xsl:call-template>

</xsl:template>

So seems simple (but verbose) to pass around function references.

You will argue that this example works only on MSXML, but on the FXSL page you will found the saxon / xalan corrispondence.

on msxml you can obtain a similar results using msxml:script but this require a little javascript code and JSCRIPTxxx.dll and ,for example on pda, this could be a issue.

So, at the end I can say I already know at least a functional programming language... a sort of... or not? ;)