Adsense

Javascript code to retrive the dojo form data

function getElements (widget){
    var tempf= widget.formFields;
    var ids = {};
    for (var data in tempf){
        var obj = widget.formFields[data];
        ids[data]=obj.fieldWidget.id;
    }
    return ids;
}

function getWidget (form , widgetId){
    var formSection = form.sections;
    if (formSection!=null){
        for (var data in formSection ){
            if (widgetId==formSection[data].sectionId){
                return getElements(formSection[data]);
            }
        }
        for (var data in formSection){
            return getWidget(formSection[data],widgetId);
        }
        }else{
    return ;}
 
}

function getElementIds( formId , widgetId){
    var form = dijit.registry.byId(formId) ;
    var elementId = getWidget(form,widgetId);
    return elementId;
}

function data () {
    var data = getElementIds("formid1","widgetid1");
alert(data);}
return data();

Free Youtube school - Examfear.com

She wanted to do PhD and become a teacher, but after her father's death she had to take up a job in an MNC. However, Roshni Mukherjee found a way to teach tens of thousands of school students for free.





She launched Examfear.com to post video lessons for classes 9 to 12, and her YouTube channel has more than 68,000 subscribers. She has shared around 3,700 videos in the past four years, which means more than two video les sons posted per day .

"It began when my maid told me her two children kept failing in their exams be cause teachers in the government school in Tamil Nadu, where they studied, would rarely come to class. These were the children I wanted to reach out to," she said.

As technology offered the best solution, she uploaded a video on YouTube, explaining the physics concept of motion. She used a Powerpoint slideshow and a microphone to explain the concepts. As there was a good response, she started posting more video lessons


"After seeing the videos, students started asking doubts in the comments section and also requested for video lessons on specific topics. I was happy to help," she said. She spent a few hours on weekdays and all her weekends preparing the videos lessons in chemistry, physics, mathematics and biology .


She initially prepared videos for classes 11 and 12, but soon expanded to classes 9 and 10. "I refer CBSE syllabus and brush through ICSE syllabus to add any points I may have missed out. The videos are simple: made on Powerpoint (slide shows) with a voice in the background explaining the concepts," she said.

Now, Roshni wants her videos to reach the remotest corners of the country. For this, she has to translate the videos into regional languages.

"That is the next course of action -making these videos into regional languages such as Kannada, Tamil and Bengali," she said.

Over time, Roshni hopes to expand her classes to junior grades and also subjects such history and geography .


Source : http://economictimes.indiatimes.com/articleshow/48021095.cms

How to read or save browser javascript console log using selenium


You can use the following code snippet:
for (LogEntry logEntry : driver.manage().logs().get("browser").getAll()) {
      System.out.println(logEntry);
}

How to add system time to VLC player ?


  1. Go to Tools > Preference
  2. Change Show settings from Simple to All
  3. Uncheck the only show current option
  4. Type in the search box marquee
  5. Select Subtitles/OSD from the list
  6. Check the box marquee display found in overlays
  7. Select from the list ;subsection Marquee which is in Subtitles/OSD
  8. In the Text box type Time:%H:%M:%S for time and Date:"%d/%m/%Y for current date
  9. Tweak the marquee properites in marquee display according to your convinence
  10. Save the preference and then run a new video

VNC client for Windows with copy/paste

vncconfig -nowin&

TOI article: techie drives cab to pay edu loan

CHENNAI: As a cab driver with Ola, R Arivazhagan, 24, is sweet. He opens the door for you, inquires if you are comfortable with the AC level, and offers you a candy before the ride. It's tough to realise that his life has been bitter.

After parking his rented car in the evening, he leaves for his real job that will keep him busy as a systems administrator at Cisco Systems, till 2.30am. The BE computer science graduate from a remote village in Dharmapuri says IT is his career, but it's the cab driver's job that would help him repay an education loan.

"My take-home salary of 9,500 won't be enough to sustain myself. I make more than double the amount as a cab driver. And that takes care of the monthly interest of 6,000 on the loan my father had taken for my studies at Paavai Engineering College, Namakkal."

C Ramakrishnan, a farmer in Dhomallahalli near the Karnataka border, had borrowed 2 lakh from a usurer to pay his son's fees that came to 1.1 lakh a year. "My parents grew vegetables, but with scarce rain, farming couldn't sustain our family of four," says Arivazhagan. "So my father worked as a labourer at construction sites in Bangalore." Arivazhagan's brother, a diploma holder in civil engineering is hunting for a job.

Driving the cab, the 24-year-old makes 800 daily, which is 30% of the day's earning. The rest goes to the car owner. He sleeps for four hours after returning from work at 2.30am. He drives the cab from 7am to 5pm before getting ready for the night duty. "It's tiring, but it's ok as long as this lets me repay the loan," he says.

It's the lack of recognition, he says, that troubles him more. "Having studied in a government school in Dharmapuri, I know my limitations," he says. "I don't speak good English, but why should that be a reason to deny me a job in programming which I may be good at?"

Nasscom regional director K Purushothaman has the answer: "Communication is of paramount importance. Every employee will have to communicate at two levels — with colleagues and clients. With just technical knowledge, one cannot rise in the industry. In this case, he wouldn't have been among the 70%-plus category of students who companies pick up from campuses. But employees can upgrade their technical and communication skills by taking refresher courses, but they are costly, and I suppose someone with an education loan and an economically poor background may not be able to afford it."

Arivazhagan realizes that. "I don't see myself making a professional leap, but I am sure that I will be better off with my efforts," he says. "I will make sure that my child gets an education in English. No point cribbing."


http://timesofindia.indiatimes.com/city/chennai/Techie-drives-cab-after-work-to-repay-education-loan/articleshow/47335845.cms

Java hashmap example



import java.awt.AWTException;

import org.apache.commons.collections.map.HashedMap;



public class myclass {

static HashedMap hm = new HashedMap();

public static final String timeXpath = ".//*[@id='tableID']/div[1]/div/div[2]/table/tbody/tr/td//div[text()='Time']";
public static final String severityXpath = ".//*[@id='tableID']/div[1]/div/div[2]/table/tbody/tr/td//div[text()='Severity']";

public static void init() {
hm.put("timeXpath", new String(
timeXpath));
hm.put("severityXpath", new String(
severityXpath));

}

static String SortingColumnList[][] = {
{ "Time", "1", "timeXpath",
"sortable-ascending" },
{ "Severity", "2", "severityXpath",
"sortable-ascending" } };


public static void main(String[] args) throws AWTException {

init();
for(String[] items :SortingColumnList)
System.out.println(hm.get(items[2]));
}

}

Kill the vnc session

ps -ef | grep username | grep vnc

kill -9 pid

or

VNC servers with display numbers :1 and :2 respectively, and can be killed by

vncserver -kill :1
vncserver -kill :2

Mouse hover and other mouse events in WebDriver

public static void MouseHoverByJavaScript(IWebElement targetElement)
{

string javaScript = "var evObj = document.createEvent('MouseEvents');" +
"evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);" +
"arguments[0].dispatchEvent(evObj);";
IJavaScriptExecutor js = _driver as IJavaScriptExecutor;
js.ExecuteScript(javaScript, targetElement);

}

selenium javascript executor

String popupAlertId = popupAlert.getAttribute("id");

JavascriptExecutor js1 = (JavascriptExecutor) driver;
String jscript = "function data() { var data = Document.getElementById('"
+ popupAlertId
+ "').innerHTML; return data;} return data ();";
Object scriptOutput = js1.executeScript(jscript);
Logging.log.info("scriptOutput " + scriptOutput);

TCL regEX parsing

set Output " ---
   enabled: no
 ..."

 if {[regexp -nocase -- {enabled:[ \t]+([^\r\n]+)} $Output - defaultState]} {
puts "Default State status is: $defaultState"
}


The output is :

sh-4.2# tclsh main.tcl                                                                                                                                                                                                                        
Hello World!                                                                                                                                                                                                                                  
Default State status is: no    

Diesel vs Petrol CAR

A simple tool to compare the prices of Petrol car and Diesel car and display the breakeven point.



http://aravindavk.in/diesel-vs-petrol-car/

Prototypal Inheritance in JavaScript


var circle = {
    radius: 5,
    create: function (radius) {
        var circle = Object.create(this);
        circle.radius = radius;
        return circle;
    },
    area: function () {
        var radius = this.radius;
        return Math.PI * radius * radius;
    },
    circumference: function () {
        return 2 * Math.PI * this.radius;
    }
};

var circle2 = circle.create(10);


function Circle(radius) {
    this.radius = radius;
}

Circle.prototype.area = function () {
    var radius = this.radius;
    return Math.PI * radius * radius;
};

Circle.prototype.circumference: function () {
    return 2 * Math.PI * this.radius;
};

var circle = new Circle(5);
var circle2 = new Circle(10);

Javascript interview questions

Basic JS programmming

Scope of variable
What is Associative Array? How do we use it?
OOPS JS

Difference between Classic Inheritance and Prototypical Inheritance
What is difference between private variable, public variable and static variable? How we achieve this in JS?
How to add/remove properties to object in run time?
How to achieve inheritance ?
How to extend built-in objects?
Why extending array is bad idea?
DOM and JS

Difference between browser detection and feature detection
DOM Event Propagation
Event Delegation
Event bubbling V/s Event Capturing
Misc

Graceful Degradation V/s Progressive Enhancement

Javascript constructor example

 function Point(x, y) {
        this.x = x;
        this.y = y;
        this.dist = function () {
            return Math.sqrt((this.x*this.x)+(this.y*this.y));
        };
        this.toString = function () {
            return "("+this.x+", "+this.y+")";
        };
    }


function Point(x, y) {
        this.x = x;
        this.y = y;
    }
    Point.prototype = {
        dist: function () {
            return Math.sqrt((this.x*this.x)+(this.y*this.y));
        },
        toString: function () {
            return "("+this.x+", "+this.y+")";
        }
    }



function Point(x, y) {
        this.x = x;
        this.y = y;
    }
    Point.prototype.dist = function () {
        return Math.sqrt((this.x*this.x)+(this.y*this.y));
    };
    Point.prototype.toString = function () {
        return "("+this.x+", "+this.y+")";
    };


> var p = new Point(2, 2)
    > p.constructor
    [Function: Point]
    > p.constructor.name
    'Point'

JavaScript Prototype-Based Inheritance

function Shape(x, y) {
    this.x = x;
    this.y = y;
}

// 1. Explicitly call base (Shape) constructor from subclass (Circle) constructor passing this as the explicit receiver
function Circle(x, y, r) {
    Shape.call(this, x, y);
    this.r = r;
}

// 2. Use Object.create to construct the subclass prototype object to avoid calling the base constructor
Circle.prototype = Object.create(Shape.prototype);





// Declaring our Animal object
var Animal = function () {

    this.name = 'unknown';

    this.getName = function () {
        return this.name;
    }

    return this;
};

// Declaring our Dog object
var Dog = function () {

    // A private variable here      
    var private = 42;

    // overriding the name
    this.name = "Bello";

    // Implementing ".bark()"
    this.bark = function () {
        return 'MEOW';
    }

    return this;
};


// Dog extends animal
Dog.prototype = new Animal();

// -- Done declaring --

// Creating an instance of Dog.
var dog = new Dog();

// Proving our case
console.log(
    "Is dog an instance of Dog? ", dog instanceof Dog, "\n",
    "Is dog an instance of Animal? ", dog instanceof Animal, "\n",
    dog.bark() +"\n", // Should be: "MEOW"
    dog.getName() +"\n", // Should be: "Bello"
    dog.private +"\n" // Should be: 'undefined'
);





The problem with this approach however, is that it will re-create the object every time you create on. So this is not the best way to go about it. The best way is by declaring your objects on the prototype stack, like so:


// Defining test one, prototypal
var testOne = function () {};
testOne.prototype = (function () {
    var me = {}, privateVariable = 42;
    me.someMethod = function () {
        return privateVariable;
    };

    me.publicVariable = "foo bar";
    me.anotherMethod = function () {
        return this.publicVariable;
    };

    return me;

})();


// Defining test two, function
var testTwo = ​function() {
    var me = {}, privateVariable = 42;
    me.someMethod = function () {
        return privateVariable;
    };

    me.publicVariable = "foo bar";
    me.anotherMethod = function () {
        return this.publicVariable;
    };

    return me;
};


// Proving that both techniques are functionally identical
var resultTestOne = new testOne(),
    resultTestTwo = new testTwo();

console.log(
    resultTestOne.someMethod(), // Should print 42
    resultTestOne.publicVariable // Should print "foo bar"
);

console.log(
    resultTestTwo.someMethod(), // Should print 42
    resultTestTwo.publicVariable // Should print "foo bar"
);



// Performance benchmark start
var stop, start, loopCount = 1000000;

// Running testOne
start = (new Date()).getTime(); 
for (var i = loopCount; i>0; i--) {
    new testOne();
}
stop = (new Date()).getTime();

console.log('Test one took: '+ Math.round(((stop/1000) - (start/1000))*1000) +' milliseconds');



// Running testTwo
start = (new Date()).getTime(); 
for (var i = loopCount; i>0; i--) {
    new testTwo();
}
stop = (new Date()).getTime();


console.log('Test two took: '+ Math.round(((stop/1000) - (start/1000))*1000) +' milliseconds');





setTimeout and closure

Eg1

// ----- works in FF, not in IE  
var msg = "Hello World";
setTimeout(doAlert, 1, msg);
function doAlert(msg)
{
    alert(msg);
}
Eg2

// ------ works in both IE, FF
var msg = "Hello World";
setTimeout(function() {doAlert(msg);}, 1);
function doAlert(msg)
{
    alert(msg);
}

jquery: diffrent between stopPropagation and stopImmediatePropagation


                          stop   |    prevent     | prevent "same element"
                          bubbling | default action | event handlers

return false                 Yes           Yes             No
preventDefault               No            Yes             No
stopPropagation              Yes           No              No
stopImmediatePropagation     Yes           No              Yes


Example :

<span class="stop">Stop Test</span> | <span class="false">Return False</span> | <span class="none">Do None</span>| <span class="propagation">Stop propagation</span>
<div class="r"></div>

$("span.stop").click(function(e) {
    $(".r").empty().append("<h1>Stop 1</h1>");
    e.stopImmediatePropagation();
}).click(function() {
    $(".r").append("<h1>Stop 2</h1>");
    return false;
}).click(function() {
    $(".r").append("<h1>Stop 3</h1>");
});

$("span.propagation").click(function(e) {
    $(".r").empty().append("<h1>Stop propagation 1</h1>");
    e.stopPropagation();
}).click(function() {
    $(".r").append("<h1>Stop propagation 2</h1>");
    return false;
}).click(function() {
    $(".r").append("<h1>Stop propagation 3</h1>");
});
$("span.false").click(function(e) {
    $(".r").empty().append("<h1>Return 1</h1>");
    return false;
}).click(function() {
    $(".r").append("<h1>Return 2</h1>");
    return false;
}).click(function() {
    $(".r").append("<h1>Return 3</h1>");
});
$("span.none").click(function(e) {
    $(".r").empty().append("<h1>Return 1</h1>");
}).click(function() {
    $(".r").append("<h1>Return 2</h1>");
}).click(function() {
    $(".r").append("<h1>Return 3</h1>");
});

$(document.body).click(function() {
    $(".r").append("<h1>Body Click</h1>");
});


output:

Stop Test | Return False | Do NoneStop propagation

Stop 1




Stop Test | Return False | Do NoneStop propagation

Return 1

Return 2

Return 3


Stop Test | Return False | Do NoneStop propagation

Return 1

Return 2

Return 3

Body Click



Stop Test | Return False | Do NoneStop propagation

Stop propagation 1

Stop propagation 2

Stop propagation 3


Jsfiddle demo http://jsfiddle.net/markcoleman/PcUfP/

A simple Javascript program

function emp(name,age){
this.name=name;
this.age=age;
this.getEmpInfo=getEmpInfo;
}

function getEmpInfo() {
   return 'Emp name : '+this.name + '\n Emp age: '+this.age;
}

var Employee = new emp("muthunce",30);
console.log(Employee.getEmpInfo());


Output:
 Emp name : muthunce
 Emp age: 30


Using object literals

var emp = {
name : "muthunce",
age : 30,
getEmpInfo : function() {
return "Emp name : "+this.name+ " ; Emp age : "+this.age;
}
}

emp.name="muthu";
console.log(emp.getEmpInfo());

Output:

 Emp name : muthu ; Emp age : 30


Singleton using a function

var emp = new function() {
   this.name="muthunce";
   this.age = 30;
   this.getInfo= function() {
      return "Emp Name : "+this.name+" Emp age : "+this.age;
   }
}

emp.name="muthu";
emp.getInfo();

Output:
"Emp Name : muthu Emp age : 30"




Java remove empty elements from a list

List<String> list = new ArrayList<String>(Arrays.asList("", "Hi", null, "How"));
System.out.println(list);
list.removeAll(Arrays.asList("", null));
System.out.println(list);

Output:

[, Hi, null, How]
[Hi, How]

TCL string comparison with -nocase

set componentList [list Hello]
foreach component $componentList {
   if {[regexp -nocase -- $component HELLO]} {
    puts "$component == HELLO"
   } else {
     puts "$component != HELLO"
   }
 
}

Log all input received by Apache

Apache produces these log files: error log, access log. The default configuration puts the error log in "$APACHE_home\logs\error.log" and access log in "$APACHE_home\logs\access.log". Take a quick glance into these log files.
Error Log: The configuration directives related to error logging are ErrorLog and LogLevel:
  • ErrorLog directive specifies the location of the error log file. For example:
    # ErrorLog: The location of the error log file.
    # If you do not specify an ErrorLog directive within a <VirtualHost>
    # container, error messages relating to that virtual host will be
    # logged here.  If you *do* define an error logfile for a <VirtualHost>
    # container, that host's errors will be logged there and not here.
    ErrorLog logs/error.log
  • LogLevel directive controls the types of error messages written to the error log. For example:
    # LogLevel: Control the number of messages logged to the error_log.
    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn
Sample entries in the error log are as follows:
[Sun Oct 18 16:53:40 xxxx] [error] [client 127.0.0.1] Invalid method in request get /index.html HTTP/1.0
[Sun Oct 18 18:36:20 xxxx] [error] [client 127.0.0.1] File does not exist: d:/myPorject/apache2/htdocs/t.html
[Sun Oct 18 19:58:41 xxxx] [error] [client 127.0.0.1] client denied by server configuration: d:/myPorject/apache2/htdocs/forbidden/index.html
Access Log: The configuration directives related to access logging are CustomLog and LogFormat:
  • The CustomLog directive specifies the locations of the access log files. There are 3 types of access logs: common, referrer and agent. Common access log captures client access. Referrer access log captures the "referrer" (as in the Referer request header) of the request. (Referrer can be used for access control or accounting purpose such as e-advertising.) Agent access log captures the types of the browsers used in issuing the request (as in the User-Agent request header). Most installations do not need the referrer and agent access logs. For example:
    # The location and format of the access logfile (Common Logfile Format).
    # If you do not define any access logfiles within a <VirtualHost>
    # container, they will be logged here.  Contrariwise, if you *do*
    # define per-<VirtualHost> access logfiles, transactions will be
    # logged therein and *not* in this file.
    CustomLog "logs/access.log" common
    #CustomLog logs/referer.log referer
    #CustomLog logs/agent.log agent
    You can combine all the 3 access logs into a single log file, using keyword "combined".
    # If you prefer a logfile with access, agent, and referer information
    # (Combined Logfile Format) you can use the following directive.
    #CustomLog "logs/access.log" combined
  • LogFormat directive controls the format of the access logs. For example:
    # The following directives define some format nicknames for use with
    # a CustomLog directive.
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common
    LogFormat "%{Referer}i -> %U" referer
    LogFormat "%{User-agent}i" agent
Some sample entries in the "common" access log are as shown:
127.0.0.1 - - [18/Oct/2009:15:41:30 +0800] "GET / HTTP/1.1" 200 44
127.0.0.1 - - [18/Oct/2009:18:36:20 +0800] "GET /t.html HTTP/1.0" 404 204
127.0.0.1 - - [18/Oct/2009:18:32:05 +0800] "get /index.html HTTP/1.0" 501 215​
Apache mod_dumpio Module
This module allows for the logging of all input received by Apache and/or all output sent by Apache to be logged / dumped to the error.log file.
Reference Link 

Java Compares two Strings

import org.apache.commons.lang3.StringUtils; 


System.err.println("String diff is="+StringUtils.difference(string1, string2));





StringUtils.difference(null, null) = null
StringUtils.difference("", "") = ""
StringUtils.difference("abc", "") = ""
StringUtils.difference("", "abc") = "abc"
StringUtils.difference("ab", "abxyz") = "xyz"
StringUtils.difference("abc", "abc") = ""
StringUtils.difference("abcde", "xyz") = "xyz"
StringUtils.difference("abcde", "abxyz") = "xyz"

selenium xpath selector expamles

WebElement k1 = Login.driver.findElement(By.xpath("//table[@id='dijit_Menu_2']/tbody/tr[*]/td[contains(.,'name 2')]"));

//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]

iconHelp= "//*[contains(@class, 'globalToolbar')]//*[contains(@title, 'Help')]";

To find a following element 

//div[contains(@title, 'Enter your name:')]/following-sibling::div/div/input

To find a previous element
ComponentXpath=".//*[@id='tableCmpsId']//div[text()='ComponnetName']/preceding::td[1]/div//input";

Using xPath to reach parent of an element
//div[@id='Histable']//div[text()='weather']/parent::div

Selecting an element with xpath and Selenium
//td[contains(@class,'Label') and text()='Code']

The nearest <div> ancestor of the context node.
ancestor::div[1]


Not contains
$x("//div[not(contains(@style,'display:none')) and contains(string(), 'Note:'))]")

$x("//div[contains(@class,'dijitContentPane')]/div[contains(@class,'contentPane')]/div[not(contains(@style,'display:none')) and contains(string(), 'Note:')]")

normalize-space

$x("//div[normalize-space()='Note: Default values are shown in bold.']")

newest questions on wordpress