Tuesday, July 26, 2011

mouse tail effect in cplusplus

hello everyone.
today i have a great,interesting and easy thing to do with cursor in c++ using graphics.
seen many animation in flash or JavaScript but today i will do something amazing in c++.
many people think that c++ is boring and is only black and white to see.
but today i will use colors to make effect in c++.
there a screenshot of the program.
before reading this post further i would like to suggest you that you read my post on cursor here
download program + source-code
/*
example of cursor tail in turbo c++ 3.0
written by kuldeep dhaka [kuldeepdhaka9@gmail.com]
*/
#include<dos.h> #include<graphics.h> #include<stdlib.h> #include<stdio.h> #include<conio.h> #include<time.h>
union REGS in,out; /*-------------------------------------------------------*/ struct mouse {int x,y,b;}; void mouse_ini(); int mouse_show(); int mouse_hide(); void mouse_get(mouse *); void mouse_set(int,int); void mouse_restrict(int,int,int,int); /*--------------------------------------------------------*/ //function to be added to main for> mouse when application loads void mouse_ini() { if(!mouse_show()) { printf("error in initializing mouse"); printf("Press any key to halt:"); getch(); exit(1); } else mouse_restrict(0,0,getmaxx(),getmaxy()); } /*--------------------------------------------------------*/ /*to enable cursor or show cursor to user*/ int mouse_show() { in.x.ax=1; return int86(51,&in,&out); } /*--------------------------------------------------------*/ /*to disable cursor or hide cursor to user*/ int mouse_hide() { in.x.ax=2; return int86(51,&in,&out); } /*--------------------------------------------------------*/ /*get current mouse information b for> button x for> x-axis u for> y-axis */ void mouse_get(mouse *mus) { in.x.ax=3; int86(51,&in,&out); mus->b=out.x.bx; /* 0:-button not pressed 1:-left button is pressed 2:-right button is pressed 3:-center button is pressed */ mus->x=out.x.cx; mus->y=out.x.dx; } /*--------------------------------------------------------*/ /*set new position for> the cursor*/ void mouse_set(int x,int y) { in.x.ax=4; in.x.cx=x; in.x.dx=y; int86(51,&in,&out); } /*--------------------------------------------------------*/ /*restrict the mouse pointer between the specific positions*/ void mouse_restrict(int x_left,int y_top,int x_right,int y_bottom) { in.x.ax=7; in.x.cx=x_left; in.x.dx=x_right; int86(51,&in,&out); in.x.ax=8; in.x.cx=y_top; in.x.dx=y_bottom; int86(51,&in,&out); } void main() { /* graphics initalisation*/ int gdriver = DETECT, gmode, errorcode; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, "bgi"); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /*---------*/ setbkcolor(7); mouse mus; mouse_ini(); /*--------------circle effect----------*/ struct { int x,y,c; }tail[5]; int i,rad[]={5,10,15,20,25},max_avail_color=getmaxcolor(); while(!kbhit()) { mouse_get(&mus); cleardevice(); mouse_hide(); setcolor(4); outtextxy(5,5,"move the cursor to see full effect...press any key to exit..."); for>(i=0;i<5;i++) { setcolor(tail[i].c); circle(tail[i].x,tail[i].y,rad[i]); } mouse_show(); for>(i=0;i<4;i++) { tail[i]=tail[i+1]; } tail[4].x=mus.x; tail[4].y=mus.y; tail[4].c=rand()%max_avail_color; delay(50); } }
thats all for now.good bye folks.

Labels: , , , , , , ,

Wednesday, July 20, 2011

build your own screen saver in c++

today i will show you something interesting,its not hard to code but i am just building it for fun.
today i will code a screensaver in c++ using graphics.
it simple and easy to understand
demo executable+ source-code
#include<graphics.h> #include<stdlib.h> #include<stdio.h> #include<conio.h> #include<time.h>
int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int maxx,maxy,x,y,color,maxcolor; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, "bgi"); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } maxcolor=getmaxcolor()+1; maxx=getmaxx()+1; maxy=getmaxy()+1; randomize(); while(!kbhit()) { color=random(maxcolor); x=random(maxx); y=random(maxy); putpixel(x,y,color); } /* clean up */ closegraph(); return 0; }
please leave comment..
please give me new ideas.you ideas will be appreciated.
soon i will return with a new art.till then,good bye.

Labels: , , , , , , ,

Tuesday, July 19, 2011

build an analog clock in c++ using graphics

today,i am going to show you some thing amazing and adventurous.
you have a clock on your wall.but today im going to show how to make a similar clock in c++ using graphics.
before continuing i would expect that you have a little knowledge of vector algebra.without vector algebra this would be nothing.

please ensure that you know how to run graphics mode and must be able to do simple thing's in graphics.if you want to learn please go here onecore-Turbo C++ graphics programming

download sourcecode+exe program
/*=======================
require header files
=========================*/
#include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> #include <dos.h> #include<math.h>
int clock_x; int clock_y; int clock_radius; void hand(int color,int thickness,float angle,int radius); void main(void) { /*======================request auto detection=============================*/ int gdriver = DETECT, gmode, errorcode; int midx, midy; /*==================initialize graphics and local variables================*/ initgraph(&gdriver, &gmode, "bgi"); /*==================read result of initialization==========================*/ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /*====================initializing settings==============================*/ clock_x=getmaxx()/2; clock_y=getmaxy()/2; clock_radius=(getmaxx()+getmaxy())/6; while(!kbhit()) { /*============clear the device===============*/ cleardevice(); /*===============set backcolor============-*/ setbkcolor(7); /*=========--print message============--*/ setcolor(4); settextstyle(0,0,1); outtextxy(10,10,"press any key to exit...."); /*=========-printing the clock numbers=========*/ float angle=-M_PI_2; char *num[]={"1","2","3","4","5","6","7","8","9","10","11","12"}; setcolor(1); for(int i=0;i<12;i++) { angle+=M_PI/6; outtextxy(clock_x+(clock_radius*cos(angle)),clock_y+(clock_radius*sin(angle)),num[i]); } /*===============-retrieving time from system===============-*/ struct time t; gettime(&t); /*--------print the am/pm---------*/ setcolor(8); settextstyle(0,0,4); if(t.ti_hour>12) outtextxy(clock_x-(textwidth("PM")/2),clock_y+textheight("PM"),"PM"); else outtextxy(clock_x-(textwidth("AM")/2),clock_y+textheight("AM"),"AM"); /*=====================printing the hour hand==================*/ angle=(M_PI/6)*(t.ti_hour); /*hour are in 24 system*/ hand(4,3,angle,clock_radius-50); /*===-printing the min hand===--*/ angle=(M_PI/30)*(t.ti_min); hand(5,2,angle,clock_radius-10); /*===-printing the second hand===--*/ angle=(M_PI/30)*(t.ti_sec); hand(15,1,angle,clock_radius-10); /*print tail of second hand*/ hand(15,1,angle-M_PI,20); /*print head circle of second*/ setlinestyle(SOLID_LINE,SOLID_FILL,1); setcolor(15); pieslice(clock_x,clock_y,0,360,3); sound(700); /*make a 700 hz tone that resembles the tik-tik sound*/ delay(50); /*delay for 50 Milli-seconds*/ nosound(); /*stop tone*/ delay(950); /*delay for 950 milliseconds*/ } /*=========-clear the device===============--*/ cleardevice(); } void hand(int color,int thickness,float angle,int radius) { /*set the thickness of hand*/ setlinestyle(SOLID_LINE,SOLID_FILL,thickness); /*set hand color*/ setcolor(color); /*calculate the x position of the hand using vector algebra*/ int num_x=clock_x+(radius*cos(angle-M_PI_2)); /*calculate the y position of the hand using vector algebra*/ int num_y=clock_y+(radius*sin(angle-M_PI_2)); line(clock_x,clock_y,num_x,num_y); /*note that M_PI_2 is for making the line 90 degree backward*/ }
that's all folk,i will return again with a new and exiting project.
please leave comment.report any bugs.

Labels: , , , ,

Monday, July 18, 2011

drag and drop a box in c++ using cursor

hello everyone,today im going to show you something you never expected from c++.
this is just a prototype which can be use in many projects to make them more interactive

but,before reading this post please read me as this post use cursor example.without cursor knowledge you will not understand the program.
gif animation of drag and drop
download exe + sourcecode
so the program is like this
there is a while loop running and will only break if any key is pressed using kbhit()

when a user right clicks and the position of the cursor is inside the box then the variable "move" is set to "yes"

and another condition after that check if the variable "move" is set to "yes" or not
if "yes" then the program checks that has the mouse moved or not
if the mouse also moved then it calculates and moves the box accordingly

this is done by taking a difference in position of cursor and box and if cursor has moved the difference is added to the cursor position and set to the box position.

that's all going on inside the program.
#include<graphics.h> #include<conio.h> #include<process.h> #include<stdio.h> #include<dos.h> #include<stdlib.h>
union REGS in,out; struct mouse{int x,y,b;}; void mouse_ini(); int mouse_show(); int mouse_hide(); void mouse_get(mouse *); void mouse_set(int,int); void mouse_restrict(int,int,int,int); void main() {
/*---graphics initialization request auto detection */
int gdriver=DETECT, gmode, errorcode; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, "path to bgi folder on computer"); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error-occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } mouse_ini(); /*-actual program from here--*/ setbkcolor(56); setfillstyle(SOLID_FILL,2); setcolor(63); /*setting for initial position and width,height*/ int x=50,y=50,w=50,h=50,xdiff,ydiff,tmpx,tmpy; mouse_hide(); bar(x,y,x + w,y + h); mouse_show(); char move; mouse mus; do{ mouse_get(&mus); if(move == 'n' && mus.b == 1 && mus.x > x && mus.x < x + w && mus.y > y && mus.y < y + h) { xdiff = mus.x - x; ydiff = mus.y - y; move = 'y'; } else if(mus.b == 0) move = 'n'; mouse_get(&mus); if(move == 'y') { tmpx = x; tmpy = y; x = mus.x - xdiff; y = mus.y - ydiff; if(tmpx != x || tmpy != y) { mouse_hide(); cleardevice(); bar(x,y,x + w,y + h); mouse_show(); } } else outtextxy(10,10,"click the rectangle and drag it,press any key from keyboard to exit"); }while(!kbhit()); //while keyboard is not hit } /*to initialize the mouse when program starts*/ void mouse_ini() { if(!mouse_show()) { printf("error in initializing mouse"); printf("Press any key to halt:"); getch(); exit(1); } else mouse_restrict(0,0,getmaxx(),getmaxy()); } /*to enable cursor or show cursor to user*/ int mouse_show() { in.x.ax=1; return int86(51,&in,&out); } /*to disable cursor or hide cursor to user*/ int mouse_hide() { in.x.ax=2; return int86(51,&in,&out); }
/*get current mouse information b for button x for x-axis u for y-axis */
void mouse_get(mouse *mus) { in.x.ax=3; int86(51,&in,&out); mus->b=out.x.bx; mus->x=out.x.cx; mus->y=out.x.dx; }
/*when you want to get the mouse position and button use this method mouse mus; mouse_get(&mus); */ /*set new position for the cursor*/
void mouse_set(int x,int y) { in.x.ax=4; in.x.cx=x; in.x.dx=y; int86(51,&in,&out); } /*restrict the mouse pointer between the specific positions*/ void mouse_restrict(int x_left,int y_top,int x_right,int y_bottom) { in.x.ax=7; in.x.cx=x_left; in.x.dx=x_right; int86(51,&in,&out); in.x.ax=8; in.x.cx=y_top; in.x.dx=y_bottom; int86(51,&in,&out); }

Labels: , , , , , , , , ,

Sunday, July 17, 2011

how to use cursor in c++ program

one year ago i was goggling the giant for code to access pointer in turbo c++ 3.0
after a long search i found one site but the tutorial was very complex and it took me a whole day to figure out how it work
but here is a simple tutorial for you.

screen-shoots of program

sreenshoot1sreenshoot2
download program + source-code


you can access pointers in both graphics and text mode
but i recommend that you use graphics mode because it looks more beautiful.

if you don't know how to change to graphics mode please read me first

now lets finish our chat and start the tutorial part

cursor functionality is provided in dos.h
so, here it is the main part of the post:-

Interrupt Service Purpose
51 0
Reset mouse and get status
Call with AX = 0
Returns: AX = FFFFh If mouse support is available
Ax = 0 If mouse support is not available
51 1
Show mouse pointer
Call with AX = 1 
Returns: Nothing
51 2
Hide mouse pointer
Call with AX = 2
Returns: Nothing
51 3
Get mouse position and button status
Call with AX = 3
Returns: BX = mouse button status
BitSignificance
0button not pressed
1left button is pressed
2right button is pressed
3center button is pressed
CX = x coordinate
DX = y coordinate
51 4 Set mouse pointer position
Call with AX = 4
CX = x coordinate
DX = y coordinate
Returns: Nothing
51 7 Set horizontal limits for pointer
Call with AX = 7
CX = minimum x coordinate
DX = maximum x coordinate
Returns: Nothing
51 8 Set vertical limits for pointer
Call with AX = 8
CX = minimum y coordinate
DX = maximum y coordinate
Returns: Nothing
so here is a working code that you can attach to your program and easily add cursor to your program
/*you must include dos.h*/
#include<dos.h>
/*you must include stdlib.h for exit function*/
#include<stdlib.h>
/*----------------------------------*/
struct mouse{int x,y,b;};
void mouse_ini();
int mouse_show();
int mouse_hide();
void mouse_get(mouse *);
void mouse_set(int x,int y);
void mouse_restrict(int x_left,int y_top,int x_right,int y_bottom);
/*-----------------------------------*/
/*to initialize the mouse when program starts*/
int mouse_ini()
{
if(!mouse_show())
 {
 printf("error in inializing mouse");
 printf("Press any key to halt:");
 getch();
 exit(1);
 }
else mouse_restrict(0,0,getmaxx(),getmaxy());
/*note:-getmaxx() and getmaxy() are functions of graphics.h*/
}
/*to enable cursor or show cursor to user*/
int mouse_show()
{
 in.x.ax=1;
 return int86(51,&in,&out);
}
/*to disable cursor or hide cursor to user*/
int mouse_hide()
{
 in.x.ax=2;
 return int86(51,&in,&out);
}
/*get current mouse information
b for button
x for x-axis
u for y-axis
*/
void mouse_get(mouse *mus)
{
 in.x.ax=3;
 int86(51,&in,&out);
 mus->b=out.x.bx;
 mus->x=out.x.cx;
 mus->y=out.x.dx;
}
/*when you want to get the mouse position and button use this method
mouse mus;
mouse_get(&mus); */
/*set new position for the cursor*/
void mouse_set(int x,int y)
{
 in.x.ax=4;
 in.x.cx=x;
 in.x.dx=y;
 int86(51,&in,&out);
}
/*restrict the mouse pointer between the specific positions*/
void mouse_restrict(int x_left,int y_top,int x_right,int y_bottom)
{
 in.x.ax=7;
 in.x.cx=x_left;
 in.x.dx=x_right;
 int86(51,&in,&out);
 in.x.ax=8;
 in.x.cx=y_top;
 in.x.dx=y_bottom;
 int86(51,&in,&out);
}
/*include this code just after graphics initialization*/
void main()
{
mouse_ini();
}
that's all folks for now
so long for next time for a new and exiting post.
waiting for you comment's.
download the example its very helpful for those who want to see cursor in c++ 3.0

Labels: , , , , , , , , ,

how to use back button and bookmarking in ajax

i had a similar problem a few months ago.
want to use AJAX but cannot go back after loading.
if you bookmark the dynamically loaded page you don't see the dynamically loaded page again.
there is a solution for this.
hashing is a possible solution for this.

live example


but first lets understand what is hash
hash is a part of the a URL
for example
http://www.websitename.com/path/page.ext?get_var1=value1&get_var2=value2&...&get_varn=valuen#hash

example:
http://username:password@www.sakul.com:256/query/index.htm?q=kuldeep#techpreach
scheme sub-domain host-name port path file-name get variables hash
http www sakul.com 80 query index.htm q="kuldeep" techpreach
but most likely you will see a domain like this
sakul.com/query/
schemeby default it add host name to http
host-nameminimum you have to pass that
username and passwordonly used for authentication purpose
sub-domaindefault is www but added according to server
portdefault port is 80
pathcan be null
file-nameif null passed server decide

but for now just get the hash part in your mind
sometimes when you click a link it don't reload but moves you to another part of the page or when you load a page with hash it automatically moves to new location on the page.
you must be thinking how??
the answer is hash
a hash is a part of URL that redirect the user to a part of the page and many browser store a new hash as new link so when you click back you again moves to the location that you left
hashing make pages more navigable and simple to work upon.
so now we will exploit these feature to use back and forward button in Ajax
if somehow we get the hash from the address bar how will JavaScript know that back button is clicked by user
the answer to this question is setInterval(function,milliseconds) function
we will check that if the hash stored in variable is matching with the hash from the address bar if hash don't match user has clicked back button
in an interval of 500 Milli seconds we will check this and user will see no change
reference to the function used int the code
function reference
window.location.hash this can be used to get and set hash in JavaScript
window.location.hash="hash value here";
var variable_to_store_hash=window.location.hash;
note:-remember that when you set a new hash the old hash will become history
add a special character before storing your Ajax information to hash because if a real hash[i mean here that if a "a" refer you to a new page location] come it can distinguish between them like twitter.com user "!" we will here use dollar sign "$"
setInterval(function,milliseconds)
setInterval is a function that load the specific function pass in after a time-period of the milliseconds passed
note:-1000 Milli-seconds= 1 second
window.onload=< function name >
load's the function on window load or simply when the page load's
< string >.split(delimiter)
a delimiter is a character that is used to break a string into array
counting of array starts from 0
for-example:-
var array="this is a string".split(" ");//" " stands for space
now,
array[0]="this";
array[1]="is";
array[2]="a";
array[3]="string";
< string >.charAt(position)
return the character which is found on position where position is an integer and can have value 0
same work can be done by < string >[position]here string behaves like array

now here is the code for it
<html>
<head>
<title>ajax backbutton and bookmarking using hash</title>
<script type="text/JavaScript">
/*tested on Mozilla Firefox 5.0 [don't work on internet explorer =<6.0]*/
var saved_hash="";
/*-----on form load this will run------*/
window.onload=function ()
{
if(window.location.hash!="") alert("opening bookmark");
setInterval(function(e){
 var visible_hash=window.location.hash;
 if(visible_hash!=saved_hash)
  {
  ajax(visible_hash,false);
  }
 },500);
}
/*------------------------------------------------------------------*/
function Ajax(rec_hash,newhash)
{
saved_hash=rec_hash;
/* newhash Tell's weather the hash is new or old if new  then set a new hash in address bar*/
if(newhash==true) window.location.hash=rec_hash;
alert("opening:-"+rec_hash); /*append Ajax code here*/
}
</script>
</head>
<body>
<div onclick='javascript:ajax("aboutme",true)'>open aboutme</div>
</body>
</html>

here is a bad news that internet explorer =<6.0 doesn't support this method.but there is one solution that Gmail.com use but even Gmail.com method don't support mac safari browser
so long for next time
soon i will also give a post for Gmail method.
recommended to that you must read to ensure full knowledge of AJAX
introduction to Ajax with full example
please do post comment [+report bugs (if any)*].

Labels: , , , , , , , , , , ,

Friday, July 15, 2011

introduction to ajax

today i will write a Newbie tutorial for ajax
about ajax
AJAX stands for Asynchronous JavaScript and XML.

it is not a programming language but an extension to Javascript to load content to a part of the page without reloading the page

some of the powerful implementation of AJAX are
  • Gmail -Google approach to mail
  • facebook -widely used social networking
  • twitter -widely used micro-blogging site
  • and many more out there

AJAX was introduced in 2005.

now start the main part
to create a ajax request we have to first create a ajax request variable
browser's initaliser
For modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) new XMLHttpRequest()
Old versions of Internet Explorer (IE5 and IE6) an ActiveX Object: new ActiveXObject("Microsoft.XMLHTTP")
some unknow old versions of Internet Explorer new ActiveXObject("Microsoft.XMLHTTP")

now we open the variable to get the
<ajax variable>.open(<method>,<address>,<Asynchronous>);
<address> the file to fetch from server.relative link to the path of the script address.
<Asynchronous>
true(Asynchronous):-to continue processing further script
false(synchronous):-to stop processing the script till request is finished.
<method> request method example get,post..request method in hypertext transfer protocol from wikipedia
note
if you use true then write the code for printing the recived data to the page after the function send()


finally send the request to server
send(<post data>)
<post data> to send post variable data like name or email from form input.

the most important part of the script
<ajax variable>.onreadystatechange
Stores a function (or the name of a function) to be called automatically each time the readyState property changes
Property Description
readyState Holds the status of the XMLHttpRequest. Changes from 0 to 4:

0: request not initialized

1: server connection established

2: request received

3: processing request

4: request finished and response is ready
status 200: "OK"

404: Page not found
note:200 is used to check the file exists on server if you are viewing a page directly from computer then use 0 to get "ok" status
to access readyState use <ajax variable>.readyState
this will tell you what is the status of the request

to access status use <ajax variable>.status
this will tell you the last status received from the server for this request [and for example 500 means server internal error]


to access the received data
xml format<ajax variable>.responseXml
text format<ajax variable>.responseText


now you have got the theoretical knowledge we create a function to access a text file and print it to the screen
  1. create a page index.htm and a file with name aboutme.txt in the same directory (or folder)
  2. copy the above code to index.htm
  3. write "hello my name is kuldeep dhaka..my email address is kuldeepdhaka9@gmail.com" or something of your choice to aboutme.txt
  4. run the index.htm in browser and check out what do you see
  5. see to load a ajax link if ajax is supported and goto the link this is useful for advance users
thats all folk's for today.
please comments [+ notify any bug *if any*]
code under creative commons attribute(open source).
a email of mine above the code will be appreciated
<html>
<head>
<script type='text/javascript'>
/*-created by kuldeep dhaka (kuldeepdhaka9@gmail.com)-*/
/*-code tested in mozilla firefox 5.0-*/
/*---------create a new ajax variable------*/
function new_ajax_request_variable()
{
try {return new XMLHttpRequest();}
 catch (e)
 {
        try{return new ActiveXObject("Msxml2.XMLHTTP");}
  catch (e){
   try{return new ActiveXObject("Msxml3.XMLHTTP")}
   catch(e){
    try{return new ActiveXObject("Microsoft.XMLHTTP");}
    catch (e){return "";}
 }}}
}
/*---------ajax request function [main function]----*/
function ajax_request(where,what,method,form_phrase,asyn)
{
var ajax_request=new_ajax_request_variable();
 if(isnull(ajax_request)) 
     {
      alert("your browser do not support ajax");
      return;
     }
 else
     {
  /*---the readystatechange section-----*/
  ajax_request.onreadystatechange=function()
  {
   if(ajax_request.readyState==0) 
    set_property(where,"initalising request....");
   else if(ajax_request.readyState==1) 
    set_property(where,"server connection established....");
   else if(ajax_request.readyState==2) 
    set_property(where,"request received....");
   else if(ajax_request.readyState==3) 
    set_property(where,"processing request(nearly finished)....");
   else if(ajax_request.readyState==4) 
    {
    if(ajax_request.status==200) 
     set_property(where,ajax_request.responseText);
    else if(ajax_request.status==404) 
     set_property(where,"404:file not found");
    else set_property(where,"error[status="+ajax_request.status+"]");
    }
  }
 /*----open section---------*/
 if(isnull(method)) method="GET"; //default value GET
 if (isnull(asyn)) asyn=true; //default value TRUE
 ajax_request.open(method,what,asyn);
 /*----send---------*/
 if(isnull(form_phrase)) ajax_request.send();
 else ajax_request.send(form_phrase);
 }
}
/*-------function to check variable--------*/
function isnull(variable)
{
 if(variable=="" || variable=="undefined" || variable==null) return true;
 else return false;
}
/*----function to write data with an element-----*/
//you can change it according to your need
ie=document.getElementById;
ns=document.layers;
othr=document.all;
function set_property(objid,value)
{
 if (ie) document.getElementById(objid).innerHTML=value;
 else if (ns) document.layers[objid].innerHTML=value;
 else if (othr) document.all[objid].innerHTML=value;
}
</script>
<style type="text/css">
div
{
 padding:30px;
 margin:30px;
 background:#f4f4f4;
 border:1px solid #ccc;
}
div:hover{border:1px solid #aaa;}
body{background:#fff;}
</style>
</head>
<body>
<div id='aboutmebox'>
<button onclick='ajax_request("aboutmebox","aboutme.txt")' >
click me to load aboutme</button>
</div>
</body>
</div>

Labels: , , , , ,

display a moving tail in arduino

this is a arduino program that uses led to make a moving tail effect
the source is below

/*
created by kuldeep dhaka
email:kuldeepdhaka9@gmail.com

how it work:
there are 11 boxes
array address    0  1  2  3  4  5  6  7  8  9  10
                 [] [] [] [] [] [] [] [] [] [] []
variable number  1  2  3  4  5  6  7  8  9  10 11
the last variable is to store the 10th variable value temporarily
shifting of values is done and the last one is shifted to first
the a loop is runned from 3 to 9
*/
//actual program start here:-
unsigned char i;
unsigned char led[]={3,5,6,9,10,11,7};
unsigned char tail[]={15,80,190,255,0,0,0,0,0,0,0};
void setup()
{
//do nothing
}
void loop()
{
//shifting values:-
for(i=9 ; i>=0; i--)
  {
  tail[i+1]=tail[i];
  }
tail[0]=tail[10];
//sending values to led:-
for(i=0;i<6;i++)
  {
  analogWrite(led[i],tail[i+3]);
  }
delay(500);
}

please leave comments [+report bug also if any]

Labels: , , , ,

Thursday, July 14, 2011

session in php

today i will show you how to register session's and delete session in php
but before starting i will give u a small introduction

format of session variable is $_SESSION["<variable name>"]
want to register a session for log-in or any other purpose like temporary settings.
session will be working till your page(s) are closed.

session variable are super-global variables means they can be used in any page.

for long purpose of storing data of user for next visit's like name,email cookies should be used.in my way i will show you how its done.

it's not long ago when i learned session but its practice can increase features of your website.

to initialise a session you must call a function session_start();
it return true on success and false on failure
failed to load this function will bring error and unpredictable output so be carefull to load this function first

to create a session variable [with name "dummy"]

<?php
 session_start();
 $_SESSION["dummy"]="dummy text goes here or any other data type";
?>

if you want to go a little advance you can use the below script
<?php
   session_start();
   if(isset($_SESSION["dummy"])) 
         echo "dummy variable already exists";
   else 
     {
       $_SESSION["dummy"]="dummy text goes here or any other data type";
       echo "dummy variable created";
     }
?>
if you run this script twice on server it will give this output
first run
dummy variable created
second run
dummy variable already exists

if you are planning to register user and provide them user name and password session variables come handy

for example
<?php
 session_start();
  if(isset($_SESSION["username"]))
       echo "welcome ".$_SESSION["username"];
  else
    {
      echo "checking username and password...\n";
      check_username_password(); /*dummy function to check
username and password*/
    }
function check_username_password()
{
   /------check username and password-------/
   /------check username and password-------/
   if(<authentication variable>)
    {
     /*authentication is successful*/
     $_SESSION["username"]=<received username>;
     echo "successfully logged in";
   }
   else
     {
      /*authentication failure*/
      echo "authentication failure."
     }
}
?>

now comes the last part if you register a session how to delete the session
php has inbuilt function to delete a session bool session_destroy( void )
bool session_destroy(void) will delete all session variable
it return true on sucess and false on failure
for example
log-out.php
<?php
  session_start();
  if(session_destroy()) 
      echo "session successfully destroyed";
  else 
      echo "error occurred while destroying session";
?>

that's all folk's
please comment and ask for a more advance tutorial if required.

Labels: , , , , , , , , , ,

Wednesday, July 13, 2011

introduction to server scripting (php)

as we all about programming but web programming is a little different thing.
computer you are using to view this webpage is a client and server is that provided you this webpage.
what is really a client and server script?
a client script is a program that runs on the browser.
a server script is a program that run on the server.
client scriptsJavaScript,vb script,css and many more
server scriptsphp,asp,jsp and many more

server script's run on server and can be used to store your name password email and other details.
and you can access those resource from any part of the world
and client scripts are used for make page more interactive.
if you use client script for storing data you can only access that data from the specific computer only

once the server script is finished on the server the data is send to the client

i recommend php because its open source and full of feature..
hundred's of predefined function and constants.

for storing data the best option is MySQL

programmers say that php and MySQL is a very strong combination for server scripting

example of php+MySQL
yahoo,Facebook and many more out there..

php is easy to learn and a very powerful language.
if you know c or c++ you will find php even more easy as syntax and function names are similar


http://php.net is the official site for php documentation.

php official site contains all the function documentation for reference and great examples for beginners and troubleshoot


to make a php page use the extension .php
inside the file start with
<?php
   ---php codes-----
   ---php codes-----
?>
"<?php" is used to start a php script
"?>" is used to end a php script


comments in php
<?php
    $var1="hello"; #comment 1
    $var2="how are you?"; //comment 2
    $var3="nice to meet you"; /*this is
      is a multi line comment
      you can you chose as many line
      for comment till you end it similar to c++ syntax */
?>


variables in php
variable in php start with the dollar sign and cannot start with a number
there are no reserved keywords in php like c++
no space between character is allowed
example
correct names$var,$hello_word,$class,$integer
incorrect namesvar,$var one

$var1="hello"; /*var1 contain string value "hello"*/
$var=10; /*var2 contain integer value 10*/
$var=new array(); /*create an array,more discussion on it later*/


printing a variable value in php
<?php
    $nuke="this is all about nuclear reactor's";
    echo $nuke; /*echo $nuke prints the string*/
?>
output:-

this is all about nuclear reactor's


operations on variable
<?php
    $var1=10;
    $var2=5;
    $result=0;               /*to set the result 0*/
    $result=$var1 + $var2;   /*add two variable and
store it  into $result*/
    $result=$var1 - $var2;   /*subtract first variable by
second and store it into $result*/
    $result=$var1 / $var2;   /*divide first variable by
second and store it into $result*/
    $result=$var1            /*assign $result the value of
$var1*/
?>


condition in php
<?php
   $var1=10;
   if($var1==10) 
       echo "var1 is equal to 10";
   else 
       echo "var1 is not equal to 10";
?>
some thing to remember
== /*for comparision of value if mathamatical value's are equal conditon is true
if mathamatical value's are not equal conditon is false

$var!=checkvalue /*$var value is not equals to checkvalue*/

!$varname means $varname==0

$var=>checkvalue /*$var value is equal or greater than checkvalue*/

$var=
now we had got a little theoretical knowledge,time to apply it ; )
  1. you need a server for viewing a php file
  2. for windows user goto wamp server for windows and for linux user please install lamp for your distro and replace c:/wamp/www/ with /var/www/
  3. download and install it
  4. run wamp server and a small semicircle will appear in your right of windows task bar
  5. usually it install it in c: drive as per convention im taking c: drive
  6. open notepad and copy the below text in it and save it to c:/wamp/www/first.php
    for linux user save the file with root permission or it will not let you save
  7. open you browser and type http://localhost/first.php
  8. and you will see your first php program
<html>
<head>
<title>my first php program</title>
</head>
<body>
<?php
      echo "hello world";
      $sum=1+5;
      echo "adding 1+5=$sum"; /*try replacing the double
quote with single quote and see what happens*/
?>
</body>
</html>
that's all folks your first php programs you
please do leave comment's and please don't hesitate to criticize the content if necessary because
"when we kick a football it moves forward"

now you are ready for the next level.

Labels: , , , , , ,

introduction

this is an introduction post...
this website will provide tutorial on hardware,embedded and programming...
we support html html5 javascript c++ c css php+mysql arduino avr and technical problems....

Labels: