martes, 5 de noviembre de 2013

lint CSS code

What is "linting" ? Programming languages can all be validated against its syntax reference, but nothing can prevent you to write bad code. Fortunately many common errors can be found in compile time, and especially if we are talking about non typed languages like javascript or CSS. So that's a linter, a compile-time program used to indicate possible mistakes or bad practices detected in our sources.

Today I'm happy because I've found a CSS source code linter recess that seems to be very nice, or at least it has philosophical posture about CSS very similar to mine and this is, in general the principles of Object Oriented CSS.

The CSS linter I've found is developed (and used) for bootstrap 3. I liked all the suggestions the linter tells me but the "Incorrect property order" so I disabled it (yes, there is a correct property order inside a CSS rule definition! ):

#install it
sudo npm install recess -g
recess all-my.css --strictPropertyOrder false

And the best part, it seems to work nicely with less sources
recess all-my.less --strictPropertyOrder false

Also, recess can be used for CSS minification and indentation or formatting of CSS. 

domingo, 4 de agosto de 2013

The Javascript Global Object JavaScript mystery

Today I will talk about a mystery that should be more noticeable because it is on the root of the code execution but only seems to be visible when having to face with different javascript runtime implementations (not only the browser). Since most javascript only face with The single environment the browser, lets talk about it: the problem of The javascript globals objects:

What is THE Javascript Global Object? Take in consideration the following  code:
var a = 1;
b=2; 
Here we declare 2 variables , but what's the difference. Well, in terms of usability the difference is that b is declared as a property of the global Object 'window' (in the browser) and so any javascript code can access this name (unless explicitly overriden).

So here is the first javascript mistery, So, how can I know, (as a javascript programmer), what is this Global Context Object ? For example, I need this object for performing some global evaluation and for that I need this Global Context object. The answer is simple:

`this` outside any function will be the global object.

...
Explained in other words, this is my way of understanding The Javascript Global Object:

Every code must be runned inside a function, even that code for which we don't see its corresponding function, like when we use eval() or the top-most code that is not inside any function. All the other javascript code resides on a function body. For the top most javascript written code we 


the chat conversation in irc.freenode.org#javascript that teach me :

(Cancerbero_sgx): hi all. question: when I assign a value to a name without the 'var' keyword, like global1=1, those variables are stored as properties of some global object, for example, in a browser on the 'window' object. Does that depends on the implementation?, or has the javascript language some reference this object ? example: for(var v in StandarGlobalObject){...} ? thanks in advance

....


(dwcook): Cancerbero_sgx, it's a property of the environment, not the implementation, whether the global object is the value of some global variable. In browsers, it is `window`.

(dwcook): There are other ways to access the global object. `this` outside any function will be the global object.
aha! thanks!


(Cancerbero_sgx) dwcook: so the implementation sets this initial environment value. Your "other ways to access" was what I wanted to know, thanks!

(dwcook): Cancerbero_sgx, no, it's not implementation-dependent. In different environments that all use V8, it could be `window` or `global` or something else.
However, the other way I mentioned is not dependent on implementation or environment.


(dwcook)It also works regardless of whether you're using strict mode.


(Cancerbero_sgx)aha nice to know, again thank you very much, these are the misteries of javascript that are hard to find googling ;)

(twey): Cancerbero_sgx: The global object is an object you specify when you're creating your Javascript environment (e.g. using V8).  It's up to you whether you give it a name; in browsers it's standard to call it ‘window’, but the only way to access it for sure no matter where your script is running is to use the global ‘this’.

(twey):  Cancerbero_sgx: A top-level name is just a reference, similar to (function() { var v = { }; v.v = v; return v; })()

(Cancerbero_sgx) twey: aja but for me that come from an OO language , it would never occur to me to reference 'this' in the global-root scope. till this moment 'this' only maked sense to me  inside a function and the context applyed to the function call. thanks!

(twey) Yes, the global ‘this’ is kind of magic.  Also, JS is also an OO language.  :þ



Well, an old javascripter that admit it is magic related to this issue. It is a mystery indeed.

But immediately we we start to suspect a relationship between the keywords var, this and with.

The first to notice is that, when declaring a named value, if we omit the keyword 'var' (when declaring a variable) or if we omit the keyword 'this' when declaring an attribute then the name is assigned as a property to the global object, in the case of browsers the window.  The following code try to show what i'm talking about:
<script>
// the Global Object. Because we are in the top-most context (no function sourrounding us) even if we are declared with 'var' we are global variables (properties of the current global object 'window'). This is an special case!
var GLOBALOBJECT=this; 
var Class1 = function(){
    this.attribute1="hello";
    nonattribute1="world"; //missing 'this' so this is a global veriable, this is a property of GLOBALOBJECT    
    var DeeperContext = function() {    
     var var1="just a veriable"; 
     global2="missing var so i'm global"; 
     this.attribute2="instance attribute";
     nonattribute2="missing this so i'm global"; // notice that DeeperContext constructor is executed on a second level context, but nonattribute2 name is assigned to the GLOBALOBJECT, not the parent context as some may expect.  
    }
    this.attribute12 = new DeeperContext(); 
}
var c1 = new Class1(); 
console.log(GLOBALOBJECT); //at this point the GLOBALOBJECT contains 2 new properties nonattribute1 and nonattribute2
</script>

About me

this is, Sebastián Gurin - cancerberoSgx - as a software developer


These are some notes about the author of this blog with some links to his work, mostly related to my free software projects.

 

Developer profile

I have several open source software projects in many sites, but mostly in code.google.com and github.com. These are the links to my profile on each of them: 

 

How all this started? 

When I first saw a computer I always wanted to "solve its secrets" so I can use it for my own purposes. Have the luck of love programming, since the very beginning, and at that time (the 90's) the Internet wasn't what it is today.... TODO

What I like the most

TODO

My projects

TODO

miércoles, 29 de mayo de 2013

Get final HTML markup of a JavaScript application using rhino - envjs

This article briefly describes how to dump the final HTML markup of any web site using serverside tool rhino-envjs. We will work into the release root folder so "cd" to it.

step 1 - download latest envjs release (as this writing 1.2) and uncompress it.
step 2 - download ant and run "ant" on the previously uncompressed envjs folder. This should build envjs. step 3 - create the file test1.js with the following content: 
load('dist/env.rhino.js');
var url = "http://jquery.com"; 
window.location = url; 
print(document.innerHTML+"");
step 4 - in a shell enter the following command:
java -cp rhino/js.jar org.mozilla.javascript.tools.shell.Main \
  -opt -1 test1.js > test1.html

If everything was fine you can open the generated file test1.html with firefox and see the jquery generated markup, not a very visual replica but often useful for SEO and those. For each JavaScript error a Java exception will be printed on stderr.

In my case this is useful for 100% JavaScript web applications SEO support.

domingo, 17 de marzo de 2013

Make a single .jar from many

What if  some project require several Java .jar files and for some reason you want to work with a single .jar with all of them inside? Or what if want to distribute your library, that requires several .jar to work, in a single .jar so it is less painful to new users? If you have permission on the other jars this is not a problem at all. The following is a sh script that uses the unzip tool:


rm -rf jartmp
mkdir jartmp
cd jartmp
unzip -u ../path/to/someJarA.jar
unzip -u ../path/toother.jar
unzip -u ../ahother/one.jar
zip -r myLibrary-alldeps.jar *
cd ..
rm -rf jartmp

The previous script will generate a myLibrary-alldeps.jar that contains the three previousgiven .jars files, all inside. This way the user of your library do not have to download your library's dependencies. Hope this serves somebody.

martes, 4 de diciembre de 2012

Guidelines for writing GWT Overlay types

Guidelines for writing GWT Overlay types

This post is related with an older post Eclipse templates for overlay types about the same topic. You can find eclipse java code templates for code proposed here in that section. Now, that I have my ideas more clear and tested this is a summary.

When writing overlay types we have to take in consideration two main ideas:

  • we are writing a Java class that will be used by Java users
  • we are overlaying a JavaScript object with an API designed to be used in JavaScript

The following presents some guidelines learned and adopted in my GWT libraries porting javascript libraries like YUI and raphaël to GWT using 100% overlay types for a zero overhead Java API implementation.

Constructor

Use a static method with a simple name like create() or newInstance() that return an empty object or an object with some desired initialization state. Example:

public class MyOverlay extends JavaScriptObject {
 protected MyOverlay(){}
 public static native final create()/*-{
  return {}; 
 }-*/;
}

Properties

In Java we use the Bean convention for accessing obejct attributes / properties with getters and setters methods:

public class MyOverlay extends JavaScriptObject {
 protected MyOverlay(){}
 public static native final create()/*-{
  return {}; 
 }-*/;
 public native final String getColor()/*-{
  return this.color; 
 }-*/;
 public native final void setColor(String color)/*-{
  this.color=color; 
 }-*/;
}
End User example code:
MyOverlay o = MyOverlay.create(); 
o.setColor("red"); 
aController.method1(o);

Nevertheless, we must remember that "we are overlaying a JavaScript object with an API designed to be used in JavaScript". In JavaScript we normally are able to define an entire object in a single statement. For accomplish this in Java we need our setters methods to return the this object so we can perform method chaning. Also, but not so important, se omit the prefixes get/set for there methods

public class MyOverlay extends JavaScriptObject {
 protected MyOverlay(){}
 public static native final create()/*-{
  return {}; 
 }-*/;
 public native final String color()/*-{
  return this["color"]; 
 }-*/;
 public native final MyOverlay color(String color)/*-{
  this["color"]=color; 
  return this; 
 }-*/;
}

End User example code:

aController.method1(MyOverlay.create().color("red")); 

Much more similar to its JavaScript common counterpart aController.method1({color: "red"}), don't you think ?

Some notes:

  • We use setters and getters without the prefixes "get" or "set", so our method names are the same as the property name. This make it easy to use IDE tools like eclipse Java Code templates for generating the getter/setter code automatically.
  • In JSNI code we use string literals this["color"] instead variable names like this.color so the closure compiler (available optionally in GWT > 2.5) don't mess up JavaScript Object property names.

For those Java convention lovers I think it wouldnt cost too much to have "normal" java bean getters and setters AND this kind of shorter accessor methods for those who like to define object more "a la" javascript.

About Performance

Unfortunately the proposed code style here adds some overhead to the JavaScript code output produced by the GWT compiler. In the following example, I have created 2 JSOs, one called NormalBean that follows the Java Bean getter/setter conventions and other one called JsFriendlyBean that uses the solution proposed here with setters that return 'this' for method chaining. Then I use them both and compared the resulting JavaScript output code by GWT compiler using -style PRETTY and -optimize 9 compiler options. This is the result:

Java Sources:

NormalBean normalBean = NormalBean.create();
normalBean.setColor("turttlered1");
normalBean.setAge(13);

JsFriendlyBeam jsFriendlyBeam = JsFriendlyBeam.create()
 .color("turttlered2").age(14); 

Window.alert(normalBean + " - " + jsFriendlyBeam);

JavaScript output:

normalBean = {};
normalBean['color'] = 'turttlered1';
normalBean['age'] = 13;
jsFriendlyBeam = $age($color({}, 'turttlered2'), 14);
$wnd.alert(normalBean + ' - ' + jsFriendlyBeam);
...
function $color(this$static, val){
  this$static['color'] = val;
  return this$static;
}
function $age(this$static, val){
  this$static['age'] = val;
  return this$static;
}

As you can see, the setters of the NormalBean are inlined in JavaScript with zero-overhead while the setters of JsFriendlyBean are not. In the later, JavaScript functions $age() and $color() are created and called and that adds little but some overhead.

I cannot find a workaround for this. Tried with single JSNI statements like the followings but the result is the same:

public native final JsFriendlyBeam age(int val) /*-{
 return (this["age"]=val, this); 
}-*/;
and
public native final JsFriendlyBeam age(int val) /*-{
 return (this["age"] = val || true) ? this : null;
}-*/;

If anybody has an idea about how this setters can be written so they are inlined in JavaScritp output, pleas share it with me :)

martes, 27 de noviembre de 2012

HTML to valid XML code using tidy.

Sometimes you copy HTML source code from a web page that is not valid. Some tools, like mine htmlminimizator requires valid XML fragments to work. In this case we need to transform HTML sources to valid XML. I'm doing it fine with the tidy utility like this.

First I suppose you have your HTML code fragment in a file called test1.html, then I perform :

tidy -asxml -ashtml -utf8 test1.html 

Hope that can be of help to others in a similar situation.