Pages

Thursday, August 18, 2011

Lagrange's four-square theorem implementation code in JAVA

Lagrange's four-square theorem : any natural number can be represented as the sum of four integer squares

p = a02 + a12 + a22 + a32

where the four numbers a0, a1, a2, a3 are integers. For illustration, 3, 31 and 310 can be represented as the sum of four squares as follows:

3 = 12 + 12 + 12 + 02
31 = 52 + 22 + 12 + 12
310 = 172 + 42 + 22 + 12.

 int n, t1, t2, t;  
           n = 23;//Your number  
           for (int i = (int) Math.sqrt(n / 4); i * i <= n; i++) {  
                t1 = n - i * i;  
                for (int j = (int) Math.sqrt(t1 / 3); j <= i && j * j <= t1; j++) {  
                     t2 = t1 - j * j;  
                     for (int k = (int) Math.sqrt(t2 / 2); k <= j && k * k <= t2; k++) {  
                          t = (int) Math.sqrt(t2 - k * k);  
                          if (t <= k && t * t == t2 - k * k) {                                
                               System.out.println("(" + i + "^2) + (" + j + "^2) + ("+ k + "^2) + ("+ t +"^2)");  
                          }  
                     }  
                }  
           }  


Thursday, August 4, 2011

Prevent copy paste on input : allow only numeric values jQuery


The following example won't allow values other than numeric.
  1. From keyboard (even copy paste)
  2. From drag drop
  3. From mouse (copy paste)
Demo : Try demo here
 <!DOCTYPE html>  
 <html>  
      <head>  
           <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />  
           <title>jQuery UI Example Page</title>  
           <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script>  
           <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.js"></script>  
      </head>  
      <body>  
           <input type="text" id="textBox" class="numericOnly" />  
      </body>  
      <script type="text/javascript">  
           $(function(){  
                $(".numericOnly").bind('keypress',function(e){  
                          if(e.keyCode == '9' || e.keyCode == '16'){  
                                return;  
                           }  
                           var code;  
                           if (e.keyCode) code = e.keyCode;  
                           else if (e.which) code = e.which;   
                           if(e.which == 46)  
                                return false;  
                           if (code == 8 || code == 46)  
                                return true;  
                           if (code < 48 || code > 57)  
                                return false;  
                     }  
                );  
                $(".numericOnly").bind("paste",function(e) {  
                     e.preventDefault();  
                });  
                $(".numericOnly").bind('mouseenter',function(e){  
                      var val = $(this).val();  
                      if (val!='0'){  
                           val=val.replace(/[^0-9]+/g, "")  
                           $(this).val(val);  
                      }  
                });  
           });  
      </script>  
 </html>  

Tuesday, August 2, 2011

Override Invalid value for field [fieldName] message in Struts2

The default field error message in struts 2 is Invalid field value for field "[fieldName]".

To override this message you need to create a property file with a file name pattern [ClassName].properties under the package of the Action class.



If you are getting error message like : Invalid field value for field "birthDate". You can override this by adding a line in properties file like,

             invalid.fieldvalue.birthDate = Birthdate is invalid

So now your message is : "Birthdate is invalid"

Wednesday, June 15, 2011

Preserve TimeStamp value in Struts2

Problem Definition : After page is submitted the value of TimeStamp is not preserve in page. As an additional requirement is that I want TimeStamp value in "MM/dd/yyyy hh:mm:ss a" format on my jsp pages..

File :  xwork-conversion.properties
  
 java.sql.Timestamp = com.myApp.util.MyTimeStampConverter  

Create java file i.e. Class MyTimeStampConverter

Code:

 public class MyTimeStampConverter extends  
     StrutsTypeConverter {  
   private static final SimpleDateFormat sdf =  
     new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");  
   @Override  
   public Object convertFromString(Map context,  
       String[] values, Class toClass)  
       throws TypeConversionException {  
     try {  
       if (values == null || values.length == 0) {  
         return null;  
       }  
       return new java.sql.Timestamp(sdf  
           .parse(values[0]).getTime());  
     } catch (Exception e) {  
       throw new TypeConversionException(e);  
     }  
   }  
   @Override  
   public String convertToString(Map context,  
       Object object)  
       throws TypeConversionException {  
     try {  
       if (object instanceof Timestamp) {  
         return sdf.format(  
             new Date((Timestamp) object).getTime()));  
       }  
       return "";  
     } catch (Exception e) {  
       throw new TypeConversionException(e);  
     }  
   }  
 }  

Thursday, April 7, 2011

How to know which application is using desired port in windows

Just go to command prompt and type

netstat -o -n -a | findstr 0.0:80

output is like

TCP    0.0.0.0:80    0.0.0.0:0    LISTENING     1656

The number at the end (1656, in this case) is a process ID.

Open Task Manager and click View -> Select Columns. Check the box next to PID (Process Identifier). You can then find the process ID returned by netstat and determine which process is using the port.

Thursday, March 24, 2011

Style Preecedencr in CSS : Specificity, Inheritance and Cascade

CSS rule applies to a given html element is controled by

Specificity Calculations

Specificity is calculated by counting various components of your css and expressing them in a form (a,b,c,d). This will be clearer with an example, but first the components.
  • Element, Pseudo Element: d = 1 – (0,0,0,1)
  • Class, Pseudo class, Attribute: c = 1 – (0,0,1,0)
  • Id: b = 1 – (0,1,0,0)
  • Inline Style: a = 1 – (1,0,0,0)
An id is more specific than a class is more specific than an element.
It’s also important to note that 0,0,1,0 is more specific than 0,0,0,15.

Let’s look at the example
div p.bio {font-size: 14px} - (0,0,1,2)
#sidebar p {font-size: 12px} - (0,1,0,1)
The second has the higher specificity and thus takes precedence.
Importance trumps specificity, When you mark a css property with !important you’re overriding specificity rules and so
div p.bio {font-size: 14px !important}
#sidebar p {font-size: 12px}
means the first line of css above takes precedence instead of the second. !important is still mostly a hack around the basic rules and is something you should never need if you understand how the rules work.

Inheritance

Elements inherit styles from their parent container. If you set the body tag to use color: red then the text for all elements inside the body will also be red unless otherwise specified.

Not all css properties are inherited, though. For example margins and paddings are non-inherited properties. If you set a margin or padding on a div, the paragraphs inside that div do not inherit the margin and padding you set on the div. The paragraph will use the default browser margin and padding until you declare otherwise.

You can explicitly set a property to inherit styles from it’s parent container, though. For example you could declare
p {margin: inherit; padding: inherit}
and your paragraph would then inherit both from it’s containing element.

The Cascade

At the highest level the cascade is what controls all css precedence and works as follows.
  1. Find all css declarations that apply to the element and property in question.
  2. Sort by origin and weight. Origin refers to the source of the declaration (author styles, user styles, browser defaults) and weight refers to the importance of the declaration. (author has more weight than user which has more weight than default. !importance has more weight than normal declarations)
  3. Calculate specificity
  4. If two rules are equal in all of the above, the one declared last wins. CSS embedded in the html always come after external stylesheets regardless of the order in the html
#3 above is likely the one you’ll need to pay attention to most.
#2 just understand that your styles will override how a user sets their browser unless they set their rules to be important.

Friday, March 4, 2011

JSP Implicit Objects



Implicit objects in jsp are the objects that are created by the container automatically.Since these objects are created automatically by the container and are accessed using standard variables; hence, they are called implicit objects. The implicit objects are parsed by the container and inserted into the generated servlet code. They are available only within the jspService method and not in any declaration. Implicit objects are used for different purposes. Our own methods (user defined methods) can't access them as they are local to the service method and are created at the conversion time of a jsp into a servlet. But we can pass them to our own method if we wish to use them locally in those functions.


Objebt Class
application javax.servlet.ServletContext
config javax.servlet.ServletConfig
exception java.lang.Throwable
out javax.servlet.jsp.JspWriter
page java.lang.Object
PageContext javax.servlet.jsp.PageContext
request javax.servlet.ServletRequest
response javax.servlet.ServletResponse
session javax.servlet.http.HttpSession

  • Application: These objects has an application scope. These objects are available at the widest context level, that allows to share the same information between the JSP page's servlet and any Web components with in the same application.
  • Config: These object has a page scope and is an instance of javax.servlet.ServletConfig class. Config object allows to pass the initialization data to a JSP page's servlet. Parameters of this objects can be set in the deployment descriptor (web.xml) inside the element . The method getInitParameter() is used to access the initialization parameters.
  • Exception: This object has a page scope and is an instance of java.lang.Throwable class. This object allows the exception data to be accessed only by designated JSP "error pages."
  • Out: This object allows us to access the servlet's output stream and has a page scope. Out object is an instance of javax.servlet.jsp.JspWriter class. It provides the output stream that enable access to the servlet's output stream.
  • Page: This object has a page scope and is an instance of the JSP page's servlet class that processes the current request. Page object represents the current page that is used to call the methods defined by the translated servlet class. First type cast the servlet before accessing any method of the servlet through the page.
  • Pagecontext: PageContext has a page scope. Pagecontext is the context for the JSP page itself that provides a single API to manage the various scoped attributes. This API is extensively used if we are implementing JSP custom tag handlers. PageContext also provides access to several page attributes like including some static or dynamic resource.
  • Request: Request object has a request scope that is used to access the HTTP request data, and also provides a context to associate the request-specific data. Request object implements javax.servlet.ServletRequest interface. It uses the getParameter() method to access the request parameter. The container passes this object to the _jspService() method.
  • Response: This object has a page scope that allows direct access to the HTTPServletResponse class object. Response object is an instance of the classes that implements the javax.servlet.ServletResponse class. Container generates to this object and passes to the _jspService() method as a parameter.
  • Session: Session object has a session scope that is an instance of javax.servlet.http.HttpSession class. Perhaps it is the most commonly used object to manage the state contexts. This object persist information across multiple user connection.

Thursday, March 3, 2011

Database : May I help u????

Select Top N records..........

Microsoft SQL Server
SELECT TOP 10 column FROM table

MySQL
SELECT column FROM table LIMIT 10

Oracle
SELECT column FROM table WHERE ROWNUM <= 10

DB2
SELECT column FROM table
FETCH FIRST 10 ROWS ONLY


Wednesday, February 16, 2011

IE Rendering Modes

  • IE=5
    • <meta http-equiv="X-UA-Compatible" content="IE=5" />
    • This forces IE 8 to render the page in “Quirks” mode.
  • IE=7
    • <meta http-equiv="X-UA-Compatible" content="IE=7" />
    • This forces IE 8 to render the page using IE 7 Strict mode.
  • IE=EmulateIE7
    • <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
    • This forces IE 8 to use the !DOCTYPE declaration in the page to determine the rendering mode.
  • IE=8
    • <meta http-equiv="X-UA-Compatible" content="IE=8" />
    • This forces IE 8 to display the page in Internet Explorer Standards mode.
  • IE=EmulateIE8
    • <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />
    • This forces IE 8 to use the !DOCTYPE declaration in the page to determine the rendering mode.
  • IE=edge
    • <meta http-equiv="X-UA-Compatible" content="edge" />
    • This forces Internet Explorer 8 to render in the most recent mode. For instance; currently this would behave like using a value of IE=8, but when IE 9 is available that will be the mode that IE=edge will render in.