mercoledì 5 gennaio 2011

Parsing HTML string to get links in Javascript

Recently I needed a Javascript function to retrieve links from a HTML string. Unfortunately I couldn't use third party powerful tools like jquery, so I thought to use RegEx.
Let's assume we have a HTML page like this:
<html>
    <body>
        <a href="google.com" title="Google Site">Google</a>
        <a href="mozilla.com" title="Mozilla Site">Mozilla</a>
        <a href="blogger.com" title="Blogger Site">Mozilla</a>
    </body>
</html>
This page contains links to Google, Mozilla and Blogger. How can we get the links from the HTML content?
<script language="JavaScript" type="text/javascript">
function getLinks() {
    var html = "<html> \
                <body> \
                <a href=\"google.com\" 
                   title=\"Google Site\">Google</a> \
                <a href=\"mozilla.com\" 
                   title=\"Mozilla Site\">Mozilla</a> \
                <a href=\"blogger.com\" 
                   title=\"Blogger Site\">Blogger</a> \
                </body> \
                </html>";

    var links = [];

    html.replace(
     /[^<]*(<a href="([^"]+)" title="([^"]+)">([^<]+)<\/a>)/g, 
     function() {
        links.push(Array().slice.call(arguments, 1, 5));
    });

    alert(links.join("\n"));
}
</script>
The getLinks() function retrieves the links from the HTML content and puts them into an array. "The slice method creates a new array from a selected section of the links array". Some useful informations about the slice method here.


So at the end we have an "array of array". If we want to retrieve a single element, we can call it as links[x][y], where x is the row and y is the column.
For example, let's assume we want to extract some information from the first link:
alert("First link (Google):\n" +
      "Destination anchor: " + links[0][1] + "\n" +
      "\"title\" attribute: " + links[0][2] + "\n" +
      "Source anchor: " + links[0][3]);
The function has several limits: for example it's case sensitive and depends on the A element. In the case above, the href and title attribute are set, but if we have an A element like this:
<a href="google.com">Google</a>
without the title attribute, the function won't work. In that case, we should modify the regex in this way
html.replace(
     /[^<]*(<a href="([^"]+)">([^<]+)<\/a>)/g, 
     function() {
        links.push(Array().slice.call(arguments, 1, 4));
    });
Best regards.

lunedì 3 gennaio 2011

One year old

The 50th post is all dedicated to the first birthday of this blog. One year ago I started writing this little diary with no expectation, but in the hope to give back to internet a bit of what I was in receipt of. How many times do we earn money, create something or fix problems simply browsing the internet? We digit our keywords and someone somewhere helps us. The idea was to be the nth someone, one of many, to expand that marvelous microcosm of the internet community, the best form of cohabitation I have never seen, even though it's not free from problems. So I hope not to have written too much crap.
I don't want to miss the opportunity to thank the visitors ( I didn't expect so many ) and who took the trouble to mail me. Thanks a lot.
This post is planned for January, 3rd 2011 and it isn't too late to wish you a happy new year.

Best regards.

martedì 28 dicembre 2010

Problem with Google Images and Firefox - 2

By browsing the internet, my brother Massimo found out the solution for the problem described here. This problem is due to the router.
As explained here: 

"When image results are to be displayed, Safari and Firefox make multiple simultaneous connections to the host to retrieve them. This is usually faster than downloading one and moving on to the next and on and on."
...
"Some consumer-level SPI firewalls misinterpret the attempt to open that many simultaneous connections to one server as a "SYN flood" and block the traffic. Not good, especially when the connections are being made from your machine to an outside host, so the firewall is effectively blocking you from perpetrating what it thinks is a SYN flood."

The SYN flood attack is visible in the router logs. The solution:

"If your router allows configuration of its SPI firewall, you may be able to solve this problem if it has a setting labeled something like:

Maximum incomplete TCP/UDP sessions number from same host

On those routers, this setting is often set to a default of "10"; simply increasing this value to a much higher value - many have had good luck with "20" - will allow accesses to work as desired and will also allow some room for possible future expansion in the number of simultaneous queries made.

If your router does not offer such a setting, there's no solution other than to disable the firewall.

Note that any operating system - Linux, Solaris, even perhaps Windows 7 - could trigger the same problem. You can even generate the same issue in Windows XP by applying "speed tweaks" such as this."

domenica 19 dicembre 2010

Modeling a Cylon Raider - Central part

Yesterday I modeled the central part of my Cylon Raider. After the wings, this is the last part.

I decided to use a poly sphere to start sculpting the geometry. I chose to decrease the subdivisions axis to 12 and the subdivisions height to 8. At the end of the process it will be evident that these values are probably too low. I wanted to sculpt the piece as fast as I could, so I didn't need too much geometry. The sphere has been rotated by 90 degrees about X and Y. After that, I deleted the part filled with the yellow cross-hatching.


The "fuselage" is symmetrical, so it's possible to model half of it and then mirror on X axis. I decided to start the modeling process from the top  of the central part. The geometry has been scaled on the Y axis. The low poly geometry comes in very handy because it's possible to sculpt the shape easily. Obviously, it's possible to add some more geometry inserting edge loops.

The shape was finished extruding the border edges. I decided to extract some parts to handle the model.  I added some edge loops to  reinforce the hard edges and not to have weird results when  I'll smooth the shape The image on the left is the low poly model. It has to be smoothed but it's quite similar to the original one.



This is the final geometry. As said before, I understimated the shape, because I wanted to model it quickly, so I needed to smooth two times the low poly model. The result is good but this is piece of geometry is quite heavy. It should be retopologized, but I have not much time now and texturing the model will be a time-consuming process, so, probably, I will let the model melt my cpus.


Best regards.

giovedì 2 dicembre 2010

Shelf buttons for loading and unloading Maya plugins

Shelf buttons for loading and unloading Maya plugins are very useful and, as a matter of fact, I use them every day.  I'd want to clarify that this method is not mine, but I don't remember where I read it, so I cannot give notice of copyright nor the right credits. I hope to correct this post as soon as possible.

Loading the plugin: we can copy (fixing the path to the plugin) the following lines to the Script Editor, select the text and drag it to the Shelf Bar:
{
    string $pluginFile = "c:\\path\\to\\plugin.mll";
    loadPlugin $pluginFile;
}
Unloading the plugin: same as above.
{
     string $pluginFile = "c:\\path\\to\\plugin.mll";
     if ( `pluginInfo -query -loaded $pluginFile` &&!
          `pluginInfo -query -unloadOk $pluginFile` )
         file -f -new;
     unloadPlugin plugin.mll;
}

Best regards.

mercoledì 1 dicembre 2010

Modeling a Cylon Raider - the wings

I have a couple of free days, so I want to start to model my last homage to Battlestar Galactica, one of my favorite TV Shows.
After the Viper MK II and the Cylon Centurion, it's the turn of the Cylon Raider.

I've found this blueprint as reference, so the first step is to crop all of the images in Photoshop. I will have four different images at the end of the process (top, left, bottom and rear) to import into Maya 2011 as image planes. It's important to use horizontal and vertical guides in Photoshop to resize correctly the images, because the references must have same dimensions.


First impressions: the original model is fantastic, I love the design and the final look, this fighter is really awesome. I don't know the authot but I'd like to pay him a compliment. It is interesting to notice that the model is composed of 4 parts: the wings (I can model one of them and then mirror it), the engines, the weapons and the central part. The fighter hasn't a linear design, but it's possible to break down it into 4 parts to ease the modeling process.


I decided to get started from the wings. I think the wings are the funniest and the most difficult part of this model. I'm using traditional methods to model the wing, nothing fancy: I get started from a box, extruded it a lot of times, added some edge rings and moved the vertices to match my reference images. I'd want to create a low poly model, because I'd like to animate a fight between the viper and the raider and obviously the raider will be destroyed.



Anyway, during the modeling process, I prefer to smooth the mesh to see if it's correct and perfectly rounded. This step helps me to notice that the bottom needs some correction.

In the meantime I decided to use the references as texture, so, in a next article, I'd like to share my method to project the images from a camera to create a new texture. First of all I will create the UV maps, then I will project the reference images from a given camera (unfortunately, it's not possible to use an orthographic one).


Best regards.

lunedì 29 novembre 2010

Replacing HTML entities with the appropriate characters in Javascript

I was looking for a good Javascript example to replace HTML entities with the appropriate characters and, after a long search, I found out this thread on stackoverflow. The function below, proposed by the user Tomalak, works like a charm for me:

var replaceHtmlEntites = (function() {
    var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
    var translate = {
        "nbsp": " ", // Space
        "amp" : "&", // Char &
        "quot": "\"", // Char "
        "lt"  : "<", // Char <
        "gt"  : ">" // Char >
    };
    return function(s) {
        return (s.replace(translate_re, function(match, 
                                                 entity) { 
            return translate[entity];
        }) );
    }
})();
callable as
var strIn ="This string has special chars &amp; and &nbsp;";
var strOut = replaceHtmlEntites(strIn);


Best regards.

mercoledì 24 novembre 2010

The 12th Intl. Architecture Exhibition, People meet in architecture, in Venice

Two weeks ago I was in Venice to visit the 12th Architecture Exhibition, "People meet in architecture", organized by Kazuyo Sejima. I could talk a lot about this Biennale but I won't, because I basically agree with a message left on a toilet wall  ("the toilet wisdom" cit. my Brother Massimo Bolli)   from an unknown visitor (on the left). I will post here the videos of the best pavilions in my opinion. The "Biennale di Architettura" is over now and these videos will allow us to get the picture of this Exhibition, especially if someone didn't visit it.


martedì 2 novembre 2010

JSubs - Programma JAVA per scaricare sottotitoli da italiansubs.net

JSubs è un software JAVA Open Source pensato per scaricare automaticamente i sottotitoli delle serie TV dal sito italiansubs.net (e nell'ultima versione anche da subsfactory.it). Ho scritto JSubs perché mi capita spesso di accumulare un gran numero di puntate, anche di serie TV diverse, e scaricarne i relativi sottotitoli può essere cosa tediosa. Il software cerca in una cartella radice (e sottocartelle) gli episodi dei serial TV (i film o i video personali vengono scartati) e li elenca in una tabella. Cliccando sull'apposito pulsante, si possono scaricare i sottotitoli: JSubs si logga su Itasa, cerca i sottotitoli, li scarica, li unzippa e li rinomina.


CLICCA QUI PER SCOPRIRE IN MODO INTERATTIVO IL SOFTWARE SENZA SCARICARLO

(Si può cliccare sui pulsanti come se fosse il vero JSubs.
Si può inoltre cliccare con il tasto destro del mouse sulla lista dei serial per scoprire il menù.)

JSubs è un software gratuito, il link per il download è in fondo all'articolo.

In questo video si vede il programma in azione su Ubuntu, in particolare la feature, utilissima nel mio caso, del menù contestuale. Sia su Windows che su Ubuntu (nb: il file JSubsCMDL.jar deve essere eseguibile), JSubs può essere aggiunto al menù del tasto destro del mouse: in pratica si possono scaricare i sottotitoli con un semplice click sulla voce del menù, senza neanche avviare l'interfaccia grafica.




JSubs deve essere configurato per poter funzionare. I parametri necessari sono pochi ed alcuni di essi (la homepage di Itasa e l'indirizzo della pagina con l'elenco delle serie TV) sono già configurati. E' importante inserire il nome utente e la password per l'accesso ad italiansubs.net e  la  cartella contenente i video. E' possibile inizializzare un timer all'avvio del programma: JSubs, in modo ricorsivo, controllerà se ci sono nuovi video e scaricherà i relativi sottotitoli automaticamente, senza richiedere il nostro intervento.

I moderni Sistemi Operativi permettono di interagire con gli oggetti attraverso il menù contestuale o menù del tasto destro del mouse. JSubs offre la possibilità di aggiungere una voce al menù contestuale per scaricare i sottotitoli più velocemente, senza avviare l'interfaccia. Facendo click col tasto destro del mouse su un video, si aprirà il classico menù con in più la voce "Scarica sottotitoli con JSubs". Questa feature è supportata su Windows e Linux (attraverso le nautilus-actions, che devono essere installate).
Su Windows verranno create le necessarie chiavi nel Registro di Sistema, su Linux è possibile aggiungere automaticamente un'azione a nautilus-actions o creare un file di configurazione da aggiungere manualmente. Questa feature non è attualmente supportata sui MAC. La finestra delle Impostazioni permette di rimuovere le chiavi dal Registro di Sistema. Su Linux bisogna rimuovere manualmente l'azione con lo Strumento di Configurazione di nautilus-actions.

Sui sistemi supportati, JSubs si installa nella System Tray. Ciò significa che, se si clicca sulla X della barra, il programma non si chiuderà, verrà solamente nascosto, ma sarà ancora attivo nella System Tray. Per chiudere il programma utilizzare il pulsante con l'icona grigia nella finestra principale o File --> Esci nella toolbar. L'opzione più interessante del menù della System Tray è quella di modificare il timer di JSubs.





NOTE IMPORTANTI: JSubs è un software in versione beta, rilasciato sotto GPL e senza alcuna garanzia di funzionamento. Il programma era stato creato per uso personale, ma ho pensato che potesse essere utile anche ad altri. Utilizzo tutti i giorni JSubs su Ubuntu Lucid Lynx, Windows 7 64 bit e Windows XP Media Center senza problemi, ma va specificato che il software non è stato testato per una distribuzione pubblica.
Il programma utilizza librerie ed icone di terze parti e le relative Licenze sono incluse nel pacchetto.


Saluti.