Friday, February 28, 2014

JavaScript Regular Expression Basics

Regular Expression is a pattern that matched a given input string. The pattern can be formed by using meta characters.

Meta characters

char meaning

^   => beginning of string
$   => end of string
.  => any character except newline
*  =>match 0 or more times
+ =>match 1 or more times
? =>match 0 or 1 times; or: shortest match
| =>alternative
( ) =>grouping; “storing”
[ ] =>set of characters
{ } =>repetition modifier

Repetition

a* =>zero or more a’s
a+ =>one or more a’s
a? =>zero or one a’s (i.e., optional a)
a{m} =>exactly m a’s
a{m,} =>at least m a’s
a{m,n} =>at least m but at most n a’s

Syntax in JavaScript
var patt=new RegExp(pattern,modifiers);
or

var patt=/pattern/modifiers;

Modifiers
1) The i modifier is used to perform case-insensitive matching.
2) The g modifier is used to perform a global match 

Pattern

  • Username [Min 8 Chars and alpha numeric characters)

    /^[a-z0-9]{8,}/i

  • Email ID

    /^[a-z0-9._-]+@[a-z]+.[a-z.]{2,5}$/i

  • Date of Birth

    /^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$/i
  • Mobile Number

    /^([+0-9]{1,3})?([0-9]{10,11})$/i

  • Web Site URL

    /^[http://]+[www]?.[0-9a-z_.]+.[a-z.]{2,5}$/i

  • Pincode

    /^[0-9]{6}$/i 

SAMPLE CODE

<!DOCTYPE html>
<html>
    <head>
        <title>Test Script</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <div>
            <form id="myform" method="post">
                Enter the Username
                <input type="text" id="uname" /> <br />
                <input type="submit" value="Validate"/>
            </form>
            <script>
 
                document.getElementById("myform").onsubmit =function()
                {
                 var pattern = /^[a-z0-9_]{8,25}$/i;
                 var text = document.getElementById("uname");
                 if(!pattern.test(text.value))
                   {
                     alert("Enter a valid Username");
                     text.focus();
                    }
                  else
                   {
                     alert("Thank You");
                   }
                };  
            </script>
        </div>
    </body>
</html>



With Regards,
Animesh Nanda
Sr.Software Engineer | Photon Infotech
Bengaluru | Karnataka | INDIA.

Sunday, February 23, 2014

HTML 5 Geo-location API

The Geo-location API lets you share your location with trusted web sites. The latitude and longitude are available to JavaScript on the page, which in turn can send it back to the remote web server and do fancy location-aware things like finding local businesses or showing your location on a map.
As you can see from the following table, the geolocation API is supported by most browsers on the desktop and mobile devices. 

GEO-LOCATION API SUPPORT

  • IE 9.0+
  • Firefox 3.5+
  • Safari 5.0+
  • CHROME 5.0+
  • OPERA 10.6+
  • IPHONE 3.0+
  • ANDROID 2.0+
CODE

<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to get your position:</p>
<button onclick="getLocation()">Show in MAP</button>
<div id="mapholder"></div>
<script>
var x=document.getElementById("demo");
function getLocation()
  {
  if (navigator.geolocation)
    {
    navigator.geolocation.getCurrentPosition(showPosition,showError);
    }
  else{x.innerHTML="Geolocation is not supported by this browser.";}
  }

function showPosition(position)
  {
  var latlon=position.coords.latitude+","+position.coords.longitude;

  var img_url="http://maps.googleapis.com/maps/api/staticmap?center="
  +latlon+"&zoom=14&size=400x300&sensor=false";
  document.getElementById("mapholder").innerHTML="<img src='"+img_url+"'>";
  }

function showError(error)
  {
  switch(error.code) 
    {
    case error.PERMISSION_DENIED:
      x.innerHTML="User denied the request for Geolocation."
      break;
    case error.POSITION_UNAVAILABLE:
      x.innerHTML="Location information is unavailable."
      break;
    case error.TIMEOUT:
      x.innerHTML="The request to get user location timed out."
      break;
    case error.UNKNOWN_ERROR:
      x.innerHTML="An unknown error occurred."
      break;
    }
  }
</script>
</body>

</html>

Regards,

Animesh Nanda

Sr. Software Engineer,
Photon Infotech Pvt. Ltd.

Sunday, February 16, 2014

A fix for window.location.origin in Internet Explorer

Internet Explorer does not have access to window.location.origin, which is a bummer because it is a pretty handy variable to have, but we can make it work with a fairly straight forward check because we access .origin;

if (!window.location.origin) {
 window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}

This should now have .origin set to what you would expect.


Regards,

Animesh Nanda

Sr. Software Engineer,
Photon Infotech Pvt. Ltd.

Monday, April 22, 2013

Object-Oriented Inheritance with JavaScript

JavaScript does not support an explicit inheritance operator the way Java or C++ do.
However, there are two ways to implement inheritance in JavaScript:

1. Using functions . This is the classical way.
2. Using Prototype. This is recommended and more powerful way of doing.  

Inheritance through Functions


1. Define super class.
2. Define sub class.
3. Assign the superclass object to one of the member method of the sub class.
4. Call the superclass constructor function inside the subclass.
/* Step 1 : define super class
*/
function superClass() {
this.sayHello = function(){alert('Hello SuperClass');}
this.sayMessage = function(){alert('Say Message SuperClass');}
this.name = 'superClass';
}

/*
Step 2: define sub class
a) assign the superclass object to one of the function object
b) call the superclass constructor inside the subclass
*/
function subClass()
{
//you can use any propertyname instead of parentClass eg superclass
this.parentClass = superClass;
this.parentClass(); // assigns the super class methods to subclass
this.sayHello = function(){alert('Hello SubClass');}
}

/* test */
function testSub() {
var sc = new subClass();
sc.sayHello();
sc.sayMessage();
}

Explanation


The explanation is pretty simple if you know the concept of “this” keyword in JS.
Remember that the ‘this’ keyword refers to the containing object.
So, when you call the following line, you have copied the entire superClass object to the subClass property
parentClass.
this.parentClass = superClass;
Then when you call the following line the constructor of the ‘superClass’ is fired.
this.parentClass();
Now, inside the superClass function you have the following line:
this.sayHello = function(){alert('Hello SuperClass');}
What does ‘this’ refer to?
Since the enclosing object of ‘superClass’ is ‘subClass’, the ‘this’ keyword refers to it’s enclosing object i.e.
“subClass” and not the ‘window’ object. Therefore all the properties of ‘superClass’ get copied to the ‘subClass’.

Inheritance through Prototype


This is the most suitable method of implementing inheritance in JavaScript.
1. The main advantage of this method is that the inheritance chain is dynamic i.e you can assign or remove   new methods and properties to the super class that becomes available to the child class automatically.
2. Also, JS natively supports prototypal inheritance and not class based inheritance.
3. We can only do method overriding and not method overloading.

Steps:

1. Create a super class.
2. Attach all the callable methods of super class to it’s prototype. Important step!
3. Create a sub class.
4. Assign the subclass prototype object to the super class instance. This creates inheritance.
5. Reset the constructor property for the sub class usingChildClassName.prototype.constructor=ChildClassName. This ensures that the objects created are
of the sub class and not the super class.
6. Call the super class methods using ClassName.prototype.methodName.call(this,parameters…). This will
work only for methods added via the prototype.

/* create a super class */
function Person()
{
this.sayName = function(){alert("Person::sayName()");}
this.name = "Person";
}
//create the callable methods in super using it's prototype
Person.prototype.sayHello = function(name){alert("Person::sayHello()");}

/* create sub class */
function Student()
{
this.name = "Student";
this.sayName = function(){alert("Student::sayName()");}
}

/* derive the sub class from super class by using it's prototype */
Student.prototype = new Person;

/*Reset the constructor property for the subclass using it's prototype.constructor property*/
Student.prototype.constructor = Student;
//add new methods to the super class which become available to all the sub classes automatically
Person.prototype.sayNew = function(){alert("Person::sayNew()");}
//call super class method
Student.prototype.callParentMethod = function()
{
//call parent methods this will work because sayHello is part of the object prototype
hierarchy
Person.prototype.sayHello.call(this);
//this NOT will work because sayName is NOT declared using the superclass prototype
Person.prototype.sayName.call(this); //error
}
function testProtoInherit()
{
var sc = new Student;
sc.sayHello();
sc.sayName();
sc.sayName('amit');
alert(sc.name);
sc.sayNew();
sc.callParentMethod();
}
testProtoInherit();
With Regards,
Animesh Nanda
Sr.Software Engineer | Photon Infotech
Bengaluru | Karnataka | INDIA.

Sunday, April 21, 2013

Javascript Prototype Object



Prototype is a builtin js property that is part of JS objects. It was introduced in JS version 1.1.
Prototype object can be added only to Function,String, Image, Number, Date and Array.
We can use prototype on the base class not on the objects derived from it.
The prototype object help you quickly add a custom method or member to an object that is
reflected on ALL instances of it.
Prototype object can only be used to add PUBLIC member and methods. It cannot add private
members or methods.
If the prototype object is used to override the the previously set property it will not override the
properties of already created objects. It will only affect the objects that have been created after
the prototype change.

Using prototype on custom objects:


var func = function(){};
func.prototype.foo = "bar"; //adds the property foo
alert(func.foo); //alerts undefined
func2 = new func();
alert(func2.foo); //alerts bar
func2.prototype.foo2 = 'ddd'; //Error : func2.prototype is undefined
Using prototype on builtin JS objects:

String.prototype.foo = "bar";
Image.prototype.foo = "bar";
Number.prototype.foo = "bar";
Array.prototype.foo = "bar";
You cannot use prototype on derived objects:
var str = new String();
str.prototype.foo = 'bar'; //Error : str.prototype is undefined




With Regards,
Animesh Nanda,
Sr. Software Engineer | Photon Infotech
Bengaluru | Karnataka | INDIA.

Wednesday, October 17, 2012

How to read directory or folder contents in PHP

TO GET ALL FILES ON RECURSIVE DIRECTORIES IN SINGLE ARRAY USE THE CODE GIVEN BELOW.




function getFilesFromDir($dir) { 

  
$files = array(); 
  if (
$handle = opendir($dir)) { 
    while (
false !== ($file = readdir($handle))) { 
        if (
$file != "." && $file != "..") { 
            if(
is_dir($dir.'/'.$file)) { 
                
$dir2 = $dir.'/'.$file; 
                
$files[] = getFilesFromDir($dir2); 
            } 
            else { 
              
$files[] = $dir.'/'.$file; 
            } 
        } 
    } 
    
closedir($handle); 
  } 

  return
$this->array_flat($files); 
} 

function 
array_flat($array) { 

  foreach(
$array as $a) { 
    if(
is_array($a)) { 
      
$tmp = array_merge($tmp, array_flat($a)); 
    } 
    else { 
      
$tmp[] = $a; 
    } 
  } 

  return 
$tmp; 
} 
// Code to get folder contents (Usage) $dir = '/data'; $foo = $this->getFilesFromDir($dir); print_r($foo); ?>  




With Regards,
Er.Animesh Nanda
Sr. Programmer Analyst,
Innovate Search Pvt. Ltd..
Bengaluru,Karnataka,INDIA.

Wednesday, July 13, 2011

Showing and Hiding Windows Form in System Tray in VB .net

Show and Hide Windows Form in System Tray

How to show and hide your form in windows system tray.

1. Add NotifyIcon class in your project (System.Windows.Forms.NotifyIcon) and drag it into form.




2. Change NotifyIcon properties.

BalloonTipIcon = Info
BalloonTipText = Running
Change Icon
Text = Running Your Program
Visible = True






3. Add code in Event Form1_Resize.

Private Sub Form1_Resize(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles MyBase.Resize
' If minimize form that will show in system tray.
If System.Windows.Forms.FormWindowState.Minimized = WindowState Then
sysMonTray.ShowBalloonTip(5, "Running", "Running Your Program", ToolTipIcon.Info)
Me.Hide()
End If
End Sub


4. Add code in Event NotifyIcon_Click to hide and show form.

Private Sub sysMonTray_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles sysMonTray.Click

If Me.Visible Then
Me.Hide()
Else
Me.Show()
Me.ShowInTaskbar = True
Me.WindowState = FormWindowState.Normal
Me.StartPosition = FormStartPosition.CenterScreen
End If

End Sub



With Regards,
Er.Animesh Nanda
Manusis Technologies Pvt.Ltd.
Bengaluru,
Karnataka,INDIA.