Archive for January, 2009

A concised discussion over relative merits & demerits of different laws to measure speed-up performance vis-à-vis to a parallel-computer algorithm-system

A concised discussion over relative merits & demerits of different laws to measure speed-up performance vis-à-vis to a parallel-computer algorithm-system

The Merits & demerits of different laws to measure a speed-up performances!

Amdahl’s Law

The speed-up factor help us to know the relative gain that is achieved in shifting the execution of a task from sequential computer to parallel computer and the performance does not increase linearly with the increase in number of processor.

Now, Let us consider a problem say P, which has to be solved using a parallel computer. According to Amdahl’s law, there are mainly two types of operations; therefore, the problem will have some sequential operation and some parallel operations. We already know that it requires T (1) amount of time to execute a problem using a sequential machine and sequential algorithm. The time to compute the sequential operation is a fraction ? (?<=1) of the total execution time i.e. T (1) and the time to computer the parallel operations is (1- ?), therefore S (N) can be calculated as under:-

S (N) =T (1)/T (N)

S (N) =T (1)/ (?*T (1) + (1- ?)*T (1)/N)

Dividing by T (1)

S (N) =1/ (?+ (1- ?)/N)

Remember the value of ? is between 0 and 1. Now put some values of number of processors, we find that the S (N) keeps on decreasing with increase in the value of ?.

speedpro1

Speed up Factor S (N) v/s ?

spdpro2


Outcomes of analysis of Amdahl’s Law:-

To optimize the performance of parallel computers modifies compiler need to be developed which aim to reduce the number of sequential operation pertaining to the reaction ?.

Manufacturers of parallel computers were discouraged from manufacturing large scale machine having millions of processors.

One major shortcoming identified in Amdahl’s law: according to Amdahl’s law the problem size is always fixed and of sequential operations remains mainly same.

Gustafson’s Law

There are numerous applications that require that accuracy of the resultant output should be high. In the present situation the computing power has increased substantially due to increase in number of processors attached to parallel computer. Thus it is possible to increase the size of the problem. The graph of speed up:

spd3


S (N) =? +N*(1- ?)

S (N) = N- ?*(N-1)

Thus decrease is because of overhead or sizes caused by inter processor communication.

Sun and Ni’s Law

The Sun and Ni’s Law is a generalization of Amdahl’s Law as well as Gustafson’s Law. The fundamental concept of underlying the Sunand Ni’s Law is to find the solution to a problem with a maximum size along with limited requirement of memory. Now a day, there are many applications which are bounded by the memory in contrast to the processing speed.

In a multiple based parallel computer, each processor has an independent small memory. In order to solve a problem, normally the problem is divided into sub problems and distributed to various processors. It may be noted that size of sub-problem should be in proportion with size of the independent local memory available with the processor. The size of the problem can be increased further such that the memory could be utilized. This technique assists in generating more accurate solution as the problem size has been increased.

Filed in: - MS CS/IT, Study Stuff
44
Diagrammatic Discussion over an arithmetic pipeline for Multiplication of two 8-digit fixed numbers

Diagrammatic Discussion over an arithmetic pipeline for Multiplication of two 8-digit fixed numbers

Arithmetic Pipelining for fixed numbers Multiplication of 8 digit fixed numbers

arith-pipeline

Following stages for pipelining:

  1. The first stage generates the partial product of number, which form the six rows of shifted multiplicands.
  2. In second step, the eight are given to the two carry save address merging six numbers.
  3. Third step: a single CSA merging the number into 5 numbers.
  4. Similarly in next step 5 numbers into 4 number and 4 number into 3.
  5. In last step, two numbers are added through a carry propagation adder (CPA) to get the final result. X & Y are two 8 digit fixed number so arithmetic pipeline for multiplication of two 8 digit fixed number is given below:

pipelinestages

Filed in: - MS CS/IT, Study Stuff
2
A diagrammatic representation of obtaining a Perfect-Shuffle Permutation network of 32 nodes

A diagrammatic representation of obtaining a Perfect-Shuffle Permutation network of 32 nodes

Perfect shuffle permutation Consider N objects each represented by 4 bits, 4 number say Xn-1, Xn-2, X0. The perfect shuffle of this N object 4 expressed as.

Xn-1, Xn-2, X0 = Xn-2, X0, Xn-1,

This means that perfect shuffle is obtained by rotating the address by 1 bit left.

Shuffle permutation of 32 Nodes:

shuffle32net1

Close Network:

It is a non-blocking network and provides full connectivity like crossbar network but it requires significantly less number of switches. The organization of close network is shown below using 4 X 4 cross point switches:

close-network1

Filed in: - MS CS/IT, Study Stuff
0
THE BUSINESS COMMUNICATION-1

THE BUSINESS COMMUNICATION-1

This article is a kind of presentation to basics of business communication. In the next up-coming articles, you’ll be able to learn the major pillars and the specifics of business communication.

Communication characteristics and competence

(Significance of communication once approaching a job)

This is the most crucial aspect of the communication that can be considered as one of the major pillars to professionalism. The competency or skill listed most often in job advertisements was communication combined with a variety of adjectives ranging from excellent, the most common to superior, advanced, well-developed, proven, outstanding and natural. Being a team player was most favorite followed closely by interpersonal skills.

An integrated or shared meaning model of communication

comm-model2

Why study communication?

Following four reasons describe the need of the communication.

The growth of technology

Social alienation is growing

Physical well-being

Survival of the human race

Dimensions in communication

Following four objects make the concrete dimension of the business communication.

Verbal

Non-verbal

Mediated

Unmediated

Skill sets

Again there are four observations in communication skill set.

Thinking and feeling

Acting and observing

Speaking and listening

Writing and reading

Levels of communication

There are five major levels of business communication that briefly reveal the sense and existence of the communication.

Level one: intrapersonal communication or the experience of the individual.

Level two: interpersonal communication.

Level three: group communication.

Level four: organizational communication, including:

Internal organizational communication

External organizational communication.

Level five: mass communication

The communication theory

This portion will describe the overall gathered knowledge about communication.

What is a theory?

It explains information or behavior that has been observed.

It is useful because it can be applied to questions about observed behavior to analyze or explain it.

It can be used to suggest solutions to problems, or improvements to a situation.

Why a model?

A model simplifies a theory.

It can aid our thinking about a concept or idea.

It maps something abstract and presents it in a visual form.

It shows the major elements in relationship to each other.

Components of the communication process

Participants

Sender: the participant transmitting the message.

Receiver: the participant receiving the message.

Encoding: the translation of a message (thoughts or ideas of the sender) into words or symbols that the receiver will understand.

Decoding: the translation by the receiver of words or symbols (the encoded message) into thoughts or ideas.

Components of the communication process

Channel: the route through which communication takes place

Context: the situation/environment in which communication occurs. Includes time, place and socio/psychological factors

Perception: a person’s understanding or interpretation of a particular event/message.

Components of the communication process

Purpose: what the sender and receiver intend as the outcome of the communication.

Barriers (sometimes known as noise): anything that interferes with effective communication.

An integrated or shared meaning model of communication

comm-model


The Principles of communication

We communicate with others: it is a two-way process

Communication is a collection of signals; it is more than words

Communication is always on two levels:

Content & relational

Communication is punctuated

Communication is inevitable

Communication is irreversible

Communication is unrepeatable

Communication is rarely completely understood

Filed in: - MBA, Study Stuff
3
Equations for writing ‘C’ Programs using LU decomposition-method and Jacobi iterative-method

Equations for writing ‘C’ Programs using LU decomposition-method and Jacobi iterative-method

Question-1

‘C’

Please solve the equations given below?

q1-c

You’ll be using the LU decomposition-method

Answer

I got the values as

L11 = 10

L21 = 1

L22 = 101/10

L31 = 2

L32 = 32/10

L33 = 2018/101

U12 = -1/10

U13 = 1/5

U23 = -12/101

Using LUX = B

Let UX = y

LY = B

10y1 = 4

y1 = 4/10

y1 + 101/10 y2 = 3

y2 = 26 /101

2y1 +32/10 y2 + 2018/101 y3 = 7

y3 = 543/2018

Now solving UX = Y

The equation are..

x1 -1/10 x2 + 1/5 x3 = 4/10

x2 – 12/101 x3 = 26/101

x3 = 543/2018 = 0.269

x2 = 58984/203818 = .289

x1 = 76457/203818 = 0.375

You can verify the answer by substituting it in the given equation.

‘D’

Look into the system of equations as given below.

q1-d

You’ll be using Jacobi iterative-method and will perform three iterations.

This system can be written as

X1 = 0.5X2 + 0X3 + 3.5

X2 = 0.5X1 +0.5X3 + 0.5

X3 = 0X1 + 0.5X3 + 0.5

X1k+1 = ½ (X2k + 7)

X2k+1 = ½ (X3k + X1k + 1)

X3k+1 = ½ (X2k + 1)

So the Jacobbi iteration is:

q1-d2


No initial iteration is given so we start with X0 = (0, 0, 0)T

We get the following iteration

X1 = [3.500 0.500 0.500 ]T

X2 = [3.750 2.500 0.750]T

X3 = [4.750 2.750 1.750]T

X4 = [4.875 3.750 1.875]T

After 4 iteration the errors in the solutions are

q1-d3


The solution X4 is almost correct to 3 decimal positions.

Filed in: - MS CS/IT, Study Stuff
2
Definition and comparison to Secant method, Regular Falsi method and the Newton Raphson method

Definition and comparison to Secant method, Regular Falsi method and the Newton Raphson method

Question No.1

‘B’

There are three methods Secant method, Regula Falsi method and the Newton Raphson method. Your next task is to briefly define which method is more and why efficient? Determine the efficiency or the order of these three methods?

Answer

The Newton-Raphson method is considered to be the fastest method. But the method approaches to the root only when the initial guess is chosen very near the root. If the initial guess is not near the actual root, the method may diverge. The Secant method gives better results than Regula Falsi method. But the Secant method may not converge to the root sometimes. But the Regula Falsi method always converges.

If f ‘(x) evaluation is not difficult then Newton Raphson method is recommended. If evaluation of f ‘(x) is difficult then Secant method is recommended. But the convergence must be verified using bisection method once in every 10 iterations.

This is a detailed examination of four methods of discovering roots and the effects of different equations on the efficiency of each method and the amount of error produced by each method. Although some calculation here has been done by hand, the vast majority of our conclusions were arrived at by using computer programs for each of the methods. The four methods examined were bisection, false-position, secant, and Newton. Each method seemed to have a particular type of equation or desirable outcome for which it is most efficient.

Secant Method

One of the faster methods, compared to bisection and false position, for approximating roots is the secant method. Unlike the other two methods, f(a) and f(b) of the two initial values that we pick to start with do not have be on opposites sides of the root and have a sign change. This one works by always making the old b value into the new a value. The new b value then becomes the zero of the secant line.

One of the problems with this method is that the slope of the secant line can become very small and this will cause it to move very far from the points you have. This method fails when estimating the roots of an equation, which has a very low slope near the root because the secant line will jump large amounts due to the low slope. Another problem is that this method like the false position method does not know when to stop. It must be performed several times until the f of the current guess is very small.

Newton’s Method

Newton’s method is generally used in calculus to approximate roots. One main difference between Newton and other methods is that it only requires one initial guess instead of two. Also, if the guess is relatively close to a root, Newton‘s method works incredibly fast. If the guess is not close to a root, however, Newton’s method can work slowly and, depending on the function, may be impossible to use.

One similarity between Newton’s method and the bisection method is that both approximate roots in a consistent fashion. This allows the user to predict exactly how long it will take to arrive at a root, assuming the function and the original guess are sufficiently “nice” for Newton’s method. Newton’s method doubles in precision with each step. This is why Newton requires the same number of steps in Table B, regardless of the value of n in the equation.

Newton’s method uses not only the function itself but also the derivative of that function to approximate the root. One chooses a point ‘a’. Throughout the course of the method, this will be replaced by the zero of the tangent line (the zero of the derivative). To find the new point, use the formula [a – (f(a))/(f’(a))]. This will be the new ‘a’, and one repeats this process until the root is found to sufficient precision.

Another interesting possibility with Newton’s method is error calculation.

Error calculations simply show the difference between the values arrived at by some method and the actual value. Notice below where R is the root and x is the result of the most recent Newton iteration.

Error = x – R

New Error = x- (f(x)/f’(x))-R ~ f(x) and f’(x) are expanded out to a power series.

With the Newton‘s method, we make the assumption that X is close enough to R so that the first nonzero term in the power series in numerator and denominator is almost the entire error. Finally, following this assumption, one can determine that the new error is about (x-R)/2, which means that the error is cut in half each time.

False Position

Another method used for estimating roots of equations is the false position method. This method functions by first starting with two endpoints a and b. If f(a) and f(b) are not roots, then f(a) times f(b) is a negative value since they both need to lie on opposites sides of the root. This follows the logic that a negative value times a positive value equals a negative value. After the endpoints are chosen, false position finds the zero of the secant line joining (a,f(a)) and (b,f(b)) and then setting that as its new endpoint. This is done repetitively as the endpoints become continually closer to the root. An examination of the computer code for the false position method shows that it is very similar to the bisection method except that it uses the zero of the secant line to approach the root rather then finding the midpoint each time.

The false position method is often significantly faster then the bisection method for equations such as y = xn –2 for a small value of n. When n becomes large then false position often becomes the slowest method. In the data section of this paper, table B shows the number of repetitions for each method and value of n using the equation y = xn-2.

Data

Table A:

f(x) = x2 – 2 a = 1 b = 2 accuracy within 0.00001


Method Name

Number of steps

Bisection

17 steps

False – Position

8 steps

Secant

5 steps

Newton

4 steps


Table B:

For f(x) = xn – 2, a = 1, b = 2, n = {3, 4,…, 10} and accuracy within 0.0001


Number of steps

n = 3

n = 4

n = 5

n = 6

n = 7

n = 8

n = 9

N = 10

Bisection

17

17

17

17

17

17

17

17

False – Position

13

20

31

49

76

120

189

296

Secant

6

7

7

7

8

8

8

8

Newton’s

4

4

4

4

4

4

4

4

Table C:

For f(x) = x2 – 2, a = 1, b = 2, done for 25 iterations of each method, the error was:

Method:

Error:

Bisection

9.501 x 10-8

False-Position

-2.420323 x 10-8

Secant

-2.420323 x 10-8

Newton

-2.420323 x 10-8

For secant and Newton, the program was not able to complete 25 iterations. After 6 iterations, the memory overflowed.

Analysis of Data

The above data produces “nice” endpoints since the functions that were examined are also ideal. Even so, there was a lot of variation in the speed, accuracy, and reliability of each method. Table A shows the variation in speed between all four methods. It is clear that in this case Newton’s method would be a good choice for finding the root.

In Table B, one can see the consistency with which the bisection and Newton methods work for nice functions. This same consistency could be seen using the bisection method on any function, but Newton requires a relatively calm function in order to be helpful. One can also see that one method’s definition of a nice function is not the same as another method’s definition. Newton will work well on any non-oscillating, non-asymptotic function whose slope is not very close to zero. Nearly any polynomial fits this description. However, the false -position method’s effectiveness is inversely proportional to the degree of the polynomial. False-position’s definition of a nice function would be something more on the order of a low – degree function.

Table C shows the degree of accuracy, which can be achieved in 25 iterations of each method. The errors for all the methods are the same except for the bisection method. This once again emphasizes how relatively fast the other three are for functions they consider nice. The main problem encountered in this exercise had to do with the speed of these functions. Because they worked so quickly, within six steps secant and Newton’s methods had produced results, which were as accurate as the computer’s memory could hold. After six iterations, the computer would have a memory overflow. We corrected this by altering the number of iterations.

Conclusion

It was shown first-hand in this analysis that the speed of the method was inversely proportional to the consistency of the method to deal with non-nice functions. Newton’s method originally seemed to be an exception to this rule, because it was about five times as fast as bisection, but just as consistent for xn – 2 for all n. It was after trying some functions of different forms that one can find that the functions which are nice for Newton’s method are different than those for false-position and secant methods. These non-nice functions are easily found for Newton’s method, which makes Newton inconsistent and unable to efficiently solve for the root.

For nice functions and guesses relatively close to the root, each of the methods used require relatively few iterations before coming very close to that root. By examining the type of function, one can determine which sort of method would be most efficient in finding the root.

Filed in: - MS CS/IT, Study Stuff
3
Writing a Program in ‘C’ Language using Secant-Method

Writing a Program in ‘C’ Language using Secant-Method

Question No. 1

‘A’

You next task is to develop a ‘C’ program to find a root using Secant Method. You’ll have to perform the five iterations to obtain the smallest positive root of the equation f(x) = cos x – xex = 0,, verify your answer with the program written by you.

Answer

/* Root Using Secant Method*/


#include <stdio.h>

#include <math.h>

#define f(x) (exp(x)*log(x)-x*x)


main()

/* Main program to use the Secant Method to find the root of

f(x)=exp(x)*ln(x)-x*x=0. Copyright © Tao Pang 1997. */

{

int istep;

double dl=1e-6;

double a,b,xi,xf,di,df;

void secant ();

a = 1; b = 2;

di = (b-a)/10;

xi = (a+b)/2;

secant (dl,xi,di,&xf,&df,&istep);

printf(“%4d %16.8lf %16.8lf\n”, istep,xf,df);

}


void secant (dl,xi,di,xf,df,istep)

/* Subroutine for the root of f(x)=0 with the secant method.

Copyright © Tao Pang 1997. */

int *istep;

double dl,xi,di;

double *xf,*df;

{

double x0,x1,x2,d;

x0 = xi;

x1 = xi+di;

*df = di;

*istep = 0;

while (fabs(*df) > dl)

{

d = f(x1)-f(x0);

x2 = x1-f(x1)*(x1-x0)/d;

x0 = x1;

x1 = x2;

*df = x1-x0;

*istep = *istep+1;

}


*xf = x0;

}

Filed in: - MS CS/IT, Study Stuff
2
The hope, revoke, crisis slope & President Obama

The hope, revoke, crisis slope & President Obama

At last USA 44th president took the oath to dedicate his potentials to America and hopefully the world most genius and courteous present & future strategies and policies. American president is stepped into the most significant position where the world concentrations are centralized to look into the substantial change. Let us see what changes up-front there.

Yet….a lot to cope with Up!

44th-president

The way Obama watching the Nation, Nation watching the way!

obama-oath

Oath Ceremony!

obama-wife

Obama’s first hope into reality!

obama-flag

Filed in: News Update
2
Europeon Up-coming Biometric recognition passports

Europeon Up-coming Biometric recognition passports

The bill was backed by the majority members of the European Parliament that was proposed by the Eu-Commission on the pre-introduction of biometric passport within the Schengen area. The mentioned countries are advised to start issuing new passport by the June and complete the process until 2012.

pass-sensetive

The fundamental for new regulation demanding passports feature live fingerprint recognition in the report Coelho released after having brief negotiations with the European Commission, executive body of the European Union for this proposal. The report is named after Carlos Coelho, a Portuguese member of parliament for the central-right EPP-ED Group, that include.

Protection of children against cross-border traveling or kidnapping is one of the reasons for this regulation. Agrees that children need their own passport, instead of traveling on their parents’ documents.

But the new card for children is not part of biometric identification, Parliament Civil Liberties Committee that it is unnecessary, because their fingerprints are constantly changing as they grow up.

Countries that are members of the European Union, but not part of the Schengen Agreement, which the United Kingdom, Ireland or Denmark, are exempt from this policy, but is necessary for machine-readable passports with facial images instead. But Britain has already announced that it will introduce biometric data, even if he does not want his actions to be classified as 2nd class.

Furthermore, some countries such as France and Germany already use fingerprint ID cards embedded in their chips, although the last day to initiate the implementation of June 2009. People can travel with older passport until 2012, with certain exceptions.

Meanwhile, a number of civil liberties and security researchers strongly contested, both technical and ethical reasons. They claim to save as much as biometric data in a central European database is a security threat, or that the costs of implementation are not justified, compared with profits. Although the new passports may be more difficult to counterfeit, fingerprint identification is not soundproof, precedents exist for the false positive, security researchers maintain.

The relaxation of earlier identification techniques such as visual contact between the border area, officials and passengers is another possible side effect. Physical look at a person who can reveal more visual signals, such as adjustments or sweating, which gives an indication of agitation or anxiety, and can give people something.

People who do not have any fingerprints on the basis of disability or otherwise, because of their daily work, they will be able to travel with temporary passports with biometric identification, which will be valid for 12 months. For example, bricklayer constantly removes their fingerprints when working in conjunction with the constant stress on their fingers’ skin.

2
Creating application to display Time, Date and number of hits at website using Servlet

Creating application to display Time, Date and number of hits at website using Servlet

Question-8:

Write a servlet application that displays the current time, date and the number of hits if a person opens a particular web site.

import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Date;

public class Hitcounter extends HttpServlet {

public static int hitcounter = 0;

public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
out.println(“<html>”);
synchronized(this) {
hitcounter++;}

out.println(“<head>”);
out.println(“<title>Website hit counter servlet::</title>”);
out.println(“</head>”);
out.println(“<body>”);
out.println(“<p>Current Date and Time is: ” +
new Date().toString() + “</p>”);
out.println(“Since loading, this servlet has been hit ” +
hitcounter + ” times.”);

out.println(“</body></html>”);
}
}

Filed in: - MS CS/IT, Study Stuff
0
Ceating an Award-list for MCA Students as XML Doc.

Ceating an Award-list for MCA Students as XML Doc.

Question-6:

Implement the award list of MCA final year students as an XML document. The table must have student name, enrollment number, three subjects and its score.

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE Awardlist SYSTEM”c:/xml/awardlist.dtd”>
<!–Award list MCA final year student–>
<Awardlist>
<students>
<student contact=”yes/no”>
<nameEnrol>
<firstName>firstName</firstName>
<lastName>lastName</lastName>
<enrolNo>enrolNo</enrolNo>
</nameEnrol>
<subjects>
<subject>
<subjectName>subjectName</subjectName>
<score>score</score>
</subject>
<subject>
<subjectName>subjectName</subjectName>
<score>score</score>
</subject>
<subject>
<subjectName>subjectName</subjectName>
<score>score</score>
</subject>
</subjects>
</student>
</students>
</Awardlist>

DTD for above xml file

<!DOCTYPE Awardlist [
<!ELEMENT students (student+)>
<!ELEMENT student(nameEnrol,subject)>
<!ELEMENT nameEnrol(firstName,lastName,enrolNo)>
<!ATTLIST student contact(yes|no)"yes">
<!ELEMENT firstName(#PCDATA)>
<!ELEMENT lastName(#PCDATA)>
<!ELEMENT enrolNo(#PCDATA)>
<!ELEMENT subjects (subject+)>
<!ELEMENT subject (subjectName,score)>
<!ELEMENT subjectName(#PCDATA)>
<!ELEMENT score(#PCDATA)>
]>

Filed in: - MS CS/IT, Study Stuff
0
Tourism Database using Servlet, JSP, JDBC and XML

Tourism Database using Servlet, JSP, JDBC and XML

Question-5:

Using Servlet, JSP, JDBC and XML, create a web application for a tourist company to provide online help in the searching for tourist places across the country, and other details like cost, and how to reach these places.


Here I use one simple xml file(touristplace.xml) and one servlet (Touristplaces.java)to store and show respected all tourist places and two servlets to show transportation type and transportation cost whenever the user selects the starting place and destination place in the home page(tourist.jsp)

.
Mysql Code


CODE

CREATE DATABASE Tourist;


CODE

CREATE TABLE Transport

(
id int NOT NULL AUTO_INCREMENT,
transport_type VARCHAR(30),
transport_start VARCHAR(30),
transport_dest VARCHAR(30),
PRIMARY KEY(ID)
);


CODE

CREATE TABLE Transport_cost

(
id int NOT NULL AUTO_INCREMENT,
transport_start VARCHAR(30),
transport_dest VARCHAR(30),
transport_bus VARCHAR(10),
transport_air VARCHAR(10),
transport_train VARCHAR(10),
PRIMARY KEY(ID),
FOREIGN KEY(transport_start,transport_dest) REFERENCES Transport (transport_start,transport_dest)
);

Home page->>tourist.jsp


CODE

<html>
<head>
<title>Welcome to Shuvyaatra</title>
</head>
<body>
<table cellpadding=”5″ border=”0″ width=”756″>
<TR><td>
<h3 ALIGN=”CENTER”>Welcome to ShuvYaatra</h3></TD></TR>
<tr>
<td>
<p>
<br><br><a href=”/ignoumca/servlet/ignou.mca.Touristplaces”>Show places</a><br><br>
</td></TR>
<form name=”regis” method=”get” action=”/ignoumca/servlet/ignou.mca.Transport_type”  >
<table cellpadding=”5″ border=”0″>
<tr>
<td align=”right”><p>Transport type:</td>
<td >
<select name=”start_place”>
<option value=”none”>Please select Starting place
<option value=”Delhi”>Delhi
<option value=”Guwahati”>Guwahati
</td>
<td>
<select name=”dest_place”>
<option value=”none”>Please select Destination place
<option value=”Delhi”>Delhi
<option value=”Guwahati”>Guwahati
</td>
</tr>
<tr><table align=”center”><tr><td>
<input type=”Submit” value=”Submit”></p>
</form></td></tr></table></tr>
<form name=”regis1″ method=”get” action=”/ignoumca/servlet/ignou.mca.Transport_cost”  >
<table cellpadding=”5″ border=”0″>
<tr>
<td align=”right”><p>Transport cost:</td>
<td>
<select name=”starting_place”>
<option value=”none”>Please select Starting place
<option value=”Delhi”>Delhi
<option value=”Guwahati”>Guwahati
</td>
<td>
<select name=”destination_place”>
<option value=”none”>Please select Destination place
<option value=”Delhi”>Delhi
<option value=”Guwahati”>Guwahati
</td>
</tr>
<tr><table align=”center”><tr><td>
<input type=”Submit” value=”Submit”></p>
</form></td></tr></table></tr>
</table>
</body>
</html>


touristplace.xml

CODE

<?xml version=”1.0″ encoding=”UTF-8″?>
<touristplace>
<zone>
<north>
<place>
<name></name>
<details></details>
</place>
</north>
<east>
<place>
<name></name>
<details></details>
</place>
</east>
<south>
<place>
<name></name>
<details></details>
</place>
</south>
<west>
<place>
<name></name>
<details></details>
</place>
</west>
</zone>
</touristplace>


Touristplaces.java

CODE

package.ignou.mca;
import java.io.*;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;

public class Touristplaces extends HttpServlet{

public void doGet(HttpServletRequest req,HttpServletResponse res)
throws IOException,ServletException{
response.setContentType(“text/xml”);
File file=new File(“/ignoumca/WEB-INF/touristplace.xml”);
FileInputStream in=new FileInputStream(file);
PrintWriter out=res.getWriter();
int i;
while((i=in.read())!=-1)
out.write(i);
in.close();
}
}


Transport_type.java

CODE

package.ignou.mca;
import java.io.*;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.net.*;

public class Transport_type extends HttpServlet{

private ServletConfig config;

public void init(ServletConfig config)
throws ServletException{ this.config=config;}
public void service (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException

{


HttpSession session = req.getSession(true);
res.setContentType(“text/html”);
PrintWriter out = res.getWriter();
String start_place=req.getParameter(“start_place”);
String dest_place=req.getParameter(“dest_place”);
out.println(“<HTML><HEAD><TITLE>Transport facility</TITLE>”);
out.println(“</HEAD>”);
out.println(“<BODY bgColor=#FFFFCC text=#008000 topMargin=0>”);
out.println(“<P align=center><FONT face=Helvetica><FONT color=fuchsia style=\”BACKGROUND-COLOR: white\”><BIG><BIG>Type of tranport facility</BIG></BIG></FONT></P>”);
out.println(“<P align=center>”);
out.println(“<TABLE align=center border=0 cellPadding=5 cellSpacing=7 width=\”100%\”>”);

out.println(“<TR>”);
out.println(“<TD bgcolor=#b0c0cf><p style=\”font-size:15px\”>Transport facility</TD>”);
out.println(“</TR>”);
Connection theConnection=null;
Statement theStatement = null;
try{
Class.forName(“org.gjt.mm.mysql.Driver”);
String dbURL=”jdbc:mysql://localhost/Tourist”;
String username=”root”;
String password=”";

theConnection=DriverManager.getConnection(dbURL,username,password);
theStatement=theConnection.createStatement();
ResultSet theResult=theStatement.executeQuery(“select transport_type from Transport

where transport_start=’”+start_place+”‘ AND transport_dest=’”+dest_place+”‘”);
while(theResult.next())
{
out.println();
out.println(“<TR>”);
out.println(“<TD><p style=\”font-size:15px\”>Transport facility of your

places->>” + theResult.getString(“tranport_type”) + “</TD>”);
out.println(“</TR>”);
}

theResult.close();

theStatement.close();

theConnection.close();

}catch(Exception e){out.println(e.getMessage());}

out.println(“</TABLE></P>”);
out.println(“<P>&nbsp;</P></FONT></BODY></HTML>”);
}
public void destroy(){}

}


Transport_cost.java

CODE

package.ignou.mca;
import java.io.*;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.net.*;
public class Transport_cost extends HttpServlet{
private ServletConfig config;
public void init(ServletConfig config)
throws ServletException{ this.config=config;}

public void service (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException

{

HttpSession session = req.getSession(true);
res.setContentType(“text/html”);
PrintWriter out = res.getWriter();
String start_place=req.getParameter(“starting_place”);
String dest_place=req.getParameter(“destination_place”);

out.println(“<HTML><HEAD><TITLE>Transport facility</TITLE>”);
out.println(“</HEAD>”);
out.println(“<BODY bgColor=#FFFFCC text=#008000 topMargin=0>”);
out.println(“<P align=center><FONT face=Helvetica><FONT color=fuchsia style=\”BACKGROUND-COLOR: white\”><BIG><BIG>Tranport Cost</BIG></BIG></FONT></P>”);
out.println(“<P align=center>”);
out.println(“<TABLE align=center border=0 cellPadding=5 cellSpacing=7 width=\”100%\”>”);
out.println(“<TR>”);
out.println(“<TD bgcolor=#b0c0cf><p style=\”font-size:15px\”>Transport cost</TD>”);
out.println(“</TR>”);
Connection theConnection=null;
Statement theStatement = null;
try{

Class.forName(“org.gjt.mm.mysql.Driver”);

String dbURL=”jdbc:mysql://localhost/Tourist”;

String username=”root”;
String password=”";
theConnection=DriverManager.getConnection(dbURL,username,password);
theStatement=theConnection.createStatement();
ResultSet theResult=theStatement.executeQuery(“select transport_bus,transport_air,transport_train from Transport_cost where transport_start=’”+start_place+”‘ AND transport_dest=’”+dest_place+”‘”);
while(theResult.next())
{

out.println();
out.println(“<TR>”);
out.println(“<TD><p style=\”font-size:15px\”>Bus Fair=” + theResult.getString(“tranport_bus”) + “</TD>”);
out.println(“<TD><p style=\”font-size:15px\”>Air Fair=” + theResult.getString(“tranport_air”) + “</TD>”);
out.println(“<TD><p style=\”font-size:15px\”>Train Fair=” + theResult.getString(“tranport_train”) + “</TD>”);
out.println(“</TR>”);

}
theResult.close();
theStatement.close();
theConnection.close();
}catch(Exception e){ out.println(e.getMessage());}
out.println(“</TABLE></P>”);
out.println(“<P>&nbsp;</P></FONT></BODY></HTML>”);

}
public void destroy(){}
}

Filed in: - MS CS/IT, Study Stuff
0
Developing a Database in JSP & JDBC

Developing a Database in JSP & JDBC

Question-4

Build a database of students those are enrolled at your Institute and working in a BPO company, then develop a program using JSP and JDBC to show their names, addresses and the names of the companies where they are working presently.

This problem is very simple as we need only two tables to be created regarding Student and BPO to show the only BPO working students. The presentation and processing logic will be handled by a JSP page as given below.

DATABASE

Database name:BPO

CREATE TABLE Student

(
StudentID VARCHAR(10)NOT NULL ,
Student_name VARCHAR(30),
Student_enrol VARCHAR(9),
Student_address VARCHAR(70),
Student_course VARCHAR(10),
CentreID VARCHAR(4),
PRIMARY KEY(StudentID)
);

CREATE TABLE BPO_company

(
BPOID INT NOT NULL AUTO_INCREMENT,
BPO_name VARCHAR(30),
BPO_address VARCHAR(70),
StudentID VARCHAR(10),
PRIMARY KEY(BPOID),
FOREIGN KEY(StudentID) REFERENCES Student (StudentID)
);

JSP page for displaying BPO working students.
<!doctype html public “-//W3C//DTD HTML 4.0 Transitional//EN”>
<html>
<head>
<title>BPO Working student</title>
</head>
<body bgcolor=#ffccdd text=#111ccc>
<h3>Information of student who are currently working in BPO Company</h3>
<table cellspacing=”5″ cellpadding=”5″ border=”1″ align=”center”width=”70%”>
<tr>
<td align=”right”>Name:</td>
<td align=”right”>Address:</td>
<td align=”right”>BPO Company:</td>
</tr>
<%@page language=”java”%>
<%@page import=”java.sql.*”%>
<%
Connection con = null;
Statement stm = null;
try

{
Class.forName(“org.gjt.mm.mysql.Driver”);
String dbURL=”jdbc:mysql://localhost/BPO”;
String username=”root”;
String password=”";
con=DriverManager.getConnection(dbURL,username,password);
stm=con.createStatement();
ResultSet rs=stm.executeQuery(“SELECT Student.Student_name,Student.Student_address,BPO_company.BPO_name FROM Student,BPO_company WHERE Student.StudentID=BPO_company.StudentID”);
while(rs.next()){%>
<TR>
<TD><%out.println(rs.getString(“Student_name”));%></TD>
<TD><%out.println(rs.getString(“Student_address”));%></TD>
<TD><%out.println(rs.getString(“BPO_name”));%></TD>
</TR>
<%}%>
<%
rs.close();
stm.close();
con.close();

}catch(Exception e){e.printStackTrace();}%>

</table>
</body>
</html>

Filed in: - MS CS/IT, Study Stuff
9
Writing a program using Servlet and JDBC

Writing a program using Servlet and JDBC

Question-3:

You Write a program using Servlet and JDBC that takes a name, telephone number and an id number issued by the telephone company and provides online detailed information regarding the monthly bill a customer has to pay. Moreover, make your own assumptions.

I’ve developed this application using servlet and JDBC. Here I use two servlets, one servlet is used for provide a form and perform authentication and another servlet is used to show their monthly bill from data access layer.


Here I create a database named as telephone and two tables as Customer and Bill

CREATE TABLE Customer

(

Customer_ID INT NOT NULL AUTO_INCREMENT,
Customer_name VARCHAR(30),
Customer_address VARCHAR(70),
Customer_phone_no VARCHAR(12),
PRIMARY KEY(Customer_ID)

);

CREATE TABLE Bill

(

Bill_ID INT NOT NULL AUTO_INCREMENT,
Customer_ID VARCHAR(30) ,
Bill_date DATETIME NOT NULL,
Bill_amount VARCHAR(5),
Bill_due_date DATETIME NOT NULL,
Bill_after_due_date VARCHAR(5),
PRIMARY KEY(Bill_ID) ,
FOREIGN KEY(Customer_ID) REFERENCES Customer (Customer_ID)

);
form related servlet

QUOTE

package telephone;
import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.URL;

public class Telephone extends HttpServlet

{
public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException

{
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
out.println(“<HTML>”);
out.println(“<HEAD>”);
out.println(“<TITLE>User Login</TITLE>”);
out.println(“</HEAD>”);
out.println(“<BODY>”);
out.println(“<h3 align=center>Please enter the following data</h3>”);
out.println(“<TABLE align=center border=1 cellPadding=2 cellSpacing=3 width=”40%”>”);
out.println(“<FORM METHOD=POST”);
out.println(“<tr><td align=right>Name: <INPUT TYPE=TEXT NAME=name></tr></td>”);
out.println(“<tr><td align=right>Telephone number: <INPUT TYPE=TEXT NAME=phone></tr></td>”);
out.println(“<tr><td align=right>ID: <INPUT TYPE=TEXT NAME=id></tr></td>”);
out.println(“<tr><td align=right><INPUT TYPE=SUBMIT VALUE=Submit></td></tr > </TABLE>”);
out.println(“</FORM>”);
out.println(“</BODY>”);
out.println(“</HTML>”);
}

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException

{
PrintWriter out = res.getWriter();

String name = “”;
String id = “”;
String phone=”";
name = req.getParameter(“name”);
phone = req.getParameter(“phone”);
id=req.getParameter(“id”);
boolean result = check_details(name, phone,id);

if (result)

{

res.sendRedirect(“/examples/servlet/telephone.Billshow?id=”+id+”");

}
else

{

out.println(“<HTML>”);
out.println(“<HEAD>”);
out.println(“<TITLE> Login Fail</TITLE>”);
out.println(“</HEAD>”);
out.println(“<BODY>”);
out.println(“<h3 align=center>Please  login again</h3>”);
out.println(“<a href=/examples/servlet/telephone.Telephone>Return to login page</a>”);
out.println(“</BODY>”);
out.println(“</HTML>”);

}
}

public boolean check_details(String name, String phone,String id)

{

Connection con = null;
Statement stm = null;
boolean result = false;
try

{

Class.forName(“org.gjt.mm.mysql.Driver”);
String dbURL=”jdbc:mysql://localhost/telephone”;
String username1=”root”;

String password1=”";

con=DriverManager.getConnection(dbURL,username1,password1);

stm = con.createStatement();

String query = “SELECT * FROM Customer WHERE Customer_ID = ‘” + id + “‘ AND Customer_name = ‘” + name + “‘ AND Customer_phone_no = ‘” + phone + “‘”;

ResultSet rs =stm.executeQuery(query);
while(rs.next())

{

result = true;

}

}catch(Exception e){  System.out.println(e.getMessage()); result=false;}

return result;

}
}

Bill display servlet

QUOTE

package telephone;
import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.URL;
public class Billshow extends HttpServlet

{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException

{

res.setContentType(“text/html”);
PrintWriter out = res.getWriter();
String id = req.getParameter(“id”);
out.println(“<HTML><HEAD><TITLE>Telephone bill:::</TITLE>”);
out.println(“</HEAD>”);
out.println(“<BODY >”);
out.println(“<P align=center>Telephone Bill.</P>”);
out.println(“<TABLE align=center border=1  width=”65%”>”);
Connection con=null;
Statement stm = null;
try

{

Class.forName(“org.gjt.mm.mysql.Driver”);
String dbURL=”jdbc:mysql://localhost/telephone”;
String username=”root”;
String password=”";

con=DriverManager.getConnection(dbURL,username,password);

stm=con.createStatement();

ResultSet rs=stm.executeQuery(“SELECT Bill_date,Bill_amount,Bill_due_date,

Bill_after_due_date,Customer_name,Customer_address,Customer_phone_no FROM

Bill,Customer WHERE Customer.Customer_id =Bill.Customer_id AND Customer.Customer_id=”+id+”");
while(rs.next()) //retreive all the records into the table
{
out.println(“<TR>”);
out.println(“<TD>Name</TD><TD>” + rs.getString(“Customer_name”) +

“</TD></TR>”);
out.println(“<TR><TD>Address</TD><TD>” +

rs.getString(“Customer_address”) + “</TD></TR>”);
out.println(“<TR><TD>Telephone Number</TD><TD>” +

rs.getString(“Customer_phone_no”) + “</TD></TR>”);
out.println(“<TR><TD>Bill Date</TD><TD>” + rs.getString(“Bill_date”) +

“</TD></TR>”);
out.println(“<TR><TD>Bill Amount</TD><TD>” + rs.getString(“Bill_amount”)

+”</TD></TR>”);

out.println(“<TR><TD>Bill Due-date</TD><TD>” +

rs.getString(“Bill_due_date”) + “</TD>”);
out.println(“<TR><TD>Bill after Due-date</TD><TD>” +

rs.getString(“Bill_after_due_date”) + “</TD>”);
out.println(“</TR>”);
rs.close();
stm.close();
con.close();

}

}catch(Exception e){out.println(e.getMessage());}

out.println(“<a href=/examples/servlet/telephone.Telephone><h6 align=center>Return to

login page</h6></a>”);

out.println(“<P>&nbsp;</P></FONT></BODY></HTML>”);

}

}

Assumptions:-

The above application can’t be regarded as suitable for maintenance as far as presentation and processing logic is concerned. Its really hard to maintain such application for developer, so only servlet is not suitable for holding both presentation and processing logic. It’s better to use servlet as only presentation and ejb or java bean as processing. This can give better scalability and flexibility.

Filed in: - MS CS/IT, Study Stuff
0
How to Create a student-enquiry-system using EJB

How to Create a student-enquiry-system using EJB

Question-2:


Create a student enquiry system using EJB through which a student could enquire about the Program / Courses on offer by the different Schools of Studies of a particular University.

A sample ejb application for student enquiry system

Course Remote Interface

CODE

import javax.ejb.*;
import java.rmi.RemoteException;
public interface Course extends EJBObject

{
public String getCourseSchool() throws RemoteException;
public void setCourseSchool(String courseschool) throws RemoteException;
public String getCourseName() throws RemoteException;
public void setCourseName(String coursename) throws RemoteException;
public String getCourseDuration() throws RemoteException;
public void setCourseDuration(String courseduration) throws RemoteException;
public String getCourseType() throws RemoteException;
public void setCourseType(String coursetype) throws RemoteException;
public String getCourseCost() throws RemoteException;
public void setCourseCost(String coursecost) throws RemoteException;

}

Course Home Interface

CODE

import javax.ejb.*;
import java.rmi.RemoteException;
public interface CourseHome extends EJBHome
{

public Course create(String courseSchool) throws RemoteException,CreateException;
public Course findByPrimaryKey(String courseSchool) throws RemoteException,FinderException;

}

Course Entity Bean

CODE

import javax.ejb.*;
import java.rmi.RemoteException;
import java.sql.*;

public interface CourseBean extends EntityBean

{

transient private EntityContext ejbContext;
public String courseSchool;
public String courseName;
public String courseDuration;
public String courseType;
public String courseCost;

public String getCourseSchool()
{

return courseSchool;
}
public void setCourseSchool(String school)
{

courseSchool=school;
}
public String getCourseName()
{

return courseName;
}
public void setCourseName(String name)
{

courseName=name;
}
public String getCourseDuration()
{

return courseDuration;
}
public void setCourseDuration(String duration)
{

courseDuration=duration;
}
public String getCourseType()
{

return courseType;
}
public void setCourseType(String type)
{

courseType=type;
}
public String getCourseCost()
{

return courseCost;
}
public void setCourseCost(String cost)
{

courseCost=cost;
}
public Course ejbCreate(String school)
{

courseSchool=school;

return null;
}
public void ejbPostCreate(String school)
{}
public void setEntityContext(EntityContext ctx)
{

ejbContext=ctx;
}
public void unsetEntityContext()
{

ejbContext=null;
}
public void ejbActivate(){}
public void ejbPassivate(){}
public void ejbLoad()
{

Connection con;

try

{

String primaryKey=(String)ejbContext.getPrimaryKey();

con=this.getConnection();

Statement stm=con.createStatement(SELECT * FROM Course WHERE

courseSchool=”+primaryKey);

ResultSet rst=stm.executeQuery();

if(rst.next())

{

courseSchool=rst.getString(“CourseSchool”);

courseName=rst.getString(“CourseName”);

courseDuration=rst.getString(“CourseDuration”);

courseType=rst.getString(“CourseType”);

courseCost=rst.getString(“CourseCost”);

}

}
catch(SQLException sqle)
{

throw new EJBException(sqle);
}
finally
{

if(connection !=null)

con.close();
}

}

Filed in: - MS CS/IT, Study Stuff
1
© 2009 InfoFanz.com. All rights reserved.