Wednesday, November 17, 2010
Ajax example
function getBoardsSold() {
createRequest();
var url = "getUpdatedBoardSales-ajax.php";
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}
function updatePage() {
if (request.readyState == 4) {
if(request.status ==200) {
var somevariable = request.responseText;
document.getElementById("Id").value = somevariable;
...
}
}
}
<--input --value="Show Me the Money" onclick="getBoardsSold();" type="button">
(more event handler)
<--input type="text" name="abc" onChange="getBoardsSold();" >
<--input type="text" name="abc" onFocus="foo();" >
<--input type="text" name="abc" onBlur="foo();" >
<--textarea name ="Id" id = "id" >
Any JavaScript in your web page that is not in a function gets run statically.
if (request == null) check out of function, will have the users know right away. (page 92)
Friday, November 5, 2010
Ajax
2. your request and response are handled by the web browser, not directly by your JavaScript code.
3. Once the web browser gets a response to your asynchronous request, it will 'call back' your JavaScript with the server's response.
Tuesday, September 14, 2010
python help pages
rollback deployment: http://benosullivan.co.uk/internet/google-app-engine/google-app-engine-fix-another-transaction-by-user-acct-is-already-in-progress/
sample rollback:
"C:\Python27\python" "C:\Program Files (x86)\Google\google_appengine\appcfg.py" -verbose --no_cookies -
-email=XXX@gmail.com --passin rollback "C:\\Documents and Settings\\kli\\My Documents\\Python\\helloworld"
Wednesday, September 1, 2010
some java interview questions(1)
http://www.interview-questions-java.com/java-questions/interview-questions-on-java
What if the main method is declared as private?
The program compiles properly but at runtime it will give “Main method not public.” message.
What are the differences between == and .equals() ?
The == operator compares two objects to determine if they are the same object in memory i.e. present in the same memory location. It is possible for two String objects to have the same value, but located in different areas of memory.
== compares references while .equals compares contents. The method public boolean equals(Object obj) is provided by the Object class and can be overridden. The default implementation returns true only if the object is compared with itself, which is equivalent to the equality operator == being used to compare aliases to the object. String, BitSet, Date, and File override the equals() method. For two String objects, value equality means that they contain the same character sequence. For the Wrapper classes, value equality means that the primitive values are equal.
What is the difference between final, finally and finalize? What do you understand by the java final keyword?
o final - declare constant
o finally - handles exception
o finalize - helps in garbage collection
Variables defined in an interface are implicitly final. A final class can’t be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can’t be overridden when its class is inherited. You can’t change value of a final variable (is a constant). finalize() method is used just before an object is destroyed and garbage collected. finally, a key word used in exception handling and will be executed whether or not an exception is thrown. For example, closing of open connections is done in the finally method.
What is the Java API?
The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.
What is the GregorianCalendar class?
The GregorianCalendar provides support for traditional Western calendars.
What is the ResourceBundle class?
The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program’s appearance to the particular locale in which it is being run.
When is static variable loaded? Is it at compile time or runtime? When exactly a static block is loaded in Java?
Static variable are loaded when classloader brings the class to the JVM. It is not necessary that an object has to be created. Static variables will be allocated memory space when they have been loaded. The code in a static block is loaded/executed only once i.e. when the class is first initialized. A class can have any number of static blocks. Static block is not member of a class, they do not have a return statement and they cannot be called directly. Cannot contain this or super. They are primarily used to initialize static fields.
What is reflection API? How are they implemented?
Reflection is the process of introspecting the features and state of a class at runtime and dynamically manipulate at run time. This is supported using Reflection API with built-in classes like Class, Method, Fields, Constructors etc. Example: Using Java Reflection API we can get the class name, by using the getName method.
Does JVM maintain a cache by itself? Does the JVM allocate objects in heap? Is this the OS heap or the heap maintained by the JVM? Why
Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP, but references to those objects are on the STACK.
What is phantom memory?
Phantom memory is false memory. Memory that does not exist in reality.
Can a method be static and synchronized?
A static method can be synchronized. If you do so, the JVM will obtain a lock on the java.lang.
Class instance associated with the object. It is similar to saying:
synchronized(XYZ.class) {
}
Garbage collection
A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists.
In Java, it is good idea to explicitly assign null into a variable when no more in use. In Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. Garbage collection is an automatic process and can’t be forced. There is no guarantee that Garbage collection will start immediately upon request of System.gc().
Garbage collector is a daemon thread
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup, before the object gets garbage collected. For example, closing an opened database Connection.
java options for Garbage collection
JDK 1.4.1 adds some new options to control garbage collection.
The options for server applications should be:
-server -Xms(size)where-Xmx(size) -XX:+UseParallelGC -XX:UseAdaptiveSizePolicy
The options for applications where pauses are undesirable should be:
-server -Xmswhere(size) -Xmx(size) -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:SurvivorRatio=2 -XX:NewRatio=8
Monday, August 30, 2010
Lazy initialization
Lazy initialization of a field may be useful when both of these conditions are true :
* the field is particularly expensive to create
* the field has an optional character, in the sense that it may or may not be of interest to the caller
In this case, the construction of such a field may be deferred till the moment it is actually required. This increases performance by avoiding unnecessary creation of expensive objects.
Immutable objects
Immutable objects are simply objects whose state (the object's data) cannot change after construction. Examples of immutable objects from the JDK include String and Integer.
Immutable objects greatly simplify your program, since they :
* are simple to construct, test, and use
* are automatically thread-safe and have no synchronization issues
* do not need a copy constructor
* do not need an implementation of clone
* allow hashCode to use lazy initialization, and to cache its return value
* do not need to be copied defensively when used as a field
* make good Map keys and Set elements (these objects must not change state while in the collection)
* have their class invariant established once upon construction, and it never needs to be checked again
* always have "failure atomicity" (a term used by Joshua Bloch) : if an immutable object throws an exception, it's never left in an undesirable or indeterminate state
Immutable objects have a very compelling list of positive qualities. Without question, they are among the simplest and most robust kinds of classes you can possibly build. When you create immutable classes, entire categories of problems simply disappear.
Make a class immutable by following these guidelines :
* ensure the class cannot be overridden - make the class final, or use static factories and keep constructors private
* make fields private and final
* force callers to construct an object completely in a single step, instead of using a no-argument constructor combined with subsequent calls to setXXX methods (that is, avoid the Java Beans convention)
* do not provide any methods which can change the state of the object in any way - not just setXXX methods, but any method which can change state
* if the class has any mutable object fields, then they must be defensively copied when passed between the class and its caller
Hash Code
What is an Object's Hash Code?
Objects in Java have hash codes associated with them. An object's hash code is a signed number that identifies the object (for example, an instance of the parent class). An object's hash code may be obtained by using the object's hashCode() method as follows:
int hashCode = SomeObject.hashCode();
The method hashCode() is defined in the Object class and is inherited by all Java objects. The following code snippet shows how the hash codes of two objects relate to the corresponding equals() method:
1. // Compare objects and then compare their hash codes
2. if (object1.equals(object2)
3. System.out.println("hash code 1 = " + object1.hashCode() +
4. ", hashcode 2 = " + object2.hashCode());
5.
6. // Compare hash codes and then compare objects
7. if (object1.hashCode() == object2.hashCode())
8. {
9. if (object1.equals(object2))
10. System.out.println"object1 equals object2");
11. else
12. System.out.println"object1 does not equal object2");
13. }
By definition if two objects equal (o1.equals(o2)) then calling their hashCode() method must produce the same integer value.
This is essencial to the correct working of a hash table. Don't forget if you override equals, always override hashCode() as well.
Thursday, August 26, 2010
Python
indention is very important

Friday, July 9, 2010
Singleton
Monday, June 7, 2010
Strategy Pattern
Class A{
SortInterface i;
}
Interface SortInterface{
sort();
}
Class ConcreteAlgorithm1 implements SortInterface{
sort(){
...
}
}
Class ConcreteAlgorithm2 implements SortInterface{
sort(){
...
}
}
a family of sort algorithms
Sunday, June 6, 2010
Design principles
take the parts that vary and encapsulate them, so that later you can alter or extend the parts that vary without affecting those that don't.
All patterns provide a way to let some part of a system vary independently of all other parts.
2. Program to an interface, not an implementation.
The point is to exploit polymorphism by programming to a supertype so that the actual runtime object isn't locked into the code.
The declared type of the variables should be a supetype, usually an abstract class or interface, so that the objects assigned to those variables can be of any concrete implementation of the supertype, which means the class declaring them doesn't have to know about the actual object type. (page 12)
3. Favor composition over inheritance.
class A{
BehaviorClass1 behavior1;
BehaviorClass1 behavior2;
}
When you put two classes together like this you're using composition. Instead of inheriting their behavior,the class A get their behavior by being composed with the right behavior object.
Not only does it let you encapsulate a family of algorithms into their own set of classes, but it also lets you change behavior at runtime as long as the object you'are composing with implements the correct behavior interface.
Wednesday, June 2, 2010
Floating point Types
double 8 bytes (15 significant decimal digits)
The name double refers to the fact that these numbers have twice the precision of the float type. (double-precision). Most applications choose double. the only reaons to use float are in the rare situation in which the slightly faster processing of single-precision numbers is important.
float have a suffix F 3.402F
floating point numbers without an F suffix are always considered to be of type double. you can optionally suppfly suffix D
SE5.0 0x1.0-3 = 0.125 (floating point in hexadecimal)
three special floating point values to denote overflows and errors
Double.POSITIVE_INFINITY
DOUBLE.NEGATIVE_INFINITY
DOUBLE.NaN( not a number)
ALL 'not a number' values are considered distinct.
Thursday, May 27, 2010
Charater set vs encoding
examples:
ASCII, ISO-8859-1 to ISO-8859-13 ISO-8859-15 (each set represent a different language set)
Unicode
An encoding maps a character set's code points to units of a specific width, and defines byte serialization and ordering rules.
example: UTF-8
UTF-8 unifies US-ASCII with Unicode.
http://java.sun.com/blueprints/guidelines/designing_enterprise_applications_2e/i18n/i18n2.html
Locale
Internationalization, also known as "I18n," is the process of separating locale dependencies from an application's source code.
Examples of locale dependencies include messages and user interface labels, character set, encoding, and currency and time formats.
Localization (also called "L10n") is the process of adapting an internationalized application to a specific locale. An application must first be internationalized before it can be localized.
Class java.util.Locale represents a locale in the Java 2 Platform, Standard Edition (J2SE). A Locale object is an identifier in a program that determines such factors as how numbers, currency, and time should be displayed, and the human language used to present data in a user interface.
Thursday, May 20, 2010
Localization vs. Internationalization
* Localization of internationalized software is done by simply adding locale-specific components, such as translated messages, data describing locale-specific behavior, fonts, and input methods, etc.
http://javaboutique.internet.com/tutorials/leskov/
More Reading
http://java.sun.com/blueprints/guidelines/designing_enterprise_applications_2e/i18n/i18n.html
Tuesday, May 18, 2010
Data Types
Java does not have any unsigned types
4 integer types
(int, long, short, byte)
4 bytes, 8 bytes, 2 bytes, 1 byte
long number: 400000000L
Hexadecimal: 0xCAFE
Octal: 0700
2 Floating point types
float (4), double (8)
exit code in Java
Thursday, May 13, 2010
Principles behind the Agile Software Development
http://agilemanifesto.org/principles.html
Our highest priority is to satisfy the customer through early and continuous delivery of valuable software.Welcome changing requirements, even late in development. Agile processes harness change for the customer's competitive advantage.
Deliver working software frequently, from a couple of weeks to a couple of months, with a
preference to the shorter timescale.
Business people and developers must work together daily throughout the project.
Build projects around motivated individuals. Give them the environment and support they need,and trust them to get the job done.
The most efficient and effective method of conveying information to and within a development team is face-to-face conversation.
Working software is the primary measure of progress.
Agile processes promote sustainable development.The sponsors, developers, and users should be able to maintain a constant pace indefinitely.
Continuous attention to technical excellence and good design enhances agility.
Simplicity--the art of maximizing the amount of work not done--is essential.
The best architectures, requirements, and designs emerge from self-organizing teams.
At regular intervals, the team reflects on how to become more effective, then tunes and adjusts its behavior accordingly.
linklist implementation in Java
private Object element ;
private Node next;
private Node prev;
// constructors
public Node(Object element){
this.element = element;
next = null;
prev = null;
}
}
public class LinkedList{
private Node tail;
private Node head;
//construct an empty list
public LinkedList(){
head= new Node(null);
tail = head;
}
public void addFirst(Node n){ // add to the beginning of the list
n.next = header.next ;
header.next = n;
}
public void addLast(Node n){ // add to the end of the list
n.prev = tail.prev ;
tail.prev = n;
}
remove();
find();
size();
}
the difference between a linked list and an array
downside: sequential access. Finding a node takes linear time. O(n)
Arrays are fixed in size, so resources must be anticipated and consumed in advance. Each element is the same size and must contain the same data type.Finding a node is fast, can be calculated mathmetically
Wednesday, May 12, 2010
Thread Safe Collections
A new Java JDK package was introduced at Java 1.5, that is java.util.concurrent
. This package supplies a few Collection implementations designed for use in multithreaded environments.
You can use the non-synchronized implementations in multiple thread environments, when you make sure that only one thread updating the collection at any given time.
The following table list all the syncronized collection classes:
syncronized | non-syncronized | |
---|---|---|
Vector | ArrayList | |
Stack | ||
LinkList | ||
CopyOnWriteArrayList | ||
jTreeSet | ||
HashSet | ||
LinkHashSet | ||
CopyOnWriteArraySet | ||
TreeMap | ||
Hashtable ConcurrentHashMap | jHashMap | |
LinkHashMap | ||
IdentityHashMap | ||
EnumMap |
Collection
the UML diagram are very clear on this page.
The Java JDK contains two high level Interfaces:
- java.util.Collection
- java.util.Map
java.util.Collection
interface. The Collection interface has three sub interfaces.- java.util.Set
(implementation are TreeSet,HashSet ...) Set
cannot have duplicates in it.- java.util.List
- ( implementation are Vector,Stack,ArrayList,LinkedList,AttributeList,RoleList...)
- interfaces SortedSet
- java.util.Queue
( implementation are: PriorityQueue, ArrayBlockingQueue ..) interface: BlockingQueque
java.util.Map implementations are:
TreeMap,HashMap, HashTable,LinkedHashMap,IdentityHashMap ..
Before selecting a particular collection implementation, ask the following question:
- Can my collection contain the same elements, i.e. are duplicates allowed?
- Can my collection contain the
null
element? - Should the collection maintain the order of the elements? Is the order important in any way?
- How do you want to access an element? By index, key or just with an iterator?
- Does the collection need to be synchronized?
- From a performance perspective, which one needs to be faster, updates or reads?
- From a usage perspective, which operation will be more frequent, updates or reads?
Tuesday, May 11, 2010
Java Annotations
Annotations do not directly affect program semantics, but they do affect the way programs are treated by tools and libraries, which can in turn affect the semantics of the running program. Annotations can be read from source files, class files, or reflectively at run time.
Annotations complement javadoc tags. In general, if the markup is intended to affect or produce documentation, it should probably be a javadoc tag; otherwise, it should be an annotation.
Define : An at-sign (@) precedes the interface keyword
/**
* Describes the Request-For-Enhancement(RFE) that led
* to the presence of the annotated API element.
*/
public @interface infoForMethod {
int id();
String s1();
String s2() default "[unassigned]";
String s3(); default "[unimplemented]";
}
Use Annotation:
An annotation is a special kind of modifier, and can be used anywhere that other modifiers (such as public, static, or final) can be used.
@infoForMethod (
id = 123456,
s1= "AAAAA",
s2= "BBBB",
s3= "4/1/2009"
)
public static void aMethod(Date destination) { ... }
---
An annotation type with no elements is termed a marker annotation type
define: public @interface example{ }
Use:
@example
public void aMethod()
--
In annotations with a single element, the element should be named value,
/**
* Associates a copyright notice with the annotated API element.
*/
public @interface Author{
String value();
}
use
m.isAnnotationPresent()
Sample Junit Test
import static org.junit.Assert.* ;
public class ATest {
@Test
public void test_method() {
A a = new A(200,2) ;
assertTrue(a.getM() == 1.0) ;
}
The marker @Test is called an
annotation in Java. When we later execute JUnit’s test runner it needs
to know which methods in your test class are test methods (e.g. you may
have several helper methods in your test class). The @Test is used to mark that a method is a test method.
Junit Version
currently I am using junit-3.8.2.jar which is installed eclipse plugin.
You can also find out Junit Version in Java by doing the following:
import junit.runner.Version;
System.out.println("JUnit version is: " + Version.id());