<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>Programming on Abdullah Diab&#39;s Blog</title>
    <link>https://mpcabd.xyz/tags/programming/</link>
    <description>Recent content in Programming on Abdullah Diab&#39;s Blog</description>
    <generator>Hugo</generator>
    <language>en-us</language>
    <lastBuildDate>Fri, 31 Jul 2015 20:54:36 +0000</lastBuildDate>
    <atom:link href="https://mpcabd.xyz/tags/programming/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>Verifying User Input – Thinking Outside The Box</title>
      <link>https://mpcabd.xyz/verifying-user-input-thinking-outside-the-box/</link>
      <pubDate>Fri, 31 Jul 2015 20:54:36 +0000</pubDate>
      <guid>https://mpcabd.xyz/verifying-user-input-thinking-outside-the-box/</guid>
      <description>&lt;p&gt;Now I’m not going to talk about user input validation, no that’s something that’s been covered a lot around the web, I’m going to talk about something else.&lt;/p&gt;
&lt;p&gt;Let’s imagine you are designing a game, where the user can create a puzzle, for example a maze, and you want to verify that what the user has input is a valid maze, that if played by another player that player will have a chance of winning it. Normally the solution that would come to your (and mine) mind is to try to solve that maze automatically – also we’re not going to talk about the different algorithms for solving mazes – but there is another way to do it that no one told us about in Algorithms 101!&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>Now I’m not going to talk about user input validation, no that’s something that’s been covered a lot around the web, I’m going to talk about something else.</p>
<p>Let’s imagine you are designing a game, where the user can create a puzzle, for example a maze, and you want to verify that what the user has input is a valid maze, that if played by another player that player will have a chance of winning it. Normally the solution that would come to your (and mine) mind is to try to solve that maze automatically – also we’re not going to talk about the different algorithms for solving mazes – but there is another way to do it that no one told us about in Algorithms 101!</p>
<p>Guess what! You can verify it manually! Yes Yes I know this is super smart right? No one thought about it!</p>
<img class="aligncenter wp-image-446 size-full" src="http://mpcabd.xyz/wp-content/uploads/2015/07/smart-language-blog.jpg" alt="So smart ... duh" width="310" height="232" srcset="https://mpcabd.xyz/wp-content/uploads/2015/07/smart-language-blog.jpg 310w, https://mpcabd.xyz/wp-content/uploads/2015/07/smart-language-blog-300x225.jpg 300w" sizes="(max-width: 310px) 100vw, 310px" />
<p>Come one enough kidding, but yes verifying it manually will save you a lot of work and complexity, and will also mean that other people will have a good chance (not very high necessarily) of solving the puzzle, let’s face it, if a backtracking algorithm is able to solve a puzzle it doesn’t mean that people will be able to do so too, it might be very hard for people to find that solution, so the point here is that by verifying the puzzle manually you can ensure you give people a better and fair chance.</p>
<img class="aligncenter size-full wp-image-447" src="http://mpcabd.xyz/wp-content/uploads/2015/07/JCLdMDveAn.png" alt="Ain't nobody got time for dat" width="310" height="256" srcset="https://mpcabd.xyz/wp-content/uploads/2015/07/JCLdMDveAn.png 310w, https://mpcabd.xyz/wp-content/uploads/2015/07/JCLdMDveAn-300x248.png 300w" sizes="(max-width: 310px) 100vw, 310px" />
<p>Of course I’m not telling you to verify it yourself, that would be nonsense, this is not 1990s, when you would afford verifying user input yourself after you throw it in some queue, now everything seems to be built for the masses and you can’t afford sparing your time or buying someone else’s time to do so. Then what am I talking about?!</p>
<p>Well the idea is not mine unfortunately, I saw the idea in the latest game by <a href="http://www.zeptolab.com/" target="_blank">Zeptolab</a>, an <a href="https://en.wikipedia.org/wiki/Massively_multiplayer_online_game" target="_blank">MMO</a> strategy game called <a href="http://www.zeptolab.com/games/king_of_thieves/" target="_blank">King Of Thieves</a>.<figure id="attachment_443" style="width: 300px" class="wp-caption aligncenter"></p>
<p><a href="http://mpcabd.xyz/wp-content/uploads/2015/07/Screenshot_2015-07-31-19-03-49.png" rel="lightbox[442]" title="Verifying User Input - Thinking Outside The Box"><img class="wp-image-443" src="http://mpcabd.xyz/wp-content/uploads/2015/07/Screenshot_2015-07-31-19-03-49-300x169.png" alt="King Of Thieves Splash Screen" width="300" srcset="https://mpcabd.xyz/wp-content/uploads/2015/07/Screenshot_2015-07-31-19-03-49-300x169.png 300w, https://mpcabd.xyz/wp-content/uploads/2015/07/Screenshot_2015-07-31-19-03-49-1024x576.png 1024w" sizes="(max-width: 300px) 100vw, 300px" /></a><figcaption class="wp-caption-text">King Of Thieves Splash Screen © 2015 Zeptolab</figcaption></figure></p>
<p>In this game you have a dungeon and a chest of gold and some gems, and like all the other strategy games, you get to design your defences to work the best way against your enemies (every other player out there!), and the goal of your design is to make reaching the chest of gold very hard for other thieves (players) who enter your dungeon, but <strong>not impossible or super hard</strong>, and that’s the catch; how do you verify that the user doesn’t make it extremely hard if not impossible for other players to reach his/her gems and gold?</p>
<p>The way the game creators solved it is a creative way – I’m not sure where it comes from and whether it is their original idea or it’s known in the game industry, but personally I only saw it in their game so far -, and this idea is to ask the user who designs the dungeon to prove that he/she can reach the chest within this design, if the user can’t solve the puzzle (reach the chest here), don’t allow him/her to save the design, and don’t run complex algorithms to check if the design is not an impossible design or a very hard design.<figure id="attachment_444" style="width: 300px" class="wp-caption aligncenter"></p>
<p><a href="http://mpcabd.xyz/wp-content/uploads/2015/07/Screenshot_2015-07-31-19-03-09.png" rel="lightbox[442]" title="Verifying User Input - Thinking Outside The Box"><img class="wp-image-444" src="http://mpcabd.xyz/wp-content/uploads/2015/07/Screenshot_2015-07-31-19-03-09-300x169.png" alt="King Of Thieves Splash Screen" width="300" srcset="https://mpcabd.xyz/wp-content/uploads/2015/07/Screenshot_2015-07-31-19-03-09-300x169.png 300w, https://mpcabd.xyz/wp-content/uploads/2015/07/Screenshot_2015-07-31-19-03-09-1024x576.png 1024w" sizes="(max-width: 300px) 100vw, 300px" /></a><figcaption class="wp-caption-text">King Of Thieves Screenshot © 2015 Zeptolab</figcaption></figure></p>
<p>By doing this the user would have to play in his/her own dungeon trying to defeat his/her defences to reach the chest, and by doing so twice in a row we can be sure that other players stand a good and fair chance of solving this puzzle. One thing that might be of a problem is when the user can actually design a good puzzle but he/she is not yet experienced in this game to solve it, then he/she might need to make their designs easier so that they can save them; but for that the game creators saw a chance where they can make money and they would offer you a proven design that works and is hard in exchange of some valuable resource in the game or you can purchase that design for real money.</p>
<p>The other major benefit of this approach is that you end up with a solution to the puzzle – or more than one solution if the user tried two different approaches -, with detailed steps (because you tracked the user while he/she was trying to solve the puzzle). You can use this data to do two important things; 1. You can sell the solution to the players who are trying to solve this puzzle (and betray the user but that’s another moral story), 2. You got yourself a training set for your machine learning algorithms that will be able to mimic the human’s way of solving such puzzles after studying all these massive solutions (and the other ones that users come up with when solving other users’ puzzles themselves).</p>
<p>I find this very genius, don’t you think?!</p>
<p>You can apply this idea to other games where the user creates defences against intruders and still you want to give the intruders a chance not allowing the user to make it impossible for them, and you can generalize the idea to many puzzle games where the user sets up the puzzle for other users.</p>
<p>With this idea the creators of that game spared a lot of time, effort and money from being spent on verifying the user’s input, and I think it’s something that’s worth sharing and applying to other platforms, maybe not only to other games.</p>]]></content:encoded>
    </item>
    <item>
      <title>Get Pattern From an Image in PIL Python</title>
      <link>https://mpcabd.xyz/get-pattern-from-an-image-in-pil-python/</link>
      <pubDate>Mon, 14 Jan 2013 11:14:23 +0000</pubDate>
      <guid>https://mpcabd.xyz/get-pattern-from-an-image-in-pil-python/</guid>
      <description>&lt;p&gt;Two days ago I needed to generate a PIL image that is made up from repeating a pattern – another PIL image – multiple times, I didn’t find a code online to do it so I just wrote this small code to do it, thought might share it to help somebody out there.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>Two days ago I needed to generate a PIL image that is made up from repeating a pattern – another PIL image – multiple times, I didn’t find a code online to do it so I just wrote this small code to do it, thought might share it to help somebody out there.</p>
<pre class="lang:python decode:true">def get_pattern_from_image(file_name, pattern_width, pattern_height):
    import Image
    pattern_image = Image.open(file_name, 'r')
    result_image = Image.new('RGB', (pattern_width, pattern_height))
    x = 0
    while x &lt; pattern_width:
        y = 0
        while y &lt; pattern_height:
            result_image.paste(pattern_image, (x, y))
            y += pattern_image.size[1]
        x += pattern_image.size[0]
    return result_image
</pre>
<p>It&rsquo;s a very simple solution which uses the <a href="http://www.pythonware.com/library/pil/handbook/image.htm#Image.paste" title="The Image Module - Paste" target="_blank">Image.paste</a> method to repeat the pattern.</p>
<p>You can download this snippet of code from here: <a href="https://gist.github.com/4529367" target="_blank"><a href="https://gist.github.com/4529367">https://gist.github.com/4529367</a></a>.</p>
<p>Enjoy 🙂</p>]]></content:encoded>
    </item>
    <item>
      <title>Android Map View With Pan &amp; Zoom Events</title>
      <link>https://mpcabd.xyz/android-map-view-with-pan-zoom-events/</link>
      <pubDate>Thu, 15 Dec 2011 18:29:51 +0000</pubDate>
      <guid>https://mpcabd.xyz/android-map-view-with-pan-zoom-events/</guid>
      <description>&lt;p&gt;I was working an Android application, and I had an activity that contains a map in it, the map is hosted inside a &lt;a href=&#34;http://developer.android.com/resources/tutorials/views/hello-mapview.html&#34;&gt;MapView&lt;/a&gt;. The application had to show some pins over the map, the pins locations are obtained from a web service. I had to retrieve the pins locations after the user pans the map or zooms in or out.&lt;/p&gt;
&lt;p&gt;Google didn’t provide events for panning and zooming inside MapView class, but you can extend the class and do it your self, and that’s what I did.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>I was working an Android application, and I had an activity that contains a map in it, the map is hosted inside a <a href="http://developer.android.com/resources/tutorials/views/hello-mapview.html">MapView</a>. The application had to show some pins over the map, the pins locations are obtained from a web service. I had to retrieve the pins locations after the user pans the map or zooms in or out.</p>
<p>Google didn’t provide events for panning and zooming inside MapView class, but you can extend the class and do it your self, and that’s what I did.</p>
<p><a href="http://mpcabd.xyz/wp-content/uploads/2011/12/Androids.png" rel="lightbox[320]" title="Androids"><img src="http://mpcabd.xyz/wp-content/uploads/2011/12/Androids-300x105.png" alt="" title="Androids" width="300" height="105" class="aligncenter size-medium wp-image-315" srcset="https://mpcabd.xyz/wp-content/uploads/2011/12/Androids-300x105.png 300w, https://mpcabd.xyz/wp-content/uploads/2011/12/Androids.png 766w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<h3 id="listener-interface">Listener Interface</h3>
<pre class="lang:java decode:true">import com.google.android.maps.GeoPoint;

public interface MapViewListener {
	void onPan(GeoPoint oldTopLeft,
			   GeoPoint oldCenter,
			   GeoPoint oldBottomRight,
			   GeoPoint newTopLeft,
			   GeoPoint newCenter,
			   GeoPoint newBottomRight);
	void onZoom(GeoPoint oldTopLeft,
				GeoPoint oldCenter,
				GeoPoint oldBottomRight,
				GeoPoint newTopLeft,
				GeoPoint newCenter,
				GeoPoint newBottomRight,
				int oldZoomLevel,
				int newZoomLevel);
	void onClick(GeoPoint clickedPoint);
}
</pre>
<p>This listener will receive three events, onPan when the user pans the map, onZoom when the user zooms in or out, onClick when the user taps on the map without panning.</p>
<p>Each event will pass useful parameters, which are old and new values for the top left corner, bottom right corner, center point and zoom level.</p>
<h3 id="map-view-code">Map View Code</h3>
<p>The new map view will inherit the MapView class, and define some useful variables:</p>
<pre class="lang:java decode:true">import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;

public class ObservableMapView extends MapView {
	public ObservableMapView(Context context, String apiKey) { super(context, apiKey); }
	public ObservableMapView(Context context, AttributeSet attrs) { super(context, attrs); }
	public ObservableMapView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); }
	
	private GeoPoint mOldTopLeft;
	private GeoPoint mOldCenter;
	private GeoPoint mOldBottomRight;
	private int mOldZoomLevel = -1;
	
	private MapViewListener mMapViewListener;
	public MapViewListener getMapViewListener() { return mMapViewListener; }
	public void setMapViewListener(MapViewListener value) { mMapViewListener = value; }

// ...
}
</pre>
<p>To get touch events we’re going to override the onTouchEvent:</p>
<pre class="lang:java decode:true">@Override
	public boolean onTouchEvent(MotionEvent ev) {
		if (ev.getAction() == MotionEvent.ACTION_UP) {
			GeoPoint newCenter = this.getMapCenter();
			GeoPoint newTopLeft = this.getProjection().fromPixels(0, 0);
			GeoPoint newBottomRight = this.getProjection().fromPixels(this.getWidth(), this.getHeight());
			
			if (this.mMapViewListener != null &&
				newTopLeft.getLatitudeE6() == mOldTopLeft.getLatitudeE6() &&
				newTopLeft.getLongitudeE6() == mOldTopLeft.getLongitudeE6()) {
				mMapViewListener.onClick(this.getProjection().fromPixels((int)ev.getX(), (int)ev.getY()));
			}
		}
		return super.onTouchEvent(ev);
	}
</pre>
<p>Here we’re checking the new coordinates with the old coordinates, if they haven’t changed then the user has tapped on the map, but if they changed then it is a panning event, we’re not going to emit the event of panning now.</p>
<p>To be able to find if the user has zoomed we’re going to override the dispatchDraw method, because it will be called when the user pans or zooms, so it is the place we’re going to check for events in it.</p>
<pre class="lang:java decode:true">@Override
	protected void dispatchDraw(Canvas canvas) {
		super.dispatchDraw(canvas);
		
		GeoPoint newCenter = this.getMapCenter();
		GeoPoint newTopLeft = this.getProjection().fromPixels(0, 0);
		GeoPoint newBottomRight = this.getProjection().fromPixels(this.getWidth(), this.getHeight());
		int newZoomLevel = this.getZoomLevel();
		
		if (mOldCenter == null)
			mOldCenter = newCenter;
		
		if (mOldTopLeft == null)
			mOldTopLeft = newTopLeft;

		if (mOldBottomRight == null)
			mOldBottomRight = newBottomRight;

		if (newTopLeft.getLatitudeE6() != mOldTopLeft.getLatitudeE6() || newTopLeft.getLongitudeE6() != mOldTopLeft.getLongitudeE6()) {
			if (this.mMapViewListener != null) {
				GeoPoint oldTopLeft, oldCenter, oldBottomRight;
				
				oldTopLeft = mOldTopLeft;
				oldCenter = mOldCenter;
				oldBottomRight = mOldBottomRight;
		
				mOldBottomRight = newBottomRight;
				mOldTopLeft = newTopLeft;
				mOldCenter = newCenter;
				
				mMapViewListener.onPan(oldTopLeft,
									   oldCenter,
									   oldBottomRight,
									   newTopLeft,
									   newCenter,
									   newBottomRight);
			}
		}
		
		if (mOldZoomLevel == -1)
			mOldZoomLevel = newZoomLevel;
		else if (mOldZoomLevel != newZoomLevel && mMapViewListener != null) {
			int oldZoomLevel = mOldZoomLevel;
			GeoPoint oldTopLeft, oldCenter, oldBottomRight;
			oldTopLeft = mOldTopLeft;
			oldCenter = mOldCenter;
			oldBottomRight = mOldBottomRight;
	
			mOldZoomLevel = newZoomLevel;
			mOldBottomRight = newBottomRight;
			mOldTopLeft = newTopLeft;
			mOldCenter = newCenter;
			
			mMapViewListener.onZoom(oldTopLeft,
									oldCenter,
									oldBottomRight,
									newTopLeft,
									newCenter,
									newBottomRight,
									oldZoomLevel,
									newZoomLevel);
		}
	}
</pre>
<h3 id="download">Download</h3>
<p>The source code is licensed under the <a href="http://www.gnu.org/copyleft/gpl.html">GNU Public License (GPL)</a>.</p>
<p>You can download the source code from here:</p>
<p><a href="https://github.com/mpcabd/android-map-view-pan-zoom">Project on GitHub</a></p>
<p><a href="https://github.com/mpcabd/android-map-view-pan-zoom/tarball/master">Source code from GitHub</a></p>]]></content:encoded>
    </item>
    <item>
      <title>Log to a file on computer in Android</title>
      <link>https://mpcabd.xyz/log-to-a-file-on-computer-in-android/</link>
      <pubDate>Mon, 12 Dec 2011 19:53:04 +0000</pubDate>
      <guid>https://mpcabd.xyz/log-to-a-file-on-computer-in-android/</guid>
      <description>&lt;p&gt;It’s been a long time since the last time I blogged about something, and many things have changed since then,&lt;/p&gt;
&lt;p&gt;I graduated, got engaged and moved to Dubai.&lt;/p&gt;
&lt;p&gt;I have plenty of things in my mind to blog about, many solutions and many tools that I developed that I’d like to share it with everyone, but I haven’t settled down, and my schedule is not stable yet, so I haven’t got enough time to sort things out and start blogging, anyway this post is simple and it doesn’t need much description so I thought I’d share it with you now.&lt;/p&gt;
&lt;p&gt;&lt;a href=&#34;http://mpcabd.xyz/wp-content/uploads/2011/12/Androids.png&#34; rel=&#34;lightbox[310]&#34; title=&#34;Androids&#34;&gt;&lt;img src=&#34;http://mpcabd.xyz/wp-content/uploads/2011/12/Androids-300x105.png&#34; alt=&#34;&#34; title=&#34;Androids&#34; width=&#34;300&#34; height=&#34;105&#34; class=&#34;aligncenter size-medium wp-image-315&#34; srcset=&#34;https://mpcabd.xyz/wp-content/uploads/2011/12/Androids-300x105.png 300w, https://mpcabd.xyz/wp-content/uploads/2011/12/Androids.png 766w&#34; sizes=&#34;(max-width: 300px) 100vw, 300px&#34; /&gt;&lt;/a&gt;Now let’s move to business, so I was working on an &lt;a href=&#34;http://developer.android.com/index.html&#34; title=&#34;Android Developers&#34;&gt;Android&lt;/a&gt; application and I needed to log some debug messages, normally I’d use &lt;code&gt;Log.d(TAG, message);&lt;/code&gt; and this will send the message to &lt;a href=&#34;http://developer.android.com/guide/developing/tools/logcat.html&#34; title=&#34;logcat | Android Developers&#34;&gt;logcat&lt;/a&gt;, but logcat is not useful for long messages, like for example if I needed to log the response I received from a web service, this response might be long and sending it to logcat will truncate it.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>It’s been a long time since the last time I blogged about something, and many things have changed since then,</p>
<p>I graduated, got engaged and moved to Dubai.</p>
<p>I have plenty of things in my mind to blog about, many solutions and many tools that I developed that I’d like to share it with everyone, but I haven’t settled down, and my schedule is not stable yet, so I haven’t got enough time to sort things out and start blogging, anyway this post is simple and it doesn’t need much description so I thought I’d share it with you now.</p>
<p><a href="http://mpcabd.xyz/wp-content/uploads/2011/12/Androids.png" rel="lightbox[310]" title="Androids"><img src="http://mpcabd.xyz/wp-content/uploads/2011/12/Androids-300x105.png" alt="" title="Androids" width="300" height="105" class="aligncenter size-medium wp-image-315" srcset="https://mpcabd.xyz/wp-content/uploads/2011/12/Androids-300x105.png 300w, https://mpcabd.xyz/wp-content/uploads/2011/12/Androids.png 766w" sizes="(max-width: 300px) 100vw, 300px" /></a>Now let’s move to business, so I was working on an <a href="http://developer.android.com/index.html" title="Android Developers">Android</a> application and I needed to log some debug messages, normally I’d use <code>Log.d(TAG, message);</code> and this will send the message to <a href="http://developer.android.com/guide/developing/tools/logcat.html" title="logcat | Android Developers">logcat</a>, but logcat is not useful for long messages, like for example if I needed to log the response I received from a web service, this response might be long and sending it to logcat will truncate it.</p>
<p>So usually in such situations we use files and log whatever we need inside them, but I’m working on an Android phone/emulator, and dealing with files and logging to them and reading them later from the computer will be a tedious thing to do, so I came up with a simple solution to log messages from Android to my computer.</p>
<p>The idea is to create a simple web server that accepts POST requests, these requests have only one parameter which is the data to be logged. I made it as simple as possible, I could have defined levels for logging and tags and other sorts of things, but I wanted a simple solution that wouldn’t take more than five minutes to write and get it working.</p>
<h3 id="simple-web-server">Simple web server</h3>
<p>Since I’m a pythonist geek I couldn’t think of anything better than Python to implement the simple web server, and it was really great, since I didn’t have to write so much code!</p>
<p>I’ll be using <code>HTTPServer</code> and <code>BaseHTTPRequestHandler</code> from <a href="http://docs.python.org/library/basehttpserver.html">BaseHTTPServer</a> module, some <a href="http://docs.python.org/library/threading.html">threading</a> and <a href="http://docs.python.org/library/cgi.html">cgi</a>.</p>
<pre class="lang:python decode:true">from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

import threading
import cgi
import time

IP = '192.168.1.3'
PORT = 5500

LOG_FILE = r'C:\AndroidLogFile.log'

POST_PARAMETER = 'log'
</pre>
<p>I set the server to run on port 5500, don’t ask why I chose this number, I didn’t think of it 😛</p>
<p>I define a function that will execute a function in a separate thread as a daemon thread:</p>
<pre class="lang:python decode:true">def startThread(fn):
    thread = threading.Thread(target=fn)
    thread.setDaemon(True)
    thread.start()
    return thread
</pre>
<p>I define the block of code to be executed when running the server:</p>
<pre class="lang:python decode:true">if __name__ == '__main__':
    httpd = HTTPServer((IP, PORT), lambda *args, **kwargs: LogHandler(*args, **kwargs))
    serve_thread  = startThread(httpd.serve_forever)
    while serve_thread.isAlive():
        serve_thread.join(timeout=1)
</pre>
<p>Here I created an HTTP web server that is bound to the IP/PORT set at the beginning of the script, and I mapped the handler for this web server to a class called LogHandler.</p>
<p>This handler will handle the requests, and hence it’ll handle POST requests and save their contents into the specified file.</p>
<pre class="lang:python decode:true">class LogHandler(BaseHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        BaseHTTPRequestHandler.__init__(self, *args, **kwargs)

    def do_POST(self):
        length = int(self.headers.getheader('content-length'))
        postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)
        f = open(LOG_FILE, 'a')
        f.write('%s:\n%s\n%s\n' % (time.strftime('%Y/%m/%d %H:%M:%S'), postvars[POST_PARAMETER][0], '*' * 20))
        f.close()

        self.send_response(200)
        self.send_header('Content-Type', 'text/plain')
        self.send_header('Cache-Control', 'no-cache')
        self.end_headers()
        self.wfile.write('Saved!')
</pre>
<p>Pretty simple, not more than 35 lines of code!</p>
<p>Now let’s move to the Android/Java side.</p>
<h3 id="androidjava-class">Android/Java class</h3>
<p>This class will be responsible for sending POST requests to the server, I’ll be using Apache classes to do the HTTP requests, and I’ll use some other classes from Java standard library, along with Android log class to log exceptions.</p>
<pre class="lang:java decode:true">import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
</pre>
<p>The class starts with defining some constants:</p>
<pre class="lang:java decode:true">public class LogToFile {
	private static final String LOG_TO_FILE_ADDRESS = "http://192.168.1.3";
	private static final String LOG_TO_FILE_URL = "/";
	private static final String LOG_TO_FILE_LOG_PARAMETER = "log";
	private static final int LOG_TO_FILE_PORT = 5500;
</pre>
<p>Then I define a method that constructs an HTTP POST request to the specified url along with the specified parameters:</p>
<pre class="lang:java decode:true">private static HttpPost Post(String url, HashMap&lt;String, String> params, HashMap&lt;String, ArrayList&lt;String>> arrayParams) {
		try {
			if (!url.endsWith("/"))
				url += "/";
			List&lt;NameValuePair> params_list = null;
			if (params != null) {
				params_list = new LinkedList&lt;NameValuePair>();
				for (Entry&lt;String, String> entry : params.entrySet())
					params_list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
			if (arrayParams != null) {
				if (params_list == null)
					params_list = new LinkedList&lt;NameValuePair>();
				for (Entry&lt;String, ArrayList&lt;String>> entry : arrayParams.entrySet())
					for (String value : entry.getValue())
						params_list.add(new BasicNameValuePair(entry.getKey(), value));
			}
			HttpPost request = new HttpPost(url);
			if (params != null)
				request.setEntity(new UrlEncodedFormEntity(params_list, "utf-8"));
			return request;
		} catch (Exception e) {
			Log.e("", e.getClass().getName() + "\n" + e.getMessage());
		}
		return null;
	}
</pre>
<p>I know this is a lot of code for such thing, but this method is used elsewhere in my application and that’s why it had to be this generic.</p>
<p>Another method will be used to execute the request, also it is generic to be used elsewhere, you can edit the code and make it more specific to your needs.</p>
<pre class="lang:java decode:true">private static HttpResponse ExecuteRequest(HttpUriRequest request) {
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpResponse response = httpclient.execute(request);
			return response;
		} catch (Exception e) {
			Log.e("", e.getClass().getName() + "\n" + e.getMessage());
		}
		return null;
	}
</pre>
<p>And now to the final piece of code here, this is the method that you’ll call from anywhere in your application to log messages to the file:</p>
<pre class="lang:java decode:true">public static void LogToFile(String log) {
		try {
			HashMap&lt;String, String> params = new HashMap&lt;String, String>();
			params.put(LOG_TO_FILE_LOG_PARAMETER, log);
			HttpPost request = Post(String.format("%s:%d%s", LOG_TO_FILE_ADDRESS, LOG_TO_FILE_PORT, LOG_TO_FILE_URL), params, null);
			HttpResponse response = ExecuteRequest(request);
			response.getEntity().consumeContent();
		} catch (Exception e) {
			Log.e("", e.getClass().getName() + "\n" + e.getMessage());
		}
	}
</pre>
<h3 id="download">Download</h3>
<p>The source code is licensed under the <a href="http://www.gnu.org/copyleft/gpl.html">GNU Public License (GPL)</a>.</p>
<p><a href="https://github.com/mpcabd/android-log-to-pc-file">Project on GitHub</a></p>
<p>You can download the source code from here:</p>
<p><a href="https://github.com/mpcabd/android-log-to-pc-file/tarball/master">Source code from GitHub</a></p>]]></content:encoded>
    </item>
    <item>
      <title>Get Online Users in Django</title>
      <link>https://mpcabd.xyz/get-online-users-in-django/</link>
      <pubDate>Mon, 21 Sep 2009 22:41:00 +0000</pubDate>
      <guid>https://mpcabd.xyz/get-online-users-in-django/</guid>
      <description>&lt;p&gt;I was upgrading my &lt;a href=&#34;http://mpcabd.alwaysdata.net/&#34; target=&#34;_blank&#34;&gt;Django Bookmarks&lt;/a&gt; site, and I wanted to list the online users. I searched the internet and I found a &lt;a href=&#34;http://www.djangosnippets.org/snippets/947/&#34; target=&#34;_blank&#34;&gt;simple method&lt;/a&gt;, but it doesn’t work properly. So I developed my own method.&lt;/p&gt;
&lt;h1 id=&#34;why-the-simple-method-didnt-work&#34;&gt;Why the simple method didn’t work?&lt;/h1&gt;
&lt;p&gt;The problem with it is that it depends on the last login date in the user model. This field is updated on every login for the user.&lt;/p&gt;
&lt;p&gt;Imagine the following scenario:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;The user X logs in @ 1:00 pm.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The user X posts a new post @ 1:30 pm.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The user X comments on a previous post @ 1:35 pm.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The user X leaves the website @ 1:40 pm.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The user X comes back to the website @ 3:00 pm.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The user X is logged in since the session cookie has not expired yet.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The user X posts a new post @ 3:15 pm.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;A guest enters the website, and looks at the online users corner.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The guest won’t see X’s name in the list of online users, simply because X’s last login date is @ 1 pm, even though user X is now online and he has just posted a new post.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>I was upgrading my <a href="http://mpcabd.alwaysdata.net/" target="_blank">Django Bookmarks</a> site, and I wanted to list the online users. I searched the internet and I found a <a href="http://www.djangosnippets.org/snippets/947/" target="_blank">simple method</a>, but it doesn’t work properly. So I developed my own method.</p>
<h1 id="why-the-simple-method-didnt-work">Why the simple method didn’t work?</h1>
<p>The problem with it is that it depends on the last login date in the user model. This field is updated on every login for the user.</p>
<p>Imagine the following scenario:</p>
<ul>
<li>
<p>The user X logs in @ 1:00 pm.</p>
</li>
<li>
<p>The user X posts a new post @ 1:30 pm.</p>
</li>
<li>
<p>The user X comments on a previous post @ 1:35 pm.</p>
</li>
<li>
<p>The user X leaves the website @ 1:40 pm.</p>
</li>
<li>
<p>The user X comes back to the website @ 3:00 pm.</p>
</li>
<li>
<p>The user X is logged in since the session cookie has not expired yet.</p>
</li>
<li>
<p>The user X posts a new post @ 3:15 pm.</p>
</li>
<li>
<p>A guest enters the website, and looks at the online users corner.</p>
</li>
</ul>
<p>The guest won’t see X’s name in the list of online users, simply because X’s last login date is @ 1 pm, even though user X is now online and he has just posted a new post.</p>
<h2 id="update-8th-may-2013">UPDATE 8th May 2013</h2>
<p>Please note the solution provided in this post is an old solution, it is coded in a weird way maybe, and it is not the best way to achieve what is required. I’ll write soon a new solution that in my opinion will be far better than this one.</p>
<h1 id="so-what-is-missing-here">So what is missing here?</h1>
<p>The last login date is not enough to tell if the user online or not, we must have another field that tells us when is the last activity date for the user.</p>
<p>In ASP .NET there is a field called LastActivityDate in the users table, and it is used for this specific mission.</p>
<h1 id="when-to-update-last-activity-date">When to update last activity date?</h1>
<p>In ASP .NET you have to update the last activity manually, and there is a good way to do it; in global.asax:</p>
<pre class="lang:c# decode:true">private void Application_AuthenticateRequest(Object source, EventArgs e) {
    //Your Code Goes Here
}
</pre>
<p>In this method you can access the request, get the current user, update his/her last activity date.</p>
<p>So basically updating last activity date is done on the request, when the user makes a request to your application and he/she is authenticated.</p>
<h1 id="but-there-is-no-last-activity-date-in-djangos-user-model">But there is no last activity date in Django’s user model?</h1>
<p>Yeah I know, but you can extend the User module in Django. And to do this there are many ways, one of them is by making a new model with a foreign key to the User. Then you can do whatever you want.</p>
<h1 id="and-where-am-i-going-to-write-the-code-that-will-update-the-last-activity-date">And where am I going to write the code that will update the last activity date?</h1>
<p>In Django we have <a href="http://docs.djangoproject.com/en/dev/topics/http/middleware/" target="_blank">Middleware</a>; a Middleware is a layer that handles something on each request, its input is the request and it can process it or modify it.</p>
<p>So I simply created a new Middleware that takes the request and finds the user, then updates his/her last activity.</p>
<p>I installed the middleware in the settings module, I appended its name after ‘django.contrib.auth.middleware.AuthenticationMiddleware’ in MIDDLEWARE_CLASSES.</p>
<p>There was a problem in doing that, because the user might send many request per page, each image will send a request, and imagine how many updates there is in each page!</p>
<p>The solution is to skip a list of URLs, so if the user requests a URL within this list his/her last activity date won’t be updated. The skip list is stored within the urls.py file.</p>
<p>The skip list will contain regular expressions just like the url_patterns dictionary.</p>
<h1 id="making-the-solution-generic">Making the solution generic</h1>
<p>I wanted to publish this solution, and it had to be generic so you can use it without editing its code.</p>
<p>Making it generic required small modifications:</p>
<ul>
<li>
<p>Making a new application called lastActivityDate.</p>
</li>
<li>
<p>Pasting the extended user model inside models.py.</p>
</li>
<li>
<p>Modifying the settings module and add lastActivityDate to the INSTALLED_APPS list.</p>
</li>
</ul>
<h1 id="extending-the-user-module">Extending the user module</h1>
<pre class="lang:python decode:true">from django.db import models
from django.contrib.auth.models import User
from datetime import datetime

class UserActivity(models.Model):
    last_activity_ip = models.IPAddressField()
    last_activity_date = models.DateTimeField(default = datetime(1950, 1, 1))
    user = models.OneToOneField(User, primary_key=True)
</pre>
<p>Since the User and UserActivity models are now related one-to-one we can now type:</p>
<pre class="lang:python decode:true">a = User.objects.get(username__exact='mpcabd')
print a.useractivity.last_activity_ip

b = UserActivity.objects.get(user=a)
print b.user.username
</pre>
<h1 id="the-middleware">The Middleware</h1>
<pre class="lang:python decode:true">from models import UserActivity
from datetime import datetime
from django.conf import settings
from django.contrib.sites.models import Site
import re

compiledLists = {}

class LastActivityMiddleware(object):
    def process_request(self, request):
        if not request.user.is_authenticated():
            return
        urlsModule = __import__(settings.ROOT_URLCONF, {}, {}, [''])
        skipList = getattr(urlsModule, 'skip_last_activity_date', None)
        skippedPath = request.path
        if skippedPath.startswith('/'):
            skippedPath = skippedPath[1:]
        if skipList is not None:
            for expression in skipList:
                compiledVersion = None
                if not compiledLists.has_key(expression):
                    compiledLists[expression] = re.compile(expression)
                compiledVersion = compiledLists[expression]
                if compiledVersion.search(skippedPath):
                    return
        activity = None
        try:
            activity = request.user.useractivity
        except:
            activity = UserActivity()
            activity.user = request.user
            activity.last_activity_date = datetime.now()
            activity.last_activity_ip = request.META['REMOTE_ADDR']
            activity.save()
            return
        activity.last_activity_date = datetime.now()
        activity.last_activity_ip = request.META['REMOTE_ADDR']
        activity.save()
</pre>
<p>The compiled list is for enhancing performance, each regular expression is compiled one time; when it is accessed the first time.</p>
<p>You can see that I used the settings module to get a the URLs module name. And I used the __import__ function to import the module dynamically.</p>
<p>In line 12 I check if there is a list called ‘skip_last_activity_date’ using the getattr function, passing a third parameter to this functions specifies the default value if the list was not found so I don’t get an exception.</p>
<p>In lines 25 to 37 I get or create the UserActivity object, I update the last activity date using datetime.now(), I update the last activity IP using request.META[‘REMOTE_ADDR’] which gives me the client IP address.</p>
<h1 id="modifying-the-urls-module">Modifying the URLs module</h1>
<p>In the urls.py file insert the following code:</p>
<pre class="lang:python decode:true">skip_last_activity_date = [
    #Your expressions go here
]
</pre>
<h1 id="modifying-the-settings-module">Modifying the settings module</h1>
<p>In the settings.py file insert the following code:</p>
<pre class="lang:python decode:true">#Your settings code
MIDDLEWARE_CLASSES = (
    #Your middleware classes go here
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'lastActivityDate.LastActivityMiddleware.LastActivityMiddleware',
    #Your middleware classes go here
)
#Your settings code
INSTALLED_APPS = (
    #Your installed apps
    'YOUR_APP_FOLDER.lastActivityDate',
    #Your installed apps
)
#Your settings code
</pre>
<p>Replace YOUR_APP_FOLDER with the folder of your application, such that the directory tree is like this:</p>
<pre class="decode:true">YourAppFolder:
--&gt; appFolder
--&gt; …
--&gt; __init__.py
--&gt; views.py
--&gt; models.py
--&gt; …
--&gt; lastActivityDate
--&gt; __init__.py
--&gt; LastActivityMiddleware.py
--&gt; models.py
--&gt; urls.py
--&gt; settings.py
--&gt; __init__.py
--&gt; manage.py
</pre>
<h1 id="ps">P.S.</h1>
<p>Do not forget to synchronize the database using “manage.py syncdb” so that Django creates the lastactivitydate_useractivity table in the database.</p>
<h1 id="getting-online-users">Getting online users</h1>
<p>After this long trip here is how to get online users:</p>
<pre class="lang:python decode:true">from django.contrib.auth.models import User
from datetime import datetime, timedelta
from lastActivityDate.models import UserActivity

def get_online_users(num):
    fifteen_minutes = datetime.now() - timedelta(minutes=15)
    sql_datetime = datetime.strftime(fifteen_minutes, '%Y-%m-%d %H:%M:%S')
    users = UserActivity.objects.filter(last_activity_date__gte=sql_datetime, user__is_active__exact=1).order_by('-last_activity_date')[:num]
    return [u.user for u in users]
</pre>
<p>This function returns a list of users whose last activity was in the last 15 minutes. Of course you can modify it and expand the duration.</p>
<h1 id="download-source-code">Download source code</h1>
<p>Here is the link to download source code of the lastActivityDate application:</p>
<p><a href="http://www.box.net/shared/1prdvejycg" target="_blank">lastActivityDate.tar.gz</a></p>
<p>Notice that the code is written using Python 2.6 and Django 1.0. If you have different version(s) you <strong>might</strong> encounter a problem.</p>
<h1 id="license">License</h1>
<p>This work is licensed under the Creative Commons Attribution-Share Alike 3.0 License.</p>
<p>To view a copy of this license, visit <a href="http://creativecommons.org/licenses/by-sa/3.0/">http://creativecommons.org/licenses/by-sa/3.0/</a>.</p>]]></content:encoded>
    </item>
    <item>
      <title>I’m Learning Python part 10 (last one)</title>
      <link>https://mpcabd.xyz/im-learning-python-part-10-last-one/</link>
      <pubDate>Tue, 15 Sep 2009 22:24:22 +0000</pubDate>
      <guid>https://mpcabd.xyz/im-learning-python-part-10-last-one/</guid>
      <description>&lt;div dir=&#34;ltr&#34;&gt;
  &lt;div style=&#34;text-align:center;&#34; align=&#34;center&#34;&gt;
    &lt;h1 style=&#34;font-size:18pt;font-family:Verdana;&#34;&gt;
      I&#39;m Learning Python part 10
    &lt;/h1&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;p&amp;gt;
  &amp;lt;h1 style=&amp;quot;font-size:18pt;font-family:Verdana;&amp;quot;&amp;gt;
    (last one)
  &amp;lt;/h1&amp;gt;
  
  &amp;lt;p&amp;gt;
    &amp;lt;img src=&amp;quot;http://www.python.org/images/python-logo.gif&amp;quot; alt=&amp;quot;Python Logo&amp;quot; title=&amp;quot;Python Logo&amp;quot; /&amp;gt; &amp;lt;/div&amp;gt; 
    
    &amp;lt;h1 style=&amp;quot;font-family:Georgia;&amp;quot;&amp;gt;
      Back to blogging
    &amp;lt;/h1&amp;gt;
    
    &amp;lt;p&amp;gt;
      As usual, I will apologize for not blogging for a long time.&amp;lt;br /&amp;gt; I have been very busy, university exams, university projects, job projects, teaching and learning.
    &amp;lt;/p&amp;gt;
    
    &amp;lt;h1 style=&amp;quot;font-family:Georgia;&amp;quot;&amp;gt;
      Python Course
    &amp;lt;/h1&amp;gt;
    
    &amp;lt;p&amp;gt;
      At Damascus University, in the faculty of informatics we managed to create free courses to students, and I was one of the teachers there, I taught Python to students.&amp;lt;br /&amp;gt; As far as I know this course was the first Python course in Damascus University.&amp;lt;br /&amp;gt; Even though the students were a few (actually a very little few about 8 ~ 10 students) the course was great. We managed to learn Python 2.6 Syntax, a little bit of its standard library and a little bit of PyQt4 in about 7 days x 2 hours daily.&amp;lt;br /&amp;gt; As far as I know too, students understood it and found it great, and I hope they&amp;amp;#8217;ll be using this great language more in their programs.
    &amp;lt;/p&amp;gt;
    
    &amp;lt;h1 style=&amp;quot;font-family:Georgia;&amp;quot;&amp;gt;
      Why last one?
    &amp;lt;/h1&amp;gt;
    
    &amp;lt;p&amp;gt;
      The tour with Python ends here, while it ends here it starts here too, it ends here because so far you&amp;amp;#8217;ve learned what you need to start your own path in Python. And it starts here because you&amp;amp;#8217;re fully equipped with the base tool to discover more tools, I&amp;amp;#8217;ll let you discover the standard library and 3rd-party libraries on your own, because everyone differs in his/her interests.&amp;lt;br /&amp;gt; I&amp;amp;#8217;ll be blogging more on more technical issues but they might not be I&amp;amp;#8217;m Learning Python series :).&amp;lt;br /&amp;gt; Let&amp;amp;#8217;s stop talking here and move directly to the heart of our last lesson.&amp;lt;br /&amp;gt; 
&lt;/code&gt;&lt;/pre&gt;</description>
      <content:encoded><![CDATA[<div dir="ltr">
  <div style="text-align:center;" align="center">
    <h1 style="font-size:18pt;font-family:Verdana;">
      I'm Learning Python part 10
    </h1>
<pre><code>&lt;p&gt;
  &lt;h1 style=&quot;font-size:18pt;font-family:Verdana;&quot;&gt;
    (last one)
  &lt;/h1&gt;
  
  &lt;p&gt;
    &lt;img src=&quot;http://www.python.org/images/python-logo.gif&quot; alt=&quot;Python Logo&quot; title=&quot;Python Logo&quot; /&gt; &lt;/div&gt; 
    
    &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
      Back to blogging
    &lt;/h1&gt;
    
    &lt;p&gt;
      As usual, I will apologize for not blogging for a long time.&lt;br /&gt; I have been very busy, university exams, university projects, job projects, teaching and learning.
    &lt;/p&gt;
    
    &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
      Python Course
    &lt;/h1&gt;
    
    &lt;p&gt;
      At Damascus University, in the faculty of informatics we managed to create free courses to students, and I was one of the teachers there, I taught Python to students.&lt;br /&gt; As far as I know this course was the first Python course in Damascus University.&lt;br /&gt; Even though the students were a few (actually a very little few about 8 ~ 10 students) the course was great. We managed to learn Python 2.6 Syntax, a little bit of its standard library and a little bit of PyQt4 in about 7 days x 2 hours daily.&lt;br /&gt; As far as I know too, students understood it and found it great, and I hope they&amp;#8217;ll be using this great language more in their programs.
    &lt;/p&gt;
    
    &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
      Why last one?
    &lt;/h1&gt;
    
    &lt;p&gt;
      The tour with Python ends here, while it ends here it starts here too, it ends here because so far you&amp;#8217;ve learned what you need to start your own path in Python. And it starts here because you&amp;#8217;re fully equipped with the base tool to discover more tools, I&amp;#8217;ll let you discover the standard library and 3rd-party libraries on your own, because everyone differs in his/her interests.&lt;br /&gt; I&amp;#8217;ll be blogging more on more technical issues but they might not be I&amp;#8217;m Learning Python series :).&lt;br /&gt; Let&amp;#8217;s stop talking here and move directly to the heart of our last lesson.&lt;br /&gt; 
</code></pre>
<br /> 
<pre><code>      &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
        Revision
      &lt;/h1&gt;
      
      &lt;p&gt;
        The last part introduced classes, how to define them, how to use them. This lesson will continue to explain classes and functions more.&lt;br /&gt; Defining a function:
      &lt;/p&gt;
      
      &lt;pre class=&quot;lang:python decode:true&quot;&gt;
def functionName(param0, param1, ...):
	#Your function code goes here.
	#You can return values using:
	return values
</code></pre>
<p></pre></p>
<pre><code>      &lt;p&gt;
        Defining a class:
      &lt;/p&gt;
      
      &lt;pre class=&quot;lang:python decode:true&quot;&gt;
class ClassName(BaseClass0, BaseClass1, ...):
	#Your class code goes here.
	#Your class ends whenever you go out of the scope (you go back one tab).
</code></pre>
<p></pre></p>
<pre><code>      &lt;p&gt;
        The constructor of the class is defined using the special name __init__:
      &lt;/p&gt;
      
      &lt;pre class=&quot;lang:python decode:true&quot;&gt;
class A:
	def __init__(self, param0, ...):
		#Constructor code goes here.
</code></pre>
<p></pre></p>
<pre><code>      &lt;p&gt;
        The method inside a class is just a function which receives the object instance as its first parameter:
      &lt;/p&gt;
      
      &lt;pre class=&quot;lang:python decode:true&quot;&gt;
class A:
	def myMethod(self, param0, ...):
		#method is just a function
</code></pre>
<p></pre></p>
<pre><code>      &lt;p&gt;
        Properties are fields encapsulated within a function to get their values and might be encapsulated withing a function to set their values. These two functions allow you to do your business logic over the values before allowing the user to read/write them.
      &lt;/p&gt;
      
      &lt;pre class=&quot;lang:python decode:true&quot;&gt;
class A:
	@property
	def Id(self):
		return self.__id

	@Id.setter
	def setId(self, value):
		self.__id = value

	def __init__(self):
		self.__id = 0
</code></pre>
<p></pre></p>
<pre><code>      &lt;p&gt;
        Defining an object instance of the class is done by calling the class constructor:
      &lt;/p&gt;
      
      &lt;pre class=&quot;lang:python decode:true&quot;&gt;
a = A()
</code></pre>
<p></pre></p>
<pre><code>      &lt;p&gt;
        If the constructor takes a list of parameters you &lt;b&gt;might&lt;/b&gt; specify them when calling it:&lt;br /&gt;:
      &lt;/p&gt;
      
      &lt;pre class=&quot;lang:python decode:true&quot;&gt;
class B:
	def __init__(self, name):
		self.name = name

b = B('some name')
</code></pre>
<p></pre></p>
<pre><code>      &lt;p&gt;
        Properties after defining an object instance can be used as if they were fields:
      &lt;/p&gt;
      
      &lt;pre class=&quot;lang:python decode:true&quot;&gt;
a.Id = 10
print a.Id
</code></pre>
<p></pre></p>
<pre><code>      &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
        More and more about functions
      &lt;/h1&gt;
      
      &lt;p&gt;
        Functions can be used in many ways.
      &lt;/p&gt;
      
      &lt;h2&gt;
        Functions with default values
      &lt;/h2&gt;
      
      &lt;p&gt;
        You can let the parameters of the functions have default values, so that if the user didn&amp;#8217;t supply them they&amp;#8217;ll have valid values:
      &lt;/p&gt;
      
      &lt;pre class=&quot;lang:python decode:true&quot;&gt;
def f(id = 1, name = 'some name', age = 10):
	print(str(id) + ' ' + name + ' at age ' + str(age))
#All of the following calls are valid
f()				#Will print: 1 some name at age 10
f(2)			#Will print: 2 some name at age 10
f(2, 'a')		#Will print: 2 a at age 10
f(2, 'a', 3)	#Will print: 2 a at age 3
</code></pre>
<p></pre></p>
<pre><code>      &lt;p&gt;
        What if I want to supply the second paramter without supplying the first one and the third one? The solution is by:
      &lt;/p&gt;
      
      &lt;h2&gt;
        Passing specified parameters
      &lt;/h2&gt;
      
      &lt;p&gt;
        You can choose the paramters you want to supply and with any order you want:
      &lt;/p&gt;
      
      &lt;pre class=&quot;lang:python decode:true&quot;&gt;
#All of the following calls are valid
f(age = 3)						#Wil print: 1 some name at age 3
f(age = 3, id = 2)				#Will print: 2 some name at age 3
f(name = 'a', age = 3, id = 2)	#Will print: 2 a at age 3
</code></pre>
<p></pre></p>
<pre><code>      &lt;p&gt;
        You can see that this way is useful, you can choose which parameters to pass and in what order :).
      &lt;/p&gt;
      
      &lt;h2&gt;
        Passing unlimited count of paramters
      &lt;/h2&gt;
      
      &lt;p&gt;
        Yes you can do it, you can call a function and pass it any count of parameters you want:
      &lt;/p&gt;
      
      &lt;pre class=&quot;lang:python decode:true&quot;&gt;
def u(*args):
	s = ''
	for arg in args:
		s += arg + ' '
	print s
#All of the following calls are valid
u()			#Will print nothing
u(1)		#Will print: 1
u(1, 2)		#Will print: 1 2
u(1, 2, 3)	#Will print: 1 2 3
</code></pre>
<p></pre></p>
<pre><code>      &lt;p&gt;
        So args actually is enumerable type, may be a list ;).
      &lt;/p&gt;
      
      &lt;h2&gt;
        Passing unlimited named parameters
      &lt;/h2&gt;
      
      &lt;p&gt;
        Hmmmm, yes you can too specify names for those unlimited parameters of yours:
      &lt;/p&gt;
      
      &lt;pre class=&quot;lang:python decode:true&quot;&gt;
def uu(**kargs):
	s = ''
	for k, v in kargs.iteritems():
		s += k + ' =&amp;gt; ' + v + ', '
	print s
#All of the following calls are valid
uu()							#Will print nothing
uu(a = 1)						#Will print: a =&amp;gt; 1
uu(a = 1, b = 2)				#Will print: a =&amp;gt; 1, b =&amp;gt; 2,
uu(a = 1, b = 'asd', c = 0.5)	#Will print: a =&amp;gt; 1, b =&amp;gt; 'asd', c =&amp;gt; 0.5,
</code></pre>
<p></pre></p>
<pre><code>      &lt;p&gt;
        So kargs actually is a dictionary.&lt;br /&gt; If you don&amp;#8217;t already know, dictionary.iteritems is a method that iterates over the keys and values of the dictionary, yielding a tuple every iteration, the first item of the tuple is the key, and the other is the value.&lt;br /&gt; dictionary.iteritems is a great method for iterating over a dictionary of unknown keys.
      &lt;/p&gt;
      
      &lt;h2&gt;
        Overloading and why I don&amp;#8217;t need it here
      &lt;/h2&gt;
      
      &lt;p&gt;
        Overloading is simply more than one instance of the same function with one or more of the following points achieved in them:&lt;br /&gt; * The count of parameters differs between them.&lt;br /&gt; * The types of the parameters differ between them.&lt;br /&gt; * The prder of the parameters differ between them.
      &lt;/p&gt;
      
      &lt;p&gt;
        Using what we&amp;#8217;ve learned so far, we can say that the first point can be achieved using one function, by using default values for the parameters.&lt;br /&gt; The second point can also be achieved using one function since Python has no strict data types to variables and parameters.&lt;br /&gt; The third point can also be achieved using one function, by using paramters names while calling you can change the order of parameters passed.&lt;br /&gt; And so I can continue coding without overloading.
      &lt;/p&gt;
      
      &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
        Last Words
      &lt;/h1&gt;
      
      &lt;p&gt;
        After learning how to implement classes and functions properly you can start your path on learning Python standard library and 3rd-party libraries. Python is widely supported and you won&amp;#8217;t find difficulties in using it as your main programming language.&lt;br /&gt; In the last two months I learned how to use Python to develop web applications using Django (pronounced yangoo), and being an expert ASP .NET developer I assure you, Django is easier and more fun to code than ASP .NET. I made a testing website from the book I read &amp;#8211; The book was: &lt;a href=&quot;http://www.packtpub.com/django-1-0-website-development-2nd-edition&quot;&gt;Django 1.0 Website Development&lt;/a&gt;, by my colleague and friend &lt;a href=&quot;http://www.aymanh.com&quot;&gt;Ayman Hourieh&lt;/a&gt; -, the website is for sharing bookmarks, it is now hosted for free at AlwaysData here &lt;a href=&quot;http://mpcabd.alwaysdata.net&quot;&gt;http://mpcabd.alwaysdata.net&lt;/a&gt;&lt;br /&gt; You can do in Python whatever you want with less coding. Enjoy your life more.
      &lt;/p&gt;
      
      &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
        The End
      &lt;/h1&gt;
      
      &lt;p&gt;
        It is the end of this course but the start of your path.&lt;br /&gt; I hope you enjoyed it, and that I could give you the information in a nice and easy way.&lt;br /&gt; For any questions or suggestions you can leave your comments here.&lt;br /&gt; Thanks for being patient :).&lt;br /&gt; &amp;#8212; Abd Allah Diab &lt;/div&gt;
</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>I’m Learning Python part 9</title>
      <link>https://mpcabd.xyz/im-learning-python-part-9/</link>
      <pubDate>Fri, 20 Mar 2009 00:35:21 +0000</pubDate>
      <guid>https://mpcabd.xyz/im-learning-python-part-9/</guid>
      <description>&lt;div dir=&#34;ltr&#34;&gt;
  &lt;div style=&#34;text-align:center;&#34;&gt;
    &lt;h1 style=&#34;font-size:18pt;font-family:Verdana;&#34;&gt;
      I&amp;#8217;m Learning Python part 9
    &lt;/h1&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;p&amp;gt;
  &amp;lt;img title=&amp;quot;Python Logo&amp;quot; src=&amp;quot;http://www.python.org/images/python-logo.gif&amp;quot; alt=&amp;quot;Python Logo&amp;quot; /&amp;gt;&amp;lt;/div&amp;gt; 
  
  &amp;lt;h1 style=&amp;quot;font-family:Georgia;&amp;quot;&amp;gt;
    Classes In Python
  &amp;lt;/h1&amp;gt;
  
  &amp;lt;div dir=&amp;quot;ltr&amp;quot;&amp;gt;
    As I told you before, Python is a powerful programming language, and powerful it won&amp;amp;#8217;t be without Object Oriented design.
  &amp;lt;/div&amp;gt;
  
  &amp;lt;div dir=&amp;quot;ltr&amp;quot;&amp;gt;
    Python supports both Pure Object Oriented Programming (Every thing must be in a class) and Structural Programming (You can type code everywhere).
  &amp;lt;/div&amp;gt;
  
  &amp;lt;div dir=&amp;quot;ltr&amp;quot;&amp;gt;
    It supports also other programming paradigms like Functional Programming. I won&amp;amp;#8217;t write about OOP and its uses, why we should use it, I&amp;amp;#8217;ll just give you the keys to use OOP in Python.
  &amp;lt;/div&amp;gt;
  
  &amp;lt;h1 style=&amp;quot;font-family:Georgia;&amp;quot;&amp;gt;
    Defining a Class
  &amp;lt;/h1&amp;gt;
  
  &amp;lt;p&amp;gt;
    Classes in Python are defined like this:
  &amp;lt;/p&amp;gt;
  
  &amp;lt;p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;</description>
      <content:encoded><![CDATA[<div dir="ltr">
  <div style="text-align:center;">
    <h1 style="font-size:18pt;font-family:Verdana;">
      I&#8217;m Learning Python part 9
    </h1>
<pre><code>&lt;p&gt;
  &lt;img title=&quot;Python Logo&quot; src=&quot;http://www.python.org/images/python-logo.gif&quot; alt=&quot;Python Logo&quot; /&gt;&lt;/div&gt; 
  
  &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
    Classes In Python
  &lt;/h1&gt;
  
  &lt;div dir=&quot;ltr&quot;&gt;
    As I told you before, Python is a powerful programming language, and powerful it won&amp;#8217;t be without Object Oriented design.
  &lt;/div&gt;
  
  &lt;div dir=&quot;ltr&quot;&gt;
    Python supports both Pure Object Oriented Programming (Every thing must be in a class) and Structural Programming (You can type code everywhere).
  &lt;/div&gt;
  
  &lt;div dir=&quot;ltr&quot;&gt;
    It supports also other programming paradigms like Functional Programming. I won&amp;#8217;t write about OOP and its uses, why we should use it, I&amp;#8217;ll just give you the keys to use OOP in Python.
  &lt;/div&gt;
  
  &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
    Defining a Class
  &lt;/h1&gt;
  
  &lt;p&gt;
    Classes in Python are defined like this:
  &lt;/p&gt;
  
  &lt;p&gt;
</code></pre>
</p>
<pre><code>  &lt;pre class=&quot;lang:python decode:true&quot;&gt;
</code></pre>
<p>class CLASS_NAME (BASE0,BASE1,BASE2):
&ldquo;&ldquo;&ldquo;OPTIONAL DOC STRING&rdquo;&rdquo;&rdquo;
#Class Code
.
.
.
</pre></p>
<pre><code>  &lt;div dir=&quot;ltr&quot;&gt;
    Yes, I know what you&amp;#8217;re thinking of, Python supports multiple inheritance.
  &lt;/div&gt;
  
  &lt;div dir=&quot;ltr&quot;&gt;
    In Python 3.0 you must at least inherit the object class (or any other class that inherits object), this is called new-style-classes, and that&amp;#8217;s because before Python 3.0 you could make a classic class that doesn&amp;#8217;t inherit any class, not even object.
  &lt;/div&gt;
  
  &lt;div dir=&quot;ltr&quot;&gt;
    Because of Python&amp;#8217;s dynamic data typing you don&amp;#8217;t need interfaces in Python, so there is no implicit syntax for declaring interfaces.
  &lt;/div&gt;
  
  &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
    Sample
  &lt;/h1&gt;
  
  &lt;div dir=&quot;ltr&quot;&gt;
    Let&amp;#8217;s create a sample class, I always implement the stack when I want to show OOP examples, I don&amp;#8217;t know why but that&amp;#8217;s what I&amp;#8217;m gonna do now:
  &lt;/div&gt;
  
  &lt;div dir=&quot;ltr&quot;&gt;
    I always start implementing stack by implementing its unit type, a class called StackItem.
  &lt;/div&gt;
  
  &lt;div dir=&quot;ltr&quot;&gt;
    StackItem is a stack unit that has two properties, its value, and a reference to its next item in the stack, so it will be defined:
  &lt;/div&gt;
  
  &lt;pre class=&quot;lang:python decode:true&quot;&gt;
</code></pre>
<p>class StackItem(object):
def <strong>init</strong>(self, value):
self.Value = value
self.Next = None</p>
<pre><code>@property
def Value(self):
	return self.__value
@Value.setter
def Value(self, value):
	self.__value = value

@property
def Next(self):
	return self.__next
@Next.setter
def Next(self, value):
	self.__next = value
</code></pre>
<p></pre></p>
<pre><code>  &lt;p&gt;
    Let&amp;#8217;s describe the whole scene of code:
  &lt;/p&gt;
  
  &lt;ol&gt;
    &lt;li&gt;
      StackItem inherits object, it is a way of saying &amp;#8220;Everything is an object&amp;#8221; 🙂
    &lt;/li&gt;
    &lt;li&gt;
      __init__ is the constructor of StackItem, it takes two arguments, the instance of StackItem to construct and the value of it, it sets the given value to the Value property of the given StackItem instance. And it sets the Next property of the given StackItem instance to None (Which is the null pointer).
    &lt;/li&gt;
    &lt;li&gt;
      @property is called function decorator, a decorator is a function which takes a function as a parameter and returns a function too. (Weird but handy).&lt;br /&gt; The decorator works as a transformer that transforms the function from one state to another. @property decorator creates a property from the given function, a property is like a variable, you store values in it for further reading/writing, but properties have a special function called a getter that returns the hidden value, and a special function called a setter that sets a given value to the hidden variable, the benefits you get from using properties instead of variables is that you can do some check before assigning the value to the variable, you can make sure that the give value is a positive number for instance.&lt;br /&gt; @property created a property called Value inside StackItem class, and it bounded its value to a private variable called __value.&lt;br /&gt; You&amp;#8217;d ask how come __value is a private variable?&lt;br /&gt; The answer is that in Python there is no access modifiers but Python annotates that any class variable with two leading underscores at least and one trailing underscore at most will be a private class variable, so other classes can&amp;#8217;t see it, so it is a way of creating private variables.
    &lt;/li&gt;
    &lt;li&gt;
      @Value.setter is another decorator which binds the setting of the Value property tho the given function.
    &lt;/li&gt;
    &lt;li&gt;
      Next is like Value, a property.&lt;br /&gt; A property can be used later by calling its name only, just like any variable: e.g.:&lt;/p&gt; &lt;pre class=&quot;lang:python decode:true&quot;&gt;
</code></pre>
<p>s.Value = 5
#This will call the function with
#@Value.setter decorator,
#passes s as the first argument,
#and 5 as the second one.
print(s.Value)
This will call the function with
#@property decorator,
#passes s as the first argument.
</pre>
</li></p>
<pre><code>    &lt;li&gt;
      self is passed to each function in the class, it refers to the instance of the class that the function was called from (Like this in C++, C#, Java and Me in Visual Basic).&lt;br /&gt; When not passing self to the function you&amp;#8217;re declaring that this function doesn&amp;#8217;t need an instance of the class to be called, in other words, you&amp;#8217;re declaring this as a static function, but you must tell the compiler that you did it on purpose so you should add @staticmethod decorator to the function, e.g.:&lt;/p&gt; &lt;pre class=&quot;lang:python decode:true&quot;&gt;
</code></pre>
<p>class C(object):
def NonStatic(self):
print (&ldquo;NonStatic&rdquo; )
@staticmethod
def Static():
print(&ldquo;Static&rdquo; )</p>
<p>cObj = C()
cObj.NonStatic() #Will print NonStatic
#(self = cObj)
cObj.Static() #Will print Static
C.Static() #Will also print Static
C.NonStatic() #Would give an error because
#NonStatic expects 1 argument
#and was called using none.
</pre>
</li>
</ol></p>
<pre><code>  &lt;p&gt;
    The other part must be easy for you after understanding the first one, now we&amp;#8217;ll implement the Stack class:
  &lt;/p&gt;
  
  &lt;pre class=&quot;lang:python decode:true&quot;&gt;
</code></pre>
<p>class Stack(object):
@property
def Head(self):
return self.__head</p>
<pre><code>@property
def Count(self):
	return self.__count

def __init__(self):
	self.__head = None
	self.__count = 0

def Push(self, value):
	if (self.__head is None):
		self.__head = StackItem(value)
	else:
		temp = StackItem(value)
		temp.Next = self.__head
		self.__head = temp
	self.__count += 1

def Pop(self):
	if (self.__head is None):
		raise Exception(&quot;Empty Stack&quot; )
	else:
		temp = self.__head
		self.__head = self.__head.Next
		self.__count -= 1
		return temp.Value

def PopAll(self):
	while (self.__count &amp;gt; 0):
		yield self.Pop()
</code></pre>
<p></pre></p>
<pre><code>  &lt;p&gt;
    Notes:
  &lt;/p&gt;
  
  &lt;ol&gt;
    &lt;li&gt;
      Stack has two read-only properties (They have no setters), Head (a reference to its top-most item) and Count (the count of items in the Stack).
    &lt;/li&gt;
    &lt;li&gt;
      The constructor sets the Count to 0 and the Head to None.
    &lt;/li&gt;
    &lt;li&gt;
      Push takes two arguments, the stack to push into, and the value to be pushed.
    &lt;/li&gt;
    &lt;li&gt;
      Pop takes one argument, the stack to pop out from, and returns the popped value. If the stack is empty Pop method will raise (throw) a new Exception with a message that says &amp;#8220;Empty Stack&amp;#8221;.
    &lt;/li&gt;
    &lt;li&gt;
      PopAll is called a Generator, it generates values from a data structure, it can be used with for loops. e.g.: &lt;pre class=&quot;lang:python decode:true&quot;&gt;
</code></pre>
<p>for value in s.PopAll():
print(value)
</pre></p>
<pre><code>      &lt;p&gt;
        yield is a keyword in Python that yields 😀 a given value to the caller. PopAll method works this way: The first time the caller calls it it would return the first value and stop. Each next time it will continue from where it stopped.&lt;/li&gt; &lt;/ol&gt; 
        
        &lt;p&gt;
          Now we can use our stack freely 🙂
        &lt;/p&gt;
        
        &lt;pre class=&quot;lang:python decode:true&quot;&gt;
</code></pre>
<p>S = Stack()</p>
<p>map(S.Push, range(1, 10))</p>
<p>for value in S.PopAll():
print value
</pre></p>
<pre><code>        &lt;div dir=&quot;ltr&quot;&gt;
          Simple code, right?
        &lt;/div&gt;
        
        &lt;div dir=&quot;ltr&quot;&gt;
          Notes:
        &lt;/div&gt;
        
        &lt;ol&gt;
          &lt;li&gt;
            S = Stack() initializes a new Stack and put its reference in S.
          &lt;/li&gt;
          &lt;li&gt;
            map is a function that takes a function as first argument and a list as second argument, and it calls the given function on each value from the give list and returns a tuple with the values of calling the function, in our case there is no return because Push returns no value. range is a function that takes two numbers and returns a list of numbers between the first one inclusively and the second one exclusively. e.g.: &lt;pre class=&quot;lang:python decode:true&quot;&gt;
</code></pre>
<p>print(rang(1, 10)) #prints from 1 to 9
</pre></p>
<pre><code>            &lt;p&gt;
              range can also take three numbers, the third would be the step between each two numbers. e.g.:
            &lt;/p&gt;
            
            &lt;pre class=&quot;lang:python decode:true&quot;&gt;
</code></pre>
<p>print(range(1, 10, 2)) #prints 1, 3, 5, 7, 9
</pre></p>
<pre><code>            &lt;p&gt;
              So map(S.Push, range(1, 10)) will fill the stack with values from 1 to 9.&lt;/li&gt; 
              
              &lt;li&gt;
                I used the PopAll method which is a generator to iterate over the StackItems and print them.
              &lt;/li&gt;&lt;/ol&gt; 
              
              &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
                Overriding and Overloading
              &lt;/h1&gt;
              
              &lt;div dir=&quot;ltr&quot;&gt;
                In OOP we use Overriding for a method in the sub-class that overrides a method in the base-class, and Overloading for two methods with the same name but differ in signature (number of arguments, types of arguments, order of arguments).
              &lt;/div&gt;
              
              &lt;div dir=&quot;ltr&quot;&gt;
                Usually to override a method in the sub-class the method must be declared virtual in the base-class, but in Python all methods are implicitly virtual.
              &lt;/div&gt;
              
              &lt;div dir=&quot;ltr&quot;&gt;
                To override a method you simply have to define it in the sub-class. e.g:
              &lt;/div&gt;
              
              &lt;pre class=&quot;lang:python decode:true&quot;&gt;
</code></pre>
<p>class A(object):
def M(self):
print (self.X)
def <strong>init</strong>(self):
self.X = 5
class B(A):
def M(self):
print (self.X + 1)</p>
<p>b = B()
b.M() #Will print 6
</pre></p>
<pre><code>              &lt;div dir=&quot;ltr&quot;&gt;
                Sometimes you need to extend the base method instead of overriding it completely, you can call the base method by using BaseClassName.MethodName(self, arguments).
              &lt;/div&gt;
              
              &lt;div dir=&quot;ltr&quot;&gt;
                e.g.:
              &lt;/div&gt;
              
              &lt;pre class=&quot;lang:python decode:true&quot;&gt;
</code></pre>
<p>class C(B):
def M(self):
B.M(self)
print (&ldquo;This is C&rdquo; )
c = C()
c.M() #Will print 6 This is C
</pre></p>
<pre><code>              &lt;div dir=&quot;ltr&quot;&gt;
                While overriding is a piece of cake, overloading is not supported by Python, you have to pick different names for different overloads from your method, that is because Python associates each function to a variable, so when overloading the variable will have the last function only.
              &lt;/div&gt;
              
              &lt;div dir=&quot;ltr&quot;&gt;
                A def statement is roughly executed like this:
              &lt;/div&gt;
              
              &lt;ol&gt;
                &lt;li&gt;
                  Compile the body of the function.
                &lt;/li&gt;
                &lt;li&gt;
                  Build a function object __f
                &lt;/li&gt;
                &lt;li&gt;
                  Assign it: FunctionName = __f
                &lt;/li&gt;
              &lt;/ol&gt;
              
              &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
                Bottom Line:
              &lt;/h1&gt;&lt;/div&gt; 
              
              &lt;div dir=&quot;ltr&quot;&gt;
                Python supports Pure Object Oriented strongly, You can write pure Object Oriented programs using Python, so why don&amp;#8217;t you start writing your programs now?
              &lt;/div&gt;
              
              &lt;div dir=&quot;ltr&quot;&gt;
                Cheers.
              &lt;/div&gt;
</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>I’m Learning Python part 8</title>
      <link>https://mpcabd.xyz/im-learning-python-part-8/</link>
      <pubDate>Fri, 20 Feb 2009 22:34:20 +0000</pubDate>
      <guid>https://mpcabd.xyz/im-learning-python-part-8/</guid>
      <description>&lt;div&gt;
  &lt;div style=&#34;text-align:center;&#34;&gt;
    &lt;h1 style=&#34;font-size:18pt;font-family:Verdana;&#34;&gt;
      I&amp;#8217;m Learning Python part 8
    &lt;/h1&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;p&amp;gt;
  &amp;lt;img title=&amp;quot;Python&amp;quot; src=&amp;quot;//www.python.org/images/python-logo.gif&amp;quot; alt=&amp;quot;Python&amp;quot; /&amp;gt;&amp;lt;/div&amp;gt; 
  
  &amp;lt;h1 style=&amp;quot;font-family:Georgia;&amp;quot;&amp;gt;
    Python 3.0
  &amp;lt;/h1&amp;gt;
  
  &amp;lt;p&amp;gt;
    Since the last time I wrote an article Python many changes happened in my life, one of them is the release of Python 3.0 (Which is known also as Python3K and Python3000).
  &amp;lt;/p&amp;gt;
  
  &amp;lt;p&amp;gt;
    Python 3.0 is the first intentionally backwards incompatible Python release, which means that there are some changes you must notice before start coding in Python 3.0.
  &amp;lt;/p&amp;gt;
  
  &amp;lt;p&amp;gt;
    Don&amp;amp;#8217;t worry that much, the language has become more useful, and also there is &amp;lt;a href=&amp;quot;//docs.python.org/library/2to3.html&amp;quot;&amp;gt;2to3 source-to-source conversion tool&amp;lt;/a&amp;gt; which converts your Python 2.x code to meet the requirements of Python 3.0 🙂
  &amp;lt;/p&amp;gt;
  
  &amp;lt;p&amp;gt;
    To find more about change in Python please refer to &amp;lt;a title=&amp;quot;What&#39;s&amp;quot; href=&amp;quot;//docs.python.org/3.0/whatsnew/3.0.html&amp;quot;&amp;gt;Python website&amp;lt;/a&amp;gt;.
  &amp;lt;/p&amp;gt;
  
  &amp;lt;p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;</description>
      <content:encoded><![CDATA[<div>
  <div style="text-align:center;">
    <h1 style="font-size:18pt;font-family:Verdana;">
      I&#8217;m Learning Python part 8
    </h1>
<pre><code>&lt;p&gt;
  &lt;img title=&quot;Python&quot; src=&quot;//www.python.org/images/python-logo.gif&quot; alt=&quot;Python&quot; /&gt;&lt;/div&gt; 
  
  &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
    Python 3.0
  &lt;/h1&gt;
  
  &lt;p&gt;
    Since the last time I wrote an article Python many changes happened in my life, one of them is the release of Python 3.0 (Which is known also as Python3K and Python3000).
  &lt;/p&gt;
  
  &lt;p&gt;
    Python 3.0 is the first intentionally backwards incompatible Python release, which means that there are some changes you must notice before start coding in Python 3.0.
  &lt;/p&gt;
  
  &lt;p&gt;
    Don&amp;#8217;t worry that much, the language has become more useful, and also there is &lt;a href=&quot;//docs.python.org/library/2to3.html&quot;&gt;2to3 source-to-source conversion tool&lt;/a&gt; which converts your Python 2.x code to meet the requirements of Python 3.0 🙂
  &lt;/p&gt;
  
  &lt;p&gt;
    To find more about change in Python please refer to &lt;a title=&quot;What's&quot; href=&quot;//docs.python.org/3.0/whatsnew/3.0.html&quot;&gt;Python website&lt;/a&gt;.
  &lt;/p&gt;
  
  &lt;p&gt;
</code></pre>
<p><br /> P.S.
</p></p>
<pre><code>  &lt;p&gt;
    From now on all the code will be written in Python 3.0.
  &lt;/p&gt;
  
  &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
    Decimal vs. float
  &lt;/h1&gt;
  
  &lt;p&gt;
    Please try the following code in your python console:
  &lt;/p&gt;
  
  &lt;pre class=&quot;lang:python decode:1&quot;&gt;
</code></pre>
<p>d = 0.1
print(d)
print(str(d))
</pre></p>
<pre><code>  &lt;p&gt;
    You&amp;#8217;d get this output:
  &lt;/p&gt;
  
  &lt;div&gt;
    &lt;strong&gt;&lt;span style=&quot;color:#666666;font-family:verdana;&quot;&gt;0.10000000000000001&lt;/span&gt;&lt;/strong&gt;
  &lt;/div&gt;
  
  &lt;p&gt;
    &lt;strong&gt;&lt;span style=&quot;color:#666666;font-family:verdana;&quot;&gt;0.1&lt;br /&gt; &lt;/span&gt;&lt;/strong&gt;Strange ain&amp;#8217;t it?&lt;br /&gt; The second value is the one you put in the variable.&lt;br /&gt; The first one is the real value represented in memory. This is not Python&amp;#8217;s fault, this happens because of the way computer store float values in memory as 0&amp;#8217;s and 1&amp;#8217;s, computers use floating point IEEE-745 representation.
  &lt;/p&gt;
  
  &lt;p&gt;
    Using this representation unfortunately we can&amp;#8217;t represent any float value using 0&amp;#8217;s and 1&amp;#8217;s, and 0.1 is one of those poor values (The reason is that it can&amp;#8217;t be represented in sum of powers of 0.5).
  &lt;/p&gt;
  
  &lt;p&gt;
    So what all programming languages do is that they ignore the small fraction so it would be 0.1 instead of 0.10000000000000001, but Python doesn&amp;#8217;t.
  &lt;/p&gt;
  
  &lt;p&gt;
    Try this code in Java if you have:
  &lt;/p&gt;
  
  &lt;pre class=&quot;lang:python decode:1&quot;&gt;
</code></pre>
<p>public class NoDifference{
  public static void main(String[] args){
    double a = 0.1;
    System.out.println(a);
    a = 0.10000000000000001;
    System.out.println(a);
  }
}
</pre></p>
<pre><code>  &lt;p&gt;
    You&amp;#8217;d get this output:
  &lt;/p&gt;
  
  &lt;div&gt;
    &lt;strong&gt;&lt;span style=&quot;color:#666666;font-family:verdana;&quot;&gt;0.1&lt;/span&gt;&lt;/strong&gt;
  &lt;/div&gt;
  
  &lt;p&gt;
    &lt;strong&gt;&lt;span style=&quot;color:#666666;font-family:verdana;&quot;&gt;0.1&lt;/span&gt;&lt;/strong&gt;
  &lt;/p&gt;
  
  &lt;p&gt;
    &lt;strong&gt;&lt;/strong&gt;So Java doesn&amp;#8217;t differ those two values while they&amp;#8217;re different. (Such a difference could make a disaster in a nuclear reactor :twisted:)&lt;br /&gt; If you want to go with the flow and ignore this difference in your calculations you&amp;#8217;d have to use another data type than float, you&amp;#8217;ll have to use Decimal.
  &lt;/p&gt;
  
  &lt;pre class=&quot;lang:python decode:1&quot;&gt;
</code></pre>
<p>from decimal import Decimal
d = Decimal(&ldquo;0.1&rdquo;)
print(d)
</pre></p>
<pre><code>  &lt;p&gt;
    &lt;strong&gt;&lt;span style=&quot;color:#666666;font-family:verdana;&quot;&gt;0.1&lt;/span&gt;&lt;/strong&gt;
  &lt;/p&gt;
  
  &lt;p&gt;
    &lt;strong&gt;&lt;/strong&gt;Decimal data type allows you to represent any decimal value you want 🙂
  &lt;/p&gt;
  
  &lt;p&gt;
    It also supports addition, subtraction, multiplication, division and modulo, but the two sides must be Decimals.
  &lt;/p&gt;
  
  &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
    Functions
  &lt;/h1&gt;
  
  &lt;p&gt;
    Let&amp;#8217;s write a function that prints Fibonacci series to a given boundary:
  &lt;/p&gt;
  
  &lt;pre class=&quot;lang:python decode:1&quot;&gt;
</code></pre>
<p>def fib(n):
  &ldquo;&ldquo;&ldquo;Prints Fibonacci series up to n&rdquo;&rdquo;&rdquo;
  a, b = 0, 1
  while b &lt; n:
    print(b, end = &quot; &ldquo;)
    a, b = b, a + b
#Now we can call the function by its name
fib(2000)
</pre></p>
<pre><code>  &lt;p&gt;
    &lt;strong&gt;&lt;span style=&quot;color:#666666;font-family:verdana;&quot;&gt;1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597&lt;/span&gt;&lt;/strong&gt;
  &lt;/p&gt;
  
  &lt;p&gt;
    Now let&amp;#8217;s describe what we have done:
  &lt;/p&gt;
  
  &lt;ol&gt;
    &lt;li&gt;
      def is a keyword in Python, def defines 🙂 it defines methods and classes.
    &lt;/li&gt;
    &lt;li&gt;
      fib is the method&amp;#8217;s name, method&amp;#8217;s name must meet the same requirements for variable&amp;#8217;s name. (first character a-z, A-Z or _, other characters a-z, A-Z, 0-9, _)
    &lt;/li&gt;
    &lt;li&gt;
      (n) is the list of parameters, notice that no type names in this list. parameters are comma separated.
    &lt;/li&gt;
    &lt;li&gt;
      : defines the scope of the method. All statements under this scope must be tab-aligned.
    &lt;/li&gt;
    &lt;li&gt;
      &amp;#8220;&amp;#8221;&amp;#8221;Prints &amp;#8230;&amp;#8221;&amp;#8221;&amp;#8221; is an optional string literal that describes what this method does, it will help you and other developers understand the purpose of the method, and it will also help you auto-generate documentation for your code.
    &lt;/li&gt;
    &lt;li&gt;
      a, b = 0, 1. define two variables and give them two values. a handy way 🙂
    &lt;/li&gt;
    &lt;li&gt;
      a, b = b, a + b. also assign two values to two variables.
    &lt;/li&gt;
  &lt;/ol&gt;
  
  &lt;p&gt;
    The previous code defines a procedure (not a function) because it doesn&amp;#8217;t return a value, let&amp;#8217;s modify the code so it builds an array of Fibonacci values instead of printing them:
  &lt;/p&gt;
  
  &lt;pre class=&quot;lang:python decode:1&quot;&gt;
</code></pre>
<p>def fib(n):
  &ldquo;&ldquo;&ldquo;Prints Fibonacci series up to n&rdquo;&rdquo;&rdquo;
  a, b = 0, 1
  result = []
  while b &lt; n:
    result.append(b)
    a, b = b, a + b
  return result
f = fib(100)
print(f)
</pre></p>
<pre><code>  &lt;p&gt;
    &lt;strong&gt;&lt;span style=&quot;color:#666666;font-family:verdana;&quot;&gt;[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]&lt;/span&gt;&lt;/strong&gt;
  &lt;/p&gt;
  
  &lt;p&gt;
    What we have added is the return statement only, which returns a value to the caller.
  &lt;/p&gt;
  
  &lt;p&gt;
    One more thing to be told is default arguments:
  &lt;/p&gt;
  
  &lt;pre class=&quot;lang:python decode:1&quot;&gt;
</code></pre>
<p>def askYesNoQuestion(question, retries = 4, complaint = &ldquo;Please write Yes or No only!&rdquo;):
  while retries &gt; 0:
    answer = raw_input(question)
    if answer in [&lsquo;y&rsquo;, &lsquo;ye&rsquo;, &lsquo;yes&rsquo;, &lsquo;yep&rsquo;]: return True
    if answer in [&rsquo;n&rsquo;, &rsquo;no&rsquo;, &rsquo;nop&rsquo;]: return False
    retries -= 1
    print(complaint)
  raise IOError, &ldquo;stupid user&rdquo;
#Now we can call it
askYesNoQuestion(&ldquo;Are you sure?&rdquo;, 1, &ldquo;What?!&rdquo;)
askYesNoQuestion(&ldquo;Overwrite?&rdquo;, 1)
#Same as askYesNoQuestion(&ldquo;Overwrite?&rdquo;, 1, &ldquo;Please write Yes or No only!&rdquo;)
askYesNoQuestion(&ldquo;Do you know me?&rdquo;)
#Same as askYesNoQuestion(&ldquo;Do you know me?&rdquo;, 4, &ldquo;Please write Yes or No only!&rdquo;)
askYesNoQuestion(&ldquo;Do you have a pen?&rdquo;, complaint = &ldquo;You can say no if you want!&rdquo;)
#Same as askYesNoQuestion(&ldquo;Do you have a pen?&rdquo;, 4, &ldquo;You can say no if you want!&rdquo;)
</pre></p>
<pre><code>  &lt;p&gt;
    Default arguments are assigned a default value if they aren&amp;#8217;t when called.&lt;br /&gt; You can set arguments values when calling by writing Name = Value.&lt;br /&gt; Default parameters can&amp;#8217;t be followed by non-default arguments.&lt;br /&gt; &lt;strong&gt;Important note&lt;/strong&gt;:&lt;br /&gt; Default arguments are evaluated only once, so the following code will accumulate the values:
  &lt;/p&gt;
  
  &lt;pre class=&quot;lang:python decode:1&quot;&gt;
</code></pre>
<p>def f(a, L = []):
  L.append(a)
  return L
f(1)
print(f)
</pre></p>
<pre><code>  &lt;p&gt;
    &lt;strong&gt;&lt;span style=&quot;color:#666666;font-family:verdana;&quot;&gt;[1]&lt;/span&gt;&lt;/strong&gt;
  &lt;/p&gt;
  
  &lt;pre class=&quot;lang:python decode:1&quot;&gt;
</code></pre>
<p>f(2)
print(f)
</pre></p>
<pre><code>  &lt;p&gt;
    &lt;strong&gt;&lt;span style=&quot;color:#666666;font-family:verdana;&quot;&gt;[1, 2]&lt;/span&gt;&lt;/strong&gt;
  &lt;/p&gt;
  
  &lt;pre class=&quot;lang:python decode:1&quot;&gt;
</code></pre>
<p>f(3)
print(f)
</pre></p>
<pre><code>  &lt;p&gt;
    &lt;strong&gt;&lt;span style=&quot;color:#666666;font-family:verdana;&quot;&gt;[1, 2, 3]&lt;/span&gt;&lt;/strong&gt;&lt;br /&gt; If you don&amp;#8217;t want the function to behave like this you can write:
  &lt;/p&gt;
  
  &lt;pre class=&quot;lang:python decode:1&quot;&gt;
</code></pre>
<p>def f(a, L = None):
  if L is None:
    L = []
  L.append(a)
  return L
</pre></p>
<pre><code>  &lt;p&gt;
    Let&amp;#8217;s explain what I meant by saying &amp;#8220;are evaluated only once&amp;#8221;:&lt;br /&gt; When the Python interpreter reaches the line that defines the method, it allocates a list in the memory and assigns its address to L the reference.&lt;br /&gt; Next time you call the function L will reference the same list it referenced the time it was created in memory, so it will always reference the same object.&lt;br /&gt; The second code actually referenced to None, so every time you call the function it will assign None to L.&lt;br /&gt; By understanding what I meant you can consider the following example:
  &lt;/p&gt;
  
  &lt;pre class=&quot;lang:python decode:1&quot;&gt;
</code></pre>
<p>i = 10
def f(a, b = i):
  return a + b
i = 11
print(f(2)) # Will it print 12 or 13?
</pre></p>
<pre><code>  &lt;p&gt;
    &lt;strong&gt;&lt;span style=&quot;color:#666666;font-family:verdana;&quot;&gt;12&lt;/span&gt;&lt;/strong&gt;&lt;br /&gt; That&amp;#8217;s because b was given the value of i before the interpreter reached the line in which i was give the value of 11.
  &lt;/p&gt;
  
  &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
    Bottom Line
  &lt;/h1&gt;
  
  &lt;p&gt;
    Not that much I presented in this part, but you should consider upgrading your Python knowledge to Python 3.0 for the next time.&lt;br /&gt; And by the way, I&amp;#8217;m sorry, I&amp;#8217;ve betrayed you and learned a lot during the last month, I have also started creating GUI Applications using Python and Qt, so please forgive me 🙂&lt;br /&gt; Cheers.
  &lt;/p&gt;&lt;/div&gt;
</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>I’m Learning Python part 7</title>
      <link>https://mpcabd.xyz/im-learning-python-part-7/</link>
      <pubDate>Fri, 28 Nov 2008 23:35:36 +0000</pubDate>
      <guid>https://mpcabd.xyz/im-learning-python-part-7/</guid>
      <description>&lt;div dir=&#34;ltr&#34;&gt;
  &lt;div dir=&#34;ltr&#34; style=&#34;text-align: center;&#34;&gt;
    &lt;h1 style=&#34;font-size: 18pt; font-family: Verdana;&#34;&gt;
      I&amp;#8217;m Learning Python (part 7)
    &lt;/h1&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;p&amp;gt;
  &amp;lt;img title=&amp;quot;Python Logo&amp;quot; src=&amp;quot;http://www.python.org/images/python-logo.gif&amp;quot; alt=&amp;quot;Python Logo&amp;quot; /&amp;gt;
&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
  &lt;/div&gt;
  &lt;h1 style=&#34;font-family: Georgia;&#34;&gt;
    Apology:
  &lt;/h1&gt;
  &lt;p&gt;
    First of all I wanna apologize for being late with this part, I&amp;#8217;ve had busy days first during Shaam 2008 expo and second during some studies at the college and last busy time past launching Bawabaty project.&lt;br /&gt;</description>
      <content:encoded><![CDATA[<div dir="ltr">
  <div dir="ltr" style="text-align: center;">
    <h1 style="font-size: 18pt; font-family: Verdana;">
      I&#8217;m Learning Python (part 7)
    </h1>
<pre><code>&lt;p&gt;
  &lt;img title=&quot;Python Logo&quot; src=&quot;http://www.python.org/images/python-logo.gif&quot; alt=&quot;Python Logo&quot; /&gt;
&lt;/p&gt;
</code></pre>
  </div>
  <h1 style="font-family: Georgia;">
    Apology:
  </h1>
  <p>
    First of all I wanna apologize for being late with this part, I&#8217;ve had busy days first during Shaam 2008 expo and second during some studies at the college and last busy time past launching Bawabaty project.<br /> 
</p>
  <h1 style="font-family: Georgia;">
    Numbers:
  </h1>
  <p>
    Numbers in Python are divided into 5 sections:
  </p>
  <p>
    Integers:
  </p>
  <p>
    Such as: 1234, -1234, 0
  </p>
  <p>
    Long Integers (unlimited size):
  </p>
  <p>
    Such as: 71632487932648921735413278645238947231659821365213847L
  </p>
  <p>
    These numbers grow as long as your memory can hold, and it ends with a small or capital L but it is an optional literal, you can define:
  </p>
  <p>
    />>> TheLongVariable = 99999999999999999999999999
  </p>
  <p>
    />>> TheLongVariable
  </p>
  <p>
    99999999999999999999999999L
  </p>
  <p>
    Floating Point Numbers:
  </p>
  <p>
    Such as: 1.234, 3.14e-10, 4.01e+12
  </p>
  <p>
    You can define them using points, e or E.
  </p>
  <p>
    Octal and hex literals:
  </p>
  <p>
    Such as: 0172, 0x9fab, 0X3FBC
  </p>
  <p>
    Octal is defined by starting your number with a leading zero, while hexadecimal is defined by starting you number by a leading 0x or 0X.
  </p>
  <p>
    Complex Numbers:
  </p>
  <p>
    Such as: 3+4j, 3.0-5.1j, 3J
  </p>
  <p>
    Complex numbers are defined by a j or J at the end of the number, the number can consist of two parts, real and imaginary, so all the following are complex numbers:
  </p>
  <p>
    1 + 3j, 3j, 5J, -10.1j
  </p>
  <h1 style="font-family: Georgia;">
    Python has lots of built-in numeric tools:
  </h1>
  <p>
    Of course you can use +, -, *, /, <, >, ==, !=, <> as any other programming language, but Python has more:
  </p>
  <p>
    **: Power, 2 ** 3 is 8.
  </p>
  <p>
    //: Is truncated division, 5 // 2 is 2
  </p>
  <p>
    %: Remainder, 5 % 2 is 1
  </p>
  <p>
    You can use also bitwise operations:
  </p>
  <p>
    />>, << shift right and left, 5 << 2 is 20, 24 >> 3 is 3.
  </p>
  <p>
    |, & Or and And, 4 | 3 is 7, 7 & 2 is 2.
  </p>
  <p>
    Just as any other programming language, Python deals with expressions using operator precedence: 3 + 4 * 2 is 11 because * is done before +.
  </p>
  <p>
    Of course you can use parentheses to define the way you want to deal with the expression, (3+ 4) * 2 is 14.
  </p>
  <p>
    When mixing multiple types in an expressions, all types are converted up, 40 + 3.14 will be calculated as 40.0 + 3.14. The types are ordered like this:
  </p>
  <p>
    Integers < Long Integers < Floating Points < Complex Numbers.
  </p>
  <p>
    The type of the result of a mixed expression is the type of the higher type, so 40 + 3.14 is a floating point, but you can force it into an integer using: int(40 + 3.14).
  </p>
  <h1 style="font-family: Georgia;">
    Variables:
  </h1>
  <p>
    During our trip in Python till now we used variables but we haven&#8217;t talked about them:
  </p>
  <p>
    Variables are created once they are assigned a value.
  </p>
  <p>
    Variables are replaced with their values in expressions.
  </p>
  <p>
    You can&#8217;t use an unassigned variable, because simply you don&#8217;t have the variable yet.
  </p>
  <p>
    Variables are references to objects.
  </p>
  <h1 style="font-family: Georgia;">
    repr & str:
  </h1>
  <p>
    Try this
  </p>
  <p>
    />>> a = 3
  </p>
  <p>
    />>> b = 4
  </p>
  <p>
    />>> b / (2.0 + a)
  </p>
  <p>
    0.80000000000000004
  </p>
  <p>
    />>> print b / (2.0 + a)
  </p>
  <p>
    0.8
  </p>
  <p>
    We&#8217;ve seen something like this before, and we discussed it, the difference between the two methods is that each one uses a specified function, the first uses a function called repr which prints the value as it is in your memory, while the other uses a function called str which prints the value in a user friendly way.
  </p>
  <h1 style="font-family: Georgia;">
    More Functions:
  </h1>
  <p>
    Python provides functions for Octal and Hex conversion:
  </p>
  <p>
    />>> oct(64)
  </p>
  <p>
    &#8216;0100&#8217;
  </p>
  <p>
    />>> oct(8 )
  </p>
  <p>
    &#8216;010&#8217;
  </p>
  <p>
    />>> hex(255)
  </p>
  <p>
    &#8216;0xff&#8217;
  </p>
  <p>
    And vice versa, Python provides functions for retrieving integers out of Hex and Oct:
  </p>
  <p>
    />>> int(&#8216;0234&#8217;)
  </p>
  <p>
    234
  </p>
  <p>
    />>> int(&#8216;0234&#8217;, 8 )
  </p>
  <p>
    256
  </p>
  <p>
    />>> int(&#8216;0234&#8242;, 16)
  </p>
  <p>
    564
  </p>
  <p>
    And it also provides a way to format numbers in strings, which we will cover in another part, but a small example won&#8217;t hurt:
  </p>
  <p>
    />>> &#8220;%o %x&#8221; % (25, 21)
  </p>
  <p>
    &#8217;31 15&#8217;
  </p>
  <p>
    Other built-in functions and methods are in math module, which you can import and use:
  </p>
  <p>
    />>> import math
  </p>
  <p>
    />>> math.pi, math.e
  </p>
  <p>
    (3.1415926535897931, 2.7182818284590451)
  </p>
  <p>
    />>> math.sin(math.pi / 2)
  </p>
  <p>
    1.0
  </p>
</div>
<div dir="ltr">
  The result shown in parentheses is a tuple (which we covered last part), it is shown in a tuple because we put a column between math.pi and math.e</p> 
  <h1 style="font-family: Georgia;">
    Bottom Line:
  </h1>
  <p>
    Thank you for waiting for this part, and until I meet you on another part try to read more about numbers from the online documentation of Python.
  </p>
  <p>
    Cheers.
  </p>
</div>
<p> </p>]]></content:encoded>
    </item>
    <item>
      <title>I’m Learning Python part 6</title>
      <link>https://mpcabd.xyz/im-learning-python-part-6/</link>
      <pubDate>Fri, 07 Nov 2008 21:36:29 +0000</pubDate>
      <guid>https://mpcabd.xyz/im-learning-python-part-6/</guid>
      <description>&lt;div dir=&#34;ltr&#34;&gt;
  &lt;div style=&#34;text-align: center;&#34;&gt;
    &lt;h1 style=&#34;font-size: 18pt; font-family: Verdana;&#34;&gt;
      I&amp;#8217;m Learning Python (part 6)
    &lt;/h1&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;p&amp;gt;
  &amp;lt;img title=&amp;quot;Python Logo&amp;quot; src=&amp;quot;http://www.python.org/images/python-logo.gif&amp;quot; alt=&amp;quot;Python Logo&amp;quot; /&amp;gt;
&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
  &lt;/div&gt;
  &lt;h1 style=&#34;font-family: Georgia;&#34;&gt;
    Dictionaries
  &lt;/h1&gt;
  &lt;div dir=&#34;ltr&#34;&gt;
    Dictionaries in Python are like dictionaries in life, they consist of key-value pairs, each key maps a value, values can be any object type, and keys also. Keys must be unique, I mean that we can&amp;#8217;t have two identical keys with different values.
  &lt;/div&gt;
  &lt;p&gt;</description>
      <content:encoded><![CDATA[<div dir="ltr">
  <div style="text-align: center;">
    <h1 style="font-size: 18pt; font-family: Verdana;">
      I&#8217;m Learning Python (part 6)
    </h1>
<pre><code>&lt;p&gt;
  &lt;img title=&quot;Python Logo&quot; src=&quot;http://www.python.org/images/python-logo.gif&quot; alt=&quot;Python Logo&quot; /&gt;
&lt;/p&gt;
</code></pre>
  </div>
  <h1 style="font-family: Georgia;">
    Dictionaries
  </h1>
  <div dir="ltr">
    Dictionaries in Python are like dictionaries in life, they consist of key-value pairs, each key maps a value, values can be any object type, and keys also. Keys must be unique, I mean that we can&#8217;t have two identical keys with different values.
  </div>
  <p>
</p>
  <div dir="ltr">
    Dictionaries are defined using curly braces { and } as the following:
  </div>
  <div dir="ltr">
    <em>>>> D = {&#8216;name&#8217; : &#8216;Abd Allah Diab&#8217;, &#8216;age&#8217; : 19, &#8216;job&#8217; : &#8216;Web Developer&#8217;}</em>
  </div>
  <div dir="ltr">
    Now we can access any of the pairs using only the key:
  </div>
  <div dir="ltr">
    <em>>>> D[&#8216;age&#8217;]</em>
  </div>
  <div dir="ltr">
    <em>19</em>
  </div>
  <div dir="ltr">
    Dictionaries are mutable objects, which means we can change their values in place:
  </div>
  <div dir="ltr">
    <em>>>> D[&#8216;age&#8217;] += 1</em>
  </div>
  <div dir="ltr">
    <em>>>> D[&#8216;age&#8217;]</em>
  </div>
  <div dir="ltr">
    <em>20</em>
  </div>
  <div dir="ltr">
    We can add new pairs also easily:
  </div>
  <div dir="ltr">
    <em>>>> D[&#8216;eyes&#8217;] = &#8216;brown&#8217;</em>
  </div>
  <div dir="ltr">
    <em>>>> D</em>
  </div>
  <div dir="ltr">
    <em>{&#8216;job&#8217; : &#8216;Web Developer&#8217;, &#8216;age&#8217; : 20&#8242;, &#8216;eyes&#8217; : &#8216;brown&#8217;, &#8216;name&#8217; : &#8216;Abd Allah Diab&#8217;}</em>
  </div>
  <div dir="ltr">
    As you can see, the dictionary is not sorted, we entered the name first then the age and job, and at last we added the eyes, but it prints in a different order.<br /> To sort a dictionary you should sort its keys and then print the values of the keys after sorting like the following:
  </div>
  <div dir="ltr">
    <em>>>> keys = D.keys()</em>
  </div>
  <div dir="ltr">
    <em>>>> keys [&#8216;job&#8217;, &#8216;age&#8217;, &#8216;eyes&#8217;, &#8216;name&#8217;]</em>
  </div>
  <div dir="ltr">
    <em>>>> keys.sort()</em>
  </div>
  <div dir="ltr">
    <em>>>> keys</em>
  </div>
  <div dir="ltr">
    <em>[&#8216;age&#8217;, &#8216;eyes&#8217;, &#8216;job&#8217;, &#8216;name&#8217;]</em>
  </div>
  <div dir="ltr">
    <em>>>> for key in keys:</em>
  </div>
  <div dir="ltr">
    <em> print key, &#8216;=>&#8217;, D[key]</em>
  </div>
  <div dir="ltr">
    <em>age => 20</em>
  </div>
  <div dir="ltr">
    <em>eyes => brown</em>
  </div>
  <div dir="ltr">
    <em>job => Web Developer</em>
  </div>
  <div dir="ltr">
    <em>name => Abd Allah Diab</em>
  </div>
  <div dir="ltr">
    Here we used a for loop which I haven&#8217;t covered, but it is just like list comprehensions, it will do what follows its declaration for each member of the set (here keys).
  </div>
  <div dir="ltr">
    Please notice the <strong>indentation</strong>, after the for declaration you must hit the &#8216;tab&#8217; for each line inside the for loop, and to exit the loop just don&#8217;t hit the &#8216;tab&#8217; (press &#8216;enter&#8217; in interactive mode).
  </div>
  <div dir="ltr">
    You can make use of a new method called &#8216;sorted&#8217; which takes any iteratable object (like a sequence or a string etc):
  </div>
  <div dir="ltr">
    <em>>>> for key in sorted(D)</em>
  </div>
  <div dir="ltr">
    <em> print key, &#8216;=>&#8217;, D[key]</em>
  </div>
  <div dir="ltr">
    <em>age => 20</em>
  </div>
  <div dir="ltr">
    <em>eyes => brown</em>
  </div>
  <div dir="ltr">
    <em>job => Web Developer</em>
  </div>
  <div dir="ltr">
    <em>name => Abd Allah Diab </em>
  </div>
  <h1 style="font-family: Georgia;">
    Nesting
  </h1>
  <div dir="ltr">
    As I told you @ first, the values can be any object, so we can nest anything inside dictionaries, for example if I want to store the first name and last name inside the &#8216;name&#8217; in the dictionary, and to save a list of jobs inside the &#8216;job&#8217; in the dictionary, I&#8217;d do that just like I nested matrices last time:
  </div>
  <div dir="ltr">
    <em>>>> D = {&#8216;name&#8217; : {&#8216;first&#8217; : &#8216;Abd Allah&#8217;, &#8216;last&#8217; : &#8216;Diab&#8217;}, &#8216;age&#8217; : 19, &#8216;job&#8217; : [&#8216;Web Developer&#8217;, &#8216;Teacher&#8217;, &#8216;Student&#8217;]}</em>
  </div>
  <div dir="ltr">
    Now let&#8217;s see how we can access what we&#8217;ve built:
  </div>
  <div dir="ltr">
    <em>>>> D[&#8216;name&#8217;]</em>
  </div>
  <div dir="ltr">
    <em>{&#8216;first&#8217; : &#8216;Abd Allah&#8217;, &#8216;last&#8217; : &#8216;Diab&#8217;}</em>
  </div>
  <div dir="ltr">
    <em>>>> D[&#8216;name&#8217;][&#8216;first&#8217;]</em>
  </div>
  <div dir="ltr">
    <em>&#8216;Abd Allah&#8217;</em>
  </div>
  <div dir="ltr">
    <em>>>> D[&#8216;name&#8217;][&#8216;last&#8217;]</em>
  </div>
  <div dir="ltr">
    <em>&#8216;Diab&#8217;</em>
  </div>
  <div dir="ltr">
    <em>>>> D[&#8216;job&#8217;]</em>
  </div>
  <div dir="ltr">
    <em>[&#8216;Web Developer&#8217;, &#8216;Teacher&#8217;, &#8216;Student&#8217;]</em>
  </div>
  <div dir="ltr">
    <em>>>> D[&#8216;job&#8217;][0]</em>
  </div>
  <div dir="ltr">
    <em>&#8216;Web Developer&#8217;</em>
  </div>
  <div dir="ltr">
    <em>>>> D[&#8216;job&#8217;][-1]</em>
  </div>
  <div dir="ltr">
    <em>&#8216;Student&#8217;</em>
  </div>
  <div dir="ltr">
  </div>
  <div dir="ltr">
    Pretty easy right? 🙂
  </div>
  <h1 style="font-family: Georgia;">
    Memory issue
  </h1>
  <div dir="ltr">
    Did you ask yourself where did the old D dictionary go?
  </div>
  <div dir="ltr">
    In C, C++ and many other old languages you had to manage memory by hand, but in advanced languages like Java, .NET and Python there exists a garbage collector which handles this process for you, whenever you an object has no references the garbage collector will deallocate its space.
  </div>
  <h1 style="font-family: Georgia;">
    Missing keys
  </h1>
  <div dir="ltr">
    When accessing a dictionary you should be careful to missing keys, especially when the dictionary is filled dynamically.
  </div>
  <div dir="ltr">
    Accessing a missing key will be a mistake:
  </div>
  <div dir="ltr">
    <em>>>> D[&#8216;FFF&#8217;] #Will give you a key error.</em><br /> To avoid this mistake you can ask the dictionary if it has the key then you can access it:
  </div>
  <div dir="ltr">
    <em>>>> if not D.has_key(&#8216;fff&#8217;):</em>
  </div>
  <div dir="ltr">
    <em> print &#8216;MISS&#8217;</em>
  </div>
  <div dir="ltr">
    <em>MISS</em>
  </div>
  <div dir="ltr">
    Here we used the if control, which takes this form:
  </div>
  <div dir="ltr">
    if <Condition1>:
  </div>
  <div dir="ltr">
    Block1
  </div>
  <div dir="ltr">
    elif <Condition2>:
  </div>
  <div dir="ltr">
    Block2
  </div>
  <div dir="ltr">
    .<br /> .
  </div>
  <div dir="ltr">
    elif <ConditionN>:
  </div>
  <div dir="ltr">
    BlockN
  </div>
  <div dir="ltr">
    else:
  </div>
  <div dir="ltr">
    Block
  </div>
  <div dir="ltr">
    Notice the <strong>indentation</strong>, &#8216;cuz in Python the scope is defined using indention not curly braces or Begin and End.
  </div>
  <div dir="ltr">
  </div>
  <h1 style="font-family: Georgia;">
    For Loops, List Comprehensions and Performance
  </h1>
  <div dir="ltr">
    Every list comprehension can be done using a for loop instead:
  </div>
  <div dir="ltr">
    <em>>>> squares = [x ** 2 for x in [1, 2, 3, 4, 5]]</em>
  </div>
  <div dir="ltr">
    <em>>>> squares</em>
  </div>
  <div dir="ltr">
    <em>[1, 4, 9, 16, 25]</em>
  </div>
  <div dir="ltr">
    Can be done:
  </div>
  <div dir="ltr">
    <em>>>> squares = []</em>
  </div>
  <div dir="ltr">
    <em>>>> for x in [1, 2, 3, 4, 5]</em>
  </div>
  <div dir="ltr">
    <em> squares.append(x ** 2)</em>
  </div>
  <div dir="ltr">
    <em>>>> squares</em>
  </div>
  <div dir="ltr">
    <em>[1, 4, 9, 16, 25]</em>
  </div>
  <div dir="ltr">
    But the former is faster than the latter (sometimes it is twice faster), that&#8217;s because Python is optimized, and every new version is faster and optimized more than old ones.
  </div>
  <div dir="ltr">
    So the rule in Python is &#8220;Code for simplicity and readability firs, and worry about performance later&#8221; but in most cases you will stop after writing a readable program, &#8216;cuz Python is optimized by itself.
  </div>
  <h1 style="font-family: Georgia;">
    Tuples
  </h1>
  <div dir="ltr">
    Tuples (pronounced &#8216;tooples&#8217;) are just like lists but they are immutable, which mean that they can&#8217;t be changed once the are created, but like strings support type methods (split, len, &#8230;) and nesting and sequence operations.
  </div>
  <div dir="ltr">
    Tuples are defined in parentheses ( ):
  </div>
  <div dir="ltr">
    <em>>>> T = (1, 2, 3, 4)</em>
  </div>
  <div dir="ltr">
    <em>>>> T</em>
  </div>
  <div dir="ltr">
    <em>(1, 2, 3, 4)</em>
  </div>
  <div dir="ltr">
    <em>>>> T[2]</em>
  </div>
  <div dir="ltr">
    <em>3</em>
  </div>
  <div dir="ltr">
    <em>>>> T[-1]</em>
  </div>
  <div dir="ltr">
    <em>4</em>
  </div>
  <div dir="ltr">
    <em>>>> T = T + (5, 6, 7)</em>
  </div>
  <div dir="ltr">
    <em>>>> T</em>
  </div>
  <div dir="ltr">
    <em>(1, 2, 3, 4, 5, 7)</em>
  </div>
  <div dir="ltr">
    You might wonder, why would I use an immutable list when I can use a list? The answer is that sometimes you might want to call a method with a list parameter which you don&#8217;t want it to be changed, or when you send lists through your program and you don&#8217;t want them to be changed, you&#8217;ll use tuples then.
  </div>
  <h1 style="font-family: Georgia;">
    Other File Types
  </h1>
  <div dir="ltr">
    Those types we discussed aren&#8217;t the only types, there exist more types, such as sets, which are like mathematical sets (a container for a list of objects):
  </div>
  <div dir="ltr">
    <em>>>> X = set([1, 2, 3, 4])</em>
  </div>
  <div dir="ltr">
    <em>>>> X set([1, 2, 3, 4])</em>
  </div>
  <div dir="ltr">
    <em>>>> X.add(5)</em>
  </div>
  <div dir="ltr">
    <em>>>> X</em>
  </div>
  <div dir="ltr">
    <em>set([1, 2, 3, 4, 5])</em>
  </div>
  <div dir="ltr">
    <em>>>> Y = set([1, 6, 3])</em>
  </div>
  <div dir="ltr">
    <em>>>> X & Y #Intersection</em>
  </div>
  <div dir="ltr">
    <em>set([1, 3])</em>
  </div>
  <div dir="ltr">
    <em>>>> X | Y #Union</em>
  </div>
  <div dir="ltr">
    <em>set([1, 2, 3, 4, 5, 6])</em>
  </div>
  <div dir="ltr">
    <em>>>> X &#8211; Y #Difference<br /> </em>
  </div>
  <div dir="ltr">
    <em>set([2, 4, 5])</em>
  </div>
  <div dir="ltr">
    Python also supports lots of types, but we won&#8217;t cover them all here (or at least now :)).
  </div>
  <h1 style="font-family: Georgia;">
    User-defined Types
  </h1>
  <div dir="ltr">
    You can build your own classes in Python:
  </div>
  <div dir="ltr">
    <em>>>> class Man:</em>
  </div>
  <div dir="ltr">
    <em> def __intit__(self, name, age): #Constructor which takes two parameters and saves them</em>
  </div>
  <div dir="ltr">
    <em> self.name = name #self is the object that we&#8217;re calling the method on.</em>
  </div>
  <div dir="ltr">
    <em> self.age = age</em>
  </div>
  <div dir="ltr">
    <em> def lastname(self): #A method to get the last name of the man.</em>
  </div>
  <div dir="ltr">
    <em> return self.name.split(&#8216; &#8216;)[-1]</em>
  </div>
  <div dir="ltr">
    Now you can use your class:
  </div>
  <div dir="ltr">
    <em>>>> me = Man(&#8216;Abd Allah Diab&#8217;, 19) #Initialize a new instance of Man </em>
  </div>
  <div dir="ltr">
    <em>>>> me.lastname()</em>
  </div>
  <div dir="ltr">
    <em>&#8216;Diab&#8217;</em>
  </div>
  <div dir="ltr">
    <em>>>> me.age</em>
  </div>
  <div dir="ltr">
    <em>19</em>
  </div>
  <div dir="ltr">
    We won&#8217;t discuss classes and objects here, but I wanted to show you that you can have your own type easily.
  </div>
  <h1 style="font-family: Georgia;">
    Bottom Line
  </h1>
</div>
<div dir="ltr">
  Here we come to the end of our tour on built in primitive types of Python, Next time we&#8217;ll start our detailed trip to Numbers 🙂
</div>
<div dir="ltr">
  Until then keep coding and make mistakes, and don&#8217;t forget to learn of your mistakes 😀
</div>
<div dir="ltr">
</div>
<div dir="ltr">
  Cheers.
</div>]]></content:encoded>
    </item>
    <item>
      <title>I’m Learning Python (part 5)</title>
      <link>https://mpcabd.xyz/im-learning-python-part-5/</link>
      <pubDate>Wed, 29 Oct 2008 15:34:38 +0000</pubDate>
      <guid>https://mpcabd.xyz/im-learning-python-part-5/</guid>
      <description>&lt;div dir=&#34;ltr&#34;&gt;
  &lt;div style=&#34;text-align: center;&#34;&gt;
    &lt;h1 style=&#34;font-size: 18pt; font-family: Verdana;&#34;&gt;
      I&amp;#8217;m Learning Python (part 5)
    &lt;/h1&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;p&amp;gt;
  &amp;lt;img title=&amp;quot;Python Logo&amp;quot; src=&amp;quot;http://www.python.org/images/python-logo.gif&amp;quot; alt=&amp;quot;Python Logo&amp;quot; /&amp;gt;
&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
  &lt;/div&gt;
  &lt;h1 style=&#34;font-family: Georgia;&#34;&gt;
    String Is Immutable?
  &lt;/h1&gt;
  &lt;p&gt;
    Last time I told you to try to change a specified character, you must have failed if you tried:&lt;br /&gt; &lt;em&gt;&gt;&gt;&gt; s[0] = &amp;#8216;c&amp;#8217;&lt;/em&gt;&lt;br /&gt; The error you&amp;#8217;d get is:&lt;br /&gt; &lt;em&gt;TypeError: &amp;#8216;str&amp;#8217; object does not support item assignment&lt;br /&gt; &lt;/em&gt;This means that strings are immutable, so are core-types, numbers and tuples, they can’t be changed, while lists and dictionaries can be changed freely.&lt;br /&gt;</description>
      <content:encoded><![CDATA[<div dir="ltr">
  <div style="text-align: center;">
    <h1 style="font-size: 18pt; font-family: Verdana;">
      I&#8217;m Learning Python (part 5)
    </h1>
<pre><code>&lt;p&gt;
  &lt;img title=&quot;Python Logo&quot; src=&quot;http://www.python.org/images/python-logo.gif&quot; alt=&quot;Python Logo&quot; /&gt;
&lt;/p&gt;
</code></pre>
  </div>
  <h1 style="font-family: Georgia;">
    String Is Immutable?
  </h1>
  <p>
    Last time I told you to try to change a specified character, you must have failed if you tried:<br /> <em>>>> s[0] = &#8216;c&#8217;</em><br /> The error you&#8217;d get is:<br /> <em>TypeError: &#8216;str&#8217; object does not support item assignment<br /> </em>This means that strings are immutable, so are core-types, numbers and tuples, they can’t be changed, while lists and dictionaries can be changed freely.<br /> 
</p>
  <h1 style="font-family: Georgia;">
    More Methods?
  </h1>
  <p>
    All the previous methods and operations are sequence operations, but strings have more methods:<br /> <em>>>> s = &#8216;My Text&#8217;<br /> >>> s.find(&#8216;Tex&#8217; ) #returns the index of the first occurrence of the parameter<br /> </em>3<em><br /> >>> s.find(&#8216;abc&#8217; ) #if the parameter wasn&#8217;t found it will return -1<br /> -1<br /> >>> s.replace(&#8216;Text&#8217;, &#8216;Code&#8217; ) #replaces every occurrence of the first parameter with the second one &#8216;My Code&#8217; >>> s #notice that the string hasn&#8217;t changed<br /> &#8216;My Text&#8217;<br /> >>> s = &#8216;aa,bb,cc,dd&#8217;<br /> >>> s.split(&#8216;,&#8217; ) #splits the string into a list of values separated with the parameter<br /> [&#8216;aa&#8217;, &#8216;bb&#8217;, &#8216;cc&#8217;, &#8216;dd&#8217;]<br /> >>> s =&#8217;My Text\n&#8217;<br /> >>> s.rstrip() #removes white space characters from the right of the string<br /> &#8216;My Text&#8217;<br /> >>> s #don&#8217;t forget that the string hasn’t changed 😉<br /> &#8216;My Text\n&#8217;<br /> >>> len(s) #returns the length of the string<br /> </em>8<em><br /> >>> ord(&#8216;\n&#8217; ) #returns the ASCII code for the given character<br /> 10<br /> >>> s = &#8216;MyTextA&#8217; # is the null character though it doesn&#8217;t terminate the string ?<br /> >>> len(s)<br /> </em>9<em><br /> >>> s<br /> &#8216;MyTextA&#8217;<br /> </em>
  </p>
  <h1 style="font-family: Georgia;">
    Wanna Get More?
  </h1>
  <p>
    Of course I can&#8217;t talk about every method for every type, but I&#8217;ll give you a simple way to get more, in Python there is a method called &#8220;dir&#8221; which lists the object&#8217;s methods and properties:<br /> <em>>>> dir(s)<br /> [&#8216;__add__&#8217;, &#8216;__class__&#8217;, &#8216;__contains__&#8217;, &#8216;__delattr__&#8217;, &#8216;__doc__&#8217;, &#8216;__eq__&#8217;, &#8216;__format__&#8217;, __ge__&#8217;, &#8216;__getattribute__&#8217;, &#8216;__getitem__&#8217;, &#8216;__getnewargs__&#8217;, &#8216;__getslice__&#8217;, &#8216;__gt__&#8217;, __hash__&#8217;, &#8216;__init__&#8217;, &#8216;__le__&#8217;, &#8216;__len__&#8217;, &#8216;__lt__&#8217;, &#8216;__mod__&#8217;, &#8216;__mul__&#8217;, &#8216;__ne__&#8217;, &#8216;__new__&#8217;, __reduce__&#8217;, &#8216;__reduce_ex__&#8217;, &#8216;__repr__&#8217;, &#8216;__rmod__&#8217;, &#8216;__rmul__&#8217;, &#8216;__setattr__&#8217;, __sizeof__&#8217;, __str__&#8217;, &#8216;__subclasshook__&#8217;, &#8216;_formatter_field_name_split&#8217;, &#8216;_formatter_parser&#8217;, &#8216;capitalize&#8217;, center&#8217;, &#8216;count&#8217;, &#8216;decode&#8217;, &#8216;encode&#8217;, &#8216;endswith&#8217;, &#8216;expandtabs&#8217;, &#8216;find&#8217;, &#8216;format&#8217;, &#8216;index&#8217;, isalnum&#8217;, isalpha&#8217;, &#8216;isdigit&#8217;, &#8216;islower&#8217;, &#8216;isspace&#8217;, &#8216;istitle&#8217;, &#8216;isupper&#8217;,&#8217;join&#8217;, &#8216;ljust&#8217;, &#8216;lower&#8217;, &#8216;lstrip&#8217;, &#8216;partition&#8217;, replace&#8217;, &#8216;rfind&#8217;, &#8216;rindex&#8217;, &#8216;rjust&#8217;, &#8216;rpartition&#8217;, &#8216;rsplit&#8217;, &#8216;rstrip&#8217;, &#8216;split&#8217;, &#8216;splitlines&#8217;, &#8216;startswith&#8217;, &#8216;strip&#8217;, &#8216;swapcase&#8217;, &#8216;title&#8217;, &#8216;translate&#8217;, &#8216;upper&#8217;, &#8216;zfill&#8217;]<br /> </em>Don&#8217;t care about those who has underscores, but the rest are methods.<br /> Now to know more about a specified method you can use the &#8220;help&#8221; method:<br /> <em>>>> help(s.count)<br /> Help on built-in function count:<br /> count(&#8230;)<br /> </em><em>S.count(sub[, start[, end]]) -> int<br /> Return the number of non-overlapping occurrences of substring sub in string S[start:end].<br /> Optional arguments start and end are interpreted as in slice notation.<br /> </em>
  </p>
  <h1 style="font-family: Georgia;">
    What About Regular Expressions?
  </h1>
  <p>
    Users with a background about regular expressions will definitely ask about it, and the answer is yes you can use them with strings:<br /> <em>>>> import re<br /> >>> match = re.match(&#8216;Hello[ \t]*(.*)world&#8217;, &#8216;Hello Python world&#8217; )<br /> >>> match.group(1)<br /> &#8216;Python&#8217;<br /> >>> match = re.match(&#8216;/(.*)/(.*)/(.*)/&#8217;, &#8216;/usr/lib/bin/&#8217; )<br /> >>> match.groups()<br /> (&#8216;usr&#8217;, &#8216;lib&#8217;, &#8216;bin&#8217; )<br /> </em>Of course you can do more as you know with regular expressions like replacing and splitting, try &#8220;dir&#8221; and &#8220;help&#8221; for more 😉
  </p>
  <h1 style="font-family: Georgia;">
    What Is The Difference Between &#8216;Text&#8217; And &#8220;Text&#8221;?
  </h1>
  <p>
    There is no difference at all, but there is a third way to write strings:<br /> <em>>>> s = &#8220;&#8221;&#8221;Text&#8221;&#8221;&#8221;</em><br /> This way preserves the text formatting, which means you can write:<br /> <em>>>> s = &#8220;&#8221;&#8221;<br /> <html><br /> <head></head><br /> <body><br /> <b>&#8217;I Love &#8220;Python&#8221;&#8216;</b><br /> </body><br /> </html><br /> &#8220;&#8221;&#8221;<br /> >>> s<br /> &#8216;\n<html>\n<head></head>\n<body>\n<b>&#8217;I Love &#8220;Python&#8221;&#8216;</b>\n</body>\n</html>\n&#8217;<br /> </em>You can use this way to write pre-formatted text just like XML and HTML.
  </p>
  <h1 style="font-family: Georgia;">
    Lists And Sequences:
  </h1>
  <p>
    Lists are sequences like strings and they support every thing we talked about when discussed strings methods but the difference is that the results of methods are lists instead of strings, and that lists are changeable objects which means they support changing in place:<br /> <em>>>> L = [123, &#8216;mpcabd&#8217;, 1.23] #lists support multi-types 🙂<br /> >>> len(L)<br /> </em>3<em><br /> >>> L[0]<br /> 123<br /> >>> L[-1]<br /> 1.23<br /> >>> L[:-1]<br /> [123, &#8216;mpcabd&#8217;]<br /> >>> L + [4, 5, 6]<br /> [123, &#8216;mpcabd&#8217;, 1.23, 4, 5, 6]<br /> >>> L<br /> [123, &#8216;mpcabd&#8217;, 1.23]<br /> </em>Lists are so much like arrays but they have no fixed size, so you can append to them and delete from them:<br /> <em>>>> L.append(111)<br /> >>> L<br /> [123, &#8216;mpcabd&#8217;, 1.23, 111]<br /> >>> L.pop(0)<br /> [&#8216;mpcabd, 1.23, 111]<br /> </em>You can even sort and reverse them:<br /> <em>>>> L = [&#8216;a&#8217;, &#8216;z&#8217;, &#8216;c&#8217;]<br /> >>> L.sort()<br /> >>> L<br /> [&#8216;a&#8217;, &#8216;c&#8217;, &#8216;z&#8217;]<br /> >>> L.reverse()<br /> [&#8216;z&#8217;, &#8216;c&#8217;, &#8216;a&#8217;]<br /> </em>To find more try &#8220;dir&#8221; and &#8220;help&#8221; 🙂
  </p>
  <h1 style="font-family: Georgia;">
    What abound boundaries?
  </h1>
  <p>
    Try the following and you&#8217;d see an error:<br /> <em>>>> L = [&#8216;a&#8217;, &#8216;b&#8217;, &#8216;c&#8217;]<br /> >>> L[9]<br /> </em><em>IndexError: list index out of range<br /> </em>This means that Python checks for boundaries not like C and C++.
  </p>
  <h1 style="font-family: Georgia;">
    Can I Nest Lists?
  </h1>
  <p>
    Yes 😀<br /> <em>>>> M = [<br /> [ 1, 2, 3 ], [ 4, 5, 6 ],<br /> [ 7, 8, 9 ] </em>]<em><br /> >>> M<br /> [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]<br /> >>> M[1] [4, 5, 6]<br /> >>> M[1][2]<br /> </em>6<em><br /> </em>This is a good way to define matrices, but I advise you to use NumPy for mathematical operations, &#8216;cuz it is optimized for fast use.
  </p>
  <h1 style="font-family: Georgia;">
    What Are List Comprehensions?
  </h1>
  <p>
    Python includes along with what we&#8217;ve discussed a powerful methods called &#8220;List Comprehension Expressions&#8221;, suppose we wanna extract the second column of our previous matrix (M), what would you do? Python provides a good way:<br /> <em>>>> col2 = [row[1] for row in M]<br /> >>> col2<br /> [2, 5, 8]<br /> </em>Not good enough? Take this:<br /> <em>>>> [row[1] + 1 for row in M]<br /> [3, 6, 9]<br /> >>> [row[1] for row in M if row[1] % 2 == 0]<br /> [2, 8]<br /> </em>Not enough yet? Take this one and take a nap 🙂<br /> <em>>>> [M[i][i] for i in [0, 1, 2]]<br /> [1, 5, 9]<br /> </em>Not enough? I&#8217;ll kill you then 😈<br /> For more wait for me to study 🙂
  </p>
  <h1 style="font-family: Georgia;">
    Bottom Line:
  </h1>
  <p>
    I&#8217;m sorry I was late this time but I&#8217;m really having a busy phase @ work, please wait for more and don&#8217;t get bored.
  </p>
  <p>
    Cheers.
  </p>
</div>]]></content:encoded>
    </item>
    <item>
      <title>I’m Learning Python part 4</title>
      <link>https://mpcabd.xyz/im-learning-python-part-4/</link>
      <pubDate>Wed, 15 Oct 2008 15:45:55 +0000</pubDate>
      <guid>https://mpcabd.xyz/im-learning-python-part-4/</guid>
      <description>&lt;div dir=&#34;ltr&#34;&gt;
  &lt;div style=&#34;text-align: center;&#34;&gt;
    &lt;h1 style=&#34;font-size: 18pt; font-family: Verdana;&#34;&gt;
      I&amp;#8217;m Learning Python (part 4)
    &lt;/h1&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;p&amp;gt;
  &amp;lt;img title=&amp;quot;Python Logo&amp;quot; src=&amp;quot;http://www.python.org/images/python-logo.gif&amp;quot; alt=&amp;quot;Python Logo&amp;quot; /&amp;gt;
&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
  &lt;/div&gt;
  &lt;h1 style=&#34;font-family: Georgia;&#34;&gt;
    Why Use Built-In Types?
  &lt;/h1&gt;
  &lt;p&gt;
    Most of the time in programming you&amp;#8217;ll use lists, stacks, arrays, queues and dictionaries, so instead of constructing them, Python gives you a bunch of built-in types to use. The built-in types implement the semantic of the type ADT (Abstract Data Type), and they are fast, &amp;#8216;cuz some of them are written in C and C++.&lt;br /&gt;</description>
      <content:encoded><![CDATA[<div dir="ltr">
  <div style="text-align: center;">
    <h1 style="font-size: 18pt; font-family: Verdana;">
      I&#8217;m Learning Python (part 4)
    </h1>
<pre><code>&lt;p&gt;
  &lt;img title=&quot;Python Logo&quot; src=&quot;http://www.python.org/images/python-logo.gif&quot; alt=&quot;Python Logo&quot; /&gt;
&lt;/p&gt;
</code></pre>
  </div>
  <h1 style="font-family: Georgia;">
    Why Use Built-In Types?
  </h1>
  <p>
    Most of the time in programming you&#8217;ll use lists, stacks, arrays, queues and dictionaries, so instead of constructing them, Python gives you a bunch of built-in types to use. The built-in types implement the semantic of the type ADT (Abstract Data Type), and they are fast, &#8216;cuz some of them are written in C and C++.<br /> 
</p>
  <h1 style="font-family: Georgia;">
    What Core Data Types Does Python Provide?
  </h1>
  <p>
    As in any language, Python provides the usual list of types besides other data types:
  </p>
  <ul>
    <li>
      Numbers: 1234, 3.1415, 999L, 3+4j, Decimal
    </li>
    <li>
      String: &#8216;Some text&#8217;, &#8220;a Text&#8221;
    </li>
    <li>
      Lists: [1, [2, &#8216;Three&#8217;], 4]
    </li>
    <li>
      Dictionaries: {&#8216;food&#8217; : &#8216;Lemon&#8217;, &#8216;taste&#8217; : &#8216;Yummy!&#8217; }
    </li>
    <li>
      Tuples: (1, &#8216;Name&#8217;, 5, &#8216;u&#8217; )
    </li>
    <li>
      Files: myFile = open(&#8216;someFile&#8217;, &#8216;r&#8217; )
    </li>
    <li>
      Other Types: Sets, Types, Boolean, Object, None
    </li>
  </ul>
  <p>
    And don&#8217;t forget that everything is an object at the end 😉<br /> Although Python has no variable declaration – you just assign the value to a variable name and it will be declared automatically -, it keeps track of your variables dynamically, so when you assign a string value to a variable you can use string operations only on it, and so on.<br /> Now let&#8217;s discuss the types in a glance &#8216;cuz we&#8217;ll talk about them in depth later.
  </p>
  <h1 style="font-family: Georgia;">
    Numbers:
  </h1>
  <p>
    Python provides: integers (1234), floating point (3.1415), unlimited precision long (43251278364218357642386321984621734982137469321856412L), complex numbers (4568 + 789j), fixed precision decimals and sets.<br /> Python also provides the simple operations:<br /> + is used for addition, &#8211; for subtraction, * for multiplication, ** for exponents, / for division.<br /> You can calculate whatever you want (2 ** 1000000, but you don&#8217;t wanna print 300000 digit ;)).<br /> When printing numbers there are two methods of printing, the first one is called &#8216;repr&#8217; (object as code) and it prints the number with full precision, the second one is called &#8216;str&#8217; which prints the number in a user-friendly way:<br /> >>> 3.1415000000000002 * 2 <em>#repr</em><br /> 6.2830000000000004<br /> >>> print 3.1415000000000002 * 2 <em>#str</em><br /> 6.283<br /> We&#8217;ll discuss this method later when we introduce classes 🙂<br /> Besides basic operations Python provides a module called &#8216;math&#8217; which has useful methods and variables:<br /> <em>>>> import math<br /> >>> math.pi<br /> 3.1415926535897931<br /> >>> math.sqrt(123)<br /> 11.090536506409418</em><br /> And it also provides a module called &#8216;random&#8217; which generates random numbers:<br /> <em>>>> import random<br /> >>> random.random()<br /> 0.8591504308650737 #You might get another value 😉</em><br /> <em>>>> random.choice([1, 2, 3, 4])<br /> 4 #You might also get another value 😉</em><br /> We&#8217;ll discuss more numbers types soon, but now let&#8217;s move to another type.
  </p>
  <h1 style="font-family: Georgia;">
    Strings:
  </h1>
  <p>
    Strings as you might all now are arrays of characters (in Python we call the array a sequence).<br /> Some of the sequence operations:<br /> <em>>>> s = &#8216;My Text&#8217;<br /> >>> len(s)<br /> </em>7<em><br /> >>> s[0]<br /> &#8216;M&#8217;<br /> >>> s[3]<br /> &#8216;T&#8217;</em><br /> A good indexing way is the negative indexing, which starts from left to right:<br /> <em>>>> s[-1] #Equivalent to s[len(s) – 1]<br /> &#8216;t&#8217;<br /> >>> s[-2] #Equivalent to s[len(s) – 2]<br /> &#8216;x&#8217;</em><br /> Slicing is another way of indexing in sequences, and it is used to extract a portion of the sequence:<br /> <em>>>> s[3:6] #A slice starts from 3 and ends at 5 not 6<br /> &#8216;Tex&#8217;</em><br /> In slicing the left parameter&#8217;s default value is 0, and the right&#8217;s is the length of the sequence, which leads to some other slicing operations:<br /> <em>>>> s[:]<br /> &#8216;My Text&#8217;<br /> >>> s[1:]<br /> &#8216;y Text&#8217;<br /> >>> s[1:len(s)] #Same as s[1:]<br /> &#8216;y Text&#8217;<br /> >>> s #Notice that s hasn&#8217;t changed, we were given new objects.<br /> &#8216;My Text&#8217;<br /> >>>s[:-1] #Everything but the last character 😉<br /> &#8216;My Tex&#8217;</em><br /> As you have noticed we were given new objects, which leads to the fact that slicing using [:] will copy the sequence into another new sequence, which is a great way to copy lists and other sequences.<br /> As sequences, strings support concatenation and repetition:<br /> <em>>>> s + &#8216; Is Beautiful&#8217;<br /> &#8216;My Text Is Beautiful&#8217;<br /> >>> s #s hasn&#8217;t changed<br /> &#8216;My Text&#8217;<br /> >>> s * 5<br /> &#8216; My TextMy TextMy TextMy TextMy Text&#8217;</em><br /> You see, + is used here for concatenation while in numbers it is used for addition, this is called operator overloading in other languages.
  </p>
  <h1 style="font-family: Georgia;">
    Bottom Line:
  </h1>
  <p>
    We&#8217;ll continue talking about types next time, until then create numbers and strings. Try to set a value to specified index of a string, what would you get?<br /> Cheers.
  </p>
</div>]]></content:encoded>
    </item>
    <item>
      <title>I’m Learning Python part 3</title>
      <link>https://mpcabd.xyz/im-learning-python-part-3/</link>
      <pubDate>Fri, 10 Oct 2008 21:16:19 +0000</pubDate>
      <guid>https://mpcabd.xyz/im-learning-python-part-3/</guid>
      <description>&lt;div dir=&#34;ltr&#34;&gt;
  &lt;div style=&#34;text-align: center;&#34; align=&#34;center&#34;&gt;
    &lt;h1 style=&#34;font-size: 18pt; font-family: Verdana;&#34;&gt;
      I&amp;#8217;m Learning Python (part 3)
    &lt;/h1&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;p&amp;gt;
  &amp;lt;img title=&amp;quot;Python Logo&amp;quot; src=&amp;quot;http://www.python.org/images/python-logo.gif&amp;quot; alt=&amp;quot;Python Logo&amp;quot; /&amp;gt;&amp;lt;/div&amp;gt; 
  
  &amp;lt;h1 style=&amp;quot;font-family: Georgia;&amp;quot;&amp;gt;
    What Is Interactive Mode?
  &amp;lt;/h1&amp;gt;
  
  &amp;lt;p&amp;gt;
    When you install Python on your platform you&amp;amp;#8217;ll find an executable called &amp;amp;#8216;python&amp;amp;#8217;, when you run it you&amp;amp;#8217;ll find a terminal and you&amp;amp;#8217;ll see something like the following:&amp;lt;br /&amp;gt; &amp;lt;em&amp;gt;Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win32&amp;lt;br /&amp;gt; Type &amp;amp;#8220;help&amp;amp;#8221;, &amp;amp;#8220;copyright&amp;amp;#8221;, &amp;amp;#8220;credits&amp;amp;#8221; or &amp;amp;#8220;license&amp;amp;#8221; for more information.&amp;lt;br /&amp;gt; &amp;gt;&amp;gt;&amp;gt;&amp;lt;/em&amp;gt;&amp;lt;br /&amp;gt; This is called interactive coding (or interactive mode), here you can write Python statements and the interpreter will execute them directly, let&amp;amp;#8217;s try:&amp;lt;br /&amp;gt; &amp;lt;em&amp;gt;&amp;gt;&amp;gt;&amp;gt; print &amp;amp;#8220;I Love Python&amp;amp;#8221;&amp;lt;br /&amp;gt; I Love Python&amp;lt;br /&amp;gt; &amp;gt;&amp;gt;&amp;gt; print 2 ** 10&amp;lt;br /&amp;gt; 1024&amp;lt;br /&amp;gt; &amp;gt;&amp;gt;&amp;gt;&amp;lt;/em&amp;gt;&amp;lt;br /&amp;gt; 
&lt;/code&gt;&lt;/pre&gt;</description>
      <content:encoded><![CDATA[<div dir="ltr">
  <div style="text-align: center;" align="center">
    <h1 style="font-size: 18pt; font-family: Verdana;">
      I&#8217;m Learning Python (part 3)
    </h1>
<pre><code>&lt;p&gt;
  &lt;img title=&quot;Python Logo&quot; src=&quot;http://www.python.org/images/python-logo.gif&quot; alt=&quot;Python Logo&quot; /&gt;&lt;/div&gt; 
  
  &lt;h1 style=&quot;font-family: Georgia;&quot;&gt;
    What Is Interactive Mode?
  &lt;/h1&gt;
  
  &lt;p&gt;
    When you install Python on your platform you&amp;#8217;ll find an executable called &amp;#8216;python&amp;#8217;, when you run it you&amp;#8217;ll find a terminal and you&amp;#8217;ll see something like the following:&lt;br /&gt; &lt;em&gt;Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win32&lt;br /&gt; Type &amp;#8220;help&amp;#8221;, &amp;#8220;copyright&amp;#8221;, &amp;#8220;credits&amp;#8221; or &amp;#8220;license&amp;#8221; for more information.&lt;br /&gt; &gt;&gt;&gt;&lt;/em&gt;&lt;br /&gt; This is called interactive coding (or interactive mode), here you can write Python statements and the interpreter will execute them directly, let&amp;#8217;s try:&lt;br /&gt; &lt;em&gt;&gt;&gt;&gt; print &amp;#8220;I Love Python&amp;#8221;&lt;br /&gt; I Love Python&lt;br /&gt; &gt;&gt;&gt; print 2 ** 10&lt;br /&gt; 1024&lt;br /&gt; &gt;&gt;&gt;&lt;/em&gt;&lt;br /&gt; 
</code></pre>
<p><br /> You can write any statement here (even those who are more than on line as we’ll see later).<br /> If you remember we said that the Python compiler and interpreter are always in present at runtime, so that’s why you can execute the statements directly here. Another benefit you get from the presence of the compiler and interpreter at runtime that you can let your program execute Python code written by the user, and that’s what some programs do, they let the user manipulate the program’s behavior by writing his/her code inside the program.<br /> To do so you can run the “exec” statement like this:<br /> <em>&raquo;&gt; exec “print &amp;#8221;I Love Python&amp;#8221;”<br /> I Love Python<br /> &raquo;&gt;</em><br /> Here we invoked a method called “exec” and it takes a string parameter, this string contains Python code, and the interpreter will run it, so you can simply read code from the user and run it for him/her. This method is available anywhere (not just in the interactive mode).<br /> You must have noticed using the escape character &amp;#8221; in the text, and that is to tell the interpreter that this is not the end of the string and it is a double quotation inside the string, there are more escape characters that we’ll find more in the upcoming parts.<br /> Another feature to talk about in the interactive mode that you don’t have to write print every time, so the next statement will run without errors:<br /> <em>&raquo;&gt; “I Love Python”<br /> ‘I Love Python’<br /> &raquo;&gt;</em><br /> But beware, you <strong>must</strong> use print in any other mode, interactive mode is the only mode which doesn’t need the print statement, that’s ‘cuz it is made to print the results.<br /> You might ask, what about statements that don’t return values, what would the interactive mode print for them? The answer is: simply nothing 🙂<br /> <em>&raquo;&gt; text = “I Love Python”<br /> &raquo;&gt;</em><br /> The previous statement is an assignment statement, which declares a string called “text” and has the value of “I Love Python”.<br /> To exit the interactive code you use the break character (Ctrl+Z in Windows, Ctrl+D in Linux) and hit return.
</p></p>
<pre><code>  &lt;h1 style=&quot;font-family: Georgia;&quot;&gt;
    What Are Modules?
  &lt;/h1&gt;
  
  &lt;p&gt;
    Let&amp;#8217;s here explain the Python program hierarchy:&lt;br /&gt; Each program consists of modules -&gt; Each module consists of statements -&gt; Each statement consists of expressions -&gt; Each expression creates and processes objects -&gt; Objects are the raw materials you&amp;#8217;ll use 🙂&lt;br /&gt; When you write a Python program you write it in files, these files usually called modules, the module is a namespace, so each module has its own variables and methods. You can have two variables with the same name, but you must put each one in a module.&lt;br /&gt; We&amp;#8217;ll use modules (for now) to run our code multiple times without the need of re-typing it again.&lt;br /&gt; You can access another module using &amp;#8220;import&amp;#8221; statement, so let&amp;#8217;s try something:
  &lt;/p&gt;
  
  &lt;ul&gt;
    &lt;li&gt;
      Open your editor and write the following in it:&lt;br /&gt; text = &amp;#8220;I Love Python&amp;#8221;&lt;br /&gt; print text
    &lt;/li&gt;
    &lt;li&gt;
      Save the file somewhere with the name &amp;#8220;module1.py&amp;#8221;
    &lt;/li&gt;
    &lt;li&gt;
      Now start a new file and write the following in it:&lt;br /&gt; import module1&lt;br /&gt; module1.text = &amp;#8220;You Know I Love Python&amp;#8221;&lt;br /&gt; print module1.text
    &lt;/li&gt;
    &lt;li&gt;
      Save the file in the same folder which has &amp;#8220;module1.py&amp;#8221; with the name &amp;#8220;module2.py&amp;#8221;
    &lt;/li&gt;
    &lt;li&gt;
      Now let the Python interpreter run your module2 file:&lt;br /&gt; python [SOME FOLDER]/module2.py
    &lt;/li&gt;
    &lt;li&gt;
      You must see the following:&lt;br /&gt; I Love Python&lt;br /&gt; You Know I Love Python
    &lt;/li&gt;
  &lt;/ul&gt;
  
  &lt;p&gt;
    What happened here? In module2 I only printed the variable after editing it, why was it printed before it was edited?&lt;br /&gt; When you import a module, you&amp;#8217;re simply running it, so the Python interpreter ran module1, and executed the print statement so you see &amp;#8220;I Love Python&amp;#8221;, then it executed module2, it edited the value of the variable in module1, then executed the print statement in module2, and you see &amp;#8220;You Know I Love Python&amp;#8221;.&lt;br /&gt; So importing means running, but what if I needed to run the code again? Knowing that you can&amp;#8217;t import a module more than one, what should we do?&lt;br /&gt; There is another statement &amp;#8220;reload&amp;#8221; which is a method and takes a string with the name of the module to re-run it again, but it should be imported before.&lt;br /&gt; Try adding this line to your code in module2.py:&lt;br /&gt; reload(module1)&lt;br /&gt; Re-run your module2 and you must see:&lt;br /&gt; I Love Python&lt;br /&gt; You Know I Love Python&lt;br /&gt; I Love Python&lt;br /&gt; The third line is actually the print statement in module1 file.
  &lt;/p&gt;
  
  &lt;h1 style=&quot;font-family: Georgia;&quot;&gt;
    What Is The Difference Between &amp;#8220;import [MODULE]&amp;#8221; And &amp;#8220;from [MODULE] import&amp;#8221;?
  &lt;/h1&gt;
  
  &lt;p&gt;
    The first – import [MODULE] – imports and runs the module, but when you want to access its variables you should write: [MODULE].[VARIABLE], so each time you want to use the variable you should write the module&amp;#8217;s name followed by a period before the variable&amp;#8217;s name.&lt;br /&gt; The second – from [MODULE] import – imports the specified variables from the module, so to import the &amp;#8220;text&amp;#8221; variable from &amp;#8220;module1&amp;#8221; in the previous example you write:&lt;br /&gt; from module1 import text&lt;br /&gt; To import more than one variable separate them with columns:&lt;br /&gt; from [MODULE] impor [VAR1], [VAR2], …, [VARN]&lt;br /&gt; Notice that importing a variable lets you use the variable without the need to write the module&amp;#8217;s name before it, you can simply use the &amp;#8220;text&amp;#8221; variable in module2 after importing it without writing module1.text.&lt;br /&gt; Beware that importing a variable that has the same name of a local variable will replace the local one, for instance:&lt;br /&gt; in module1.py write:&lt;br /&gt; text = &amp;#8220;I Love Python&amp;#8221;&lt;br /&gt; in module2.py write:&lt;br /&gt; text = &amp;#8220;You Know I Love Python&amp;#8221;&lt;br /&gt; from module1 import text&lt;br /&gt; print text
  &lt;/p&gt;
  
  &lt;p&gt;
    Executing module2 will give you: I Love Python.
  &lt;/p&gt;
  
  &lt;h1 style=&quot;font-family: Georgia;&quot;&gt;
    How can I write hints and comments in Python?
  &lt;/h1&gt;
  
  &lt;p&gt;
    Using the sharp &amp;#8211; # &amp;#8211; character will hint the following text until the end of the line:&lt;br /&gt; text = &amp;#8220;I Love Python&amp;#8221; &lt;em&gt;#a declaration of a variable named text&lt;/em&gt;
  &lt;/p&gt;
  
  &lt;h1 style=&quot;font-family: Georgia;&quot;&gt;
    Bottom Line:
  &lt;/h1&gt;
  
  &lt;p&gt;
    Next time we&amp;#8217;ll learn about built-in types in Python, till then try to create and import and print modules and variables, try that in both files and interactive mode, try to make syntax errors, try to divide by zero.
  &lt;/p&gt;
  
  &lt;p&gt;
    Cheers.
  &lt;/p&gt;&lt;/div&gt;
</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>I’m Learning Python part 2</title>
      <link>https://mpcabd.xyz/i%E2%80%99m-learning-python-part-2/</link>
      <pubDate>Tue, 07 Oct 2008 07:02:03 +0000</pubDate>
      <guid>https://mpcabd.xyz/i%E2%80%99m-learning-python-part-2/</guid>
      <description>&lt;div dir=&#34;ltr&#34;&gt;
  &lt;div style=&#34;text-align: center;&#34;&gt;
    &lt;p&gt;
      &lt;span style=&#34;font-size: large; font-family: georgia,palatino;&#34;&gt;I&amp;#8217;m Learning Python (part 2)&lt;/span&gt;
    &lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;p&amp;gt;
  &amp;lt;img title=&amp;quot;Python Logo&amp;quot; src=&amp;quot;http://www.python.org/images/python-logo.gif&amp;quot; alt=&amp;quot;Python Logo&amp;quot; /&amp;gt;
&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
  &lt;/div&gt;
  &lt;h1 style=&#34;font-family: Georgia;&#34;&gt;
    Who Uses Python?
  &lt;/h1&gt;
  &lt;p&gt;
    In the world there are more than 1 million Python user, that&amp;#8217;s because it&amp;#8217;s&lt;br /&gt; open source, and because it is implemented for every platform, and it comes&lt;br /&gt; included within Linux distributions and Macintosh computers and more.
  &lt;/p&gt;
  &lt;ol&gt;
    &lt;li&gt;
      Google uses Python in its web search system, and it employs the Python&amp;#8217;s&lt;br /&gt; creator.
    &lt;/li&gt;
    &lt;li&gt;
      YouTube is largely written in Python.
    &lt;/li&gt;
    &lt;li&gt;
      BitTorrent file sharing system is a Python program.
    &lt;/li&gt;
    &lt;li&gt;
      Intel, Cisco, HP, Seagate, Qualcomm and IB&lt; use Python for hardware&lt;br /&gt; testing.
    &lt;/li&gt;
    &lt;li&gt;
      Industrial Light &amp; Magic, Pixar, and others use Python in the production&lt;br /&gt; of movie animation.
    &lt;/li&gt;
    &lt;li&gt;
      NASA, Los Alamos, Fermilab, JPL, and others use Python for scientific&lt;br /&gt; programming.
    &lt;/li&gt;
    &lt;li&gt;
      iRobot uses Python to develop commercial robotic vacuum cleaners 🙂
    &lt;/li&gt;
    &lt;li&gt;
      NSA uses Python for cryptography and intelligence analysis.
    &lt;/li&gt;
  &lt;/ol&gt;
  &lt;p&gt;
    See Python website for more.&lt;br /&gt;</description>
      <content:encoded><![CDATA[<div dir="ltr">
  <div style="text-align: center;">
    <p>
      <span style="font-size: large; font-family: georgia,palatino;">I&#8217;m Learning Python (part 2)</span>
    </p>
<pre><code>&lt;p&gt;
  &lt;img title=&quot;Python Logo&quot; src=&quot;http://www.python.org/images/python-logo.gif&quot; alt=&quot;Python Logo&quot; /&gt;
&lt;/p&gt;
</code></pre>
  </div>
  <h1 style="font-family: Georgia;">
    Who Uses Python?
  </h1>
  <p>
    In the world there are more than 1 million Python user, that&#8217;s because it&#8217;s<br /> open source, and because it is implemented for every platform, and it comes<br /> included within Linux distributions and Macintosh computers and more.
  </p>
  <ol>
    <li>
      Google uses Python in its web search system, and it employs the Python&#8217;s<br /> creator.
    </li>
    <li>
      YouTube is largely written in Python.
    </li>
    <li>
      BitTorrent file sharing system is a Python program.
    </li>
    <li>
      Intel, Cisco, HP, Seagate, Qualcomm and IB< use Python for hardware<br /> testing.
    </li>
    <li>
      Industrial Light & Magic, Pixar, and others use Python in the production<br /> of movie animation.
    </li>
    <li>
      NASA, Los Alamos, Fermilab, JPL, and others use Python for scientific<br /> programming.
    </li>
    <li>
      iRobot uses Python to develop commercial robotic vacuum cleaners 🙂
    </li>
    <li>
      NSA uses Python for cryptography and intelligence analysis.
    </li>
  </ol>
  <p>
    See Python website for more.<br /> 
</p>
  <h1 style="font-family: Georgia;">
    How Does Python work?
  </h1>
  <p>
    Python is not compiled (almost), it is interpreted. So when you run the program<br /> the interpreter will run it line by line without compilation.
  </p>
  <p>
    You might say &#8220;Why did you say almost?&#8221;, the answer is, Python as described<br /> before can be compiled into byte code, so it&#8217;ll be faster for the interpreter<br /> to execute it than the source code, just like Java&#8217;s byte code and .NET&#8217;s MSIL.
  </p>
  <p>
    Python files have a .py extension normally, so when you write Python code you<br /> should save it with a .py extension.
  </p>
  <p>
    Let&#8217;s try and write our first Hello World Python program:
  </p>
  <ol>
    <li>
      Open the editor you use (Emacs, Notepad, Notepad++, …).
    </li>
    <li>
      Write this line inside it:
    </li>
    <li>
      print &#8220;Hello World, It&#8217;s My First Python Program&#8221;
    </li>
    <li>
      Save the file as .py file.
    </li>
    <li>
      Now you should tell the Python interpreter to run your file, depending<br /> on your platform you should have the Python interpreter in (&#8220;<em>C:\Python[VER]\</em>&#8221;<br /> in Windows where [VER] is the version of the Python release you have [24,<br /> 25, 26,…]) or in (&#8220;<em>/usr/bin/</em>&#8221; in Linux).
    </li>
    <li>
      In Windows open a command prompt and guide it to the location of your<br /> Python.
    </li>
    <li>
      In Linux open a terminal and go to the location of your Python interpreter.
    </li>
    <li>
      Now you can execute the following command on both platforms:<em>python [FILE]</em>Where [File] is the location of your .py file.
    </li>
    <li>
      Now you should see some thing like this:<em>python [FILE]</em>Hello World, It&#8217;s My First Python Program
    </li>
  </ol>
  <p>
    Very easy, right?
  </p>
  <p>
    Although it is not that big program but you can run your files this way :).
  </p>
  <p>
    Now let&#8217;s understand what happened:
  </p>
  <p>
    The Python interpreter was given a file to run.
  </p>
  <p>
    If it has write privileges it&#8217;ll compile it into byte code and you&#8217;ll see that<br /> a new file was created next to your file with a .pyc extension, if it doesn&#8217;t<br /> it&#8217;ll run it as source code.
  </p>
  <p>
    It reads the first line (which is a print statement) and runs it and you see<br /> the result, the execution takes place inside the PVM – Python Virtual Machine,<br /> which handles the execution of Python byte code and source code to run on more<br /> than one platform without change in code.
  </p>
  <div style="text-align: center;">
    <img src="http://i146.photobucket.com/albums/r257/mpcabd/ILP/ILP2-01.gif" alt="" />
  </div>
  <p>
    If you have a background in C or C++ you might find a change in the way of running<br /> and compiling code, &#8216;cuz there is no making and linking in Python, and it is<br /> not compiled into machine code (binary file), instead it runs inside a virtual<br /> machine, that&#8217;s why some Python code will run faster in C++ and C.
  </p>
  <p>
    But don&#8217;t be afraid, 90% of the time you&#8217;ll be running your programs as if they<br /> were written in C or C++, there won&#8217;t be any difference in the time of execution,<br /> and that’s because of the Python simplicity which makes the program in Python<br /> shorter and simpler than C or C++, and because it&#8217;s optimization which we&#8217;ll<br /> describe later.
  </p>
  <p>
    In Python you&#8217;ll notice that the compiler and the execution environment are<br /> one thing, the compiler always present in runtime, and that leads to rapid development<br /> cycle, with no linking and making stage.
  </p>
  <p>
    CPython runs inside the PVM, while Jython runs inside the JVM and IronPython<br /> .NET runs inside .NET Framework or Mono.
  </p>
  <p>
    Jython and IronPython .NET allows the Python program to use Java and .NET classes<br /> respectively.
  </p>
  <p>
    If you don&#8217;t wanna use Java or .NET classes you should use CPython, &#8216;cuz it&#8217;s<br /> faster and the most complete, CPython runs like C and C++ so it is the fastest.
  </p>
  <p>
    In Jython the Python byte code is translated into Java byte code to be run inside<br /> the JVM, while in .NET it is translated to MSIL.
  </p>
  <h1 style="font-family: Georgia;">
    What Are The Frozen Binaries?
  </h1>
  <p>
    Python has something called Frozen Binaries, which are the executables, if you<br /> chose to create a frozen binary for your program, you&#8217;d end up with an executable<br /> that runs on a specified platform (exe for Windows).
  </p>
  <p>
    This executable has a great feature; it includes your program along with its<br /> dependencies and the Python interpreter. Yes you don&#8217;t have to tell the user<br /> to install a Python interpreter to be able to use your program, he/she doesn&#8217;t<br /> have to know that your program is a Python program.
  </p>
  <p>
    You can use Py2Exe to get an exe of your program (Which runs only in Windows),<br /> or PyInstaller which gives you the ability to create a frozen binary for Windows,<br /> Linux or UNIX. And you can use Freeze the original one. Those are available<br /> free of charge, you can check Python website or Vaults of Parnassus (http://www.vex.net/parnassus).
  </p>
  <h1 style="font-family: Georgia;">
    What IDE&#8217;s To Use With Python?
  </h1>
  <p>
    Python comes with a simple IDE called IDLE you can use it, or you can use Emacs, but IMHO<br /> Eclipse with PyDev make a great IDE for you and Python.
  </p>
  <h1 style="font-family: Georgia;">
    Bottom Line:
  </h1>
  <p>
    Today it was just a description on how Python runs your program, and we wrote<br /> our Hello World program.
  </p>
  <p>
    For the next part, try to use the ** operator &#8211; which is the power operator<br /> in Python – to see how much you can do in Python, e.g.:
  </p>
  <p>
    print 2 ** 10
  </p>
  <p>
    1024
  </p>
  <p>
    Try huge numbers and see 😉
  </p>
  <p>
    Cheers.
  </p>
</div>]]></content:encoded>
    </item>
    <item>
      <title>I’m Learning Python part 1</title>
      <link>https://mpcabd.xyz/im-learning-python-part-1/</link>
      <pubDate>Sat, 04 Oct 2008 20:25:51 +0000</pubDate>
      <guid>https://mpcabd.xyz/im-learning-python-part-1/</guid>
      <description>&lt;div style=&#34;text-align: center;&#34;&gt;
  &lt;span style=&#34;font-family: georgia,palatino; font-size: large;&#34;&gt; I&amp;#8217;m Learning Python &lt;/span&gt;&lt;br /&gt; &lt;img title=&#34;Python Logo&#34; src=&#34;http://www.python.org/images/python-logo.gif&#34; alt=&#34;Python Logo&#34; width=&#34;211&#34; height=&#34;71&#34; border=&#34;0&#34; /&gt;
&lt;/div&gt;
&lt;p&gt;I’ll start posting this series of blogs on &lt;a title=&#34;Magic PC On WordPress&#34; href=&#34;http://magicpc.wordpress.com&#34; target=&#34;_blank&#34;&gt;WordPress&lt;/a&gt; and &lt;a title=&#34;mpcabd&#39;s Bolg On CSC&#34; href=&#34;https://mpcabd.xyz/blog/2300&#34; target=&#34;_blank&#34;&gt;CSC&lt;/a&gt;, here I’ll write what I’m gonna learn on my way to learning Python.&lt;/p&gt;
&lt;p&gt;If you don’t know what Python is, or you’ve heard about it but you’re not sure what it is, my first blog will cover it for you.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<div style="text-align: center;">
  <span style="font-family: georgia,palatino; font-size: large;"> I&#8217;m Learning Python </span><br /> <img title="Python Logo" src="http://www.python.org/images/python-logo.gif" alt="Python Logo" width="211" height="71" border="0" />
</div>
<p>I’ll start posting this series of blogs on <a title="Magic PC On WordPress" href="http://magicpc.wordpress.com" target="_blank">WordPress</a> and <a title="mpcabd's Bolg On CSC" href="/blog/2300" target="_blank">CSC</a>, here I’ll write what I’m gonna learn on my way to learning Python.</p>
<p>If you don’t know what Python is, or you’ve heard about it but you’re not sure what it is, my first blog will cover it for you.</p>
<h1 id="what-is-python"><span style="font-family: georgia,palatino;">What is Python? </span></h1>
<p>Python is a <a href="http://en.wikipedia.org/wiki/Programming_Language" target="_blank">programming language</a>, this programming language was created in 1990, this programming language has proved its power through the last 18 years she’s been with us.</p>
<h1 id="why-should-i-be-interested-in-learning-a-new-language"><span style="font-family: georgia,palatino;">Why should I be interested in learning a new language? </span></h1>
<p>The most points that will catch your interest in this language are:</p>
<ul>
<li>
<p>It’s <a href="http://en.wikipedia.org/wiki/Object-oriented_programming" target="_blank">Object Oriented</a>:</p>
<p>Python supports classes, inheritance, multiple inheritance, polymorphism, operator overloading and more.</p>
<p>Python is OOP from ground up, besides it’s like C++ supports both object oriented and procedural programming, so it may be used for scripting applications.</p>
</li>
<li>
<p>It’s <a href="http://en.wikipedia.org/wiki/Free_Software" target="_blank">Free</a>:</p>
<p>Python is completely free to use and redistribute, it is also widely supported through web portals where millions of users world-wide can help you find solutions for your problems.</p>
</li>
<li>
<p>It’s <a href="http://en.wikipedia.org/wiki/Cross_platform" target="_blank">Portable</a>:</p>
<p>Python first was written in C, and because of that it can be run on almost every platform, you can run it on (Windows, Linux, Mac OS, BeOS, PDAs, Cell Phones, Gaming Consoles, …).</p>
<p>Everything is portable, that’s because Python code is compiled into <a href="http://en.wikipedia.org/wiki/Bytecode" target="_blank">byte-code</a> (Like .NET and Java), and so it can be run on any platform with a Python interpreter.</p>
</li>
<li>
<p>It’s Powerful:</p>
<p>Python sits on the chair along with Perl, Tcl and Scheme as a powerful scripting language, while also it sits on the chair with Java and .NET as a powerful Pure OOP language, and of course it shares the chair with C and C++ as a powerful programming language that is capable of doing everything.</p>
<p>While sitting on more than one chair at the same time, Python provides the simplicity in writing a fully readable code.</p>
<p>From its most powerful features I’ll write some and I’ll explain them deeply when I understand them 😀</p></p>
<ol>
<li>Dynamic Typing.</li>
<li>Automatic Memory Management:</li>
</ol>
<pre><code>This one I already know from .NET, Python has its own garbage collector which runs automatically and deallocates space from unused objects in the memory.
</code></pre>
<ol start="3">
<li>Programming for large systems using OOP allows you to develop components and systems so you can reuse them in most of your applications.</li>
<li>Built-in tools used for manipulating built-in types such as lists and collections.</li>
<li>Libraries from regular expressions to networking, all libraries can be used easily.</li>
<li>Third-party utilities: since Python is open source developers from around the globe can build their tools and libraries and everybody can use them.</li>
</ol>
</li>
<li>
<p>It’s Mixable:</p>
<p>You can use Python and call your programs and methods from inside C and C++ and even Java and .NET, you can also call C and C++ methods and tools from Python along with Java and .NET.</p>
</li>
<li>
<p>It’s easy to use and learn:</p>
<p>You’ll notice just like I have that Python is an easy yet powerful language which can be used in every technical field without losing it simplicity.</p>
</li>
</ul>
<h1 id="what-can-i-do-with-python"><span style="font-family: georgia,palatino;">What can I do with Python? </span></h1>
<p>Here I’ll tell you what fields you can use Python in, but in a glance ‘cuz I don’t know how to use it yet.</p>
<ul>
<li>
<p>System Programming:</p>
<p>Because it can be used as scripting language, Python can be used to develop shell tools, which can communicate with system shell and provide a layer for you to search files and folders, launch applications and even do parallel processing using processes and threads.</p>
</li>
<li>
<p>GUIs:</p>
<p>Using Tk GUI, Qt, GTK, MFC and Swing you can make your application have a GUI, but not any GUI, your GUI is cross-platform and you’d be able to run your application on any platform.</p>
</li>
<li>
<p>Internet Scripting:</p>
<p>You can develop web applications using Python, you can do Server scripting, Server-Client Scripting and Client Scripting.</p>
<p>A lot of websites already use Python now.</p>
<p>You can use FTP to transfer files, parse XML files, parse HTML and you can generate HTML based on Python code.</p>
</li>
<li>
<p>Gluing:</p>
<p>Python can be glued to C, C++, .NET and Java applications.</p>
<p>Python now has 3 major implementations: CPython which is the base implementation, Jython which can be run inside the JVM (Java Virtual Machine), and IronPython .NET which can be run inside .NET Framework.</p>
</li>
<li>
<p>Database Applications:</p>
<p>Python can use Sybase, Oracle, Informix, ODBC, MySql, PostgreSQL, SQLite and more.</p>
<p>Python even has a built in database API which can be used with any database system, you can easily change it from anyone to anyone by just switching the used interface.</p>
</li>
<li>
<p>Numeric and Scientific Programming:</p>
<p>Python can be used easily to create scientific applications, there is an extension called NumPy which can do more than Matlab!</p>
<p>You can calculate 2<sup>2000</sup> in milliseconds:</p>
<p>114813069527425452423283320117768198402231770208869</p>
<p>520047764273682576626139237031385665948631650626991</p>
<p>844596463898746277344711896086305533142593135616665</p>
<p>318539129989145312280000688779148240044871428926990</p>
<p>063486244781615463646388363947317026040466353970904</p>
<p>996558162398808944629605623311649536164221970332681</p>
<p>344168908984458505602379484807914058900934776500429</p>
<p>002716706625830522008132236281291761267883317206598</p>
<p>995396418127021779858404042159853183251540889433902</p>
<p>091920554957783589672039160081957216630582755380425</p>
<p>583726015528348786419432054508915275783882625175435</p>
<p>528800822842770817965453762184851149029376.</p>
<p>You don’t have to wait to get this value 😀</p>
</li>
<li>
<p>More:</p>
<p>Python can be used in more fields, XML, Gaming, Graphics, Robots, Networking and more, everything is possible 🙂</p>
</li>
</ul>
<h1 id="bottom-line"><span style="font-family: georgia,palatino;">Bottom Line: </span></h1>
<p>That’s enough for today, hope I’ll tell you more on my next blog.</p>
<p>For now I’d suggest you to read more about the language and its features from the language website: <a href="https://www.Python.org">www.Python.org</a>.</p>
<p>And also don’t forget to download the appropriate built for your platform.</p>
<p>Cheers.</p>]]></content:encoded>
    </item>
  </channel>
</rss>
