<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Wanderer&#039;s Thougths</title>
	<atom:link href="http://aprajshekhar.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://aprajshekhar.wordpress.com</link>
	<description>A tech-hobbyist&#039;s musings</description>
	<lastBuildDate>Sat, 16 Jul 2011 18:56:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='aprajshekhar.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Wanderer&#039;s Thougths</title>
		<link>http://aprajshekhar.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://aprajshekhar.wordpress.com/osd.xml" title="Wanderer&#039;s Thougths" />
	<atom:link rel='hub' href='http://aprajshekhar.wordpress.com/?pushpress=hub'/>
		<item>
		<title>SDL Programming in Linux SDL &amp; OpenGL-Brothers in Gaming</title>
		<link>http://aprajshekhar.wordpress.com/2011/07/16/sdl-programming-in-linux-sdl-opengl-brothers-in-gaming/</link>
		<comments>http://aprajshekhar.wordpress.com/2011/07/16/sdl-programming-in-linux-sdl-opengl-brothers-in-gaming/#comments</comments>
		<pubDate>Sat, 16 Jul 2011 11:20:23 +0000</pubDate>
		<dc:creator>AP Rajshekhar</dc:creator>
				<category><![CDATA[SDL]]></category>
		<category><![CDATA[C/C++]]></category>
		<category><![CDATA[game-programming]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://aprajshekhar.wordpress.com/?p=150</guid>
		<description><![CDATA[In the world of gaming, SDL provides the entire necessary infrastructure. This would have become clear from the past parts of the series. But infrastructure is to a game what skeleton is to a human body. But without muscles, no locomotion is possible. So working with the analogy of body, SDL provides the skeletal structure to build up the game whereas the flesh, blood and skin are provided by 2D and 3D graphics libraries. In the current plethora of 3D libraries, OpenGL stands out on various accounts. The most significant of them is its compatibility with almost all the platforms and graphics cards. This even reflects in the architecture of SDL as SDL can create and use OpenGL contexts on several platforms. Such architecture helps the game programmer to use all the sub-systems of SDL seamlessly in conjunction with OpenGL to provide most effective games and gaming environments. In this article I will discuss how to use SDL and OpenGL together where gaming infrastructure is provided by SDL and animation as well as rendering is being handled by OpenGL.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=aprajshekhar.wordpress.com&amp;blog=5963225&amp;post=150&amp;subd=aprajshekhar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In the world of gaming, SDL provides the entire necessary infrastructure. This would have become clear from the past parts of the series. But infrastructure is to a game what skeleton is to a human body. But without muscles, no locomotion is possible. So working with the analogy of body, SDL provides the skeletal structure to build up the game whereas the flesh, blood and skin are provided by 2D and 3D graphics libraries. In the current plethora of 3D libraries, OpenGL stands out on various accounts. The most significant of them is its compatibility with almost all the platforms and graphics cards. This even reflects in the architecture of SDL as SDL can create and use OpenGL contexts on several platforms. Such architecture helps the game programmer to use all the sub-systems of SDL seamlessly in conjunction with OpenGL to provide most effective games and gaming environments. In this article I will discuss how to use SDL and OpenGL together where gaming infrastructure is provided by SDL and animation as well as rendering is being handled by OpenGL. The first section would discuss the steps required to integrate OpenGL with SDL. The second section would utilize the pointers provided in the first section to create an application having animation(basic) using OpenGL. That is the agenda for the current discussion.</p>
<p><strong>Initialization- Bringing OpenGL into Picture:</strong></p>
<p><strong> </strong></p>
<p>In SDL all the sub-systems are initialized via SDL_Init(). OpenGL, being a part of graphics subsystem, is not directly initialized in this manner. For initializing OpenGL following are the steps:</p>
<p>1. Set OpenGL Attributes</p>
<p>2. Specify use of Double Buffering</p>
<p>3. Set the Video Mode</p>
<p>Of these second one is optional as it is used only when double buffering is a requirement. Lets have a detailed look at all of them.</p>
<p>1. Setting the OpenGL Attributes:</p>
<p>Before initializing the video, it is better to set up the OpenGL. These attributes are passed to the OpenGL via SDL calling the SDL_GL_SetAttribute() function. The parameters are the OpenGL attribute and their values. The most common attributes passed to this function are:</p>
<p>i. SDL_GL_RED_SIZE:</p>
<p>It sets the size of the red component of the frame buffer. The value is in bits. The commonly used value is 5. Similar parameters exist for blue and green components which are SDL_GL_BLUE_SIZE and SDL_GL_GREEN_SIZE respectively. To set green component to a bit value of 4 the code would be:</p>
<p>SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 4 );</p>
<p>ii. SDL_GL_BUFFER_SIZE:</p>
<p>To set the size of the frame buffer this attribute is passed with the required Buffer size in bits. It is greater than or equal to the combined value i.e. sum of the red, green, blue and alpha components. If the requirement is 24 bit color depth and alpha channel of 32-bits then each color component must be given the size value as 8 and frame buffer must be given size as 32. In code it would be:</p>
<p>SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );</p>
<p>SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );</p>
<p>SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE,8 );</p>
<p>SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 );</p>
<p>iii. SDL_GL_DEPTH_SIZE:</p>
<p>This attribute controls the size of depth buffer or Z buffers. Normally the graphics cards provide 16-bit or 24-bit depth. If the value is set more than what is available, the operation will fail. To make it more clear following is the code:</p>
<p>SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,16);</p>
<p>iv. SDL_GL_ACCUM_RED_SIZE:</p>
<p>To set the size of red component of accumulation buffer, this attribute is used.</p>
<p>The value is specified in bits. SDL_GL_ACCUM_BLUE_SIZE, SDL_GL_ACCUM_GREEN_SIZE controls the size of blue and green component of accumulation buffer. In code it would be:</p>
<p>SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE,5);</p>
<p>The question that would be arising in your mind would be that whether these attributes could be set after initializing the video mode. The answer is no. The reason is that these settings have to be initialized before invoking and configuring video mode. Next we have to setup the video mode.</p>
<p>2. Setting up double buffering:</p>
<p>This aspect has also to be covered before setting up the video mode as this     attribute goes as a flag parameter to the SDL_GL_SetAttribute. The attribute is     SDL_GL_DOUBLEBUFFER and the value is either 1 or 0. The point to be kept in     mind is that when working in conjunction with OpenGL, the flag specifying double     buffer must be passed as an attribute to the SDL_GL_SetAttribute function and not to the SDL_Set_VideoMode(). In code this would be:</p>
<p>SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,1);</p>
<p>would set the double buffering to one state.</p>
<p>3. Setting the Video Mode:</p>
<p>Once the OpenGL attributes are set, setting the video mode is similar to the     setting of video mode as described in last tutorials. For more details have a look     at Part-II of the tutorial. The only difference comes in flags being sent to the     SDL_Set_VideoMode(). Apart from other required flags the SDL_OPENGL would     also be set i.e.</p>
<p>int flags=0;</p>
<p>flags= SDL_OPENGL | SDL_FULLSCREEN;</p>
<p>setting the SDL_OPENGL flag is a must.</p>
<p>That’s all there about the required steps. Now let the OpenGL play.</p>
<p><strong>OpenGL in Action:</strong></p>
<p>The theory is over. Its now time to see some real action. The example application would render a rotating triangle. The includes will contain one more header file.</p>
<p>#include &lt;SDL/SDL.h&gt;</p>
<p><strong>#include &lt;gl/gl.h&gt;</strong></p>
<p><strong> </strong></p>
<p>gl.h contains function declarations necessary to work with OpenGL.</p>
<p>Next comes the main() and OpenGL attributes.</p>
<p><strong>int main(int argc, char *argv[])</strong></p>
<p><strong>{</strong></p>
<p><strong>  SDL_Event event;</strong></p>
<p><strong>  float theta = 0.0f;</strong></p>
<p><strong>  SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );</strong></p>
<p><strong>  SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );</strong></p>
<p><strong>  SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE,8 );        </strong></p>
<p><strong>  SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 );</strong></p>
<p><strong> </strong></p>
<p>:</p>
<p>:</p>
<p><strong>}</strong></p>
<p>Next initialize the video and video mode</p>
<p><strong> </strong></p>
<p>int main(int argc, char *argv[])</p>
<p>{</p>
<p>SDL_Event event;</p>
<p>float theta = 0.0f;</p>
<p>SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );</p>
<p>SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );</p>
<p>SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE,8 );</p>
<p>SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 );</p>
<p><strong>SDL_Init(SDL_INIT_VIDEO);</strong></p>
<p><strong>  SDL_SetVideoMode(600, 300, 0, SDL_OPENGL | SDL_HWSURFACE |  </strong></p>
<p><strong>                               SDL_NOFRAME);</strong></p>
<p>:</p>
<p>:</p>
<p>}</p>
<p><strong> </strong></p>
<p>The video is initialized to 600&#215;300 resolutions. And the hardware rendering mode is being used. This is done by SDL_HWSURFACE flag. Hence OpenGL would write on the graphic card’s memory instead of mapping it to software memory. After this step, the territory of OpenGL starts.</p>
<p><strong> </strong></p>
<p>int main(int argc, char *argv[])</p>
<p>{</p>
<p>SDL_Event event;</p>
<p>float theta = 0.0f;</p>
<p>SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );</p>
<p>SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );</p>
<p>SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE,8 );</p>
<p>SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 );</p>
<p>SDL_Init(SDL_INIT_VIDEO);</p>
<p>SDL_SetVideoMode(600, 300, 0, SDL_OPENGL | SDL_HWSURFACE |</p>
<p>SDL_NOFRAME);</p>
<p><strong>glViewport(0, 0, 600, 300);</strong></p>
<p><strong>  glClearColor(0.0f, 0.0f, 0.0f, 0.0f);</strong></p>
<p><strong>  glClearDepth(1.0);</strong></p>
<p><strong>  glDepthFunc(GL_LESS);</strong></p>
<p><strong>  glEnable(GL_DEPTH_TEST);</strong></p>
<p><strong>  glShadeModel(GL_SMOOTH);</strong></p>
<p><strong>  glMatrixMode(GL_PROJECTION);</strong></p>
<p><strong>  glMatrixMode(GL_MODELVIEW);</strong></p>
<p>:</p>
<p>:</p>
<p>}</p>
<p>to start working with OpenGL, the view port is initialized. Then the screen is cleared or rendered with the specified background color. Since the triangle would be rotating in 3D space hence the depth has to be set and depth testing has to be enabled. If smooth shading is not used, then the edges would seem jagged. Hence smooth shading model is used. This completes the setting up of OpenGL parameters after SDL video initialization. Drawing and rotation is taken care by the following code in bold:</p>
<p>int main(int argc, char *argv[])</p>
<p>{</p>
<p>SDL_Event event;</p>
<p>float theta = 0.0f;</p>
<p>SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );</p>
<p>SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );</p>
<p>SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE,8 );</p>
<p>SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 );</p>
<p>SDL_Init(SDL_INIT_VIDEO);</p>
<p>SDL_SetVideoMode(600, 300, 0, SDL_OPENGL | SDL_HWSURFACE |</p>
<p>SDL_NOFRAME);</p>
<p>glViewport(0, 0, 600, 300);</p>
<p>glClearColor(0.0f, 0.0f, 0.0f, 0.0f);</p>
<p>glClearDepth(1.0);</p>
<p>glDepthFunc(GL_LESS);</p>
<p>glEnable(GL_DEPTH_TEST);</p>
<p>glShadeModel(GL_SMOOTH);</p>
<p>glMatrixMode(GL_PROJECTION);</p>
<p>glMatrixMode(GL_MODELVIEW);</p>
<p><strong>int done;</strong></p>
<p><strong>  for(done = 0; !done;)</strong></p>
<p><strong> {</strong></p>
<p><strong>    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);</strong></p>
<p><strong> </strong></p>
<p><strong>    glLoadIdentity();</strong></p>
<p><strong>    glTranslatef(0.0f,0.0f,0.0f);</strong></p>
<p><strong>    glRotatef(theta, 0.0f, 0.0f, 1.0f);</strong></p>
<p><strong>   </strong>:</p>
<p>:</p>
<p>}</p>
<p>}</p>
<p>The focus is brought to the point of origin by translating it. Then rotation function is provided the theta value through which the triangle has to be rotated.</p>
<p>int main(int argc, char *argv[])</p>
<p>{</p>
<p>SDL_Event event;</p>
<p>float theta = 0.0f;</p>
<p>SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );</p>
<p>SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );</p>
<p>SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE,8 );</p>
<p>SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 );</p>
<p>SDL_Init(SDL_INIT_VIDEO);</p>
<p>SDL_SetVideoMode(600, 300, 0, SDL_OPENGL | SDL_HWSURFACE |</p>
<p>SDL_NOFRAME);</p>
<p>glViewport(0, 0, 600, 300);</p>
<p>glClearColor(0.0f, 0.0f, 0.0f, 0.0f);</p>
<p>glClearDepth(1.0);</p>
<p>glDepthFunc(GL_LESS);</p>
<p>glEnable(GL_DEPTH_TEST);</p>
<p>glShadeModel(GL_SMOOTH);</p>
<p>glMatrixMode(GL_PROJECTION);</p>
<p>glMatrixMode(GL_MODELVIEW);</p>
<p>int done;</p>
<p>for(done = 0; !done;)</p>
<p>{</p>
<p>glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);</p>
<p>glLoadIdentity();</p>
<p>glTranslatef(0.0f,0.0f,0.0f);</p>
<p>glRotatef(theta, 0.0f, 0.0f, 1.0f);</p>
<p><strong>glBegin(GL_TRIANGLES);</strong></p>
<p><strong>    glColor3f(1.0f, 0.0f, 0.0f);</strong></p>
<p><strong>    glVertex2f(0.0f, 1.0f);</strong></p>
<p><strong>    glColor3f(0.0f, 1.0f, 0.0f);</strong></p>
<p><strong>    glVertex2f(0.87f, -0.5f);</strong></p>
<p><strong>    glColor3f(0.0f, 0.0f, 1.0f);</strong></p>
<p><strong>    glVertex2f(-0.87f, -0.5f);</strong></p>
<p><strong>    glEnd();</strong></p>
<p><strong> </strong></p>
<p><strong>    theta += .5f;</strong></p>
<p><strong>    SDL_GL_SwapBuffers();</strong></p>
<p><strong>   </strong>:</p>
<p>:</p>
<p>}</p>
<p>}</p>
<p>The triangle is drawn by specifying the vertices. Then the theta value is increased. Next event handling part cometh.</p>
<p>int main(int argc, char *argv[])</p>
<p>{</p>
<p>SDL_Event event;</p>
<p>float theta = 0.0f;</p>
<p>SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );</p>
<p>SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );</p>
<p>SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE,8 );</p>
<p>SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 );</p>
<p>SDL_Init(SDL_INIT_VIDEO);</p>
<p>SDL_SetVideoMode(600, 300, 0, SDL_OPENGL | SDL_HWSURFACE |</p>
<p>SDL_NOFRAME);</p>
<p>glViewport(0, 0, 600, 300);</p>
<p>glClearColor(0.0f, 0.0f, 0.0f, 0.0f);</p>
<p>glClearDepth(1.0);</p>
<p>glDepthFunc(GL_LESS);</p>
<p>glEnable(GL_DEPTH_TEST);</p>
<p>glShadeModel(GL_SMOOTH);</p>
<p>glMatrixMode(GL_PROJECTION);</p>
<p>glMatrixMode(GL_MODELVIEW);</p>
<p>int done;</p>
<p>for(done = 0; !done;)</p>
<p>{</p>
<p>glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);</p>
<p>glLoadIdentity();</p>
<p>glTranslatef(0.0f,0.0f,0.0f);</p>
<p>glRotatef(theta, 0.0f, 0.0f, 1.0f);</p>
<p><strong> </strong>glBegin(GL_TRIANGLES);</p>
<p>glColor3f(1.0f, 0.0f, 0.0f);</p>
<p>glVertex2f(0.0f, 1.0f);</p>
<p>glColor3f(0.0f, 1.0f, 0.0f);</p>
<p>glVertex2f(0.87f, -0.5f);</p>
<p>glColor3f(0.0f, 0.0f, 1.0f);</p>
<p>glVertex2f(-0.87f, -0.5f);</p>
<p>glEnd();</p>
<p>theta += .5f;</p>
<p>SDL_GL_SwapBuffers();</p>
<p><strong>SDL_PollEvent(&amp;event);</strong></p>
<p><strong>    if(event.key.keysym.sym == SDLK_ESCAPE)</strong></p>
<p><strong>      done = 1;</strong></p>
<p>}</p>
<p>}</p>
<p>That’s it. This is how SDL and OpenGL work together. The only piece missing in this puzzle is sound. It will be tackled in the next part which incidentally is the last part of this series. So till next time.</p>
<br />Filed under: <a href='http://aprajshekhar.wordpress.com/category/sdl/'>SDL</a> Tagged: <a href='http://aprajshekhar.wordpress.com/tag/cc/'>C/C++</a>, <a href='http://aprajshekhar.wordpress.com/tag/game-programming/'>game-programming</a>, <a href='http://aprajshekhar.wordpress.com/tag/linux/'>Linux</a>, <a href='http://aprajshekhar.wordpress.com/tag/programming/'>programming</a>, <a href='http://aprajshekhar.wordpress.com/tag/sdl/'>SDL</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/aprajshekhar.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/aprajshekhar.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/aprajshekhar.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/aprajshekhar.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/aprajshekhar.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/aprajshekhar.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/aprajshekhar.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/aprajshekhar.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/aprajshekhar.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/aprajshekhar.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/aprajshekhar.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/aprajshekhar.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/aprajshekhar.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/aprajshekhar.wordpress.com/150/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=aprajshekhar.wordpress.com&amp;blog=5963225&amp;post=150&amp;subd=aprajshekhar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://aprajshekhar.wordpress.com/2011/07/16/sdl-programming-in-linux-sdl-opengl-brothers-in-gaming/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/655da95aab86392587def3f9196de1ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">aprajshekhar</media:title>
		</media:content>
	</item>
		<item>
		<title>SDL Programming in Linux &#8211; Events And Raw Graphics</title>
		<link>http://aprajshekhar.wordpress.com/2011/07/16/sdl-programming-in-linux-event/</link>
		<comments>http://aprajshekhar.wordpress.com/2011/07/16/sdl-programming-in-linux-event/#comments</comments>
		<pubDate>Sat, 16 Jul 2011 10:23:17 +0000</pubDate>
		<dc:creator>AP Rajshekhar</dc:creator>
				<category><![CDATA[SDL]]></category>
		<category><![CDATA[C/C++]]></category>
		<category><![CDATA[game-programming]]></category>
		<category><![CDATA[graphics-programming]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://aprajshekhar.wordpress.com/?p=143</guid>
		<description><![CDATA[Graphics and handling user inputs- the combination that creates the symphony called game. A world (of game) where these two are out of phase ends in cacophony. In the last article I discussed about the various parameters that goes into creating a screen and loading bitmapped images on to the screen. That was pretty high-level [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=aprajshekhar.wordpress.com&amp;blog=5963225&amp;post=143&amp;subd=aprajshekhar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Graphics and handling user inputs- the combination that creates the symphony called game. A world (of game) where these two are out of phase ends in cacophony. In the last article I discussed about the various parameters that goes into creating a screen and loading bitmapped images on to the screen. That was pretty high-level as the work was done on structures that represent the actual screen and maps or sprites. But there are times when one has to get his/her hand dirty by working directly upon pixels. The creators of SDL had already anticipated this requirement and built the capacities to work at raw graphics level into the core itself. Thus developer is redeemed from understanding system, platform and architecture specific nitty-gritty about manipulating the pixels. The other aspect of gaming that gives sleepless nights to developers is handling the user input, as the handling of input devices changes from system to system. To remove this burden from the minds of the developers, SDL provides object-oriented approach in handling the events. In this article, I would be discussing these two aspects of SDL. In the first section, the discussion would focus on using pixel manipulation functions and their usages and the second section would focus on input handling. So now that the agenda for this article have been laid down lets get started.   <strong>Raw Graphics-Writing Directly onto the Display:</strong>  Though the SDL Graphics APIs provide pretty high level functionality abstracting off all the low-level details, yet, there are times when abstraction is not required. For this purpose also there are ways. These ways doesn’t exist as a library function but as separate functions that has to be embedded into your program. The functions are freely available. But for the completeness I am including them here. These functions are:</p>
<ol start="1">
<li>getpixel():</li>
</ol>
<p>This function is useful if pixel value have to be obtained from a given coordinates represented by X and Y values on the display. It works on a single pixel at a time. The first parameter is the surface from which the value has to be obtained. This is represented by a pointer to the SDL_Surface. The next two integer parameters represent the x and y coordinates from where the pixel value has to be obtained. The return value is an Uint32 representing the value of the pixel. Following is the code: <strong> </strong> <strong>/*</strong> <strong> * Return the pixel value at (x, y)</strong> <strong> * NOTE: The surface must be locked before calling this!</strong> <strong> */</strong> <strong>Uint32 getpixel(SDL_Surface *surface, int x, int y)</strong> <strong>{</strong> <strong>    int bpp = surface-&gt;format-&gt;BytesPerPixel;</strong> <strong>    /* Here p is the address to the pixel we want to retrieve */</strong> <strong>    Uint8 *p = (Uint8 *)surface-&gt;pixels + y * surface-&gt;pitch + x * bpp;</strong> <strong> </strong> <strong>    switch(bpp) {</strong> <strong>    case 1:</strong> <strong>        return *p;</strong> <strong> </strong> <strong>    case 2:</strong> <strong>        return *(Uint16 *)p;</strong> <strong> </strong> <strong>    case 3:</strong> <strong>        if(SDL_BYTEORDER == SDL_BIG_ENDIAN)</strong> <strong>            return p[0] &lt;&lt; 16 | p[1] &lt;&lt; 8 | p[2];</strong> <strong>        else</strong> <strong>            return p[0] | p[1] &lt;&lt; 8 | p[2] &lt;&lt; 16;</strong> <strong> </strong> <strong>    case 4:</strong> <strong>        return *(Uint32 *)p;</strong> <strong> </strong> <strong>    default:</strong> <strong>        return 0;       /* shouldn&#8217;t happen, but avoids warnings */</strong> <strong>    }</strong> <strong>}</strong>   The first thing to be done is to obtain the depth represented by BytesPerPixel. It is done by the first statement: <strong>int bpp = surface-&gt;format-&gt;BytesPerPixel;</strong> <strong> </strong> Next statement is self explanatory. To get the address of the pixel, the pitch of the of the passed surface is multiplied by the value of Y- coordinate, the depth is multiplied by the X- coordinate and the resulting values are added with pixel data of the surface represented by pixels member of SDL_Surface. This calculation provides the actual address of the pixel. The SDL_Surface could be thought of as multi dimensional array. Hence the value could be accessed as row-major and column-major format. That is done in the second statement: <strong>Uint8 *p = (Uint8 *)surface-&gt;pixels + y * surface-&gt;pitch + x * bpp;</strong> <strong> </strong>As the value returned by BytesPerPixels ranges from 1-4 according to the bytes needed to represent the pixel, it can be used for returning the values in the corresponding format i.e. 8, 16, 24 or 32. this is achieved by the switch-case block. That’s all about getpixel function.</p>
<ol start="2">
<li>putpixel():</li>
</ol>
<p>This is same as getpixel(). Apart from the parameters accepted by getpixel() function, this accepts one parameter extra- the address where the value has to be put. Following is the code for putpixel():   <strong>/*</strong> <strong> * Set the pixel at (x, y) to the given value</strong> <strong> * NOTE: The surface must be locked before calling this!</strong> <strong> */</strong> <strong>void putpixel(SDL_Surface *surface, int x, int y, Uint32 pixel)</strong> <strong>{</strong> <strong>    int bpp = surface-&gt;format-&gt;BytesPerPixel;</strong> <strong>    /* Here p is the address to the pixel we want to set */</strong> <strong>    Uint8 *p = (Uint8 *)surface-&gt;pixels + y * surface-&gt;pitch + x * bpp;</strong> <strong> </strong> <strong>    switch(bpp) {</strong> <strong>    case 1:</strong> <strong>        *p = pixel;</strong> <strong>        break;</strong> <strong> </strong> <strong>    case 2:</strong> <strong>        *(Uint16 *)p = pixel;</strong> <strong>        break;</strong> <strong> </strong> <strong>    case 3:</strong> <strong>        if(SDL_BYTEORDER == SDL_BIG_ENDIAN) {</strong> <strong>            p[0] = (pixel &gt;&gt; 16) &amp; 0xff;</strong> <strong>            p[1] = (pixel &gt;&gt; <img src='http://s0.wp.com/wp-includes/images/smilies/icon_cool.gif' alt='8)' class='wp-smiley' /> &amp; 0xff;</strong> <strong>            p[2] = pixel &amp; 0xff;</strong> <strong>        } else {</strong> <strong>            p[0] = pixel &amp; 0xff;</strong> <strong>            p[1] = (pixel &gt;&gt; <img src='http://s0.wp.com/wp-includes/images/smilies/icon_cool.gif' alt='8)' class='wp-smiley' /> &amp; 0xff;</strong> <strong>            p[2] = (pixel &gt;&gt; 16) &amp; 0xff;</strong> <strong>        }</strong> <strong>        break;</strong> <strong> </strong> <strong>    case 4:</strong> <strong>        *(Uint32 *)p = pixel;</strong> <strong>        break;</strong> <strong>    }</strong> <strong>}</strong>   The working of putpixel() is almost opposite to that of getpixel(). In case of later, the returned value is pixel value corresponding to the coordinates whereas the later places the pixel value according the coordinates. For this first the BytesPerPixel of the passed SDL_Suface is extracted just like before. Then pixel’s address (or pixel value) is calculated and according to the value returned by BytesPerPixels the value is placed. Since the calculated value is address of the pixel, hence the passed pixel value can be directly assigned and the display will be getting the new value.   Now that both the functions have been explained, lets see how to put one them to use i.e. putpixel(). For this I am defining a method called <strong><em>putyellowpixel()</em></strong> that places a yellow pixel at the center of the screen. It doesn’t accept any parameter nor does it returns any value.   <strong>void putyellowpixel()</strong> <strong>{</strong> <strong>    int x, y;</strong> <strong>    Uint32 yellow;</strong> <strong> </strong> <strong>    /* Map the color yellow to this display (R=0xff, G=0xFF, B=0&#215;00)</strong> <strong>       Note:  If the display is palettized, you must set the palette first.</strong> <strong>    */</strong> <strong>    yellow = SDL_MapRGB(screen-&gt;format, 0xff, 0xff, 0&#215;00);</strong> <strong> </strong> <strong>    x = screen-&gt;w / 2;</strong> <strong>    y = screen-&gt;h / 2;</strong> <strong> </strong> <strong>    /* Lock the screen for direct access to the pixels */</strong> <strong>    if ( SDL_MUSTLOCK(screen) ) {</strong> <strong>        if ( SDL_LockSurface(screen) &lt; 0 ) {</strong> <strong>            fprintf(stderr, &#8220;Can&#8217;t lock screen: %s\n&#8221;, SDL_GetError());</strong> <strong>            return;</strong> <strong>        }</strong> <strong>    }</strong> <strong> </strong> <strong>    putpixel(screen, x, y, yellow);</strong> <strong> </strong> <strong>    if ( SDL_MUSTLOCK(screen) ) {</strong> <strong>        SDL_UnlockSurface(screen);</strong> <strong>    }</strong> <strong>    /* Update just the part of the display that we&#8217;ve changed */</strong> <strong>    SDL_UpdateRect(screen, x, y, 1, 1);</strong> <strong> </strong> <strong>    return;</strong> <strong> </strong> <strong>}</strong>   To get the yellow color, the SDL_MapRGB() has to be used. The SDL_PixelFormat is the first parameter. It stores surface format information. Next three parameters correspond to the red, blue and green components of the color. The return value is the actual color corresponding to the passed color components in hexadecimal format as follows: <strong>yellow = SDL_MapRGB(screen-&gt;format, 0xff, 0xff, 0&#215;00);</strong>   Once the color has been retrieved, the next step is to get the required x and y coordinates which is achieved by the following statement: <strong>x = screen-&gt;w / 2;</strong> <strong>y = screen-&gt;h / 2;</strong> then screen surface is locked. If this is not done, then corruption of the SDL_Surface structure could get corrupted causing instability of the game as putpixel works on the address of pixel directly. This is done by:   <strong>SDL_MUSTLOCK(screen);</strong> <strong> </strong> The next step is to call the putpixel. Once putpixel has returned, then unlock the surface and update the surface. That completes placing a pixel directly on to the surface. Next section would focus on even handling with reference to keyboard.   <strong>Handling the Key Board- the SDL way:</strong>Whatever has been discussed till now completes only one aspect of providing interactivity. Even now the application doesn’t have the ability to handle user gestures provided through different input devices such as keyboard, joy stick etc. So now the focus would be on the input handling. Two of the most common input devices are mouse and keyboard. SDL has wrappers for each of these. In this section I would be discussing about keyboard handling. Before entering the world of keyboard events, it is better to understand the most recurring structures in keyboard handling jargon. They are:</p>
<ol start="1">
<li>SDLKey:</li>
</ol>
<p>It is an enumerated type that represents various keys. For example SDLK_a represents lowercase ‘a’, SDLK_DELETE is for ‘delete’ key and so on.</p>
<ol start="2">
<li>SDLMod:</li>
</ol>
<p>SDLKey enumeration represents only keys. To represent key modifiers such as Shift and Ctrl, SDLMod enumeration is provided by the SDL. The KMOD_CAPS is one of the enumeration that can be used to find out whether caps key is down or not. Other modifiers also have representations in SDLMod.</p>
<ol start="3">
<li>SDL_keysym:</li>
</ol>
<p>It is a structure that contains the information of a key-press. The members of this structure include scan code in hardware dependent format, SDLKey value of the pressed key in sym field, the value of modifier key in mod field and the Unicode representation of the key in Unicode field.</p>
<ol start="4">
<li>SDL_KeyboardEvent:</li>
</ol>
<p>From the name itself it is obvious that this structure describes a keyboard event. The first member, <em>type</em>, tells that the event is key release or key press event. The second member gives the same info as the first but uses different values. The last member is a structure itself- the SDL_keysym structure.   Now that the structures have been brought into the picture, the next step is to use these in handling the keyboard events. For this the logic is simple. The SDL_PollEvent is used to read the events. This is placed within the while loop. Then the value of <em>type</em> member of SDL_Event variable, passed as the parameter to SDL_PollEvent, is checked to find the type of event and then event processing can be done. In code it is thus:   <strong>SDL_Event event;</strong> <strong>  .</strong> <strong>  .</strong> <strong>  /* Poll for events. SDL_PollEvent() returns 0 when there are no  */</strong> <strong>  /* more events on the event queue, our while loop will exit when */</strong> <strong>  /* that occurs.                                                  */</strong> <strong>  while( SDL_PollEvent( &amp;event ) ){</strong> <strong>    /* We are only worried about SDL_KEYDOWN and SDL_KEYUP events */</strong> <strong>    switch( event.type ){</strong> <strong>      case SDL_KEYDOWN:</strong> <strong>        printf( &#8220;Key press detected\n&#8221; );</strong> <strong>        break;</strong> <strong> </strong> <strong>      case SDL_KEYUP:</strong> <strong>        printf( &#8220;Key release detected\n&#8221; );</strong> <strong>        break;</strong> <strong> </strong> <strong>      default:</strong> <strong>        break;</strong> <strong>    }</strong> <strong>  }</strong> <strong>  .</strong> <strong>  . </strong>   If this is used this in the program developed in last article, the exit condition of the program can be controlled. The new version would exit only at key press.     void display_bmp(char *file_name) { SDL_Surface *image;   /* Load the BMP file into a surface */ image = SDL_LoadBMP(file_name); if (image == NULL) { fprintf(stderr, &#8220;Couldn&#8217;t load %s: %s\n&#8221;, file_name, SDL_GetError()); return; }   /* * Palettized screen modes will have a default palette (a standard * 8*8*4 colour cube), but if the image is palettized as well we can * use that palette for a nicer colour matching */ if (image-&gt;format-&gt;palette &amp;&amp; screen-&gt;format-&gt;palette) { SDL_SetColors(screen, image-&gt;format-&gt;palette-&gt;colors, 0, image-&gt;format-&gt;palette-&gt;ncolors); }   /* Blit onto the screen surface */ if(SDL_BlitSurface(image, NULL, screen, NULL) &lt; 0) fprintf(stderr, &#8220;BlitSurface error: %s\n&#8221;, SDL_GetError());   SDL_UpdateRect(screen, 0, 0, image-&gt;w, image-&gt;h);   /* Free the allocated BMP surface */ SDL_FreeSurface(image); }   int main(int argc,char* argv[]) { /*variable to hold the file name of the image to be loaded *In real world error  handling  code would precede this                                                                          */ char* filename=”Tux.bmp”; /*The following code does the initialization for Audio and Video*/ int i_error=SDL_Init(SDL_INIT_VIDEO); /*If initialization is unsuccessful, then quit */ if(i_error==-1) exit(1); atexit(SDL_Quit); /* * Initialize the display in a 640&#215;480 8-bit palettized mode, * requesting a software surface */ screen = SDL_SetVideoMode(640, 480, 8, SDL_SWSURFACE); if ( screen == NULL ) { fprintf(stderr, &#8220;Couldn&#8217;t set 640x480x8 video mode: %s\n&#8221;, SDL_GetError()); exit(1); }   <strong>/*Handle the keyboards events here. Catch the SDL_Quit event to exit*/</strong> <strong>done = 0;</strong> <strong>             while (!done)</strong> <strong>            {</strong> <strong>               SDL_Event event;</strong> <strong> </strong> <strong>              /* Check for events */</strong> <strong>        while (SDL_PollEvent (&amp;event))</strong> <strong>             {</strong> <strong>            switch (event.type)</strong> <strong>            {</strong> <strong>                          case SDL_KEYDOWN:</strong> <strong>                break;</strong> <strong>                          case SDL_QUIT:</strong> <strong>                            done = 1;</strong> <strong>                           break;</strong> <strong>            default:</strong> <strong>                          break;</strong> <strong>            }</strong> <strong>        } </strong> /* Now call the function to load the image and copy it to the screen surface*/ load_bmp(filename); }   If you run the above code the window wont be closed until the close button is pressed. Though, this code does nothing much in area of interactivity but it’s a beginning. So as you can see, it is really easy to handle keyboard events using SDL. It totally removes the dependence of developer on Operating System for event handling. Also working at raw graphics level is not that difficult.   This brings us to the end of the third part of SDL programming. The next part would cover using OpenGL with SDL. Also using timers would be covered. Till next time.</p>
<br />Filed under: <a href='http://aprajshekhar.wordpress.com/category/sdl/'>SDL</a> Tagged: <a href='http://aprajshekhar.wordpress.com/tag/cc/'>C/C++</a>, <a href='http://aprajshekhar.wordpress.com/tag/game-programming/'>game-programming</a>, <a href='http://aprajshekhar.wordpress.com/tag/graphics-programming/'>graphics-programming</a>, <a href='http://aprajshekhar.wordpress.com/tag/linux/'>Linux</a>, <a href='http://aprajshekhar.wordpress.com/tag/programming/'>programming</a>, <a href='http://aprajshekhar.wordpress.com/tag/sdl/'>SDL</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/aprajshekhar.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/aprajshekhar.wordpress.com/143/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/aprajshekhar.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/aprajshekhar.wordpress.com/143/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/aprajshekhar.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/aprajshekhar.wordpress.com/143/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/aprajshekhar.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/aprajshekhar.wordpress.com/143/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/aprajshekhar.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/aprajshekhar.wordpress.com/143/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/aprajshekhar.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/aprajshekhar.wordpress.com/143/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/aprajshekhar.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/aprajshekhar.wordpress.com/143/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=aprajshekhar.wordpress.com&amp;blog=5963225&amp;post=143&amp;subd=aprajshekhar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://aprajshekhar.wordpress.com/2011/07/16/sdl-programming-in-linux-event/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/655da95aab86392587def3f9196de1ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">aprajshekhar</media:title>
		</media:content>
	</item>
		<item>
		<title>Sockets in Python:  Into the world of Python Network Programming</title>
		<link>http://aprajshekhar.wordpress.com/2011/02/28/sockets-in-python-into-the-world-of-python-network-programming/</link>
		<comments>http://aprajshekhar.wordpress.com/2011/02/28/sockets-in-python-into-the-world-of-python-network-programming/#comments</comments>
		<pubDate>Mon, 28 Feb 2011 15:02:00 +0000</pubDate>
		<dc:creator>AP Rajshekhar</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[socket]]></category>

		<guid isPermaLink="false">http://aprajshekhar.wordpress.com/?p=135</guid>
		<description><![CDATA[“Code less ..Achieve more” is the prime philosophy behind the development of all the Very High Level Languages (or VHLL in short). But less no. of lines should not mean reduced flexibility in terms of choosing an approach in solving a problem. Though many of the VHLL or Scripting Languages as they are popularly known, does not keep in mind the flexibility, yet there area few that have the logic of flexibility and choice as their core. Python is one of them. This fact is evident if one tries to do network programming in Python. The choices are aplenty for the programmer. The choices range from low-level sockets or raw-sockets to a completely extensible and functional web-server. In this tutorial I will be discussing how to use raw sockets to create network oriented applications in Python. <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=aprajshekhar.wordpress.com&amp;blog=5963225&amp;post=135&amp;subd=aprajshekhar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>“Code less ..Achieve more” is the prime philosophy behind the development of all the Very High Level Languages (or VHLL in short). But less no. of lines should not mean reduced flexibility in terms of choosing an approach in solving a problem. Though many of the VHLL or Scripting Languages as they are popularly known, does not keep in mind the flexibility, yet there area few that have the logic of flexibility and choice as their core. Python is one of them. This fact is evident if one tries to do network programming in Python. The choices are aplenty for the programmer. The choices range from low-level sockets or raw-sockets to a completely extensible and functional web-server. In this tutorial I will be discussing how to use raw sockets to create network oriented applications in Python. The first section will cover the basics of the socket module and by the end of the section a simple echo server will be coded. In the second section the echo server would be enhanced by making it capable of serving multiple clients using the concepts introduced in the first section.</p>
<p>&nbsp;</p>
<p><strong>Sockets and Ports- Doing it the Python way:</strong></p>
<p><strong> </strong></p>
<p>Sockets and ports form the core of any network oriented application. According to the formal definition a socket is “An endpoint of communication to which a name may be bound”. The concept (as well as implementation) comes from the BSD community. The 4.3BSD implementation defines three domains for the sockets:</p>
<ol>
<li>Unix Domain/ File-system Domain:</li>
</ol>
<p>The sockets under this domain are used when two or more processes within a system have to communicate with each other. In this domain, the sockets are created within the file system. They are represented as strings that contains local path such as /var/lock/sock or /tmp/sock.</p>
<p>&nbsp;</p>
<ol>
<li>Internet Domain:</li>
</ol>
<p>This domain represents the processes that communicate over the TCP/IP. The sockets created for this domain are represented using a (host, port) tuple. Here <em>host</em> is a fully qualified Internet host name that can be represented using a string or in the dotted decimal format (or IP address).</p>
<p><em> </em></p>
<ol>
<li>NS Domain:</li>
</ol>
<p>This domain is the one used by the processes communicating over Xerox protocol which is now obsolete.</p>
<p>&nbsp;</p>
<p>Of these only the first two are the most commonly used. Python supports all of these. My discussion would be limited to the Internet Domain. To create an application that uses TCP/IP sockets following are the steps:</p>
<p>&nbsp;</p>
<ol>
<li>Creating a socket</li>
<li>Connecting the socket</li>
<li>Binding the socket to an address</li>
<li>Listening and accepting connections</li>
<li>Transferring data/receiving data.</li>
</ol>
<p>&nbsp;</p>
<p>But before creating a socket libraries have to be imported. The <em>socket</em> module contains all that is needed to work with sockets. The imports can be done in two ways:</p>
<p><em>import socket</em> or <em>from socket import *. </em>If the first form is used then to access the methods of <em>socket </em>module, <em>socket.methodname() </em>would have to be used. If the later format is used, then the methods could be called without the fully qualified name. I will be using the second format for clarity of the code and ease. Now lets see the various provisions within socket module for the programmers.</p>
<p>&nbsp;</p>
<ol>
<li>Creating a socket:</li>
</ol>
<p>A socket can be created by making call to the socket() function. The socket() function returns a socket in the domain specified. The parameters to the function are:</p>
<p>&nbsp;</p>
<p>a. family:</p>
<p>The family parameter specifies in which domain the socket has to be created.  The valid values are AF_UNIX for UNIX domain and AF_INET for internet domain.</p>
<p>b. type:</p>
<p>Type defines the type of the protocol to be used. The type can be                   connection oriented like TCP or connection less like UDP. These are defined by the constants SOCK_STREAM for TCP, SOCK_DGRAM for UDP. Other valid parameters are SOCK RAW, SOCK SEQPACKET and SOCK RDM.</p>
<p>c. protocol:</p>
<p>This generally left for default value. The default is 0.</p>
<p>&nbsp;</p>
<p>So a socket for Internet domain is created thus:</p>
<p><strong>testsocket=socket(AF_INET,SOCK_STREAM)</strong></p>
<p>&nbsp;</p>
<ol>
<li>Connecting the Socket:</li>
</ol>
<p>Sockets thus created can be used on the server-side or client-side. To use the socket as client-socket it needs to be connected to a host. That can be done using the <em>connect() </em>method of the socket object. The connect() method accepts either the host name as the parameter or a tuple containing host name/address and port number as parameter. For example to connect to a host whose address is 192.168.51.100 and the port number 8080 the statement would be:</p>
<p>&nbsp;</p>
<p><strong>testsocket.connect((‘192.168.51.100’,8080))</strong></p>
<p>&nbsp;</p>
<ol>
<li>Binding the socket to an address:</li>
</ol>
<p>If the socket has to be used on the server side, then the socket has to be bound to an address and a port, thus naming it. To bind a socket to an address, the <em>bind() </em>method of the socket object has to be used. The valid parameter is a tuple containing the address to which the socket has to be bound and the port at which it has to listen for incoming requests. To use the same socket i.e. <em>testsocket</em> on the server side the statement would be:</p>
<p>&nbsp;</p>
<p><strong>testsocket.bind((‘192.168.51.100’,8080))</strong></p>
<p><strong> </strong></p>
<ol>
<li>Listening and accepting connections:</li>
</ol>
<p>Once a socket has been named, then it has to be instructed to listen at the given port for incoming requests. This can be done using the listen() method. The<em> listen</em> accepts a no. representing the maximum queued connection. The argument should be atleast 1. for example the following code sets the max queued connection to 2:</p>
<p>&nbsp;</p>
<p><strong>testsocket.listen(2)</strong></p>
<p><strong> </strong></p>
<p>The next thing to be done is to accept the incoming connection requests. This can be done by the <em>accept() </em>function. This function returns a tuple containing a new socket object representing the client and the address of the client. For example:</p>
<p><strong>clientsock,address= testsocket.accept()</strong></p>
<p>in the above statement clientsock would contains a new socket object and address would contain the address of the client.</p>
<p>&nbsp;</p>
<ol>
<li>Transferring data/receiving data:</li>
</ol>
<p>Data can be transferred using <em>recv()</em> and <em>send()</em> methods of socket object. Socket’s recv() method is used to receive the data send from the server or from the client. The parameters are a buffer size for the data , and flags. The flags parameter is optional. So to receive data the code would be:</p>
<p><strong>buff=1024</strong></p>
<p><strong>testsocket.recv(buff)</strong></p>
<p>&nbsp;</p>
<p>To send the data, a call to the send method is in order. The parameters are the data to be send and the flags. To elucidate  further:</p>
<p><strong> </strong></p>
<p><strong>data=raw_input(‘&gt;&gt;’)</strong></p>
<p><strong>testsocket.send(data)</strong></p>
<p><strong> </strong></p>
<p>Now that the steps are clear, lets create a simple echo server. First the imports</p>
<p><strong>from socket import * </strong></p>
<p><strong> </strong></p>
<p>Then the constants that defines the host, port, buffer size and the address tuple to be used with bind().</p>
<p>&nbsp;</p>
<p>from socket import *</p>
<p><strong>HOST = &#8216;localhost&#8217;</strong></p>
<p><strong>PORT = 21567</strong></p>
<p><strong>BUFSIZ = 1024</strong></p>
<p><strong>ADDR = (HOST, PORT)</strong></p>
<p>&nbsp;</p>
<p>Then create the server side socket and bind it to the host and the port. Then comes the max queue size to 2:</p>
<p>&nbsp;</p>
<p>from socket import *</p>
<p>HOST = &#8216;localhost&#8217;</p>
<p>PORT = 21567</p>
<p>BUFSIZ = 1024</p>
<p>ADDR = (HOST, PORT)</p>
<p><strong>serversock = socket(AF_INET, SOCK_STREAM)</strong></p>
<p><strong>serversock.bind(ADDR)</strong></p>
<p><strong>serversock.listen(2)</strong></p>
<p>&nbsp;</p>
<p>Now to make it listen for incoming requests continuously place the accept() method in a while loop. This is not the most preferable mode. The preferable way will be discussed in next section:</p>
<p>&nbsp;</p>
<p>from socket import *</p>
<p>HOST = &#8216;localhost&#8217;</p>
<p>PORT = 21567</p>
<p>BUFSIZ = 1024</p>
<p>ADDR = (HOST, PORT)</p>
<p>serversock = socket(AF_INET, SOCK_STREAM)</p>
<p>serversock.bind(ADDR)</p>
<p>serversock.listen(2)</p>
<p>&nbsp;</p>
<p><strong>while </strong><strong>1:</strong></p>
<p><strong>print </strong><strong>&#8216;waiting for connection…&#8217;</strong></p>
<p><strong> clientsock, addr = serversock.accept()</strong></p>
<p><strong> print &#8216;…connected from:&#8217;, addr</strong></p>
<p>:</p>
<p>:</p>
<p>Next  receive the data from the client and echo it back. This has to continue till the client doesn’t send the null data or ctrl+c. to achieve this again use a while loop and then close the connection when done.</p>
<p>&nbsp;</p>
<p>from socket import *</p>
<p>HOST = &#8216;localhost&#8217;</p>
<p>PORT = 21567</p>
<p>BUFSIZ = 1024</p>
<p>ADDR = (HOST, PORT)</p>
<p>serversock = socket(AF_INET, SOCK_STREAM)</p>
<p>serversock.bind(ADDR)</p>
<p>serversock.listen(2)</p>
<p>&nbsp;</p>
<p>while 1:</p>
<p>print &#8216;waiting for connection…&#8217;</p>
<p>clientsock, addr = serversock.accept()</p>
<p>print &#8216;…connected from:&#8217;, addr</p>
<p>&nbsp;</p>
<p><strong>while </strong><strong>1:</strong></p>
<p><strong>data = clientsock.recv(BUFSIZ)</strong></p>
<p><strong>if not </strong><strong>data: break </strong></p>
<p><strong>clientsock.send(‘echoed’, data)</strong></p>
<p>&nbsp;</p>
<p><strong>clientsock.close()</strong></p>
<p><strong> </strong></p>
<p><strong>serversock.close()</strong></p>
<p>&nbsp;</p>
<p>That’s all for the server. Now for the client. The only exception is that there is no bind(), accept() and listen().</p>
<p>&nbsp;</p>
<p><strong>from </strong><strong>socket import * </strong></p>
<p><strong> </strong></p>
<p><strong>HOST = &#8216;localhost&#8217;</strong></p>
<p><strong>PORT = 21567</strong></p>
<p><strong>BUFSIZ = 1024</strong></p>
<p><strong>ADDR = (HOST, PORT)</strong></p>
<p><strong> </strong></p>
<p><strong>tcpCliSock = socket(AF_INET, SOCK_STREAM)</strong></p>
<p><strong>tcpCliSock.connect(ADDR)</strong></p>
<p><strong> </strong></p>
<p><strong>while </strong><strong>1:</strong></p>
<p><strong> data = raw_input(&#8216;&gt; &#8216;)</strong></p>
<p><strong> if not data: break </strong></p>
<p><strong>tcpCliSock.send(data)</strong></p>
<p><strong>data = tcpCliSock.recv(1024)</strong></p>
<p><strong>if not </strong><strong>data: break </strong></p>
<p><strong> print data</strong></p>
<p><strong> </strong></p>
<p><strong>tcpCliSock.close()</strong></p>
<p><strong> </strong></p>
<p><strong> </strong></p>
<p><strong>Multi-Threaded Echo Server- Other Approach in Creating a Server:</strong></p>
<p>&nbsp;</p>
<p>In the above example the uses while loop to service different clients. For elucidations it is ok. But in the real world, it won’t work well. The reason is that more than one client cannot be served simultaneously by just while constructs. To overcome the limitations there are several strategies. One of them is making the server multi-threaded. There are two parts in the creation of a multi threaded server:</p>
<p>&nbsp;</p>
<ol>
<li>Create threads for each accepted  connections:</li>
</ol>
<p>This is the core of the multi-threaded server. For each accepted connection request, a different thread is created and the serving that particular client is carried out by an independent thread. Thus quick response time can be achieved.</p>
<p>&nbsp;</p>
<ol>
<li>Create a handler:</li>
</ol>
<p>It is the handler where the whole processing goes on. In our case transferring a file.</p>
<p>&nbsp;</p>
<p>To make the echo server some changes have to be made. It starts with the accept part as shown below:</p>
<p>&nbsp;</p>
<p>from socket import *</p>
<p>from threading import *</p>
<p>HOST = &#8216;localhost&#8217;</p>
<p>PORT = 21567</p>
<p>BUFSIZ = 1024</p>
<p>ADDR = (HOST, PORT)</p>
<p>serversock = socket(AF_INET, SOCK_STREAM)</p>
<p>serversock.bind(ADDR)</p>
<p>serversock.listen(2)</p>
<p>while 1:</p>
<p>print &#8216;waiting for connection…&#8217;</p>
<p>clientsock, addr = serversock.accept()</p>
<p>print &#8216;…connected from:&#8217;, addr</p>
<p><strong>thread.start_new_thread(handler, (clientsock, addr))</strong></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>serversock.close()</p>
<p>&nbsp;</p>
<p>After accepting the request a new thread is created for the client. This is done for each connection request. The logic of handling the client is defined within the handler which goes thus:</p>
<p>&nbsp;</p>
<p>from socket import *</p>
<p>from threading import *</p>
<p><strong>def handler(clientsock,addr):</strong></p>
<p><strong>while </strong><strong>1:</strong></p>
<p><strong>data = clientsock.recv(BUFSIZ)</strong></p>
<p><strong>if not </strong><strong>data: break </strong></p>
<p><strong>clientsock.send(‘echoed:..’, data)</strong></p>
<p>&nbsp;</p>
<p><strong>clientsock.close()</strong></p>
<p>if __name__==’__main__’:</p>
<p>HOST = &#8216;localhost&#8217;</p>
<p>PORT = 21567</p>
<p>BUFSIZ = 1024</p>
<p>ADDR = (HOST, PORT)</p>
<p>serversock = socket(AF_INET, SOCK_STREAM)</p>
<p>serversock.bind(ADDR)</p>
<p>serversock.listen(2)</p>
<p>&nbsp;</p>
<p>while 1:</p>
<p>print &#8216;waiting for connection…&#8217;</p>
<p>clientsock, addr = serversock.accept()</p>
<p>print &#8216;…connected from:&#8217;, addr</p>
<p>thread.start_new_thread(handler, (clientsock, addr))</p>
<p>#some other cleanup code if necessary</p>
<p>&nbsp;</p>
<p>The handler has to be defined before calling it. The handler contains the same code that was contained in the inner while loop previously. This example is not optimized. But it serves the purpose of providing a different approach for serving multiple clients. This brings us to the end of this section.</p>
<p>&nbsp;</p>
<p><strong>Parting Thoughts: </strong></p>
<p><strong> </strong></p>
<ol>
<li>The low level sockets can be mixed and      matched with other modules such as threads and forks to create a server      capable of serving multiple clients simultaneously.</li>
<li>While using threading approach the      locking and synchronization issues must be kept in mind.</li>
<li>The security measures must be taken      care of when creating FTP kind of servers.</li>
</ol>
<p>&nbsp;</p>
<p>This brings us to the end of this discussion. In the introductory section I mentioned flexibility as one of the core aspects of Python. Ability to work with low-level sockets is one of them. But at the other end of the spectrum are the pre-built yet extensible web-servers. These will be discussed in the near future. Till then…</p>
<br />Filed under: <a href='http://aprajshekhar.wordpress.com/category/python/'>Python</a> Tagged: <a href='http://aprajshekhar.wordpress.com/tag/programming/'>programming</a>, <a href='http://aprajshekhar.wordpress.com/tag/python/'>Python</a>, <a href='http://aprajshekhar.wordpress.com/tag/socket/'>socket</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/aprajshekhar.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/aprajshekhar.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/aprajshekhar.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/aprajshekhar.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/aprajshekhar.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/aprajshekhar.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/aprajshekhar.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/aprajshekhar.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/aprajshekhar.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/aprajshekhar.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/aprajshekhar.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/aprajshekhar.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/aprajshekhar.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/aprajshekhar.wordpress.com/135/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=aprajshekhar.wordpress.com&amp;blog=5963225&amp;post=135&amp;subd=aprajshekhar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://aprajshekhar.wordpress.com/2011/02/28/sockets-in-python-into-the-world-of-python-network-programming/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/655da95aab86392587def3f9196de1ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">aprajshekhar</media:title>
		</media:content>
	</item>
		<item>
		<title>2010 in review</title>
		<link>http://aprajshekhar.wordpress.com/2011/01/02/2010-in-review/</link>
		<comments>http://aprajshekhar.wordpress.com/2011/01/02/2010-in-review/#comments</comments>
		<pubDate>Sun, 02 Jan 2011 07:23:25 +0000</pubDate>
		<dc:creator>AP Rajshekhar</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://aprajshekhar.wordpress.com/?p=131</guid>
		<description><![CDATA[The stats helper monkeys at WordPress.com mulled over how this blog did in 2010, and here&#8217;s a high level summary of its overall blog health: The Blog-Health-o-Meter™ reads This blog is on fire!. Crunchy numbers A helper monkey made this abstract painting, inspired by your stats. A Boeing 747-400 passenger jet can hold 416 passengers. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=aprajshekhar.wordpress.com&amp;blog=5963225&amp;post=131&amp;subd=aprajshekhar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The stats helper monkeys at WordPress.com mulled over how this blog did in 2010, and here&#8217;s a high level summary of its overall blog health:</p>
<p><img style="border:1px solid #ddd;background:#f5f5f5;padding:20px;" src="http://s0.wp.com/i/annual-recap/meter-healthy4.gif" alt="Healthy blog!" width="250" height="183" /></p>
<p>The <em>Blog-Health-o-Meter™</em> reads This blog is on fire!.</p>
<h2>Crunchy numbers</h2>
<div style="width:288px;float:right;border:1px solid #ddd;background:#fff;margin:0 0 1em 1em;padding:6px;">
<p><img src="http://s0.wp.com/i/annual-recap/abstract-stats-3.png" alt="Featured image" /></p>
<p><em>A helper monkey made this abstract painting, inspired by your stats.</em></p>
</div>
<p>A Boeing 747-400 passenger jet can hold 416 passengers.  This blog was viewed about <strong>3,400</strong> times in 2010.  That&#8217;s about 8 full 747s.</p>
<p>In 2010, there were <strong>7</strong> new posts, growing the total archive of this blog to 65 posts.</p>
<p>The busiest day of the year was August 13th with <strong>39</strong> views. The most popular post that day was <a style="color:#08c;" href="http://aprajshekhar.wordpress.com/2010/05/23/bluetooth-programming-in-python-network-programming-using-rfcomm/">Bluetooth Programming in Python: Network Programming using RFCOMM</a>.</p>
<h2>Where did they come from?</h2>
<p>The top referring sites in 2010 were <strong>note19.com</strong>, <strong>en.wordpress.com</strong>, <strong>yandex.ru</strong>, <strong>google.co.in</strong>, and <strong>packtpub.com</strong>.</p>
<p>Some visitors came searching, mostly for <strong>server_sock listen python</strong>, <strong>c# image memory intptr to bitmap</strong>, <strong>python bluetooth</strong>, <strong>steps for accessing camera using pys60</strong>, and <strong>operations on text  in pys60</strong>.</p>
<h2>Attractions in 2010</h2>
<p>These are the posts and pages that got the most views in 2010.</p>
<div style="clear:left;float:left;font-size:24pt;line-height:1em;margin:-5px 10px 20px 0;">1</div>
<p><a style="margin-right:10px;" href="http://aprajshekhar.wordpress.com/2010/05/23/bluetooth-programming-in-python-network-programming-using-rfcomm/">Bluetooth Programming in Python: Network Programming using RFCOMM</a> <span style="color:#999;font-size:8pt;">May 2010</span><br />
2 comments</p>
<div style="clear:left;float:left;font-size:24pt;line-height:1em;margin:-5px 10px 20px 0;">2</div>
<p><a style="margin-right:10px;" href="http://aprajshekhar.wordpress.com/2009/07/06/image-manipulation-using-gdi-thumbnails-and-zooming/">Image Manipulation using GDI+ &#8211; The C# Way: Thumbnails and Zooming</a> <span style="color:#999;font-size:8pt;">July 2009</span><br />
2 comments</p>
<div style="clear:left;float:left;font-size:24pt;line-height:1em;margin:-5px 10px 20px 0;">3</div>
<p><a style="margin-right:10px;" href="http://aprajshekhar.wordpress.com/2010/04/13/bluetooth-programming-using-python/">Bluetooth Programming using Python</a> <span style="color:#999;font-size:8pt;">April 2010</span><br />
1 comment</p>
<div style="clear:left;float:left;font-size:24pt;line-height:1em;margin:-5px 10px 20px 0;">4</div>
<p><a style="margin-right:10px;" href="http://aprajshekhar.wordpress.com/2009/07/11/mobile-programming-in-python-using-pys60-ui-controls/">Mobile Programming in Python using PyS60: UI Controls</a> <span style="color:#999;font-size:8pt;">July 2009</span><br />
3 comments</p>
<div style="clear:left;float:left;font-size:24pt;line-height:1em;margin:-5px 10px 20px 0;">5</div>
<p><a style="margin-right:10px;" href="http://aprajshekhar.wordpress.com/2009/07/14/mobile-programming-using-pys60-advanced-ui-controls/">Mobile Programming using PyS60: Advanced UI Controls</a> <span style="color:#999;font-size:8pt;">July 2009</span><br />
1 comment</p>
<br />Filed under: <a href='http://aprajshekhar.wordpress.com/category/uncategorized/'>Uncategorized</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/aprajshekhar.wordpress.com/131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/aprajshekhar.wordpress.com/131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/aprajshekhar.wordpress.com/131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/aprajshekhar.wordpress.com/131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/aprajshekhar.wordpress.com/131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/aprajshekhar.wordpress.com/131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/aprajshekhar.wordpress.com/131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/aprajshekhar.wordpress.com/131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/aprajshekhar.wordpress.com/131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/aprajshekhar.wordpress.com/131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/aprajshekhar.wordpress.com/131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/aprajshekhar.wordpress.com/131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/aprajshekhar.wordpress.com/131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/aprajshekhar.wordpress.com/131/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=aprajshekhar.wordpress.com&amp;blog=5963225&amp;post=131&amp;subd=aprajshekhar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://aprajshekhar.wordpress.com/2011/01/02/2010-in-review/feed/</wfw:commentRss>
		<slash:comments>46</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/655da95aab86392587def3f9196de1ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">aprajshekhar</media:title>
		</media:content>

		<media:content url="http://s0.wp.com/i/annual-recap/meter-healthy4.gif" medium="image">
			<media:title type="html">Healthy blog!</media:title>
		</media:content>

		<media:content url="http://s0.wp.com/i/annual-recap/abstract-stats-3.png" medium="image">
			<media:title type="html">Featured image</media:title>
		</media:content>
	</item>
		<item>
		<title>Data-Structures in Python: Lists and Tuples</title>
		<link>http://aprajshekhar.wordpress.com/2010/11/20/data-structures-in-python-lists-and-tuples/</link>
		<comments>http://aprajshekhar.wordpress.com/2010/11/20/data-structures-in-python-lists-and-tuples/#comments</comments>
		<pubDate>Sat, 20 Nov 2010 08:19:35 +0000</pubDate>
		<dc:creator>AP Rajshekhar</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://aprajshekhar.wordpress.com/?p=128</guid>
		<description><![CDATA[The arrangement of data within the memory forms the basis of computing. The arrangement of data is known as data-structure. Every language provides variety of built-in data-structures. Languages such as C provide basic data-structure mechanisms using which complex structures can be built whereas languages such as Java use full-blown object-oriented approach for almost all types of data-structures. Then there are languages like Python which takes a middle approach. In this article I would be discussing the middle path used by Python using two of its built-in data-structures – Lists and Tuples. The first section would focus on functionalities of Lists and Tuples. In the second section I would develop a real world application which makes use of Lists and/or Tuples.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=aprajshekhar.wordpress.com&amp;blog=5963225&amp;post=128&amp;subd=aprajshekhar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The arrangement of data within the memory forms the basis of computing. The arrangement of data is known as data-structure. Every language provides variety of built-in data-structures. Languages such as C provide basic data-structure mechanisms using which complex structures can be built whereas languages such as Java use full-blown object-oriented approach for almost all types of data-structures. Then there are languages like Python which takes a middle approach. In this article I would be discussing the middle path used by Python using two of its built-in data-structures – Lists and Tuples. The first section would focus on functionalities of Lists and Tuples. In the second section I would develop a real world application which makes use of Lists and/or Tuples. That’s the agenda for this discussion.</p>
<p>&nbsp;</p>
<p><strong>List and Tuple – More About Them:</strong></p>
<p>List and Tuple are two of the basic built-in data-structures. As with all other features of Python, these in-built data-structures provide both flexibility and power. The answer to how flexible and powerful they are is what I am going to discuss now. First lets look at List data-structure.</p>
<p>&nbsp;</p>
<p>1. List:</p>
<p>By definition a List is “An instance of an abstract data type (ADT), formalizing the concept of an ordered collection of entities”. In other words, a List is a collection of objects. In contrast with Array, List contains different objects. That’s how Python also views Lists. Data types (that’s what Python calls built-in data-structures too) such as List is known as <em>compound data type </em>in Python<em>.</em> The operations that can be performed on a List are:</p>
<p>&nbsp;</p>
<p>a. Creation</p>
<p>b. Addition of elements</p>
<p>c. Accessing and Searching</p>
<p>d. Deletion</p>
<p>&nbsp;</p>
<p>Many of the library functions essentially create Lists. These functions may be working on Lists themselves such as during accessing and searching. Here are the details:</p>
<p>&nbsp;</p>
<p>a. Creation:</p>
<p>A List is defined as list of coma separated values between square brackets thus:</p>
<p>&nbsp;</p>
<p><strong>a = ['spam', 'eggs', 100, 1234]</strong></p>
<p>&nbsp;</p>
<p>where the items of the List <strong>a</strong> are of different data types.  This is the most common method of creating a list. The other technique is to use the range() function. The range() function provides a List of consecutive integers. The range() function takes two arguments. The List returned contains all the integers from the first to the second, including the first but not including the second. For example,</p>
<p><strong> </strong></p>
<p><strong>&gt;&gt;range(1, 5)</strong></p>
<p>Gives</p>
<p><strong>[1,2,3,4]</strong></p>
<p>Since List itself is a data type, so a List can contain another List. For example,</p>
<p>&nbsp;</p>
<p><strong>[1,”a”,[2,3]]</strong></p>
<p>&nbsp;</p>
<p>is perfectly valid List.</p>
<p>&nbsp;</p>
<p>b. Addition of elements:</p>
<p>There are three ways to add elements to an existing List using member functions of the List which are:</p>
<p>&nbsp;</p>
<p>i. <strong>append </strong>adds a single element to the end of the List. For example, let <strong>li</strong> be</p>
<p>a List, then</p>
<p><strong> </strong></p>
<p><strong> &gt;&gt;&gt; li</strong></p>
<p><strong> ['a', 'b', 'mpilgrim', 'z', 'example']</strong></p>
<p><strong> &gt;&gt;&gt; li.append(&#8220;new&#8221;) </strong></p>
<p><strong> &gt;&gt;&gt; li</strong></p>
<p><strong> ['a', 'b', 'mpilgrim', 'z', 'example', 'new']</strong></p>
<p>&nbsp;</p>
<p>ii. <strong>insert</strong> method inserts a single element into the List. The numeric argument</p>
<p>is the index of the first element that gets shifted out of position. Also there can be two elements of same value at two different positions.</p>
<p>&nbsp;</p>
<p><strong>&gt;&gt;&gt; li.insert(2, &#8220;new&#8221;) </strong></p>
<p><strong>&gt;&gt;&gt; li</strong></p>
<p><strong>['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new']</strong></p>
<p><strong> </strong></p>
<p><strong> </strong>iii. <strong>extends </strong>concatenates the List passed as argument with the existing List.</p>
<p>For example,</p>
<p><strong> </strong></p>
<p><strong> &gt;&gt;&gt; li.extend(["two", "elements"]) </strong></p>
<p><strong> &gt;&gt;&gt; li</strong></p>
<p><strong> ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']</strong></p>
<p>&nbsp;</p>
<p>c. Accessing and Searching:</p>
<p>For accessing and searching, one of the following techniques can be used:</p>
<p>&nbsp;</p>
<p>i. Slicing:</p>
<p>Slice is a sub-list of a List. Slicing is done using the <strong>[n : m] </strong>which</p>
<p>returns the part of the List from the n-eth character to the m-eth</p>
<p>character, including the first but excluding the last. For example if a_list is</p>
<p>a List of alphabets from a to f, then</p>
<p>&nbsp;</p>
<p><strong> &gt;&gt;&gt; a_list = ['a', 'b', 'c', 'd', 'e', 'f']</strong></p>
<p><strong> &gt;&gt;&gt; a_list[1:3]</strong></p>
<p><strong> ['b', 'c']</strong></p>
<p><strong> &gt;&gt;&gt; a_list[:4]</strong></p>
<p><strong> ['a', 'b', 'c', 'd']</strong></p>
<p><strong> &gt;&gt;&gt; a_list[3:]</strong></p>
<p><strong> ['d', 'e', 'f']</strong></p>
<p><strong> &gt;&gt;&gt; a_list[:]</strong></p>
<p><strong> ['a', 'b', 'c', 'd', 'e', 'f']</strong></p>
<p>&nbsp;</p>
<p>ii. Indexing:</p>
<p>Index of a given element can be found using the <strong>index() </strong>function of List. It returns the first occurrence of the element supplied as argument. That means even if the element occurs twice, only the position of the first element would be returned. If  the element is not found an exception is raised. For example</p>
<p><strong>&gt;&gt;&gt;li=['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']</strong></p>
<p><strong>&gt;&gt;&gt; li</strong></p>
<p><strong>['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']</strong></p>
<p><strong>&gt;&gt;&gt; li.index(&#8220;example&#8221;) </strong></p>
<p><strong>5</strong></p>
<p><strong>&gt;&gt;&gt; li.index(&#8220;new&#8221;) </strong></p>
<p><strong>2</strong></p>
<p><strong>&gt;&gt;&gt; li.index(&#8220;c&#8221;) </strong></p>
<p><strong>Traceback (innermost last):</strong></p>
<p><strong> File &#8220;&lt;interactive input&gt;&#8221;, line 1, in ?</strong></p>
<p><strong>ValueError: list.index(x): x not in list</strong></p>
<p>&nbsp;</p>
<p>Apart from these, a List can be accessed as one access an array by specifying index thus:</p>
<p><strong>&gt;&gt;&gt;li=['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']</strong></p>
<p><strong> &gt;&gt;&gt;li[0]</strong></p>
<p><strong> ‘a’</strong></p>
<p><strong> </strong></p>
<p>d. Deletion:</p>
<p>To delete an element from a List, one can us <strong>del</strong>. It removes an element from the specified List. For example:</p>
<p><strong>&gt;&gt;&gt; a = ['one', 'two', 'three']</strong></p>
<p><strong>&gt;&gt;&gt; del a[1]</strong></p>
<p><strong>&gt;&gt;&gt; a</strong></p>
<p><strong>['one', 'three']</strong></p>
<p>&nbsp;</p>
<p><strong> </strong>del also can have slice thus:</p>
<p><strong> &gt;&gt;&gt; a_list = ['a', 'b', 'c', 'd', 'e', 'f']</strong></p>
<p><strong> &gt;&gt;&gt; del a_list[1:5]</strong></p>
<p><strong> &gt;&gt;&gt; print a_list</strong></p>
<p><strong> ['a', 'f']</strong></p>
<p><strong> </strong></p>
<p>That’s all about the operations on Lists. The way the operations are implemented shows the flexibility of Python’s middle path approach. The flexibility doesn’t just stop here. Though strings are immutable and Lists are mutable yet they are inter-convertible. Two of the most useful functions in the string module involve Lists of strings – split and join. The former returns a List composed of individual elements of string separated by the delimiter passed as argument. While the latter creates a string out of supplied List. Following are the examples:</p>
<p>&nbsp;</p>
<p><strong>&gt;&gt;&gt; import string</strong></p>
<p><strong>&gt;&gt;&gt; song = &#8220;The rain in Spain&#8230;&#8221;</strong></p>
<p><strong>&gt;&gt;&gt; string.split(song)</strong></p>
<p><strong>['The', 'rain', 'in', 'Spain...']</strong></p>
<p>&nbsp;</p>
<p>Here the string is split on the basis of space as delimiter which is the default delimiter. Next example shows the reverse of the above functionality – string from a List:</p>
<p>&nbsp;</p>
<p><strong>&gt;&gt;&gt; lst = ['The', 'rain', 'in', 'Spain...']</strong></p>
<p><strong>&gt;&gt;&gt; string.join(lst)</strong></p>
<p><strong>&#8216;The rain in Spain&#8230;&#8217;</strong></p>
<p>where the joining is done on the basis of space delimiter which again is default delimiter. That’s all about Lists at present. Next lets look at the other compound data-type – Tuple.</p>
<p>&nbsp;</p>
<p>2. Tuple:</p>
<p>According to definition, “A tuple is a finite sequence (also known as an &#8220;ordered list&#8221;) of objects, each of a specified type”. In other words, a Tuple is an ordered collection of  objects of different types. In Python, a Tuple is a list of comma separated values but immutable unlike List. So the operations on a Tuple are restricted to the ones that don’t affect its immutability. Accordingly following are the operations that can be performed on a Tuple are:</p>
<p>&nbsp;</p>
<p>a. Creation</p>
<p>b. Accessing</p>
<p>&nbsp;</p>
<p>Due to immutability, deletion and addition of new elements are not possible.</p>
<p>&nbsp;</p>
<p>a. Creation:</p>
<p>Creating or defining a Tuple is as simple as giving a list of values within parenthesis. For example</p>
<p>&nbsp;</p>
<p><strong>&gt;&gt;&gt; tup = (2, 4, 6, 8, 10) </strong></p>
<p>&nbsp;</p>
<p>is a Tuple. If a Tuple is having only one element, then, it would be defined as follows:</p>
<p><strong>&gt;&gt;&gt; tup = (5,)</strong></p>
<p>&nbsp;</p>
<p>b. Accessing:</p>
<p>Since Lists and Tuples are almost same, so the accessing mechanisms also works in similar fashion. Elements of a Tuple can be accessed in two ways:</p>
<p>&nbsp;</p>
<p>i. Index based:</p>
<p>The elements of a  Tuple can be accessed using their indices. The</p>
<p>index starts at 0. For example to access an element at index 0 of a Tuple</p>
<p>tup, the statement would be:</p>
<p>&nbsp;</p>
<p><strong> &gt;&gt;&gt; tup = (&#8216;a&#8217;, &#8216;b&#8217;, &#8216;c&#8217;, &#8216;d&#8217;, &#8216;e&#8217;)</strong></p>
<p><strong> &gt;&gt;&gt; tup[0]</strong></p>
<p><strong> &#8216;a&#8217;</strong></p>
<p>&nbsp;</p>
<p>ii. Slicing:</p>
<p>As in List, slice operator can be used to access elements of a Tuple. It selects a range of elements. For example the following statement selects elements between 1 and 3 (excluding 3):</p>
<p><strong>&gt;&gt;&gt; tup[1:3]</strong></p>
<p><strong>(&#8216;b&#8217;, &#8216;c&#8217;)</strong></p>
<p>That’s about operations on a Tuple. So the question arises, when to use List and when to use Tuple. List can be used almost in all the cases. However, there are certain contexts where Tuple is more useful which are:</p>
<p>&nbsp;</p>
<ul>
<li>Tuples are faster than lists.      If you&#8217;re defining a constant set of values and all you&#8217;re ever going to      do with it is iterate through it, use a tuple instead of a list.</li>
<li>It makes your code safer if      you “write-protect” data that does not need to be changed. Using a Tuple      instead of a list is like having an implied assert statement that this      data is constant, and that special thought (and a specific function) is      required to override that.</li>
</ul>
<p>&nbsp;</p>
<p>In all other contexts, Lists can be used. That brings us to the next section – a real world example using List.</p>
<p>&nbsp;</p>
<p><strong>Lists And Tuples – In Real World:</strong></p>
<p>The example application would implement a ring buffer or a bounded buffer using List. In a bounded buffer, once the capacity is full, then the first element i.e. the oldest element is replaced with newest element. The implementation uses class switch pattern. Here is the code:</p>
<p>&nbsp;</p>
<p><strong>class RingBuffer(object):</strong></p>
<p><strong> &#8220;&#8221;" class that implements a not-yet-full buffer &#8220;&#8221;"</strong></p>
<p><strong> </strong></p>
<p><strong> def __init__(self, size_max):</strong></p>
<p><strong> self.max = size_max</strong></p>
<p><strong> self.data = [  ]</strong></p>
<p><strong> </strong></p>
<p><strong> class __Full(object):</strong></p>
<p><strong> &#8220;&#8221;" class that implements a full buffer &#8220;&#8221;"</strong></p>
<p><strong> def append(self, x):</strong></p>
<p><strong> &#8220;&#8221;" Append an element overwriting the oldest one. &#8220;&#8221;"</strong></p>
<p><strong> self.data[self.cur] = x</strong></p>
<p><strong> self.cur = (self.cur+1) % self.max</strong></p>
<p><strong> </strong></p>
<p><strong> def tolist(self):</strong></p>
<p><strong> &#8220;&#8221;" return list of elements in correct order. &#8220;&#8221;"</strong></p>
<p><strong> return self.data[self.cur:] + self.data[:self.cur]</strong></p>
<p><strong> </strong></p>
<p><strong> def append(self, x):</strong></p>
<p><strong> &#8220;&#8221;" append an element at the end of the buffer. &#8220;&#8221;"</strong></p>
<p><strong> self.data.append(x)</strong></p>
<p><strong> if len(self.data) == self.max:</strong></p>
<p><strong> self.cur = 0</strong></p>
<p><strong> # Permanently change self&#8217;s class from non-full to full</strong></p>
<p><strong> self.__class__ = __Full</strong></p>
<p><strong> </strong></p>
<p><strong> def tolist(self):</strong></p>
<p><strong> &#8220;&#8221;" Return a list of elements from the oldest to the newest. &#8220;&#8221;"</strong></p>
<p><strong> return self.data</strong></p>
<p><strong> </strong></p>
<p>The class defines an empty List as a buffer. The nested class __<strong>Full </strong>implements the logic to overwrite the oldest element if the buffer is full. The <strong>tolist</strong> method returns the List in correct order. Next the append method of the outer class i.e. <strong>RingBuffer </strong>appends a new item to the end of the List. It also checks whether the length of the buffer is equal to  the max size. If it is equal, then buffer’s state is changed to full. The tolist method returns the buffer. Following is sample implementation that shows how to use the RingBuffer class:</p>
<p>&nbsp;</p>
<p><strong>if __name__ == &#8216;__main__&#8217;:</strong></p>
<p><strong> x = RingBuffer(5)</strong></p>
<p><strong> x.append(1); x.append(2); x.append(3); x.append(4)</strong></p>
<p><strong> print x.__class__, x.tolist( )</strong></p>
<p><strong> x.append(5)</strong></p>
<p><strong> print x.__class__, x.tolist( )</strong></p>
<p><strong> x.append(6)</strong></p>
<p><strong> print x.data, x.tolist( )</strong></p>
<p><strong> x.append(7); x.append(8); x.append(9); x.append(10)</strong></p>
<p><strong> print x.data, x.tolist( )</strong></p>
<p><strong> </strong></p>
<p>That brings us to the end of this discussion. List and Tuple are the basic data-structures found in Python. On the basis of these more complex structures such as trees can be developed. How to implement them would be the topic for discussion in the future. Till then…</p>
<br />Filed under: <a href='http://aprajshekhar.wordpress.com/category/python/'>Python</a> Tagged: <a href='http://aprajshekhar.wordpress.com/tag/programming/'>programming</a>, <a href='http://aprajshekhar.wordpress.com/tag/python/'>Python</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/aprajshekhar.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/aprajshekhar.wordpress.com/128/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/aprajshekhar.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/aprajshekhar.wordpress.com/128/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/aprajshekhar.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/aprajshekhar.wordpress.com/128/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/aprajshekhar.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/aprajshekhar.wordpress.com/128/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/aprajshekhar.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/aprajshekhar.wordpress.com/128/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/aprajshekhar.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/aprajshekhar.wordpress.com/128/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/aprajshekhar.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/aprajshekhar.wordpress.com/128/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=aprajshekhar.wordpress.com&amp;blog=5963225&amp;post=128&amp;subd=aprajshekhar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://aprajshekhar.wordpress.com/2010/11/20/data-structures-in-python-lists-and-tuples/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/655da95aab86392587def3f9196de1ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">aprajshekhar</media:title>
		</media:content>
	</item>
		<item>
		<title>Understanding Time &#8211; The questions</title>
		<link>http://aprajshekhar.wordpress.com/2010/10/13/understanding-time-the-questions/</link>
		<comments>http://aprajshekhar.wordpress.com/2010/10/13/understanding-time-the-questions/#comments</comments>
		<pubDate>Wed, 13 Oct 2010 13:49:01 +0000</pubDate>
		<dc:creator>AP Rajshekhar</dc:creator>
				<category><![CDATA[Physics]]></category>
		<category><![CDATA[Time]]></category>
		<category><![CDATA[quantum-mechanics]]></category>
		<category><![CDATA[space]]></category>
		<category><![CDATA[time]]></category>

		<guid isPermaLink="false">http://aprajshekhar.wordpress.com/?p=125</guid>
		<description><![CDATA[Everyday we use the term time &#8216;Everything depends upon time&#8217;, &#8216;There is a time for everything&#8217; and so on But, what is Time exactly? How can one define time? There is a simple definition that has been going around It states Time is that can be measured But this definition arises another question &#8211; What [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=aprajshekhar.wordpress.com&amp;blog=5963225&amp;post=125&amp;subd=aprajshekhar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><span style="font-size:small;">Everyday we use the term time  &#8216;Everything depends upon time&#8217;, &#8216;There is a time for everything&#8217; and so on  But, what is <strong>Time</strong> exactly? How can one define time? There is a simple definition that has been going around  It states <strong>Time is that can be measured </strong> But this definition arises another question &#8211; <strong>What is the yardstick for this measurement?</strong> From ancient time itself earth&#8217;s rotation and revolution has been the  basis or yardstick for the measurement of time  However, rotation and  revolution varies  So what are we left with? A whole bundle of  misconceptions </span></p>
<p><span style="font-size:small;">Then  you will ask what should be the basis? A basis should be a non-varient   But is such an ideal, universal and non-variant basis available or can  such a basis be found? Let me leave that question for the moment (for  your ponderings)  Now next problem in understanding the working of time   Change in every quantity is measured with respect to chnage in time  <strong>If time&#8217;s measure change from one point in space to another, then how the measured change can be accurate? </strong>Thus, in short, all the derivatives of time are set on a foundation of transitory theorems </span></p>
<p><span style="font-size:small;">All the changes measured depend upon time, then on what does time <strong>depends</strong>?  Is the dependency on ever-changing orbits and orbital velocity? Or is  it the frequency of atom (believed to be accurate)? But what of changes  in them that occurs with changes in environment? These are questions that  needs to be answered in order to understand time </span></p>
<p><span style="font-size:small;">In the upcoming posts I will try to put forward my thoughts, ideas and approach in answering these questions  So keep visiting </span></p>
<br />Filed under: <a href='http://aprajshekhar.wordpress.com/category/physics/'>Physics</a>, <a href='http://aprajshekhar.wordpress.com/category/physics/time/'>Time</a> Tagged: <a href='http://aprajshekhar.wordpress.com/tag/quantum-mechanics/'>quantum-mechanics</a>, <a href='http://aprajshekhar.wordpress.com/tag/space/'>space</a>, <a href='http://aprajshekhar.wordpress.com/tag/time-2/'>time</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/aprajshekhar.wordpress.com/125/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/aprajshekhar.wordpress.com/125/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/aprajshekhar.wordpress.com/125/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/aprajshekhar.wordpress.com/125/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/aprajshekhar.wordpress.com/125/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/aprajshekhar.wordpress.com/125/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/aprajshekhar.wordpress.com/125/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/aprajshekhar.wordpress.com/125/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/aprajshekhar.wordpress.com/125/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/aprajshekhar.wordpress.com/125/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/aprajshekhar.wordpress.com/125/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/aprajshekhar.wordpress.com/125/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/aprajshekhar.wordpress.com/125/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/aprajshekhar.wordpress.com/125/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=aprajshekhar.wordpress.com&amp;blog=5963225&amp;post=125&amp;subd=aprajshekhar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://aprajshekhar.wordpress.com/2010/10/13/understanding-time-the-questions/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/655da95aab86392587def3f9196de1ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">aprajshekhar</media:title>
		</media:content>
	</item>
		<item>
		<title>Introducing jQuery</title>
		<link>http://aprajshekhar.wordpress.com/2010/10/02/introducing-jquery/</link>
		<comments>http://aprajshekhar.wordpress.com/2010/10/02/introducing-jquery/#comments</comments>
		<pubDate>Sat, 02 Oct 2010 06:20:10 +0000</pubDate>
		<dc:creator>AP Rajshekhar</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[ui controls]]></category>

		<guid isPermaLink="false">http://aprajshekhar.wordpress.com/?p=121</guid>
		<description><![CDATA[It is JavaScript that brings a HTML page to 'life'. Whether it is client-side validation, animating the page elements or calling the server in the background to get updated page, one can use JavaScript to achieve all this and much more. However, using JavaScript in its 'raw' state compels the developer to write multiple lines to implement each of the afore-mentioned functionality and for each application. The pit-fall in such an approach is that each application will have its own pattern and trying to reuse JavaScript code developed for one application, will ultimately result in re-factoring most of the code so that it meets the requirements of both the applications. This is where JavaScript libraries come into picture. These libraries encapsulate the ordinary yet oft used functionalities (e.g. validation, selection of elements etc.) and provide simplified API to access these functionalities. Among the JavaScript libraries, one of the most used is jQuery. In this discussion, the focus will be on the basics of jQuery.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=aprajshekhar.wordpress.com&amp;blog=5963225&amp;post=121&amp;subd=aprajshekhar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>It is JavaScript that brings an HTML page to &#8216;life&#8217;. Whether it is client-side validation, animating the page elements or calling the server in the background to get updated page, one can use JavaScript to achieve all this and much more. However, using JavaScript in its &#8216;raw&#8217; state compels the developer to write multiple lines to implement each of the afore-mentioned functionality and for each application. The pit-fall in such an approach is that each application will have its own pattern and trying to reuse JavaScript code developed for one application, will ultimately result in re-factoring most of the code so that it meets the requirements of both the applications. This is where JavaScript libraries come into picture. These libraries encapsulate the ordinary yet oft used functionalities (e.g. validation, selection of elements etc.) and provide simplified API to access these functionalities. Among the JavaScript libraries, one of the most used is jQuery. In this discussion, the focus will be on the basics of jQuery. The first section will be about the whys and wherefores of the jQuery. The second section will provide details about using various functionalities of jQuery. That’s the agenda for this discussion.</p>
<p><strong>jQuery – the Whys and Wherefores</strong></p>
<p>To understand how jQuery can ease web client (JavaScript based) development, one has to understand two aspects of jQuery. They are:</p>
<p>1. Functionalities</p>
<p>2. Modules</p>
<p>Understanding the functionalities/services provided by jQuery will tell you what jQuery provides and understanding the modules that constitute jQuery will tell you how to access the services provided by jQuery. Here are the details.</p>
<p><strong> </strong></p>
<p><strong>1. Functionalities</strong></p>
<p>The functionalities provided by jQuery can be classified into following</p>
<p>a. Selection</p>
<p>b. Attributes handling</p>
<p>c. Element manipulation</p>
<p>d. Ajax</p>
<p>e. Callbacks</p>
<p>f. Event Handling</p>
<p>Among the above listed functionalities, selection, element manipulation and event handling makes common tasks very easily implementable or trivial.</p>
<p>a. Selection</p>
<p>Using this functionality one can select one or multiple HTML elements. The raw JavaScript equivalent of the selection functionality is</p>
<p>document.getElementByID(‘&lt;element id&gt;’) or</p>
<p>document.getElementByTagName(‘&lt;tag name&gt;’)</p>
<p>b. Attributes handling</p>
<p>One of most required task in JavaScript is to change the value of an attribute of a tag. The conventional way is to use getElementByID to get the element and then use index to get to the required attribute. jQuery eases it by using selection and attributes handling functionality in conjunction.</p>
<p>c. Element handling</p>
<p>There are scenarios where the values of tags need to be modified. One of such scenarios is rewriting text of a &lt;p&gt; tag based on selection from combo box. That is where element handling functionality of jQuery comes handy. Using the element handling or DOM scripting, as it is popularly known, one can not only access a tag but also perform manipulation such as appending child tags to multiple occurrences of a specific tag without using for loop.</p>
<p>d. Ajax</p>
<p>Ajax is of the concept and implementation that brought the usefulness of JavaScript to the fore. However, it also brought the complexities and the boilerplate code required for using Ajax to its full potential. The Ajax related functionalities of jQuery encapsulates away the boilerplate code and lets one concentrate on the result of the Ajax call. The main point to keep in mind is that encapsulation of the setup code does not mean that one cannot access the Ajax related events. jQuery takes care of that too and one can register to the Ajax events and handle them.</p>
<p>e. Callbacks</p>
<p>There are many scenarios in web development, where you want to initiate another task on the basis of completion of one task. An example of such a scenario involves animation. If you want to execute a task after completion of an animation, you will need callback function. The core of jQuery is implemented in such a way that most of the API supports callbacks.</p>
<p>f. Event handling</p>
<p>One of the main aspects of JavaScript and its relationship with HTML is the events triggered by the form elements can be handled using JavaScript. However, when multiple elements and multiple events come into picture, the code complexity becomes very hard to handle. The core of jQuery is geared towards handling the events in such a way that complexity can be maintained at manageable levels.</p>
<p>Now that we have discussed the main functionalities of jQuery, let us move onto the main modules of jQuery and how the functionalities map onto the functionalities.</p>
<p><strong>2. Modules</strong></p>
<p>The modules contain APIs that have one-to-one mapping with the functionalities (most of the time). The main modules of jQuery are</p>
<p>a. Selectors</p>
<p>b. Attributes/CSS</p>
<p>c. Manipulation</p>
<p>d. Ajax</p>
<p>e. Callback</p>
<p>f. Event Handling</p>
<p>The names are indicators as to which functionalities they map to. Here are the details</p>
<p>a. Selectors</p>
<p>As the name indicates, selectors provide the functionality to select elements.  As mentioned earlier, selectors are denoted by dollar ($) sign. Some of the commonly used selectors are</p>
<ul>
<li>all selector – selects all the elements</li>
<li>:first and :last selectors – select the first and last occurrence of a recurring element/tag.</li>
<li>:eq (index) – selects the element with the index having the  value passed as argument.</li>
<li>#id – selects the element whose id is passed.</li>
</ul>
<p>Following statements show how selectors are commonly used</p>
<p><strong>$(&#8220;p&#8221;) </strong></p>
<p>The above statement selects all &lt;p&gt; elements.</p>
<p><strong>$(&#8220;p.start&#8221;)</strong></p>
<p>It selects all &lt;p&gt; elements with class whose name is “start”.</p>
<p><strong>$(&#8220;p#demo&#8221;)</strong></p>
<p>It selects the first &lt;p&gt; element with &#8220;demo&#8221; as id.</p>
<p>b. Attributes/CSS:</p>
<p>The attribute handling functionality can be found in the API of this module. It also provides manipulation of CSS classes attached to the elements or attributes. Some of the most commonly used API is</p>
<h4>·         .attr( attributeName ) – gets the value of an attribute for the first element having the attribute with name equal to the passed attribute name</h4>
<ul>
<li>.addClass (classname) – sets the CSS class of a particular element.</li>
<li>.val() &#8211; gets the current value of the first element in the set of matched elements. It is primarily used to get the values from form elements.</li>
<li>.css(name, value)  &#8211; sets the style property that matches the name of the style passed to the value passed for style</li>
</ul>
<p>Following is an example of css() API</p>
<p><strong>$(&#8220;p&#8221;).css(&#8220;background-color&#8221;,&#8221;yellow&#8221;);</strong></p>
<p>It will set the style of all the &lt;p&gt; elements. In this case the style is background color. Its value is set to yellow.</p>
<p>c. Manipulation</p>
<p>The API related to DOM scripting can be found in this module. In other words, the API in this module is used to manipulate DOM in one way or other. One point to keep in mind is that many of the API in this module overlaps with API in Attributes/CSS module. Some of the most commonly used API is:</p>
<ul>
<li>.after(content) – adds the specified content after each of the elements from a set of matched elements.</li>
<li>clone() – duplicates the elements in a set o matched elements.</li>
<li>replaceWith(newContent) – replaces each element from a set of matched elements with the specified content.</li>
</ul>
<p>The term “set of matched elements” means that these APIs need to be used along with selectors. A selector may return more than one element. Hence, the returned values are collectively termed as set. For example, the following statement appends “This is appended” to all the &lt;p&gt; elements</p>
<p><strong>$(&#8220;p&#8221;).append(&#8220;This is appended &#8220;);</strong></p>
<p>And the following replaced all the values between &lt;p&gt; and &lt;</p>
<p>d. Ajax</p>
<p>The Ajax related functionality can be found in this module. Following are the most commonly used APIs</p>
<ul>
<li>get() – retrieve data from the server specified by the URL, with the data passed.</li>
<li>Post() – same as get but uses POST HTTP method to retrieve the data.</li>
</ul>
<p>For example, the following statements depict the use of get() API</p>
<p><strong>$.get(</strong></p>
<p><strong> &#8220;http://mysite.org/test.php&#8221;,</strong></p>
<p><strong> function(data) { alert(data); },</strong></p>
<p><strong> );</strong></p>
<p>In the above example, get takes two parameters – URL of the remote site and the callback that performs some operation on the data passed into the callback by get API. Here the URL is “http://mysite.org/test.php” and the operation performed is alerting the user.</p>
<p>e. Callbacks</p>
<p>One of the aspects of jQuery that is heavily used is callbacks. A callback is a function that is registered with another method and gets called when a specific condition, such as response from the server is fulfilled. Following statements display callback in its simplest form</p>
<p><strong>$(&#8220;p#test&#8221;).hide(1000,function(){</strong></p>
<p><strong>alert(&#8220;The paragraph is now hidden&#8221;);</strong></p>
<p><strong>});</strong></p>
<p>The hide() API takes two arguments, speed with which the element has to be hidden and the method that needs to be called when the task of hiding is done. In the above example, when the &lt;p&gt; element with id as test is hidden an alert is displayed. In this case callback function is directly defined within hide().</p>
<p>f. Event handling</p>
<p>As stated before, event handling is part of the core functionalities of jQuery. However, to use it, one point needs to be understood. It is the place (within the HTML document) where event and its handler will be attached. The answer to this question is the correct place is the section which gets called before body section is called and it is the head section.</p>
<p>To attach a handler with an event, the statements need to be place within the ready() function of document DOM element. For example, following statements attach the click event of button to its handler</p>
<p><strong>$(document).ready(function(){</strong></p>
<p><strong> $(&#8220;button#test&#8221;).click(function(){</strong></p>
<p><strong> $(&#8220;p&#8221;).hide();</strong></p>
<p><strong> });</strong></p>
<p><strong>});</strong></p>
<p>The click event button with id ‘test’ is attached to the handler using callback functionality which in turn is defined inside the callback for ready(). One point to keep in mind is that any kind event handling code must be defined inside ready() and read() itself must be a part of the head section (&lt;head&gt;&lt;/head&gt;).</p>
<p>This completes the bird’s eye view of the APIs of jQuery. Next section will deal with the steps in using jQuery and some its APIs. It will also cover how to use some of the APIs discussed in this section.</p>
<p><strong>Developing with jQuery – Step-by-Step:</strong></p>
<p>The steps to use jQuery  include downloading and installing (in some cases), referencing the jQuery library and calling the API. Following are the details</p>
<p><strong>1. Downloading and installing jQuery</strong></p>
<p>This step is not mandatory. The reason for this step being optional is that there are alternative ways to reference jQuery library which will be discussed as a part of next step. To download jQuery, one has to download it from the following URL</p>
<p>http://docs.jquery.com/Downloading_jQuery#Current_Release</p>
<p>Unzip it to the local folder from where it will be referenced. That completes the step for downloading and installing.</p>
<p><strong>2. Referencing the Library</strong></p>
<p>There are two ways to reference jQuery. They are</p>
<p>a. Local reference</p>
<p>c. Remote reference</p>
<p>Both use src attribute of // </p>
<p>a. Local reference</p>
<p>When the library (JS files of jQuery) resides within the application directory structure, then the files are locally referenced. Following statement references files stored in the scripts folder of the application</p>
<p><strong>// &lt;![CDATA[<br />
<span class="hiddenSpellError">src</span>="../script/jquery-1.4.2.js"&gt;<br />
// ]]&gt;</strong></p>
<p><strong>&lt;/script&gt;</strong></p>
<p>b. Remote reference</p>
<p>When the library is hosted on another site ( e.g. code.google.com) and the URL is used to access the functionalities of the library, it is known as remote referencing. The steps to remotely refer jQuery hosted at code.google.com are as follows</p>
<p>i. Refer to the jQuery hosted on code.google.com using the src attribute of the //<br />
statement does the same</p>
<p><strong>// &lt;![CDATA[<br />
javascript"<br />
// ]]&gt;</strong></p>
<p><strong> src=&#8221;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&#8221;&gt;</strong></p>
<p><strong> &lt;/script&gt;</strong></p>
<p>The main point to remember is that the URL for the jQuery library may change based on the version of jQuery.</p>
<p>ii. Call the initialization function i.e. ready() after the referencing statement. The following example shows both the steps together</p>
<p><strong>&lt;script</strong></p>
<p><strong> src=&#8221;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&#8221;&gt;</strong></p>
<p><strong> &lt;/script&gt;</strong></p>
<p><strong>&lt;script&gt;</strong></p>
<p><strong> $(document).ready(function() {</strong></p>
<p><strong> // provide the initialization such as event handling here</strong></p>
<p><strong> });</strong></p>
<p><strong>&lt;/script&gt;</strong></p>
<p><strong>3. Calling the API</strong></p>
<p>To call the API, one can use one of the following ways</p>
<p>a. Fully qualified name</p>
<p>When calling the API with fully qualified name, the statement starts with jQuery. The following statement calls the selector using fully qualified name</p>
<p><strong>jQuery(‘:first’)</strong></p>
<p>b. Using Dollar sign</p>
<p>The dollar sign ($) can be used to call the APIs, instead of using ‘jQuery’. The following statement uses dollar sign to call the selector instead of jQuery</p>
<p><strong>$(‘:first’)</strong></p>
<p><strong>4. Putting it all Together:</strong></p>
<p>Let’s put all the steps together.  The following example will implement  a simple time server. There are two files –one that sits at the server and the one executed at the client. They are</p>
<p>1. SimpleTimeServer.php – it will reside at the server and respond with the current server time.</p>
<p>2. Client.html – it will send request to the server for current server  time via Ajax and display the response it<br />
receives.</p>
<p>First is the SimpleTimeServer.php.  It will have the following code</p>
<p><strong>&lt;?php</strong></p>
<p><strong>$time_now=mktime(date(&#8216;h&#8217;)+5,date(&#8216;i&#8217;)+30,date(&#8216;s&#8217;));</strong></p>
<p><strong>$time_now_str = date(&#8216;l M dS, Y, h:i:s A&#8217;,$time_now)</strong></p>
<p><strong>print $time_now_str;</strong></p>
<p><strong>?&gt;</strong></p>
<p>It uses the mktime function to get the current date time and the date function to convert it to human readable string.</p>
<p>Next is Client.html. Following is the code</p>
<p><strong>xmlns=&#8221;http://www.w3.org/1999/xhtml&#8221; xml:lang=&#8221;en&#8221; lang=&#8221;en&#8221;&gt;</strong></p>
<p><strong> &lt;head&gt;</strong></p>
<p><strong> &lt;title&gt;Current Date and Time&lt;/title&gt;</strong></p>
<p><strong> &lt;script src=&#8221;jquery-1.2.6.js&#8221;&gt;&lt;/script&gt;</strong></p>
<p><strong> &lt;script&gt; </strong></p>
<p><strong> function  getTime()</strong></p>
<p><strong> {</strong></p>
<p><strong>$.ajax({</strong></p>
<p><strong> </strong></p>
<p><strong>url : &#8220;SimpleTimeServer.php&#8221;,</strong></p>
<p><strong> </strong></p>
<p><strong>success : function (data) {</strong></p>
<p><strong>$(&#8220;#contentArea&#8221;).html(data);</strong></p>
<p><strong>}</strong></p>
<p><strong>});</strong></p>
<p><strong>setTimeout(&#8220;getTime()&#8221;, 1000);</strong></p>
<p><strong>}</strong></p>
<p><strong> &lt;/script&gt; </strong></p>
<p><strong> </strong></p>
<p><strong> &lt;/head&gt;</strong></p>
<p><strong> </strong></p>
<p><strong> &lt;body onload=&#8221;getTime();&#8221;&gt;</strong></p>
<p><strong> &lt;table width=&#8221;100%&#8221;&gt;</strong></p>
<p><strong> &lt;tr&gt;</strong></p>
<p><strong>&lt;td  width=&#8221;100%&#8221; align=&#8221;center&#8221;&gt;</strong></p>
<p><strong></p>
<div id="contentArea" style="color:blue;font:bold &lt;">14px arial;padding-top:140px;&#8221;&gt;</div>
<p></strong></p>
<p><strong> &lt;/div&gt; </strong></p>
<p><strong> &lt;/td&gt;</strong></p>
<p><strong> &lt;/tr&gt;</strong></p>
<p><strong> &lt;/table&gt;</strong></p>
<p><strong> &lt;/body&gt;</strong></p>
<p><strong> &lt;/html&gt;</strong></p>
<p>The core of the client is the getTime function. It make call to the server using the get API and displays the received value using the manipulator html(). Then the function uses setTimeOut() to call itself at specified interval. The getTime() is called when the body section loads, thus once the body is loaded the time is displayed at a specific interval.</p>
<p>That completes the example. What I discussed here is just the tip of the ice-berg. In the next article, the selectors will be covered in details. Till then…</p>
<br />Filed under: <a href='http://aprajshekhar.wordpress.com/category/uncategorized/'>Uncategorized</a> Tagged: <a href='http://aprajshekhar.wordpress.com/tag/ajax/'>AJAX</a>, <a href='http://aprajshekhar.wordpress.com/tag/jquery/'>jQuery</a>, <a href='http://aprajshekhar.wordpress.com/tag/ui-controls/'>ui controls</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/aprajshekhar.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/aprajshekhar.wordpress.com/121/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/aprajshekhar.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/aprajshekhar.wordpress.com/121/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/aprajshekhar.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/aprajshekhar.wordpress.com/121/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/aprajshekhar.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/aprajshekhar.wordpress.com/121/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/aprajshekhar.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/aprajshekhar.wordpress.com/121/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/aprajshekhar.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/aprajshekhar.wordpress.com/121/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/aprajshekhar.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/aprajshekhar.wordpress.com/121/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=aprajshekhar.wordpress.com&amp;blog=5963225&amp;post=121&amp;subd=aprajshekhar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://aprajshekhar.wordpress.com/2010/10/02/introducing-jquery/feed/</wfw:commentRss>
		<slash:comments>26</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/655da95aab86392587def3f9196de1ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">aprajshekhar</media:title>
		</media:content>
	</item>
		<item>
		<title>SDL Programming in Linux Playing with Graphics</title>
		<link>http://aprajshekhar.wordpress.com/2010/07/06/sdl-programming-in-linux-playing-with-graphics/</link>
		<comments>http://aprajshekhar.wordpress.com/2010/07/06/sdl-programming-in-linux-playing-with-graphics/#comments</comments>
		<pubDate>Tue, 06 Jul 2010 17:38:02 +0000</pubDate>
		<dc:creator>AP Rajshekhar</dc:creator>
				<category><![CDATA[SDL]]></category>
		<category><![CDATA[C/C++]]></category>
		<category><![CDATA[game-programming]]></category>
		<category><![CDATA[Linux]]></category>

		<guid isPermaLink="false">http://aprajshekhar.wordpress.com/?p=117</guid>
		<description><![CDATA[Graphics manipulation is the core of any game programming library. Without graphics manipulation, games can never realize the actual potential of interactivity and environmental feedback- the two facets of any game that makes it engrossing. SDL provides for this through its graphics sub-system. In this part, I will be discussing about the graphics subsystem and the various functionalities provided by it. Though the routines to work with graphics are present in the corresponding sub-system yet, the graphics sub-subsystem itself is a part of the video subsystem. Hence all the graphics related routines are present in the Video sub-system. <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=aprajshekhar.wordpress.com&amp;blog=5963225&amp;post=117&amp;subd=aprajshekhar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Graphics manipulation is the core of any game programming library. Without graphics manipulation, games can never realize the actual potential of interactivity and environmental feedback- the two facets of any game that makes it engrossing. SDL provides for this through its graphics sub-system. In this part, I will be discussing about the graphics subsystem and the various functionalities provided by it. Though the routines to work with graphics are present in the corresponding sub-system yet, the graphics sub-subsystem itself is a part of the video subsystem. Hence all the graphics related routines are present in the Video sub-system. The first section would cover the basics covered with initializing the video for best resolution. The second section would detail about loading a bitmap onto the screen. That’s the agenda for the second part of SDL Programming in Linux.</p>
<p><strong>Working with Video- the SDL way:</strong></p>
<p>When working with gaming libraries, one has to drop into system specific APIs(Win SDK on Windows and Xlib and et al on *nix) to access the video related functionalities. These functionalities include initializing the video, setting the best video mode and loading the bitmapped images among other things. But SDL encapsulates all these within the Video sub-system. The functions that provides access to these are:</p>
<ol>
<li>SDL_Init():</li>
</ol>
<p>This function had been discussed in the first part. This function initializes the sub-system that has been passed as parameter. To initialize video the parameter would be SDL_INIT_VIDEO. To elucidate:</p>
<p>SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO)</p>
<p>would initialize video as well as audio.</p>
<ol>
<li>SDL_SetVideoMode():</li>
</ol>
<p>Once the video is initialized, the next obvious step is setting the best video mode. To achieve this end, SDL contains a method SDL_SetVideoMode. This method sets up a video mode with specified width, height and bits per pixel i.e. depth. In short using this function one could set up the required resolution. The parameters are:</p>
<ol>
<li>width</li>
<li>height</li>
<li>bpp(bits-per-pixel)</li>
<li>flags</li>
</ol>
<p>The first three parameters take integer values. They represent height, width and depth of the screen respectively. The fourth parameters need some considerations. The flags parameter defines the properties of the surface of the screen. They are eleven in number. The important and most commonly used are:</p>
<ol>
<li>SDL_SWSURFACE:</li>
</ol>
<p>This instructs SDL to create the surface in the system memory. In other words, the rendering area is created using software renderer. This is useful in case support for software based acceleration is on cards.</p>
<ol>
<li>SDL_HWSURFACE:</li>
</ol>
<p>To create surface in hardware memory i.e. memory of the graphics card, use this value as the flag value. This means to support hardware acceleration use this value. It can be or’d with SDL_SWSURFACE to support both.</p>
<ol>
<li>SDL_ANYFORMAT:</li>
</ol>
<p>When the passed depth value is unsupported on the target machine, then SDL emulates it with a shadow surface i.e. to emulate required depth, SDL would use shadows. To prevent this pass SDL_ANYFORMAT as the flag value. By using SDL_ANYFORMAT SDL can be instructed to use the video surface even if the required depth is not available.</p>
<ol>
<li>SDL_DOUBLEBUF:</li>
</ol>
<p>It enables hardware double buffering. The double buffering works only if called with SDL_HWSURFACE. Otherwise when flipping function is called only updation of the surface takes place.</p>
<ol>
<li>SDL_OPENGL:</li>
</ol>
<p>It creates an OpenGL rendering context. This is useful when SDL is used in conjunction with OpenGL.</p>
<ol>
<li>SDL_FULLSCREEN:</li>
</ol>
<p>By passing it as the flag value, the mode could be change to full screen. If SDL is unable to do so, then it will use the next available higher resolution. But the window will be centered on black screen.</p>
<ol>
<li>SDL_NOFRAME:</li>
</ol>
<p>To set have the window without decoration (without title bar and frame decoration), use this as the value. Setting SDL_FULLSCREEN as the flag value, this flag is automatically set.</p>
<p>All the above values are same as that of SDL_Surface. The <em>SDL_SetVideoMode()</em> function returns a pointer to the structure SDL_Surface. Now lets see how to use it in a program.</p>
<p>#include “SDL.h”</p>
<p>#include&lt;stdio.h&gt;</p>
<p>int main(int argc,char* argv[])</p>
<p>{</p>
<p><strong>SDL_Surface *screen</strong><strong>;</strong></p>
<p><strong> </strong>/*The following code does the initialization for Audio and Video*/</p>
<p><strong>int i_error=SDL_Init(SDL_INIT_VIDEO);</strong></p>
<p>/*If initialization is unsuccessful, then quit */</p>
<p>if(i_error==-1)</p>
<p>exit(1);</p>
<p>atexit(SDL_Quit);</p>
<p><strong> </strong><strong>/*</strong></p>
<p><strong> * Initialize the display in a 640&#215;480 8-bit palettized mode,</strong></p>
<p><strong> * requesting a software surface</strong></p>
<p><strong> */</strong></p>
<p><strong> screen = SDL_SetVideoMode(640, 480, 8, SDL_SWSURFACE);</strong></p>
<p><strong> if ( screen == NULL ) </strong></p>
<p><strong>{</strong></p>
<p><strong> fprintf(stderr, &#8220;Couldn&#8217;t set 640x480x8 video mode: %s\n&#8221;,</strong></p>
<p><strong> SDL_GetError());</strong></p>
<p><strong> exit(1);</strong></p>
<p><strong> } </strong></p>
<p><strong> </strong>}<strong> </strong></p>
<p>If you recall, most of the above code is same as the one I discussed in first part. The changes are set in bold. First a point to the structure SDL_Surface is declared. When the video mode is set, this comes into picture. Then the video is initialized using SDL_Init(). This part is not much different. If initialization fails, then exit the application.</p>
<p>As I said before, the function to set video mode returns a pointer to the initialized SDL_Surface structure. The above code sets the resolution at 640&#215;480 at 8 bit depth. It also sets the rendering to software based i.e. the surface is created in system memory and not in graphics card’s memory. Now that video mode has been set we can move to the next section. That is loading a bitmap on to the returned surface.</p>
<p><strong>Loading Bitmap – the SDL way:</strong></p>
<p><strong> </strong></p>
<p>To load a bitmap onto the surface following functions come handy:</p>
<ol>
<li>SDL_LoadBMP:</li>
</ol>
<p>This function forms the basis of loading a bitmap. It returns a pointer to surface for name of the bitmap given as the parameter. If the loading of bitmap has not been successful, null is returned. For example, if the file parameter is “Tux.bmp”, then following code will load it:</p>
<p>SDL_Surface *image=SDL_LoadBMP(“Tux.bmp”);</p>
<ol>
<li>SDL_SetColors:</li>
</ol>
<p>The default palette would be an 8x8x4 color cube. To get a better color matching it is required to palletize the image itself. For this SDL_Setcolors function is quite useful. The first parameters is the surface for  which the palette has to be created, second parameter is the SDL color component which decides the number of the displayable colors. Third and fourth parameters sets the range of colors to be used. To palletize the loaded image the first parameter would be the surface returned by the SDL’s initialization routine, the second is the color component of the image to be palletized, the third would be 0 that would be lower range of the colors to be used, and the maximum value of the color palette of the image would be the fourth parameter. To put in code:</p>
<p>SDL_SetColors(screen, image-&gt;format-&gt;palette-&gt;colors, 0,</p>
<p>image-&gt;format-&gt;palette-&gt;ncolors);</p>
<p>where <em>screen </em>is the surface returned by the initialization and <em>image</em> is the loaded bitmap.</p>
<ol>
<li>SDL_BlitSurface:</li>
</ol>
<p>This function performs a fast blit from source surface to the destination surface. The parameters are source surface, source rectangle, destination surface and destination rectangle. If the source and destination rectangle are specified as null then the entire surface is copied. For example the following code copies loaded image surface to the screen surface:</p>
<p>SDL_BlitSurface(image, NULL, screen, NULL);</p>
<ol>
<li>SDL_UpdateRect:</li>
</ol>
<p>Once the loaded image surface is copied onto the screen surface, it must be ensured that the screen display is updated accordingly. The surface to be updated is the first parameter, the rectangle of the screen to be updated is specified is the second parameter. The following fragment updates the screen according to the height and width of the loaded image:</p>
<p>SDL_UpdateRect(screen, 0, 0, image-&gt;w, image-&gt;h);</p>
<ol>
<li>SDL_FreeSurface:</li>
</ol>
<p>Once work is completed with the loaded image, then the surface has to be freed so that the memory occupied by the surface is released. To free a surface SDL library contains SDL_FreeSurface. The parameter is the surface to be freed. In code it would be:</p>
<p>SDL_FreeSurface(image);</p>
<p>Where image is the surface to be freed.</p>
<p>Now that the functions to be used have been introduced, lets see them in action. First define a function that loads a bitmap image passed to it as parameter.</p>
<p>void display_bmp(char *file_name)</p>
<p>{</p>
<p>SDL_Surface *image;</p>
<p>/* Load the BMP file into a surface */</p>
<p>image = SDL_LoadBMP(file_name);</p>
<p>if (image == NULL) {</p>
<p>fprintf(stderr, &#8220;Couldn&#8217;t load %s: %s\n&#8221;, file_name, SDL_GetError());</p>
<p>return;</p>
<p>}</p>
<p>/*</p>
<p>* Palettized screen modes will have a default palette (a standard</p>
<p>* 8*8*4 colour cube), but if the image is palettized as well we can</p>
<p>* use that palette for a nicer colour matching</p>
<p>*/</p>
<p>if (image-&gt;format-&gt;palette &amp;&amp; screen-&gt;format-&gt;palette) {</p>
<p>SDL_SetColors(screen, image-&gt;format-&gt;palette-&gt;colors, 0,</p>
<p>image-&gt;format-&gt;palette-&gt;ncolors);</p>
<p>}</p>
<p>/* Blit onto the screen surface */</p>
<p>if(SDL_BlitSurface(image, NULL, screen, NULL) &lt; 0)</p>
<p>fprintf(stderr, &#8220;BlitSurface error: %s\n&#8221;, SDL_GetError());</p>
<p>SDL_UpdateRect(screen, 0, 0, image-&gt;w, image-&gt;h);</p>
<p>/* Free the allocated BMP surface */</p>
<p>SDL_FreeSurface(image);</p>
<p>}</p>
<p>As you can observe the code is a compilation of all the functions I had discussed earlier. The only difference is the error handling code has been used. To use it first declare a global variable of the type SDL_Surface:</p>
<p><strong>SDL_Surface *screen=NULL;</strong></p>
<p>Then call the display_bmp() as follows:</p>
<p>int main(int argc,char* argv[])</p>
<p>{</p>
<p><strong>/*variable to hold the file name of the image to be loaded</strong></p>
<p><strong> *In real world error  handling  code would precede this                                                                          */</strong></p>
<p><strong> char* filename=”Tux.bmp”;</strong></p>
<p>/*The following code does the initialization for Audio and Video*/</p>
<p>int i_error=SDL_Init(SDL_INIT_VIDEO);</p>
<p>/*If initialization is unsuccessful, then quit */</p>
<p>if(i_error==-1)</p>
<p>exit(1);</p>
<p>atexit(SDL_Quit);</p>
<p>/*</p>
<p>* Initialize the display in a 640&#215;480 8-bit palettized mode,</p>
<p>* requesting a software surface</p>
<p>*/</p>
<p>screen = SDL_SetVideoMode(640, 480, 8, SDL_SWSURFACE);</p>
<p>if ( screen == NULL )</p>
<p>{</p>
<p>fprintf(stderr, &#8220;Couldn&#8217;t set 640x480x8 video mode: %s\n&#8221;,</p>
<p>SDL_GetError());</p>
<p>exit(1);</p>
<p>}</p>
<p><strong>/* Now call the function to load the image and copy it to the screen surface*/</strong></p>
<p><strong> load_bmp(filename);</strong></p>
<p>}</p>
<p>That brings us to the end of this part of the discussion on SDL. In the next part I would discuss about working at pixel level and handling keyboard events. Till next time.</p>
<br />Filed under: <a href='http://aprajshekhar.wordpress.com/category/sdl/'>SDL</a> Tagged: <a href='http://aprajshekhar.wordpress.com/tag/cc/'>C/C++</a>, <a href='http://aprajshekhar.wordpress.com/tag/game-programming/'>game-programming</a>, <a href='http://aprajshekhar.wordpress.com/tag/linux/'>Linux</a>, <a href='http://aprajshekhar.wordpress.com/tag/sdl/'>SDL</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/aprajshekhar.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/aprajshekhar.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/aprajshekhar.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/aprajshekhar.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/aprajshekhar.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/aprajshekhar.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/aprajshekhar.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/aprajshekhar.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/aprajshekhar.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/aprajshekhar.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/aprajshekhar.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/aprajshekhar.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/aprajshekhar.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/aprajshekhar.wordpress.com/117/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=aprajshekhar.wordpress.com&amp;blog=5963225&amp;post=117&amp;subd=aprajshekhar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://aprajshekhar.wordpress.com/2010/07/06/sdl-programming-in-linux-playing-with-graphics/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/655da95aab86392587def3f9196de1ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">aprajshekhar</media:title>
		</media:content>
	</item>
		<item>
		<title>Bluetooth Programming in Python: Network Programming using RFCOMM</title>
		<link>http://aprajshekhar.wordpress.com/2010/05/23/bluetooth-programming-in-python-network-programming-using-rfcomm/</link>
		<comments>http://aprajshekhar.wordpress.com/2010/05/23/bluetooth-programming-in-python-network-programming-using-rfcomm/#comments</comments>
		<pubDate>Sun, 23 May 2010 13:14:41 +0000</pubDate>
		<dc:creator>AP Rajshekhar</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[bluetooth]]></category>
		<category><![CDATA[Smart mobile]]></category>

		<guid isPermaLink="false">http://aprajshekhar.wordpress.com/?p=113</guid>
		<description><![CDATA[If one wants to create a client-server based application using Bluetooth, then one should program for the RFCOMM profile. RFCOMM provides socket based client-server paradigm for providing services. In this article, I will focus on creating networked based application using RFCOMM. The first section will be about the whys and wherefores of RFCOMM. In the second section, I will enumerate the steps to create client-server based application using RFCOMM. In the last section, a single-threaded server will be developed that would use RFCOMM to provide a file transfer service. That’s the outline for this discussion.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=aprajshekhar.wordpress.com&amp;blog=5963225&amp;post=113&amp;subd=aprajshekhar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In the last article I discussed about various Bluetooth profiles. If one wants to create a client-server based application using Bluetooth, then one should program for the RFCOMM profile. RFCOMM provides socket based client-server paradigm for providing services. In this article, I will focus on creating networked based application using RFCOMM. The first section will be about the whys and wherefores of RFCOMM. In the second section, I will enumerate the steps to create client-server based application using RFCOMM. In the last section, a single-threaded server will be developed that would use RFCOMM to provide a file transfer service. That’s the outline for this discussion.</p>
<p><strong>RFCOMM – The Whys and Wherefores:</strong></p>
<p>The term or abbreviation RFCOMM comes from the terms Radio Frequency or RF. The main aspect of RFCOMM is emulation of serial port communication using Radio Frequency, so the name RFCOMM. The serial port emulated by RFCOMM is RS-232 which has 9-circuits. RFCOMM uses the baseband of Bluetooth to provide reliable and in-sequence delivery of data stream. The main attributes of RFCOMM are:</p>
<p>1. It provides multiple concurrent connections. It does this by relying on L2CAP.</p>
<p>L2CAP can handle multiplexing over a single connection.</p>
<p>2. It supports flow control on separate and individual channels.</p>
<p>3. It does not provide error-control. The assumption that RFCOMM makes is L2CAP</p>
<p>will be providing error-free channel.</p>
<p>4. How devices should communicate using RFCOMM is decided by Serial Port Profile</p>
<p>(SPP), which is one of the Bluetooth profiles.</p>
<p>RFCOMM divides devices into two major classes. They are:</p>
<p>1. Type I</p>
<p>2. Type II</p>
<p>The division is based on whether the port is physically present or it is emulated. Here are the details</p>
<p>1. Type I:</p>
<p>The devices of this type have emulated serial ports. Emulated ports are entities used to map system specific services and their API to the RFCOMM services. Therefore, whenever applications are built for RFCOMM, then Type I devices are used. In other words, Type I Devices enable programmer to use serial port even if there is no physical serial port.</p>
<p>2. Type II:</p>
<p>These devices have physical serial ports. They act as intermediate devices. In other words, they are proxy for relaying transmissions from RFCOMM to an external RS-232 interfaces that may be linked with other devices.</p>
<p>As I have said before, RFCOMM provides a client-server based paradigm. In case of PyBluez, the client-server is based on sockets. And the steps to create them are similar to the steps that one would follow in creating TCP/IP or UDP based sockets. The next section is about those steps. Lets get started with the steps.</p>
<p><strong>Developing Applications for RFCOMM – Step by Step:</strong></p>
<p>The steps to develop RFCOMM based applications can be divided into two main set of steps. They are:</p>
<p>1. Creating the Server</p>
<p>2. Creating the Client</p>
<p>Each of the steps can be again divided into sub-steps. Let us take each step one at a time.</p>
<p>1. Creating the Server:</p>
<p>The server of RFCOMM applications, are essentially, Bluetooth based services. This has to be kept in mind when developing the server. The importance of this point will become clear in the steps regarding the client. Creating the server can be further divided into following steps</p>
<p>a. Creating the Server Socket</p>
<p>b. Binding to a port</p>
<p>c. Listening for requests</p>
<p>d. Accepting the requests</p>
<p>e. Sending data</p>
<p>The steps are same as that for creating TCP/IP-based server. However, the first and last step differs in the case of RFCOMM. The details are as follows</p>
<p>a. Creating the Server Socket:</p>
<p>First step is to create the socket that would listen for and accepts incoming requests and creates the connection. The sockets one would use, when working with RFCOMM, are Bluetooth sockets. To create a Bluetooth socket, BluetoothSocket needs to be called with the protocol to be used. In this case it is RFCOMM. So, in order to create a socket named server_socket the statement will be:</p>
<p><strong>server_socket= Bluetooth.BluetoothSocket(Bluetooth.RFCOMM)</strong></p>
<p><strong> </strong></p>
<p>This statement only creates a simple Bluetooth based socket that uses RFCOMM for communication. The next three steps make it a server socket.</p>
<p>b. Binding to a Port:</p>
<p>This is the second step to make a simple socket work as server socket. The socket object needs to be bound to an address and a port so that it can start listening for requests. However, since the socket will be communicating over Bluetooth, IP address is not required. PyBluez will use the address of the device on which it is running. If the device is a Desktop PC, then the address will correspond to the address provided by the Bluetooth adapter or dongle. To bind a socket object to a port, bind() method needs to b called on the socket object. The argument passed is a tuple containing the address and the port no. with which the socket has to be bound. For example, to bind a socket to a port, say 11, the statement will be</p>
<p><strong>server_socket.bind((“”,11))</strong></p>
<p><strong> </strong></p>
<p>One point to keep in mind while working with RFCOMM is that RFCOMM uses ports between 1-30 only.</p>
<p><strong> </strong></p>
<p>c. Listening for requests:</p>
<p>Once a socket has been bound to a port, next step is to make it listen for</p>
<p>incoming requests. To do this, listen() method needs to be called on the socket object. The listen() method accepts no. of requests to be kept in queue as the argument. For example, to make a socket start listening with a queue of size 3, the statement will be</p>
<p><strong> server_socket.listen(3)</strong></p>
<p><strong> </strong></p>
<p><strong> </strong>d. Accepting the requests:</p>
<p>Once a request is received, it has to be accepted so that communication can start. To do so, one has to call accept() method on the socket object. The accept() method doesn’t have any arguments. It returns a tuple containing the address of the client and socket object through which further communication can be done. So the statement to accept connection is</p>
<p><strong>client_socket,address=server_socket.accept()</strong></p>
<p><strong> </strong></p>
<p><strong> </strong>e. Sending/receiving data:</p>
<p>The last step is sending and/or receiving data. If the server is on the desktop pc or normal pc, then sending and receiving can be done using Python library. However, if the server is on say, a smart phone, then the library required will be based on the OS of the smart phone. For a normal PC, one would have to call send() and recv() methods on the socket object returned by the accept() method. Both accept string as arguments. For example, if server wants to send a message say, “hello”, the code will be</p>
<p><strong>client_socket.send(“Hello from server”)</strong></p>
<p>That completes server part. Next comes the client.</p>
<p>2. Developing the Client</p>
<p>The steps to develop the client are almost common to that of developing the server. The steps are</p>
<p>a. Create a socket</p>
<p>b. Connect to a device</p>
<p>c. Sending/receiving data</p>
<p>The first and third steps are same as that of creating the server. So only second step needs scrutinizing. Here are the details</p>
<p>a. Create a socket</p>
<p>Just as with server socket, to create a client socket BluetoothSocket() needs to be called with RFCOMM as the protocol. So, to create a socket that would connect to a server, the statement will be</p>
<p><strong>client_socket= Bluetooth.BluetoothSocket(Bluetooth.RFCOMM)</strong></p>
<p><strong> </strong>b. Connect to a device:</p>
<p>To connect to a server, client needs to know the address of the server. In case of Bluetooth, the address will be the address of the device, which is of the form “XX:XX:XX:XX:XX”. So, to connect to a server running on a device with an address of “01:23:45:67:89:AB”, connect() method needs to be called on socket object with the port no and address of the server. For example, if the server port no is 4000 and address is “01:23:45:67:89:AB”, then the statement to connect to it is</p>
<p><strong> address=“01:23:45:67:89:AB”</strong></p>
<p><strong> port=4000</strong></p>
<p><strong> client_sock.connect((address, port))</strong></p>
<p>c. Sending/receiving data:</p>
<p>At the client side too, the way to send and /or receive data is same as that at the server-side. So, to receive any data from the server, the statement will be</p>
<p><strong> </strong></p>
<p><strong> data = client_sockect.recv(1024)</strong></p>
<p><strong>print &#8220;received [%s]&#8221; % data </strong></p>
<p><strong> </strong></p>
<p>That completes the steps to create a client and a server. Next, let us see how to develop a server that transfers a file using Bluetooth and RFCOMM.</p>
<p><strong>RFCOMM in Real World:</strong></p>
<p>The server will service only one client at a time. So, it is neither multithreaded nor multi-process based. Let us start. First comes the imports</p>
<p><strong>from bluetooth import *</strong></p>
<p>Then comes the class that will contain the server functionalities. Its constructor will take port no on which the server has to listen. It will also call the create_server function.</p>
<p>from bluetooth import *</p>
<p><strong>class rfcomm_server:</strong></p>
<p><strong> def __init__(self,port):</strong></p>
<p><strong> self.port=port</strong></p>
<p><strong> self.create_server()</strong></p>
<p>Next is the create_server method that will create a RFCOMM based socket and make it listen on the passed port. It then calls the start_server method.</p>
<p>from bluetooth import *</p>
<p>class rfcomm_server:</p>
<p>def __init__(self,port):</p>
<p>self.port=port</p>
<p>self.create_server()</p>
<p>def create_server(self):</p>
<p><strong>self.server_socket=\ </strong></p>
<p><strong>Bluetooth.BluetoothSocket(Bluetooth.RFCOMM)</strong></p>
<p><strong>self</strong>.<strong>server_socket.bind((“”,self.port))</strong></p>
<p><strong>self.start_server()</strong></p>
<p><strong> </strong></p>
<p>Next is the start_server method. This method makes the server listen on the port and then starts the connection. After that it asks the user for the file and then transfers it.</p>
<p>from bluetooth import *</p>
<p>class rfcomm_server:</p>
<p>def __init__(self,port):</p>
<p>self.port=port</p>
<p>self.create_server()</p>
<p>def create_server(self):</p>
<p>self.server_socket=\</p>
<p>Bluetooth.BluetoothSocket(Bluetooth.RFCOMM)</p>
<p>self.server_socket.bind((“”,self.port))</p>
<p>self.start_server()<strong> </strong></p>
<p><strong>def start_server(self):</strong></p>
<p><strong>while true:</strong></p>
<p><strong>self.server_socket.listen(3)</strong></p>
<p><strong> self.client_socket,address=server_socket.accept()</strong></p>
<p><strong> self.client_socket.send(“Enter the file name”)</strong></p>
<p><strong> file_name= self.client_socket.recv(2048)</strong></p>
<p><strong> </strong></p>
<p><strong> if file_name is not None:</strong></p>
<p><strong> transfer_data=open(file_name,’r’).readlines()</strong></p>
<p><strong> </strong></p>
<p><strong> for data in transfer_data:</strong></p>
<p><strong> self.client_socket.send(data)</strong></p>
<p><strong> </strong></p>
<p><strong> self.client_socket.send(“Transfer complete”)</strong></p>
<p>Next, let us start the server. To do that first we need to check whether main function is being executed. If it is being executed, then create the instance of server.</p>
<p>from bluetooth import *</p>
<p>class rfcomm_server:</p>
<p>def __init__(self,port):</p>
<p>self.port=port</p>
<p>self.create_server()</p>
<p>def create_server(self):</p>
<p>self.server_socket=\</p>
<p>Bluetooth.BluetoothSocket(Bluetooth.RFCOMM)</p>
<p>self.server_socket.bind((“”,self.port))</p>
<p>self.start_server()<strong> </strong></p>
<p>def start_server(self):</p>
<p>while true:</p>
<p>self.server_socket.listen(3)</p>
<p>self.client_socket,address=server_socket.accept()</p>
<p>self.client_socket.send(“Enter the file name”)</p>
<p>file_name= self.client_socket.recv(2048)</p>
<p>if file_name is not None:</p>
<p>transfer_data=open(file_name,’r’).readlines()</p>
<p>for data in transfer_data:</p>
<p>self.client_socket.send(data)</p>
<p>self.client_socket.send(“Transfer complete”)</p>
<p><strong>if ‘__name__’==’__main__’:</strong></p>
<p><strong> server=rfcomm_server(20)</strong></p>
<p><strong> </strong></p>
<p>That completes the application. It also brings us to the end of this discussion. The discussion until now has not touched upon the topic of service discovery. The next part of discussion will be about service discovery. Till then…</p>
<br />Filed under: <a href='http://aprajshekhar.wordpress.com/category/python/'>Python</a> Tagged: <a href='http://aprajshekhar.wordpress.com/tag/bluetooth/'>bluetooth</a>, <a href='http://aprajshekhar.wordpress.com/tag/python/'>Python</a>, <a href='http://aprajshekhar.wordpress.com/tag/smart-mobile/'>Smart mobile</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/aprajshekhar.wordpress.com/113/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/aprajshekhar.wordpress.com/113/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/aprajshekhar.wordpress.com/113/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/aprajshekhar.wordpress.com/113/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/aprajshekhar.wordpress.com/113/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/aprajshekhar.wordpress.com/113/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/aprajshekhar.wordpress.com/113/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/aprajshekhar.wordpress.com/113/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/aprajshekhar.wordpress.com/113/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/aprajshekhar.wordpress.com/113/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/aprajshekhar.wordpress.com/113/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/aprajshekhar.wordpress.com/113/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/aprajshekhar.wordpress.com/113/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/aprajshekhar.wordpress.com/113/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=aprajshekhar.wordpress.com&amp;blog=5963225&amp;post=113&amp;subd=aprajshekhar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://aprajshekhar.wordpress.com/2010/05/23/bluetooth-programming-in-python-network-programming-using-rfcomm/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/655da95aab86392587def3f9196de1ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">aprajshekhar</media:title>
		</media:content>
	</item>
		<item>
		<title>Getting Started with Hibernate 3 &#8211; Part 1</title>
		<link>http://aprajshekhar.wordpress.com/2010/05/05/getting-started-with-hibernate-3-part-1/</link>
		<comments>http://aprajshekhar.wordpress.com/2010/05/05/getting-started-with-hibernate-3-part-1/#comments</comments>
		<pubDate>Wed, 05 May 2010 00:57:46 +0000</pubDate>
		<dc:creator>AP Rajshekhar</dc:creator>
				<category><![CDATA[Database Programming]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Hibernate 3]]></category>
		<category><![CDATA[ORM frameworks]]></category>

		<guid isPermaLink="false">http://aprajshekhar.wordpress.com/?p=107</guid>
		<description><![CDATA[The chasm between the Object Oriented approach followed by almost all the language or platforms on which applications are developed and the language used by database servers (SQL) is considerably big. This divide exists because the application development languages/platforms deals with objects, attributes and classes whereas SQL deals with rows, columns and tables. There are many frameworks that provide the means to bridge this gap. These frameworks do so by mapping the database artefacts to their object oriented counterparts. Such frameworks are called Object Relational Mapping or ORM frameworks. In the world of Java, Hibernate is one of the widely used ORM frameworks. In its 2.x version, Hibernate depended on XML files to map Java artefacts to Database artefacts. However, in 3.0 and above, Hibernate provides annotations as an alternative to the XML based mapping. Use of annotations in Hibernate will be the focus of this discussion.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=aprajshekhar.wordpress.com&amp;blog=5963225&amp;post=107&amp;subd=aprajshekhar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The chasm between the Object Oriented approach followed by almost all the language or platforms on which applications are developed and the language used by database servers (SQL) is considerably big. This divide exists because the application development languages/platforms deals with objects, attributes and classes whereas SQL deals with rows, columns and tables. There are many frameworks that provide the means to bridge this gap. These frameworks do so by mapping the database artefacts to their object-oriented counterparts. Such frameworks are called Object Relational Mapping or ORM frameworks. In the world of Java, Hibernate is one of the widely used ORM frameworks. In its 2.x version, Hibernate depended on XML files to map Java artefacts to Database artefacts. However, in 3.0 and above, Hibernate provides annotations as an alternative to the XML based mapping. Use of annotations in Hibernate will be the focus of this discussion. The first section will be about the whys and wherefores of annotations in Hibernate. In the second section, the focus will be on the steps required to use the annotations for relational-object mapping. The third section will be about a real world example that makes use of Hibernate 3 and annotations.</p>
<p><strong>Annotations in Hibernate – the Whys and Wherefores</strong></p>
<p>To understand annotation used in Hibernate, two aspects need to be understood. They are</p>
<p>1. Annotations in Java</p>
<p>2. Annotations in Hibernate</p>
<p>Between these two aspects, former of the deals with annotations in general and  later  deals with annotations specific to Hibernate. Here are the details.</p>
<p><strong>1. Annotations in Java</strong><br />
Before we move onto how Hibernate makes use of annotations, let us take a bird’s eye view of what<br />
annotations are. By definition Annotations are “is a special form of syntactic metadata that can be added to<br />
Java source code. Classes, methods, variables, parameters and packages may be annotated. Unlike Javadoc<br />
tags, Java annotations can be reflective in that they can be embedded in class files generated by the<br />
compiler and may be retained by the Java VM to be made retrievable at run-time”. From the definition it is<br />
clear that Annotations in Java have two components. They are:</p>
<p>a. The Metadata</p>
<p>It is of the form “@” where  is the name of the metadata. Annotations are metadata of<br />
this form. They can be used to decorate classes, methods, variables, parameters and packages. For<br />
example, the following statements tell the metadata processor that the method is overriding the method<br />
of the base class</p>
<p><strong> @override</strong></p>
<p><strong> Public void display(String name)</strong></p>
<p><strong> {</strong></p>
<p><strong> System.out.println(“Hello “+ name);</strong></p>
<p><strong> }</strong></p>
<p>One important point to keep in mind is that annotations are not discarded after compilation to byte code.<br />
By applying certain policies, they can be retained during runtime. This is not the case with Javadoc tags.<br />
Once compiled, they are lost. In other words, the byte code does not contain the Javadoc tags.</p>
<p>b. The Metadata Processor</p>
<p>It comes into picture during compilation. Metadata Processors or Annotation Processors, as they are<br />
commonly called, are plug-ins to the compiler. A Processor can do a variety of things for the annotated<br />
code including generation of source code files. One important point about Processors is that cannot do<br />
any modification to the annotated code.</p>
<p>That completes the bird’s eye view of Annotations. Let us move onto Annotations in Hibernate.</p>
<p><strong>2. Annotations in Hibernate</strong></p>
<p>Any ORM does four basic mapping. They are:</p>
<p>a. Table mapping</p>
<p>b. Column mapping</p>
<p>c. Key mapping</p>
<p>d. Relationship mapping</p>
<p>How each framework performs the mapping is what makes them different or unique, so is how each<br />
framework wants mapping to be described. Hibernate allows the mapping to be described using either XML<br />
file or Annotations. These two options cannot be mixed and matched. Let us see how Hibernate uses<br />
Annotations for describing the mappings. However, among the four mappings mentioned above, Relationship<br />
mapping will not be a part of this discussion as it is out scope.</p>
<p>a. Table mapping</p>
<p>To map a table, @Table is used. It takes the name of the table that is passed using the <em>name </em>property of the<br />
@Table annotation. For example, the following statements map a table named ‘Products’ to a class named<br />
Product</p>
<p><strong>@Table (name=”Products”)</strong></p>
<p><strong> public class Products {</strong></p>
<p><strong> //&#8230;other declarations</strong></p>
<p><strong> }</strong></p>
<p>b. Column mapping</p>
<p>The annotation used to map a column of a table to an attribute of a class is @Column. The name of the<br />
column of the table to be mapped is passed to the annotation using the <em>name </em>property of the @Column.<br />
Following statements map ‘Product_name’ column of ‘Products’ table to ‘name’ field of ‘Products’ class.</p>
<p>@Table (name=”Products”)</p>
<p>public class Products {</p>
<p>//&#8230;other declarations</p>
<p><strong> @Column (name=”Product_name”)</strong></p>
<p><strong> String name;</strong></p>
<p>}</p>
<p>c. Key mapping:</p>
<p>Key, in this context, means Primary key of the table being mapped. The @Id annotation is used to map a<br />
field of a class to the Primary key column of the table. @Id is used along with @Column. More specifically,<br />
@Id is used for a field that is already decorated with @Column. The reason is that unless a field is mapped to<br />
a column, the field cannot be considered for Primary key mapping. For example, the following statements<br />
map a field named ‘productId’ to the primary key of the table ‘Products’</p>
<p>@Table (name=”Products”)</p>
<p>public class Products {</p>
<p>//&#8230;other declarations</p>
<p><strong> @Id </strong></p>
<p><strong> @Column (name=”Product_id”)</strong></p>
<p><strong> long productId;</strong></p>
<p>}</p>
<p>That completes the whys and wherefores of Annotations in general and how annotations are used in<br />
Hibernate. Let’s move on to the steps for using annotations for mapping.</p>
<br />Filed under: <a href='http://aprajshekhar.wordpress.com/category/database-programming/'>Database Programming</a>, <a href='http://aprajshekhar.wordpress.com/category/hibernate/'>Hibernate</a>, <a href='http://aprajshekhar.wordpress.com/category/java/'>Java</a>, <a href='http://aprajshekhar.wordpress.com/category/uncategorized/'>Uncategorized</a> Tagged: <a href='http://aprajshekhar.wordpress.com/tag/hibernate-3/'>Hibernate 3</a>, <a href='http://aprajshekhar.wordpress.com/tag/java/'>Java</a>, <a href='http://aprajshekhar.wordpress.com/tag/orm-frameworks/'>ORM frameworks</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/aprajshekhar.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/aprajshekhar.wordpress.com/107/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/aprajshekhar.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/aprajshekhar.wordpress.com/107/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/aprajshekhar.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/aprajshekhar.wordpress.com/107/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/aprajshekhar.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/aprajshekhar.wordpress.com/107/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/aprajshekhar.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/aprajshekhar.wordpress.com/107/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/aprajshekhar.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/aprajshekhar.wordpress.com/107/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/aprajshekhar.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/aprajshekhar.wordpress.com/107/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=aprajshekhar.wordpress.com&amp;blog=5963225&amp;post=107&amp;subd=aprajshekhar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://aprajshekhar.wordpress.com/2010/05/05/getting-started-with-hibernate-3-part-1/feed/</wfw:commentRss>
		<slash:comments>56</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/655da95aab86392587def3f9196de1ca?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">aprajshekhar</media:title>
		</media:content>
	</item>
	</channel>
</rss>
