toggle Cinema 10 Nov 2009

Comparando herramientas de compresión para javascript Posted by Insane in Cool, Google, Javascript, Php | No responses

A la fecha en que este post fue escrito, Google tenia 5 dias de haber anunciado Closure Compiler para la compresión de archivos javascript.Su herramienta no solo comprime código sino que lo hace más pequeño ademas de  optimizarlo.

En este post comparo a Closure con las herramientas de compresión mas conocidas, YUI, Packer de Dean Edward y Shrinksafe the Dojo compressor comprimiendo tres importantes frameworks para javascript.

Métricas

porc

La diferencia entre Closure en modo simple contraYUI es de pocos bytes, esto cambia notablemente en modo avanzado, colocando a Closure en la cima de las herramientas para compresión.

Si deseas hacer tus propias pruebas con Closure aquí hay algunos tips.

Usar Closure mediante PHP y el API REST

protected function gClosure($filename){
 $ch = curl_init('http://closure-compiler.appspot.com/compile');
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_POST, 1);
 curl_setopt($ch, CURLOPT_POSTFIELDS
 , 'output_info=compiled_code&output_format=text&compilation_level=ADVANCED_OPTIMIZATIONS&js_code=' . urlencode(file_get_contents($filename)));
 $output = curl_exec($ch);
 curl_close($ch);
 return $output;
 }
  • Si el tamaño de tu código supera los 200000 bytes no especifiques  el codigo sino la dirección de tu scritpt usando la variable code_url en lugar de js_code de otro modo el servicio te regresara un error indicando que has excedido el tamaño máximo de la petición POST.
  • Una buena practica si utilizas Apache es crear un RewriteRule para redirigir todos los peticiones que soliciten archivos javascripts a ser manejados por tu ServerSide , asi podras comprimirlos al instante ademas de posiblemente “cachearlos” para futuras peticiones aumentando el performance considerablemente.
  • Closure en su modo avanzado verifica que las funciones asi como variables en tu script sean usadas al menos una vez en el, de no ser asi el símbolo no es retornado en la compresión. Se muestra un ejemplo a continuación:
    // esta funcion no es llamada en el escript
    // asi que se suprime en el retorno
    function a(b){alert(a);}
    // esta funcion es llamada y/o referenciada en el escript
    window.aa = function a(b){alert(a);};
    a("Hola");

Enlaces

http://code.google.com/intl/es/closure/

http://dean.edwards.name/weblog/2006/12/packer-php/

http://www.dojotoolkit.org/docs/shrinksafe

  • Share/Bookmark
toggle Cinema 27 Oct 2009

Google-api-translate-java Posted by Insane in Uncategorized | 6 responses

Encontre  este proyecto en Google Code el nos permite usar Google Translate en nuestras aplicaciones Java.

Su uso es de lo mas sencillo:

import com.google.api.translate.Language;
import com.google.api.translate.Translate;
public class Main {
public static void main(String[] args) {
try {
String translatedText = Translate.translate("Hola mundo", Language.SPANISH, Language.ENGLISH);
System.out.println(translatedText);
} catch (Exception ex) {
ex.printStackTrace(); }
}
}
  • Share/Bookmark
toggle Cinema 25 Oct 2009

Mashup: put your Google Analytics Data inside a Gadget Posted by Insane in Google, Java, Php | No responses

-

-google_mashup

The acuracy of the data is probably one of the most challenging aspects of the web analysis , on these days to know how to interpretate that data is quite vital for almost every person involved with the web.Google Analytics (’GA’ from now on ) has become one free powerfull tool to track your web campaign.My aim here it is not only to show how easy it`s to remake that GA graphs inside a Google gadget but also to show how usefull they really are outside GA.

For the purpose of this article, i will asume that the reader has previous knowledge on GA  otherwise here´s a strongly recommended page for a quick and straight forward initiation. we will use  Yahoo Pipes, Google Charts ,Google Gadgets and just a pinch of you server side language.

Note: this is just an experiment, i recomend you to take a look at the Google Analytics Labs if you need a more complete way to get & analize your data.

dilbert2004887870516_1

First of all you need a way to get a perodical report without visit the GA website right ? you need to schedule a report , this can be done by entering to the panel of “schedule report” , complete all fields required by this form and make sure of choose XML as de format of the report ( in order to make this tutorial works, you can change this later ).

Pipe Web Address: http://pipes.yahoo.com/pipes/pipe.info?_id=0ff66029e7bf71cbcd31acbb7279f079

0

Ok, if anything goes wrong until then you sucessfully had created a scheduled report wow, the following JAVA code allow you to check your inbox and determinate wheter an email have an attachment and an specific remitent, yes, your scheduled report from GA wow.

Getting out the report of your inbox.

(toggle java code)

Read and interpretate your inform.


Note : now hat we have our xml we need a scheduled cron that copy it to a visible URL , it can be simplest as an a cp command.

At least that you had been hiding down of some kind of big rock on a far far country with no internet connection you must know by now that Yahoo Pipes is the new big thing to compose,manipulate and reorder the information from around the web therefore we give it a chance to manipulate our xml and  give it an json output.

yahoo_pipes_analytics

There are 6 points to need to be explained about this pipe, these are shown below:

  • 1 -The url of our GA xml.
  • 2 -Extra url parameters if you need it
  • 3 -Fetch Data coming from the URL
  • 4 -Rename of node names.
  • 5 -This step shows how easy it`s to use a regular expression on an specific node , on this case append “Analytics Report”, to the current title.
  • 6- A simple sorter.

Parse it and Graph it.

(toggle php code)

All the requirements to make things works are in the basket, now it`s just a question of time to put them togheter, next steep Google Gadget ( God bless the GG )
, this is the simplest of all steps.The main reason why i decided to choose Google gadgets is that it`s more and more easy to place them in

All the requirements to make things works are completed, now it`s just a question of time to put them together, next steep is  the gadget ( God bless Google Gadget), this is the easiest part of this tutorial.

The main reason why I decided to choose Google gadgets is because is more and more easy to place them in almost all the services of Google.

The gadget

(toggle Google Gadget Code)

<?xml version="1.0" encoding="UTF-8" ?>
<Module>
<ModulePrefs title="Mashup Analytics Google Gadget"  height="300"/>
<Content type="html">

<![CDATA[

<div id="content_div">
	<span>loading...</span>
</div>

<script type="text/javascript">	

	function makeGETRequest(url) {
		var params = {};
		params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
		gadgets.io.makeRequest(url, response, params);
	};

	function makeCachedRequest(url, callback, params, refreshInterval) {
	  var ts = new Date().getTime();
	  var sep = "?";
	  if (refreshInterval && refreshInterval > 0) {
		ts = Math.floor(ts / (refreshInterval * 1000));
	  }
	  if (url.indexOf("?") > -1) {
		sep = "&";
	  }
	  url = [ url, sep, "nocache=", ts ].join("");
	  gadgets.io.makeRequest(url, response, params);
	}

	function response(obj) {
		document.getElementById('content_div').innerHTML = (obj.text);
	};

//serverside call
makeCachedRequest("http://www.yourdomain.com/serverside.php?resultFormat=image",response,{},60);

 </script>
]]>
</Content>
</Module>

Final Result

Even if this could be considered as an looong workaround for one solution , you must admit is funny to create our own graphics and refine the results of it isn´t it ? I hope someone find this usefull . In the image you can see how easy it`s to integrate this gadget to Google Wave and Gmail by example wow

ggraph_waveggraph_gmail

References

  • Share/Bookmark