Simple pattern matching with Javascript String.replace

The first rule of any technology used in a business is that automation applied to an efficient operation will magnify the efficiency. The second is that automation applied to an inefficient operation will magnify the inefficiency.
-Bill Gates

For my personal music related project (Scribbletune) I wanted to generate an array of objects from a string. Here are some examples of the input expected and the output desired in each case:

Input (String):

x-x_
x---x---x---x---
x-xxx-xx-x-
x_x_x___x___x___

Output(Array of Objects):

[
  { on: true, length: 32 },
  { on: false, length: 32 },
  { on: true, length: 64 }
  ...
]

What’s happening here is, x denotes a Note On state and one or more underscores following an x denotes the length of the note in units of 32. Each hyphen denotes an interval or a Note Off state. The first thing that came to mind was to use a for loop on the string input and then whenever x is detected, I could split the string from that x to the end of the string and run one more loop to find the occurence of the underscores and use them to compute the noteLength value.

So then it would like

for (var i=0; i<string.length; i++) {
  if(string[i] == 'x') {
    // check if the next item in the string is _
    // if so, start a new loop with var j to string.length
    // count the occurrence of consecutive _
  }
}

This is fine and it will get the job done. But I wanted to break away from the dependency on the for loop.

Enter String.replace

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.  The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.

Basically I d need to ‘match’ occurrences of  x followed by zero or more underscores and occurrences of hyphens. Then based on those, I d just need to push the desired object to an array.

var pattern = 'x-x_';
var len = 32;
var retArr = [];
//separating occurrences of x_ and - in separate braces
//so that we can use them as capturing groups later
pattern.replace(/(x_*)|(-)/g, function(match, $1, $2){
  //match is the matched element itself
  //$1 is the first capturing group (x_*)
  //$2 is the second capturing group (-)
  if($1) retArr.push({ on: true, length: $1.length * len });
  if($2) retArr.push({ on: false, length: len });
});
console.log(retArr);

And that’s about it. The jsperf for this shows tremendous performance improvement as well as reduced number of lines of code (from 25 lines it went down to 4 lines) without sacrificing readability!


Categories: Javascript | Tags: , | Leave a comment

How to load jquery plugins dynamically while understanding Javascript closures and the difference between apply and call.

I guess the issue for me is to keep things dynamic.
-Robert Downey, Jr.

When I was a kid, I had this big hard cover red book of Russian folk tales. This book was filled with stories of dragons with more than 8 heads dealing with sons and daughters of farmers while covering a lot of ground on foot or animal back. Each story had a really long title, just like the title for this blog post :)

At the cost of not digressing any more, I ll start off with what I intended to document through this post. I had to solve a challenge where there were over 50 custom jquery plugins written to do specific things on certain HTML elements but the presence of the HTML elements that they were to be initialized on were not fixed. It was certain though that there would not be more than 7 or 8 elements at any given time that would need their corresponding plugins. So here’s what I came up with for this. It also helps me showcase a really good example for JavaScript closure and the difference between apply and call. I ve noticed that these terms are searched widely and though the explanations for them exist widely too, there just arent enough good examples that demonstrate them.

Ok here goes.

You can download this sample from github to see how the files are structured and what are their contents.

Just as a sample, I created just 4 js files and called them a.js, b.js, c.js and d.js. These were to denote 4 custom jquery plugins. For this sample the plugin would just put the alphabet letter in the html() of the element they were initialized on. So the plugin a.js would insert ‘a’ in the html element that it was initialized on. b.js would insert ‘b’ in the html element that is was initialized and so on:

//sample plugin
$.fn.a = function() {
	this.html( 'a' );
}

Then I created a HTML page that had DIVs in the following fashion in its BODY tag:

<div class='hasPlugin' data-plugin='a'></div>
<div class='hasPlugin' data-plugin='b'></div>
<div class='hasPlugin' data-plugin='c'></div>
<div class='hasPlugin' data-plugin='a'></div>
<div class='hasPlugin' data-plugin='a'></div>
<div class='hasPlugin' data-plugin='d'></div>

As you can see, each div has a class called ‘hasPlugin’ to denote that this html element will need a plugin initialized on it. These divs also have a data-plugin attribute that denotes the name of the plugin that it needs. As you can also see, I have 3 divs with the requirement for the plugin ‘a’. This is just to demonstrate a one to many relation while initializing the plugins.

The only next thing I did in the HTML was to add a script tag that pulled jquery from a CDN

<script src='http://codeorigin.jquery.com/jquery-1.10.2.min.js'></script>

This concludes my HTML setup. For the SCRIPT part, I started with an anonymous function declaration. But this is not my example for JavaScript closures. That example will come up shortly and it ‘will’ explain how and why you would use it :)

(function(){
	//all code here
})();

My goal was clear and my logic was simple. I knew that there could be multiple DIVs that required the same plugin. And I certainly did not want to go and fetch that plugin multiple times. Neither did I want to use some custom function to loop over an array to remove duplicate entries. So I defined a hash map kinda object called plugs = {}. I looped over the DIVs which had the class ‘hasPlugin’ and took their data-plugin attribute to determine the name of the required plugin. I started assigning the names of the plugins as properties of the plugs object. Every time I did that if that property already existed

if plugs[pluginName] then create a new property
else append div to the existing propery

This way I did not have to worry about having to explicitly remove duplicates. Here’s how that code looked:

$('.hasPlugin').each(function(){
  var p = $(this).data('plugin');
  if (!plugs[p]) {
    plugs[p] = {
      plugin: p,
      divs: [this]
    }
  } else {
    plugs[p].divs.push(this);
  }
});

At the end of that I got a pseudo hashmap with plugin names as the property name and an object with the DIVs that had the plugin applied to them as a value. I also included the name of the plugin in this object so that I could make use of it later.

All I need to do now was to go over the plugs object and take each ‘item’ in it and load the JavaScript file for it. On loading of that file I needed to initialize that plugin on to the DIVs of that ‘item’. Here’s where we’ll use the closure (as well as the function.call method)

for (var p in plugs) {
  var fileref=document.createElement('script');
  fileref.setAttribute('type','text/javascript');
  fileref.setAttribute('src', plugs[p].plugin + '.js');
  document.getElementsByTagName('head')[0].appendChild(fileref);
  //on load of each script file, initialize it on the div(s)
  fileref.onload = (function(plugObj) {
    return function() {
      $.each(plugObj.divs, function(i, div){
        var pluginName = plugObj.plugin;
        $.fn[pluginName].call($(div));
      });
    }
  })(plugs[p]);
}

A little bit of explanation is called for. In the loop, I m first setting up a file reference object that create’s a SCRIPT tag it’s src attribute set to the name of the plugin. That was pretty straightforward. The next thing I do is to check for the onload method of the file reference object in which I use a JavaScript closure. I love digressing and I m gonna do that for a bit now. Let’s say you had a bunch of buttons that you created from a ‘for’ loop. Like this:

for (var i=0; i<5; i++) {
  var btn = document.createElement('button');
  document.getElementsByTagName('body')[0].appendChild(btn);
  btn.onclick = function() {
    alert(i);
  }
}

What do you think will be alerted every time you click any of the buttons? If you are one of those really cool kids who actually try out things before answering these kinda questions, you ll take a moment to quickly run that last snippet in the console of your browser to learn that no matter what button you click, it always alerts 5! What a mischievous bunch of buttons we've created! :D Well maybe it was obvious and maybe you re so cool that you knew it without running the snippet in the console of your browser :)

If we change the snippet such that we use a JavaScript closure in the form of an anonymous function inside the loop and explicitly tell it the value of i then we can discipline the buttons to behave appropriately:

for (var i=0; i<5; i++) {
  var btn = document.createElement('button');
  document.getElementsByTagName('body')[0].appendChild(btn);
  btn.onclick = (function(i) {
    return function() {
      alert(i);
    }
  })(i);
}

Basically we are passing that (function(){})(); thing inside the onclick to define an anonymous function which we are defining and calling at the same time. ()(); is the function call itself. The first set of braces is to define the function with whatever arguments we want. The second set of braces is to pass in the arguments we defined. This should suffice as a good example of a closure. If you run that last snippet in your browser's console, you ll see that the buttons are not so mischievous anymore.

Going back to the intended subject of this post, we are using a similar closure to define an anonymous function which is called at the same time and we are passing it the plug object to work with.

Now we come to the difference between JavaScript function.call and function.apply. In the following partial snippet I m using function.call:

$.each(plugObj.divs, function(i, div){
  var pluginName = plugObj.plugin;
  $.fn[pluginName].call($(div));    //

Both function.call and function.apply have a similar role to play. Both call a function and allow us to pass the value for 'this' as the first argument followed by the arguments required by the function itself. If you do not know how many arguments you are gonna end up passing OR if the function expected an Array to be passed, then use function.apply. But if you know the number of arguments you are going to pass, then use call. A comment on StackOverflow had an interesting way to remember this. The comment was something to the effect of, use Apply for an Array as an argument (AA) and use Call when you can Count the arguments you re going to pass (CC). Unfortunately (at least for me) this does not yet fully explain the difference nor the use case scenario for either function.apply OR function.call. I need a real world use case scenario sometimes to understand some concepts. The topic I m covering in this post helps me get just that. A use case scenario!

So as we ve discussed so far, we are dealing with a bunch of jquery custom plugins that we load dynamically and initialize them on DIV elements that need them. Since they are jquery plugins, they are basically namespaced under $.fn coz at the very basic level, a jquery plugin is:

$.fn.a = function() {
  this.html( 'a' );
}

So if I had to initialize that on the first DIV element on a page, I d first need to load the script file a.js along with jquery and then simply initialize the plugin in this way:

$('div:first').a();

For our example, we do not have 'div:first' nor do we know that it needs plugin 'a'. But we do have those in variables. So we use function.call in this fashion:

$.fn[pluginName].call($(div));

This will initialize the pluginName on to $(div). This could ve been done with function.apply in this fashion:

$.fn[pluginName].apply($(div), []);  //apply takes an array as the second argument

But since the plugin did not have any arguments for this sample, we do not need to pass any second argument to either call or apply. In such a case I d rather use function.call coz it may be a little faster than function.apply which has to parse the second argument as Array. Function.call is not obliged to do so and we do not have a second argument here.

So that summarizes my take on dynamic jquery plugin loading, closures and apply vs call. You can download this sample from github to see how the files are structured and what are their contents.


Categories: How To, Javascript, jQuery | Tags: , , , | Leave a comment

How to run Grunt tasks only on changed files

You can observe a lot by just watching.
-Yogi Berra

For a recent workflow improvement I was trying at work, I needed to setup a Grunt watch and uglify on a bunch of javascript files to minify them into individual minified files and then concatenate them. The number of files to be concatenated was over 50 hence uglifying the whole bunch each time a file was updated would slow down the workflow.

So the goal was to minify each file individually into its own minified version and then run a watch on the minified files directory contents and concatenate the minified files into one js file. The uglify target looked like this:

uglify: {
  all: {
    files: [{
      expand: true,
      cwd: 'js/',
      src: ['*.js', '**/*.js'],
      dest: 'js-min/',
      //ext: '.min.js',    //commenting out for now
    }],
  },
}

The second part of the goal was to concatenate minified files into one main.js. This needed to happen every time a file was minified. Which means I needed to run the uglify task only on the file that was changed or updated and then concatenate the minified files. Before moving on, here’s the Grunt concat task inside the watch:

concat: {
  files: {
    src: [
      'js-min/*.js',
    ],
    dest: 'main.js'
  },
}

A watch task on the ‘js’ directory would run the uglify task and a watch task on the ‘js-min’ directory would run the concat task. The challenge was, every time the uglify task ran, it went through all of the js files specified in it’s target and uglified them. And then the watch task on the ‘js-min’ directory would kick in and concatenate all the files in the ‘js-min’ directory. SO the required behaviour was to set the watch task for uglify to run only on the updated/changed file.

Say hello to the on watch event

Grunt watch has a ‘on’ event so that one can compile files as needed. My first hack was to use this ‘on’ event and run uglify on the changed file from this event’s handler which provides a filepath paramenter. Grunt’s core developers will not advise us to use this event method in this fashion as it deviates from the standard procedure of assigning tasks using Grunt. Hence we ll maintain the existing uglify task just the way it was defined earlier. In the watch event handler, we ll simply change our uglify task’s source parameter to the file that was updated. So instead of taking all the files defined in the src parameter, Grunt watch will only process the updated file

grunt.event.on('watch', function(action, filepath, target) {
	//change the source and destination in the uglify task at run time so that it affects the changed file only
        var destFilePath = filepath.replace(/(.+)\.js$/, 'js-min/$1.js');
	grunt.config('uglify.all.src', filepath);
	grunt.config('uglify.all.dest', destFilePath);

});

This will make sure that only the changed file is uglified. Once it compiles it as a minified file, we run concat on the minified files by adding another watch target in the Gruntfile.

This solution helps meet the goal I set out to achieve. Though there is an issue in this. What if we wanted to append .min.js to the end of all the files we minify? We could just add that in the uglify target object as ext: min.js. But then it will create some problems on files that have a dot (or 2) in their ‘name’ itself. For example its a common practice to name jquery plugins like this: jquery.pluginname.js

At the time of this writing, Grunt uglify will not differentiate between files with more than one dot in their name. It will use the first dot that it finds in the file name and consider the rest of the file path as an extension of the file. So let’s say we decide to append a .min.js to our uglified files, our Grunt task will convert both jquery.pluginname.js and jquery.js to jquery.min.js. This is not what we want! There is a bug filed for this and maybe the core team will do something to tackle it, but since one can pass a rename function, they may not consider tackling this right away.

A quick and dirty solution is to explicitly rename the changed files the way you want in the on watch event itself. So you’d first uncomment the ext portion in the uglify task and update the on watch task:

var destFilePath = filepath.replace(/^js\/(.+)\.js$/, 'js-min/$1.min.js');

If you know a better way than this, then please do leave it in the comments.


Categories: How To, Javascript | Tags: , , | 1 comment

Twitter Bootstrap Website Starter: Create a mobile friendly, HTML5 responsive website instantly!

One cannot be deeply responsive to the world without being saddened very often.
-Erich Fromm

While creating a small HTML website, I wonder if developers still need to manually put together a bunch of HTML files and wire them up in a navigation menu. I feel the process to put together a barebones HTML5 website should be like a handy Lorem Ipsum text generator. It should let you quickly setup a site based on maybe a settings file that you can edit to suit your website’s structure. Well, I ve just put together something like that and here is how to use it :)

Download or clone the Bootstrap Website Starter from github. If you do not intend to customize it using the built-in python tool, then simply:

  1. copy the contents of the ‘site’ folder to your web server’s public folder
  2. each page is a static HTML page, so you can just go in and populate the page with your content

Here s a demo of what that would look like.

A quick design suggestion I d like to recommend is: head over to Google web fonts and select 2 contrasting fonts (please do not use similar looking fonts – it really does not add any value to your typography). Use one for the header texts and the other for the body text. Since we are using Twitter Bootstrap, you can even change the navigation bar to something else.

Of course, so far we ve only used the ‘site’ folder contents as is. The biggest issue is, what if you wanted more pages than the default number of pages provided? What if you needed to change the name of the Project or the name of the pages themselves? Well, you d need to manually change all that and then you ll have to go to each page to make changes to the navigation menu (and links) as well! Honestly, it wont be so bad to do it manually, but then if you don’t mind using the terminal a little bit, then you could simply use the built-in python tool to structure your site the way you want before you start making any design changes.

Please note: Windows users need to have Python on their machine. For Linux and Mac users, Python in installed by default and you can simply open settings.json from the downloaded starter kit and edit the file to suit your site-structure needs. Here is the default settings.json file (we ll edit this shortly):

{
    "project": {
        "project_name": "Project Name",
        "year": "2013",
        "keywords": "comma separated, keywords",
        "description": "Enter a brief descriptio.",
        "canonical_url": "http://www.project_url.com",
        "google_analytics_id": "UA-XXXXX-X"
    },
    "pages": [
        {
            "title": "Home",
            "template": "home.html"
        },
        {
            "title": "About",
            "template": "page.html"
        },
        {
            "title": "Services",
            "template": "page.html"
        },
        {
            "title": "Gallery",
            "template": "gallery.html"
        },
        {
            "title": "Contact",
            "template": "contact.html"
        }
    ]
}

In this file, you can have 2 primary settings. One for the project itself (which is self explanatory) and the other is an array for the pages to generate. To add more pages, just copy over one of the ‘page’ objects in the array (do not add a comma at the very end coz Python will not accept it as a valid JSON page) Each ‘page’ object in this array has a ‘title’ and a ‘template’ property. Change the title to whatever you want. For example, if you’d like to call the ‘Contact’ page ‘Get in touch’ then simply change the title for that page object to ‘Get in touch’. The tool will create a file called ‘get-in-touch.html’ and set its title and header text to ‘Get in touch’.

For the template of each page object, you can chose one of the following template types:

  • home.html <- Generates a home page with a slideshow on it
  • page.html <- Generic page
  • gallery.html <- Generates a page with thumbnals
  • contact.html <- Generate a a page with a basic contact form

These are self explanatory for the kind of content they d create. In most cases, you d need to chose ‘page.html’ for a new page. This will create a generic ‘page’ with 2 columns (one with an image and the other with some text). You can even add more template types if you want. Take a look at the HTML inside the templates folder and create another HTML file to create a new template.

Once you re done editing the settings.json file, fire up the terminal and ‘cd’ into the folder you downloaded (or cloned). Run the following command:

python generate-site.py

A brand new site with your customized settings will get created inside the ‘site’ folder. Copy over its contents to your web server’s public folder and that’s about it!

Here s a demo of what a site thus generated would look like.


Categories: How To, Useful | Tags: , , , | 1 comment

How to layout a BackboneJS project in CakePHP using GruntJS

BackboneJS does not seem to come with a recommended layout for its file structure, though Yeoman suggests it’s own concept of laying out a BackboneJS project. I took inspiration from Yeoman to put together this approach for laying out a BackboneJS project inside the CakePHP framework. CakePHP is convention over configuration and expects you to put all your assets inside cakeroot/app/webroot/.

For the sake of this tutorial, I m going to create my files based on a simple ToDo project since almost every developer creates a ToDo app at least once! The ToDo list app for this project has a database with 3 tables:

users
categories
tasks

Inside webroot/js, create the following directories

vendor
src
collections
models
views

Yeoman generates directories for routes, helpers and templates. I m not going to add these coz I dont need them. For routes, I m going to use only one file and it can stay inside the js folder alongside my main.js file. I have a feeling that the convention to use main.js comes from ActionScript 3.0 projects (though I do not have any proof of this)

Once you ve created your directories in the js folder, its time to put in some files. Here is the same directory structure for the js/ directory, but includes files that are based on my database schema.

js/
  main.js
  application-router.js
  vendor/
    jquery.min.js
    underscore.min.js
    backbone.min.js
  src/
  collections/
    application-collection.js
    categories-collection.js
    tasks-collection.js
  models/
    application-model.js
    category-model.js
    task-model.js
    user-model.js
  views/
    application-view.js
    categories-view.js
    task-view.js
    user-view.js

Yeoman creates the main.js with one global variable based on the name of your project and creates placeholders within that for our models, collections, views and routes. Here s a sample of it:

window.ProjectName = {
    Models: {},
    Collections: {},
    Views: {},
    Routers: {},
}

Now, while defining your models or collections or views, make sure to namespace it inside ProjectName.Models or ProjectName.Collections or ProjectName.Views. For example, our task-model would look like this:

ProjectName.Models.TaskModel = Backbone.Model.extend({
  defaults: {}
});

Notice the name of the model. The file was named task-model.js and the model itself is called TaskModel. This is just a convention. You can change this to whatever you think is better for you.

Finally templates, Yeoman does create a structure for that but I figured that out the easy way that it has not yet implemented the feature where you can define .ejs files inside your templates directory and use em from there. At least not as of this post. So instead of trying to do that, we can just define the templates inside a directory inside app/View/Elements/Templates. We can then render that element in Cake’s view file which also has the scripts pulled in for our app. For this tutorial, I have a controller called UsersController.php and I have routed /app to UsersControllers:app

Router::connect('/app', array('controller' => 'users', 'action' => 'app'));

Since that s how the route is defined, we need to have a file at app/View/User/app.ctp. At the beginning of this render the templates file and at the end of the same file, pull in the required JS files.

For now I ll just pull all the required JS files from CakePHP’s perspective (later we’ll use Grunt):

//vendor
echo $this->Html->script('vendor/jquery-1.9.1.min');
echo $this->Html->script('vendor/underscore-min');
echo $this->Html->script('vendor/backbone-min');

//src
echo $this->Html->script('src/main');
echo $this->Html->script('src/application-router');
//collections
echo $this->Html->script('src/collections/application-collection');
echo $this->Html->script('src/collections/categories-collection');
echo $this->Html->script('src/collections/tasks-collection');
//models
echo $this->Html->script('src/models/application-model');
echo $this->Html->script('src/models/user-model');
echo $this->Html->script('src/models/category-model');
echo $this->Html->script('src/models/task-model');
//views
echo $this->Html->script('src/views/application-view');
echo $this->Html->script('src/views/user-view');
echo $this->Html->script('src/views/category-view');
echo $this->Html->script('src/views/task-view');

Lets say your application-router.js file looks like this:

ProjectName.Routers.ApplicationRouter = Backbone.Router.extend({
    routes: {
        "": "firstrun",

    },
    firstrun: function() {
        console.log("router - firstrun");
    }
});

Then at the end of all the javascript calls, create script tag and create a router object and kick start the show!

(function(){
    var router = new ProjectName.Routers.ApplicationRouter();
    Backbone.history.start();
})();

We could even use GruntJS and have all the JavaScript and CSS files uglified or minified into one single app.js and app.css file and just pull that instead. To do so you ll need NodeJS and Node Package Manager installed. If you do have these installed, then create a file called package.json inside cakeroot/app/. I m not using the webroot directory coz I dont want my Gruntfile and package.json file to be publicly accessible. Inside your package.json file you could do something like this:

{
  "name": "ProjectName",
  "title": "ProjectName",
  "version": "2.0.0",
  "devDependencies": {
    "grunt-contrib-uglify": "~0.1.1",
    "grunt-contrib-watch": "~0.2.0",
    "grunt": "~0.4.1",
    "grunt-contrib-cssmin": "~0.6.0"
  }
}

Then, add n navigate to your app folder in a terminal and run:
npm install

Once the required modules are installed, you can add app/node_modules to your .gitignore file. Then create a file (inside app/) called Gruntfile.js (unless it is not already created) and enter something like this:

module.exports = function (grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        uglify: {
          options: {
            banner: '/*!    */'
          },
          dist: {
            src: [
              'webroot/js/src/main.js',
              'webroot/js/src/router.js',
              'webroot/js/src/collections/*',
              'webroot/js/src/models/*',
              'webroot/js/src/views/*',
            ],
            dest: 'webroot/js/app.js'
          },
        },
        cssmin: {
          compress: {
            options: {
              banner: '/*    */'
            },
            files: {
              'webroot/css/app.css': ['webroot/css/reset.css', 'webroot/css/style.css']
            }
          },
        },
        watch: {
          scripts: {
            files: [
              'webroot/js/src/main.js',
              'webroot/js/src/router.js',
              'webroot/js/src/collections/*',
              'webroot/js/src/models/*',
              'webroot/js/src/views/*',
              'webroot/css/*'
            ],
            tasks: ['uglify', 'cssmin'],
            options: {
              nospawn: true
            }
          }
        }
    });
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-contrib-watch');
    //register default task
    grunt.registerTask('default', 'watch');
}

I m just using uglify and cssmin along with watch. You can add whatever else you may need. After that you wont need to pull all those JS files in your view file. As you may already know, the browser pulls 2 files at a time from the server. So if you have 16 files (including Javascript as well as CSS), then it ll make 8 trips to the server and back!

Now that we have some grunt tasks running, we can reduce the round trips to the server (and cut file size considerably). Run ‘grunt’ from the ‘app/’ directory in a terminal and marvel at the ‘magic’ from the contributors of Grunt as you make even the tiniest of the changes to the files that are being ‘watched’. These views are just my idea based on how Yeoman lays out a Backbone JS project. If you have some suggestions to improve this, then please do share.


Categories: How To, Javascript | Tags: , , , | 3 comments

Install Apache, MySQL PHP and phpMyAdmin on Ubuntu 13.04 Raring Ringtail

When Thomas Edison worked late into the night on the electric light, he had to do it by a gas LAMP or candle. I’m sure it made the work seem that much more urgent.
-George Carlin

Ubuntu 13.04 ‘Raring Ringtail’ released yesterday and though I use Crunchbang, like any ex Ubuntu fanboy I got myself the iso, put it on a thumbdrive and installed it on a small netbook I have that was just lying around doing nothing fancy. I thought I d install the new Ubuntu on it and use it to ‘code’ while in the John or while standing in the line at Starbucks :D

So anyway, I had to setup a LAMP server:

sudo apt-get update
sudo apt-get upgrade

MySQL

sudo apt-get install mysql-server mysql-client

Apache

sudo apt-get install apache2

PHP

sudo apt-get install php5 libapache2-mod-php5 php5-mysql

Restart Apache

/etc/init.d/apache2 restart

phpMyAdmin

sudo apt-get install phpmyadmin

I don’t like to use Apache’s default http folder /var/www so I need to update the apache2.conf file:

sudo nano /etc/apache2/apache2.conf

Changing the default location will require me to make sure phpMyAdmin continues to load on http://localhost/phpMyAdmin so at the end of the same file I ll add the virtual host configuration for phpMyAdmin

Include /etc/phpmyadmin/apache.conf

Restart Apache

/etc/init.d/apache2 restart


Categories: How To, Linux, Useful | 25 comments

Rearrange characters of a string to create all possible combinations

Governments tend not to solve problems, only rearrange them
-Ronald Reagan

How to take a word(string) and rearrange its letters to create all possible combinations? Lets say we want to use the word ‘goal’ and list out all possible words that can be made by rearranging the letters of the word ‘goal’. Take the first letter ‘g‘ and then create permutations and combinations of the balance letters ‘oal‘ and append them to ‘g‘.

g oal
ola
alo
aol
loa
lao 

Then take go and create create permutations for the balance letters ’al‘ and append them to ‘go‘.

go al
la

Then we take goa and l

goa l

This is done for each of the letters. As you can see, with each letter, the permutations will reduce for the subsequent letters. The parameters that are passed to our recursive function are a string that will be used to prepend (starting with an empty string) AND the array of the letters of the word that will be looped over to rearrange its words.

At the moment the JavaScript function I ve written tends to have too many iterations to produce the desired result but it works alright. Here’s a demo for this. I ve added 2 helper functions to this function. One to find if an item exists in a given array and another to remove an item from an array by index. I m not using the Array.splice function to remove item by index coz it to alters the array that was passed to it.

Here’s the function in JavaScript:
Here’s the same thing in python:


Categories: How To, Javascript | 1 comment

Create a right click menu for your web application

Taken out of context I must seem so strange.
-Ani DiFranco

Update: I ve converted this into a jquery plugin. You can download/fork it from my gitbhub page.

There is a common issue when crafting out non-trivial web applications, where you may have many different actions for the user to perform and yet you certainly do not want to overwhelm her with a complex UI with icons, menus, floating divs with action buttons in them etc. A simpler way to reduce the UI clutter could be to introduce a contextual menu on right-clicking an element. This is really simple using jQuery. Here s a DEMO for the following snippet. And here’s the demo for the same thing as a jquery plugin.

You could design a UL element the way you want and set

ul#context-menu {
   postion: absolute;
   display: none;
   /*sample style attributes follow*/
   width: 100px;
   background: #333;
   color: #fff;
   font-size: 12px;
}

ul#context-menu li {
   margin: 3px;
   padding: 3px;
   background: #000;
}

Assuming that we want this context menu to appear on right clicking an image, the sample HTML could be:

<img src='' />

<ul id='context-menu'>
   <li>Edit</li>
   <li>Delete></li>
   <li>Export</li>
</ul>

Now we simply bind the ‘contextmenu’ event of images to show this context menu.

$('img').bind('contextmenu', function(e){
   $('#context-menu').css('left', e.pageX + 'px');
   $('#context-menu').css('top', e.pageY + 'px');
   $('#context-menu').show();
   e.preventDefault();
   return false;
});

Basically, we got the X and Y position of the current mouse position and applied it to the context-menu UL element (which has position set to absolute) and prevented the default action from happening. Finally, we need to get rid of this context menu if the user clicks anywhere but the context menu.

$('html').click(function(e){
   $('#context-menu').hide();
});

We don’t want the menu to hide if the user clicked the menu itself, so we disable the default behavior of the element from propagating the click event way up to the HTML element:

$('#context-menu').click(function(e){
   e.stopPropagation();
});

Since we set position: absolute on the context menu, resizing the browser when its open will mess it s position. The probability of the user right clicking the image and then resizing the browser window is low, but just in case she does so, then we can simply hide the menu on resize as well:

$(window).resize(function() {
   $('#context-menu').hide();
});

So that s about it. Here’s a DEMO for this code. If you d like to see a demo of this same thing used as a jQuery plugin, then here’s the link for that and finally, here s my github page for it.


Categories: How To, jQuery, Tips | 1 comment

Solution for VideoJS not playing some videos in Firefox


This seems to be a common issue while using VideoJS where it will not play some videos in Firefox. Apparently some encodings of H264 are incompatible with the Firefox browser in which case you need to specify an alternative video format -> OGG. But then if you do not have the alternative format and you dont mind a dirty but quick hack, then you can just force VideoJS to use the Flash player instead of HTML5 video if the browser is Firefox. You ll need to host video.js from your own server as opposed to using their CDN for it. Then inside the video.js file ‘Find’ the term ‘techOrder’. It s the first attribute in the VideoJS.options object and looks something like this:

VideoJS.options={techOrder:["html5","flash"],

Declare an array to hold the default array and rearrange its value if the browser is Firefox:

var techOrderArr = ["html5","flash"];
if (navigator.userAgent.indexOf("Firefox")!=-1) techOrderArr = ["flash","html5"];

Then change that earlier code to
VideoJS.options={techOrder:techOrderArr,

Now VideoJS will use Flash in case its Firefox and play those videos that were not playing with the HTML5 video player :)

Here s a version of videojs where I ve done the required change.


Categories: How To, Tips | 11 comments

How to create resize handles for jqueryui’s resizable feature

Size matters not. Look at me. Judge me by my size, do you? Hmm? Hmm. And well you should not. For my ally is the Force, and a powerful ally it is. -Yoda

Create a 10px x 10px red square and save it as gif and call it resize-handle.gif and store it in your images folder. Then use jqueryui to assign resizable() on an element that you wish to resize. In the css file that came in with jqueryui (jquery-ui-1.8.13.custom.css in my case), around line #311, substitute the style declaration for the resizable ui with this

.ui-resizable-disabled .ui-resizable-handle, .ui-resizable-autohide .ui-resizable-handle { display: none; }
.ui-resizable-n { cursor: n-resize; height: 10px; width: 100%; top: 0px; left: 0; background: url(images/resize-handle.gif) top center no-repeat; border-top: 1px solid #f00;}
.ui-resizable-s { cursor: s-resize; height: 10px; width: 100%; bottom: 0px; left: 0; background: url(images/resize-handle.gif) bottom center no-repeat; border-bottom: 1px solid #f00; }
.ui-resizable-e { cursor: e-resize; width:10px; right: 0px; top: 0; height: 100%; background: url(images/resize-handle.gif) right center no-repeat; border-right: 1px solid #f00; }
.ui-resizable-w { cursor: w-resize; width: 10px; left: 1px; top: 0; height: 100%; background: url(images/resize-handle.gif) left center no-repeat; border-left: 1px solid #f00; }
.ui-resizable-se { cursor: se-resize; width: 10px; height: 10px; right: 0px; bottom: 0px; background: #f00; }
.ui-resizable-sw { cursor: sw-resize; width: 10px; height: 10px; left: 0px; bottom: 0px; background: #f00; }
.ui-resizable-nw { cursor: nw-resize; width: 10px; height: 10px; left: 0px; top: 0px; background: #f00;}
.ui-resizable-ne { cursor: ne-resize; width: 10px; height: 10px; right: 0px; top: 0px; background: #f00;}

That’s it.

 


Categories: How To, jQuery | 2 comments

← Older posts