Reduce the startup time of an application server
Application server settings
Servers > Application servers > {server1}
select the Run in development mode .. restart server...
-------------------------------
Enabling this option may reduce the startup time of an application server. This may include JVM settings such as disabling bytecode verification and reducing JIT compilation costs. Do not enable this setting on production servers.
Specifies that you want to use the JVM properties -Xverify and -Xquickstart on startup. Before selecting this option, add the -Xverify and -Xquickstart properties as generic arguments to the JVM configuration.
If you select this option, you must save the configuration and restart the server before this configuration change takes effect.
The default setting for this option is false, which indicates that the server will not be started in development mode. Setting this option to true specifies that the server will be started in development mode (with settings that will speed server startup time).
Data type Boolean
Default false
Click here to View more...
How to Create Black & White Images from a Single RGB Channel
Even with the incredible ranges of colors available to digital photographers and illustrators, there is still something magical and sophisticated about the stark simplicity of a black and white image. The lack of color allows the viewer to focus on elements like shadows and highlights without the distraction of color interactions. Black and white photos can express a mood that color often cannot. 1. A color image with the RGB channels palette open Like most processes in Photoshop, there are about ten different ways to convert a color image to black and white. They all yield different black and whites and offer vastly different ranges of control over the final result. You can simply go to the “Image” menu and choose “Grayscale.” Or you can create a “Black and White” adjustment layer in CS3 that will allow you much control over your conversion. I could go on, but there are a lot of other tutorials on the web on the subject. Instead, I want to share a very simple, yet really dramatic, method for taking the color out of your images. Digital cameras produce images in the RGB color space. Very basically, each channel (red, blue, and green) contains information pertaining to the image’s hue (color), saturation (strength of the color), and luminance (or brightness) levels. You can exploit this last property to create desaturated images. With an image open in Photoshop, open the Channels Palette, which is usually tabbed along with the Layers Palette. If not, go to the Windows pull-down menu and pick “Channels.” The color channels allow you a huge amount of control over your image. For now, click on the first channel, Red. (Note: By default, the thumbnails of the channels in the Channels Palette will show in black and white. If they are displaying in color, you’ll want to type “ctrl” or “cmnd” plus the “k” key. This will open the Photoshop Preferences dialog box, where you can select “Interface” to change the channel thumbnails to display in black and white). When you select the red channel, you’ll see your original image displayed with only the information contained in the red channel. It’s completely without color. Now try it with the green channel, and then the blue channel. Your image will be in black and white, with a different look each time. 2. Channels palette open, red channel selected 3. This image was photographed in color. This is the version with only the red channel selected. 4. The same image, with only the green channel selected in the RGB channel palette 5. The same image again, only with the blue channel selected this time If one of the three desaturated images you create appeals to you, and you want to save it as an independent image,: 6. Converting to grayscale Photoshop will ask you if you want to discard the color information. Click yes. You will then be asked if you want to discard the other layers. Click discard. You will then be left with your black and white image based on whatever color channel you picked. The image has no color now, so only luminance levels need to be displayed, therefore, in the layers palette, there will be only a single layer, grayscale. Different processing techniques of the original color image can yield dramatically different results when you desaturate: 7. Color image desaturated based on the green channel 8. The same image, desaturated with the help of the blue channel 9. Desaturated image, also based on the blue channel 10. And the original RGB image from which the blue channel was extractedConverting to black and white

The RGB color space









Click here to View more...
Labels: Photoshop
JPQL Overview- Getting Started
Query Basics
SELECT x FROM Magazine x
The preceding is a simple JPQL query for all Magazine entities.
public Query createQuery (String jpql);
The EntityManager.createQuery method creates a Query instance from a given JPQL string.
public List getResultList ();
Invoking Query.getResultList executes the query and returns a List containing the matching objects. The following example executes our Magazine query above:
EntityManager em = ...
Query q = em.createQuery ("SELECT x FROM Magazine x");
List<Magazine> results = q.getResultList ();
A JPQL query has an internal namespace declared in the from clause of the query. Arbitrary identifiers are assigned to entities so that they can be referenced elsewhere in the query. In the query example above, the identifier x is assigned to the entity Magazine.
[Note] Note
The as keyword can optionally be used when declaring identifiers in the from clause. SELECT x FROM Magazine x and SELECT x FROM Magazine AS x are synonymous.
Following the select clause of the query is the object or objects that the query returns. In the case of the query above, the query's result list will contain instances of the Magazine class.
[Note] Note
When selecting entities, you can optionally use the keyword object. The clauses select x and SELECT OBJECT(x) are synonymous.
The optional where clause places criteria on matching results. For example:
SELECT x FROM Magazine x WHERE x.title = 'JDJ'
Keywords in JPQL expressions are case-insensitive, but entity, identifier, and member names are not. For example, the expression above could also be expressed as:
SELECT x FROM Magazine x WHERE x.title = 'JDJ'
But it could not be expressed as:
SELECT x FROM Magazine x WHERE x.TITLE = 'JDJ'
As with the select clause, alias names in the where clause are resolved to the entity declared in the from clause. The query above could be described in English as "for all Magazine instances x, return a list of every x such that x's title field is equal to 'JDJ'".
JPQL uses SQL-like syntax for query criteria. The and and or logical operators chain multiple criteria together:
SELECT x FROM Magazine x WHERE x.title = 'JDJ' OR x.title = 'JavaPro'
The = operator tests for equality. <> tests for inequality. JPQL also supports the following arithmetic operators for numeric comparisons: >, >=, <, <=. For example:
SELECT x FROM Magazine x WHERE x.price > 3.00 AND x.price <= 5.00
This query returns all magazines whose price is greater than 3.00 and less than or equal to 5.00.
SELECT x FROM Magazine x WHERE x.price <> 3.00
This query returns all Magazines whose price is not equals to 3.00.
You can group expressions together using parentheses in order to specify how they are evaluated. This is similar to how parentheses are used in Java. For example:
SELECT x FROM Magazine x WHERE (x.price > 3.00 AND x.price <= 5.00) OR x.price = 7.00
This expression would match magazines whose price is 4.00, 5.00, or 7.00, but not 6.00. Alternately:
SELECT x FROM Magazine x WHERE x.price > 3.00 AND (x.price <= 5.00 OR x.price = 7.00)
This expression will magazines whose price is 5.00 or 7.00, but not 4.00 or 6.00.
JPQL also includes the following conditionals:
*
[NOT] BETWEEN: Shorthand for expressing that a value falls between two other values. The following two statements are synonymous:
SELECT x FROM Magazine x WHERE x.price >= 3.00 AND x.price <= 5.00
SELECT x FROM Magazine x WHERE x.price BETWEEN 3.00 AND 5.00
*
[NOT] LIKE: Performs a string comparison with wildcard support. The special character '_' in the parameter means to match any single character, and the special character '%' means to match any sequence of characters. The following statement matches title fields "JDJ" and "JavaPro", but not "IT Insider":
SELECT x FROM Magazine x WHERE x.title LIKE 'J%'
The following statement matches the title field "JDJ" but not "JavaPro":
SELECT x FROM Magazine x WHERE x.title LIKE 'J__'
*
[NOT] IN: Specifies that the member must be equal to one element of the provided list. The following two statements are synonymous:
SELECT x FROM Magazine x WHERE x.title IN ('JDJ', 'JavaPro', 'IT Insider')
SELECT x FROM Magazine x WHERE x.title = 'JDJ' OR x.title = 'JavaPro' OR x.title = 'IT Insider'
*
IS [NOT] EMPTY: Specifies that the collection field holds no elements. For example:
SELECT x FROM Magazine x WHERE x.articles is empty
This statement will return all magazines whose articles member contains no elements.
*
IS [NOT] NULL: Specifies that the field is equal to null. For example:
SELECT x FROM Magazine x WHERE x.publisher is null
This statement will return all Magazine instances whose "publisher" field is set to null.
*
NOT: Negates the contained expression. For example, the following two statements are synonymous:
SELECT x FROM Magazine x WHERE NOT(x.price = 10.0)
SELECT x FROM Magazine x WHERE x.price <> 10.0
10.1.2. Relation Traversal
Relations between objects can be traversed using Java-like syntax. For example, if the Magazine class has a field named "publisher" or type Company, that relation can be queried as follows:
SELECT x FROM Magazine x WHERE x.publisher.name = 'Random House'
This query returns all Magazine instances whose publisher field is set to a Company instance whose name is "Random House".
Single-valued relation traversal implies that the relation is not null. In SQL terms, this is known as an inner join. If you want to also include relations that are null, you can specify:
SELECT x FROM Magazine x WHERE x.publisher.name = 'Random House' or x.publisher is null
You can also traverse collection fields in queries, but you must declare each traversal in the from clause. Consider:
SELECT x FROM Magazine x, IN(x.articles) y WHERE y.authorName = 'John Doe'
This query says that for each Magazine x, traverse the articles relation and check each Article y, and pass the filter if y's authorName field is equal to "John Doe". In short, this query will return all magazines that have any articles written by John Doe.
[Note] Note
The IN() syntax can also be expressed with the keywords inner join. The statements SELECT x FROM Magazine x, IN(x.articles) y WHERE y.authorName = 'John Doe' and SELECT x FROM Magazine x inner join x.articles y WHERE y.authorName = 'John Doe' are synonymous.
10.1.3. Fetch Joins
JPQL queries may specify one or more join fetch declarations, which allow the query to specify which fields in the returned instances will be pre-fetched.
SELECT x FROM Magazine x join fetch x.articles WHERE x.title = 'JDJ'
The query above returns Magazine instances and guarantees that the articles field will already be fetched in the returned instances.
Multiple fields may be specified in separate join fetch declarations:
SELECT x FROM Magazine x join fetch x.articles join fetch x.authors WHERE x.title = 'JDJ'
[Note] Note
Specifying the join fetch declaration is functionally equivalent to adding the fields to the Query's FetchConfiguration. See Section 5.6, “Fetch Groups”.
10.1.4. JPQL Functions
As well as supporting direct field and relation comparisons, JPQL supports a pre-defined set of functions that you can apply.
*
CONCAT(string1, string2): Concatenates two string fields or literals. For example:
SELECT x FROM Magazine x WHERE CONCAT(x.title, 's') = 'JDJs'
*
SUBSTRING(string, startIndex, length): Returns the part of the string argument starting at startIndex (1-based) and ending at length characters past startIndex.
SELECT x FROM Magazine x WHERE SUBSTRING(x.title, 1, 1) = 'J'
*
TRIM([LEADING | TRAILING | BOTH] [character FROM] string: Trims the specified character from either the beginning (LEADING), the ending (TRAILING), or both (BOTH) the beginning and ending of the string argument. If no trim character is specified, the space character will be trimmed.
SELECT x FROM Magazine x WHERE TRIM(BOTH 'J' FROM x.title) = 'D'
*
LOWER(string): Returns the lower-case of the specified string argument.
SELECT x FROM Magazine x WHERE LOWER(x.title) = 'jdj'
*
UPPER(string): Returns the upper-case of the specified string argument.
SELECT x FROM Magazine x WHERE UPPER(x.title) = 'JAVAPRO'
*
LENGTH(string): Returns the number of characters in the specified string argument.
SELECT x FROM Magazine x WHERE LENGTH(x.title) = 3
*
LOCATE(searchString, candidateString [, startIndex]): Returns the first index of searchString in candidateString. Positions are 1-based. If the string is not found, returns 0.
SELECT x FROM Magazine x WHERE LOCATE('D', x.title) = 2
*
ABS(number): Returns the absolute value of the argument.
SELECT x FROM Magazine x WHERE ABS(x.price) >= 5.00
*
SQRT(number): Returns the square root of the argument.
SELECT x FROM Magazine x WHERE SQRT(x.price) >= 1.00
*
MOD(number, divisor): Returns the modulo of number and divisor.
SELECT x FROM Magazine x WHERE MOD(x.price, 10) = 0
*
CURRENT_DATE: Returns the current date.
*
CURRENT_TIME: Returns the current time.
*
CURRENT_TIMESTAMP: Returns the current timestamp.
10.1.5. Polymorphic Queries
All JPQL queries are polymorphic, which means the from clause of a query includes not only instances of the specific entity class to which it refers, but all subclasses of that class as well. The instances returned by a query include instances of the subclasses that satisfy the query conditions. For example, the following query may return instances of Magazine, as well as Tabloid and Digest instances, where Tabloid and Digest are Magazine subclasses.
SELECT x FROM Magazine x WHERE x.price < 5
10.1.6. Query Parameters
JPQL provides support for parameterized queries. Either named parameters or positional parameters may be specified in the query string. Parameters allow you to re-use query templates where only the input parameters vary. A single query can declare either named parameters or positional parameters, but is not allowed to declare both named and positional parameters.
public Query setParameter (int pos, Object value);
Specify positional parameters in your JPQL string using an integer prefixed by a question mark. You can then populate the Query object with positional parameter values via calls to the setParameter method above. The method returns the Query instance for optional method chaining.
EntityManager em = ...
Query q = em.createQuery ("SELECT x FROM Magazine x WHERE x.title = ?1 and x.price > ?2");
q.setParameter (1, "JDJ").setParameter (2, 5.0);
List<Magazine> results = q.getResultList ();
This code will substitute JDJ for the ?1 parameter and 5.0 for the ?2 parameter, then execute the query with those values.
public Query setParameter (String name, Object value);
Named parameter are denoted by prefixing an arbitrary name with a colon in your JPQL string. You can then populate the Query object with parameter values using the method above. Like the positional parameter method, this method returns the Query instance for optional method chaining.
EntityManager em = ...
Query q = em.createQuery ("SELECT x FROM Magazine x WHERE x.title = :titleParam and x.price > :priceParam");
q.setParameter ("titleParam", "JDJ").setParameter ("priceParam", 5.0);
List<Magazine> results = q.getResultList ();
This code substitutes JDJ for the :titleParam parameter and 5.0 for the :priceParam parameter, then executes the query with those values.
10.1.7. Ordering
JPQL queries may optionally contain an order by clause which specifies one or more fields to order by when returning query results. You may follow the order by field clause with the asc or desc keywords, which indicate that ordering should be ascending or descending, respectively. If the direction is omitted, ordering is ascending by default.
SELECT x FROM Magazine x order by x.title asc, x.price desc
The query above returns Magazine instances sorted by their title in ascending order. In cases where the titles of two or more magazines are the same, those instances will be sorted by price in descending order.
10.1.8. Aggregates
JPQL queries can select aggregate data as well as objects. JPQL includes the min, max, avg, and count aggregates. These functions can be used for reporting and summary queries.
The following query will return the average of all the prices of all the magazines:
EntityManager em = ...
Query q = em.createQuery ("SELECT AVG(x.price) FROM Magazine x");
Number result = (Number) q.getSingleResult ();
The following query will return the highest price of all the magazines titled "JDJ":
EntityManager em = ...
Query q = em.createQuery ("SELECT MAX(x.price) FROM Magazine x WHERE x.title = 'JDJ'");
Number result = (Number) q.getSingleResult ();
10.1.9. Named Queries
Query templates can be statically declared using the NamedQuery and NamedQueries annotations. For example:
@Entity
@NamedQueries({
@NamedQuery(name="magsOverPrice",
query="SELECT x FROM Magazine x WHERE x.price > ?1"),
@NamedQuery(name="magsByTitle",
query="SELECT x FROM Magazine x WHERE x.title = :titleParam")
})
public class Magazine
{
...
}
These declarations will define two named queries called magsOverPrice and magsByTitle.
public Query createNamedQuery (String name);
You retrieve named queries with the above EntityManager method. For example:
EntityManager em = ...
Query q = em.createNamedQuery ("magsOverPrice");
q.setParameter (1, 5.0f);
List<Magazine> results = q.getResultList ();
EntityManager em = ...
Query q = em.createNamedQuery ("magsByTitle");
q.setParameter ("titleParam", "JDJ");
List<Magazine> results = q.getResultList ();
10.1.10. Delete By Query
Queries are useful not only for finding objects, but for efficiently deleting them as well. For example, you might delete all records created before a certain date. Rather than bringing these objects into memory and delete them individually, JPA allows you to perform a single bulk delete based on JPQL criteria.
Delete by query uses the same JPQL syntax as normal queries, with one exception: begin your query string with the delete keyword instead of the select keyword. To then execute the delete, you call the following Query method:
public int executeUpdate ();
This method returns the number of objects deleted. The following example deletes all subscriptions whose expiration date has passed.
Example 10.1. Delete by Query
Query q = em.createQuery ("DELETE s FROM Subscription s WHERE s.subscriptionDate < :today");
q.setParameter ("today", new Date ());
int deleted = q.executeUpdate ();
10.1.11. Update By Query
Similar to bulk deletes, it is sometimes necessary to perform updates against a large number of queries in a single operation, without having to bring all the instances down to the client. Rather than bring these objects into memory and modifying them individually, JPA allows you to perform a single bulk update based on JPQL criteria.
Update by query uses the same JPQL syntax as normal queries, except that the query string begins with the update keyword instead of select. To execute the update, you call the following Query method:
public int executeUpdate ();
This method returns the number of objects updated. The following example updates all subscriptions whose expiration date has passed to have the "paid" field set to true.
Example 10.2. Update by Query
Query q = em.createQuery ("UPDATE Subscription s SET s.paid = :paid WHERE s.subscriptionDate < :today");
q.setParameter ("today", new Date ());
q.setParameter ("paid", true);
int updated = q.executeUpdate ();
Click here to View more...
Assignment of a NULL value to a NOT NULL column (know what is NULL in JPA query) - sqlcode: -407 sqlstate: 23502
Hi,
This is a best and a simple way to know which all columns in your
table contain Null values.
It helped many of us, hope it might help you as well
Correct the SQL statement after examining the object table definition to determine which columns of the table have the NOT NULL attribute and do not have the WITH DEFAULT attribute.
If the value for name is of the form "TBSPACEID=n1, TABLEID=n2, COLNO=n3", you can determine the table name and column name using the following query:
SELECT C.TABSCHEMA, C.TABNAME,
C.COLNAME
FROM SYSCAT.TABLES AS T,
SYSCAT.COLUMNS AS C
WHERE T.TBSPACEID = n1
AND T.TABLEID = n2
AND C.COLNO = n3
AND C.TABSCHEMA = T.TABSCHEMA
AND C.TABNAME = T.TABNAME One of the following occurred:
- The update or insert value was NULL, but the object column was declared as NOT NULL in the table definition. Consequently:
- NULL values cannot be inserted into that column.
- An update cannot set values in that column to NULL.
- A SET transition-variable statement in a trigger cannot set values in that column to NULL.
- The update or insert value was DEFAULT, but the object column was declared as NOT NULL without WITH DEFAULT in the table definition. Consequently:
- A default value of NULL cannot be inserted into that column.
- An update cannot set default values of NULL in that column.
- A SET transition-variable statement in a trigger cannot set default values of NULL in that column.
- The column name list for the INSERT statement omits a column declared NOT NULL and without WITH DEFAULT in the table definition.
- The view for the INSERT statement omits a column declared NOT NULL and without WITH DEFAULT in the base table definition.
If the value for name is of the form "TBSPACEID=n1, TABLEID=n2, COLNO=n3", then the column name from the SQL statement was not available when the error was issued. The values provided identify the tablespace, table, and column number of the base table that does not allow NULL value.
Federated system users: this situation can be detected by the federated server or by the data source. Some data sources do not provide the appropriate values for name. In these cases the message token will have the following format: ":UNKNOWN", indicating that the actual value for the specified data source is unknown.
The statement cannot be processed.
Correct the SQL statement after examining the object table definition to determine which columns of the table have the NOT NULL attribute and do not have the WITH DEFAULT attribute.
If the value for name is of the form "TBSPACEID=n1, TABLEID=n2, COLNO=n3", you can determine the table name and column name using the following query:
SELECT C.TABSCHEMA, C.TABNAME,
C.COLNAME
FROM SYSCAT.TABLES AS T,
SYSCAT.COLUMNS AS C
WHERE T.TBSPACEID = n1
AND T.TABLEID = n2
AND C.COLNO = n3
AND C.TABSCHEMA = T.TABSCHEMA
AND C.TABNAME = T.TABNAME
The table and column identified by this query may be the base table of a view for which the SQL statement failed.
Federated system users: if the reason is unknown, isolate the problem to the data source failing the request (see the problem determination guide for procedures to follow to identify the failing data source) and examine the object definition for that data source. Remember that the defaults (NULL and NOT NULL) are not necessarily the same between data sources.
sqlcode: -407
sqlstate: 23502
Click here to View more...
Labels: Open JPA
Auto Focus on particular element on page load in JSF
Inside <f:view> place the following scriplet..
<%
javax.faces.context.FacesContext.getCurrentInstance()
.getViewRoot().setLocale(request.getLocale());
%>
-------------------------------------------------------------
Above </h:form> plce the following code...
The target filed (XXXX) indicates which field should have focus on page load
<hx:inputHelperSetFocus id="setFocus1" target="XXXX"
rendered="true"></hx:inputHelperSetFocus>
Click here to View more...
Labels: JSF, JSF Portlets Apllication
Which Collection is Best in Performance
This is why it takes me so long to write (or rewrite) a book. Examples like this, which I think are done, rear up and gobble lots of time. The good thing is that I end up understanding all the problems in much more depth. But it makes books -- especially one the size of Thinking in Java fourth edition -- take forever. The following was taken directly from the book:
A performance test framework
To prevent code duplication and to provide consistency among tests, I’ve put the basic functionality of the test process into a framework. The following code establishes a base class from which you create a list of anonymous inner classes, one for each different test. Each of these inner classes is called as part of the testing process. This approach allows you to easily add and remove new kinds of tests.
This is another example of the Template Method design pattern. Although you follow the typical approach of overriding the template method Test.test( ) for each particular test, in this case the core code (that doesn’t change) is in a separate Tester class. The type of container under test is the generic parameter C:
//: containers/Test.java
// Framework for performing timed tests of containers.
public abstract class Test {
String name;
public Test(String name) { this.name = name; }
// Override this Template Method for different tests.
// Returns actual number of repetitions of test.
abstract int test(C container, TestParam tp);
} ///:~
Each Test object stores the name of that test. When you call the test() method, it must be given the container to be tested along with a “messenger” or “data transfer object” that holds the various parameters for that particular test. The parameters include size, indicating the number of elements in the container, and loops, which control the number of iterations for that test. These parameters may or may not be used in every test.
Each container will undergo a sequence of calls to test(), each with a different TestParam, so TestParam also contains static array() methods that make it easy to create arrays of TestParam objects. The first version of array() takes a variable argument list containing alternating size and loops values, and the second version takes the same kind of list except that the values are inside Strings—this way it can be used to parse command-line arguments:
//: containers/TestParam.java
// A "data transfer object."
import java.util.*;
public class TestParam {
public final int size;
public final int loops;
public TestParam(int size, int loops) {
this.size = size;
this.loops = loops;
}
// Create an array of TestParam from a varargs sequence:
public static TestParam[] array(int... values) {
int size = values.length/2;
TestParam[] result = new TestParam[size];
int n = 0;
for(int i = 0; i < vals =" new" i =" 0;">
To use the framework, you pass the container to be tested along with a List of Test objects to a Tester.run() method (these are overloaded generic convenience methods which reduce the amount of typing necessary to use them). Tester.run() calls the appropriate overloaded constructor, then calls timedTest(), which executes each test in the list for that container. timedTest() repeats each test for each of the TestParam objects in paramList. Because paramList is initialized from the static defaultParams array, you can change the paramList for all tests by reassigning defaultParams, or you can change the paramList for one test by passing in a custom paramList for that test:
//: containers/Tester.java
// Applies Test objects to lists of different containers.
import java.util.*;
public class Tester {
public static int fieldWidth = 8;
public static TestParam[] defaultParams= TestParam.array(
10, 5000, 100, 5000, 1000, 5000, 10000, 500);
// Override this to modify pre-test initialization:
protected C initialize(int size) { return container; }
protected C container;
private String headline = "";
private List<> tests;
private static String stringField() {
return "%" + fieldWidth + "s";
}
private static String numberField() {
return "%" + fieldWidth + "d";
}
private static int sizeWidth = 5;
private static String sizeField = "%" + sizeWidth + "s";
private TestParam[] paramList = defaultParams;
public Tester(C container, List<> tests) {
this.container = container;
this.tests = tests;
if(container != null)
headline = container.getClass().getSimpleName();
}
public Tester(C container, List<> tests,
TestParam[] paramList) {
this(container, tests);
this.paramList = paramList;
}
public void setHeadline(String newHeadline) {
headline = newHeadline;
}
// Generic methods for convenience :
public static void run(C cntnr, List<> tests){
new Tester(cntnr, tests).timedTest();
}
public static void run(C cntnr,
List<> tests, TestParam[] paramList) {
new Tester(cntnr, tests, paramList).timedTest();
}
private void displayHeader() {
// Calculate width and pad with '-':
int width = fieldWidth * tests.size() + sizeWidth;
int dashLength = width - headline.length() - 1;
StringBuilder head = new StringBuilder(width);
for(int i = 0; i < i =" 0;"> test : tests) {
C kontainer = initialize(param.size);
long start = System.nanoTime();
// Call the template method:
int reps = test.test(kontainer, param);
long duration = System.nanoTime() - start;
long timePerRep = duration / reps; // Nanoseconds
System.out.format(numberField(), timePerRep);
}
System.out.println();
}
}
} ///:~
The stringField() and numberField() methods produce formatting strings for outputting the results. The standard width for formatting can be changed by modifying the static fieldWidth value. The displayHeader() method formats and prints the header information for each test.
If you need to perform special initialization, override the initialize( ) method. This produces an initialized container object of the appropriate size—you can either modify the existing container object or create a new one. You can see in test( ) that the result is captured in a local reference called kontainer, which allows you to replace the stored member container with a completely different initialized container.
The return value of each Test.test() method must be the number of operations performed by that test, which is used to calculate the number of nanoseconds required for each operation. You should be aware that System.nanoTime() typically produces values with a granularity that is greater than one (and this granularity will vary with machines and operating systems), and this will produce a certain amount of rattle in the results.
The results may vary from machine to machine; these tests are only intended to compare the performance of the different containers.
Choosing between Lists
Here is a performance test for the most essential of the List operations. For comparison, it also shows the most important Queue operations. Two separate lists of tests are created for testing each class of container. In this case, Queue operations only apply to LinkedLists.
//: containers/ListPerformance.java
// Demonstrates performance differences in Lists.
// {Args: 100 500} Small to keep build testing short
import java.util.*;
import net.mindview.util.*;
public class ListPerformance {
static Random rand = new Random();
static int reps = 1000;
static List>> tests =
new ArrayList>>();
static List>> qTests =
new ArrayList>>();
static {
tests.add(new Test>("add") {
int test(List list, TestParam tp) {
int loops = tp.loops;
int listSize = tp.size;
for(int i = 0; i < j =" 0;">>("get") {
int test(List list, TestParam tp) {
int loops = tp.loops * reps;
int listSize = list.size();
for(int i = 0; i <>>("set") {
int test(List list, TestParam tp) {
int loops = tp.loops * reps;
int listSize = list.size();
for(int i = 0; i <>>("iteradd") {
int test(List list, TestParam tp) {
final int LOOPS = 1000000;
int half = list.size() / 2;
ListIterator it = list.listIterator(half);
for(int i = 0; i <>>("insert") {
int test(List list, TestParam tp) {
int loops = tp.loops;
for(int i = 0; i <>>("remove") {
int test(List list, TestParam tp) {
int loops = tp.loops;
int size = tp.size;
for(int i = 0; i <> 5)
list.remove(5); // Minimize random access cost
}
return loops * size;
}
});
// Tests for queue behavior:
qTests.add(new Test>("addFirst") {
int test(LinkedList list, TestParam tp) {
int loops = tp.loops;
int size = tp.size;
for(int i = 0; i < j =" 0;">>("addLast") {
int test(LinkedList list, TestParam tp) {
int loops = tp.loops;
int size = tp.size;
for(int i = 0; i < j =" 0;">>("rmFirst") {
int test(LinkedList list, TestParam tp) {
int loops = tp.loops;
int size = tp.size;
for(int i = 0; i <> 0)
list.removeFirst();
}
return loops * size;
}
});
qTests.add(new Test>("rmLast") {
int test(LinkedList list, TestParam tp) {
int loops = tp.loops;
int size = tp.size;
for(int i = 0; i <> 0)
list.removeLast();
}
return loops * size;
}
});
}
static class ListTester extends Tester> {
public ListTester(List container,
List>> tests) {
super(container, tests);
}
// Fill to the appropriate size before each test:
@Override protected List initialize(int size){
container.clear();
container.addAll(new CountingIntegerList(size));
return container;
}
// Convenience method:
public static void run(List list,
List>> tests) {
new ListTester(list, tests).timedTest();
}
}
public static void main(String[] args) {
if(args.length > 0)
Tester.defaultParams = TestParam.array(args);
// Can only do these two tests on an array:
Tester> arrayTest =
new Tester>(null, tests.subList(1, 3)){
// This will be called before each test. It
// produces a non-resizeable array-backed list:
@Override protected
List initialize(int size) {
Integer[] ia = Generated.array(Integer.class,
new CountingGenerator.Integer(), size);
return Arrays.asList(ia);
}
};
arrayTest.setHeadline("Array as List");
arrayTest.timedTest();
Tester.defaultParams= TestParam.array(
10, 5000, 100, 5000, 1000, 1000, 10000, 200);
ListTester.run(new ArrayList(), tests);
ListTester.run(new LinkedList(), tests);
ListTester.run(new Vector(), tests);
Tester.fieldWidth = 12;
Tester> qTest =
new Tester>(
new LinkedList(), qTests);
qTest.setHeadline("Queue tests");
qTest.timedTest();
}
} /* Output: (Sample)
--- Array as List ---
size get set
10 130 183
100 130 164
1000 129 165
10000 129 165
--------------------- ArrayList ---------------------
size add get set iteradd insert remove
10 121 139 191 435 3952 446
100 72 141 191 247 3934 296
1000 98 141 194 839 2202 923
10000 122 144 190 6880 14042 7333
--------------------- LinkedList ---------------------
size add get set iteradd insert remove
10 182 164 198 658 366 262
100 106 202 230 457 108 201
1000 133 1289 1353 430 136 239
10000 172 13648 13187 435 255 239
----------------------- Vector -----------------------
size add get set iteradd insert remove
10 129 145 187 290 3635 253
100 72 144 190 263 3691 292
1000 99 145 193 846 2162 927
10000 108 145 186 6871 14730 7135
-------------------- Queue tests --------------------
size addFirst addLast rmFirst rmLast
10 199 163 251 253
100 98 92 180 179
1000 99 93 216 212
10000 111 109 262 384
*///:~
Each test requires careful thought to ensure that you are producing meaningful results. For example, the “add” test clears the List and then refills it to the specified list size. The call to clear() is thus part of the test, and may have an impact on the time, especially for small tests. Although the results here seem fairly reasonable, you could imagine rewriting the test framework so that there is a call to a preparation method (which would, in this case, include the clear() call) outside of the timing loop.
Note that for each test, you must accurately calculate the number of operations that occur and return that value from test(), so the timing is correct.
The “get” and “set” tests both use the random number generator to perform random accesses to the List. In the output, you can see that, for a List backed by an array and for an ArrayList, these accesses are fast and very consistent regardless of the list size, whereas for a LinkedList the access times grow very significantly for larger lists. Clearly, linked lists are not a good choice if you will be performing many random accesses.
The “iteradd” test uses an iterator in the middle of the list to insert new elements. For an ArrayList this gets expensive as the list gets bigger, but for a LinkedList it is relatively cheap, and constant regardless of size. This makes sense because an ArrayList must create space and copy all its references forward during an insertion. This becomes expensive as the ArrayList gets bigger. A LinkedList only needs to link in a new element, and doesn’t have to modify the rest of the list, so you expect the cost to be roughly the same regardless of the list size.
The “insert” and “remove” tests both use location number 5 as the point of insertion or removal, rather than either end of the List. A LinkedList treats the end points of the List specially—this improves the speed when using a LinkedList as a Queue. However, if you add or remove elements in the middle of the list, you include the cost of random access, which we’ve already seen varies with the different List implementations. By performing the insertions and removals at location five, the cost of the random access should be negligible and we should see only the cost of insertion and removal, but we will not see any specialized optimization for the end of a LinkedList. You can see from the output that the cost of insertion and removal in a LinkedList is quite cheap and doesn’t vary with the list size, but with an ArrayList, insertions especially are very expensive, and the cost increases with list size.
From the Queue tests, you can see how quickly a LinkedList can insert and remove elements from the endpoints of the list, which is optimal for Queue behavior.
Normally, you can just call Tester.run(), passing the container and the tests list. Here, however, we must override the initialize() method so that the List is cleared and refilled before each test—otherwise the List control over the size of the List would be lost during the various tests. ListTester inherits from Tester and performs this initialization using CountingIntegerList. The run() convenience method is also overridden.
We’d also like to compare array access to container access (primarily against ArrayList). In the first test in main(), a special Test object is created using an anonymous inner class. The initialize() method is overridden to create a new object each time it is called (ignoring the stored container object, so null is the container argument for this Tester constructor). The new object is created using Generated.array( ) (which was defined in the Arrays chapter) and Arrays.asList(). Only two of the tests can be performed in this case, because you cannot insert or remove elements when using a List backed by an array, so the List.subList() method is used to select the desired tests from the tests list.
For random-access get( ) and set( ) operations, a List backed by an array is slightly faster than an ArrayList, but the same operations are dramatically more expensive for a LinkedList because it is not designed for random-access operations.
Vector should be avoided; it’s only in the library for legacy code support (the only reason it works in this program is because it was adapted to be a List for forward compatibility).
The best approach is probably to choose an ArrayList as your default and to change to a LinkedList if you need its extra functionality or you discover performance problems due to many insertions and removals from the middle of the list. If you are working with a fixed-sized group of elements, either use a List backed by an array (as produced by Arrays.asList( )), or if necessary, an actual array.
CopyOnWriteArrayList is a special implementation of List used in concurrent programming, and will be discussed in the Concurrency chapter.
Choosing between Sets
Depending on the behavior you desire, you can choose a TreeSet, a HashSet, or a LinkedHashSet. The following test program gives an indication of the performance trade-off between these implementations:
//: containers/SetPerformance.java
// Demonstrates performance differences in Sets.
// {Args: 100 5000} Small to keep build testing short
import java.util.*;
public class SetPerformance {
static List>> tests =
new ArrayList>>();
static {
tests.add(new Test>("add") {
int test(Set set, TestParam tp) {
int loops = tp.loops;
int size = tp.size;
for(int i = 0; i < j =" 0;">>("contains") {
int test(Set set, TestParam tp) {
int loops = tp.loops;
int span = tp.size * 2;
for(int i = 0; i < j =" 0;">>("iterate") {
int test(Set set, TestParam tp) {
int loops = tp.loops * 10;
for(int i = 0; i <> it = set.iterator();
while(it.hasNext())
it.next();
}
return loops * set.size();
}
});
}
public static void main(String[] args) {
if(args.length > 0)
Tester.defaultParams = TestParam.array(args);
Tester.fieldWidth = 10;
Tester.run(new TreeSet(), tests);
Tester.run(new HashSet(), tests);
Tester.run(new LinkedHashSet(), tests);
}
} /* Output: (Sample)
------------- TreeSet -------------
size add contains iterate
10 746 173 89
100 501 264 68
1000 714 410 69
10000 1975 552 69
------------- HashSet -------------
size add contains iterate
10 308 91 94
100 178 75 73
1000 216 110 72
10000 711 215 100
---------- LinkedHashSet ----------
size add contains iterate
10 350 65 83
100 270 74 55
1000 303 111 54
10000 1615 256 58
*///:~
The performance of HashSet is generally superior to TreeSet, but especially when adding elements and looking them up, which are the two most important operations. TreeSet exists because it maintains its elements in sorted order, so you use it only when you need a sorted Set. Because of the internal structure necessary to support sorting and because iteration is something you’re more likely to do, iteration is usually faster with a TreeSet than a HashSet.
Note that LinkedHashSet is more expensive for insertions than HashSet; this is because of the extra cost of maintaining the linked list along with the hashed container.
Choosing between Maps
This program gives an indication of the trade-off between Map implementations:
//: containers/MapPerformance.java
// Demonstrates performance differences in Maps.
// {Args: 100 5000} Small to keep build testing short
import java.util.*;
public class MapPerformance {
static List
Insertions for all the Map implementations except for IdentityHashMap get significantly slower as the size of the Map gets large. In general, however, lookup is much cheaper than insertion, which is good because you’ll typically be looking items up much more often than you insert them.
Hashtable performance is roughly the same as HashMap. Since HashMap is intended to replace Hashtable, and thus uses the same underlying storage and lookup mechanism (which you will learn about later) this is not too surprising.
A TreeMap is generally slower than a HashMap. As with TreeSet, a TreeMap is a way to create an ordered list. The behavior of a tree is such that it’s always in order and doesn’t have to be specially sorted. Once you fill a TreeMap, you can call keySet( ) to get a Set view of the keys, then toArray( ) to produce an array of those keys. You can then use the static method Arrays.binarySearch( ) to rapidly find objects in your sorted array. Of course, this only makes sense if the behavior of a HashMap is unacceptable, since HashMap is designed to rapidly find keys. Also, you can easily create a HashMap from a TreeMap with a single object creation or call to putAll(). In the end, when you’re using a Map, your first choice should be HashMap, and only if you need a constantly sorted Map will you need TreeMap.
LinkedHashMap tends to be slower than HashMap for insertions because it maintains the linked list (to preserve insertion order) in addition to the hashed data structure. Because of this list, iteration is faster.
IdentityHashMap has different performance because it uses == rather than equals( ) for comparisons. WeakHashMap is described later in this chapter.
Click here to View more...
Labels: Do You Know ?
Best Web 2.0 Logo Generators
Hi all, I am really sorry for not posting anything the past week. I was really busy with watching anime and playing counter strike. I had been watching an anime series since the past two months and I was really close to the end so I was too hooked into watching that rather then posting here. ![]()
Anyways, today I will be sharing with you a couple of nice web 2.0 logo generators. So if you are looking for a new web 2.0 logo for your site then look no further. These tools will really save you a lot of time.
LogoCreator probably has the most options to tweak and optimize your logo to your liking. It also has 5 pre-made templates that you can choose from to make your own web 2.0 logo. You can choose from a variety of different options to change the look of your logo such as font size, font face, mirror space and effect, transparency, and many more options. It probably is the most versatile logo generator out of the four. I highly recommend it.
SimWebSol Logo Generator also offers a wide range of options for you to customize the look of your logo. A couple of nice tweaks include the reflection proximity and the “Add Symbol” option. Basically you canchoose from a number of different symbols that include the beta text as well as many other little graphic symbols. I really liked this symbol feature and no other web 2.0 logo generator has this feature.
Web 2.0 STYLr is a nice logo generator as well. It has a couple of nice tweaks as well to make an impressive web 2.0 logo generator. There is also a nice feature that lets you add an icon to the left of the text. So in the end you will have your icon to the left and your generated text to the right. You should try this feature out as well.
Web2.0V2Logo Creatr is a nice little and probably the most easiest logo generator to use. You only need to type in your text and change a total of two options. Their is only one effect that you can do with this logo generator but its good so it is kinda useful. Your logo will look similar to the logo above.Click here to View more...
Labels: Latest NEWZ, Web 2.0
Download Free Latest Orkut Themes
A lot of you people must use orkut and must be wondering how to change the default boring orkut theme. Well, your search is over. I have personally made 20 brand new orkut themes that you wont find anywhere else on the net. Everything from NBA to Cricket to Firefox to Katrina Kaif! ![]()
I would like to point out though, that these orkut themes will only be shown to yourself when YOU are browsing orkut. So lets get started. First I will list the requirements that you need to fulfill in order to install these orkut themes.
Installation Procedure for these Orkut Themes
Once you have installed mozilla firefox and the greasemonkey addon then all you need to do is install any one of the following orkut themes. Below every theme image is a link to the script for that specific orkut theme. Just click on any one and you will be prompted to install it. Click install and it will be installed in a jiffy! You can then go to browse orkut with your new theme. If you want to change a theme then you will first install the new theme from this page. Then you have to right-click on the little “monkey” face in the status bar below. From there, you will see a list of your installed scripts which will have the different orkut themes. Just uncheck any theme you do not want to use and check any orkut theme that you do want to use. Its just that simple!
Uninstall Procedure for these Orkut Themes
If you want to completely remove any of these orkut themes then right-click the monkey face and click Manage User Scripts. You will see a list of your installed scripts. Just select any script that you want to remove and click the Uninstall button at the bottom. Its just that simple!
Note: Click image to see a higher resolution image of that orkut theme
Orkut Themes
Aishwarya Rai Orkut Themes
To download this orkut theme, click here.
To download this orkut theme, click here.
Bleach Orkut Theme
To download this orkut theme, click here.
Christiano Ronaldo Orkut Theme
To download this orkut theme, click here.
David Beckham Orkut Theme
To download this orkut theme, click here.
Dhoni Orkut Theme
To download this orkut theme, click here.
Firfox Orkut Theme
To download this orkut theme, click here.
Dragonball Z Orkut Theme
To download this orkut theme, click here.
Halo 3 Orkut Theme
To download this orkut theme, click here.
Kareen Kapoor Orkut Themes
To download this orkut theme, click here.
To download this orkut theme, click here.
Katrina Kaif Orkut Theme
To download this orkut theme, click here.
Naruto Orkut Theme
To download this orkut theme, click here.
NBA Orkut Theme
To download this orkut theme, click here.
Ronaldinho Orkut Theme
To download this orkut theme, click here.
Sachin Tendulkar Orkut Theme
To download this orkut theme, click here.
Salman Khan Orkut Themes
To download this orkut theme, click here.
To download this orkut theme, click here.
Shahrukh Khan Orkut Theme
To download this orkut theme, click here.
Spiderman Orkut Theme
To download this orkut theme, click here.
Once again, you will not find these orkut themes anywhere else as I made them myself. If you have a good idea for a theme or you want a specific theme not mentioned above, just post a comment and I will see if I can make one. If you have any questions or suggestions or any type of feedback, you can leave a comment here or contact me. Thanks for visiting, and enjoy!
Click here to View more...
Labels: Orkut themes























