Thursday, January 21, 2021

Making it to Github, eventually

After only 4 years and a half since the last post, I have quite some big news: I finally created my first project on Github.

I'm not really sure it's production-ready, but it technically works and it has a minimum of documentation, so I thought I'd publish it.

It's an algorithm to anonymize hierarchically-structured data, using a multi-level approach, hence a "multi-level anonymizer".

It lives here:
https://github.com/xfranky/ml-anonymizer

I'm still trying to better document the internal working of the classes, and eventually there might be a big rewrite to make it usable for more generic problems rather than the very specific use case it was created for, which is anonymizing transfer speed of connections by provenience.

More to follow, hopefully...

Monday, July 11, 2016

Devise: redirect to specific pages after sign in using different models

As you should know, Devise can be applied in the same project to different models, but I couldn't find a simple way to redirect users after signing in, based on the kind of resource they were representing (e.g. let's say users and vendors).

After searching for long how to solve this issue and finding long and winding solutions, I found a way to solve it myself in a very simple way; as it is here it's really bare bones and possibly prone to bugs, but it does exactly what I wanted, so I thought other people might find it interesting.

So, let's say we are using Devise on the user and vendor models, and we generated our custom session controllers in user/sessions_controller.rb and vendor/sessions_controller.rb. The first thing that came to my mind was to find a way to customize the redirection from the controllers by overwriting some of the functions, but it turned out to be complicated and not working as expected.

As such I came out with a much simpler even though less elegant solution; that is overwriting the default function after_sign_in_path_for(resource) in the application controller, checking whether in my session I have an instance of one kind of resource or the other.

Here is the relevant code:

class ApplicationController < ActionController::Base
  
  [...]

  def after_sign_in_path_for(resource)
    if current_user
      "your_user_url"
    elsif current_vendor
      "your_vendor_url"
    end
  end
end

I hope this will help you as much as it helped me.

Tuesday, February 16, 2016

The old website challenge - 04 - Setting the viewport

It's renown that Google penalizes in its ranking the websites which are not mobile-friendly. As such, one of the priorities with modernizing my old website is to make it mobile friendly. The first step to do this is to implement the viewport property in the HTML code of the pages.

What's the viewport?

I'm not going to invent anything and I rely on W3schools' definition saying that
The viewport is the user's visible area of a web page.
Thus configuring the viewport means being in control of how our website adapts to the screen of any device instead of letting the user's device deciding how to adapt the website to the screen.

The default behavior of most mobile devices, without a properly configured viewport, is to set an arbitrary width (the most common is 980px), render the website as it would appear on a screen of that width, and zoom out until the view matches the device's screen width. Clever, but the results are not always predictable, and especially often not easy to navigate through.

As our objective is to have a responsive website, we want our viewport to always match the device width with no zooming in or out involved. The code to use in order to do that, adding it to the head section of the html document, is the following:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
By doing so we are telling the browser to always size the content of the website to the width of the screen. One downside of this technique is that we need to be very careful when using fixed-size elements, as they might not fit the viewport.

The first way to try to obviate this issue is to use for potentially wide elements (e.g. pictures) the attribute max-width instead of width; this tells the browser to use the given width only when the item fits the containing block; if not, the item will be proportionally scaled until it fits.

They say that With great power come great responsibilities... well, sure, now you are in control of how the website shows and it means that you need to be the one to adapt it to the different devices! As we will see in a next post, a very convenient way to do so is by using the CSS media queries.

Thursday, December 17, 2015

The Old Website Challenge - 03 - SEO and old static files

As I previously wrote, the old website I'm modernizing was rewritten in php back in 2003; yet, the old html static pages were never removed from their original folder, and are still appearing in search engines and being indexed. With some cleverness we can take that into advantage for faster indexing of the new URLs we set up in the previous post.

Going more into details, the old pages are stored in a directory named xhtml/ and their names mostly reflect the names given the files which serve the content for the php version of the website. Knowing this, we can setup a rewrite rule that can redirect the traffic directed to those old files to the new correspondent php pages.

There is one catch, though: not all old pages have the file name equal to the new one. We have two ways to solve this:

  1. Change the name of the old files which do not correspond to the new ones
  2. Implement a check in the rewrite configuration so that we only redirect pages with names that match the new ones
The first solution goes against the very principle of what we are doing (which is keeping the old pages in the search engines' indexes), since it will practically make the old pages with non-matching names disappear from search engines. Thus we go with the second option (which means also more fun!).

To implement the second solution, we move the old files to a new directory, which we call xhtml_old/, and then we need two rewriting rules. 
First we need a rule to redirect the old pages to the new ones:
RewriteRule ^xhtml/([a-z0-9]+).html$ p/$1 [L]
Then we need a different rule to redirect the requests for the old pages to the correspondent files in the new location:
RewriteRule ^xhtml/([a-z0-9_]+).html$ xhtml_old/$1.html [L]
...and now comes the most interesting part of today, that is deciding when one rule applies and when the other does. We can do this using the RewriteCond constructs before each of the two rules.
For the first rule, we want it to be executed when we have a content page for the CMS existing (-F option) with the same name of the old file (the $1 parameter coming from the rule):
RewriteCond include/$1.html -F
For the second rule, we want it to be executed after the first one, and in case we have the old file in the new location:
RewriteCond xhtml_old/$1.html -F
Now we can put all the pieces together in our .htaccess file, adding these lines before the rule defined in the previous post:
RewriteCond include/$1.html -F
RewriteRule ^xhtml/([a-z0-9]+).html$ p/$1 [L]
RewriteCond xhtml_old/$1.html -F
RewriteRule ^xhtml/([a-z0-9_]+).html$ xhtml_old/$1.html [L]
...and now let the crawlers re-index the old pages!

Wednesday, December 16, 2015

The Website Challenge - 02 - Hiding variables from the URL

The custom cms of the website uses a GET variable named pag to go into a specific folder and look for a <pagname>.html file with the page content to be loaded for each page. The result is a url which looks like this:
http://<domain.tld>/pagina.php?pag=pagname
This kind of URL is not very SEO-friendly, so I decided to use the mod_rewrite module, which is pretty much the standard on Apache installations, to turn them into something more human- and search-engine-readable.
New URLs would be in the form of
http://<domain.tld>/p/pagname
In order to do this I played around with the .htaccess file in the main directory and added the following lines:
RewriteEngine on
RewriteBase /
RewriteRule ^p/([a-z0-9]+)$ pagina.php?pag=$1 [NC,L]
The first two lines simply initialize the mod_rewrite extension since it was not previously used and tell it to calculate the addresses relative to the web root folder. The third line is the real rewriting rule, which tells to internally translate any url in the new form into the one using the GET variable; this will happen transparently, without the real address being shown to the users browsing.

To be noted is the fact that there is a debate online about whether is better to terminate URLs with a slash or not, with no clear winner. The most used strategy on CMSs is to add .html to those addresses, making dynamic pages actually look like they were static files. I might do some A/B testing in the future, but SEO is no exact science, so don't expect clear results.

Tuesday, December 15, 2015

The old website challenge (01)

One of the reasons that pushed me to go back updating this blog is a personal challenge I'm taking, which is modernizing an old website of mine, dating back to year 2001! The last big update to the website, namely its port to php from static html, dates back to exactly twelve years ago (December 15th, 2003); I made some other small updates later, up until September 2004.

Later my attention moved to my personal website (www.xfnet.it), leaving the other one untouched until a few weeks ago, when, for several reasons, I got interested again in WebDev, SEO, and the online development world in general.

I will document in this blog the steps I'm taking in order to take the old website into the current times. To be fair, I already took several actions, so the first few posts will be retroactive, but I believe posting every step of the process will help me get a better idea about where I'm going and about the road that I'm taking.

I know, I didn't say which website we are talking about, yet, but let's give it time :)

A new direction

Since I last updated this blog, my professional life went into a different direction; as such it's time to update the direction this blog is going to.

To begin with, it will be more focused on WebDev and online technologies.
Second ...you guessed it... I will be writing in English, as nowadays this is the language I'm expressing myself into most of the time.

As always, I cannot promise I will keep updating the blog, but I'll make another effort.

See you soon :)

Monday, September 5, 2011

L'ocelot inizia ad apparire nei sogni

Ovvero è uscita la prima beta di Ubuntu 11.10 Oneiric Ocelot; l'ho installata sul vecchio pc fisso e sembrano apparire dei bacozzi belli evidenti, ma rimando commenti ed impressioni ad un post successivo più dettagliato.

HP PlayBook, la storia infinita...

Dopo tutto il casino in cui sembrava che la PlayBook fosse quasi invendibile, tanto da doverla scontare a livelli inverosimili, ora vien fuori che l'HP ne produrrà un altro lotto per soddisfare le richieste rimaste inevase. Complimenti per la capacità di previsione del mercato...
Le speranze di vedere un tablet con WebOS da queste parti, dopo la dipartita di HP dal settore hardware consumer e la smentita di Samsung a proposito del suo supposto interesse per WebOS, diventano sempre meno. Vedremo...

Thursday, September 1, 2011

Fedora 16 alpha ...troppo alpha??

Scaricata la iso live, masterizzata su CD-RW, provata sul portatile... errore... provata in macchina virtuale... errore (dopo diversi minuti di caricamento)... stasera proverò sul vecchio fisso, ma l'esperienza fin qui non è confortante! Vedremo se c'è qualche speranza.

--- Aggiornamento ---

Anche sul fisso dava la schermata di errore che diceva di fare per forza logout; in un momento di disperazione ho provato a chiuderla con alt+F4 ...e ha funzionato!! Da quel momento in poi, lentezza ed un paio di bachi a parte, sembrava funzionare, e devo dire che Gnome 3 inizia seriamente ad incuriosirmi... :)

Tuesday, August 30, 2011

WebOS troverà nuova casa?

Dopo essere stato barbaramente (e probabilmente prematuramente) ucciso da HP (assieme a PlayBook e Pre), c'è chi si chiede se WebOS possa essere "salvato" da Samsung, con la classica mossa del tenere un piede in 4 scarpe (Android, Bada, WP7 ...e WebOS?). Visto quanto bene ne hanno parlato i media specializzati non sarebbe male come ipotesi, anche se resta sempre l'incognita della fruibilità in fatto di costo finale all'utente ...ovvero, vedrò mai un tablet WebOS-powered nelle mie mani?

Thursday, August 25, 2011

Grazie Steve! ...e ora??

Cosa resterà di Apple come la conosciamo ora? Sono i piccoli frammenti di vita aziendale e para-aziendale (come l'aneddoto raccontato da Vic Gundotra) che emergono qua e là che fanno capire cosa voglia dire Apple per Steve e Steve per Apple, ma ora che Jobs si è dimesso da direttore generale della Mela, cosa succederà?

Lo ammetto, l'unico aggeggio della mela in mio possesso è un iPod Nano di prima generazione con la batteria consumata, quindi più che da fanatico-apple-centrico parlo da sincero ammiratore di un leader che ha dedicato la sua vita ad un lavoro non facile e che ora si fa (più o meno, per quanto ufficialmente) da parte per motivi che, qualunque siano veramente, non credo criticherò mai, perché è giusto e sacrosanto riconoscere i propri limiti come reclamare la propria libertà.

Personalmente credo che Apple non cambierà più di tanto, anche se auguro a Tim Cook di riuscire a proseguire quanto iniziato da Steve, sperando che riesca a costruirsi anche lui la sua immagine grazie al suo lavoro ed alle sue abilità, senza cercare di essere "solo" il successore di Jobs, che comunque non sparirà, restando molto vicino al vertice.

Rimando all'ottimo articolo di Federico Viticci su MacStories.net per ulteriori riflessioni (un po' più mac-centriche, ma non banali) sull'argomento.

Wednesday, August 17, 2011

Motoogle ...a quando i frutti?

Dico anch'io la mia, come felice utente Android, sulla prossima acquisizione di Motorola Mobility da parte di Google.
Da par mio, tralasciando tutti i discorsi (comunque interessanti e con sapore di rivalsa) su brevetti e tecnologie acquisite, avendo sempre sentito parlar bene dell'hardware Motorola, quello che mi interesserebbe in un prossimo futuro sarebbe la possibilità di avere modelli Motorola finalmente con la versione stock di Android e aggiornamenti garantiti, così come succede ora con i Nexus (toglietemi tutto ma non il mio N1!!!). Se così fosse potrei fare un pensiero molto concreto su qualche prossimo modello in uscita!

Monday, June 21, 2010

Trying to get back on track

More than a year has passed since my last post on this personal would-be-technical blog; in the next days I'll be learning some new concepts and skills in SOA and ESB, and what I'll try to do, inspired by a Freestyle Mind post, is try to post here my results.
This is an experiment and it's not guaranteed to succeed, but I'll try nonetheless :)

Monday, May 25, 2009

Driver nvidia con kernel 2.6.30 (Ubuntu Karmic)

Per chi provando l'alpha di Karmic si fosse trovato nella situazione di non riuscire ad installare i driver nvidia a causa del modulo che non compila, lanciando questo errore:
error: ‘struct proc_dir_entry’ has no member named ‘owner’

ecco una soluzione funzionante presa dai forum di ubuntu e di nvidia:

  1. Aprite il file /var/lib/dkms/nvidia/<versione_driver>/source/nv.c
  2. Commentate (/*........*/) tutte le righe in cui appare la variabile "owner"
  3. Lanciate sudo dpkg-reconfigure nvidia-<versione>-kernel-source
  4. Aprite il gestore dei driver hardware e riabilitate il driver
  5. Chiudete la sessione
Ora il server X dovrebbe riavviarsi con tutto l'occorrente per godere di compiz e amenità simili. :)

Friday, May 1, 2009

Standard-compliance: un po' di soddisfazione

Dopo aver installato la nuova versione (8) di Internet Explorer, ho notato come tutti i siti che ho fatto, seguendo i vari standard di W3C e simili (e con una buona dose di testate sul muro), siano passati indenni, senza bisogno di alcuna modifica, attraverso 3 generazioni di browser di casa Microsoft! Vista la mia eterna diffidenza faccio quasi fatica a crederlo, ma non nascondo una certa soddisfazione in tutto ciò :)

Friday, November 21, 2008

PariPari!

What I'd like to write about today, other than the blog language shift towards English (more probably the US version of it), is the project I'm involved with as a work for my final thesis; its name is PariPari.

The aim of PariPari is to create a peer-to-peer network, based on the Kademlia algorithm, which will offer a certain number of base functions and will act as a platform on which different plug-ins will (and already are) developed. Some of the already-in-development plug-ins are eDonkey/eMule and BitTorrent clients, a distributed storage client, a distributed DNS server, an IRC client, a VoIP platform, ...

Inside the core of PariPari various strategies are being implemented to prevent any abuse of the clients and of the network itself.
On the project's website a first (not-much-working-) example of the built application can be tested; the development version is coming along quite well and in the next weeks should be featured on the home page of the site instead of the current first test version.
For any further information refer to the project's website, the developers' wiki (in the process of being fully translated in English), and PariPari's Bugzilla bug-tracker.

Monday, March 31, 2008

Gnome 2.22

Segnalo una bella recensione dell'ultima versione di Gnome, pubblicata oggi da Ars Technica.


La loro sezione di news è piena di cose non sempre interessanti ma le recensioni fatte in casa sono sempre di ottima qualità! In teoria hanno anche una sezione (Open Ended) dedicata al mondo open source, ma ultimamente non è molto attiva...

Saturday, March 8, 2008

Firefox o cosa? Il ritorno dello useragent

Nel precedente articolo vi avevo parlato dei problemi che potevano essere causati da versioni di Firefox non ufficiali o di sviluppo (Minefield) dando una soluzione provvisoria al problema, ovvero modificando la voce presente in about:config col nome general.useragent.extra.firefox con il problema di doverla ri-modificare ad ogni aggiornamento del numero di versione. Ho invece appena scoperto che una qualsiasi stringa del tipo general.useragent.extra.xyz viene aggiunta alla fine dello useragent in ordine alfabetico.
Ad esempio aggiungendo (sempre comodamente in about:config) una nuova stringa di nome general.useragent.extra.notfox e con valore "Firefox/3.0" si ottiene uno useragent di questo tipo:
Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9b5pre) Gecko/2008030804 Minefield/3.0b5pre Firefox/3.0
ingannando molti siti che cercano la parola Firefox fuori dalle parentesi per capire di che browser si tratta, con il vantaggio di non doverla modificare ad ogni nuova versione. Nei forum di mozilla ho visto suggerire "(like Firefox/2.0.0.13)" come stringa da usare; ho verificato che funziona su Live Maps, dove funziona anche con la soluzione da me proposta ma non con "(like Firefox/3.0)". Personalmente preferisco fingere lo useragent della versione che sto usando solo con la parola "Firefox" diversa anziché quello di un branch precedente per notare eventuali problemi ai siti che visito ed in caso segnalarli, ma non tutti potrebbero pensarla come me. ;)

Tuesday, February 26, 2008

Perché uso Linux...

Al di là di tutte le menate tecniche, poco fa preparando la presentazione per l'esame di Sistemi Distribuiti mi sono trovato in questa situazione:


... il tutto senza perdersi nei meandri di finestre, sistema operativo &co...
Ah... che bello! :)