Sunday, 31 March 2013
Thursday, 28 March 2013
Tuesday, 26 March 2013
Define the term line clipping. The parametric equation of line PQ may be defined as P + t (Q-P) where 0 ≤ t ≤ 1. Explain this equation with the help of an example. Derive the expression for t with respect to ith edge and PQ (line to be clipped) in the context of Cyber Beck line clipping algorithm. How will you determine whether a point is PE or PL in Cyrus Beck line clipping algorithm.
Define the term line clipping. The parametric equation of line PQ may be defined as P + t (Q-P) where 0 ≤ t ≤ 1. Explain this equation with the help of an example. Derive the expression for t with respect to ith edge and PQ (line to be clipped) in the context of Cyber Beck line clipping algorithm. How will you determine whether a point is PE or PL in Cyrus Beck line clipping algorithm.
Wednesday, 20 March 2013
MDB (Message Driven Bean) for news agency
Write a MDB (Message Driven Bean) for news agency that has to
capture the data from various news sources. The newly written MDB
should accept the XML format of the news. The XML data needs to be
parsed and stored in the database. The news format is as follows:
<news_id> </ news_id>
<sources> </source>
<date> </date>
<type_of_news> </type_of_news>
<priority> <priority>
<news_content> </news_content>
import java.util.Date;
import java.util.DateFormat;
import java.util.SimpleDateFormat;
import javax.jms.*;
import org.w3c.dom.Document;
import java.sql.*;
private class News{
private int id;
public int priority;
public date;
public String sources="",type_of_news,news_content;
public News(int id){
this.id=id;
}
public int getID(){
return id;
}
}
Public class NewsMDB implements MessageDrivenBean,MessageListener {
private NewsLocal news;
private Document dom;
public void setMessageDrivenContext(MessageDrivenContext mdc) {
try {
InitialContext ictx = new InitialContext();
} catch ( Exception ex ) {
throw new EJBException("Unable to get News Agency bean", ex);
}
}
public void ejbCreate() { }
public void ejbRemove() { }
public void onMessage(Message msg) {
XMLMessage xml = (XMLMessage)msg;
try {
dom=xml.getDocument();
saveInDB(parseDocument());
} catch ( Exception ex ) {
throw new EJBException(ex);
}
}
private void saveInDB(News ns){
try{
Class.forName("");//Class required for DataBase
DriverManager.getConnection("","",""); //Database file path & Userid/password
PreparedStatement st;
st=con.createPreparedStatement("Insert into news values(?,?,?,?,?,?)");
st.setInt(1,ns.getID());
st.setString(2,ns.sources);
st.setDate(3,ns.date);
st.setString(4,ns.type_of_news);
st.setInt(5,ns.priority);
st.setString(6,ns.news_content);
st.execute();
st.close();
st=null;
con.close();
con=null;
}catch(SQLException se){
throw new EJBException("Unable to Save News Agency bean", ex);
}
}
private News parseDocument(){
Element docEle;
News news;
//get the root element
docEle = dom.getDocumentElement();
//get a nodelist of elements
int id=getIntValue(docEle,"news_id");
news=new News(id);
news.sources=getIntValue(docEle,"sources");
news.date=getDateValue(docEle,"date");
news.type_of_news=getStringValue(docEle,"type_of_news");
news.priority=getIntValue(docEle,"priority");
news.news_content=getStringValue(docEle,"news_content");
return news;
}
private String getTextValue(Element ele, String tagName) {
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if(nl != null && nl.getLength() > 0) {
Element el = (Element)nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}
return textVal;
}
private int getIntValue(Element ele, String tagName) {
return Integer.parseInt(getTextValue(ele,tagName));
}
private Date getDateValue(Element ele, String tagName) {
String startDateString = getTextValue(ele,tagName);
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date newDateString;
try {
startDate = df.parse(startDateString);
newDateString = df.format(startDate);
} catch (Exception e) {
throw new EJBException(e);
}
return newDateString;
}
}
capture the data from various news sources. The newly written MDB
should accept the XML format of the news. The XML data needs to be
parsed and stored in the database. The news format is as follows:
<news_id> </ news_id>
<sources> </source>
<date> </date>
<type_of_news> </type_of_news>
<priority> <priority>
<news_content> </news_content>
import java.util.Date;
import java.util.DateFormat;
import java.util.SimpleDateFormat;
import javax.jms.*;
import org.w3c.dom.Document;
import java.sql.*;
private class News{
private int id;
public int priority;
public date;
public String sources="",type_of_news,news_content;
public News(int id){
this.id=id;
}
public int getID(){
return id;
}
}
Public class NewsMDB implements MessageDrivenBean,MessageListener {
private NewsLocal news;
private Document dom;
public void setMessageDrivenContext(MessageDrivenContext mdc) {
try {
InitialContext ictx = new InitialContext();
} catch ( Exception ex ) {
throw new EJBException("Unable to get News Agency bean", ex);
}
}
public void ejbCreate() { }
public void ejbRemove() { }
public void onMessage(Message msg) {
XMLMessage xml = (XMLMessage)msg;
try {
dom=xml.getDocument();
saveInDB(parseDocument());
} catch ( Exception ex ) {
throw new EJBException(ex);
}
}
private void saveInDB(News ns){
try{
Class.forName("");//Class required for DataBase
DriverManager.getConnection("","",""); //Database file path & Userid/password
PreparedStatement st;
st=con.createPreparedStatement("Insert into news values(?,?,?,?,?,?)");
st.setInt(1,ns.getID());
st.setString(2,ns.sources);
st.setDate(3,ns.date);
st.setString(4,ns.type_of_news);
st.setInt(5,ns.priority);
st.setString(6,ns.news_content);
st.execute();
st.close();
st=null;
con.close();
con=null;
}catch(SQLException se){
throw new EJBException("Unable to Save News Agency bean", ex);
}
}
private News parseDocument(){
Element docEle;
News news;
//get the root element
docEle = dom.getDocumentElement();
//get a nodelist of elements
int id=getIntValue(docEle,"news_id");
news=new News(id);
news.sources=getIntValue(docEle,"sources");
news.date=getDateValue(docEle,"date");
news.type_of_news=getStringValue(docEle,"type_of_news");
news.priority=getIntValue(docEle,"priority");
news.news_content=getStringValue(docEle,"news_content");
return news;
}
private String getTextValue(Element ele, String tagName) {
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if(nl != null && nl.getLength() > 0) {
Element el = (Element)nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}
return textVal;
}
private int getIntValue(Element ele, String tagName) {
return Integer.parseInt(getTextValue(ele,tagName));
}
private Date getDateValue(Element ele, String tagName) {
String startDateString = getTextValue(ele,tagName);
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date newDateString;
try {
startDate = df.parse(startDateString);
newDateString = df.format(startDate);
} catch (Exception e) {
throw new EJBException(e);
}
return newDateString;
}
}
Tuesday, 19 March 2013
Dependency relations
Determine the dependency relations among the following instructions:
I1: a=b+c;
I2: b=a+d;
I3: e=a/f;
Then, Read Sets & Write Sets of given Instruction
For I1, R1=
{b, c} W1= {a}
For I2, R2=
{a, d} W2= {b}
For I3, R3=
{a, f} W3= {e}
For Instructions I1 & I2
R1 ^ W2 = {b} ;
Anti Dependence
R2 ^ W1 = {a} ;
Flow Dependence
W1 ^ W2 = {}
Therefore I1 & I2 are both Flow Dependent and Anti
Dependent.
For Instruction I2 & I3
R2 ^ W3 = {}
R3 ^ W2 = {}
W2 ^ W3 = {}
Therefore instructions I2 & I3 are independent of each
other, and can be run in parallel.
For Instruction I1 & I3
R1 ^ W3 = {}
R3 ^ W1 = {a} ;
Flow Dependence
W1 ^ W3 = {}
Therefore instructions I1 & I3 are Flow Dependent.
Sunday, 17 March 2013
Water Jug Problem
A
Water Jug Problem: You are given two Jugs, a 4-gallon one and a
3-gallon one. Neither have any measuring markers on it. There is a
pump that can be used to fill the jugs with water. How can you get
exactly 2 gallons of water into the 4-gallon jug?
The state space for this problem can be described as the set of ordered pairs of integers (x, y), such that x=0, 1,2,3, or 4 and y = 0,1,2, 0r 3; x represents the number of gallons of water in the 4-gallon jug, and y represents the quality of water in the 3-gallon jug. The Start State is (0,0). The goal state is (2,n) for any value of n (since the problem does not specify how many gallons need to be in the 3-gallon jug).
1 (x, y) If x < 4 -> (4,y) Fill the 4-gallon jug.
2. (x, y) If y < 3 -> (x,3) Fill the 3-gallon jug.
3 (x, y) If x >0 -> (x – d, y) Pour some water out of the 4-gallon jug
4 (x, y) If y > 0 -> (x, y - d) pour some water out of the 3-Gallon jug
5 (x, y) If x > 0 -> (0, y) Empty the 4-gallon jug on the ground
6 (x, y) If y > 0 -> (x, 0) Empty the 3-gallon jug on the ground
7 (x, y) If x + y> 4 and y > 0 -> (4,y – (4 -x)) ;pour some water from the 3-Gallon jug in to the
4 - gallon jug until the 4 -gallon jug is full.
8 (x, y) If x + y> 3 and x > 0 -> (x-(3-y),3) ;pour water from the 4 -Gallon jug in to the
3 -gallon jug until the 3 -gallon jug is full.
9. (x, y) If x + y <4 and y > 0 -> (x+y,0) ;pour all the water from the 3-Gallon jug in to the
4- gallon jug
10 (x, y) If x + y < 3 and x > 0 -> (x+y,0) ;pour all the water from the 4-Gallon jug in to the
3- gallon jug
11 (0,2) -> (2,0) ;pour all 2 gallons from the 3-Gallon jug in to the
4-Gallon jug.
12. (2,y) -> (0,y) ;Empty the 2 gallons in the 4.gallons in the 4-gallon jug on the
Ground.
Production rules for the water jug problem.
Gallons of water in the 4-gallon jug. Gallons of water in the 3-gallon jug Rule Applied
0 0 2
0 3 9
3 0 2
3 3
4 2 7
0 2 5 0r 12
2 0 9 or 11
One solution for the water jug problem.
0 0 2
4 0 1
1 3 8
1 0 6
0 1 10
4 1 1
2 3 8
2 0 6
Second solution for the water jug problem
The state space for this problem can be described as the set of ordered pairs of integers (x, y), such that x=0, 1,2,3, or 4 and y = 0,1,2, 0r 3; x represents the number of gallons of water in the 4-gallon jug, and y represents the quality of water in the 3-gallon jug. The Start State is (0,0). The goal state is (2,n) for any value of n (since the problem does not specify how many gallons need to be in the 3-gallon jug).
1 (x, y) If x < 4 -> (4,y) Fill the 4-gallon jug.
2. (x, y) If y < 3 -> (x,3) Fill the 3-gallon jug.
3 (x, y) If x >0 -> (x – d, y) Pour some water out of the 4-gallon jug
4 (x, y) If y > 0 -> (x, y - d) pour some water out of the 3-Gallon jug
5 (x, y) If x > 0 -> (0, y) Empty the 4-gallon jug on the ground
6 (x, y) If y > 0 -> (x, 0) Empty the 3-gallon jug on the ground
7 (x, y) If x + y> 4 and y > 0 -> (4,y – (4 -x)) ;pour some water from the 3-Gallon jug in to the
4 - gallon jug until the 4 -gallon jug is full.
8 (x, y) If x + y> 3 and x > 0 -> (x-(3-y),3) ;pour water from the 4 -Gallon jug in to the
3 -gallon jug until the 3 -gallon jug is full.
9. (x, y) If x + y <4 and y > 0 -> (x+y,0) ;pour all the water from the 3-Gallon jug in to the
4- gallon jug
10 (x, y) If x + y < 3 and x > 0 -> (x+y,0) ;pour all the water from the 4-Gallon jug in to the
3- gallon jug
11 (0,2) -> (2,0) ;pour all 2 gallons from the 3-Gallon jug in to the
4-Gallon jug.
12. (2,y) -> (0,y) ;Empty the 2 gallons in the 4.gallons in the 4-gallon jug on the
Ground.
Production rules for the water jug problem.
Gallons of water in the 4-gallon jug. Gallons of water in the 3-gallon jug Rule Applied
0 0 2
0 3 9
3 0 2
3 3
4 2 7
0 2 5 0r 12
2 0 9 or 11
One solution for the water jug problem.
0 0 2
4 0 1
1 3 8
1 0 6
0 1 10
4 1 1
2 3 8
2 0 6
Second solution for the water jug problem
Saturday, 16 March 2013
Sutherland Hodgman Polygon Clipping
Write C/C++ program to implement the Sutherland Hodgman polygon clipping algorithm. Using this program clip the polygon against the rectangular window. Make suitable assumptions.
#include <windows.h>
#include <gl/glut.h>
struct Point{
float x,y;
} w[4],oVer[4];
int Nout;
void drawPoly(Point p[],int n){
glBegin(GL_POLYGON);
for(int i=0;i<n;i++)
glVertex2f(p[i].x,p[i].y);
glEnd();
}
bool insideVer(Point p){
if((p.x>=w[0].x)&&(p.x<=w[2].x))
if((p.y>=w[0].y)&&(p.y<=w[2].y))
return true;
return false;
}
void addVer(Point p){
oVer[Nout]=p;
Nout=Nout+1;
}
Point getInterSect(Point s,Point p,int edge){
Point in;
float m;
if(w[edge].x==w[(edge+1)%4].x){ //Vertical Line
m=(p.y-s.y)/(p.x-s.x);
in.x=w[edge].x;
in.y=in.x*m+s.y;
}
else{//Horizontal Line
m=(p.y-s.y)/(p.x-s.x);
in.y=w[edge].y;
in.x=(in.y-s.y)/m;
}
return in;
}
void clipAndDraw(Point inVer[],int Nin){
Point s,p,interSec;
for(int i=0;i<4;i++)
{
Nout=0;
s=inVer[Nin-1];
for(int j=0;j<Nin;j++)
{
p=inVer[j];
if(insideVer(p)==true){
if(insideVer(s)==true){
addVer(p);
}
else{
interSec=getInterSect(s,p,i);
addVer(interSec);
addVer(p);
}
}
else{
if(insideVer(s)==true){
interSec=getInterSect(s,p,i);
addVer(interSec);
}
}
s=p;
}
inVer=oVer;
Nin=Nout;
}
drawPoly(oVer,4);
}
void init(){
glClearColor(0.0f,0.0f,0.0f,0.0f);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0,100.0,0.0,100.0,0.0,100.0);
glClear(GL_COLOR_BUFFER_BIT);
w[0].x =20,w[0].y=10;
w[1].x =20,w[1].y=80;
w[2].x =80,w[2].y=80;
w[3].x =80,w[3].y=10;
}
void display(void){
Point inVer[4];
init();
// As Window for Clipping
glColor3f(1.0f,0.0f,0.0f);
drawPoly(w,4);
// As Rect
glColor3f(0.0f,1.0f,0.0f);
inVer[0].x =10,inVer[0].y=40;
inVer[1].x =10,inVer[1].y=60;
inVer[2].x =60,inVer[2].y=60;
inVer[3].x =60,inVer[3].y=40;
drawPoly(inVer,4);
// As Rect
glColor3f(0.0f,0.0f,1.0f);
clipAndDraw(inVer,4);
// Print
glFlush();
}
int main(int argc,char *argv[]){
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(400,400);
glutInitWindowPosition(100,100);
glutCreateWindow("Polygon Clipping!");
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
#include <windows.h>
#include <gl/glut.h>
struct Point{
float x,y;
} w[4],oVer[4];
int Nout;
void drawPoly(Point p[],int n){
glBegin(GL_POLYGON);
for(int i=0;i<n;i++)
glVertex2f(p[i].x,p[i].y);
glEnd();
}
bool insideVer(Point p){
if((p.x>=w[0].x)&&(p.x<=w[2].x))
if((p.y>=w[0].y)&&(p.y<=w[2].y))
return true;
return false;
}
void addVer(Point p){
oVer[Nout]=p;
Nout=Nout+1;
}
Point getInterSect(Point s,Point p,int edge){
Point in;
float m;
if(w[edge].x==w[(edge+1)%4].x){ //Vertical Line
m=(p.y-s.y)/(p.x-s.x);
in.x=w[edge].x;
in.y=in.x*m+s.y;
}
else{//Horizontal Line
m=(p.y-s.y)/(p.x-s.x);
in.y=w[edge].y;
in.x=(in.y-s.y)/m;
}
return in;
}
void clipAndDraw(Point inVer[],int Nin){
Point s,p,interSec;
for(int i=0;i<4;i++)
{
Nout=0;
s=inVer[Nin-1];
for(int j=0;j<Nin;j++)
{
p=inVer[j];
if(insideVer(p)==true){
if(insideVer(s)==true){
addVer(p);
}
else{
interSec=getInterSect(s,p,i);
addVer(interSec);
addVer(p);
}
}
else{
if(insideVer(s)==true){
interSec=getInterSect(s,p,i);
addVer(interSec);
}
}
s=p;
}
inVer=oVer;
Nin=Nout;
}
drawPoly(oVer,4);
}
void init(){
glClearColor(0.0f,0.0f,0.0f,0.0f);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0,100.0,0.0,100.0,0.0,100.0);
glClear(GL_COLOR_BUFFER_BIT);
w[0].x =20,w[0].y=10;
w[1].x =20,w[1].y=80;
w[2].x =80,w[2].y=80;
w[3].x =80,w[3].y=10;
}
void display(void){
Point inVer[4];
init();
// As Window for Clipping
glColor3f(1.0f,0.0f,0.0f);
drawPoly(w,4);
// As Rect
glColor3f(0.0f,1.0f,0.0f);
inVer[0].x =10,inVer[0].y=40;
inVer[1].x =10,inVer[1].y=60;
inVer[2].x =60,inVer[2].y=60;
inVer[3].x =60,inVer[3].y=40;
drawPoly(inVer,4);
// As Rect
glColor3f(0.0f,0.0f,1.0f);
clipAndDraw(inVer,4);
glFlush();
}
int main(int argc,char *argv[]){
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(400,400);
glutInitWindowPosition(100,100);
glutCreateWindow("Polygon Clipping!");
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
Friday, 15 March 2013
3D Transformation
4: Write a program in C/C++ using OpenGL to perform a 3-Dimensional transformation, such as translation ,rotation and reflection, on a given triangle.
#include <GL/glut.h> // GLUT stuff, includes OpenGL headers as well
#include <windows.h>
#include <math.h>
// Point class to keep it a little cleaner.
class Point {
public:
float x, y, z;
void setxy(float x2, float y2, float z2) { x = x2; y = y2; z=z2; }
const Point & operator=(const Point &rPoint) {
x = rPoint.x;
y = rPoint.y;
z = rPoint.z;
return *this;
}
};
void drawTriangle(Point p1, Point p2,Point p3) {
glBegin(GL_TRIANGLES);
glVertex3f(p1.x,p1.y,p1.z);//left of window
glVertex3f(p2.x,p2.y,p2.z);
glVertex3f(p3.x,p3.y,p3.z);
glEnd();//end drawing of line loop
glFlush();
}
void myDisplay() {
Point abc[3];
glMatrixMode(GL_MODELVIEW);
glClearColor(0.0,0.0,0.0,0.0);
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
abc[0].x=1.0,abc[0].y=-0.25,abc[0].z=0.0;
abc[1].x=0.0,abc[1].y=-0.25,abc[1].z=0.0;
abc[2].x=0.0,abc[2].y=0.25,abc[2].z=0.0;
drawTriangle(abc[0],abc[1],abc[2]);
glTranslatef(0.0f,-0.6f,0.0f);
drawTriangle(abc[0],abc[1],abc[2]);
glRotatef(180.0,0.0f,0.0f,1.0f);
drawTriangle(abc[0],abc[1],abc[2]);
}
int main(int argc, char *argv[]) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(640,480);
glutInitWindowPosition(100,150);
glutCreateWindow("3D Transformation");
glutDisplayFunc(myDisplay);
glutMainLoop();
return 0;
}
#include <GL/glut.h> // GLUT stuff, includes OpenGL headers as well
#include <windows.h>
#include <math.h>
// Point class to keep it a little cleaner.
class Point {
public:
float x, y, z;
void setxy(float x2, float y2, float z2) { x = x2; y = y2; z=z2; }
const Point & operator=(const Point &rPoint) {
x = rPoint.x;
y = rPoint.y;
z = rPoint.z;
return *this;
}
};
void drawTriangle(Point p1, Point p2,Point p3) {
glBegin(GL_TRIANGLES);
glVertex3f(p1.x,p1.y,p1.z);//left of window
glVertex3f(p2.x,p2.y,p2.z);
glVertex3f(p3.x,p3.y,p3.z);
glEnd();//end drawing of line loop
glFlush();
}
void myDisplay() {
Point abc[3];
glMatrixMode(GL_MODELVIEW);
glClearColor(0.0,0.0,0.0,0.0);
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
abc[0].x=1.0,abc[0].y=-0.25,abc[0].z=0.0;
abc[1].x=0.0,abc[1].y=-0.25,abc[1].z=0.0;
abc[2].x=0.0,abc[2].y=0.25,abc[2].z=0.0;
drawTriangle(abc[0],abc[1],abc[2]);
glTranslatef(0.0f,-0.6f,0.0f);
drawTriangle(abc[0],abc[1],abc[2]);
glRotatef(180.0,0.0f,0.0f,1.0f);
drawTriangle(abc[0],abc[1],abc[2]);
}
int main(int argc, char *argv[]) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(640,480);
glutInitWindowPosition(100,150);
glutCreateWindow("3D Transformation");
glutDisplayFunc(myDisplay);
glutMainLoop();
return 0;
}
Thursday, 14 March 2013
Bezier curve using OpenGL
Write a C/C++ program to draw a Bezier curve having the control points as p0 (0, 0), P1 (2, 5), P2 (5, 9), P3 (10, 20). Calculate the coordinates of the points on the curve corresponding to the parameter u = 0.2, 0.4, 0.6.
#include <windows.h>
#include <GL/glut.h>
#include <math.h>
// Point class to keep it a little cleaner.
class Point {
public:
float x, y;
void setxy(float x2, float y2) { x = x2; y = y2; }
const Point & operator=(const Point &rPoint) {
x = rPoint.x;
y = rPoint.y;
return *this;
}
};
Point abc[4];
void myInit() {
glClearColor(0.0,0.0,0.0,0.0);
glColor3f(1.0,0.0,0.0);
glPointSize(8.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,64.0,0.0,48.0);
}
void drawDot(int x, int y) {
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
glFlush();
}
void drawLine(Point p1, Point p2) {
glBegin(GL_LINES);
glVertex2f(p1.x, p1.y);
glVertex2f(p2.x, p2.y);
glEnd();
glFlush();
}
// Calculate the next bezier point.
Point drawBezier(Point A, Point B, Point C, Point D, double t) {
Point P;
P.x = pow((1 - t), 3) * A.x + 3 * t * pow((1 -t), 2) * B.x + 3 * (1-t) * pow(t, 2)* C.x + pow (t, 3)* D.x;
P.y = pow((1 - t), 3) * A.y + 3 * t * pow((1 -t), 2) * B.y + 3 * (1-t) * pow(t, 2)* C.y + pow (t, 3)* D.y;
return P;
}
void myDisplay() {
glClear(GL_COLOR_BUFFER_BIT);
Point POld=abc[0];
abc[0].x=0,abc[0].y=0;
abc[1].x=2,abc[1].y=5;
abc[2].x=5,abc[2].y=9;
abc[3].x=10,abc[3].y=20;
glColor3f(1.0,0.0,0.0);
for(int i=0;i<4;i++)
drawDot(abc[i].x, abc[i].y);
glColor3f(1.0,1.0,1.0);
drawLine(abc[0], abc[1]);
drawLine(abc[1], abc[2]);
drawLine(abc[2], abc[3]);
for(double t = 0.0;t <= 1.0; t += 0.1) {
Point P = drawBezier(abc[0], abc[1], abc[2], abc[3], t);
drawLine(POld, P);
POld = P;
}
glFlush();
}
int main(int argc, char *argv[]) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(640,480);
glutInitWindowPosition(100,150);
glutCreateWindow("Bezier Curve");
glutDisplayFunc(myDisplay);
myInit();
glutMainLoop();
return 0;
}
#include <windows.h>
#include <GL/glut.h>
#include <math.h>
// Point class to keep it a little cleaner.
class Point {
public:
float x, y;
void setxy(float x2, float y2) { x = x2; y = y2; }
const Point & operator=(const Point &rPoint) {
x = rPoint.x;
y = rPoint.y;
return *this;
}
};
Point abc[4];
void myInit() {
glClearColor(0.0,0.0,0.0,0.0);
glColor3f(1.0,0.0,0.0);
glPointSize(8.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,64.0,0.0,48.0);
}
void drawDot(int x, int y) {
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
glFlush();
}
void drawLine(Point p1, Point p2) {
glBegin(GL_LINES);
glVertex2f(p1.x, p1.y);
glVertex2f(p2.x, p2.y);
glEnd();
glFlush();
}
// Calculate the next bezier point.
Point drawBezier(Point A, Point B, Point C, Point D, double t) {
Point P;
P.x = pow((1 - t), 3) * A.x + 3 * t * pow((1 -t), 2) * B.x + 3 * (1-t) * pow(t, 2)* C.x + pow (t, 3)* D.x;
P.y = pow((1 - t), 3) * A.y + 3 * t * pow((1 -t), 2) * B.y + 3 * (1-t) * pow(t, 2)* C.y + pow (t, 3)* D.y;
return P;
}
void myDisplay() {
glClear(GL_COLOR_BUFFER_BIT);
Point POld=abc[0];
abc[0].x=0,abc[0].y=0;
abc[1].x=2,abc[1].y=5;
abc[2].x=5,abc[2].y=9;
abc[3].x=10,abc[3].y=20;
glColor3f(1.0,0.0,0.0);
for(int i=0;i<4;i++)
drawDot(abc[i].x, abc[i].y);
glColor3f(1.0,1.0,1.0);
drawLine(abc[0], abc[1]);
drawLine(abc[1], abc[2]);
drawLine(abc[2], abc[3]);
for(double t = 0.0;t <= 1.0; t += 0.1) {
Point P = drawBezier(abc[0], abc[1], abc[2], abc[3], t);
drawLine(POld, P);
POld = P;
}
glFlush();
}
int main(int argc, char *argv[]) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(640,480);
glutInitWindowPosition(100,150);
glutCreateWindow("Bezier Curve");
glutDisplayFunc(myDisplay);
myInit();
glutMainLoop();
return 0;
}
Wednesday, 13 March 2013
DDA Algorithm using OpenGL
Write a C/C++ program (USING OpenGL) to implement DDA algorithm for line generation. Use this algorithm to draw a line with endpoints (2, 3) and (9, 8).
#include <windows.h>
#include <gl/glut.h>
#include <math.h>
#include <stdio.h>
const float PI=3.14;
void drawLine(int x0,int y0,int x1,int y1){
glBegin(GL_POINTS);
glColor3f(1.0,1.0,1.0);
double m=(double)(y1-y0)/(x1-x0);
double y=(double)y0;
double x=(double)x0;
if(m<1) {
while(x<=x1) {
glVertex2d(x,floor(y));
printf("%f %f\n",floor(y),x);
y=y+m;
x++;
}
}
else {
double m1=1/m;
while(y<=y1) {
glVertex2d(floor(x),y);
y++;
x=x+m1;
}
}
glEnd();
}
void init(void){
glClearColor(0.0,0.0,0.0,0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0,100.0,0.0,100,0.0,100.0);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
drawLine(2,3,9,8);
glutSwapBuffers();
}
int main(int argc, char** argv){
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutInitWindowSize(100,100);
glutInitWindowPosition(50,50);
glutCreateWindow("DDA Line Drawing!");
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
#include <windows.h>
#include <gl/glut.h>
#include <math.h>
#include <stdio.h>
const float PI=3.14;
void drawLine(int x0,int y0,int x1,int y1){
glBegin(GL_POINTS);
glColor3f(1.0,1.0,1.0);
double m=(double)(y1-y0)/(x1-x0);
double y=(double)y0;
double x=(double)x0;
if(m<1) {
while(x<=x1) {
glVertex2d(x,floor(y));
printf("%f %f\n",floor(y),x);
y=y+m;
x++;
}
}
else {
double m1=1/m;
while(y<=y1) {
glVertex2d(floor(x),y);
y++;
x=x+m1;
}
}
glEnd();
}
void init(void){
glClearColor(0.0,0.0,0.0,0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0,100.0,0.0,100,0.0,100.0);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
drawLine(2,3,9,8);
glutSwapBuffers();
}
int main(int argc, char** argv){
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutInitWindowSize(100,100);
glutInitWindowPosition(50,50);
glutCreateWindow("DDA Line Drawing!");
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
Using OpenGL
Write a program in C/C++ using OpenGL to draw a circle of red color
inside of a rectangle of blue color on a background of green colors.
#include <windows.h>
#include <gl/glut.h>
#include <math.h>
const float PI=3.14;
void drawCircle(){
glBegin(GL_LINE_LOOP);
glColor3f(1.0,0.0,0.0);
for(int i =0; i <= 300; i++){
double angle = 2 * PI * i / 300;
double x = 5*cos(angle);
double y = 5*sin(angle);
glVertex2d(x,y);
}
glEnd();
}
void drawRect(){
glColor3f(0.0,0.0,1.0);
glRectf(-5.0,5.0,5.0,-5.0);
}
void init(void){
glClearColor(0.0,1.0,0.0,0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-10.0,10.0,-10.0,10.0,-10.0,10.0);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
drawRect();
drawCircle();
glutSwapBuffers();
}
int main(int argc, char** argv){
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutInitWindowSize(320,320);
glutInitWindowPosition(50,50);
glutCreateWindow("2D Shapes");
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
inside of a rectangle of blue color on a background of green colors.
#include <windows.h>
#include <gl/glut.h>
#include <math.h>
const float PI=3.14;
void drawCircle(){
glBegin(GL_LINE_LOOP);
glColor3f(1.0,0.0,0.0);
for(int i =0; i <= 300; i++){
double angle = 2 * PI * i / 300;
double x = 5*cos(angle);
double y = 5*sin(angle);
glVertex2d(x,y);
}
glEnd();
}
void drawRect(){
glColor3f(0.0,0.0,1.0);
glRectf(-5.0,5.0,5.0,-5.0);
}
void init(void){
glClearColor(0.0,1.0,0.0,0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-10.0,10.0,-10.0,10.0,-10.0,10.0);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
drawRect();
drawCircle();
glutSwapBuffers();
}
int main(int argc, char** argv){
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutInitWindowSize(320,320);
glutInitWindowPosition(50,50);
glutCreateWindow("2D Shapes");
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
Assembly Code to Concatenate two Strings
Assembly Code to Concatenate two Strings
DATA SEGMENT
STR1 DB "HELLO$"
STR2 DB " INDIA$"
STR DB ?
TMP DW ?
DATA ENDS
CODE SEGMENT
ASSUME CS:CODE, DS:DATA
;SET LOOP COUNTER
MOV CX, 5
;ADDRESS OF STR1
LEA BX, STR1
;ADDRESS OF STR
LEA AX, STR
AGAIN1:
;PICK CHARACTER FROM BX(STR1)
MOV DL, [BX]
;LOAD ADDRESS STR
XCHG BX, AX
;LOAD CHARACTER AT BX(STR)
MOV [BX], DL
;LOAD ADDRESS STR1
XCHG AX, BX
;INCREMENT STR1 ADDRESS
INC BX
;INCREMENT STR ADDRESS
INC AX
LOOP AGAIN1
;ADDRESS OF STR1
LEA BX, STR2
MOV CX, 6
AGAIN2:
;PICK CHARACTER FROM BX(STR21)
MOV DL, [BX]
;LOAD ADDRESS STR
XCHG BX, AX
;LOAD CHARACTER AT BX(STR)
MOV [BX], DL
;LOAD ADDRESS STR2
XCHG AX, BX
;INCREMENT STR2 ADDRESS
INC BX
;INCREMENT STR ADDRESS
INC AX
LOOP AGAIN2
;LOAD ADDRESS OF STR
XCHG BX, AX
;END STR
MOV [BX], "!"
INC BX
MOV [BX], "$"
;PRINT STR
MOV DX, OFFSET STR
MOV AH, 09H
INT 21H
CODE ENDS
DATA SEGMENT
STR1 DB "HELLO$"
STR2 DB " INDIA$"
STR DB ?
TMP DW ?
DATA ENDS
CODE SEGMENT
ASSUME CS:CODE, DS:DATA
;SET LOOP COUNTER
MOV CX, 5
;ADDRESS OF STR1
LEA BX, STR1
;ADDRESS OF STR
LEA AX, STR
AGAIN1:
;PICK CHARACTER FROM BX(STR1)
MOV DL, [BX]
;LOAD ADDRESS STR
XCHG BX, AX
;LOAD CHARACTER AT BX(STR)
MOV [BX], DL
;LOAD ADDRESS STR1
XCHG AX, BX
;INCREMENT STR1 ADDRESS
INC BX
;INCREMENT STR ADDRESS
INC AX
LOOP AGAIN1
;ADDRESS OF STR1
LEA BX, STR2
MOV CX, 6
AGAIN2:
;PICK CHARACTER FROM BX(STR21)
MOV DL, [BX]
;LOAD ADDRESS STR
XCHG BX, AX
;LOAD CHARACTER AT BX(STR)
MOV [BX], DL
;LOAD ADDRESS STR2
XCHG AX, BX
;INCREMENT STR2 ADDRESS
INC BX
;INCREMENT STR ADDRESS
INC AX
LOOP AGAIN2
;LOAD ADDRESS OF STR
XCHG BX, AX
;END STR
MOV [BX], "!"
INC BX
MOV [BX], "$"
;PRINT STR
MOV DX, OFFSET STR
MOV AH, 09H
INT 21H
CODE ENDS
Assembly Code to get BCD code
Assembly Code to get BCD code
;DATA PART
DATA SEGMENT
N DB 34H,35H,24H ; SIMILART TO "45$"
DATA ENDS
;Code Part
CODE SEGMENT
ASSUME CS: CODE, DS: DATA
;get Address of N in BX register
MOV BX, OFFSET N
;fetch first byte to AL register
MOV AL, [BX]
;Shift bits to left by 4 positions
SHL AL, 4
;Save content of AL in DL register
MOV DL, AL
;fetch second byte to AL register
MOV AL, [BX+1]
;Make left most 4 bits to 0
AND AL, 0FH
;Add first byte in DL and Second Byte in AL
; to get packed BCD Code
OR AL, DL
;to print packed BCD code move it to DL register
MOV DL, AL
;Call DOS output interrupt
MOV AH, 02H
INT 21H
CODE ENDS
;DATA PART
DATA SEGMENT
N DB 34H,35H,24H ; SIMILART TO "45$"
DATA ENDS
;Code Part
CODE SEGMENT
ASSUME CS: CODE, DS: DATA
;get Address of N in BX register
MOV BX, OFFSET N
;fetch first byte to AL register
MOV AL, [BX]
;Shift bits to left by 4 positions
SHL AL, 4
;Save content of AL in DL register
MOV DL, AL
;fetch second byte to AL register
MOV AL, [BX+1]
;Make left most 4 bits to 0
AND AL, 0FH
;Add first byte in DL and Second Byte in AL
; to get packed BCD Code
OR AL, DL
;to print packed BCD code move it to DL register
MOV DL, AL
;Call DOS output interrupt
MOV AH, 02H
INT 21H
CODE ENDS
Resize Control for change in Resolution
Resize Control for change in Resolution
Option Explicit
Public nHeight As Double
Public nWidth As Double
Dim nState As Boolean
Sub ResizeControls()
Dim ctl As Control
Dim wRatio As Double
Dim hRatio As Double
Dim fRatio As Double
On Error Resume Next
If nState = True Then Exit Sub
'Standard : 1024 * 728
If Screen.Width = 15360 And Screen.Height = 11520 Then Exit Sub
wRatio = Screen.Width / nWidth
hRatio = Screen.Height / nHeight
If UserControl.Parent.WindowState = 2 Then
For Each ctl In UserControl.Parent
ctl.Left = wRatio * ctl.Left
ctl.Top = hRatio * ctl.Top
ctl.Width = wRatio * ctl.Width
ctl.Font.Size = ctl.Font.Size * hRatio
ctl.Height = hRatio * ctl.Height
Next
End If
nState = True
End Sub
Private Sub UserControl_ReadProperties(PropBag As PropertyBag)
nHeight = UserControl.Parent.ScaleHeight
nWidth = UserControl.Parent.ScaleWidth
nState = UserControl.Parent.WindowState
End Sub
Fastest Functions to check whether a Table or Field exists in a Database (VB6)
Fastest Functions to check whether a Table or Field exists in a Database
Public Function isTableExists(con As ADODB.Connection, Table As String) As Boolean
On Error GoTo handle
Dim rs As New ADODB.Recordset
If rs.State = 1 Then rs.Close
rs.Open "Select * from " & Table, conn, adOpenStatic, adLockReadOnly
isTableExists= True
Exit Function
handle:
If Err.Number = -2147217865 Then
isTableExists = False
Else
MsgBox Err.Description
End If
End Function
Public Function isFieldExists(conn As ADODB.Connection, Table As String, field As String) As Boolean
On Error GoTo handle
Dim rs As New ADODB.Recordset
If rs.State = 1 Then rs.Close
rs.Open "Select " & field & " from " & Table, conn, adOpenStatic, adLockReadOnly
isFieldExists = True
Exit Function
handle:
If Err.Number = -2147217904 Then
isFieldExists= False
Else
MsgBox Err.Description & Err.Number
End If
End Function
Public Function isTableExists(con As ADODB.Connection, Table As String) As Boolean
On Error GoTo handle
Dim rs As New ADODB.Recordset
If rs.State = 1 Then rs.Close
rs.Open "Select * from " & Table, conn, adOpenStatic, adLockReadOnly
isTableExists= True
Exit Function
handle:
If Err.Number = -2147217865 Then
isTableExists = False
Else
MsgBox Err.Description
End If
End Function
Public Function isFieldExists(conn As ADODB.Connection, Table As String, field As String) As Boolean
On Error GoTo handle
Dim rs As New ADODB.Recordset
If rs.State = 1 Then rs.Close
rs.Open "Select " & field & " from " & Table, conn, adOpenStatic, adLockReadOnly
isFieldExists = True
Exit Function
handle:
If Err.Number = -2147217904 Then
isFieldExists= False
Else
MsgBox Err.Description & Err.Number
End If
End Function
Stack required for Evaluator (VB 6.0)
Stack required for Evaluator (VB 6.0)
Dim Stack(1000) As Variant
Dim vTop As Long
Const MaxValue = 1000
Sub push(value As Variant)
If vTop >= MaxValue Then
MsgBox "Stack OverFlow!", vbCritical, "Error!"
Exit Sub
Else
vTop = vTop + 1
Stack(vTop) = value
End If
End Sub
Sub FlushStack()
vTop = 0
End Sub
Function pop() As Variant
If vTop > 0 Then
pop = Stack(vTop)
vTop = vTop - 1
Else
MsgBox "Stack Empty!", vbCritical, "Error!"
Exit Function
End If
End Function
Function IsEmpty() As Boolean
If vTop = 0 Then
IsEmpty = True
Else
IsEmpty = False
End If
End Function
Function IsFilled() As Boolean
If vTop = MaxValue Then
IsFilled = True
Else
IsFilled = False
End If
End Function
Dim Stack(1000) As Variant
Dim vTop As Long
Const MaxValue = 1000
Sub push(value As Variant)
If vTop >= MaxValue Then
MsgBox "Stack OverFlow!", vbCritical, "Error!"
Exit Sub
Else
vTop = vTop + 1
Stack(vTop) = value
End If
End Sub
Sub FlushStack()
vTop = 0
End Sub
Function pop() As Variant
If vTop > 0 Then
pop = Stack(vTop)
vTop = vTop - 1
Else
MsgBox "Stack Empty!", vbCritical, "Error!"
Exit Function
End If
End Function
Function IsEmpty() As Boolean
If vTop = 0 Then
IsEmpty = True
Else
IsEmpty = False
End If
End Function
Function IsFilled() As Boolean
If vTop = MaxValue Then
IsFilled = True
Else
IsFilled = False
End If
End Function
Evaluator in VB6.0
Evaluator in VB6.0
Option Explicit
Dim st As New Stack
Function Evaluate(ByVal str As String) As Double
Dim word As String
Dim i As Integer
Dim A As Double
Dim B As Double
Dim C As Double
st.FlushStack
str = ChangeInPostFix(str)
i = 1
word = GetWord(str, i)
Do While word <> ""
Select Case Trim(word)
Case "*"
B = st.pop
A = st.pop
C = A * B
st.push C
Case "/"
B = st.pop
A = st.pop
C = A / B
st.push C
Case "+"
B = st.pop
A = st.pop
C = A + B
st.push C
Case "-"
B = st.pop
A = st.pop
C = A - B
st.push C
Case Trim(word)
st.push Val(word)
End Select
i = i + 1
word = GetWord(str, i)
Loop
Evaluate = st.pop
End Function
Private Function ChangeInPostFix(ByVal str As String) As String
Dim temp As String
Dim word As String
str = Trim(str)
On Error GoTo handle
If grid.Name <> "" Then str = ReplaceWithValue(str)
Dim i As Integer
i = 1
st.push "("
word = GetWord(str, i)
Do While word <> ""
Select Case Trim(word)
Case "*"
Do While HighPriority("*") = True
ChangeInPostFix = ChangeInPostFix & " " & st.pop
Loop
st.push "*"
Case "/"
Do While HighPriority("/") = True
ChangeInPostFix = ChangeInPostFix & " " & st.pop
Loop
st.push "/"
Case "+"
Do While HighPriority("+") = True
ChangeInPostFix = ChangeInPostFix & " " & st.pop
Loop
st.push "+"
Case "-"
Do While HighPriority("-") = True
ChangeInPostFix = ChangeInPostFix & " " & st.pop
Loop
st.push "-"
Case "("
st.push "("
Case ")"
temp = st.pop
Do While temp <> "("
ChangeInPostFix = ChangeInPostFix & " " & temp
temp = st.pop
Loop
Case Trim(word)
ChangeInPostFix = ChangeInPostFix & " " & Trim(word)
End Select
i = i + 1
word = GetWord(str, i)
Loop
temp = st.pop
Do While temp <> "("
ChangeInPostFix = ChangeInPostFix & " " & temp
temp = st.pop
Loop
Exit Function
handle:
If Err.Number = 91 Then
str = ""
End If
End Function
Private Function HighPriority(opt1 As String) As Boolean
Dim s As String
If st.IsEmpty = False Then
s = st.pop
If pr(s) >= pr(opt1) Then
HighPriority = True
Else
HighPriority = False
End If
Call st.push(s)
End If
End Function
Private Function pr(str As String) As Integer
Select Case str
Case "*", "/"
pr = 2
Case "+", "-"
pr = 1
Case "("
pr = 0
End Select
End Function
Function GetWord(ByVal str As String, n As Integer)
Dim word As String
Dim i As Integer
str = Trim(str)
For i = 1 To n
If InStr(1, str, " ") = 0 Then
word = str
str = ""
Else
word = Left(str, InStr(1, str, " "))
End If
If str <> "" Then str = Right(Trim(str), Len(str) - Len(word))
str = Trim(str)
Next i
GetWord = word
End Function
Private Function GetToken(ByVal str As String) As Long
Dim p1 As Integer
Dim p2 As Integer
Dim p3 As Integer
Dim p4 As Integer
Dim p5 As Integer
Dim p6 As Integer
Dim pos As Integer
p1 = InStr(1, str, "/")
p2 = InStr(1, str, "*")
p3 = InStr(1, str, "+")
p4 = InStr(1, str, "-")
p5 = InStr(1, str, "(")
p6 = InStr(1, str, ")")
pos = GetSmall(p1, p2, p3, p4, p5, p6)
GetToken = pos
End Function
Private Function GetSmall(ParamArray P()) As Long
Dim i As Integer
Dim Big As Long
Dim value As Variant
i = 0
For Each value In P
If P(i) < Big And P(i) <> 0 Then
Big = P(i)
ElseIf Big = 0 Then
Big = P(i)
End If
i = i + 1
Next
GetSmall = Big
End Function
Option Explicit
Dim st As New Stack
Function Evaluate(ByVal str As String) As Double
Dim word As String
Dim i As Integer
Dim A As Double
Dim B As Double
Dim C As Double
st.FlushStack
str = ChangeInPostFix(str)
i = 1
word = GetWord(str, i)
Do While word <> ""
Select Case Trim(word)
Case "*"
B = st.pop
A = st.pop
C = A * B
st.push C
Case "/"
B = st.pop
A = st.pop
C = A / B
st.push C
Case "+"
B = st.pop
A = st.pop
C = A + B
st.push C
Case "-"
B = st.pop
A = st.pop
C = A - B
st.push C
Case Trim(word)
st.push Val(word)
End Select
i = i + 1
word = GetWord(str, i)
Loop
Evaluate = st.pop
End Function
Private Function ChangeInPostFix(ByVal str As String) As String
Dim temp As String
Dim word As String
str = Trim(str)
On Error GoTo handle
If grid.Name <> "" Then str = ReplaceWithValue(str)
Dim i As Integer
i = 1
st.push "("
word = GetWord(str, i)
Do While word <> ""
Select Case Trim(word)
Case "*"
Do While HighPriority("*") = True
ChangeInPostFix = ChangeInPostFix & " " & st.pop
Loop
st.push "*"
Case "/"
Do While HighPriority("/") = True
ChangeInPostFix = ChangeInPostFix & " " & st.pop
Loop
st.push "/"
Case "+"
Do While HighPriority("+") = True
ChangeInPostFix = ChangeInPostFix & " " & st.pop
Loop
st.push "+"
Case "-"
Do While HighPriority("-") = True
ChangeInPostFix = ChangeInPostFix & " " & st.pop
Loop
st.push "-"
Case "("
st.push "("
Case ")"
temp = st.pop
Do While temp <> "("
ChangeInPostFix = ChangeInPostFix & " " & temp
temp = st.pop
Loop
Case Trim(word)
ChangeInPostFix = ChangeInPostFix & " " & Trim(word)
End Select
i = i + 1
word = GetWord(str, i)
Loop
temp = st.pop
Do While temp <> "("
ChangeInPostFix = ChangeInPostFix & " " & temp
temp = st.pop
Loop
Exit Function
handle:
If Err.Number = 91 Then
str = ""
End If
End Function
Private Function HighPriority(opt1 As String) As Boolean
Dim s As String
If st.IsEmpty = False Then
s = st.pop
If pr(s) >= pr(opt1) Then
HighPriority = True
Else
HighPriority = False
End If
Call st.push(s)
End If
End Function
Private Function pr(str As String) As Integer
Select Case str
Case "*", "/"
pr = 2
Case "+", "-"
pr = 1
Case "("
pr = 0
End Select
End Function
Function GetWord(ByVal str As String, n As Integer)
Dim word As String
Dim i As Integer
str = Trim(str)
For i = 1 To n
If InStr(1, str, " ") = 0 Then
word = str
str = ""
Else
word = Left(str, InStr(1, str, " "))
End If
If str <> "" Then str = Right(Trim(str), Len(str) - Len(word))
str = Trim(str)
Next i
GetWord = word
End Function
Private Function GetToken(ByVal str As String) As Long
Dim p1 As Integer
Dim p2 As Integer
Dim p3 As Integer
Dim p4 As Integer
Dim p5 As Integer
Dim p6 As Integer
Dim pos As Integer
p1 = InStr(1, str, "/")
p2 = InStr(1, str, "*")
p3 = InStr(1, str, "+")
p4 = InStr(1, str, "-")
p5 = InStr(1, str, "(")
p6 = InStr(1, str, ")")
pos = GetSmall(p1, p2, p3, p4, p5, p6)
GetToken = pos
End Function
Private Function GetSmall(ParamArray P()) As Long
Dim i As Integer
Dim Big As Long
Dim value As Variant
i = 0
For Each value In P
If P(i) < Big And P(i) <> 0 Then
Big = P(i)
ElseIf Big = 0 Then
Big = P(i)
End If
i = i + 1
Next
GetSmall = Big
End Function
E-mail Program With Visual Basic (Require Base64 encryption)
E-mail Program With Visual Basic (Require Base64 encryption)
Dim fso As New Scripting.FileSystemObject
Dim fco As New Scripting.Encoder
Dim Sdata As String, Cptr As Integer
Dim StrArray As Variant, StrElement As Variant, MsgString As String
Dim v As Boolean
Dim o As Boolean
Private Sub Command1_Click()
Winsock1.SendData "MAIL FROM:<yourID@YAHOO.in> " & vbCrLf
End Sub
Private Sub Timer1_Timer()
Me.Caption = Winsock1.State
If Winsock1.State = 9 Then Winsock1.Close
End Sub
Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Dim str As String
Call Winsock1.GetData(str)
If Left(str, 3) = "220" Then
Winsock1.SendData "EHLO YAHOO.COM " & vbCrLf
ElseIf Left(str, 4) = "250-" Then
Winsock1.SendData "AUTH LOGIN" & vbCrLf
ElseIf str = "334 VXNlcm5hbWU6" & vbCrLf Then
Winsock1.SendData "Encrypted ID" & vbCrLf
ElseIf str = "334 UGFzc3dvcmQ6" & vbCrLf Then
Winsock1.SendData "Encrypted Password" & vbCrLf
ElseIf Left(str, 3) = "235" Then
MsgBox "Authentication Succesfull!"
ElseIf Left(str, 4) = "250 " And v = False Then
Winsock1.SendData "RCPT To:<" & txtTo.Text & "> " & vbCrLf
v = True
ElseIf Left(str, 4) = "250 " Then
If o = False Then
Winsock1.SendData "DATA " & vbCrLf
MsgBox "Data Sending!"
Else
Winsock1.SendData "QUIT" & vbCrLf
MsgBox "OK Mail Sent!"
End If
ElseIf Left(str, 3) = "354" Then
Winsock1.SendData "From: ""Sender"" <yourID@yahoo.in>" & vbCrLf
Winsock1.SendData "To: ""Receiver"" <mailID@yahoo.com>" & vbCrLf
Winsock1.SendData "Date: Fri, 31 Dec 2010 16:02:43 -0500" & vbCrLf
Winsock1.SendData "Subject: " & Text2.Text & vbCrLf
Call attachment
For Each StrElement In StrArray
Winsock1.SendData (CStr(StrElement) & vbCrLf)
Next StrElement
Winsock1.SendData "." & vbCrLf
o = True
End If
End Sub
Private Sub Winsock1_Error(ByVal Number As Integer, Description As String, ByVal Scode As Long, ByVal Source As String, ByVal HelpFile As String, ByVal HelpContext As Long, CancelDisplay As Boolean)
MsgBox Number & " " & Description
End Sub
Sub attachment()
If Len(txtAttachment.Text) = 0 Then
'we don't need MIME for this
MsgString = txtEmailBodyOfMessage.Text + vbCrLf
Else
'build the 1st part of the MIME script
txtMimeCode = _
"MIME-Version: 1.0 " + vbCrLf + _
"Content-Type: multipart/mixed;" + vbCrLf + _
" boundary=" + VbQuote + "------------060502030501040302050009" + VbQuote + vbCrLf + _
vbCrLf _
+ "This is a multi-part message in MIME format." + vbCrLf + _
"--------------060502030501040302050009" + vbCrLf + _
"Content-Type: text/plain; charset=ISO-8859-1; format=flowed" + vbCrLf + _
"Content-Transfer-Encoding: 7bit" + vbCrLf + _
vbCrLf + _
txtEmailBodyOfMessage + vbCrLf + _
vbCrLf + _
"--------------060502030501040302050009" + vbCrLf
Select Case UCase(Right(txtAttachment.Text, 4))
Case ".TXT"
txtMimeCode = txtMimeCode + _
"Content-Type: text/plain;" + vbCrLf + _
"name=" + VbQuote + txtAttachment.Text + VbQuote + vbCrLf + _
"Content-Transfer-Encoding: base64" + vbCrLf + _
"Content-Disposition: attachment; filename=" + txtAttachment.Text + vbCrLf + _
vbCrLf + _
Base64Encode(RichTextBox1.Text) + vbCrLf + _
vbCrLf + _
"--------------060502030501040302050009--" + vbCrLf
Case ".DOC"
txtMimeCode = txtMimeCode + _
"Content-Type: application/msword;" + vbCrLf + _
"name=" + VbQuote + txtAttachment.Text + VbQuote + vbCrLf + _
"Content-Transfer-Encoding: base64" + vbCrLf + _
"Content-Disposition: attachment; filename=" + txtAttachment.Text + vbCrLf + _
vbCrLf + _
Base64Encode(RichTextBox1.Text) + vbCrLf + _
vbCrLf + _
"--------------060502030501040302050009--" + vbCrLf
MsgString = txtMimeCode
Case ".PDF"
txtMimeCode = txtMimeCode + _
"Content-Type: application/pdf;" + vbCrLf + _
"name=" + VbQuote + txtAttachment.Text + VbQuote + vbCrLf + _
"Content-Transfer-Encoding: base64" + vbCrLf + _
"Content-Disposition: attachment; filename=" + txtAttachment.Text + vbCrLf + _
vbCrLf + _
Base64Encode(RichTextBox1.Text) + vbCrLf + _
vbCrLf + _
"--------------060502030501040302050009--" + vbCrLf
MsgString = txtMimeCode
Case ".XLS"
txtMimeCode = txtMimeCode + _
"Content-Type: application/excel;" + vbCrLf + _
"name=" + VbQuote + txtAttachment.Text + VbQuote + vbCrLf + _
"Content-Transfer-Encoding: base64" + vbCrLf + _
"Content-Disposition: attachment; filename=" + txtAttachment.Text + vbCrLf + _
vbCrLf + _
Base64Encode(RichTextBox1.Text) + vbCrLf + _
vbCrLf + _
"--------------060502030501040302050009--" + vbCrLf
MsgString = txtMimeCode
Case Else
txtMimeCode = txtMimeCode + _
"Content-Type: application/unknown;" + vbCrLf + _
"name=" + VbQuote + txtAttachment.Text + VbQuote + vbCrLf + _
"Content-Transfer-Encoding: base64" + vbCrLf + _
"Content-Disposition: attachment; filename=" + txtAttachment.Text + vbCrLf + _
vbCrLf + _
Base64Encode(RichTextBox1.Text) + vbCrLf + _
vbCrLf + _
"--------------060502030501040302050009--" + vbCrLf
MsgString = txtMimeCode
End Select
End If
MsgString = txtMimeCode
StrArray = Split(MsgString, vbCrLf)
End Sub
Dim fso As New Scripting.FileSystemObject
Dim fco As New Scripting.Encoder
Dim Sdata As String, Cptr As Integer
Dim StrArray As Variant, StrElement As Variant, MsgString As String
Dim v As Boolean
Dim o As Boolean
Private Sub Command1_Click()
Winsock1.SendData "MAIL FROM:<yourID@YAHOO.in> " & vbCrLf
End Sub
Private Sub Timer1_Timer()
Me.Caption = Winsock1.State
If Winsock1.State = 9 Then Winsock1.Close
End Sub
Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Dim str As String
Call Winsock1.GetData(str)
If Left(str, 3) = "220" Then
Winsock1.SendData "EHLO YAHOO.COM " & vbCrLf
ElseIf Left(str, 4) = "250-" Then
Winsock1.SendData "AUTH LOGIN" & vbCrLf
ElseIf str = "334 VXNlcm5hbWU6" & vbCrLf Then
Winsock1.SendData "Encrypted ID" & vbCrLf
ElseIf str = "334 UGFzc3dvcmQ6" & vbCrLf Then
Winsock1.SendData "Encrypted Password" & vbCrLf
ElseIf Left(str, 3) = "235" Then
MsgBox "Authentication Succesfull!"
ElseIf Left(str, 4) = "250 " And v = False Then
Winsock1.SendData "RCPT To:<" & txtTo.Text & "> " & vbCrLf
v = True
ElseIf Left(str, 4) = "250 " Then
If o = False Then
Winsock1.SendData "DATA " & vbCrLf
MsgBox "Data Sending!"
Else
Winsock1.SendData "QUIT" & vbCrLf
MsgBox "OK Mail Sent!"
End If
ElseIf Left(str, 3) = "354" Then
Winsock1.SendData "From: ""Sender"" <yourID@yahoo.in>" & vbCrLf
Winsock1.SendData "To: ""Receiver"" <mailID@yahoo.com>" & vbCrLf
Winsock1.SendData "Date: Fri, 31 Dec 2010 16:02:43 -0500" & vbCrLf
Winsock1.SendData "Subject: " & Text2.Text & vbCrLf
Call attachment
For Each StrElement In StrArray
Winsock1.SendData (CStr(StrElement) & vbCrLf)
Next StrElement
Winsock1.SendData "." & vbCrLf
o = True
End If
End Sub
Private Sub Winsock1_Error(ByVal Number As Integer, Description As String, ByVal Scode As Long, ByVal Source As String, ByVal HelpFile As String, ByVal HelpContext As Long, CancelDisplay As Boolean)
MsgBox Number & " " & Description
End Sub
Sub attachment()
If Len(txtAttachment.Text) = 0 Then
'we don't need MIME for this
MsgString = txtEmailBodyOfMessage.Text + vbCrLf
Else
'build the 1st part of the MIME script
txtMimeCode = _
"MIME-Version: 1.0 " + vbCrLf + _
"Content-Type: multipart/mixed;" + vbCrLf + _
" boundary=" + VbQuote + "------------060502030501040302050009" + VbQuote + vbCrLf + _
vbCrLf _
+ "This is a multi-part message in MIME format." + vbCrLf + _
"--------------060502030501040302050009" + vbCrLf + _
"Content-Type: text/plain; charset=ISO-8859-1; format=flowed" + vbCrLf + _
"Content-Transfer-Encoding: 7bit" + vbCrLf + _
vbCrLf + _
txtEmailBodyOfMessage + vbCrLf + _
vbCrLf + _
"--------------060502030501040302050009" + vbCrLf
Select Case UCase(Right(txtAttachment.Text, 4))
Case ".TXT"
txtMimeCode = txtMimeCode + _
"Content-Type: text/plain;" + vbCrLf + _
"name=" + VbQuote + txtAttachment.Text + VbQuote + vbCrLf + _
"Content-Transfer-Encoding: base64" + vbCrLf + _
"Content-Disposition: attachment; filename=" + txtAttachment.Text + vbCrLf + _
vbCrLf + _
Base64Encode(RichTextBox1.Text) + vbCrLf + _
vbCrLf + _
"--------------060502030501040302050009--" + vbCrLf
Case ".DOC"
txtMimeCode = txtMimeCode + _
"Content-Type: application/msword;" + vbCrLf + _
"name=" + VbQuote + txtAttachment.Text + VbQuote + vbCrLf + _
"Content-Transfer-Encoding: base64" + vbCrLf + _
"Content-Disposition: attachment; filename=" + txtAttachment.Text + vbCrLf + _
vbCrLf + _
Base64Encode(RichTextBox1.Text) + vbCrLf + _
vbCrLf + _
"--------------060502030501040302050009--" + vbCrLf
MsgString = txtMimeCode
Case ".PDF"
txtMimeCode = txtMimeCode + _
"Content-Type: application/pdf;" + vbCrLf + _
"name=" + VbQuote + txtAttachment.Text + VbQuote + vbCrLf + _
"Content-Transfer-Encoding: base64" + vbCrLf + _
"Content-Disposition: attachment; filename=" + txtAttachment.Text + vbCrLf + _
vbCrLf + _
Base64Encode(RichTextBox1.Text) + vbCrLf + _
vbCrLf + _
"--------------060502030501040302050009--" + vbCrLf
MsgString = txtMimeCode
Case ".XLS"
txtMimeCode = txtMimeCode + _
"Content-Type: application/excel;" + vbCrLf + _
"name=" + VbQuote + txtAttachment.Text + VbQuote + vbCrLf + _
"Content-Transfer-Encoding: base64" + vbCrLf + _
"Content-Disposition: attachment; filename=" + txtAttachment.Text + vbCrLf + _
vbCrLf + _
Base64Encode(RichTextBox1.Text) + vbCrLf + _
vbCrLf + _
"--------------060502030501040302050009--" + vbCrLf
MsgString = txtMimeCode
Case Else
txtMimeCode = txtMimeCode + _
"Content-Type: application/unknown;" + vbCrLf + _
"name=" + VbQuote + txtAttachment.Text + VbQuote + vbCrLf + _
"Content-Transfer-Encoding: base64" + vbCrLf + _
"Content-Disposition: attachment; filename=" + txtAttachment.Text + vbCrLf + _
vbCrLf + _
Base64Encode(RichTextBox1.Text) + vbCrLf + _
vbCrLf + _
"--------------060502030501040302050009--" + vbCrLf
MsgString = txtMimeCode
End Select
End If
MsgString = txtMimeCode
StrArray = Split(MsgString, vbCrLf)
End Sub
Sunday, 10 March 2013
Download Punjabi Typing Tutor(Anmol lipi) made in C++ (No Source Code)
Punjabi Typing Tutor made in C++ (NO SOURCE CODE)
Punjabi Typing Tutor made in C++ (NO SOURCE CODE)
JSP Custom Tag Example
Q. Create a custom tag that will accept a full
name and convert into initials. For example Surendra Kumar Sharma
should be displayed as S.K. Sharma.
Sol.
java file
package univ.myClasses;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;
/**
* @author Navdeep
*/
public class ShortNameTagHandler extends SimpleTagSupport {
private String name;
@Override
public void doTag() throws JspException {
JspWriter out = getJspContext().getOut();
try {
JspFragment f = getJspBody();
if (f != null) f.invoke(out);
out.print(shortName(name));
} catch (java.io.IOException ex) {
throw new JspException("Error in ShortNameTagHandler tag", ex);
}
}
public String shortName(String name)
{
String sName="";
String words[]=name.split(" ");
for(String word:words)
sName=sName + word.substring(0, 1) + ".";
return sName;
}
public void setName(String name) {
this.name = name;
}
}
Tld file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>csajsp</shortname>
<uri>csajsp-taglib</uri>
<info>A tag library.</info>
<tag>
<name>shortName</name>
<tag-class>univ.myClasses.ShortNameTagHandler</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>name</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<type>java.lang.String</type>
</attribute>
</tag>
</taglib>
jsp File
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<%@taglib uri="csajsp-taglib.tld" prefix="csajsp" %>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test Page</title>
</head>
<body>
<csajsp:shortName name="Surendra Kumar " /> Sharma
</body>
</html>
name and convert into initials. For example Surendra Kumar Sharma
should be displayed as S.K. Sharma.
Sol.
java file
package univ.myClasses;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;
/**
* @author Navdeep
*/
public class ShortNameTagHandler extends SimpleTagSupport {
private String name;
@Override
public void doTag() throws JspException {
JspWriter out = getJspContext().getOut();
try {
JspFragment f = getJspBody();
if (f != null) f.invoke(out);
out.print(shortName(name));
} catch (java.io.IOException ex) {
throw new JspException("Error in ShortNameTagHandler tag", ex);
}
}
public String shortName(String name)
{
String sName="";
String words[]=name.split(" ");
for(String word:words)
sName=sName + word.substring(0, 1) + ".";
return sName;
}
public void setName(String name) {
this.name = name;
}
}
Tld file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>csajsp</shortname>
<uri>csajsp-taglib</uri>
<info>A tag library.</info>
<tag>
<name>shortName</name>
<tag-class>univ.myClasses.ShortNameTagHandler</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>name</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<type>java.lang.String</type>
</attribute>
</tag>
</taglib>
jsp File
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<%@taglib uri="csajsp-taglib.tld" prefix="csajsp" %>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test Page</title>
</head>
<body>
<csajsp:shortName name="Surendra Kumar " /> Sharma
</body>
</html>
Thursday, 7 March 2013
Subscribe to:
Posts (Atom)