Integrating InMobi Ads into jQueryMobile and MoSync based app

Recently I was developing a HTML5 app for a client using jQueryMobile and MoSync Reload with Wormhole Library (an amazing client which let you develop about 70% times faster compared to using native procedures) when I struck with a problem of placing InMobi ads into jQueryMobile sub-pages. If you are familiar with jQueryMobile you would know that it normally fetch pages on ID bases through AJAX and this trick allows it make smooth transitions. While on non-AJAX pages you can simply integrate InMobi’s JavaScript SDK which would be simple JavaScript snippet which you include in your pages and mobile ads will start rolling, however, in case of  AJAX based pages, ad providers normally detect AJAX requests and then refuse to serve ads because of the threat of misuse. I went as far as signing up for an AdMob account but found similar problem there.

I googled through, despite of some questions on stackoverflow, none had the solution (except the solution of turning to non-AJAX based pages which I couldn’t do in any case), I fired up an email to InMobi support and surprisingly got reply with-in an hour linking me to InMobi Mobile Web API.

InMobile Web API require POST request with a certain set of parameters and then return ads in XML format which you then need to parse and display ads wherever you want (including your jQueryMobile sub-pages).

Following is the dissection of request to API:

Basically InMobi Mobile Web API require you to make a POST request along with following parameters:

mk-siteid=xxxxxxXXXXXxxxxxXXXXXX&
mk-version=pr-SPEC-ATATA-20090521&
h-user-agent=Nokia6233%2F2.0&
mk-carrier=117.97.87.6&
format=xml
  • mk-siteid is the ID which you get after registering your app with InMobi through their website, for the purpose of development you can use their test ID which is: 4028cba631d63df10131e1d3191d00cb
  • mk-version is unknow to me but it remains static as it is.
  • h-user-agent is your browser agent which you can easily get through navigator.userAgent
  • mk-carrier is the user IP which you can get through following simple JSON call:
$.getJSON("http://jsonip.appspot.com?callback=?",
function(data){
      userIP = data.ip;
});

and format can always be XML as response will always be.

Moving forward we all know how to make POST request using jQuery along with above parameters:

$.post("http://w.sandbox.inmobi.com/showad.asm", { "mk-siteid": "4028cba631d63df10131e1d3191d00cb", "mk-version": "pr-SPEC-ATATA-20090521", "h-user-agent": navigator.userAgent,
"mk-carrier": localStorage.getItem("userIP"), format: "xml", "mk-ad-slot": 10 },
function(data) {
         console.log(data);
}

URL in above post request is of Sandbox which you should use while developing and when you are ready to go Live, you should make your calls to:

http://w.inmobi.com/showad.asm

At this point if you check your Firebug or Chrome JavaScript developer tools you should see a XML object with AdURL, ImageURL or LinkText in it. The next step would be how we extract this data and display in our page.

First you need to create an ad ‘holding’ area in HTML, in my case I created it just above the closing content div:

<div>
<a id="bannerURL" href=""><img id="playerBanner" src=""></img></a>
</div>

Next you need to expand your data callback function and include XML parsing capability which should extract the ad data out and show it in ad holding HTML.

function(data) {
        $(data).find("Ad").each(function(){ //find Ad tag and loop through each
        $("#bannerURL").attr("href", $(this).find("AdURL").text()) ;  //get AdURL tag and update 
        if($(this).attr("type") != "text"){ //if ad is not text based
           $("#playerBanner").attr("src", $(this).find("ImageURL").text()) ; //update image src 
        }else{ //in case of text based ad
           if($(this).find("LinkText").text() != "invalid ip-address"){ //ip not found
              $("#bannerURL").text($(this).find("LinkText").text()) ; //just update text
           }
        }
        });
}

Above code should be self explanatory as I have added comments against each line, basically you need to loop through all of the XML, finding “Ad” nodes, then going through each node and finding AdURL (where user will go after clicking on Ad) and updating href attribute of our hyperlink tag in holding HTML then InMobi serve ads in two formats, one is text and other is image based banner ads. If it’s not text ad, we will get ImageURL and update the img src in our holding HTML, if it’s text ad then we will simply update text enclosed in “a” tags.

This should complete your ad integration and you should see a sandbox banner or text in your sub-pages. In my case it did:

Complete code is below:

<script>
var userIP;
$.getJSON("http://jsonip.appspot.com?callback=?",
function(data){
        userIP = data.ip;
        localStorage.setItem("userIP", userIP);
});

$.post("http://w.sandbox.inmobi.com/showad.asm", { "mk-siteid": "4028cba631d63df10131e1d3191d00cb", "mk-version": "pr-SPEC-ATATA-20090521", "h-user-agent": navigator.userAgent,
"mk-carrier": localStorage.getItem("userIP"), format: "xml", "mk-ad-slot": 10 },
function(data) {
        $(data).find("Ad").each(function(){ //find Ad tag and loop through each
        $("#bannerURL").attr("href", $(this).find("AdURL").text()) ;  //get AdURL tag and update 
        if($(this).attr("type") != "text"){ //if ad is not text based
           $("#playerBanner").attr("src", $(this).find("ImageURL").text()) ; //update image src 
        }else{ //in case of text based ad
           if($(this).find("LinkText").text() != "invalid ip-address"){ //ip not found
              $("#bannerURL").text($(this).find("LinkText").text()) ; //just update text
           }
        }
        });
});
</script>
<div>
<a id="bannerURL" href=""><img id="playerBanner" src=""></img></a>
</div>

This provides basic integration of ad API and you can build your ad serving structure on top of it. One improvement would be of adding your in-house ads which would show banners linking to your other apps probably as often InMobi simply do not return any ad when you go live, instead it would show:

<!-- mKhoj: No advt for this position -->

So, it would be wise to handle this exception and in this case show your own ad.

Happy coding!

 

 

Tutorial: iOS Twitter app in 60 seconds using MoSync and Sencha Touch

Assumption for this video tutorial is that viewer don’t know Sencha Touch and MoSync at all, that’s why it is a bit longer than 60 seconds :;)

Introducing MoSync – SDK for Cross Platform Mobile App Development
MoSync is a cross platform mobile application development SDK which allows you to write cross platform apps for as many as 6 different platforms including iOS, Android and Windows Phone 7. Developers can develop their native UI web apps using HTML5 or native UI apps using C++. You can find more information about MoSync on http://www.mosync.com

Introducing Sencha Touch – JavaScript Framework for Mobile Devices

Sencha Touch is a JavaScript framework to write HTML5 based web applications targeted for touch based devices. It is specially designed to support touch based devices. Sencha Touch is from the same people who are behind ExtJs and Sencha Touch 2.0 is largely based on ExtJs codebase. You can find more information about Sencha Touch on www.sencha.com

Let’s get to work!

First step is to download MoSync IDE from www.mosync.com. You can download MoSync Mobile SDK or MoSync Reload which is specially written for HTML5 apps. I have used MoSync 3.0 Mac OSX version for this video tutorial.

The second step would be to have latest release of Sencha Touch with you, at the moment Version 1.1.1 is latest while version 2 is in developer preview only. You will need to give your email address to download free commercial version which I have already downloaded and unzipped on to my machine.

Let’s create our twitter client app. Open MoSync -> go to New Project -> Choose MoSync Project -> Choose HTML5 Project -> Choose HTML5 WebUI Project and then click Finish.
As you can see we have a HTML5 project ready for us now, it’s based on a template, so even if we don’t do anything and run it straight away on the iOS simulator, it will work for us!

A tip for you here will be that beside that you don’t need to configure anything on MoSync to run HTML5 apps, it come bundled with iOS simulator but you still need to have XCode installed on your machine to get it working, XCode is already installed on my MacBook at it’s default location and we can start using it straight away.

Now, back to our twitter client app, when you download Sencha Touch 1.1.1 and unzip the folder, you get examples folder in it, just open the examples folder, find twitter folder in it, copy it’s contents, go back to MoSync, delete all files from Local Folder and then paste the twitter folder contents in it. Then copy sencha-touch-debug.js from sencha touch folder and copy it also in Local files folder in MoSync. Then open index.html and change the path for sencha-touch.js file accordingly.

Now start you simulator again targeting iPad (because twitter example is not supporting iPhone resolution) and hey! you have your twitter client ready to go!
That is that easy! (I know this is cheeky)

Next time I will come back with a tutorial to target the same app to work on Windows Phone 7 and Android platforms.

Till then see ya!

Tutorial: Creating an Ajax based form using Zend Framework and YUI

Many of you would already know that Dojo is JavaScript framework of the choice for Zend Framework. However, Zend framework itself is very loosely coupled that you can use whatever JavaScript framework you are comfortable in. As part of my previous project we were already using YUI, so it was the best idea that while Zend Framework was our choice for our next project, we should stick to the JavaScript framework in which we already have developed our expertise i.e. YUI. As part of developing an Ajax based form, it takes a bit of time to take your head around but it works exactly as the JavaScript should work with PHP i.e. unobtrusive way. The deal is simple, the whole point of using a MVC architecture is that, you have different layers of presentation, controlling and business logic, that makes your code easier to maintain and develop upon, same should be the case of JavaScript you will be using in your application. Just a note that I am using Zend Framework 1.10 for this mini-tutorial.

Let’s get to work!

Say you have a form in your forms directory which extends Zend_Form class:

<?php class Forms_Product_Values extends Zend_Form { public function init() { // Set the method for the display form to POST $this->setMethod('post'); $this->addElement('text','my_timestamp',array( 'filters'=>array('StringTrim'), 'required'=>true, 'label'=>'Time Stamp' )); $this->addElement('text','my_value',array( 'filters'=>array('StringTrim'), 'required'=>true, 'label'=>'Currency Value' )); // Add the submit button $this->addElement('button', 'values', array( 'ignore' => true, 'label' => 'Modify', )); } } ?>
In here, note the last element, button, normally if it is a non Ajax based form, the element type will be the submit but as we do not want the form to submit itself straight away, we would just like to create a button element and give it a name, in this case ‘values’, same as controller name, I will explain this later that why I have used this specific name in our tutorial.
Next you will create a corresponding controller action obviously to handle whatever you want to do with your form input:
public function valuesAction(){ $form = new Forms_Product_Values(); $request = $this->getRequest(); // Check to see if this action has been POST'ed to. if ($this->getRequest()->isPost()) { // Now check to see if the form submitted exists, and // if the values passed in are valid for this form. if ($form->isValid($request->getPost())) { //do whatever you want to do } } $this->view->form = $form; // disable layouts for this action: $this->_helper->layout->disableLayout();
}
and not values.phtml which will act as a view for our controller action:
<?=$this->form?>
OK, up to here it was simple, straight form without submit button in the form, now we need YUI to act here. You can either create a separate JS file (always recommended) or just paste your JavaScript code in the values.phtml (your view file) which is not recommended however, I am doing that just for demonstration purpose of this tutorial!
Here is you updated values.phtml:

<!-- Combo-handled YUI JS files: -->
<script type="text/javascript" src="http://yui.yahooapis.com/combo?2.8.1/build/yahoo-dom-event/yahoo-dom-event.js&2.8.1/build/connection/connection-min.js&2.8.1/build/selector/selector-min.js"></script>
<script type="text/javascript">
function fnCallback(e) {
sUrl = e.currentTarget.id; //controller name is the same as button name;
var nodes = YAHOO.util.Selector.query('input');
//prepare the data in query string format var data = ""; for (var i = 0; i< nodes.length; i++) { data += nodes[i].name+"="+nodes[i].value; if(i != nodes.length-1){ data += "&"; } }
var div = document.getElementById("responseDiv");
var handleSuccess = function(o) { //upon successful response we embed the response text into responseDiv on our HTML page div.innerHTML = o.responseText; YAHOO.util.Event.addListener("submitButton", "click", fnCallback); }; var handleFailure = function(o){ //if the request if failed, we need to log the event if(o.responseText !== undefined){ div.innerHTML = "Failed request to the server. Please try again."; } }; var handleEvent = { start:function(eventType, args){ }}; var callback = { //on start call back calls the handle event which starts showing ajax loader image customevents:{ onStart:handleEvent.start }, success:handleSuccess, //parameter to define which function to use on success failure:handleFailure, //parameter to define which function to use on failure timeout:1500 //timeout is 1500ms, can be extended from here }; var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, data); } function init(){ YAHOO.util.Event.addListener("values", "click", fnCallback); } YAHOO.util.Event.onDOMReady(init);
<div id="responseDiv">
<?=$this->form?>
</div>

See, no rocket science, however, couple of things to note, I am using a different approach here to remember controller name, I have assigned the same name to the button as the controller i.e. ‘values’, on click event the listener fires fnCallback function and then I read what is the id of the button, hence I know which controller is this and that is all I need as sUrl (the URL which I need to call, you may also need to concatinate “../../”+e.currentTarget.id),  another approach you can use is to echo the controller name in a hidden span or div in the view and then just read it from the JavaScript on click or if you can come up with any other approach, kindly post in comments of this tutorial for others to use.

Then is the YAHOO.util.Selector.query(‘input’), the beauty of YUI become handy here, as in this form I only have input elements I want to read, however, if you want to read say for example all the select and textarea elements, it is simple, just use this YAHOO.util.Selector.query(‘input’, ‘select’, ‘textarea’), now you know how to harvest your inputs from your form, you pull that on into the data variable and make the normal Ajax request through connection manager utility of YUI. The only bit remains here is, because your controller action is same, when you will send a request to it, your whole form will regenerate itself (which is intentional as in the controller I am actually making a database call and I want to show that whatever user has modified is actually in the database now) so you will loose the listener which you attached earlier to the button, you have to add it again on receiving the response, however, in this example, I have hard-coded it, you may want to send it dynamically with function call so that your function become totally dynamic and you could use same with all of your forms, I leave that upto you!

Happy Coding!

YUI Button: Mimicking the native Select dropdown to avoid IE width problem

This is the 5th installment in YUI series. This installment uses YUI button widget and YUI keylistener utility. Although this post and example mimics the default SELECT element behaviour and look but you should also consider the JavaScript execution overhead this will cause.

Microsoft in all it’s glory continued to develop it’s own web standards, avoiding to support any open industry standards but then as technology progressed, word spread, people got knowledge and resources, open-source alternatives started to come into the market which now threatens the very existence of Microsoft itself. Yes, I am talking about the browsers at this moment, what Firefox and Google Chrome has done against a browser which comes pre-installed with an operating system which most of the people around the world use, yes the mighty IE (Internet Explorer).

As being a web-developer, you most probably would know the pain of working with IE. Although it has the developer tools now which makes the life a bit easier but what about it’s own implementation of DOM which is the only implementation and for this browser only,  a developer always feel forced to insert conditions in his/her code just so the code can work on IE as well. Anyway, this is something we all know about and can’t do anything until Microsoft thinks of something else. Let’s get to the business!

The problem with IE Select dropdown

IE Select dropdown width problem

If you are a web developer and you ever worked with a select dropdowns in your projects, you know this problem very well. IE by default don’t adjust it’s drop down panel according to the width of the longest text size. There are already work-arounds available and couple of them are based on YUI itself but they don’t mimick the exact look and feel of our old select dropdown list. I wanted the exact same look and  functionality of native SELECT element. I will list the work-arounds I founds:

Why a new fix?

Good question! The first fix I told you here, involves animation, when you get your mouse on the select element, it will animate itself to with of longest text option element, doesn’t look good to me as I think normal web user do not expect that to happen!

The second fix, had two major problems:

  • Scrollbars, my lists were very long as you will see in the example. By default YUI menu button’s scrollbars appear at the top and the bottom, if you increase the scroll rate for faster scroll, not very user friendly.
  • It didn’t had the important feature of selecting the options through keypress, I mean if you press B in normal select dropdown list, it will take you to the first item which is starting with B.

The fix itself!

Ok Ok, I think I am talking too much and few of my fellows will be in a hurry to get the code, copy paste it and get it done! Well, alright, the example is here:

Example: Work-around for fixed-width SELECT element

Explanation – The CSS

In fact I have modified the official YUI2 example.
First we need the same look as traditional select menu dropdown has. However if you want to make it more pretty, the CSS is here, do whatever you like to do, maybe using default arrow image of YUI is a better idea.

So, for the CSS, just as we override the default CSS rules of YUI skin sam:

.yui-skin-sam .yui-menu-button button {
    background-image: url("http://ciitronian.com/examples/images/select_arrow.PNG");
    outline: none;
    	font-size: 0.8em;
    	width: 15.2em;
    	background-color: #F8F8F8;
    	cursor: default;
    	line-height: 1.3em;
    	min-height: 1.45em;
	}
	.yui-skin-sam .yuimenuitemlabel:visited  {
	color:#000000;
	}

	.yui-skin-sam .yuimenuitemlabel  {
	color:#000000;
	cursor:default;
	padding:0 20px 0 0;
	text-decoration:none;
	}

	.yui-skin-sam .yuimenuitemlabel:hover  {
	background-color: #111166;
	color: #ffffff;
}

and a bit of tweak to YUI’s official example em class of button to make it look like a classic one

        /*  Restrict the width of the label to 10em. */
        width: 10em;

Our YUI menu button has got the classic look of SELECT element. Now the bit which I refer to as a nasty tweak, YUI menu button comes with it’s own scrollbars and as I mentioned earlier, if  you have a very long dropdown list, like a list of all countries in the world, the scrollbars functionality is not very useful. YUI gives you the flexibility to disable the scrollbars but I actually needed a vertical scrollbar so, what I did, I made the YUI scrollbars hidden!

Here’s what I did:

/*hide the YUI scroll bars*/
.yui-skin-sam .yuimenu .topscrollbar,
.yui-skin-sam .yuimenu .bottomscrollbar {
    height: 0px;
}

What it’s doing? Simply overriding the overriding the CSS property of height and setting it to 0. It hides the top and bottom scrollbars altogether. Next we need to turn the overflow to auto for yui menu body:

.yui-skin-sam .yuimenu .yui-menu-body-scrolled {
    overflow: auto;
    padding-right: 10px; /*to prevent horizontal scroll*/
}

If you just set overflow to auto, there will be just about a couple of pixels which will get over-flowed horizontally as well, to make it right, the padding property is there.  The padding-right property in div.yuimenu .bd is also there because IE8 was not getting right even if after the above rule.

Explanation – The JavaScript Code

The other JS code is almost the same as you will find in the official example but as mentioned earlier there were only two problems, the scrollbar, which we have already fixed through CSS, now the sorting or whatever you call it that when you click for a character, the first of it’s appearance should get selected automatically. So, all we need is basically a YUI keylistener with a correct scope and then we need to have a functionality which gets all the menu items text in an array, traverse the first character of each text element and then if matched, scroll to it and select it with the correct focus.

The keylistener code:

var kl = new YAHOO.util.KeyListener("select-1-container", { keys:keyArr },
			   { fn:labelCharCode,
				 scope:oMenuButton1,
				 correctScope:true } );
kl.enable();

The keylistener code select-1-container as first argument to give it correct scope. Notice the loops before this code in the source code of example, 65-90 are the keyboard character codes for A-Z characters and 48 to 57 are 0-9 characters. Next, keylistener calls the labelCharCode function with the keypressed event type, and arg[0] has the character which got pressed.

Now, the YUI Menu has a useful method of getting all items in a menu, as you see in the source code, I have used it to get the menu items:

var MenuItems = oMenuButton1.getMenu().getItems();

Now, in the labelCharCode, we have got the character which user has pressed, we need to match it with the first character of menu item. We access the text property of all menu items in a loop, slice the first character, match it in a if else block, if matched, simple old window.location takes us to the id of that menu item and then we fire the focus event for that menu item.

for (var i = 0; i < MenuItems.length; i++) {
			var firstChar = MenuItems[i].cfg.getProperty('text').slice(0,1);
			if(firstChar === Character){
				window.location = "#"+MenuItems[i].id;
				MenuItems[i].focus().fire;
				break;
			}

That’s it your SELECT dropdown element is ready which will work in all browsers and will adjust itself with the width of longest item in the menu!

Things which are still nagging me

The above code works as you may see in the example (I only tested that in IE8, Firefox 3.6 and Chrome 5), however I personally don’t like the concept of matching in a loop and slicing. I tried using YUI DataSource for this purpose but what I have seen in the YUI source code is that, it takes LocalDataSource array as it is and then apply matching on it, probably DataSource is more useful for remote data. However, I left it there after I tried seeing the code of AutoComplete widget and DataSource together, maybe I need to give it a bit more investigation. However, I dislike the current approach of this example because of processing involved. If you have a better understanding and know a better way of doing this, kindly embed the example or simply let me know, that will make this fix better!

Happy Coding!

Get String Length Tool

Just a bit of background, I was working on live data coming through from Java applets into Javascript, there were strings which I had to match, the conditions were like if (thisID === “blahblahblah”) and there were a lot of them, I had to match strings and then do my stuff, the strings were all different, I had to cut each string into sub-strings because there was a variable portion of every string which I didn’t wanted to match. The result you can imagine is that I was sitting there, counting each string character by character and then putting a condition on it. Got the idea of this tool then (obviously I am lazy when it comes to code), just input your string, get the length, put it as a parameter for the Javascript equivalent of PHP substr or maybe use slice() method of JS and move on! Here is tool:

When I actually searched for such a simple tool online to find a string length straight away (like I have seen a simple tool the other day to convert px values in em for CSS), couldn’t find any (maybe there are but I couldn’t find them). However, when you will search you will get lots of functions in every language (C, C++, Java, Javascript etc.) to do that but what if I only want string length and don’t want to write a line, execute it, know the length, erase it and then continue? Well, here is one, it helped me, it may help someone else too!

Happy Coding!

Current Airline Situation: Where is the Volcanic Ash Cloud now?

The biggest news in April 2010 that the air-space over UK and several other European countries was closed due to the fears that volcanic ash cloud from Eyjafjallajokull volcano in Iceland can damage the airplanes, I got this news one fine Monday morning while going towards tube escalators that due to volcanic ash the airports are closed and passengers are advised to contact their airlines before leaving home. I never thought what could be the consequences of it, apparently the airspace remained closed for several days, caused airline industry millions of dollar damage and misery to the passengers who were caught oversees with no funds in their wallets.

Eyjafjallajokull Volcanic Ash Cloud

Well that is nature, I being a big supporter of nature and most of the time in-peace with whatever nature do with us, it always has a reason. Several of my friends marked it as the end of earth as there were couple of earth quacks in the world around the eruption as well but sadly what they forgot was when millions of years ago when earth was in it’s early stages,  the seismic activity was far frequent and was at a much larger scale. In fact today we make movies about the Ice Age is coming due to global warming etc. while we had an Ice Age before when likes of were not even on earth!  The only difference now is, we see every bit of this live on our television screens and our airspace get closed because of this and then in our comfortable routine lives, we think, oh that’s bizarre, no for me it’s not!

Well this disruption which this ash cloud is causing and will continue to cause for several days, holiday industry will be the one who will suffer most  this summer. I know this because I planned to go out traveling on next bank holiday weekend which is from 29th May to 31st May. Due to this cloud, I looked at euro-star website, even before good 3 weeks the prices were already near £86 one way for Paris. I had been to Paris last summer, that’s a wonderful city but can’t give that much money to just to be there again. After considering several options, I am now booked with Ryan Air for Stockholm. The ticket was cheap but now I am not sure whether I will be able to fly or should I have a plan B ready in case of disruption.
As I am now tracking this ash cloud from several days (since I booked my ticket), I now know that it all depends on the winds, the big ocean currents which rule the weather of earth. This ash cloud will be there for several months but it will keep on swaying itself. As UK is nearest to Iceland, the most disruptions will be caused here but again depends on the direction of wind. Stockholm again is not very far away.
As the ash cloud today again caused some airports to shut down for couple of days in south-east England which has the most busiest airports in UK, the MET office UK which is also acting as the main outlet to hand-out ash cloud predictions have decided to list next 5-days predictions of cloud direction on their website instead of only 18 hours.
So here are the charts for next 5 day prediction of volcanic ash cloud on MET Office UK Website. If you are like me, going out soon, booked your ticket and now praying that this cloud do not come on your way, you need to keep an eye on the cloud, we have the science to predict but do not have the science to control it. It’s nature at work!

PIA: Pakistan International Airlines Pilot refused to fly from New York to Lahore

I would like to clarify it first that I am a very loyal customer of PIA (Pakistan International Airlines), the reasons of this I will explain later in this blog. First, I would like to talk about a tiny news appeared in the 2nd May, 2010 Jang Newspaper which reported that pilot of PIA flight PK-712 refused to take the plane back to Lahore from New York because of non-availability of the rest cabin for the crew. Here is the snapshot of that news:

Snapshot of news appeared in Jang May 2nd, 2010

According to the newspaper, the flight leaves New York at 5:30am and in alternate crew, there is always a pilot and first officer which rest for first 8 hours of flight and take charge of the plane for the next 8 hours. I have checked the flight duration on PIA’s website and it is almost 16 hours. The requirement of alternate cock-pit crew is compulsory due to international safety standards.

PALPA (Pakistan Airline Pilots’ Association) took this matter to the international authority about 5 days before this incident. Newspaper further told that the administration of Airline is thinking of operating the flight with a stop in Manchester on the way-back, so the cock-pit crew can be changed at Manchester Airport.

Later that day, I read on the Newspaper’s latest news that PIA has denied the fact that the pilot has refused to fly any flight and this flight will leave New York at its due time.

As a frequent air traveler and a avid fan of Discovery’s Air Crash Investigations, I got worried after reading this news. This was a very small news in the inside pages but I know exactly how this can be the cause of a very big news if a crash happened just due to this. National flag carrier has 9 Boeing-777 airplanes including Boeing-777LR and holds the record for longest commercial jet flight in aviation industry. The airplanes are made for long range flights specifically and were bought to cater for Toronto, Chicago and New York flights basically. However, while it gives you a great flexibility of operating at longer routes, it gives you a great responsibility of handling the flight safely without any break on the way.

The New York flight takes a break in Manchester on it’s way from Lahore to New York while on the return it come as a direct flight and takes about 16 hours. I am sure that while ordering an airline can ask for any modifications in the plane seating-wise and I am sure the original design would have a rest cabin included with the airplane as the airplane was intended for long-haul flights and I am sure again that PIA would have asked to remove the cabin to increase seating capacity.

PIA-777ER at runway

What makes me worried is a tired pilot who remain seated for first 8 hours of the flight and then he would be flying the plane back to the safety of airport for the next 8 hours. Everyone in airline industry know what a tired pilot flying an aircraft means, a flight in danger of a clash if anything goes wrong, obviously if the pilot is tired, his capability of handling potential hazards would be very low than a fresh pilot. We have seen many airliners crashing in bad weather, low visibility areas or in case of engine failures because either the pilot or first officer was tired and they missed the steps to handle the hazard.

Recently, another news in the same newspaper I read was about the maintenance of these multi-million dollar airplanes (Boeing-777) because the hanger for these airplanes were not made at the home of PIA (Pakistan International Airlines), the Karachi Airport. As of this reason, PIA is already not maintaining these airplanes properly and at times the flights are getting delayed due to security reasons in flying a faulty aircraft.

PIA has recently reported a surge in it’s operating profit which remained about Rs.5 billion in the past year. However, if you are not maintaining the safety standards and stretching your crew to get profit, that is a very risky bet, if in-case an aircraft got crashed due to these reasons, the airline would not only lose it’s multi-million dollar investment in the aircraft but also hundreds of lives along with a bad name for the airline.

I am a frequent flyer with PIA and always choose this airline whenever I go back  home. The reasons behind why I always choose this airline are not that it is a great airline to fly with or they are very hospitable (steward never reply the call, I always have to go to the kitchen myself to drink water), the PIA tickets are not cheap if compared to other airline’s fares and they are not that great in flying according to schedule (flights are often late). The reasons are, number one you get a direct flight from London to Lahore, you are in Pakistan in 8 hours, you do not need to change planes etc. If you take Emirates or Etihad or any other airline, obviously they stop at their home airports en-route. Second reason is much emotional, when you are traveling with PIA, the time when you get to your departure gate, you feel yourself as you are in Pakistan because the passengers and crew will be of your country and that makes you more happy, while coming back until you don’t leave the exit gate of heathrow airport, you again feel yourself at home, within your own people. Other than this, in-flight meals are just OK, the floors are dirty and because mostly it’s Boeing-777 which operates at heathrow route as well, the LCD screens for entertainment on the back of seats are starting to pose problems as well. It never happened with me yet but the passengers sitting beside me, normally their in-flight entertainment system will not work and they will keep on complaining and stewards will keep on saying that I am looking at the problem and nothing will happen. Obviously the airline is not taking care of it’s assets and it’s name.

PIA is our national flag carrier and despite of the fact that I am concerned with the safety of it’s airplanes and other factors, I will keep on flying with this airline as for the reasons I stated above. However, the airline itself need to give itself some fact-check and see what can happen if they keep on ignoring it’s crew and the maintenance of it’s aircraft.

Pakistan’s WAPDA and WAPDA’s website both got hacked!

Get Pakistan Breaking News app for Android now!

I recently came back from Pakistan and as most Pakistanis I was concerned with frequent power blackouts there. These power blackouts are known as load shedding in Pakistan as WAPDA (Water and Power Development Authority) and it’s controlling authority PEPCO (Pakistan Electric Power Company) try to manage the load across the power grids so none of them get blown off. The result of short fall of more than 5000MW daily is that public is sitting idle without electricity for more than 12 hours daily.

As a professional in web services I want to know every thing from the Web and on times I felt the urge to log-on to WAPDA’s website to get to know what is actually happening. What I would expect from the authority, is that, their website would have a map of Pakistan, which would get updated live through AJAX or it could be a Java applet which show you how many MWs are currently available, how many of them are actually getting distributed, how much are the line losses and how much is the demand. Then on the map additionally, you could see which areas are out of electricity at the particular moment.

I know that WAPDA will not do this ever until the political and bureaucratic structure of the authority get changed. The reason behind is, WAPDA has the capacity to generate more than 19,000MW a day through it’s own hydel power plants and through other IPP (Independent Power Producer) plants across the country. WAPDA hasn’t deliberately paid the payments to IPPs which in turn hasn’t paid fuel supplying companies, so those power plants are actually not running on their full strength and the power at the end available in the country is around 12,000MW a day.

Let’s take that in a bigger picture, when the government could get a loan of more than 7 billion dollar from international agencies with in a time frame of 2 years, it has taken too much loan from inside the company as well, why it couldn’t just pay back the IPPs debt which is around 100 billion Pakistani rupee (approximately 1.2 billion dollars) and due to only this reason, the whole country is in trouble including the industry and commercial sector and only this reason is causing a halt to growth and pushing the government to take more loans.

Yes, the last point is the answer, this is the game to pressurize the people of Pakistan so that they do not see toward the so-called war on terror game at the borders of Pakistan, secondly so that Pakistan should take more and more loans so like today, when international agencies ask something from us and we say we would not do that, they will say OK we will not release any more funds for you and as we will be down to our knees, we will do as “they” say.

Now on the corruption side of current “democratic” government of Pakistan, which country on earth would install more power plants when you have enough capacity available already and about 40% of it is not in use because of fuel supply? Well, the country’s name is Pakistan. In lieu of this scenario obviously Mr. 10% would like to have a bigger share out of his presidency, so what we are seeing is the Minister of Power saying again and again that it is due to the non-availability of power generation capacity (when 40% is idle) and then Pakistan is getting rental power plants which are expensive to get and install and more off they run on same kind of fuel which you are already not supplying to current power generators. The only purpose seems here to get kickbacks from those rental power plant operators.

This is a well known fact and every Pakistani is aware of that, anyway I got diverted here too  much from my subject, the reason behind is obviously to let the reader know that why WAPDA would not put this all live information on their website because that will put the orders in transparency and that is what the international pressure and local government do not want (that’s against the interests of those nations).

However, the grip of WAPDA’s IT department is so weak that when I searched wapda on Google and that is my habit which saved me here that I always search rather than typing in the address bar, the Google told me that visiting this website can be harmful. This is a bit shocking as the website’s domain is gov.pk and it is a government’s website, however I checked that on 7th April, the date of writing of this blog is 10th April and who knows from how long it has been hacked. Well hacked is probably not a right word here, what probably has happened that the OS it’s developer is using is pirated (shouldn’t be a shock, it’s WAPDA) or he has been installing pirated software on the system and there is probably no anti-virus on the web developer’s system as well as web server. So, this malware got it’s way all up to the one of the most important websites of Pakistan.

Here are few screen shots:

May Allah bless Pakistan!

Get Pakistan Breaking News app for Android now!

Tutorial: Using IE Developer Tools as Firebug in Mozilla Firefox

There was a time when development for Javascript and CSS was restricted mainly because IE was the only main browser around (basically because it was shipped with your copy of MS Windows) and even the other browsers like Opera and Netscape were not able to listen to the web developer needs. Then came around, Youtube, GMail, Facebook, all of them giving rise to the concept of RIA (Rich Internet Applications) and at the same time Firefox was launched (2004). Firefox was an open source project which in turn allowed thousands of developers around to write what they want as plugins and someone came up with the idea of Firebug, that bug caught the web development community like fire and this plugin has more than 117,085 weekly downloads at the time of this writing. If  you ask any web developer that which plugin is his/her favourite, firebug will always get mentioned at the top and due to all good reasons. I remember coding Javascript before the firebug, when to check and debug a javascript array, I would have to write alert(array.length) and that will pop-up an alert box with array length and then imagine my page is getting updated after 1 second or that array is in a function who is running in loop.. bang! … just to inspect an instruction in that loop, that alert box will appear after every 1 second and ultimately I would have to kill my browser to get rid of it. Not the case any more. Then came around Ajax, I remember JS frameworks such as YUI and jQuery weren’t around in those days and I wrote my first function to make an Ajax request using XMLHttpRequest and after that telling my colleagues that the problem in writing Ajax code is that, you don’t get to see what is happening behind the request. A real nightmare? well we are lucky now, that dark period for client-side web scripting is over.

I don’t think if you are a web developer and you are not aware of firebug but this can be the case that you are a web developer and you are still sticking with the Firefox just because you love firebug and web developer toolbar. Most non-techie people around the globe still love IE (some of them are still on IE6 because that came with their MS Windows XP installation) and they constitute more than 70% of  the total, so if you are going to develop for general public or for a client who just couldn’t understand that why I don’t use IE and why Firefox is my favorite browser, you need to have a look at your web application in IE before shipping it and I am telling you it could always go wrong as you may be calling a function whose one parameter Firefox is ignoring and still executing the code while IE wouldn’t ignore and will stall altogether. Luckily, IE8 comes bundled with IE developer tools (developer tools were around from some time but installing them on and off was a real nightmare, at-least for me). But yes I can hear what you are saying, most of the times, IE will throw an error and it will have very “helpful” error description such as “Unspecified Error” and it will point at totally wrong line in the source code and you will have to do your guess work to eliminate the problem, anyway, with developer tools you could see something in place of nothing.

Enough discussion, here is your 3-minutes crack-on graphical tutorial to use IE developer tools just like your native firebug console and web developer toolbar on Firefox.

First load your desired web page in IE8 which you want to inspect by pressing F12 or by selecting Tools > Developer Tools in IE8.

Second always remember that to inspect a script you need to select it first and start debugging.  In IE Developer Tools > Script tab > Select script > Start Debugging

Selecting Debugging Source

Inspecting Javascript Variables

The most convenient use of firebug for me is of seeing the JS variable values as I develop a complex client-side application. As I discussed above, you don’t want to see alert boxes again and again, IE developer tools, do that for you in two ways.

You can use console to see any output messages. To differentiate between these messages, different console.log APIs are available:

  • console.log
  • console.error
  • console.warn
  • console.info
  • console.assert

My favorite in firebug was console.debug but I left using that long ago because IE Developer Tools do not support console.debug and this will break your code. Secondly firebug allows you to format those error message, IE  Developer Tools do not support that (or at-least something I am not aware of). The output of these console messages will be exactly like something you see in firebug. For the record, you write code like this:

var myvar = 0;
console.log(myvar);
console.error(myvar);
console.warn(myvar);
console.info(myvar);

IE Developer Tools Log Messages

The other way is slightly different, can be used for the same purpose but is related to only variables, you are able to see variable values at your breakpoints, so you have the time to analyze them.

To create a break point, hover your mouse on the line number you want to mark as break point and click, a red dot will appear on the left beside the line number, now when you will start debugging, browser will stop executing it just before the line you marked as break point.

Then go to the right hand pane of IE developer tools and select Watch > Click to add the variables you want to see and developer tools will let you know the variable name, value and type at the break point.

Watch variables at break point

You are able to change variable values at this moment as well, just when you are watching a variable in Watch tab, open Console tab and assign new value to the variable to see how it will behave after you hit Play again. In the same manner you are able run any instructions which are not in source code but you want to run them at break point to analyze the effect.

Part 1: Running script at break point

Part 2: IE Developer Tools console with new variable value

Now go back to the Watch tab and see the updated value.

Part 3: Watch updated variable value

Profiling Javascript

Another important need for a web developer who do not think that JS is just a scripting language and it just has bits like getting an element and changing it’s value at run time etc. but it is so important that the developer actually needs to optimize the run times and to see how many times a function is getting called, JS profiler is just what saved our lives in firebug, it is here too in IE Developer Tools.

You need to select Profiler tab in Developer Tools > Start Profiling, do something on your page like refresh or wait for sometime if that is something you want to check and then Stop Profiling, Developer Tools will give you a complete report of JS activity done in that time span, listing Functions, count of the calls made and inclusive, exclusive time etc. Same information can be seen in Call Tree view if you select call tree from Current View.

Javascript Profiler

View Generated Source

If you ever worked with Ajax, you would probably know the importance of seeing the DOM once your Ajax call has been made and your DOM has got updated. In Firefox I use Web Developer Toolbar to see Generated Source, in IE Developer Tools, you can view the same by going into View > Source > DOM, you can view the Original source code and the selected element’s DOM as well.

View Generated Source

Outlining Elements on the Page

Another important tool of firebug is when you can outline the elements on your page to see where they are residing, like the divs or tables etc. I specifically use Web Developer Toolbar instead to outline and see the cause of cosmetic issues. IE Developer Tools comes with this solution as well. You can go to Outline in menu and select the type of elements you want to outline or to select an individual element you can go to Any Element and add the name of the element to view outline.

Outlining Elements

There are plenty of other functions which Developer Tools support like you can also see the CSS of an individual element by going to Find > Select Element by Click and then clicking on the element, just like you do for inspect element tool in firebug. You can view Images information or disable scripts, CSS, change the browser modes to render the page in IE7, validate your HTML (this will take you straight to W3C website and if you are working on localhost on your system, chances are W3C will refuse to check your code), CSS etc and you can even re size your browser to see your pages in different resolutions.

There is no doubt, Microsoft was under pressure from the developer community to bundle the developer tools with IE because after the arrival of Firefox, the whole development scenario got changed and developers want to develop more rich applications for the web. I personally havn’t adopted IE for my core development but it is handy to check my code every now and then in IE to see if everything is fine there and if not, using Developer Tools makes the life easier by allowing you to debug the code.

Feel free to comment if you have anything to say!

About me

Just another Londoner writing about life in the city, politics in general, technology and other gossips. Keep following as this will not be like any other blog.

If you want to get in touch personally, feel free to ping me on linkedin:

http://uk.linkedin.com/in/hammadtariq

Get Adobe Flash player