<?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/categories/programming/</link>
    <description>Recent content in Programming on Abdullah Diab&#39;s Blog</description>
    <generator>Hugo</generator>
    <language>en-us</language>
    <lastBuildDate>Mon, 16 Mar 2015 12:39:24 +0000</lastBuildDate>
    <atom:link href="https://mpcabd.xyz/categories/programming/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>Using curl with Proxy PAC configuration files</title>
      <link>https://mpcabd.xyz/using-curl-with-proxy-pac-configuration-files/</link>
      <pubDate>Mon, 16 Mar 2015 12:39:24 +0000</pubDate>
      <guid>https://mpcabd.xyz/using-curl-with-proxy-pac-configuration-files/</guid>
      <description>&lt;p&gt;&lt;a href=&#34;http://curl.haxx.se/&#34; target=&#34;_blank&#34;&gt;curl&lt;/a&gt; is an essential tool that most developers use, it will allow you to execute a wide range of HTTP requests from your terminal, it supports using a proxy to execute your requests, but it does not support &lt;a href=&#34;http://en.wikipedia.org/wiki/Proxy_auto-config#The_PAC_File&#34; target=&#34;_blank&#34;&gt;PAC configuration files&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;At my work I have to use a PAC file due to the large list of servers I’d interact with, and many would require me passing through specific proxies. It is a cumbersome process for me to memorize or try every URL I want to request and to identify which proxy to use, that’s why I wrote a simple perl script (yes perl not Python!) to help me with this issue.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p><a href="http://curl.haxx.se/" target="_blank">curl</a> is an essential tool that most developers use, it will allow you to execute a wide range of HTTP requests from your terminal, it supports using a proxy to execute your requests, but it does not support <a href="http://en.wikipedia.org/wiki/Proxy_auto-config#The_PAC_File" target="_blank">PAC configuration files</a>.</p>
<p>At my work I have to use a PAC file due to the large list of servers I’d interact with, and many would require me passing through specific proxies. It is a cumbersome process for me to memorize or try every URL I want to request and to identify which proxy to use, that’s why I wrote a simple perl script (yes perl not Python!) to help me with this issue.</p>
<h2 id="before-you-use-it">Before you use it</h2>
<ul>
<li>This script is written with Perl 5.16 in mind I haven’t tested it on other versions, but I suppose it should work properly, please let me know if it doesn’t work for you.</li>
<li>It also makes use of the following perl modules: <a title="Regexp::Common" href="http://search.cpan.org/~abigail/Regexp-Common-2013031301/lib/Regexp/Common.pm" target="_blank">Regexp::Common</a> and <a title="HTTP::ProxyPAC" href="http://search.cpan.org/~miyagawa/HTTP-ProxyPAC-0.01/lib/HTTP/ProxyPAC.pm" target="_blank">HTTP::ProxyPAC</a>.</li>
</ul>
<h2 id="download">Download</h2>
<p><a href="https://gist.github.com/mpcabd/b09688a0f5ec183afc68" target="_blank">The script’s gist is here</a></p>
<p>The script is available under <a href="http://www.gnu.org/copyleft/gpl.html" target="_blank">GPLv3</a>.</p>
<p>After downloading the script make sure it is executable:</p>
<pre class="lang:bash decode:true">chmod +x curlp.pl
</pre>
<p>And edit the file and set the variable <code>$PAC_URI</code> to your PAC URI in line 14.</p>
<h2 id="how-to-use">How to use</h2>
<p>You can use the script just like you use curl normally, it will automatically call curl with the appropriate proxy, but <strong>PLEASE NOTE</strong> this script will accept the URL as its last parameter always, and will pass any parameters that are before the url to curl blindly.</p>
<pre class="lang:bash decode:true">./curlp.pl ....... [URL]
</pre>]]></content:encoded>
    </item>
    <item>
      <title>Django Country Context</title>
      <link>https://mpcabd.xyz/django-country-context/</link>
      <pubDate>Sat, 05 Apr 2014 21:46:42 +0000</pubDate>
      <guid>https://mpcabd.xyz/django-country-context/</guid>
      <description>&lt;p&gt;This module solves a small problem that can be found in many sites, where the website has to support multiple countries, e.g. e-commerce website with different stores for different countries, this module allows the developer to define a context per thread, this context holds all the information about the currently available country, and allows the developer to rely on the context always to get the current country instead of passing it through the different levels of code. This module is thread-safe, it defines a different context for each thread.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>This module solves a small problem that can be found in many sites, where the website has to support multiple countries, e.g. e-commerce website with different stores for different countries, this module allows the developer to define a context per thread, this context holds all the information about the currently available country, and allows the developer to rely on the context always to get the current country instead of passing it through the different levels of code. This module is thread-safe, it defines a different context for each thread.</p>
<h2 id="using-the-context">Using The Context</h2>
<p>To use the country context</p>
<ol>
<li>You activate the country of choice when you start to process the request, one place for activating the country is by writing a <a href="https://docs.djangoproject.com/en/dev/topics/http/middleware/" title="Middleware | Django documentation | Django" target="_blank">Django middleware</a> that activates the country in the <code>process_request</code> method.</li>
<li>After that your code should depend on the <code>country_context.get_current_country_code</code> to get the current country code, and that should be everywhere, so that you don’t have to pass the current country from the view to the controllers and to other parts of your code.</li>
<li>In the end when you finish processing the request you should deactivate the country, also you can do that in the middleware in the <code>process_response</code> method.</li>
</ol>
<p>If you want to create a middleware you can extend the <code>CountryContextMiddleware</code> included with this package.</p>
<h2 id="settings">Settings</h2>
<p>You should have the following two variables:</p>
<ol>
<li><code>DEFAULT_COUNTRY</code>: The default country code that will be the active country by default.</li>
<li><code>ENABLED_COUNTRIES</code>: A list of country codes that are enabled for your site. Codes are in <a href="http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2" target="_blank">ISO 3166-1 Alpha 2</a> format.</li>
</ol>
<h2 id="example-usage">Example Usage</h2>
<p>We will imagine a Django site, an e-commerce site that serves multiple stores in US and UK, by default it’ll be serving the US site, but if the URL was prefixed with UK then the site will serve the UK store.</p>
<pre class="lang:python decode:true"># site/settings.py
# ...
DEFAULT_COUNTRY = 'US'
ENABLED_COUNTRIES = ['US', 'UK']
# ...
MIDDLEWARE_CLASSES = (
  # ...
  'site.country_context_middleware.SiteCountryContextMiddleware',
  # ...
)
</pre>
<pre class="lang:python decode:true"># site/country_context_middleware.py
import re

from django_country_context.country_context_middleware import CountryContextMiddleware


class SiteCountryContextMiddleware(CountryContextMiddleware):
  def get_country_code_from_request(self, request):
    if re.match(r'^/UK/', request.path_info, re.I):
      return 'UK'
    return 'US'
</pre>
<pre class="lang:python decode:true"># site/urls.py

from django.contrib import admin
from django.conf import settings
from django.conf.urls import patterns, include, url

urlpatterns = patterns('',
  url(r'^(?:%s)?/' % '|'.join(
    ''.join(
      '[%s%s]' % (c.upper(), c.lower()) for c in country
    ) for country in settings.ENABLED_COUNTRIES
  ), include('app.urls')),
)
</pre>
<pre class="lang:python decode:true"># app/models.py

from django.db import models
from django_country_context import country_context, countries_data


class StoreManager(models.Manager):
  def __init__(self, countries_enabled=True):
    super(StoreManager, self).__init__()
    self.countries_enabled = countries_enabled

  def get_query_set(self):
    qs = super(StoreManager, self).get_query_set()
    if self.countries_enabled:
      qs = qs.filter(country=country_context.get_current_country_code())
    return qs


class Store(models.Model):
  # ...
  country = models.CharField(max_length=2, default=country_context.get_current_country_code, choices=countries_data.ENABLED_COUNTRIES_TUPLE, db_index=True)

  objects = StoreManager()
  objects_no_countries = StoreManager(countries_enabled=False)
</pre>
<pre class="lang:python decode:true"># app/admin.py

from django.contrib import admin
from models import Store


class StoreAdmin(admin.ModelAdmin):
  model = Store
  def queryset(self, request):
    self.model._default_manager = self.model.objects_no_countries
    return super(StoreAdmin, self).queryset(request)
  # ...

admin.site.register(Store, StoreAdmin)
</pre>
<p>Using the setup above will allow the views to call the query the Store model without handling special cases for countries, and you can change the logic of getting the current country without any change to your views, this way we’ve separated the country context completely from the logic of the site. And when you need to get the current country name or code you can use <code>country_context.get_current_country_name()</code> and <code>country_context.get_current_country_code()</code> respectively. Please note that the setup above was written for a Django 1.4.x.</p>
<h2 id="download">Download</h2>
<p><a href="https://github.com/mpcabd/django-country-context/">Django Country Context on source code on GitHub</a></p>]]></content:encoded>
    </item>
    <item>
      <title>How to make django management commands send errors email to admins</title>
      <link>https://mpcabd.xyz/make-django-management-commands-send-errors-email-admins/</link>
      <pubDate>Sun, 08 Dec 2013 13:15:42 +0000</pubDate>
      <guid>https://mpcabd.xyz/make-django-management-commands-send-errors-email-admins/</guid>
      <description>&lt;p&gt;I usually use django’s &lt;a title=&#34;Writing custom django-admin commands&#34; href=&#34;https://docs.djangoproject.com/en/dev/howto/custom-management-commands/&#34; target=&#34;_blank&#34;&gt;custom management commands&lt;/a&gt; to do different tasks on the web application, most of the times with a cron job running those commands. The problem is that when you’re using a cron job, you won’t get the beautiful django error email when something goes wrong.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>I usually use django’s <a title="Writing custom django-admin commands" href="https://docs.djangoproject.com/en/dev/howto/custom-management-commands/" target="_blank">custom management commands</a> to do different tasks on the web application, most of the times with a cron job running those commands. The problem is that when you’re using a cron job, you won’t get the beautiful django error email when something goes wrong.</p>
<p><a href="http://mpcabd.xyz/wp-content/uploads/2013/12/django-error-email.jpg" rel="lightbox[403]" title="How to make django management commands send errors email to admins"><img class="aligncenter size-medium wp-image-404" alt="Django's error email sample" src="http://mpcabd.xyz/wp-content/uploads/2013/12/django-error-email-300x207.jpg" width="300" height="207" srcset="https://mpcabd.xyz/wp-content/uploads/2013/12/django-error-email-300x207.jpg 300w, https://mpcabd.xyz/wp-content/uploads/2013/12/django-error-email.jpg 996w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<p>You can of course log all the commands you run and the cron jobs you have in files, but the problem is that sometimes you need to be notified instantly via your email, so here’s how to make django management commands send you the errors email.</p>
<h2 id="understanding-how-django8217s-error-email-works">Understanding how django’s error email works</h2>
<p>If you check django’s logging documentation you will find that it has a built-in handler called <a href="https://docs.djangoproject.com/en/dev/topics/logging/#django.utils.log.AdminEmailHandler" title="Django Logging AdminEmailHandler" target="_blank">AdminEmailHandler</a> this handler sends an email to the site admins for each log message it receives.</p>
<p>So basically all you need to do is to tell your django commands to log the errors using a logger with that handler, and you’ll receive the emails.</p>
<p>To do so define a logger in your <code>settings.py</code>:</p>
<pre class="lang:python decode:true">LOGGING = {
    #OTHER OPTIONS
    'filters': {
        #OTHER FILTERS
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        #OTHER HANDLERS
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler',
            'include_html': True
        }
    },
    'loggers': {
        #OTHER LOGGERS
        'management_commands': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}
</pre>
<p>And after that in your custom commands log the errors you face using the logger you defined:</p>
<pre class="lang:python decode:true">from django.utils.log import getLogger
from django.core.management.base import BaseCommand
import sys

logger = getLogger('management_commands')

class Command(BaseCommand):
    def handle(self, *args, **options):
        try:
            #DO YOUR STUFF HERE
        except Exception as e:
            logger.error('Admin Command Error: %s', ' '.join(sys.argv), exc_info=sys.exc_info())
            #Raise the exception again so it gets logged in standard error also.
            raise e
</pre>
<h2 id="enabling-the-logger-to-all-commands-in-one-configuration">Enabling the logger to all commands in one configuration</h2>
<p>You can also make all the commands (custom or not) send the error by email by editing <code>manage.py</code> almost the same way as we edited the command file above:</p>
<pre class="lang:python decode:true">from django.utils.log import getLogger
import sys

logger = getLogger('management_commands')

#Wrap this line with a try-catch execute_from_command_line(sys.argv)
    try:
        execute_from_command_line(sys.argv)
    except Exception as e:
        logger.error('Admin Command Error: %s', ' '.join(sys.argv), exc_info=sys.exc_info())
        raise e
</pre>
<p>This way all the commands will send the error by email also to django admins.</p>
<p>Enjoy it!</p>]]></content:encoded>
    </item>
    <item>
      <title>How to make logrotate use SSMTP</title>
      <link>https://mpcabd.xyz/make-logrotate-use-ssmtp/</link>
      <pubDate>Sun, 08 Dec 2013 12:25:41 +0000</pubDate>
      <guid>https://mpcabd.xyz/make-logrotate-use-ssmtp/</guid>
      <description>&lt;p&gt;A few days ago I was looking at my server logs, my website logs are more than a year old and growing, so I was reading some of them and wanted to download the old logs, truncate the logs, so that next time I read the logs I won’t have to look at very old data. So basically I wanted to rotate the logs and archive them, luckily &lt;a title=&#34;logrotate man page&#34; href=&#34;http://linuxcommand.org/man_pages/logrotate8.html&#34; target=&#34;_blank&#34;&gt;logrotate&lt;/a&gt; is there to let me manage and administer log files in my system. It has a long list of features with a very easy configuration, so it was the tool I’m looking for.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>A few days ago I was looking at my server logs, my website logs are more than a year old and growing, so I was reading some of them and wanted to download the old logs, truncate the logs, so that next time I read the logs I won’t have to look at very old data. So basically I wanted to rotate the logs and archive them, luckily <a title="logrotate man page" href="http://linuxcommand.org/man_pages/logrotate8.html" target="_blank">logrotate</a> is there to let me manage and administer log files in my system. It has a long list of features with a very easy configuration, so it was the tool I’m looking for.</p>
<p>logrotate uses the system’s mail <code>/bin/mail</code> to send the email when a log file is to be archived and removed from the system. But my system doesn’t use /bin/mail, it uses <a title="SSMTP man page" href="http://linux.die.net/man/8/ssmtp" target="_blank">SSMTP</a> with some custom configurations. I wanted to use SSMTP with logrotate but apparently it’s not a very simple task, since the man page for logrotate says:</p>
<blockquote>
<p>Option -m, –mail <command></p>
</blockquote>
<blockquote>
<p>Tells logrotate which command to use when mailing logs. This command should accept two arguments: <strong>1) the subject of the message, and 2) the recipient. The command must then read a message on standard input and mail it to the recipient.</strong> The default mail command is /bin/mail -s.</p>
</blockquote>
<p>Which is not actually how SSMT works, SSMTP as it’s described in the man page accepts the recipients emails as command line arguments, and reads the message (along with it’s subject header) from the standard input.</p>
<h2 id="the-shell-script">The shell script</h2>
<p>The solution to this problem would be by creating a shell script that behaves like a middleware between logrotate and SSMTP.</p>
<p>The shell script would simply read the arguments passed from logrotate and then build the right command to call SSMTP with by prepending the appropriate SMTP headers (To, Subject, From) to the message.</p>
<p>You can download the shell script from this link <a title="logrotate_smtp.sh Gist on GitHub" href="https://gist.github.com/mpcabd/03ce7d302eb4e1f5bfb7" target="_blank">logrotate_ssmtp.sh</a>.</p>
<p>As you can easily see that the shell script only accepts two arguments, so it sends the email to only one person, if you want to have more than one recipient and you’ve configured logrotate to send them the email, you’ll have to modify the script to accept more arguments and pass them to SSMTP.</p>
<p>Also you’ll have to replace <code>server@example.com</code> with the email address you’re sending from.</p>
<h2 id="configuring-logrotate">Configuring logrotate</h2>
<p>Now all we have to do is to configure logrotate to use the shell script as a mail command instead of /bin/mail. To do so you’ll have to edit all the calls that you make to logrotate to be like:</p>
<p><code>/usr/sbin/logrotate -m '~/logrotate_ssmtp.sh' /etc/logrotate.conf</code></p>
<p>The main call that you should change is located in <code>cron.daily</code> directory, I’m using Ubuntu so I have to edit this file <code>/etc/cron.daily/logrotate</code> and change the command at the end of the file to the command above.</p>
<p>Hope this helps you with your logs 🙂<figure style="width: 648px" class="wp-caption aligncenter"></p>
<p><img class="" alt="Logs Vancouver - photo by ahisgett on Flickr" src="http://images.cdn.fotopedia.com/flickr-220279395-original.jpg" width="648" height="972" /><figcaption class="wp-caption-text">photo by <a href="http://www.flickr.com/photos/37804979@N00" target="_blank">ahisgett</a> on Flickr</figcaption></figure></p>]]></content:encoded>
    </item>
    <item>
      <title>Adding a timestamp to command output in linux</title>
      <link>https://mpcabd.xyz/adding-a-timestamp-to-command-output-in-linux/</link>
      <pubDate>Wed, 13 Feb 2013 06:03:59 +0000</pubDate>
      <guid>https://mpcabd.xyz/adding-a-timestamp-to-command-output-in-linux/</guid>
      <description>&lt;p&gt;This is just a quick solution to put a timestamp with each line of the output of some command in Linux (*nix). It’s a very simple thing, thought I’d write it down here so maybe it’ll help somebody some day.&lt;/p&gt;
&lt;p&gt;I have a cron job running on my server, it’s a high frequency job so I don’t want to send email reports each time, I’m logging it into a file, but I want to log the timestamp of each time it runs and logs something to this file, I didn’t want to change the code behind it to also print the timestamp with each write to the output, so I pipelined the command to a simple bash script that will append the timestamp to each line in the output then write the result to the stdout again.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>This is just a quick solution to put a timestamp with each line of the output of some command in Linux (*nix). It’s a very simple thing, thought I’d write it down here so maybe it’ll help somebody some day.</p>
<p>I have a cron job running on my server, it’s a high frequency job so I don’t want to send email reports each time, I’m logging it into a file, but I want to log the timestamp of each time it runs and logs something to this file, I didn’t want to change the code behind it to also print the timestamp with each write to the output, so I pipelined the command to a simple bash script that will append the timestamp to each line in the output then write the result to the stdout again.</p>
<p>Here is the bash script:</p>
<pre class="lang:bash decode:true">#!/bin/bash
while read x; do
	echo -n `date +%d/%m/%Y\ %H:%M:%S`;
	echo -n " ";
	echo $x;
done
</pre>
<p>Then I edited the cron job line to be like this:</p>
<pre class="lang:bash decode:true">... /path/to/my/command.sh 2&gt;&1 | /path/to/timestap.sh &gt;&gt; /var/log/cron/my_log.log
</pre>
<p>And you’re done!</p>
<p>Enjoy it.</p>]]></content:encoded>
    </item>
    <item>
      <title>Google Talk Status Countdown</title>
      <link>https://mpcabd.xyz/google-talk-status-countdown/</link>
      <pubDate>Tue, 25 May 2010 19:46:21 +0000</pubDate>
      <guid>https://mpcabd.xyz/google-talk-status-countdown/</guid>
      <description>&lt;p&gt;A few days ago I was counting down to a presentation in my faculty. As I was setting counters all over my world (Side Bar Gadget, To Do List) I thought of a way to change my Google Talk status to a counter also.&lt;/p&gt;
&lt;p&gt;Since I know that Google Talk uses &lt;a href=&#34;http://www.xmpp.org&#34;&gt;XMPP&lt;/a&gt; protocol, and since my friends and I implemented XMPP last year in our faculty I tried to make a program to set my status to a counter; and here is the result:&lt;/p&gt;
&lt;p&gt;&lt;a href=&#34;http://mpcabd.xyz/wp-content/uploads/2010/05/XMPPStatusChanger.png&#34; rel=&#34;lightbox[231]&#34; title=&#34;XMPP Status Changer&#34;&gt;&lt;img src=&#34;http://mpcabd.xyz/wp-content/uploads/2010/05/XMPPStatusChanger-300x190.png&#34; alt=&#34;XMPP Status Changer&#34; title=&#34;XMPP Status Changer&#34; width=&#34;300&#34; height=&#34;190&#34; class=&#34;alignnone size-medium wp-image-234&#34; srcset=&#34;https://mpcabd.xyz/wp-content/uploads/2010/05/XMPPStatusChanger-300x190.png 300w, https://mpcabd.xyz/wp-content/uploads/2010/05/XMPPStatusChanger.png 484w&#34; sizes=&#34;(max-width: 300px) 100vw, 300px&#34; /&gt;&lt;/a&gt;&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>A few days ago I was counting down to a presentation in my faculty. As I was setting counters all over my world (Side Bar Gadget, To Do List) I thought of a way to change my Google Talk status to a counter also.</p>
<p>Since I know that Google Talk uses <a href="http://www.xmpp.org">XMPP</a> protocol, and since my friends and I implemented XMPP last year in our faculty I tried to make a program to set my status to a counter; and here is the result:</p>
<p><a href="http://mpcabd.xyz/wp-content/uploads/2010/05/XMPPStatusChanger.png" rel="lightbox[231]" title="XMPP Status Changer"><img src="http://mpcabd.xyz/wp-content/uploads/2010/05/XMPPStatusChanger-300x190.png" alt="XMPP Status Changer" title="XMPP Status Changer" width="300" height="190" class="alignnone size-medium wp-image-234" srcset="https://mpcabd.xyz/wp-content/uploads/2010/05/XMPPStatusChanger-300x190.png 300w, https://mpcabd.xyz/wp-content/uploads/2010/05/XMPPStatusChanger.png 484w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<h1 id="the-basic-idea-behind-status-changing">The basic idea behind status changing</h1>
<p>Since Google Talk uses <a href="http://www.xmpp.org">XMPP</a> then if you can connect using an XMPP client to your Google account you can use the client instead of Google talk. But indeed that’s not what we want here, we want to use Google Talk while changing the status automatically.</p>
<p>I searched to see if there were an API to communicate with Google Talk from any other program but I had no luck.</p>
<p>So the solution was to use XMPP’s Presence Priority attribute.</p>
<p>In <a href="http://www.xmpp.org">XMPP</a>, a user can connect from multiple clients with the same ID, each client will have a unique `resource` so messages sent from one client get their replies to the same client. But what about status? XMPP has an attribute sent with each status (Status is called Presence in XMPP) which is `Priority`, this attribute describes the priority of this resource presence. In Google Talk the highest priority is 24. So if you can change the priority of the automatic presence to 24 it will be considered high priority and its status will appear instead of the old one.</p>
<h1 id="programming-it">Programming it</h1>
<p>I used Java for developing the program. There is no direct reason for using Java but that’s what I used 🙂</p>
<p>To be able to use XMPP I used the <a href="http://www.igniterealtime.org/downloads/index.jsp">Smack XMPP Library</a> because it is simple and serves me well.</p>
<p>The whole mechanism is too simple:</p>
<ol>
<li>Login.</li>
<li>Calculate difference between now and the targeted date.</li>
<li>Send the presence.</li>
</ol>
<p>Using Smack makes the whole process so easy.</p>
<h2 id="login">Login</h2>
<pre class="lang:java decode:true">import org.jivesoftware.smack.XMPPConnection;

public void connect() {
    XMPPConnection connection = new XMPPConnection(server); //Server is gmail.com for Google Talk.
    connection.connect();
    connection.login(username, password); //Username and password.
}
</pre>
<h2 id="calculate-difference-between-now-and-the-targeted-date">Calculate difference between now and the targeted date</h2>
<p>This process is done using Java Calendar and Date objects:</p>
<pre class="lang:java decode:true">import java.util.Calendar;
import java.util.Date;

{
        Calendar calendar1 = Calendar.getInstance();
        Date d = new Date();
        calendar1.setTime(d);

        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(endLine); //End line is the date we're counting to.

        long milliseconds1 = calendar1.getTimeInMillis();
        long milliseconds2 = calendar2.getTimeInMillis();
        long diff = milliseconds2 - milliseconds1;

        long diffDays = diff / (24 * 60 * 60 * 1000);
        diff = diff % (24 * 60 * 60 * 1000);

        long diffHours = diff / (60 * 60 * 1000);
        diff = diff % (60 * 60 * 1000);

        long diffMinutes = diff / (60 * 1000);
        diff = diff % (60 * 1000);
}
</pre>
<p>This code calculates the difference between the two dates in days, hours and minutes.</p>
<h2 id="send-the-presence">Send the presence</h2>
<p>After calculating the difference all we have to do is to send the presence:</p>
<pre class="lang:java decode:true">import org.jivesoftware.smack.packet.Presence;

{
         String remaining = Long.toString(diffDays) + " day(s), " + Long.toString(diffHours) + " hour(s), " + Long.toString(diffMinutes) + " minute(s) " + message; //Message is usually: Until "something".

        Presence presence = new Presence(Presence.Type.available);
        presence.setStatus(remaining);
        presence.setPriority(24); //Highest priority in Google Talk
        presence.setMode(presenceMode); //This is one of XMPP modes (Available, Chat, DND, Away, XA).
        connection.sendPacket(presence);
}
</pre>
<p>After this point people will see your new status instead of the one in Google Talk. (Notice that you won’t be able to see the change inside Google Talk but rest assured it is changed ;)).</p>
<h1 id="testing">Testing</h1>
<p><a href="http://mpcabd.xyz/wp-content/uploads/2010/05/XMPPStatusChanger2.png" rel="lightbox[231]" title="XMPP Status Changer Test"><img src="http://mpcabd.xyz/wp-content/uploads/2010/05/XMPPStatusChanger2-300x127.png" alt="XMPP Status Changer Test" title="XMPP Status Changer Test" width="300" height="127" class="alignnone size-medium wp-image-242" srcset="https://mpcabd.xyz/wp-content/uploads/2010/05/XMPPStatusChanger2-300x127.png 300w, https://mpcabd.xyz/wp-content/uploads/2010/05/XMPPStatusChanger2.png 493w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<h1 id="last-note">Last note</h1>
<p>The GUI is self explanatory, just make sure you enter a big value for “Update Interval” because when you’re talking to others and your status changes they’ll have a red line with the new status in the conversation window and certainly you don’t want them to be distracted by the counter from the real conversation.</p>
<p>And BTW, you can use this program with any XMPP account, not just Google Talk. And it’s cross platform 😉</p>
<h1 id="download">Download</h1>
<p>Google Talk Status Countdown on <a href="https://github.com/mpcabd/gtalk-status-countdown">GitHub</a></p>
<p>Smack library is attached to the files already, no need to download it separately.</p>
<ul>
<li><a href="https://github.com/mpcabd/gtalk-status-countdown/tarball/master">Source Code</a></li>
<li><a href="https://github.com/downloads/mpcabd/gtalk-status-countdown/statusChangerExecutable.tar.gz">Executable Jar File</a></li>
</ul>
<p>Hope you use it 🙂</p>]]></content:encoded>
    </item>
    <item>
      <title>Display Sub-terms In Drupal Term Page</title>
      <link>https://mpcabd.xyz/display-sub-terms-in-drupal-term-page/</link>
      <pubDate>Tue, 30 Mar 2010 22:06:42 +0000</pubDate>
      <guid>https://mpcabd.xyz/display-sub-terms-in-drupal-term-page/</guid>
      <description>&lt;p&gt;After working with Drupal in the last two months I’ve really got used to searching for modules for every problem I face and installing them.&lt;/p&gt;
&lt;p&gt;While I was working on &lt;a href=&#34;http://www.communityi.net&#34;&gt;iCommunity website&lt;/a&gt;, I was creating taxonomy terms to categorize the files using them. I created terms with sub terms. The problem was that when browsing a specified term the term page doesn’t display the sub terms of that term.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>After working with Drupal in the last two months I’ve really got used to searching for modules for every problem I face and installing them.</p>
<p>While I was working on <a href="http://www.communityi.net">iCommunity website</a>, I was creating taxonomy terms to categorize the files using them. I created terms with sub terms. The problem was that when browsing a specified term the term page doesn’t display the sub terms of that term.</p>
<p>I searched the internet and found <a href="http://www.rbgrn.net/content/194-drupal-taxonomy-how-to-add-list-clickable-sub-categories">a solution</a> that’s working.</p>
<p>After trying it I decided to try developing a module for doing that (just like the author of the solution suggested).</p>
<p>I’m a newbie in developing for Drupal but I knew how to dig my way through it 😀</p>
<p>(You’d be shocked if you knew that I don’t know PHP 😛 I just write code!)</p>
<p>So before I start this post please this is the first time I write modules, and I learned it yesterday 😛 so if you find any error or something wrong tell me 🙂</p>
<p>I named the module Taxonomy subterms. 😀</p>
<p>So the process is just re-implement the function <em>‘theme_taxonomy_term_page’</em> from taxonomy module, but to override it I needed to let Drupal call the function in my module when the user requests <em>‘/taxonomy/term/’</em> so to do that I needed to add the <em>‘hook_menu’</em> function.</p>
<pre class="lang:php decode:1">function taxonomy_subterms_menu() {  
  $items['taxonomy/term/%'] = array(
    'title' =&gt; 'Taxonomy term',
    'page callback' =&gt; 'taxonomy_subterms_term_page',
    'page arguments' =&gt; array(2),
    'access arguments' =&gt; array('access content'),
    'type' =&gt; MENU_CALLBACK,
  );
  
  return $items;
}
</pre>
<p>But by doing this I discovered that the Taxonomy module won’t handle the page, so I couldn’t find a way to tell Taxonomy module to handle the page and my module to complete the handling 🙁 So I copied the ‘taxonomy_term_page’ function and renamed it to ‘taxonomy_subterms_term_page’</p>
<p>Then I re-implemented the ‘theme_taxonomy_term_page’ function so I can add the sub-terms section (just like the solution I mentioned did):</p>
<pre class="lang:php decode:1">function theme_taxonomy_term_page($tids, $result) {
  drupal_add_css(drupal_get_path('module', 'taxonomy') . '/taxonomy.css');
  drupal_add_css(drupal_get_path('module', 'taxonomy_subterms') . '/taxonomy_subterms.css');
  $output = '';

  // Only display the description if we have a single term, to avoid clutter and confusion.
  if (count($tids) == 1) {
    $term = taxonomy_get_term($tids[0]);
    $children = taxonomy_get_children($tids[0]);
    $description = $term-&gt;description;
    if (!empty($description) || sizeof($children) &gt; 0) {
      $output .= '&lt;div class="taxonomy-details-wrapper"&gt;';
      $is_wrapped = true;
    } else {
      $is_wrapped = false;
    }
    // Check that a description is set.
    if (!empty($description)) {
      $output .= '&lt;div class="taxonomy-term-description"&gt;';
      $output .= filter_xss_admin($description);
      $output .= '&lt;/div&gt;';
    }
    if (sizeof($children) &gt; 0) {
      $output .= '&lt;div class="sub-terms-list"&gt;&lt;h3&gt;' . t('Sub-Terms:') . '&lt;/h3&gt; &lt;ul class="sub-terms inline"&gt;';
      foreach($children as $child) {
        $output .= '&lt;li&gt;' . l($child-&gt;name, taxonomy_term_path($child)) . '&lt;/li&gt;';
      }
      $output .= '&lt;/ul&gt;&lt;/div&gt;';
    }
    if ($is_wrapped) {
      $output .= '&lt;/div&gt;';
    }
  }

  $output .= taxonomy_render_nodes($result);

  return $output;
}
</pre>
<p>Then I had my module working and installed it in the website (you can check it out <a href="http://www.communityi.net/taxonomy/term/3">here</a>. The page is in Arabic but you can easily find the sub terms).</p>
<h2 id="download">Download</h2>
<p>You can download the module <a href="http://www.box.net/shared/hzahnghh6x">here</a> (I didn’t maintain a project @ Drupal because I’m not yet ready to do that, this is just a small experiment).</p>]]></content:encoded>
    </item>
    <item>
      <title>Simple AJAX Comment Preview in Drupal 6</title>
      <link>https://mpcabd.xyz/simple-ajax-comment-preview-in-drupal-6/</link>
      <pubDate>Mon, 15 Feb 2010 15:15:48 +0000</pubDate>
      <guid>https://mpcabd.xyz/simple-ajax-comment-preview-in-drupal-6/</guid>
      <description>&lt;p&gt;As I said in my previous post, I’m working on upgrading &lt;a href=&#34;http://www.csc-sy.net&#34;&gt;Computer Science in Syria&lt;/a&gt; website to Drupal 6.&lt;/p&gt;
&lt;p&gt;I wanted also to have AJAX comment preview in nodes, but I wanted it to be simple without lots of JavaScript loaded. So as usual I got pissed off and decided to create my own code to do it. 8)&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>As I said in my previous post, I’m working on upgrading <a href="http://www.csc-sy.net">Computer Science in Syria</a> website to Drupal 6.</p>
<p>I wanted also to have AJAX comment preview in nodes, but I wanted it to be simple without lots of JavaScript loaded. So as usual I got pissed off and decided to create my own code to do it. 8)</p>
<p>I used <a href="http://www.ericmmartin.com/projects/simplemodal/">Simple Modal</a> by Eric Martin to display the preview in a model instead of a new page.</p>
<p>The code is easy too like the previous post’s code, I edited also the drupal.js file and added the following code:</p>
<pre class="lang:javascript decode:true">if (location.pathname.match('^' + Drupal.settings.basePath + 'node/\\d')) {
		$('#edit-preview').click(function () {
			$.modal('&lt;div&gt;&lt;h1&gt;Preview&lt;/h1&gt;&lt;div id="previewContent"&gt;&lt;img style="width: 126px; height: 22px;" class="previewing" src="' + Drupal.settings.basePath + 'misc/previewing.gif" alt="Loading ..." /&gt;&lt;/div&gt;&lt;/div&gt;');
			var comment = $('#edit-comment').val();
			if ($('#wysiwyg-toggle-edit-comment').text() == Drupal.settings.wysiwyg.disable) {
				$('#wysiwyg-toggle-edit-comment').click();
				comment = $('#edit-comment').val();
				$('#wysiwyg-toggle-edit-comment').click();
			}
			$.post(
				$('form#comment-form').attr('action'),
				{
					'comment' : comment,
					'form_build_id' : $('form#comment-form input[name="form_build_id"]').val(),
					'form_id' : 'comment_form',
					'form_token' : $('form#comment-form input[name="form_token"]').val(),
					'op' : $('form#comment-form input#edit-preview').val(),
				},
				function (html) {
					$('div#previewContent img').remove();
					$('div#previewContent').append($(html).children().find('div.preview div.content').html());
					$('form#comment-form input[name="form_token"]').val($(html).children().find('form#comment-form input[name="form_token"]').val());
					$('form#comment-form input[name="form_build_id"]').val($(html).children().find('form#comment-form input[name="form_build_id"]').val());
				}
			);
			return false;
		});
	}
</pre>
<p>The process is too simple:</p>
<ol>
<li>@line 01: I check to see if the current page is a node page, I just want to make the preview code working on node page.</li>
<li>@line 03: I show the user a modal with a loading image <img alt="Loading &hellip;" loading="lazy" src="http://www.csc-sy.net/misc/previewing.gif"></li>
<li>@lines 04~09: I check the editor, if it is enabled I disable it to get the HTML from the comment. If it is not enabled I get the HTML directly without disabling it.</li>
<li>@lines 10~18: I gather the data of the form and post them.</li>
<li>@line 20: I remove the loading image.</li>
<li>@line 21: I append the HTML data from the response to the modal content.</li>
<li>@lines 22~23: I set the form hidden values (form_build_id and form_token) to the values from the response so I don’t get a Validation Error.</li>
<li>@line 26: I return false so the browser doesn’t post the data again to the new page.</li>
</ol>
<p>Here is an example:</p>
<p><a href="http://mpcabd.xyz/wp-content/uploads/2010/02/1.png" rel="lightbox[207]" title="1"><img src="http://mpcabd.xyz/wp-content/uploads/2010/02/1-300x138.png" alt="" title="1" width="300" height="138" class="alignnone size-medium wp-image-211" srcset="https://mpcabd.xyz/wp-content/uploads/2010/02/1-300x138.png 300w, https://mpcabd.xyz/wp-content/uploads/2010/02/1.png 668w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<p><a href="http://mpcabd.xyz/wp-content/uploads/2010/02/2.png" rel="lightbox[207]" title="2"><img src="http://mpcabd.xyz/wp-content/uploads/2010/02/2-300x138.png" alt="" title="2" width="300" height="138" class="alignnone size-medium wp-image-211" /></a></p>
<p>Simple 😉</p>]]></content:encoded>
    </item>
    <item>
      <title>Simple AJAX Quote in Drupal 6</title>
      <link>https://mpcabd.xyz/simple-ajax-quote-in-drupal-6/</link>
      <pubDate>Fri, 12 Feb 2010 23:02:34 +0000</pubDate>
      <guid>https://mpcabd.xyz/simple-ajax-quote-in-drupal-6/</guid>
      <description>&lt;p&gt;I’ve been upgrading the forum of &lt;a href=&#34;http://www.csc-sy.net/&#34; target=&#34;_blank&#34;&gt;Computer Science in Syria&lt;/a&gt; for a week now.&lt;/p&gt;
&lt;p&gt;The forum uses Drupal, and it ran a beta version of Drupal 4, and I upgraded it to the latest Drupal version now.&lt;/p&gt;
&lt;p&gt;I wanted to have AJAX quoting in the forum, but I wanted it to be simple without lots of JavaScript loaded. So as usual I got pissed off and decided to create my own code to do it. 8)&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>I’ve been upgrading the forum of <a href="http://www.csc-sy.net/" target="_blank">Computer Science in Syria</a> for a week now.</p>
<p>The forum uses Drupal, and it ran a beta version of Drupal 4, and I upgraded it to the latest Drupal version now.</p>
<p>I wanted to have AJAX quoting in the forum, but I wanted it to be simple without lots of JavaScript loaded. So as usual I got pissed off and decided to create my own code to do it. 8)</p>
<p>The code was very simple, knowing that the Quote link will get you to a page where the textarea has the quoted text, and knowing that Drupal 6 has <a href="http://jquery.com/">jQuery</a> loaded in it 🙂</p>
<p>I added the following code to /misc/drupal.js file:</p>
<pre class="lang:javascript decode:true">$('a.quote, li.quote a').click(function () {
	$(this).after($('&nbsp;&lt;img style="width: 16px; height: 16px;" class="quoting" src="/misc/quoting.gif" alt="loading" /&gt;'));
	$.ajax({
		url: $(this).attr('href'),
		cache: false,
		success: function(html){
			$('img.quoting').remove();
			var changed = false;
			if ($('#wysiwyg-toggle-edit-comment').text() == Drupal.settings.wysiwyg.disable) {
				$('#wysiwyg-toggle-edit-comment').click();
				changed = true;
			}
			$('#edit-comment').val($('#edit-comment').val() + ($('#edit-comment').val() == '' ? '' : '\n') + $(html).children().find('#edit-comment').val());
			var $target = $('#edit-comment');
			$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
			if ($target.length) {
					var targetOffset = $target.offset().top;
					$('html,body').animate({scrollTop: targetOffset}, 1000);
			}
			if (changed)
				$('#wysiwyg-toggle-edit-comment').click();
			$('#edit-comment').scrollTop($('#edit-comment')[0].scrollHeight);
		}
	});
	return false;
});
</pre>
<p>You can see that I used this image to be displayed while loading the quote into the textarea  <img alt="Quoting" loading="lazy" src="http://www.csc-sy.net/misc/quoting.gif">because it matches the colors of the forum style.</p>
<p>The process is too simple:</p>
<ol>
<li>@line 02: Display a loading image.</li>
<li>@line 03: Request the quoting page which is located in the href attribute of the quote link.</li>
<li>@line 07: Remove the image.</li>
<li>@lines 08 ~ 12: Checking if the HTML editor is enabled, and disabling it so I can assign the value directly to the textarea.</li>
<li>@line 13: Assigning the value of the textarea in the quote page to the textarea in this page.</li>
<li>@lines 14 ~ 19: Scrolling the page’s vertical scroll to reach the textarea.</li>
<li>@lines 20 ~ 21: Re-enabling the editor if I disabled it.</li>
<li>@line 22: Scrolling the textarea’s vertical scroll to reach the end of the text.</li>
<li>@line 25: Returning false to the browser so it doesn’t redirect the page to the quoting page.</li>
</ol>
<p>You see? it is as simple as this 🙂</p>
<p>I’ll soon post some other modifications that made the forum more simple 🙂</p>]]></content:encoded>
    </item>
    <item>
      <title>Notepad&#43;&#43; Plugin To Run Python Scripts</title>
      <link>https://mpcabd.xyz/notepad-plugin-to-run-python-scripts/</link>
      <pubDate>Tue, 03 Nov 2009 20:25:44 +0000</pubDate>
      <guid>https://mpcabd.xyz/notepad-plugin-to-run-python-scripts/</guid>
      <description>&lt;p&gt;I use Python everyday, it has become my first tool to use when I need to do anything. In Arabic (in &lt;a href=&#34;http://en.wikipedia.org/wiki/Syria&#34; target=&#34;_blank&#34;&gt;Syrian&lt;/a&gt; Arabic specifically) I’d say that Python has become my hand and leg 😛&lt;/p&gt;
&lt;p&gt;Yesterday I was writing a small Python script to read the YACC file and generate a list of all the specified rules inside it, so I don’t have to scroll through the long file to find out what rules are inside it 😉&lt;/p&gt;
&lt;p&gt;I use Notepad++ as my default text editor on Windows, and I was writing the script using it – Notepad++. I wanted to test if the script is working, so I ran an instance of Command Line Prompt, and as I was going to change the directory to the directory of the script I thought; “Why doesn’t Notepad++ have a &lt;em&gt;Run In Python&lt;/em&gt; command in it?”. So as usual I got pissed off and decided to create my own plugin to have that command in Notepad++ 8)&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>I use Python everyday, it has become my first tool to use when I need to do anything. In Arabic (in <a href="http://en.wikipedia.org/wiki/Syria" target="_blank">Syrian</a> Arabic specifically) I’d say that Python has become my hand and leg 😛</p>
<p>Yesterday I was writing a small Python script to read the YACC file and generate a list of all the specified rules inside it, so I don’t have to scroll through the long file to find out what rules are inside it 😉</p>
<p>I use Notepad++ as my default text editor on Windows, and I was writing the script using it – Notepad++. I wanted to test if the script is working, so I ran an instance of Command Line Prompt, and as I was going to change the directory to the directory of the script I thought; “Why doesn’t Notepad++ have a <em>Run In Python</em> command in it?”. So as usual I got pissed off and decided to create my own plugin to have that command in Notepad++ 8)</p>
<h3 id="the-reference">The Reference</h3>
<p>I searched on the net, I found this <a href="http://sourceforge.net/projects/notepad-plus/forums/forum/482781/topic/3393597" target="_blank">Notepad++ Plugin Template</a>, I edited it a little bit and I managed to do it 🙂</p>
<p>You can read below about the process and how it works, but if you just came here to <a href="#download">download it click here</a>.</p>
<h3 id="the-process">The Process</h3>
<p>To run a Python script; the plugin must do the following:</p>
<ul>
<li>Get the path of the selected file in Notepad++.</li>
<li>Get the path of Python executable file, since not everyone has Python in the PATH environment variable.</li>
<li>Building the run command.</li>
<li>Execute the run command.</li>
</ul>
<h3 id="get-the-path-of-the-selected-file-in-notepad">Get The Path of The Selected File In Notepad++</h3>
<p>I also searched the net and found the following code:</p>
<pre class="lang:c++ decode:true">std::wstring getCurrentFile(bool &ok)
{
	LRESULT result = ::SendMessage(nppData._nppHandle, NPPM_SAVECURRENTFILE, 0, 0);
	TCHAR path[MAX_PATH];
	::SendMessage(nppData._nppHandle, NPPM_GETFULLCURRENTPATH, MAX_PATH, (LPARAM)path);
	std::wstring wPath(path);
	if (result == 0) {
		ok = false;
		for (int i = 0; i &lt; wPath.length() && !ok; i++)
			if (wPath[i] == '\\')
				ok = true;
	}
	else
		ok = true;
	return wPath;
}
</pre>
<p>The function sends a message to Notepad++ asking it to save the file before trying to run it, the result of the message will be either 1 which means that the file was saved, or 0 which means that the file wasn’t.</p>
<p>Then the function sends a message to Notepad++ asking it to put the full path of the currently selected file into a specific variable.</p>
<p>Now a little problem occurs when the file is unmodified, and the problem is that the first message will return 0 which means that the file wasn’t saved, while the second message will return a valid file path. So the function will search the path for a backslash `` which is the path separator in Windows, because a valid full path must contain at least one separator.</p>
<p>When the path is valid and the file is saved the function returns the path and sets the `ok` parameter to true, while in other cases it will return the path and set `ok` parameter to false.</p>
<h3 id="get-the-path-of-python-executable-file">Get The Path Of Python Executable File</h3>
<p>The plugin will search for Python in its default path (“C:\Python[VER]”). If this method fails the plugin will search in registry for the key.</p>
<pre class="lang:c++ decode:true">bool pythonExists(std::wstring foldername) {
	std::wstring path = L"C:\\";
	path += foldername;
	path += L"\\python.exe";
	WIN32_FIND_DATA data;
	HANDLE h = FindFirstFile(const_cast&lt;LPCWSTR&gt;(path.c_str()), &data);
	return (h != INVALID_HANDLE_VALUE);
}

	//This code will be run before the plugin calls the function 'getPythonLocation'
	std::wstring pythonLoc = L"";
	bool pythonInstalled = false;

	WIN32_FIND_DATA data;
	HANDLE h = FindFirstFile(L"c:\\python*", &data);
	if( h != INVALID_HANDLE_VALUE ) 
	{
		do 
		{
			if (!(data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
				continue;

			char*   nPtr = new char [lstrlen( data.cFileName ) + 1];
			for( int i = 0; i &lt; lstrlen( data.cFileName ); i++ )
				nPtr[i] = char( data.cFileName[i] );

			nPtr[lstrlen( data.cFileName )] = '&#92;&#48;';
			if (pythonExists(const_cast&lt;LPWSTR&gt;(data.cFileName)))
			{
				pythonLoc = L"C:\\";
				pythonLoc += const_cast&lt;LPWSTR&gt;(data.cFileName);
				pythonLoc += L"\\";
				pythonInstalled = true;
				break;
			}
		} while (FindNextFile(h, &data));
	}
</pre>
<p>The Python installation path exists in the Windows Registry, so I wrote a small function to search the registry for the path and return it:</p>
<pre class="lang:c++ decode:true">bool getPythonLocationFromRegistry(std::wstring &loc, HKEY baseKey) {
{
	HKEY hKey;
	if(RegOpenKeyEx(baseKey, TEXT("Software\\Python\\PythonCore"), 0,
		KEY_READ, &hKey) != ERROR_SUCCESS)
	{
		return false;
	}
	DWORD dwIdx=0;
	TCHAR szKeyName[1024];
	DWORD dwSize=1024;
	FILETIME fTime;
	TCHAR pyPath[MAX_PATH];
	DWORD length = MAX_PATH;

	if (RegEnumKeyEx(hKey, dwIdx, szKeyName, &dwSize, NULL, NULL, NULL, &fTime) == ERROR_SUCCESS)
	{
		HKEY hSubKey;
		if (RegOpenKeyEx(hKey, szKeyName, 0, KEY_READ, &hSubKey) == ERROR_SUCCESS)
		{
			LONG x = RegOpenKeyEx(hSubKey, TEXT("InstallPath"), 0, KEY_READ, &hSubKey);
			if (x == ERROR_SUCCESS)
			{
				if(RegQueryValueEx(
					hSubKey,
					TEXT(""),
					NULL,
					NULL,
					(LPBYTE)pyPath,
					&length) != ERROR_SUCCESS)
				{
					return false;
				}

				loc = loc.append(pyPath);
				return true;
			}
			else
				return false;
		}
		else
			return false;
	}
	else
		return false;
}
</pre>
<p>The code above accepts the root key as a parameter, and the code that calls it will call it twice, once with <code>HKEY_CURRENT_USER</code> and the other with <code>HKEY_LOCAL_MACHINE</code>, so it will try to find it in both locations <code>HKEY_CURRENT_USER\Software\Python\PythonCore</code> and <code>HKEY_LOCAL_MACHINE\Software\Python\PythonCore</code>.</p>
<h3 id="building-the-run-command">Building The Run Command</h3>
<p>The plugin allows the user to choose to run the file in interactive mode, so the window won’t disappear after the program is done. I’ve also added another thing, that is the ability to run the file in pythonw.exe instead of python.exe, and that’s for applications with GUI, so you don’t have to see a console window behind your application GUI 😉</p>
<p>This one would be very simple, just concatenate: Python installation path, “python.exe” and the full path of the current file.</p>
<pre class="lang:c++ decode:true">std::wstring buildRunCommand(std::wstring &filePath, std::wstring &pypath, bool isW = false, bool isI = false)
{
	std::wstring command = pypath;
	command += TEXT("python");
	if (isW)
		command += TEXT("w");
	command += TEXT(".exe ");
	if (isI)
		command += TEXT("-i ");
	command += TEXT("\"");
	command += filePath;
	command += TEXT("\"");
	return command;
}
</pre>
<h3 id="execute-the-run-command">Execute The Run Command</h3>
<p>This function accepts a path parameter so it will run the process in the specified path (which is the path of the folder that includes the Python file to run) instead of the default path, this allows applications reading/writing files inside the same folder (or a relative path) of the application path to find those files.</p>
<p>This one is also simple, just create a new process with the run command.</p>
<pre class="lang:c++ decode:true">bool launchPython(std::wstring &command, std::wstring &path)
{
	STARTUPINFOW si;
	PROCESS_INFORMATION pi;
	memset(&si, 0, sizeof(si));
	memset(&pi, 0, sizeof(pi));
	si.cb = sizeof(si);

	return CreateProcess(
		NULL,
		const_cast&lt;LPWSTR&gt;(command.c_str()),
		NULL,
		NULL,
		FALSE,
		CREATE_DEFAULT_ERROR_MODE,
		NULL,
		path.c_str(),
		&si,
		&pi) != 0;
}
</pre>
<h3 id="screenshot">Screenshot</h3>
<p><a href="http://mpcabd.xyz/wp-content/uploads/2009/11/PyNPP.png" rel="lightbox[185]" title="PyNPP Notepad++ Plugin Screenshot"><img src="http://mpcabd.xyz/wp-content/uploads/2009/11/PyNPP-300x149.png" alt="PyNPP Notepad++ Plugin Screenshot" title="PyNPP Notepad++ Plugin Screenshot" width="300" height="149" class="aligncenter size-medium wp-image-306" srcset="https://mpcabd.xyz/wp-content/uploads/2009/11/PyNPP-300x149.png 300w, https://mpcabd.xyz/wp-content/uploads/2009/11/PyNPP.png 788w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<h3 style="text-align:left;">
  License
</h3>
<p>This work is licensed under <a href="http://www.gnu.org/licenses/gpl.html" target="_blank">GNU General Public License v3</a>.</p>
<h3 style="text-align:left;" id="download">
  Download
</h3>
<h4 id="pynpp-v12-on-github">PyNPP v1.2 on GitHub</h4>
<p><a href='https://github.com/mpcabd/PyNPP' target='_blank'>GitHub</a></p>
<h4 id="plugin-dll">Plugin DLL:</h4>
<p><a href='https://github.com/mpcabd/PyNPP/releases/download/v1.2/PyNPP.dll' target="_blank">Plugin DLL</a></p>
<h4 id="source-code">Source Code</h4>
<p><a href="https://github.com/mpcabd/PyNPP/archive/v1.2.tar.gz" target="_blank">Source Code</a></p>
<hr>
<h4 id="update-history">Update History</h4>
<ul>
<li>18, April 2010: PyNPP will search for Python in its default path <code>C:\Python[VER]\</code>.</li>
<li>13, December 2010: PyNPP will allow the user to run the file in three modes: normal, interactive and GUI. As suggested by Andrew <a href="http://mpcabd.xyz/notepad-plugin-to-run-python-scripts/comment-page-1/#comment-3433">here</a>.</li>
<li>13, December 2010: PyNPP will run the file in its folder, so it can read/write files next to it. As suggested by Andrew <a href="http://mpcabd.xyz/notepad-plugin-to-run-python-scripts/comment-page-1/#comment-3433">here</a>.</li>
<li>03, January 2011: PyNPP will search for Python in both <code>HKEY_CURRENT_USER\Software\Python\PythonCore</code> and <code>HKEY_LOCAL_MACHINE\Software\Python\PythonCore</code>.</li>
<li>05, January 2011: PyNPP will save the file before trying to run it.<br>
Fixed a bug in setting the current folder while running the process.</li>
<li>12, August 2011: PyNPP allows you to select the Python folder using an options dialog. As suggested by Hönes <a href="http://mpcabd.xyz/notepad-plugin-to-run-python-scripts/comment-page-1/#comment-5616">here</a>.
<ul>
<li>21, December 2011: PyNPP moved to GitHub.</li>
<li>27, April 2014: v1.1 released, PyNPP kills the Python instance it launches when the file is re-run. As suggested by Michał Kłopot.</li>
<li>30, March 2015: v1.2 released, PyNPP supports debugging the file with PDB. As suggested by fdufnews.</ul></li>
</ul>
</li>
</ul>]]></content:encoded>
    </item>
    <item>
      <title>Brainfuck Python Interpreter</title>
      <link>https://mpcabd.xyz/brainfuck-python-interpreter/</link>
      <pubDate>Mon, 19 Oct 2009 22:31:17 +0000</pubDate>
      <guid>https://mpcabd.xyz/brainfuck-python-interpreter/</guid>
      <description>&lt;h1 id=&#34;what-is-brainfuck&#34;&gt;What is brainfuck?&lt;/h1&gt;
&lt;p&gt;Brainfuck is a programming language&lt;img loading=&#34;lazy&#34; src=&#34;http://www.zu14.cn/coolemotion/emotions/zz_8.gif&#34;&gt;&lt;/p&gt;
&lt;p&gt;This is the definition from &lt;a href=&#34;http://en.wikipedia.org/wiki/Brainfuck&#34; target=&#34;_blank&#34;&gt;Wikipedia&lt;/a&gt;:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The &lt;strong&gt;brainfuck&lt;/strong&gt; programming language is an &lt;a href=&#34;http://en.wikipedia.org/wiki/Esoteric_programming_language&#34;&gt;esoteric programming language&lt;/a&gt; noted for its extreme minimalism. It is a &lt;a href=&#34;http://en.wikipedia.org/wiki/Turing_tarpit&#34;&gt;Turing tarpit&lt;/a&gt;, designed to challenge and amuse &lt;a href=&#34;http://en.wikipedia.org/wiki/Programmer&#34;&gt;programmers&lt;/a&gt;, and is not suitable for practical use. Its name has been variously &lt;a href=&#34;http://en.wikipedia.org/wiki/Expurgation&#34;&gt;bowdlerized&lt;/a&gt;. The name of the language is generally not capitalized, although it is a &lt;a href=&#34;http://en.wikipedia.org/wiki/Proper_noun&#34;&gt;proper noun&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;This programming language is very easy to learn, very hard to do work with. As the &lt;a href=&#34;http://en.wikipedia.org/wiki/Brainfuck&#34; target=&#34;_blank&#34;&gt;Wikipedia article&lt;/a&gt; describes it; the language is an esoteric language, which means it was created for fun &lt;img loading=&#34;lazy&#34; src=&#34;http://www.zu14.cn/coolemotion/emotions/zz_14.gif&#34;&gt;&lt;/p&gt;
&lt;p&gt;I discovered the language while I was reading an article about &lt;a href=&#34;http://blog.damonjablons.com/2009/10/15/the-perfect-django-settings-file/&#34; target=&#34;_blank&#34;&gt;writing the perfect settings file for Django&lt;/a&gt;. The author used &lt;a href=&#34;http://dpaste.com/&#34; target=&#34;_blank&#34;&gt;DPaste&lt;/a&gt; website to link to pieces of code. DPaste website says that it uses &lt;a href=&#34;http://pygments.org/&#34; target=&#34;_blank&#34;&gt;Pygments&lt;/a&gt; for syntax highlighting. Pygments say that their syntax highlighter even supports &lt;a href=&#34;http://www.muppetlabs.com/~breadbox/bf/&#34; target=&#34;_blank&#34;&gt;brainfuck&lt;/a&gt;. And that’s how I got to brainfuck &lt;img loading=&#34;lazy&#34; src=&#34;http://www.zu14.cn/coolemotion/emotions/zz_2.gif&#34;&gt;&lt;/p&gt;
&lt;p&gt;After I read articles about the language I wanted to test some code of it, I found some &lt;a href=&#34;http://koti.mbnet.fi/villes/php/bf.php&#34; target=&#34;_blank&#34;&gt;online interpreters&lt;/a&gt;, but I wanted to test some code on my machine. I found a &lt;a href=&#34;http://home.arcor.de/partusch/html_en/bfd.html&#34; target=&#34;_blank&#34;&gt;compiler&lt;/a&gt; for it, but I’m using Windows 7 on my machine and the compiler is not compatible with it. I got pissed off and I decided I have to write my own interpreter &lt;img loading=&#34;lazy&#34; src=&#34;http://www.zu14.cn/coolemotion/emotions/zz_3.gif&#34;&gt;&lt;/p&gt;</description>
      <content:encoded><![CDATA[<h1 id="what-is-brainfuck">What is brainfuck?</h1>
<p>Brainfuck is a programming language<img loading="lazy" src="http://www.zu14.cn/coolemotion/emotions/zz_8.gif"></p>
<p>This is the definition from <a href="http://en.wikipedia.org/wiki/Brainfuck" target="_blank">Wikipedia</a>:</p>
<blockquote>
<p>The <strong>brainfuck</strong> programming language is an <a href="http://en.wikipedia.org/wiki/Esoteric_programming_language">esoteric programming language</a> noted for its extreme minimalism. It is a <a href="http://en.wikipedia.org/wiki/Turing_tarpit">Turing tarpit</a>, designed to challenge and amuse <a href="http://en.wikipedia.org/wiki/Programmer">programmers</a>, and is not suitable for practical use. Its name has been variously <a href="http://en.wikipedia.org/wiki/Expurgation">bowdlerized</a>. The name of the language is generally not capitalized, although it is a <a href="http://en.wikipedia.org/wiki/Proper_noun">proper noun</a>.</p>
</blockquote>
<p>This programming language is very easy to learn, very hard to do work with. As the <a href="http://en.wikipedia.org/wiki/Brainfuck" target="_blank">Wikipedia article</a> describes it; the language is an esoteric language, which means it was created for fun <img loading="lazy" src="http://www.zu14.cn/coolemotion/emotions/zz_14.gif"></p>
<p>I discovered the language while I was reading an article about <a href="http://blog.damonjablons.com/2009/10/15/the-perfect-django-settings-file/" target="_blank">writing the perfect settings file for Django</a>. The author used <a href="http://dpaste.com/" target="_blank">DPaste</a> website to link to pieces of code. DPaste website says that it uses <a href="http://pygments.org/" target="_blank">Pygments</a> for syntax highlighting. Pygments say that their syntax highlighter even supports <a href="http://www.muppetlabs.com/~breadbox/bf/" target="_blank">brainfuck</a>. And that’s how I got to brainfuck <img loading="lazy" src="http://www.zu14.cn/coolemotion/emotions/zz_2.gif"></p>
<p>After I read articles about the language I wanted to test some code of it, I found some <a href="http://koti.mbnet.fi/villes/php/bf.php" target="_blank">online interpreters</a>, but I wanted to test some code on my machine. I found a <a href="http://home.arcor.de/partusch/html_en/bfd.html" target="_blank">compiler</a> for it, but I’m using Windows 7 on my machine and the compiler is not compatible with it. I got pissed off and I decided I have to write my own interpreter <img loading="lazy" src="http://www.zu14.cn/coolemotion/emotions/zz_3.gif"></p>
<h2 id="brainfuck-in-simple-description">Brainfuck in simple description</h2>
<p>The language consists of 8 symbols &lt; &gt; . , + – [ ]</p>
<p>The language deals with a 30,000 bytes array, at the start of the application all the items of that array are zeros.</p>
<p>The symbols can just deal with a pointer on that array to do specific jobs.</p>
<h1 id="ply">PLY</h1>
<p>I mentioned in a <a href="http://mpcabd.xyz/binding-netbeans-with-flex/" target="_blank">previous post</a> that I’m implementing a compiler for my 4th year in Informatics faculty. Hence I made a lot of searching around the net for information about implementing compilers. Implementing a compiler requires building a lexer which can be generated using lexer generator tools, and a parser which also can be generated using parser generator tools.</p>
<p>Since I’m a Python-Lover I searched for Python lexer and parser tools, and I came across the great PLY.</p>
<p><a href="http://www.dabeaz.com/ply/" target="_blank">PLY (Python Lex-Yacc)</a> is an implementation of lex and yacc parsing tools for Python.</p>
<p>The usage of PLY is not the target of this post.</p>
<h1 id="writing-a-lexer-for-brainfuck">Writing a lexer for brainfuck</h1>
<p>The lexer would be so simple, since the language only has 8 symbols, and capturing them requires almost nothing.</p>
<p>The lexer file is the following</p>
<pre class="lang:python decode:true">import ply.lex as lex

tokens = [
    'GoLeft',
    'GoRight',
    'Print',
    'Read',
    'Increase',
    'Decrease',
    'WhileStart',
    'WhileEnd'
]

t_GoLeft = r'\&lt;'
t_GoRight = r'\&gt;;'
t_Print = r'\.'
t_Read = r','
t_Increase = r'\+'
t_Decrease = r'\-'
t_WhileStart = r'\['
t_WhileEnd = r'\]'

def t_error(t):
    t.lexer.skip(1)

lexer = lex.lex()

if __name__ == "__main__":
    lex.runmain()
</pre>
<p>It simply captures the symbols of the language and ignores any other symbol. Simple isn’t it 🙂</p>
<h1 id="writing-a-parser-for-brainfuck">Writing a parser for brainfuck</h1>
<p>The parser will have to capture the instructions and store them in a tree so that it can do operations on the code without too much efforts.</p>
<p>The parser will ask the lexer to capture the symbols, while the parser will be responsible for making instructions from symbols.</p>
<h2 id="sparse-matrix">Sparse matrix</h2>
<p>I won’t actually allocate 30,000 bytes array for the application, and since the default value for any item is 0 then I can make use of the <a href="http://en.wikipedia.org/wiki/Sparse_matrix" target="_blank">Sparse Matrix</a>.</p>
<p>Implementing a simple sparse matrix is nothing more than a dictionary:</p>
<pre class="lang:python decode:true">class sparseMatrix:
    def __init__(self):
        self.dict = {}

    def __getitem__(self, index):
        if self.dict.has_key(index):
            return self.dict[index]
        else:
            return 0

    def __setitem__(self, index, value):
        self.dict[index] = value
</pre>
<h2 id="building-the-tree">Building the tree</h2>
<p>Six commands from the brainfuck language have no arguments or any other elements attaching to them, so they would just add elements containing the command type.</p>
<p>While two commands have a scope of code attached with them, the “[“ and “]” can be used to define while loops. So the while loop is the only command that will add an element with sub-level to the tree.</p>
<pre class="lang:python decode:true">def p_start(p):
    """
    start : code
            | empty
    """
    if p[1]:
        executeStatements(p[1])

def p_empty(p):
    'empty : '
    pass

def p_code(p):
    """
    code : code statement
            | code whilestatement
            | statement
            | whilestatement
    """
    if len(p) == 2:
        p[0] = [p[1]]
    else:
        p[0] = p[1][:]
        p[0].extend([p[2]])

def p_statement(p):
    """
    statement : GoLeft
                   | GoRight
                   | Print
                   | Read
                   | Increase
                   | Decrease
    """
    if p[1] == '&lt;':
        p[0] = ('GoLeft', None)
    elif p[1]  == '&gt;':
        p[0] = ('GoRight', None)
    elif p[1] == '.':
        p[0] = ('Print', None)
    elif p[1] == ',':
        p[0] = ('Read', None)
    elif p[1] == '+':
        p[0] = ('Increase', None)
    elif p[1] == '-':
        p[0] = ('Decrease', None)

def p_whilestatement(p):
    'whilestatement : WhileStart code WhileEnd'
    p[0] = ('While', p[2])
</pre>
<h2 id="executing-the-tree">Executing the tree</h2>
<p>Since I’m not building a real compiler I won’t have to generate machine specific code after building the tree. I decided that I can execute the code from within python since the code is too simple to be executed.</p>
<p>So I wrote a method to execute a list of tree elements and it can execute while loops using recursive calling to itself.</p>
<p>The method will be called when the parser parses a valid application and when it can recognize the start symbol of the generating rules of the language.</p>
<pre class="lang:python decode:true">def executeStatements(tuplesList):
    global matrix
    global index
    global MAX_INDEX

    for node in tuplesList:
        if node[0] == 'GoLeft':
            if index &gt; 0:
                index -= 1
            else:
                raise Exception, "Index out of array bounds!"
        elif node[0] == 'GoRight':
            if index &lt; MAX_INDEX:
                index += 1
            else:
                raise Exception, "Index out of array bounds!"
        elif node[0] == 'Print':
            print(chr(matrix[index]), sep='', end='')
        elif node[0] == 'Read':
            matrix[index] = ord(raw_input()[0])
        elif node[0] == 'Increase':
            matrix[index] += 1
        elif node[0] == 'Decrease':
            matrix[index] -= 1
        elif node[0] == 'While':
            while matrix[index] != 0:
                executeStatements(node[1])
</pre>
<h1 id="testing-the-interpreter">Testing the interpreter</h1>
<p>After running the interpreter, I tried the <a href="http://en.wikipedia.org/wiki/Brainfuck#Hello_World.21" target="_blank">Hello World example in Wikipedia</a> and I got the result:</p>
<pre class="lang:python decode:true">BrainFuck&gt; ++++++++++[&gt;+++++++&gt;++++++++++&gt;+++&gt;+&lt;&lt;&lt;&lt;-]&gt;++.&gt;+.+++++++..+++.&gt;++.&lt;&lt;+++++++++++++++.&gt;.+++.------.--------.&gt;+.&gt;.
Hello World!
BrainFuck&gt;
</pre>
<h1 id="download-source-code">Download source code</h1>
<p>You can download and test the interpreter from <a href="http://www.box.net/shared/jaranfgyz1" target="_blank">here</a>.</p>]]></content:encoded>
    </item>
    <item>
      <title>Binding NetBeans with Flex</title>
      <link>https://mpcabd.xyz/binding-netbeans-with-flex/</link>
      <pubDate>Wed, 07 Oct 2009 16:47:49 +0000</pubDate>
      <guid>https://mpcabd.xyz/binding-netbeans-with-flex/</guid>
      <description>&lt;p&gt;In my faculty – Informatics Engineering, Damascus University -, in the 4th year of Software Engineering Department, we have to build a compiler :shock:.&lt;/p&gt;
&lt;p&gt;I like using NetBeans for developing applications, it supports lots of languages and tools; like C, C++, Java, Python, Ruby and more. The compiler would be implemented in C++.&lt;/p&gt;
&lt;p&gt;The first two phases of implementing a compiler are: building a lexer (tokenizer) and building a parser. The lexer is implemented using &lt;a href=&#34;http://www.gnu.org/software/flex/&#34; target=&#34;_blank&#34;&gt;GNU Flex&lt;/a&gt; while the parser is implemented using &lt;a href=&#34;http://www.gnu.org/software/bison/&#34; target=&#34;_blank&#34;&gt;GNU Bison&lt;/a&gt;.&lt;/p&gt;
&lt;h1 id=&#34;the-problem&#34;&gt;The Problem&lt;/h1&gt;
&lt;p&gt;The first problem I faced when starting the project was to tell NetBeans how to handle the lex file:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;The lex file must be passed to the flex tool to generate a C++ code file.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The second problem was that when the code file is generated it contains errors:&lt;/p&gt;
&lt;pre class=&#34;lang:c++ decode:true&#34;&gt;#ifdef __cplusplus

#include &amp;lt;stdlib.h&amp;gt;
class istream;
#include &amp;lt;unistd.h&amp;gt;
&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;When using building the file you’ll find that it contains errors regarding the usage of istream. (You might not face this problem, then you’re a lucky programmer).&lt;/em&gt;&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>In my faculty – Informatics Engineering, Damascus University -, in the 4th year of Software Engineering Department, we have to build a compiler :shock:.</p>
<p>I like using NetBeans for developing applications, it supports lots of languages and tools; like C, C++, Java, Python, Ruby and more. The compiler would be implemented in C++.</p>
<p>The first two phases of implementing a compiler are: building a lexer (tokenizer) and building a parser. The lexer is implemented using <a href="http://www.gnu.org/software/flex/" target="_blank">GNU Flex</a> while the parser is implemented using <a href="http://www.gnu.org/software/bison/" target="_blank">GNU Bison</a>.</p>
<h1 id="the-problem">The Problem</h1>
<p>The first problem I faced when starting the project was to tell NetBeans how to handle the lex file:</p>
<p><em>The lex file must be passed to the flex tool to generate a C++ code file.</em></p>
<p>The second problem was that when the code file is generated it contains errors:</p>
<pre class="lang:c++ decode:true">#ifdef __cplusplus

#include &lt;stdlib.h&gt;
class istream;
#include &lt;unistd.h&gt;
</pre>
<p><em>When using building the file you’ll find that it contains errors regarding the usage of istream. (You might not face this problem, then you’re a lucky programmer).</em></p>
<h1 id="the-first-problem-binding-netbeans-with-flex">The first problem: Binding NetBeans with Flex</h1>
<p>From NetBeans –&gt; Projects Side Tab –&gt; right click on the lex file –&gt; Properties:</p>
<p>Categories –&gt; General:</p>
<ul>
<li>
<p>Uncheck “Excluded From Build”.</p>
</li>
<li>
<p>Select “Custom Build Tool” in the Tool drop down list.</p>
</li>
</ul>
<p>Categories –&gt; Custom Build Step:</p>
<ul>
<li>
<p>Enter in the Command Line field: flex lex.l <em>Assuming that your lex file is called lex.l</em></p>
</li>
<li>
<p>Enter in the Outputs field: lex.yy.cc</p>
</li>
<li>
<p>Enter in the Description: Running Flex …</p>
</li>
</ul>
<p>Press Ok.</p>
<p>Now when you compile the solution your lex file will be passed the the flex tool.</p>
<h1 id="the-second-problem-fixing-the-error">The second problem: Fixing the error</h1>
<p>When I started fixing the error, I was doing it by hand, but I got bored of the process so I wrote a small Python script to do this for me:</p>
<p><em>Assuming that the output file of the lex file is called lex.yy.cc:</em></p>
<pre class="lang:python decode:true">f = open('lex.yy.cc')
lines = f.readlines()
i = 0
for i in range(len(lines)):
    if lines[i] == 'class istream;\n':
        break;
else:
    return;
lines[i] = '#include &lt;iostream&gt;\n'
lines.insert(i + 1, 'using namespace std;\n')
f.close()
f = open('lex.yy.cc', 'w')
f.writelines(lines)
f.close()
</pre>
<p>The script is easy, it opens the file, changes the line from “class istream;” to “#include <iostream>”, inserts “using namespace std;” next.</p>
<p>Put the file next to your sources and run it after the build process to fix the error.</p>
<h1 id="fixing-both-problems-without-executing-anything-manually">Fixing both problems without executing anything manually:</h1>
<p>After a while I got bored of executing the script manually and I decided that the script must be executed automatically.</p>
<p>To do that the script must be called by NetBeans, so back to the lex file properties I changed the Custom Build Command from “flex lex.l” to “python fixer.py”.</p>
<p>Now the fixer script is called to build the lex file, so the script must change to call the flex from the script itself:</p>
<pre class="lang:python decode:true">import os

os.system("flex token.l")

f = open('lex.yy.cc')
lines = f.readlines()
i = 0
for i in range(len(lines)):
    if lines[i] == 'class istream;\n':
        break;
else:
    return;
lines[i] = '#include &lt;iostream&gt;\n'
lines.insert(i + 1, 'using namespace std;\n')
f.close()
f = open('lex.yy.cc', 'w')
f.writelines(lines)
f.close()
</pre>
<p>Now all my problems are solved, hope that yours will be solved too 🙂</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>
    <item>
      <title>Your drawings are Objects in GDI&#43;</title>
      <link>https://mpcabd.xyz/your-drawings-are-objects-in-gdi/</link>
      <pubDate>Tue, 12 Jun 2007 16:43:16 +0000</pubDate>
      <guid>https://mpcabd.xyz/your-drawings-are-objects-in-gdi/</guid>
      <description>&lt;p&gt;Hi all .Net developers and programmers.&lt;/p&gt;
&lt;p&gt;If you’re a .Net developer or a programmer you must have heard of the Drawing namespace in System namespace, and you maybe used it to draw in your applications.&lt;/p&gt;
&lt;p&gt;For those who used them they must have found that moving a single shape in a scene using simple code is not that easy, you’ll have to redraw the whole scene with the shape in its new location, the same thing happens for rotating and scaling a shape, so I had an idea, “Why can’t we just write Rectangle.Move(X,Y) and it moves? Why should I remember every shape coordinates to redraw a small shape in a new position?” so I answered the question.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>Hi all .Net developers and programmers.</p>
<p>If you’re a .Net developer or a programmer you must have heard of the Drawing namespace in System namespace, and you maybe used it to draw in your applications.</p>
<p>For those who used them they must have found that moving a single shape in a scene using simple code is not that easy, you’ll have to redraw the whole scene with the shape in its new location, the same thing happens for rotating and scaling a shape, so I had an idea, “Why can’t we just write Rectangle.Move(X,Y) and it moves? Why should I remember every shape coordinates to redraw a small shape in a new position?” so I answered the question.</p>
<p>I developed a small class that lets you manipulate your drawings as Objects, I mean that you can define a rectangle and just write Rectangle.Move(x,y) and it’ll move to the given position without much hard-coding, I defined (Rectangle, Ellipse, Lines), but you can also define your own shape, you just have to inherit the base class (MagicGraphics.Shape) and you’ll have to write your own Render sub (void) and ToString function, and you can add as much as you want of properties.</p>
<p dir="ltr">
  All the shapes you draw must be placed in a ShapeContainer that handles the drawing according to the Z-Order between shapes.
</p>
<p dir="ltr">
  The following links are for the class and the testing project in VB .Net 2005:
</p>
<p dir="ltr">
  <a target="_blank" href="http://www.savefile.com/files/757490" title="http://www.savefile.com/files/757490">The Class</a> &#8211;    <a target="_blank" href="http://www.savefile.com/files/757502" title="http://www.savefile.com/files/757502">The Testing Project.</a>
</p>
<p dir="ltr">
  The testing project shows how to draw, rotate and move shapes, you can start using my class directly after downloading it.
</p>
<p dir="ltr">
  P.S.: The whole project is still Beta but I wanted to share the first build with you.
</p>
<p dir="ltr">
  Have fun, and please tell me what do you think.
</p>]]></content:encoded>
    </item>
  </channel>
</rss>
