Archive | Opensource RSS for this section

Validazione Codice fiscale Partita IVA con Ruby / Ruby On Rails

Cercando di validare codice fiscale e partita iva con Ruby, sono capitato nel sito di Umberto Salsi, dove si parla della validazione di Partita Iva e Codice Fiscale.

Visto che l’implementazione in Ruby non era disponibile ne ho realizzata una che ho già inoltrato all’autore della pagina perchè possa aggiungerla all’elenco.

Nel frattempo comunque, le due classi che ho preparato sono disponibili per il download.

Il codice Ruby che ho realizzato per eseguire i check di validità su codice fiscale e partita iva non è corredato da alcuna garanzia, potrebbe causare la morte di migliaia di persone, l’incendio del vostro PC, il mutamento del vostro orientamento sessuale, ma in nessun caso potrete ritenermi responsabile. Usatelo a vostro rischio e pericolo! 🙂

Scarica la validazione Ruby di codice fiscale e partita iva

updated (16/11/2009) – nuova versione con licenza GPL inclusa, descrizione, eccezioni e qualche miglioria

L’utilizzo è molto banale e potete riutilizzare, modificare e redistribuire il codice a vostro piacimento per qualsiasi utilizzo.

Un banale esempio di utilizzo per il codice fiscale:

require 'codice_fiscale'
if CodiceFiscale.valid?('ILTU0C0D1C3FISCAL3')
puts 'il codice fiscale è valido!'
else
puts 'il codice fiscale non è valido!'
end

Un banale esempio di utilizzo per la partita iva:

require 'partita_iva'
if PartitaIva.valid?('02030405060')
puts 'la partita iva è valida!'
else
puts '
la partita iva non è valida!'
end

Sull’opportunità o meno di utilizzare la validazione, vi consiglio di leggere il capitolo “Miti, superstizioni e falsità” sul sito di Umberto Salsi a proposito della validazione del codice fiscale. A tal proposito riporto riassumendo il concetto: usate la validazione ma non sempre è attendibile, potrebbe dare dei falsi negativi, bloccando per esempio la registrazione di utenti legittimi. Viceversa gli utenti malintenzionati potrebbero fabbricarsi in pochi secondi un codice fiscale falso (ma corretto) attraverso uno dei tanti servizi online. La validazione del codice fiscale risulta quindi utile solamente se si vuole eseguire un controllo formale per evitare errori di battitura, ma è solamente controproducente se si cerca con questo mezzo di tener lontano qualcosa e/o qualcuno.

Per quanto riguarda la partita iva vale quanto detto a proposito del codice fiscale.
Tuttavia ho individuato un bel webservice per la validazione delle partita iva messo a disposizione dell’Unione Europea e denominato VIES VAT number validation. Il wsdl e maggiori informazioni sul servizio potete trovarle nelle Faq. Il servizio peraltro funziona, l’ho provato oggi, ed è pure gratuito e discretamente veloce. Interroga i database dei paesi dell’Unione quindi è in grado di fornire validazione anche per le altre partite iva europee. Va sottolineato che non si limita a fare la validazione formale, ma da quanto si apprende attraverso le Faq è anche in grado di verificare se la partita iva esiste realmente ed è attiva. Per alcuni paesi inoltre, fornendo la partita iva, oltre a verificare se esiste ed è disponibile, vengono forniti anche alcuni dati utili sull’azienda tra cui nome ed indirizzo (l’italia è ovviamente esclusa da questa chicca).

Se qualcuno è interessato può scaricare la ruby class for VIES VAT number validation che ho realizzato per un applicativo su base Rails. Per altri usi dovete chiaramente adattarla, ma fa il suo dovere. Ricordate di copiare i wsdl in locale, è una scelta preferibile.

Buona giornata!

linux/debian raid 1 recovery how-to

Hi!

Today one of two harddisks on server fails. How-to repair raid? Easy.

Check raid status (find hda is not updated)

cat /proc/mdstat

If damaged disk is active (for example: only bad sectors) remove it from raid.

mdadm /dev/md0 -r /dev/hda

Turn off your server if hd is not hot-swappable.
Remove damaged hd and replace it with new hd.
Restart your server, be sure that is starts from the old ok hd (ex. hdb). Sometimes bios doesn’t properly updates boot devices and tries to start from new hd or cds, fix it.

System must boot-up properly from old ok hd.

Clean new hd (ex. /dev/hda), remove all partitions.

fdisk /dev/hda

Clean MBR of new disk (to be sure that an old mbr doesn’t exist)

dd if=/dev/zero of=/dev/hda bs=512 count=1

Copy raid partitions scheme from old ok hd.

sfdisk -d /dev/hdb > mbr_hdb.txt

Apply that scheme to your new hd.

sfdisk /dev/hda < /root/mbr_hdb.txt

Add partitions from new disk to your raid

mdadm /dev/md0 -a /dev/hda1

Raid recovery starts.
Check rebuild status

mdadm –detail /dev/md0


/dev/md0:
Version : 00.90
Creation Time : Wed Apr  1 11:10:50 2009
Raid Level : raid1
Array Size : 37110016 (35.39 GiB 38.00 GB)
Used Dev Size : 37110016 (35.39 GiB 38.00 GB)
Raid Devices : 2
Total Devices : 2
Preferred Minor : 0
Persistence : Superblock is persistent

Update Time : Fri May  8 11:52:58 2009
State : clean, degraded, recovering
Active Devices : 1
Working Devices : 2
Failed Devices : 0
Spare Devices : 1

Rebuild Status : 74% complete

UUID : b1d86bee:0e4dedf0:4ddd5836:05672650
Events : 0.680998

Number   Major   Minor   RaidDevice State
2       3        1        0      spare rebuilding   /dev/hda1
1       3       65        1      active sync   /dev/hdb1

That’s it!
Wait and be happy.

oh…. as you know this is not a complete/best/lucky tutorial, if you follow it you home may explode, your city my be destroyed, but don’t bother me! 🙂 no warranty

Good luck!! 😀

sanitize inline css with rails

Hi! You can simply use the sanitize(…) helper in your views to whitelist allowed tags and attributes… but what to do if you need to sanitize the content of a style attribute?  I found a solution to sanitize inline css with rails. This may not be the best solution available, but I didn’t find another solution (like an argument for sanitize helper).

Put this code in your config/enviroment.rb

# ALLOWED CSS PROPERTIES 
HTML::WhiteListSanitizer.allowed_css_properties = Set.new(%w(text-align font-weight text-decoration font-style))
# ALLOWED CSS PROPERTIES - acts like property_name-*, for example `text` allows text-align, text-deco...
HTML::WhiteListSanitizer.shorthand_css_properties = Set.new(%w())

Remember to restart your application, enviroment.rb must be reloaded also in development mode.

Have a nice day!

undefined method `length’ for Enumerable Enumerator on text_helper.rb:50:in `truncate’

With rails 2.0.2 and ruby 1.8.7 you can find this error using rails truncate helper

To solve this problem, paste this code in your enviroment.rb (eof).

module ActionView
  module Helpers
    module TextHelper
      def truncate(text, length = 30, truncate_string = "...")
        if text.nil? then return end
        l = length - truncate_string.chars.to_a.size
        (text.chars.to_a.size > length ? text.chars.to_a[0...l].join + truncate_string : text).to_s
      end
    end
  end
end

Have a nice day!

How to downgrade rails version on debian

If you want to downgrade rails (aka install an old version of rails) on debian first of all install rails gems. Execute next command as root:

apt-get install rubygems

Remove rails package of debian if it’s actually installed

apt-get remove rails

Now install rails by gems utility and force the right version. Example:

gem install -v=2.0.2 rails --include-dependencies

Now put gems bin folder on bash PATH. Edit /etc/bash.bashrc

export PATH=$PATH:/var/lib/gems/1.8/bin

Note: version of rubygems may be different, check your right PATH to gems bin folder

If all goes right now you can use your preferred rails version. Note, rails command from gems is little different between the script that debian package installs. Just check params: call rails command without params.

$ rails
Usage: /var/lib/gems/1.8/bin/rails /path/to/your/app [options]
Options:
-r, --ruby=path Path to the Ruby binary of your choice (otherwise scripts use env, dispatchers current path).
Default: /usr/bin/ruby1.8
-d, --database=name Preconfigure for selected database (options: mysql/oracle/postgresql/sqlite2/sqlite3).
Default: mysql
-f, --freeze Freeze Rails in vendor/rails from the gems generating the skeleton
Default: false
Rails Info:
-v, --version Show the Rails version number and quit.
-h, --help Show this help message and quit.
General Options:
-p, --pretend Run but do not make any changes.
--force Overwrite files that already exist.
-s, --skip Skip files that already exist.
-q, --quiet Suppress normal output.
-t, --backtrace Debugging: show backtrace on errors.
-c, --svn Modify files with subversion. (Note: svn must be in path)

That’s all folks! 🙂

Intel Corporation PRO/Wireless 4965 AG or AGN (HP notebook dv2690el / Debian / Linux)

Hi! I’m posting to release a fast and furious tutorial to bring your wireless lan active in a few minutes.

I assume that you have a kernel release >= 2.6.24. The iwlwifi driver (we need it) has been merged into mainline kernel since 2.6.24.
Run uname -r command to know your kernel version.

Ex.
$ uname -r
2.6.26-1-686

If your kernel is < 2.6.24, you have to upgrade your kernel.
If your kernel is >= 2.6.24 simply load iwlwifi module with modprobe as root user (to become root user use su command at command line and insert root’s password):

modprobe iwlwifi

Is your wlan led turned blue? It’s right. Your wlan is active.
Now you can configure it with ifconfig or you can create an adeguate configuration in /etc/network/interfaces file. If you need help simply use man interfaces command.

Uhm, but I think you need a basic config to use at home with WPA encryption… you don’t have time to read / search / study… that’s so strange!! 😀

So that’s it: edit /etc/network/interfaces (you need root privileges) and put this at the end of file.

#IW
# uncomment next row if you want your wlan active at startup
#auto wlan0
iface wlan0 inet dhcp
pre-up (echo 'Modprobing iwl4965') && /sbin/modprobe iwl4965
post-down (echo 'Removing iwl4965') && /sbin/modprobe -r iwl4965
wpa-ssid YOURNETNAMEAKASID
wpa-key_mgmt WPA-PSK
wpa-proto WPA
wpa-pairwise TKIP
wpa-group TKIP
wpa-psk "yourpassphrase"
wpa-driver wext

With this config you can easy bring up/down your wlan with ifup wlan0 or ifdown wlan0 as root user.

Note: in order to use wpa you need to install a package called wpasupplicant. Install it with apt-get install wpasupplicant as root user.

Have a nice day!

HP notebook dv2690el and linux and… WOW!!!

Hp dv2690el (dv2000 series) is my new laptop.

dv2690el notebook and linux debian

dv2690el notebook and linux debian

Microsoft Vista is too much slow for a pc like this… Who code Vista think to users or think to Hardware Productors? I can’t belive that a new machine equipped with centrino duo and 2gb ram may be slow like it may be with Vista… like a pentium II and XP four years ago…

So, my friend, I’m going on linux with my preferred distro: Debian. And I’m going like a rocket!!!
When I bought this notebook I thinked «I hope that linux works with it».
But now, with debain unstable and kernel 2.6.26-1-686 I think: «Wow!!! It’s completly ready to work after installation!!!». Webcam works without any configuration, also with Skype. alsaconf configure audiocard in no more than 30s, nvidia video card has native linux drivers directly from productor, wlan is active immediatly and without problems (see my dv2690el linux wireless how-to), touchpad it’s right, eth0 works without problems during installation (NETinst) and after, k3b burn CDs and DVDs whitout stop, special keys work immediatly with xmodmap and remote control too… simply wonderful!!!

You like linux and want a new notebook? dv2690el it’s a good choice!

To use special keys and remote control put these rows in a new file:

keycode 162 = XF86AudioPlay
keycode 164 = XF86AudioStop
keycode 144 = XF86AudioPrev
keycode 153 = XF86AudioNext
keycode 174 = XF86AudioLowerVolume
keycode 176 = XF86AudioRaiseVolume
keycode 160 = XF86AudioMute

Name this file .Xmodmap and put it in your home (~) directory. Reload X or type xmodmap ~/.Xmodmap.

Utilissimo: da oggi righe e colonne con Inkscape!

Con la nuova versione 0.46 è possibile creare tabelle in modo semplice e veloce. Read More…

Nuova versione di Inkscape, 0.46!

Sto finalmente provando la nuova versione 0.46 di Inkscape dopo aver aggiornato la mia Debian Unstable.

Stupendo il nuovo strumento `Ritocca Oggetti Scolpendoli o Ridipingendoli`.
Fa esattamente quello che si ripromette di fare! Vi permetterà di modificare i vostri oggetti come se fossero fatti di plastilina. Sei modalità sono infatti destinate alle “sculture” mentre altre due sono dedicate alle “tinteggiature”.

Il nuovo strumento `Disegna solido 3d` vi permetterà di realizzare con agilità nuovi disegni in falso 3d attraverso Inkscape.

La nuova selezione “multi-livello” vi renderà la vita più facile evitandovi di dover cercare oggetti saltellando tra i livelli, cosa che si rendeva indispensabile fino ad ora. Read More…

Estendere Ruby con C

Capita a volte di aver bisogno di estendere Ruby con codice C.
I motivi principali riguardano le performance dell’applicativo e la comodità garantita da un linguaggio di basso livello come C.
Altre motivazioni possono riguardare la necessità di utilizzare con Ruby una libreria C non disponibile in Ruby.

Nel mio caso ho trovato estremamente utile, se non del tutto necessario, utilizzare C per eseguire operazioni di compressione/decompressione con l’algoritmo di Huffman, in special modo sentivo particolarmente la mancanza dei comodi puntatori C.

Dopo una breve ricerca ho trovato un buon tutorial in lingua inglese su rubyinside.com.
Seguendo il tutorial potrete compilare la vostra libreria in C e creare un modulo da utilizzare per estendere una classe Ruby.

Per completezza, ho trovato anche altri metodi per ottenere risultati similari, tra i quali Ruby Inline, Swig e DL. A mio parere però, nessuno di questi metodi ha la linearità e la semplicità del metodo offerto da `How to create a Ruby extension in C in under 5 minutes` di Peter Cooper.

A breve creerò un tutorial per questa utile funzionalità.