Friday, December 21, 2012

Installing and working with CoffeeScript in Netbeans

Netbeans Plugin page
Netbeans already has excellent support for JavaScript fortunately it also has a plugin for CoffeeScript written by a guy name Denis Stepanov. Although its missing a "set target folder" feature and only supports CoffeeScript 1.3.3, its still good. The thing here is that it just works. I don't need to install node.js (and the associated npm) to translate CoffeeScript to JavaScript.

To add CoffeeScript support in Netbeans, we start off downloading the plugin. When done you install it via the plugin page. You should restart Netbeans after and that's it. 

After the restart, try creating a new project. There should be a new project type called CoffeeScript Application. And you should be able to add CoffeeScript scripts to existing web projects also. Just remember the limitation that where you wrote your CoffeeScript is also where the output JavaScript will be saved to.

Next post will be about CoffeeScript data types and functions.


Thursday, December 20, 2012

My course to learn the good parts of JavaScript -> CoffeeScript


JavaScript is big. A lot of stuff are now getting built with JavaScript: mobile apps, desktop apps, database shells, etc.

Now, if you write enough JavaScript you will learn that JavaScript is can be a mess especially on large projects. Even if you followed Douglas Crockford's JavaScript the good parts, its quite verbose. This is where CoffeeScript comes in. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way. And this is my course for learning CoffeeScript.

My course works out to something like this:

1. Installing and working with CoffeeScript in Netbeans
2. CoffeeScript data types and functions
3. CoffeeScript control structures
4. CoffeeScript prototypes and classes
5. CoffeeScript and JQuery



Saturday, December 8, 2012

Steam on Linux: Need to update them Nvidia Driver

Valve is now running a closed beta for its Steam platform on Linux; more specifically Ubuntu. This is a good thing since I do believe what's holding Ubuntu (and Linux in general) back from the mainstream is the lack of good games. I bet down the line, I will be building a Ubuntu gaming rig. This isn't really a bad idea but them video driver repositories need to catch up.

Right now if you let Ubuntu select your Nvidia driver from the official repositories, it will install the 295.xx driver which makes Steam on Linux unhappy. So we need to update it to, at least, 304.xx driver. The least painful way to do this is via ppa rather than downloading the driver from the Nvidia site, shutdown X and sh run the installer.

So to install the Nvidia 304.xx driver on Ubuntu 12.04; Open a terminal and run the following commands:

# Add ppa repo
sudo apt-add-repository ppa:ubuntu-x-swat/x-updates
# Update software list
sudo apt-get update
# Install drive
sudo apt-get install nvidia-current nvidia-settings

You should be downloading about 70ish MB worth of stuff. Restart and then configure it via:

# Configure video settings
sudo nvidia-settings

So that's it and you should be downloading the 25 available games and then playing. I'm download Team Fortress 2 and getting my sandvich.

Wednesday, November 28, 2012

Multiple hyperlinks on an area (or image)

slicing + absolute positioning
I was working on a website which had a front banner that looked like a spice cup board and the owners wanted when you click on a certain "jar" it takes you to a certain page in the site. But they already had someone working on this before me and decided to use image slices + absolute positioning.

I'm not saying its a bad solution, I just don't like dealing with multiple images and other penalties (ie. maintenance) associated with it. I would rather go with a single large image and define regions in it that's clickable. That's where image maps come in.

Image maps enable me to define multiple links within a single image. It's clean and doesn't involve any JavaScript or CSS just plain HTML5 markup.

You start off by declaring the image:

<img scr="bigbanner.jpg" alt="frontpage banner" border=0 usemap="#hotspots"/>  

The new thing here is the usemap attribute. The value of the usemap attribute must be the same with the map id. The map element acts as a container for specifications regarding the map's active areas (ie. hotspots), where are define as area elements within the map.

 The matching map markup would be:

<map name="hotspots">  
      <area shape="rect" coords="20,20,170,170" href="somepage2.html"/>  
      <area shape="circle" coords="250,175,50" href="somepage3.html"/>  
      <area shape="poly" coords="117,241,277,312,84,370" href="somepage4.html"/>  
 </map>  

The shape of the area element is influenced by the *duh* shape attribute. Rectangles and circles are fairly easy to use but watch out for with poly. Its the most flexible and most tricky to use. In the example, I'm creating a "triangle"; the first 2 values in the coords form the first point, the second 2, form the second point and the third pair gives use the third (end) point. Given enough coords information, I can make the "poly" area follow the outline of any item on any image.

As for the coordinate values, I just have to remember that the top left corner of the image is 0,0. Also, map is a non-visual element so I can put it anywhere on the page markup.

Friday, November 16, 2012

Making sense of WPF layouts

I started out as a Swing developer and I have the Java Foundation Classes book to prove it. But Swing never really caught on and so I started working with C# and WPF. Windows Presentation Foundation (WPF) isn't what you'd expect for making desktop applications. It kinda feels like making web applications since you "describe" the UI via a XML-like language called XAML. This isn't really a bad thing just different.

I could go on about WPF being different but at the end of the day the foundation of a desktop app is the layout it's built upon. This is what I've learned.

  1. By default, WPF apps have a base "Grid Panel" layout. Get rid of it and use "Dock Panel" as your base.
    Dock Panels are the same to Border layout in Swing. The idea is to place the menu on top (DockPanel.Dock="Top"), status bar bottom (DockPanel.Dock="Bottom") and put a "Grid Panel" at the center. Now you have a well-behaved desktop app that reacts well to window re-sizes. 
  2. The Grid Panel is like Swing's GridBagLayout only easier to use.
  3. Use the Alignment properties in combination with Margin to position elements in a panel; avoid fixed positions (using the x,y coordinates) unless you have a really, really good reason to do so. They don't work out so well when tested against various screen resolutions.
  4. Also, the same for height and width. Use min and max properties instead.
  5. Don't use blank "label" components to separate components. Use the margin and padding properties. For example, if 2 buttons are side by side, don't put a blank label in-between them to create space.

Friday, October 26, 2012

In Android: Long press = right click

Share anyone?
I just sat through an IPad demo for education. The demo was basically about using IPad as a teaching tool for college/university level instruction. It was pretty good but then I notice something wrong amiss with the IPads. You can't just share data between apps like I just can't just pass links from say Safari to Chrome.You have to do a copy-paste procedure which is kinda stupid and unnecessary.

For Android old-timers, doing stuff like that is a piece of cake. Just do a long press and you will be presented a "Share via" option and then you can send where you want it and the target know what to do with it.

New Android people seem to be limited to point-click and swiping with their phones and/or tablets. If they do a long presses on stuff in their phones they'll discover a whole new layer of features to play around with.

Android programmers know this as "Intents". In Android, the 3 core components of an application — activities, services, and broadcast receivers — are activated through messages, called intents. Thus allowing my app to pass data and stuff to other apps. That's cool in every which way you look at it. Which begs the questions:

Why the copy-paste procedure Apple?

Edit: Apparently, Windows Phone does the same with Bing Search and Internet Explorer. That's sad.

Saturday, October 20, 2012

Drupal Extended Filtered HTML tags

In Drupal (no matter the version), content editing uses text filters to "sanitize" the output. The text format contains filters that change the user input, for example stripping out malicious HTML or making URLs clickable. One of these filters is "Filtered HTML"; Due to security reasons, enabling Full HTML is only an option for trusted users.

But the default set of allowed HTML tags for "Filtered HTML" is quite narrow and limited. So, the first thing to do is to extend the list of allowed tags to:

<a> <p> <span> <div> <h1> <h2> <h3> <h4> <h5> <h6> <img> <map> <area> <hr> <br> <br /> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <em> <b> <u> <i> <strong> <font> <del> <ins> <<sub> <sup> <quote> <blockquote> <pre> <address> <code> <cite> <embed> <object> <strike> <caption>  

But remember, "Filtered HTML" not only strips disallowed tags, but also strips inline style definitions.

Saturday, October 13, 2012

Installing Maven 3 in Ubuntu 12.04 Precise

Ubuntu needs to no explanation and Maven is software project management tool. It manages software dependencies and how your code is compiled and deployed. Its pretty handy because now I don't have to hunt down jars that my other jars need and no more copying the binaries to target folders.

Unfortunately, the Ubuntu repos are a bit slow. The repos only have Maven2. Now, let's get to installing Maven3.

1. Install the Nate Carlson's PPA for Maven3
2. Open a terminal console and type in: sudo apt-get update
3. After update finishes, type in: apt-get install Maven3

You now have Maven3 installed but you can't run it from the terminal because you didn't set the paths. If you try to type: mvn --version; That should fail. To fix this you have to make a symbolic link from where Maven3 is installed to where it can be run it "globally" from the terminal.

$ sudo ln -s /usr/share/maven3/bin/mvn /usr/bin/mvn

You just created a symbolic link in /usr/bin/mvn. The mvn command now should work in your terminal.

Update (3/29/2013):
Caution: command "sudo add-apt-repository ppa:natecarlson/maven3" did not work on my Ubuntu and and had to run "sudo add-apt-repository -rm ppa:natecarlson/maven3" to get my apt-get to work again. ~AmirHD
See this Stackoverflow thread.

Wednesday, September 12, 2012

WHY U NO USE ROBOGUICE!?!

That's exactly how I ask myself after trying out Roboguice 2 after a tutorial or two.

I discovered Roboguice after a guy in my facebook group posted a link to an excellent Android stack named android-bootstrap. Android-bootstrap is boilerplate application that includes tons of great open source tools and frameworks. I'll save this one for another time.

Back to Roboguice, roboguice adds dependency injection patterns to Android development. It adds annotations that makes writing Android applications like Spring apps in the J2EE space. It basically takes something that looks like this:

class AndroidWay extends Activity { 
    TextView name; 
    ImageView thumbnail; 
    LocationManager loc; 
    Drawable icon; 
    String myName; 

    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main);
        name      = (TextView) findViewById(R.id.name); 
        thumbnail = (ImageView) findViewById(R.id.thumbnail); 
        loc       = (LocationManager) getSystemService(Activity.LOCATION_SERVICE); 
        icon      = getResources().getDrawable(R.drawable.icon); 
        myName    = getString(R.string.app_name); 
        name.setText( "Hello, " + myName ); 
    } 
} 

To something like this:

class RoboWay extends RoboActivity { 
    @InjectView(R.id.name)             TextView name; 
    @InjectView(R.id.thumbnail)        ImageView thumbnail; 
    @InjectResource(R.drawable.icon)   Drawable icon; 
    @InjectResource(R.string.app_name) String myName; 
    @Inject                            LocationManager loc; 

    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main);
        name.setText( "Hello, " + myName ); 
    } 
} 

That's some kind of witchcraft if you ask me but still you can't argue how convenient this style of programming can be and we all know programmers are lazy as sin.

Saturday, September 8, 2012

Staring at boobs gave me an idea for Underscored Knockout

I have been using knockout.js ever since I discovered it. Since that time also, my JavaScript chops have been getting good to the point I discovered (and using) underscore.js. Let's face it, array and/or collections handling in plain JavaScript isn't pretty.

Then a couple of days ago, I was staring that this random lady's cleavage on the ride to work - had my sunglasses so she was none the wiser - that I suddenly had a great idea - Knockout's arrays with Underscore's array functionality. And I was like, "FUCK! Why did I think of this sooner?!" Needless to say, I forgot about the boobies.

When I got to work, I fired up my browser and searched the web if someone got the same idea thankfully, Kamran Ayub thought about it while driving home from work - UnderscoreKO. It's was exactly what I was thinking! If I had discovered underscore sooner, I bet I would have wrote this beauty of a library.  Now I can stop writing half-ass functions/closures of my design to merge arrays or search it for certain values and get to writing short, concise, functional Knockout code.

Thank you Kamran!


Sunday, September 2, 2012

Quick & Dirty Tabs on Drupal nodes

I just want a dead simple tab on a Drupal node but sometimes Drupal (with the internet) will just bend you over and spank you.

If you are reading this, I bet you found Quicktabs and read katbailey's "Go forth and tabbify" post but you came to the conclusion that its either:
  1. To complicated; You suspect that the hook_page_alter() function is gonna bite you in the ass down the line 
  2. Its not what you need 
I'll also bet you tried a few other approaches like leveraging the jQueryUI tabs like what Matt did and still found that it wasn't what you want. So now what? Well, you can do what I did - the quick and dirty tabs. 

My quick and dirty tabs is just javascript, html markup and a Omega subtheme. And it just involves 4 steps.

1. The HTML markup. You will use this inside your node.tpl.php or equivalent node template override. Notice the page-control and page-sections parts of the markup.
<div class="com-profile">  
      <div class="page-control">  
           <ul class="myQDtabs">  
                <li class="active"><a href="#">Basic Information</a></li>  
                <li><a href="#">Photos</a></li>  
                <li><a href="#">Forum</a></li>  
                <li><a href="#">Contact Persons</a></li>  
           </ul>  
      </div>  
      <div class="page-sections" style="display:none" >  
           <div class="section">  
                <div class="info">  
                     ...  
                </div>  
           </div>  
           <div class="section" style="display:none" >  
                <div class="gallery">  
                     ...  
                </div>  
           </div>  
           <div class="section" style="display:none" >  
                <div class="forum">  
                     ...  
                </div>  
           </div>  
           <div class="section" style="display:none" >  
                <div class="contactperson">  
                     ....  
                </div>  
           </div>  
      </div>  
 </div>  

2. The Stylesheet. I settled on a pill type of tabs. Just add these styles on the main subtheme stylesheet.
3. The Javascript. This is a tricky bit. If you have read Matt's post about Drupal and jQueryUI tabs, you'll know that Drupal allows other javascript frameworks so Drupal uses jQuery's .noConflict() function. This forces you to write your jQuery withouth that the '$' alias. Oh, create this script somewhere inside your subtheme.
jQuery(document).ready(function(){
    QDtabs('.myQDtabs','.page-sections','click');
});

//function-type tab switching
QDtabs = function($tabs,$tabcontent,method){
  jQuery($tabcontent + ' .section').eq(0).fadeIn();
  jQuery($tabs + ' li').eq(0).addClass('active');
 
  jQuery($tabs + ' li:not(.active)').die().live(method,function(e){
  e.stopPropagation();
  
  var $self = jQuery(this);
  var index = $self.index();  
  $self.addClass('active').siblings('.active').removeClass();  
  jQuery($tabcontent + ' .section').hide().eq(index).stop(false,true).fadeIn();
  
  return false;
 })
}

4. And the last step is making my Omega subtheme load the custom script. Omega has a particular way of adding custom javascripts.

libraries[my_script][name] = QD custom script
libraries[my_script][description] = Quick and dirty tabs
libraries[my_script][js][0][file] = my_scripts.js
libraries[my_script][js][0][options][weight] = 15

The last thing to do is a bit of housekeeping - Clear your Drupal cache and turning on my_script inside my theme's admin interface.


Tuesday, August 21, 2012

My CodeIgniter + Bootstrap starter kit


I thought I would share my CodeIgniter + Bootstrap starter kit.

Highlights:
- CodeIgniter 2.1.0 codebase included
- Bootstrap 2.0.3 theme with its JS extensions in a single file
- jquery 1.7.1 and knockout 2.1 included
- default controller: home/start.php; default view: home/start.php

To use, it just drop inside your /htdoc or /var/www folder.

Download the zipped file or clone it from my bitbucket mercurial repo. To clone:

hg clone https://bitbucket.org/jaypax/cibootstrap

Have fun with it.

Updated 9/29/2012

  • Updated Bootstrap to 2.1.0 
  • Added bootstrap-responsive.css (min version included)
  • Updated CodeIgniter to 2.1.2 
  • Added underscore.js 
  • Added underscore-ko.min.js (see https://github.com/kamranayub/UnderscoreKO
  • Added jquery-1.7.1-vsdoc.js

Friday, August 17, 2012

Autobind All Tapestry5 services!

Norman Franke, Dmitry Gusev and a bunch of other guys in the Tapestry5 mailing list show us a very cool way to bind services via package traversal. No more binder declarations for DAO services several miles long.

The technique they showed made me want to smack my older self - Why didn't you think of that!? This autobind technique basically just needs a bit of planning - a "convention" if you will. The idea is to put the "implementation" package as a folder below your DAO interfaces. Typically, you would append an "Impl" tag to your DAO interfaces so for example: UserDAO = UserDAOImpl and then place them in the correct packages: com.myapp.dao for the DAO interfaces and then com.myapp.dao.impl for the DAO implementations. The rest is done in the AppModule of Tapestry5.

...
public static void Bind(ServiceBinder binder) throws ClassNotFoundException  
{  
   autoBindServices(binder, ProjectDAO.class.getPackage());  
   .....  
}  
private static void autoBindServices(ServiceBinder binder, Package interfacePackage) throws ClassNotFoundException  
{  
  List<Class<?>> interfaces = Utils.getClassesForPackage(interfacePackage.getName());  
  for(Class intf : interfaces)  
  {  
     String className = interfacesPackage.getName() + ".impl." + intf.getSimpleName() + "Impl";  
     try  
     {  
         Class impl = Class.forName(className);  
         binder.bind(intf, impl);  
     }  
     catch(ClassNotFoundException e)  
     {  
         logger.warn("Class not found during autobinding: {}", className);  
     }  
  }  
}
Very cool stuff.

Wednesday, July 18, 2012

Tapestry-hibernate and that ValueEncoder exception

I love tapestry5 but sometimes it just does something bad. In this instance, its a ValueEncoder error you get when your are using the default transitive dependencies from Maven. If just followed the "Using Tapestry with Hibernate" you might end up with a HTML 500 error with tapestry5 telling you about a ValueEncoder exception.

A first I thought it was my stuff (Netbeans + MSSQL + Glassfish) but I eventually figured out it wasn't by process of elimination.

The way to fix this is to change something in your POM file. Look for the hibernate dependency entry. You will notice that its using older version of hibernate.

<dependency>  
    <groupId>org.hibernate</groupId>  
    <artifactId>hibernate</artifactId>  
    <version>3.2.5.ga</version>  
</dependency>  

I just changed this to to use the newer version of the hibernate. Also changed it from hibernate to hibernate-core. So the dependency would read:
<dependency>  
    <groupId>org.hibernate</groupId>  
    <artifactId>hibernate-core</artifactId>  
    <version>4.1.4.Final</version>  
</dependency>  

It would be also a good idea to update the rest dependencies.

EDIT: Apparently the Tapestry-hibernate module doesn't like 4.1.4.Final version of Hibernate. The Hibernate Session will fail when you use it. The fix is just to revert Hibernate to anything in the 3.xx branch like 3.4.xx.

Friday, July 13, 2012

Install local jars with maven

I don't know why it took me a long time to write about this.

There are a lot of Java jars that isn't on the maven repository but you still need or like to manage these jars via Maven. To install a jar into your local Maven repo:

 
mvn install:install-file -Dfile={file} -DgroupId={groupname} -DartifactId={artifactname} -Dversion={versionnumber} -Dpackaging=jar
 
For example, you want to add Microsoft MSSQL jdbc driver into your local Maven repo then the procedure would be:
  1. Download and extract the file.
  2. Open the command line and type in:
  3.  
    mvn install:install-file -Dfile=sqljdbc4.jar -DgroupId=com.microsoft.sqlserver -DartifactId=mssqljdbc4 -Dversion=4.0 -Dpackaging=jar
     
    
You can then add it to your project with:
<dependency>  
<groupId>com.microsoft.sqlserver</groupId>  
<artifactId>mssqljdbc4</artifactId>  
<version>4.0</version>  
</dependency>

Thursday, July 5, 2012

What bullshit is this Cisco?! I call shenanigans!

I use and endorse your stuff Cisco but no more! You heard me, NO FUCKING MORE! You Cisco just plain pissed me off! What is this bullshit in your new router line about I must use your Cisco Connect Cloud or get my router bricked? And your license is bullshit, It reads:

You agree not to use or permit the use of the Service: (i) to invade another's privacy; (ii) for obscene, pornographic, or offensive purposes; (iii) to infringe another's rights, including but not limited to any intellectual property rights; (iv) to upload, email or otherwise transmit or make available any unsolicited or unauthorized advertising, promotional materials, spam, junk mail or any other form of solicitation; (v) to transmit or otherwise make available any code or virus, or perform any activity, that could harm or interfere with any device, software, network or service (including this Service); or (vi) to violate, or encourage any conduct that would violate any applicable law or regulation or give rise to civil or criminal liability. 

You can brick my device if I browse or download porn or warez? YOU GOTTA BE FUCKING KIDDING ME!

I call shenanigans!
 

Monday, July 2, 2012

Checking out Brackets editor

So the guys over at WeAreKiss told me to check out Brackets. Brackets is this new open-source code editor built with the web for the web. I'm trying it out to see if it lives up to its slogan (or "hype"). Don't expect much of it just now since its sort of in "Alpha". Think experimental build. Using it though isn't really a hassle you just download it, unpack and find the binaries and run with it.

Brackets Code Editor
I have been running Brackets for a few hours now and it's pretty nice to use when editing JavaScript, CSS (Less format) and HTML5. Not everything was that smooth though. I had a rough time figuring out the preview thing with this.

I like the jsLint add-on. It comes handy when I'm editing JavaScript files although it will nag to no end about how terrible my JavaScript is. ;)

But there's one thing, I wish Brackets had and that's a concept of a "project" folder like in inotai's inType editor.

Other than that, let's see how it goes in a week or so.

Sunday, June 10, 2012

Drupal taxonomy for Philippine Regions & Provinces

Drupal Filipino developers might find this useful, A CSV formatted taxonomy for Philippine regions and provinces. It's hierarchical in format and you can import it into your Drupal site using taxonomy manager.

Here is a small sample of the taxonomy:

ARMM (Autonomous Region in Muslim Mindanao)
Basilan
Lanao del Sur
Maguindanao
Tawi-tawi

CAR (Cordillera Administrative Region)
Abra
Apayao
Benguet
Ifugao
Kalinga
Mountain Province

Sorry, cities are not included in this taxonomy.

Download Philippine regions and provinces CSV.

The data is from www.pinas.ph website.

Tuesday, June 5, 2012

One word, Hubris.

So, I got a new video card after a long time. I got a GTX550 Ti from a Afox. It's a very nice mid-range card and its just priced right.The hubris part comes when I installed the damn thing.

Just so you know, I haven't tinkered with my desktop for a long time. And for that long time, I always thought I know "the" shit when it comes to hardware. "I know what I'm doing, motherfucker!", I always thought to myself. The universe was about to bitch-slap me seven ways to Tuesday.

The 12v source I forgot to plug-in
So, open the box, skipped the instructions, removed my old video card (its a XFX HD4650 - it has served me well) and dropped in my new card. Got the new drivers, didn't use the driver it came with and the restarted my box, no problem.

Ohhhh, I felt good, godlike even. Then it happen, none of my games would play. WTF! No just play, it even crashed my whole box. Tried it twice just to make sure, then got on the internet for some answers.

1. Hacked games config file - didn't take
2. Downgraded driver - fail
3. Moved card to another slot (got a SLI-ready motherboard) - also failed

I started to believe that I got a bad card until I stumbled into this hardware forum which from the looks of it was mostly Chinese. This guy basically said, "Hey asshole, did you plug in the 12v source?" He was right, I was an asshole, I didn't know that the new cards needed a 12v source. I always thought they all draw power from the PCI-E rail.

Moral is "READ THE GODDAMN MANUAL".

Wednesday, May 30, 2012

Which thing to use: phonegap or codename one?

I have been puttering around with Phonegap and then I stumbled upon CodenameOne. Both are frameworks for making applications for mobile devices and will run on Netbeans (although Android support for Netbeans could be better). So which leads us to the question of the moment: which thing to use?

Let's start with what's common with the two:

1. One code base for almost all mobile platforms: IOS, Android, Blackberry and Windows Phone. PhoneGap is the only one that (right now) supports Windows 7. CodenameOne promises to support it soon. CodenameOne now supports Windows Phone.

2. Both use the pay for building app model. Assuming that you are using the free account; With Phonegap you are limited to 1 app/1 collaborator while CodenameOne limits you to 100 build credits every month and 1 app at the time.

PhoneGap Codename One
IDE Support Optimal on Eclipse; Can be used on Netbeans but stifled because of Netbean's weak support for Android. Has an excellent plugin for both Eclipse and Netbeans
Tooling HTML5, CSS and JavaScript Just Java
Supports IOS, Android, BlackBerry, WebOS, Symbian, Windows Phone IOS, Android, BlackBerry, J2ME, Windows Phone
Documentation Excellent Also excellent
Feels like ...making a website; lots of JavaScript ...old school Swing desktop development

So which one to use? Truth be told, that depends on what you are comfortable with. If you're an old hand with Java and you want to make mobile applications then (I suggest that you) go with Codename One but if started out as a web developer then you might want to go with PhoneGap.

Although both fill the mobile development niche, but have different approach vectors. Different strokes for different folks.

Sunday, May 20, 2012

Be a game programmer they said

Be a games programmer they said. It's going to be fun they said.

Making games from scratch 10 years ago was hard. Try reading Tricks of the 3D Game Programming Gurus-Advanced 3D Graphics and Rasterization by Andrew LaMothe. The Math alone will make you cry, I did. I thought making a game for Android will be equally as hard. Glad to know there's AndEngine.

AndEngine is a framework for building games on the Android platform. It provides a lot of abstractions so as a programmer you don't have to deal with the low-level details. I particularly like the AndEngine physics extension - rolling your own physics engine is no walk in the park.

A few pointers on getting started with AndEngine:

1. You'll need an actual phone for this. The AndEngine examples can't run on the virtual devices since they can't support the OpenGL stuff.
2. AndEngine is designed for 2D not 3D.
3. As for the turtorial, when done you will get errors. Don't just give up, troubleshoot it. Giving up? What's the fun in that?
4. AndEngine is open-source.

Now, what game should I be making? Any suggestions?


Friday, May 4, 2012

My week of Sproutcore and Netbeans

After running around with knockout, I decided to try out sproutcore for a week. The first task was getting it installed. My dev maching is running the lastest from Ubuntu (I think its 12.04 LTS). My install experience wasn't exactly pleasant. I followed the Sproutcore's install guide to the letter and it resulted is a dozen or so of can't compiles and missing libs - I did fix the errors eventually.

With my Sproutcore running, I started following the tutorials and by the "TodosThree" part I was writing a fair amount of JavaScript. I need an IDE for this work - Netbeans.

Sproutcore and Netbeans

Netbeans doesn't officially support Sproutcore but that isn't really a problem. Sproutcore is like 95% JavaScript and Netbeans has excellent JavaScript support. It's just a matter of "creative" use of Netbeans. The trick is to create a "PHP Application with Existing Source" and point it to your Sproutcore project folder. Here's the procedure:

  1. New Project > PHP Application with Existing Source
  2. Sources Folder should point to your Sproutcore project folder (not the apps folder)
  3. Change the Project URL to https://localhost:4020 also remove the index file
  4. And your done!
As for the rest like running the "sproutcore gen app" commands. You'll have to run that outside Netbeans and on the terminal. Its not really a big deal. 

BTW, code intellesense amazingly also works, I didn't expect it to work but it does. BONUS!


Monday, April 23, 2012

My website starterkit - 1kb Grid, Less, Formalize & Reset

I made starter kit for web development. It's a simple 960 grid-based kit with Less CSS. My starter kit is based on Tyler Tates' 1KB CSS grid, but it also has other stylesheets like:
  1. Meyer's Reset - to reset everything
  2. Formalize - for well mannered forms. 
  3. Style.less - This is where you should be adding your CSS, in the Less format.
I also turned Formalize and Grid into Less style sheets so I can combine all three into a single style sheet.

The starter kit also has jquery1.7 (via CDN) already added. You might want to change this during development.

To get the most of my starter kit you'll need something to turn Less style sheets to valid cascading style sheets. Try out Winless or Simpless.

You can clone my mercurial repo at https://bitbucket.org/jaypax/grid10kless if you want to try it out.

In case your wondering the code is DBAD licensed.

Wednesday, April 18, 2012

Getting knocked around while dealing with a check box

I've been using Knockoutjs heavily these couple of weeks and I think it has place in my programming toolkit. With Knockout, my markup is significantly cleaner and my pages with form elements are not a pain.

Knockout isn't that hard to use. I bet you can get a good handle of it once you finish some of the tutorials. Knockout, also has a couple of cool extensions like combining it with Kendo. I got good with Knockout but I had stuff to learn.

I had to implement a feature where an "admin" can select a "role" for new accounts. To select a role, admin had to select one of three check boxes in the page. The data for the check boxes is from JSON. Not a big problem since Knockout plays nice with jQuery.

So what exactly is the problem then?

The problem was that I needed to capture the "checked" value and push it into a new array. You would think that this a straight-forward preposition. So my first attempt went something like:

My Knockout script
<script type="text/javascript"> 
...{some code omitted for clarity}
        function roleModel(id, name, description) {
            var self = this;
            self.RoleId = id;
            self.RoleName = name;
            self.Description = description;
        }

        function viewModel(){
            var self = this;
            self.AvailableRoles = ko.observableArray();
            $.getJSON("/Role/GetRoles", function (data) {
                for (var i = 0; i < data.length; i++) {
                    self.AvailableRoles.push(new roleModel(data[i].RoleId, data[i].RoleName, data[i].Description));
                }
            });
            self.Roles = ko.observableArray();
        }
...{some code omitted for clarity}

        ko.applyBindings(new viewModel());

My Markup (HTML5)
<div data-bind="foreach: AvailableRoles">  
    <input type="checkbox" data-bind="attr: {value: AvailableRoles}, checked: Roles"/>  
    <span data-bind="text: RoleName"></span>  
</div>  
Notice the Roles and AvailableRoles properties. Apparently you can't bind the AvailbleRoles "directly" into the value field of the checkbox.

After looking around the web, I hit on the that idea I needed an intermediary field to store a key (thus I can bind it into the checkbox's value field) then I can use that key to retrieve the right role object from the AvailableRole object which is an array of role objects and store it in the Role property.
            
            self.Roles = ko.computed(function () {
                return ko.utils.arrayMap(self.SelectedRolesIds(), function (roleId) {
                    return ko.utils.arrayFirst(self.AvailableRoles(), function (item) {
                        return item.RoleId == roleId;
                    });
                });
            });
            self.SelectedRolesIds = ko.observableArray();
That's the SelectedRolesIds property in my viewModel. I also changed the Roles propety to be a computed field to make it "dependent" on what Role Ids are present in the SelectedRolesIds property. You still have to make changes to the markup. This all made nice with knockout utility functions - arrayMap and arrayFirst.

<div data-bind="foreach: AvailableRoles">  
    <input type="checkbox" data-bind="attr: {value: RoleId}, checked:$root.SelectedRolesIds"/>  
    <span data-bind="text: RoleName"></span>  
 </div>
The AvailableRoles property stays the same. 

Wednesday, April 11, 2012

Debugging Javascript: Blackbird, JSLint & dumpProps

JavaScript can be difficult to debug despite the tooling we got - IDE, Firebug, etc.

A naive way of doing debugging in JavaScript is to use alert() function. Unfortunately, alert falls short in this respect. Enter Blackbird. Blackbird is sort of a JavaScript console that is better than using alert(). As their website says, "You might never use alert() again."


Blackbird is attractive and useful but not might fall short in some debug scenarios. All too often, I have had a need to dump the insides of a JavaScript object - its properties. Fortunately, plain JavaScript can do this. This script can be found at the www.breakingpar.com site and it works nicely with Blackbird (with a few modifications).

function dumpProps(obj, parent) {  
   // Go through all the properties of the passed-in object   
   for (var i in obj) {  
    // if a parent (2nd parameter) was passed in, then use that to   
    // build the message. Message includes i (the object's property name)   
    // then the object's property value on a new line   
    if (parent) { var msg = parent + "." + i + "\n" + obj[i]; } else { var msg = i + "\n" + obj[i]; }  
    // Display the message. If the user clicks "OK", then continue. If they   
    // click "CANCEL" then quit this level of recursion   
    if (!confirm(msg)) { return; }  
    // If this property (i) is an object, then recursively process the object   
    if (typeof obj[i] == "object") {   
      if (parent) { dumpProps(obj[i], parent + "." + i); } else { dumpProps(obj[i], i); }  
    }  
   }  
 }  

When you get your script working as expected you might want to run it through JSLint. JSLint is a code analysis tool following the coding rules as discussed by Douglas Crockford's book, JavaScript: The good parts. Essentially, JSLint looks for problems in JavaScript program. It is a code quality tool.

I hope that these stuff makes debugging JavaScript a little more pleasant.

Saturday, March 31, 2012

What the heck is a RockMelt?

The Rockmelt Browser
Most recently, a friend pointed me to Rockmelt. It tags itself as a Wowser. I don't know how the marketing guys come up with that but technically is just a fork of the Chromium browser which the Google's Chrome browser calls papa. Don't see this as a bad thing, Chromium (and by extension Chrome) are pretty stable and fast browsers. Rockmelt is the same thing its a just as fast. Rockmelt is just customized to do a particular thing - social web surfing. It directly integrates to Facebook, Twitter, 9gag, etc. in this nifty sidebar widget thing on the left. A direct share button is pretty nice feature and a Facebook chat on the right sidebar.

But Rockmelt inherits one of Chrome's bad characteristics. It's memory-hungry.  Each widget spawns its own process, sure it makes the Rockmelt run fast but I would be hard press in recommending it to be installed on a budget notebook with only 1 GB of RAM or less. I come across a lot of these 11-13 inch notebooks in my work.

Installing Rockmelt is no big deal, its free and the installer is like 600kb. The installer is one of those file tractor pullers - you run the installer and it then down loads the rest of the browser. No biggie.

After that, you get to a first-run wizard, it ask for your facebook login, this is where it get hairy for some of us, Rockmelt basically want all the rights. If you're concern about privacy, this page will make think about why you got Rockmelt. I already know of a guy who said no and uninstalled Rockmelt.Then you move to a page where you pick a bunch of "Apps" to be added to your Rockmelt.

The Apps here are more of RSS readers allowing you see if there's anything new on that site. Think of them as direct views into the associated site. You have a lot of choices, from Tumblr, Twitter, Pixable, Mashable!, etc. But some apps have direct interaction to the sites, for example Twitter, you can post tweets directly from the Twitter app inside Rockmelt.

Once done it works like another browser but with a direct connection to Facebook.

Which leads me to "the" question: is it worth it? Nothings seriously wrong with it. It did crash a few times but only the tab causing the crash was lost not the whole browser. Nothing serious. A few people will find the permissions page during installing a bit unnerving. Reminds me of that phrase: "signing your life away."

Overall?

Get Rockmelt if basically your homepage is Facebook or you check your Facebook every chance you get and you're not a privacy rights Nazi. Which I think is an oxymoron if I ever seen one. It's already a pretty fast and stable browser. Who knows, it might make you more "productive" but that's a long shot.




Thursday, March 15, 2012

Got tired waiting for ICS so back to MIUI

ICS on my phone was sweet - battery life was excellent, games (3d and what not) were running smoothly but and this is a BIG but..No camera. I know that edowar is working on it and its a pretty hard problem to crack. It's a hardware driver problem and Foxconn isn't really going to fork over that one any time soon.

My Home screen
So we go back to MIUI. Imagine my surprise that TJ's MIUI wasn't the only one out there for my CM Magnum. People made forks and ran with it. I mean RAN. I found 4 more other ROMs for my phone and all based on TJ's stuff. TJ is a god!

As for the choosing which on to flash into my phone - I wasn't really that scientific about it. I just basically went for the "eye-candy" factor. I decided on CacingKalung's MIUI 2.2.3 ROM.

It's about 117MB (make that about 120ish if you download the extras which I did.) and it installs flawlessly.

I'm reinstalling my stuff and let's see how this works out while waiting for a stable,working ICS for my phone.

So far, its pretty sweet.


Sunday, March 4, 2012

Quirky stuff with JNDI and MSSQL

My last post talked about getting Glassfish and MSSQL connected. By doing this, we effectively hand over the management of the our database connection to the application container. One less thing to deal with in code.

Now, we try to get some data and see if it works. I decided to try out JDBC first. I could just jump to Hibernate but remember Hibernate just glosses over the details. If JDBC works then I know that Hibernate will work. So my code started as:
        ....
        try{
            InitialContext ctx = new InitialContext();
            DataSource ds = (DataSource)ctx.lookup("MSSQL2008");
            
            Connection conn = ds.getConnection();
            Statement stmt = conn.createStatement();
            
            ResultSet rs = stmt.executeQuery("SELECT * FROM [TestDB].[dbo].[Users]");
            String temp = rs.getString("email");
            
            stmt.close();
            conn.close();
           
            return temp;
        }catch(Exception e){
            e.printStackTrace();
        }
That didn't go off without errors. I got a "SQLServerException: The result set has no current row." error. Apparently, the Microsoft JDBC driver I was using didn't move the cursor to the first row of the result set. Feature or bug?
To fix this we forcibly move the cursor to the first row by adding the line: rs.absolute(1).
The code then will look like:

        ....
        try{
            InitialContext ctx = new InitialContext();
            DataSource ds = (DataSource)ctx.lookup("MSSQL2008");
            
            Connection conn = ds.getConnection();
            Statement stmt = conn.createStatement();
            
            ResultSet rs = stmt.executeQuery("SELECT * FROM [TestDB].[dbo].[Users]");
            rs.absolute(1);
            String temp = rs.getString("email");
            
            stmt.close();
            conn.close();
           
            return temp;
            
        }catch(Exception e){
            e.printStackTrace();
        }
Save, compile and redeploy and.....another error. Typical. This time the error I got was: SQLServerException: The requested operation is not supported on forward only result sets. Can you get what's the error? So we need to NOT create a forward only result set. This is done by adding the line: createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY). 
The final code is then:
        ....
        try{
            InitialContext ctx = new InitialContext();
            DataSource ds = (DataSource)ctx.lookup("MSSQL2008");
            
            Connection conn = ds.getConnection();
            Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            
            ResultSet rs = stmt.executeQuery("SELECT * FROM [TestDB].[dbo].[Users]");
            rs.absolute(1);
            String temp = rs.getString("email");
            
            stmt.close();
            conn.close();
           
            return temp;
            
        }catch(Exception e){
            e.printStackTrace();
        }
All should be OK now. Now to do some real damage. *evil grin*

Wednesday, February 15, 2012

Unholy union: Glassfish and MSSQL

I'm in a situation where the data is on a Microsoft SQL Server and I want to use Glassfish and J2EE. And all of this done inside Netbeans.
SQLServer + Netbeans?
Getting Netbean's version of Glassfish to work with MS SQLServer 2008 is a trick. When you start it up and open the Admin console webpage you'll head to the Resources > JDBC > JDBC Connection Pool and open make a new connection. You'll finish out the wizard until you try to ping the server. FAIL!

The problem is Netbean's version of Glassfish doesn't have the correct jars. Open C:\Program Files\glassfish-3.1.1\glassfish\lib; take a look and facepalm at this display of fail from Oracle.

Lets not dwell on that.

So we need a JDBC driver and a JDBC driver we shall get. Don't worry although its Microsoft, it won't cost you a thing. Documentation here. Driver here and just drop the jar file into that folder you just opened. Use the sqljdbc4.jar. Don't forget to restart the Glassfish server.

Now we redo the step in creating the JDBC connection pool resource. Here is what I did:
  1. Named the Pool: MSSQL2008
  2. Set the resource type to: java.sql.driver
  3. Set the driver class name to: com.microsoft.sqlserver.jdbc.SQLServerDriver
  4.  Set my properties to the following values:
    • URL = jdbc:sqlserver://{iptoserver};instanceName={name};databaseName={defaultdb};integratedSecurity=false;
    • user = my admin username
    • password = duh!
Troubleshoot if the ping test fails.

Don't forget to create a JDBC resource after you succeed in creating your connection pool in Glassfish. You'll need it if you want to get database access via JNDI.

Saturday, February 11, 2012

Adb can't detect my Android Phone. Damn.

So you open a command line and type in adb devices and, guess what, it can't detect your Android phone. This could be because of a variety of reasons like you installed a custom ROM. In any case, adb can't detect your device. Fortunately, the fix is just to install a driver. The bad part is the phone manufacturers sometimes don't post their USB drivers on the net.

How do we fix this?

1. Identify who really makes your phone. Like mine, which is sold as the Cherry Mobile Magnum HD but its actually a Foxconn phone. Do a google search or a lsusb command if your running a Linux box. You should be able then to get the ATTR{idVendor} value.

2. With that, go to this webpage. That should explain how to get your device recognized and help you figure out who made your phone.

3. You should be able to figure out which OEM driver to get.

Install and then you might have to do a reboot. When you get back, your Android phone now should be recognized by running adb devices again. You should be looking at something like below.
adb devices
This is related to my older post: Getting Ubuntu to play nice with your Android device.


Sunday, February 5, 2012

ICS for your Cherry Mobile Magnum

I'm trying out Alpha1 Alpha2  Alpha3 AOSP ICS Rom for Huawei x6 and other FB0 devices. The ROM is cooked by edowar. The ROM is currently Alpha, its working but its still a ways off.

Although, its still alpha it did install painlessly. The procedure is:


1. Downloaded new rom. (.zip) to your SD card
2. Go to 'backup and restore ' and take a backup
3. Reset userdata, cache and dalvik !important
4. Install the zip from SD card
5. Reboot system and you are done

After the install if you already rooted your Cherry Mobile Magnum, it stays rooted. After the reboot, you'll notice that it doesn't have any apps. So get GAPPS and install it following the same procedure for the ROM.

Unfortunately the ROM, doesn't have support for the camera and WIFI yet. Edowar and team are still working on it. And they as nice as the ICS rom is to look at, they don't have an ETA.

Despite of the shortcomings, my preview of the ICS rom has had me convinced that to wait for a release. From what I can see, the ROM is pretty stable (1 reboot for the week I had it) and is choke full of eye candy.

Can't wait!

Friday, February 3, 2012

.NET MVC3, Web Forms, Tapestry5 and Arnold being dead

They told me to learn .NET MVC3 or get fired and I'm like fine, whatever. I hack java, groovy, javascript, Less CSS and HTML5, how hard .NET MVC3 can be? I mean, Java has a ton of MVC frameworks (Struts, Play, etc.) and I've used (or at least tried) a lot of them. And don't get me started with PHP - CodeIgniter, Zend, etc.

Apparently, it isn't that hard, C# .NET is more or less a direct rip of Java with some syntactic sugar and good ideas. It took me about a week to find a groove with .NET MVC3 and another week to learn Entity Framework (which BTW, looks like Hibernate in Microsoft branding). So, I was chugging out good code and then Arnold told me to try out Web Forms. "It's like Tapestry5." He's words. He's. Last. Words. Then I BEAT HIM to DEATH with my old IBM ceramic keyboard.

Web Forms IS NOT Tapestry5!

Tapestry5 is way, waaaaaayyyyyyyy cleaner than Microsoft's Web forms. Proof? Try making a non-trivial Web Form's based web application and take a look at its "Code Behind" classes and generated HTML. I see spaghetti and it doesn't adhere to Tapestry5 programming tenets of  Single Responsiblity Classes and Seperation of Concerns.

What kind of class code are you writing when it balloons past 1k lines and you can't identity what it actually does from the first 20 or so lines?

Another that rubs me the wrong way with Web Forms  is that I have limited control on how to the HTML is generated. You can argue that I could "override" it, screw that, its more trouble than its worth.

And lastly, Web Forms is a bitch when trying to work in your favorite JavaScript library.

I though writing this blog would be, you know, cathartic. It's just making me angry again.

Where is that keyboard.....

Saturday, January 28, 2012

That jquery click event and moving viewport problem

Sometimes certain combinations of attributes and values on a DOM element conspire to make you look stupid. In this case, a jQuery click function attached to an anchor tag with a href attribute.
<a href="#" class="reply-action">  
      <span>  
         <i></i>  
             Reply  
         </span>  
      </a>  
</span> 
And the jQuery is pretty straight-forward. The anchor tag when clicked will just toggle a div.replies to show or hide.
$('.reply-action').click(function () {
 $('.replies').toggle();
})
At this point, all things work. The replies div slide up and down as described by the jQuery toggle function. Normally this isn't a problem when you run this code at very top of the browser viewport. "Top of the browser viewport" simply means that the page hasn't scrolled down. The "moving viewport" problem happens when you run the click function when you're at bottom of the page. The click function keeps forcing the viewport to move to the top. Its annoying as hell. Fortunately the solution is simple. So simple in fact it made me go *FACE PALM*. The root of the problem is the the anchor href attribute set to "#". So by just changing the href attribute to something else like javascript:void(0) or just simply delete it, you fix the problem.
<a href="javascript:void(0)" class="reply-action">  
      <span>  
         <i></i>  
             Reply  
         </span>  
      </a>  
</span> 
It took me about a day to figure it out after trying to use overly complex jQuery like event and mouse APIs. Talk about being given the runaround.

Wednesday, January 18, 2012

Going dark

I'm a freelance web developer and web administrator. I am able to do this because the Internet is free and open. But redneck, technology ignorant American congressmen and senators are sponsoring a pair of bills that will kill that freedom and openness. All in the name of stopping online piracy.

These bills (SOPA and PIPA) are moving through the American political system and even though I'm not American and I have an interest in this. So in about 4 hours (from this post) I'm going to shutdown all the sites that I'm currently the administrator for 12 hours in protest. Just like what reddit.com and wikipedia.org will be doing in protest.

You can read up here on how these two bills are written and will affect the whole Internet if passed and signed into law.

I'm going dark because if SOPA and/or PIPA pass, it wouldn't matter much because my sites will be going dark PERMANENTLY.

If you are a citizen of the Internets, show your support here.


Thursday, January 5, 2012

Learning Scala is screwing up my head

After learning Groovy, I decided to learn Scala. I'm in my 2nd week of learning it and its screwing up my head. I think its has more to do with the programming paradigm that Scala is in. Scala is a multi-paradigm programming language designed to integrate features of object-oriented programming and functional programming. 

Scala 2.9.1 in Netbeans
So to get started, I download and install Scala and got Netbeans to work with in. Scala in Netbeans is pretty sweet. You can follow all the Scala tutorials using the interactive shell and then try your hands on writing Scala scripts. 

The object-oriented part is cake but the functional programming part that what's screwing up my head. All this reminds me of what I had to go through learning object oriented programming coming from a procedural programming language. I'm expecting to go half-mad, a nervous breakdown and then suddenly just get it. 

This is going to be wild ride.