[{"content":"The most important 1:1 meeting you can ever have, and you\u0026rsquo;re absent.\nWe all know one-on-one meetings, I hope you do, it\u0026rsquo;s a meeting where you meet your superior at work, where they check up on you, talk to you, give you guidance, listen to you, and take your requests for consideration. The talk that grows you in your career and guides you around the challenges you\u0026rsquo;re facing at work. The talk that you feel safe having, I also hope so, because you know your superior wants what\u0026rsquo;s best for you, you trust them, you trust their experience and knowledge, and you trust that from above they see and listen a bit more than you, and can foresee things you can\u0026rsquo;t think of.\nDuring that meeting, that call; how attentive are you? How carefully do you listen to absorb and understand every single word being said? How well do you speak? I believe you\u0026rsquo;d be the most attentive in that call, and you\u0026rsquo;d be trying to show the best version of yourself, even when complaining or asking for help and guidance. How often do you have that call? Once a week? Biweekly? Once a month?\nNow let\u0026rsquo;s take a look at the much more important one-on-one meeting you have, it\u0026rsquo;s with a superior beyond superiors, high above every other rank you can ever imagine, it\u0026rsquo;s with the Lord of Lords, the one who created you, who knows every single detail about you, and not only can He see you, He can see everyone else, He can listen to everyone else, He knows what\u0026rsquo;s within you and everyone else.\nIf this were an Earthly lord you wouldn\u0026rsquo;t even think of wishing to meet him once in your lifetime. This is different, in Islam you must meet your God five times every single day until the day you die. It\u0026rsquo;s not an option to skip the call. You hear the call to prayer \u0026ldquo;حي على الفلاح\u0026rdquo; {Come forward to grab success}, you hear it five times a day.\nYou stand in front of your Creator, seventeen times a day across five different prayer times, you recite His words to you and to all mankind, you recite al-Fatiha. You thank Him for everything you have, الحمد لله رب العالمين {All praise is for Allah the Lord of all worlds}, you remind yourself that He is your Lord and everyone else\u0026rsquo;s Lord, that He holds all your fates and knows all about you. You remind yourself that, knowing all that He knows about us, He is still the most merciful, الرحمن الرحيم {The most compassionate, the most merciful}, that despite all your wrongdoings He is still happy to have you back, to have you repent for your sins, that He still provides for you and for everyone else what you need to sustain your life as long as you\u0026rsquo;re on Earth. You remember your actions, and others\u0026rsquo; actions, you remember that you and they will stand one day to be judged by those actions, مالك يوم الدين {Master of the day of judgement}. You then refocus yourself, you go over your eternal oath, you remind yourself that it is He who you should serve and ask for help and guidance, إياك نعبد وإياك نستعين {You ˹alone˺ we worship and You ˹alone˺ we ask for help.}. This is an ongoing conversation, you just can\u0026rsquo;t hear the response, but we were told about it. Allah says \u0026ldquo;حمدني عبدي\u0026rdquo; {My servant has thanked Me}, \u0026ldquo;أثنى علي عبدي\u0026rdquo; {My servant has lauded Me}, \u0026ldquo;مجدني عبدي\u0026rdquo; {My servant has glorified Me}, that\u0026rsquo;s His answer to every sentence you said earlier.\nNow you\u0026rsquo;ve got to the moment, now you\u0026rsquo;ve set up your heart and your mind, now you know what you want, it is now you ask \u0026ldquo;اهدنا الصراط المستقيم\u0026rdquo; {Guide us along the straight path}, because you know you need that guidance, you cannot go through life and its challenges without it, you need your superior\u0026rsquo;s experience and knowledge to guide you every step of the way; otherwise, you\u0026rsquo;re lost. You know the path you want to be guided to, you have seen examples of how other people thought they had the path and lost it, so you ask more specifically \u0026ldquo;صراط الذين أنعمت عليهم ولا الضالين\u0026rdquo; {The path of those You have blessed, not those You are displeased with, or those who are astray}. How does the conversation go further? To that, Allah replies \u0026ldquo;هذا بيني وبين عبدي، هذا لعبدي ولعبدي ما سأل\u0026rdquo; {This is between Me and My servant, and My servant will receive what he asks for}.\nCan you imagine it? Have you thought about this conversation that you must have seventeen times a day across five different prayer times? It\u0026rsquo;s a whole conversation, between you, your heart, your mind, and your God. Are you listening? Are you approaching your conversation with Him properly? It is He who guides you, it is He who provides for you, it is He who has your salvation, it is He who is the most merciful of all to you. This is the most important one-on-one meeting you can ever ask for, give it all you can, give it all your mind, all your soul, and you shall receive what you\u0026rsquo;ve asked for.\nThink about what\u0026rsquo;s actually on the table. Your manager, however good, can only offer you what they know, filtered through their own time, their own mood, their own limits. Here you\u0026rsquo;re standing before the One who knows what you haven\u0026rsquo;t even figured out about yourself yet, who holds every door you think is closed, who can undo in a moment what you\u0026rsquo;ve been stuck on for years. No deadline, no difficult project, no dreaded call with your boss carries that kind of weight, and none of them can give you that kind of return. Be present in it, truly present, say الله أكبر {Allah is greater} and mean it, and watch how small everything else you walked in with suddenly looks. That\u0026rsquo;s not by accident, that\u0026rsquo;s the whole point of standing there.\nRead al-Fatiha Listen to al-Fatiha The conversation in al-Fatiha ","permalink":"https://mpcabd.xyz/one-on-one/","summary":"\u003cp\u003eThe most important 1:1 meeting you can ever have, and you\u0026rsquo;re absent.\u003c/p\u003e\n\u003cp\u003eWe all know one-on-one meetings, I hope you do, it\u0026rsquo;s a meeting where you meet your superior at work, where they check up on you, talk to you, give you guidance, listen to you, and take your requests for consideration. The talk that grows you in your career and guides you around the challenges you\u0026rsquo;re facing at work. The talk that you feel safe having, I also hope so, because you know your superior wants what\u0026rsquo;s best for you, you trust them, you trust their experience and knowledge, and you trust that from above they see and listen a bit more than you, and can foresee things you can\u0026rsquo;t think of.\u003c/p\u003e","title":"One on One"},{"content":"Who among us developers doesn’t know StackOverflow? If you don’t know it then there is a big chance you didn’t search for any programming related question in the last 7 years, so you either are doing a super great job, using a super old community of old school programmers, or actually didn’t practice programming for some really long time.\nStackOverflow reached more than 10 million questions, I won’t list those amazing numbers and statistics here, feel free to see them on StackOverflow’s 10M page, they are really great to read and to try to imagine them.\nI’m not going to talk about its history, the internet is full of those articles, you can read about it from Wikipedia or from its co-founder Joel Spolsky. I will talk about my story and how I see StackOverflow in this occasion, it’s my way of celebrating the success of this global platform, and the success of humanity there.\nMy Story Before StackOverflow Feel free to skip to the next section if you’re not interested in my personal history 🙂\nWhen I first started my programming path, around year 1999, I had no internet, never even heard of it back then, we were living in the dark in Syria, anyway this is not the place for politics, so I started my programming path with no internet, and the only way I could get help was by searching through the thick book I was reading, I taught myself Visual Basic by reading the famous SAMS Teach Yourself Visual Basic 6 in 21 Days, and whenever I had any question back then I would try to find the answer there in that book, if I can’t find it I had no one to ask, I knew of no programmers then, my dad knew a bit of Visual Basic and he put me on the path of programming, but he couldn’t answer my questions as he was using it only for programming in Excel. In around 2001 I think we had our first dial-up connection, and it was bloody expensive, so I wasn’t allowed to use it, we’d use it very wisely, and couldn’t spend time wandering online, so I barely got to know any website for programmers.\nThings started to get better by time, and I discovered CodeProject – I think I was using MSN to search for stuff back then, I don’t remember when was the first time I used Google actually – and I was able to learn some extra good stuff, downloaded some Visual Basic projects, and I could understand them and learn. I also remember I was searching in Arabic a lot, my English wasn’t good enough back then, so I got to know some Arabic programming forums, and that was the way I was able to ask my questions, and many people were using those forums and would help me, I still remember Arab Team 2000 as one of those leading forums back then. Then my path on .NET started and I found very nice Arabic content related to the new framework, I still remember me reading the books written by M. Hamdy Ghanem and I remember me sending him lots of emails back in 2005 and 2006 asking about many different questions and he’d answer them all, also I remember reading the books of Turki Al-Asiri and checking his website which had a forum for questions and answers.\nRight around 2006 I remember I found a website that was a community for those who are interested in computer science in Syria, it was called CSC-SY (Computer SCience – SYria) and unfortunately it is not live anymore, it’s a long story why it’s not there anymore that involves politics too. On CSC-SY I was able to actually find a community that I fit it completely, many like-minded people all discussing computers, programming, algorithms, and all these stuff that I like, and actually discovering that community is the main reason that I entered the Informatics Engineering Faculty in Damascus University, because before that community I thought that people are still living in the dark in Syria. The forum on CSC-SY allowed me to ask a lot, and eventually I started answering a lot, and in a couple of years I became a moderator and then a manager of the forum, this was the place I hanged out everyday for at least 4 years.\nThen in 2009 I joined StackOverflow and started finding answers to my questions there, and since then I’m a user of that platform and a part of that community.\nLife before CSC-SY was hard, and it got way better when StackOverflow came into the picture, and now I can’t imagine the programming world without StackOverflow.\nTogether For a Better Life! I believe in paying the community back for the knowledge I get, in Islam we have the concept of Zakat, a great way of ensuring that each person contributes to the better of the community they live in, the contribution is based on what you have, and must be spent to those who need it and to make the whole community better. Many scholars have generalized this idea from money and valuable stocks to everything that can benefit the community, and knowledge is one of the biggest contributors to the prosperity of nations, and I believe that I have to pay back, to contribute, to pay it forward, too many names to one concept: Together For a Better Life!.\nNow as a professional software developer I see that there are many ways for me to make life better, two main ways are in my opinion open source projects whether it is contributing to them, starting them, or maintaining them; the other one is spreading knowledge and that’s by me writing on my blog about the stuff I find interesting and might help someone, and by me answering questions on StackOverflow.\nI’ve got some open source projects that I worked on or contributed to on my GitHub profile, not much, but I try to keep it going, and whenever I see something that I can fix I don’t hesitate to fix it.\nAlso I don’t spend time on StackOverflow now the same way I used to spend time on CSC-SY, but that’s mainly because I’m now much busier than how I was 6 years ago, I only contributed around 60 answers now, but I try to open the site every couple of days and I check the questions there and try to help when I can.\nIn general I’m giving some time, even if it’s little, to the community of developers that I can benefit, and to the world by working on projects for a better life. I don’t think that I’ve covered my part of the Knowledge Zakat in any way, but I’m trying to cover more.\nThe community on StackOverflow and GitHub are paying it forward, keeping it going and making this world a better world to live in, everyone contributes amounts of knowledge and time, and no matter how small that amount is, the massive effect is really world changing, and the numbers on StackOverflow’s celebration page are a proof that humanity works together for the better of humanity itself.\nSo in the celebration of 10M questions on StackOverflow I would say: To humanity, to mankind, to life! Let’s all make it better! We’ve already done a great job! Let’s keep it going!\n","permalink":"https://mpcabd.xyz/in-the-celebration-of-10m-questions-on-stackoverflow/","summary":"\u003cp\u003eWho among us developers doesn’t know \u003ca href=\"http://stackoverflow.com/\" target=\"_blank\"\u003eStackOverflow\u003c/a\u003e? If you don’t know it then there is a big chance you didn’t search for any programming related question in the last 7 years, so you either are doing a super great job, using a super old community of old school programmers, or actually didn’t practice programming for some really long time.\u003c/p\u003e\n\u003cp\u003eStackOverflow reached more than 10 million questions, I won’t list those amazing numbers and statistics here, feel free to see them on \u003ca href=\"http://stackoverflow.com/10m\" target=\"_blank\"\u003eStackOverflow’s 10M page\u003c/a\u003e, they are really great to read and to try to imagine them.\u003c/p\u003e\n\u003cp\u003eI’m not going to talk about its history, the internet is full of those articles, you can read about it from \u003ca href=\"https://en.wikipedia.org/wiki/Stack_Overflow\" target=\"_blank\"\u003eWikipedia\u003c/a\u003e or from its co-founder \u003ca href=\"http://www.joelonsoftware.com/items/2008/09/15.html\" target=\"_blank\"\u003eJoel Spolsky\u003c/a\u003e. I will talk about my story and how I see StackOverflow in this occasion, it’s my way of celebrating the success of this global platform, and the success of humanity there.\u003c/p\u003e","title":"In the celebration of 10M questions on StackOverflow"},{"content":"Now I’m not going to talk about user input validation, no that’s something that’s been covered a lot around the web, I’m going to talk about something else.\nLet’s imagine you are designing a game, where the user can create a puzzle, for example a maze, and you want to verify that what the user has input is a valid maze, that if played by another player that player will have a chance of winning it. Normally the solution that would come to your (and mine) mind is to try to solve that maze automatically – also we’re not going to talk about the different algorithms for solving mazes – but there is another way to do it that no one told us about in Algorithms 101!\nGuess what! You can verify it manually! Yes Yes I know this is super smart right? No one thought about it!\nCome one enough kidding, but yes verifying it manually will save you a lot of work and complexity, and will also mean that other people will have a good chance (not very high necessarily) of solving the puzzle, let’s face it, if a backtracking algorithm is able to solve a puzzle it doesn’t mean that people will be able to do so too, it might be very hard for people to find that solution, so the point here is that by verifying the puzzle manually you can ensure you give people a better and fair chance.\nOf course I’m not telling you to verify it yourself, that would be nonsense, this is not 1990s, when you would afford verifying user input yourself after you throw it in some queue, now everything seems to be built for the masses and you can’t afford sparing your time or buying someone else’s time to do so. Then what am I talking about?!\nWell the idea is not mine unfortunately, I saw the idea in the latest game by Zeptolab, an MMO strategy game called King Of Thieves.\nKing Of Thieves Splash Screen © 2015 Zeptolab\nIn this game you have a dungeon and a chest of gold and some gems, and like all the other strategy games, you get to design your defences to work the best way against your enemies (every other player out there!), and the goal of your design is to make reaching the chest of gold very hard for other thieves (players) who enter your dungeon, but not impossible or super hard, and that’s the catch; how do you verify that the user doesn’t make it extremely hard if not impossible for other players to reach his/her gems and gold?\nThe way the game creators solved it is a creative way – I’m not sure where it comes from and whether it is their original idea or it’s known in the game industry, but personally I only saw it in their game so far -, and this idea is to ask the user who designs the dungeon to prove that he/she can reach the chest within this design, if the user can’t solve the puzzle (reach the chest here), don’t allow him/her to save the design, and don’t run complex algorithms to check if the design is not an impossible design or a very hard design.\nKing Of Thieves Screenshot © 2015 Zeptolab\nBy doing this the user would have to play in his/her own dungeon trying to defeat his/her defences to reach the chest, and by doing so twice in a row we can be sure that other players stand a good and fair chance of solving this puzzle. One thing that might be of a problem is when the user can actually design a good puzzle but he/she is not yet experienced in this game to solve it, then he/she might need to make their designs easier so that they can save them; but for that the game creators saw a chance where they can make money and they would offer you a proven design that works and is hard in exchange of some valuable resource in the game or you can purchase that design for real money.\nThe other major benefit of this approach is that you end up with a solution to the puzzle – or more than one solution if the user tried two different approaches -, with detailed steps (because you tracked the user while he/she was trying to solve the puzzle). You can use this data to do two important things; 1. You can sell the solution to the players who are trying to solve this puzzle (and betray the user but that’s another moral story), 2. You got yourself a training set for your machine learning algorithms that will be able to mimic the human’s way of solving such puzzles after studying all these massive solutions (and the other ones that users come up with when solving other users’ puzzles themselves).\nI find this very genius, don’t you think?!\nYou can apply this idea to other games where the user creates defences against intruders and still you want to give the intruders a chance not allowing the user to make it impossible for them, and you can generalize the idea to many puzzle games where the user sets up the puzzle for other users.\nWith this idea the creators of that game spared a lot of time, effort and money from being spent on verifying the user’s input, and I think it’s something that’s worth sharing and applying to other platforms, maybe not only to other games.\n","permalink":"https://mpcabd.xyz/verifying-user-input-thinking-outside-the-box/","summary":"\u003cp\u003eNow I’m not going to talk about user input validation, no that’s something that’s been covered a lot around the web, I’m going to talk about something else.\u003c/p\u003e\n\u003cp\u003eLet’s imagine you are designing a game, where the user can create a puzzle, for example a maze, and you want to verify that what the user has input is a valid maze, that if played by another player that player will have a chance of winning it. Normally the solution that would come to your (and mine) mind is to try to solve that maze automatically – also we’re not going to talk about the different algorithms for solving mazes – but there is another way to do it that no one told us about in Algorithms 101!\u003c/p\u003e","title":"Verifying User Input – Thinking Outside The Box"},{"content":"curl 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 PAC configuration files.\nAt 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.\nBefore you use it 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. It also makes use of the following perl modules: Regexp::Common and HTTP::ProxyPAC. Download The script’s gist is here\nThe script is available under GPLv3.\nAfter downloading the script make sure it is executable:\nchmod +x curlp.pl\rAnd edit the file and set the variable $PAC_URI to your PAC URI in line 14.\nHow to use You can use the script just like you use curl normally, it will automatically call curl with the appropriate proxy, but PLEASE NOTE this script will accept the URL as its last parameter always, and will pass any parameters that are before the url to curl blindly.\n./curlp.pl ....... [URL]\r","permalink":"https://mpcabd.xyz/using-curl-with-proxy-pac-configuration-files/","summary":"\u003cp\u003e\u003ca href=\"http://curl.haxx.se/\" target=\"_blank\"\u003ecurl\u003c/a\u003e 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 \u003ca href=\"http://en.wikipedia.org/wiki/Proxy_auto-config#The_PAC_File\" target=\"_blank\"\u003ePAC configuration files\u003c/a\u003e.\u003c/p\u003e\n\u003cp\u003eAt 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.\u003c/p\u003e","title":"Using curl with Proxy PAC configuration files"},{"content":"After spending 3 years in Dubai and working at 2 different startups there, and after having worked at 5 different startups since I started working, I decided it’s time for me to move up and faraway from Dubai and startups, I started looking for jobs at big companies, Google, Facebook, Twitter, and got into a couple of interviews, and in the end I chose to go with Booking.com and I will be joining their team starting December 2014 as an IT Developer!\nJoining Booking.com opens great doors for me, meeting new people, very talented people, working in a stable organization, working on big systems with huge traffic, trying new technologies (like programming with Perl), and so many more!\nI have relocated from Dubai to Amsterdam and thanks to Booking.com Global Mobility Team the relocation was super smooth, and I’m happily settled down now in Amsterdam!\nHopefully I will have more free time so 2015 will have some new projects and posts!\n","permalink":"https://mpcabd.xyz/joining-booking-com/","summary":"\u003cp\u003eAfter spending 3 years in Dubai and working at 2 different startups there, and after having worked at 5 different startups since I started working, I decided it’s time for me to move up and faraway from Dubai and startups, I started looking for jobs at big companies, Google, Facebook, Twitter, and got into a couple of interviews, and in the end I chose to go with Booking.com and I will be joining their team starting December 2014 as an IT Developer!\u003c/p\u003e","title":"Joining Booking.com"},{"content":"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.\nUsing The Context To use the country context\nYou activate the country of choice when you start to process the request, one place for activating the country is by writing a Django middleware that activates the country in the process_request method. After that your code should depend on the country_context.get_current_country_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. In the end when you finish processing the request you should deactivate the country, also you can do that in the middleware in the process_response method. If you want to create a middleware you can extend the CountryContextMiddleware included with this package.\nSettings You should have the following two variables:\nDEFAULT_COUNTRY: The default country code that will be the active country by default. ENABLED_COUNTRIES: A list of country codes that are enabled for your site. Codes are in ISO 3166-1 Alpha 2 format. Example Usage 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.\n# site/settings.py\r# ...\rDEFAULT_COUNTRY = 'US'\rENABLED_COUNTRIES = ['US', 'UK']\r# ...\rMIDDLEWARE_CLASSES = (\r# ...\r'site.country_context_middleware.SiteCountryContextMiddleware',\r# ...\r)\r# site/country_context_middleware.py\rimport re\rfrom django_country_context.country_context_middleware import CountryContextMiddleware\rclass SiteCountryContextMiddleware(CountryContextMiddleware):\rdef get_country_code_from_request(self, request):\rif re.match(r'^/UK/', request.path_info, re.I):\rreturn 'UK'\rreturn 'US'\r# site/urls.py\rfrom django.contrib import admin\rfrom django.conf import settings\rfrom django.conf.urls import patterns, include, url\rurlpatterns = patterns('',\rurl(r'^(?:%s)?/' % '|'.join(\r''.join(\r'[%s%s]' % (c.upper(), c.lower()) for c in country\r) for country in settings.ENABLED_COUNTRIES\r), include('app.urls')),\r)\r# app/models.py\rfrom django.db import models\rfrom django_country_context import country_context, countries_data\rclass StoreManager(models.Manager):\rdef __init__(self, countries_enabled=True):\rsuper(StoreManager, self).__init__()\rself.countries_enabled = countries_enabled\rdef get_query_set(self):\rqs = super(StoreManager, self).get_query_set()\rif self.countries_enabled:\rqs = qs.filter(country=country_context.get_current_country_code())\rreturn qs\rclass Store(models.Model):\r# ...\rcountry = models.CharField(max_length=2, default=country_context.get_current_country_code, choices=countries_data.ENABLED_COUNTRIES_TUPLE, db_index=True)\robjects = StoreManager()\robjects_no_countries = StoreManager(countries_enabled=False)\r# app/admin.py\rfrom django.contrib import admin\rfrom models import Store\rclass StoreAdmin(admin.ModelAdmin):\rmodel = Store\rdef queryset(self, request):\rself.model._default_manager = self.model.objects_no_countries\rreturn super(StoreAdmin, self).queryset(request)\r# ...\radmin.site.register(Store, StoreAdmin)\rUsing 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 country_context.get_current_country_name() and country_context.get_current_country_code() respectively. Please note that the setup above was written for a Django 1.4.x.\nDownload Django Country Context on source code on GitHub\n","permalink":"https://mpcabd.xyz/django-country-context/","summary":"\u003cp\u003eThis 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.\u003c/p\u003e","title":"Django Country Context"},{"content":"I usually use django’s custom management commands 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.\nYou 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.\nUnderstanding how django’s error email works If you check django’s logging documentation you will find that it has a built-in handler called AdminEmailHandler this handler sends an email to the site admins for each log message it receives.\nSo 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.\nTo do so define a logger in your settings.py:\nLOGGING = {\r#OTHER OPTIONS\r'filters': {\r#OTHER FILTERS\r'require_debug_false': {\r'()': 'django.utils.log.RequireDebugFalse'\r}\r},\r'handlers': {\r#OTHER HANDLERS\r'mail_admins': {\r'level': 'ERROR',\r'filters': ['require_debug_false'],\r'class': 'django.utils.log.AdminEmailHandler',\r'include_html': True\r}\r},\r'loggers': {\r#OTHER LOGGERS\r'management_commands': {\r'handlers': ['mail_admins'],\r'level': 'ERROR',\r'propagate': True,\r},\r}\r}\rAnd after that in your custom commands log the errors you face using the logger you defined:\nfrom django.utils.log import getLogger\rfrom django.core.management.base import BaseCommand\rimport sys\rlogger = getLogger('management_commands')\rclass Command(BaseCommand):\rdef handle(self, *args, **options):\rtry:\r#DO YOUR STUFF HERE\rexcept Exception as e:\rlogger.error('Admin Command Error: %s', ' '.join(sys.argv), exc_info=sys.exc_info())\r#Raise the exception again so it gets logged in standard error also.\rraise e\rEnabling the logger to all commands in one configuration You can also make all the commands (custom or not) send the error by email by editing manage.py almost the same way as we edited the command file above:\nfrom django.utils.log import getLogger\rimport sys\rlogger = getLogger('management_commands')\r#Wrap this line with a try-catch execute_from_command_line(sys.argv)\rtry:\rexecute_from_command_line(sys.argv)\rexcept Exception as e:\rlogger.error('Admin Command Error: %s', ' '.join(sys.argv), exc_info=sys.exc_info())\rraise e\rThis way all the commands will send the error by email also to django admins.\nEnjoy it!\n","permalink":"https://mpcabd.xyz/make-django-management-commands-send-errors-email-admins/","summary":"\u003cp\u003eI usually use django’s \u003ca title=\"Writing custom django-admin commands\" href=\"https://docs.djangoproject.com/en/dev/howto/custom-management-commands/\" target=\"_blank\"\u003ecustom management commands\u003c/a\u003e 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.\u003c/p\u003e","title":"How to make django management commands send errors email to admins"},{"content":"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 logrotate 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.\nlogrotate uses the system’s mail /bin/mail 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 SSMTP 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:\nOption -m, –mail Tells logrotate which command to use when mailing logs. This command should accept two arguments: 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. The default mail command is /bin/mail -s.\nWhich 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.\nThe shell script The solution to this problem would be by creating a shell script that behaves like a middleware between logrotate and SSMTP.\nThe 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.\nYou can download the shell script from this link logrotate_ssmtp.sh.\nAs 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.\nAlso you’ll have to replace server@example.com with the email address you’re sending from.\nConfiguring logrotate 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:\n/usr/sbin/logrotate -m '~/logrotate_ssmtp.sh' /etc/logrotate.conf\nThe main call that you should change is located in cron.daily directory, I’m using Ubuntu so I have to edit this file /etc/cron.daily/logrotate and change the command at the end of the file to the command above.\nHope this helps you with your logs 🙂\nphoto by ahisgett on Flickr\n","permalink":"https://mpcabd.xyz/make-logrotate-use-ssmtp/","summary":"\u003cp\u003eA 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 \u003ca title=\"logrotate man page\" href=\"http://linuxcommand.org/man_pages/logrotate8.html\" target=\"_blank\"\u003elogrotate\u003c/a\u003e 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.\u003c/p\u003e","title":"How to make logrotate use SSMTP"},{"content":"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.\nI 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.\nHere is the bash script:\n#!/bin/bash\rwhile read x; do\recho -n `date +%d/%m/%Y\\ %H:%M:%S`;\recho -n \" \";\recho $x;\rdone\rThen I edited the cron job line to be like this:\n... /path/to/my/command.sh 2\u0026gt;\u00261 | /path/to/timestap.sh \u0026gt;\u0026gt; /var/log/cron/my_log.log\rAnd you’re done!\nEnjoy it.\n","permalink":"https://mpcabd.xyz/adding-a-timestamp-to-command-output-in-linux/","summary":"\u003cp\u003eThis 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.\u003c/p\u003e\n\u003cp\u003eI 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.\u003c/p\u003e","title":"Adding a timestamp to command output in linux"},{"content":"Two days ago I needed to generate a PIL image that is made up from repeating a pattern – another PIL image – multiple times, I didn’t find a code online to do it so I just wrote this small code to do it, thought might share it to help somebody out there.\ndef get_pattern_from_image(file_name, pattern_width, pattern_height): import Image pattern_image = Image.open(file_name, 'r') result_image = Image.new('RGB', (pattern_width, pattern_height)) x = 0 while x \u0026lt; pattern_width: y = 0 while y \u0026lt; pattern_height: result_image.paste(pattern_image, (x, y)) y += pattern_image.size[1] x += pattern_image.size[0] return result_image It\u0026rsquo;s a very simple solution which uses the Image.paste method to repeat the pattern.\nYou can download this snippet of code from here: https://gist.github.com/4529367.\nEnjoy 🙂\n","permalink":"https://mpcabd.xyz/get-pattern-from-an-image-in-pil-python/","summary":"\u003cp\u003eTwo days ago I needed to generate a PIL image that is made up from repeating a pattern – another PIL image – multiple times, I didn’t find a code online to do it so I just wrote this small code to do it, thought might share it to help somebody out there.\u003c/p\u003e","title":"Get Pattern From an Image in PIL Python"},{"content":"A while ago I was working on a project in Django that had many tasks that needed to be executed asynchronously such as sending emails, generating reports, and checking some database related issues.\nExecuting asynchronous tasks in Python can be made in multiple ways, one of them is using celery, a distributed task queue written in Python which has proved itself to be a great solid task queue system.\nAnd if you’re using Django then there is a Django app to make your life easier, django-celery.\nNow as always I like to make my own life easier also by implementing generic solutions for my needs, so I have written this simple piece of code to create a function decorator that declares the function as an asynchronous task, which means that by just adding this decorator to the function it becomes asynchronous.\nSo let’s get started!\nDescription The following code will allow you to decorate Python functions with a decorator that will allow them to be executed asynchronously in a seamless easy way. You don’t have to change any thing in your code, just add the asynchronous_task decorator to the functions you want them to be executed asynchronously and you’re done.\nThis code can be used with Django also, just uncomment the Django block in it and it’ll work.\nI wrote this code in a file called celery_tasks.py which probably the place you’ll have your all celery tasks, it adds a task called execute that is responsible for executing the passed function and parameters.\nimport os, sys from celery.task import task sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) sys.path.insert(0, os.path.dirname(__file__)) ########################## # Uncomment the following code block to enable it to work with Django. # Either put this file next to the settings.py file, or change the block code to import your settings module from the correct path. ########################## #from django.core.management import setup_environ #import settings #setup_environ(settings) @task(name='execute') def execute(module_name, method_name, *args, **kwargs): try: m = __import__(module_name) if m.__name__ != module_name: modules = module_name.split('.')[1:] for module in modules: m = getattr(m, module) f = getattr(m, method_name) if hasattr(f, 'func'): f = f.func return f(*args, **kwargs) except Exception, e: raise e The code looks like a mess I know, but simply what it does is that you pass this task the following parameters:\nPython module name to get the function from Method name to be executed Positional and named parameters The second part is defining the decorator, lets assume that this file is called celery_decorator.py:\nNote that I’m assuming that celery_decorator.py is in the same folder of your celery_tasks.py file.\nfrom django.utils.decorators import available_attrs from django.utils.functional import wraps def asynchronous_task(check_if_active = False): def wrapper(f): try: @wraps(f, assigned=available_attrs(f)) def _wrapper(*args, **kwargs): try: if check_if_active: from celery.task.control import inspect insp = inspect() d = insp.active() if not d: raise Exception from celery_tasks import execute execute.delay(f.__module__, f.func_name, *args, **kwargs) except Exception as e: f(*args, **kwargs) _wrapper.func = f return _wrapper except Exception: return f return wrapper This decorator simply wraps the function in a call to the execute task on celery, so that it’ll be executed asynchronously, it accept an optional parameter that defines whether the decorator should check if celery is running and if it’s not then execute the function synchronously, it is set to False by default because it takes some time to check celery, so it makes the performance poor a little bit.\nNow we can us it on any function inside our code:\nfrom celery_decorator import asynchronous_task #Default not to check if celery is running @asynchronous_task def a_very_long_process(p1, p2): pass #TODO: Do something #Force check @asynchronous_task(check_if_active = True) def another_very_long_process(p1, p2): pass #TODO: Do something Now in your code you just simply don’t change anything, all the calls to these two functions will be asynchronous calls.\nDownload The source code is licensed under the GNU Public License (GPL).\nYou can download a copy of celery_tasks.py and celery_decorators.py from this Gist: https://gist.github.com/3874979\nHope this helps somebody to perform faster 🙂\n","permalink":"https://mpcabd.xyz/python-celery-asynchronous-task-decorator/","summary":"\u003cp\u003eA while ago I was working on a project in Django that had many tasks that needed to be executed asynchronously such as sending emails, generating reports, and checking some database related issues.\u003c/p\u003e\n\u003cp\u003eExecuting asynchronous tasks in Python can be made in multiple ways, one of them is using \u003ca href=\"http://celeryproject.org/\" title=\"Celery: Distributed Task Queue\" target=\"_blank\"\u003ecelery\u003c/a\u003e, a distributed task queue written in Python which has proved itself to be a great solid task queue system.\u003c/p\u003e\n\u003cp\u003eAnd if you’re using Django then there is a Django app to make your life easier, \u003ca href=\"https://github.com/celery/django-celery/\" title=\"Celery integration for Django\" target=\"_blank\"\u003edjango-celery\u003c/a\u003e.\u003c/p\u003e\n\u003cp\u003eNow as always I like to make my own life easier also by implementing generic solutions for my needs, so I have written this simple piece of code to create a function decorator that declares the function as an asynchronous task, which means that by just adding this decorator to the function it becomes asynchronous.\u003c/p\u003e","title":"Python Celery Asynchronous Task Decorator"},{"content":"I was trying today to generate PDF reports using Geraldo Reports and I needed to generate reports with Arabic text in them. Arabic is a very special script language with two essential features:\nIt is written from right to left. The characters change shape according to their surrounding characters. So when you try to print Arabic text in an application – or a library – that doesn’t support Arabic you’re pretty likely to end up with something that looks like this:\nArabic text, broken, left to right\nWe have two problems here, first, the characters are in the isolated form, which means that every character is rendered regardless of its surroundings, and second is that the text is written from left to right.\nTo solve the latter issue all we have to do is to use the Unicode bidirectional algorithm, which is implemented purely in Python in python-bidi. If you use it you’ll end up with something that looks like this:\nArabic text, broken, right to left\nThe only issue left to solve is to reshape those characters and replace them with their correct shapes according to their surroundings.\nI solved this issue more than four years ago in a small application that I wrote in Visual Basic, my solution was naive but it solved it well, anyway, a few days ago I faced the same problem – rendering Arabic text correctly – but on Android, and I searched and used the solution in this SO answer, which is pretty similar to the solution provided in Better Arabic Reshaper.\nToday I ported the solution in Better Arabic Reshaper from Java to Python, tweaked it a little bit, and used it to successfully render Arabic text in PDF, and the result was:\nArabic text, correctly shaped, right to left\nPretty cool right? Here is another test with English text in it some diacritics:\nArabic text, with English text, correctly shaped, correctly directed, with diacritics\nIt looks fine! in Word the same text looks like this:\nArabic text, with English text, correctly shaped, correctly directed, with diacritics, in Microsoft Word\nAmazing, now it is time for you to use the ported library along with python-bidi to solve those issues.\nUsage import arabic_reshaper from bidi.algorithm import get_display #... reshaped_text = arabic_reshaper.reshape(u'اللغة العربية رائعة') bidi_text = get_display(reshaped_text) pass_arabic_text_to_render(bidi_text) # \u0026lt;-- This function does not really exist #... The pass_arabic_text_to_render function here is an imaginary function, it is just here to say that the variable bidi_text is the variable that you would need to use in your code afterwards, for example to print it in PDF, or to write it in an Image, etc.\nDemo You can try an online demo of this script on my page here: Arabic Reshaper Online.\nDownload The source code is licensed under the MIT License.\nYou can install it into your Python installation with pip:\n$ pip install arabic-reshaper Project on GitHub\nSource code download from GitHub\nHave fun واستمتع! 🙂\n","permalink":"https://mpcabd.xyz/python-arabic-text-reshaper/","summary":"\u003cp\u003eI was trying today to generate PDF reports using \u003ca href=\"http://www.geraldoreports.org/\" target=\"_blank\"\u003eGeraldo Reports\u003c/a\u003e and I needed to generate reports with Arabic text in them. Arabic is a very special script language with two essential features:\u003c/p\u003e\n\u003col\u003e\n\u003cli\u003eIt is written from right to left.\u003c/li\u003e\n\u003cli\u003eThe characters change shape according to their surrounding characters.\u003c/li\u003e\n\u003c/ol\u003e\n\u003cp\u003eSo when you try to print Arabic text in an application – or a library – that doesn’t support Arabic you’re pretty likely to end up with something that looks like this:\u003c/p\u003e\n\u003cfigure class=\"auto center\"\u003e\n    \u003cimg loading=\"lazy\" src=\"/wp-content/uploads/2012/05/arabic-1.png\"\n         alt=\"Arabic text, broken, left to right\"/\u003e \u003cfigcaption\u003e\n            \u003cp\u003eArabic text, broken, left to right\u003c/p\u003e\n        \u003c/figcaption\u003e\n\u003c/figure\u003e\n\n\u003cp\u003eWe have two problems here, first, the characters are in the isolated form, which means that every character is rendered regardless of its surroundings, and second is that the text is written from left to right.\u003c/p\u003e","title":"Python Arabic Text Reshaper"},{"content":"I was working an Android application, and I had an activity that contains a map in it, the map is hosted inside a MapView. The application had to show some pins over the map, the pins locations are obtained from a web service. I had to retrieve the pins locations after the user pans the map or zooms in or out.\nGoogle didn’t provide events for panning and zooming inside MapView class, but you can extend the class and do it your self, and that’s what I did.\nListener Interface import com.google.android.maps.GeoPoint;\rpublic interface MapViewListener {\rvoid onPan(GeoPoint oldTopLeft,\rGeoPoint oldCenter,\rGeoPoint oldBottomRight,\rGeoPoint newTopLeft,\rGeoPoint newCenter,\rGeoPoint newBottomRight);\rvoid onZoom(GeoPoint oldTopLeft,\rGeoPoint oldCenter,\rGeoPoint oldBottomRight,\rGeoPoint newTopLeft,\rGeoPoint newCenter,\rGeoPoint newBottomRight,\rint oldZoomLevel,\rint newZoomLevel);\rvoid onClick(GeoPoint clickedPoint);\r}\rThis listener will receive three events, onPan when the user pans the map, onZoom when the user zooms in or out, onClick when the user taps on the map without panning.\nEach event will pass useful parameters, which are old and new values for the top left corner, bottom right corner, center point and zoom level.\nMap View Code The new map view will inherit the MapView class, and define some useful variables:\nimport android.content.Context;\rimport android.graphics.Canvas;\rimport android.util.AttributeSet;\rimport android.view.MotionEvent;\rimport com.google.android.maps.GeoPoint;\rimport com.google.android.maps.MapView;\rpublic class ObservableMapView extends MapView {\rpublic ObservableMapView(Context context, String apiKey) { super(context, apiKey); }\rpublic ObservableMapView(Context context, AttributeSet attrs) { super(context, attrs); }\rpublic ObservableMapView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); }\rprivate GeoPoint mOldTopLeft;\rprivate GeoPoint mOldCenter;\rprivate GeoPoint mOldBottomRight;\rprivate int mOldZoomLevel = -1;\rprivate MapViewListener mMapViewListener;\rpublic MapViewListener getMapViewListener() { return mMapViewListener; }\rpublic void setMapViewListener(MapViewListener value) { mMapViewListener = value; }\r// ...\r}\rTo get touch events we’re going to override the onTouchEvent:\n@Override\rpublic boolean onTouchEvent(MotionEvent ev) {\rif (ev.getAction() == MotionEvent.ACTION_UP) {\rGeoPoint newCenter = this.getMapCenter();\rGeoPoint newTopLeft = this.getProjection().fromPixels(0, 0);\rGeoPoint newBottomRight = this.getProjection().fromPixels(this.getWidth(), this.getHeight());\rif (this.mMapViewListener != null \u0026\u0026\rnewTopLeft.getLatitudeE6() == mOldTopLeft.getLatitudeE6() \u0026\u0026\rnewTopLeft.getLongitudeE6() == mOldTopLeft.getLongitudeE6()) {\rmMapViewListener.onClick(this.getProjection().fromPixels((int)ev.getX(), (int)ev.getY()));\r}\r}\rreturn super.onTouchEvent(ev);\r}\rHere we’re checking the new coordinates with the old coordinates, if they haven’t changed then the user has tapped on the map, but if they changed then it is a panning event, we’re not going to emit the event of panning now.\nTo be able to find if the user has zoomed we’re going to override the dispatchDraw method, because it will be called when the user pans or zooms, so it is the place we’re going to check for events in it.\n@Override\rprotected void dispatchDraw(Canvas canvas) {\rsuper.dispatchDraw(canvas);\rGeoPoint newCenter = this.getMapCenter();\rGeoPoint newTopLeft = this.getProjection().fromPixels(0, 0);\rGeoPoint newBottomRight = this.getProjection().fromPixels(this.getWidth(), this.getHeight());\rint newZoomLevel = this.getZoomLevel();\rif (mOldCenter == null)\rmOldCenter = newCenter;\rif (mOldTopLeft == null)\rmOldTopLeft = newTopLeft;\rif (mOldBottomRight == null)\rmOldBottomRight = newBottomRight;\rif (newTopLeft.getLatitudeE6() != mOldTopLeft.getLatitudeE6() || newTopLeft.getLongitudeE6() != mOldTopLeft.getLongitudeE6()) {\rif (this.mMapViewListener != null) {\rGeoPoint oldTopLeft, oldCenter, oldBottomRight;\roldTopLeft = mOldTopLeft;\roldCenter = mOldCenter;\roldBottomRight = mOldBottomRight;\rmOldBottomRight = newBottomRight;\rmOldTopLeft = newTopLeft;\rmOldCenter = newCenter;\rmMapViewListener.onPan(oldTopLeft,\roldCenter,\roldBottomRight,\rnewTopLeft,\rnewCenter,\rnewBottomRight);\r}\r}\rif (mOldZoomLevel == -1)\rmOldZoomLevel = newZoomLevel;\relse if (mOldZoomLevel != newZoomLevel \u0026\u0026 mMapViewListener != null) {\rint oldZoomLevel = mOldZoomLevel;\rGeoPoint oldTopLeft, oldCenter, oldBottomRight;\roldTopLeft = mOldTopLeft;\roldCenter = mOldCenter;\roldBottomRight = mOldBottomRight;\rmOldZoomLevel = newZoomLevel;\rmOldBottomRight = newBottomRight;\rmOldTopLeft = newTopLeft;\rmOldCenter = newCenter;\rmMapViewListener.onZoom(oldTopLeft,\roldCenter,\roldBottomRight,\rnewTopLeft,\rnewCenter,\rnewBottomRight,\roldZoomLevel,\rnewZoomLevel);\r}\r}\rDownload The source code is licensed under the GNU Public License (GPL).\nYou can download the source code from here:\nProject on GitHub\nSource code from GitHub\n","permalink":"https://mpcabd.xyz/android-map-view-with-pan-zoom-events/","summary":"\u003cp\u003eI was working an Android application, and I had an activity that contains a map in it, the map is hosted inside a \u003ca href=\"http://developer.android.com/resources/tutorials/views/hello-mapview.html\"\u003eMapView\u003c/a\u003e. The application had to show some pins over the map, the pins locations are obtained from a web service. I had to retrieve the pins locations after the user pans the map or zooms in or out.\u003c/p\u003e\n\u003cp\u003eGoogle didn’t provide events for panning and zooming inside MapView class, but you can extend the class and do it your self, and that’s what I did.\u003c/p\u003e","title":"Android Map View With Pan \u0026 Zoom Events"},{"content":"It’s been a long time since the last time I blogged about something, and many things have changed since then,\nI graduated, got engaged and moved to Dubai.\nI have plenty of things in my mind to blog about, many solutions and many tools that I developed that I’d like to share it with everyone, but I haven’t settled down, and my schedule is not stable yet, so I haven’t got enough time to sort things out and start blogging, anyway this post is simple and it doesn’t need much description so I thought I’d share it with you now.\nNow let’s move to business, so I was working on an Android application and I needed to log some debug messages, normally I’d use Log.d(TAG, message); and this will send the message to logcat, but logcat is not useful for long messages, like for example if I needed to log the response I received from a web service, this response might be long and sending it to logcat will truncate it.\nSo usually in such situations we use files and log whatever we need inside them, but I’m working on an Android phone/emulator, and dealing with files and logging to them and reading them later from the computer will be a tedious thing to do, so I came up with a simple solution to log messages from Android to my computer.\nThe idea is to create a simple web server that accepts POST requests, these requests have only one parameter which is the data to be logged. I made it as simple as possible, I could have defined levels for logging and tags and other sorts of things, but I wanted a simple solution that wouldn’t take more than five minutes to write and get it working.\nSimple web server Since I’m a pythonist geek I couldn’t think of anything better than Python to implement the simple web server, and it was really great, since I didn’t have to write so much code!\nI’ll be using HTTPServer and BaseHTTPRequestHandler from BaseHTTPServer module, some threading and cgi.\nfrom BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler import threading import cgi import time IP = '192.168.1.3' PORT = 5500 LOG_FILE = r'C:\\AndroidLogFile.log' POST_PARAMETER = 'log' I set the server to run on port 5500, don’t ask why I chose this number, I didn’t think of it 😛\nI define a function that will execute a function in a separate thread as a daemon thread:\ndef startThread(fn): thread = threading.Thread(target=fn) thread.setDaemon(True) thread.start() return thread I define the block of code to be executed when running the server:\nif __name__ == '__main__': httpd = HTTPServer((IP, PORT), lambda *args, **kwargs: LogHandler(*args, **kwargs)) serve_thread = startThread(httpd.serve_forever) while serve_thread.isAlive(): serve_thread.join(timeout=1) Here I created an HTTP web server that is bound to the IP/PORT set at the beginning of the script, and I mapped the handler for this web server to a class called LogHandler.\nThis handler will handle the requests, and hence it’ll handle POST requests and save their contents into the specified file.\nclass LogHandler(BaseHTTPRequestHandler): def __init__(self, *args, **kwargs): BaseHTTPRequestHandler.__init__(self, *args, **kwargs) def do_POST(self): length = int(self.headers.getheader('content-length')) postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1) f = open(LOG_FILE, 'a') f.write('%s:\\n%s\\n%s\\n' % (time.strftime('%Y/%m/%d %H:%M:%S'), postvars[POST_PARAMETER][0], '*' * 20)) f.close() self.send_response(200) self.send_header('Content-Type', 'text/plain') self.send_header('Cache-Control', 'no-cache') self.end_headers() self.wfile.write('Saved!') Pretty simple, not more than 35 lines of code!\nNow let’s move to the Android/Java side.\nAndroid/Java class This class will be responsible for sending POST requests to the server, I’ll be using Apache classes to do the HTTP requests, and I’ll use some other classes from Java standard library, along with Android log class to log exceptions.\nimport org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import android.util.Log; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; The class starts with defining some constants:\npublic class LogToFile { private static final String LOG_TO_FILE_ADDRESS = \"http://192.168.1.3\"; private static final String LOG_TO_FILE_URL = \"/\"; private static final String LOG_TO_FILE_LOG_PARAMETER = \"log\"; private static final int LOG_TO_FILE_PORT = 5500; Then I define a method that constructs an HTTP POST request to the specified url along with the specified parameters:\nprivate static HttpPost Post(String url, HashMap\u0026lt;String, String\u003e params, HashMap\u0026lt;String, ArrayList\u0026lt;String\u003e\u003e arrayParams) { try { if (!url.endsWith(\"/\")) url += \"/\"; List\u0026lt;NameValuePair\u003e params_list = null; if (params != null) { params_list = new LinkedList\u0026lt;NameValuePair\u003e(); for (Entry\u0026lt;String, String\u003e entry : params.entrySet()) params_list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } if (arrayParams != null) { if (params_list == null) params_list = new LinkedList\u0026lt;NameValuePair\u003e(); for (Entry\u0026lt;String, ArrayList\u0026lt;String\u003e\u003e entry : arrayParams.entrySet()) for (String value : entry.getValue()) params_list.add(new BasicNameValuePair(entry.getKey(), value)); } HttpPost request = new HttpPost(url); if (params != null) request.setEntity(new UrlEncodedFormEntity(params_list, \"utf-8\")); return request; } catch (Exception e) { Log.e(\"\", e.getClass().getName() + \"\\n\" + e.getMessage()); } return null; } I know this is a lot of code for such thing, but this method is used elsewhere in my application and that’s why it had to be this generic.\nAnother method will be used to execute the request, also it is generic to be used elsewhere, you can edit the code and make it more specific to your needs.\nprivate static HttpResponse ExecuteRequest(HttpUriRequest request) { try { HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(request); return response; } catch (Exception e) { Log.e(\"\", e.getClass().getName() + \"\\n\" + e.getMessage()); } return null; } And now to the final piece of code here, this is the method that you’ll call from anywhere in your application to log messages to the file:\npublic static void LogToFile(String log) { try { HashMap\u0026lt;String, String\u003e params = new HashMap\u0026lt;String, String\u003e(); params.put(LOG_TO_FILE_LOG_PARAMETER, log); HttpPost request = Post(String.format(\"%s:%d%s\", LOG_TO_FILE_ADDRESS, LOG_TO_FILE_PORT, LOG_TO_FILE_URL), params, null); HttpResponse response = ExecuteRequest(request); response.getEntity().consumeContent(); } catch (Exception e) { Log.e(\"\", e.getClass().getName() + \"\\n\" + e.getMessage()); } } Download The source code is licensed under the GNU Public License (GPL).\nProject on GitHub\nYou can download the source code from here:\nSource code from GitHub\n","permalink":"https://mpcabd.xyz/log-to-a-file-on-computer-in-android/","summary":"\u003cp\u003eIt’s been a long time since the last time I blogged about something, and many things have changed since then,\u003c/p\u003e\n\u003cp\u003eI graduated, got engaged and moved to Dubai.\u003c/p\u003e\n\u003cp\u003eI have plenty of things in my mind to blog about, many solutions and many tools that I developed that I’d like to share it with everyone, but I haven’t settled down, and my schedule is not stable yet, so I haven’t got enough time to sort things out and start blogging, anyway this post is simple and it doesn’t need much description so I thought I’d share it with you now.\u003c/p\u003e\n\u003cp\u003e\u003ca href=\"http://mpcabd.xyz/wp-content/uploads/2011/12/Androids.png\" rel=\"lightbox[310]\" title=\"Androids\"\u003e\u003cimg src=\"http://mpcabd.xyz/wp-content/uploads/2011/12/Androids-300x105.png\" alt=\"\" title=\"Androids\" width=\"300\" height=\"105\" class=\"aligncenter size-medium wp-image-315\" srcset=\"https://mpcabd.xyz/wp-content/uploads/2011/12/Androids-300x105.png 300w, https://mpcabd.xyz/wp-content/uploads/2011/12/Androids.png 766w\" sizes=\"(max-width: 300px) 100vw, 300px\" /\u003e\u003c/a\u003eNow let’s move to business, so I was working on an \u003ca href=\"http://developer.android.com/index.html\" title=\"Android Developers\"\u003eAndroid\u003c/a\u003e application and I needed to log some debug messages, normally I’d use \u003ccode\u003eLog.d(TAG, message);\u003c/code\u003e and this will send the message to \u003ca href=\"http://developer.android.com/guide/developing/tools/logcat.html\" title=\"logcat | Android Developers\"\u003elogcat\u003c/a\u003e, but logcat is not useful for long messages, like for example if I needed to log the response I received from a web service, this response might be long and sending it to logcat will truncate it.\u003c/p\u003e","title":"Log to a file on computer in Android"},{"content":"Today I gave a lecture in my faculty about “Collaborative Software Development with SVN”, it was prepared and set by the collaboration of iCommunity, Syrian Computer Society and Damascus University.\nThe lecture included the following points:\nA Tribute to Mahmoud Darwish iCommunity Introduction Introduction Problem Definition Introducing Version Control System Definitions How it works Introducing SVN How to SVN: Hosting Projects. Local Servers. Installing TortoiseSVN. Basic Operations Advanced Operations. Conclusion The lecture went well, and I hope that students will start using such technologies during their projects.\nYou can download the presentation slides from here:\niCommunity – Collaborative Software Development with SVN Power Point 2007\niCommunity – Collaborative Software Development with SVN Power Point 97 – 2003\n","permalink":"https://mpcabd.xyz/collaborative-software-development-with-svn-lecture/","summary":"\u003cp\u003eToday I gave a lecture in my faculty about “Collaborative Software Development with SVN”, it was prepared and set by the collaboration of iCommunity, Syrian Computer Society and Damascus University.\u003c/p\u003e\n\u003cp\u003eThe lecture included the following points:\u003c/p\u003e\n\u003col\u003e\n\u003cli\u003eA Tribute to \u003ca href=\"http://en.wikipedia.org/wiki/Mahmoud_Darwish\"\u003eMahmoud Darwish\u003c/a\u003e\u003c/li\u003e\n\u003cli\u003eiCommunity Introduction\u003c/li\u003e\n\u003cli\u003eIntroduction\u003c/li\u003e\n\u003cli\u003eProblem Definition\u003c/li\u003e\n\u003cli\u003eIntroducing \u003cstrong\u003eV\u003c/strong\u003eersion \u003cstrong\u003eC\u003c/strong\u003eontrol \u003cstrong\u003eS\u003c/strong\u003eystem\u003c/li\u003e\n\u003cli\u003eDefinitions\u003c/li\u003e\n\u003cli\u003eHow it works\u003c/li\u003e\n\u003cli\u003eIntroducing SVN\u003c/li\u003e\n\u003cli\u003eHow to SVN:\n\u003col\u003e\n\u003cli\u003eHosting Projects.\u003c/li\u003e\n\u003cli\u003eLocal Servers.\u003c/li\u003e\n\u003cli\u003eInstalling TortoiseSVN.\u003c/li\u003e\n\u003cli\u003eBasic Operations\u003c/li\u003e\n\u003cli\u003eAdvanced Operations.\u003c/li\u003e\n\u003c/ol\u003e\n\u003c/li\u003e\n\u003cli\u003eConclusion\u003c/li\u003e\n\u003c/ol\u003e","title":"Collaborative Software Development with SVN Lecture"},{"content":"Google Buzz is a social networking and messaging tool from Google Inc. that’s integrated into GMail. Google Buzz was released in early February this year (9th Feb 2010), and since then it has emerged as an important social network for GMail users, and many people (including me) prefer it now to other social networking platforms such as Facebook.\nLogos of Google Buzz, OAuth And Python In May Google revealed the Buzz API to the public so developers around the world could write applications to interact with Google Buzz to read and/or write.\nGoogle uses OAuth for authentication and authorization to their services. OAuth is an open standard that allows users to share their content (or data generally) from one site to another (or to an application generally) without having to hand the other site their credentials. For more information about OAuth Open Standard go here\nI was digging around to make a small application to notify me of new Buzzes or new comments on Buzzes, so I searched and read the API to interact with Google Buzz. In this post I’ll share my Python code that uses OAuth to authorize the application to use Google Buzz data, and soon I’ll share my application when it’s done 🙂\nThe Process The process of authentication and authorization according to OAuth consists of three steps:\nAsking Google for a Request Token. The token is bound to a scope, this scope identifies the interests of your application with the user’s data. \u0026lt;a id=\u0026quot;GoogleBuzzScopes\u0026quot;\u0026gt;\u0026lt;/a\u0026gt;Google Buzz has two scopes; Full Access scope `https://www.googleapis.com/auth/buzz` and Read Only Scope `https://www.googleapis.com/auth/buzz.readonly`, you must select the scope that suits your needs. Asking the user to authorize your needs by redirecting him/her to a page in Google’s website to log in and authorize your application. As a result the user gets a verification code that must be delivered to your application so it can continue to step 3. There are three ways of getting the verification from the user listed here. Exchanging the Request Token for an Access Token that can be used later for authorizing your requests for data. Your application should save this token to use it later, this token has unlimited expiration time, so you don’t need to bother the user with authorization more than once (Unless the user revokes the access of your application from his/her account). Prerequisites My class depends on Python-OAuth2, so you need to download and install it first. The code is written using Python 2.6. General Parameters All OAuth requests must have the following parameters:\noauth_version: Which defines the version of OAuth to use (since when writing this post there were only 1.0 and 1.0a I’ll be using 1.0). oauth_nonce: A pseudo-random number. oauth_timestamp: The timestamp when generating the request. oauth_signature_method: The signature method used to sign the base string that identifies the request, which is either HMAC-SHA1 or RSA-SHA1 (It can be PLAINTEXT but Google doesn’t support it). oauth_consumer_key and oauth_consumer_secret: The key and secret of your application, if you have registered your application then you’ll have a pair of key and secret for your application. If you don’t have a registered application you can use anonymous for both key and secret. oauth_signature: Which is generated using the chosen signature method for the base string which identifies the request So basically we’ll need to add those parameters to every request we make and we’ll have to sign the request. The former is done internally by calling __getParams, while the latter is done internally by calling __signRequest for each request.\nGetting The Request Token This request has the following parameters added to the general parameters:\noauth_callback: The URL that the user would be redirected to after authorizing your application, and when redirected the verification code is passed to this URL as a parameter along other token parameters. If you don’t have a URL or can’t redirect the user for some reasons you can use the special value oob (Out Of Bounds) so that Google redirects the user to a page in Google’s website that has the verification code inside it. scope: The scope you selected for your application from here. xoauth_displayname: The friendly name of your application that will Google will use when asking the user to authorize it. This procedure is done by sending a POST request to the following URL https://www.google.com/accounts/OAuthGetRequestToken with the previous parameters while setting the ContentType header to application/x-www-form-urlencoded.\nThe response must be Request Token data with status code HTTP 200.\nparams = self.__getParams() params.update({'oauth_callback' : self.callbackURL, 'scope' : self.defaultScope, 'xoauth_displayname' : self.applicationName}) oauthRequest = oauth.Request(method=\"POST\", url=REQUEST_TOKEN_URL, parameters=params) self.__signRequest(oauthRequest) self.connection.request('POST', REQUEST_TOKEN_URL, body=oauthRequest.to_postdata(), headers={'Content-Type': 'application/x-www-form-urlencoded'}) resp = self.connection.getresponse() if resp.status != 200: raise Exception, \"Couldn't get a Request Token, status code: %d.\" % resp.status self._token = oauth.Token.from_string(resp.read()) self.__destroyConnection() This method __destroyConnection is used to destroy the connection because it becomes invalid after a few requests.\nRedirecting The User To Authorization Page Here we’ll have to know what is the URL of the page to redirect the user to, and that’s done by sending a GET request to the following URL https://www.google.com/buzz/api/auth/OAuthAuthorizeToken with the following parameters:\noauth_token: The key of the Request Token received in the previous step. scope: Described earlier. domain: The domain that your application uses, this is used for web applications, you must set it to anonymous for desktop applications. xoauth_displayname: Described earlier. The response would be a page with HTTP 302 status code, this page contains the URL to redirect the user to in the location header.\nself.connection.request('GET', AUTHORIZE_TOKEN_URL + '?oauth_token=' + self.token.key + '\u0026scope=' + self.defaultScope + '\u0026domain=anonymous' + '\u0026' + urllib.urlencode({'xoauth_displayname' : self.applicationName}).replace('+', '%20')) resp = self.connection.getresponse() if resp.status != 302: raise Exception, \"Couldn't authorize the token, status code: %d.\" % resp.status url = resp.getheader('location') webbrowser.open(url) self.__destroyConnection() This method webbrowser.open is used to open the URL in the web browser of the user, it is -obviously- contained in the webbrowser Python standard module.\nAs a result of the authorization Google gives you (or the user) the verification code for the token, after acquiring it (automatically or by asking the user to give it to your application somehow) we give it to the token by calling setTokenVerifier method.\nExchanging The Request Token For The Access Token This request has the following parameters added to the general parameters:\noauth_token: Described earlier. oauth_verifier: The verification code acquired from the previous step. This procedure is done by sending a POST request with the previous parameters to the following URL https://www.google.com/accounts/OAuthGetAccessToken.\nThe result is the Access Token data in a page with HTTP 200 status code.\nparams = self.__getParams() params.update({ 'oauth_token' : self.token.key, 'oauth_verifier' : self.token.verifier }) oauthRequest = oauth.Request(method=\"POST\", url=ACCESS_TOKEN_URL, parameters=params) self.__signRequest(oauthRequest) self.connection.request('POST', ACCESS_TOKEN_URL, body=oauthRequest.to_postdata(), headers={'Content-Type': 'application/x-www-form-urlencoded'}) resp = self.connection.getresponse() if resp.status != 200: raise Exception, \"Couldn't exchange the token with an Access Token, status code: %d.\\nMessage: %s\" % (resp.status, resp.read()) self._token = oauth.Token.from_string(resp.read()) self.__destroyConnection() Authorizing Requests Authorizing your requests for data is done by adding Authorization header to your request which includes the OAuth parameters along with the Access Token data, and by setting the ContentType header to either application/json or application/atom+xml:\nparams = self.__getParams() params.update({ 'oauth_token' : self.token.key, }) oauthRequest = oauth.Request(method=method, url=url, parameters=params) self.__signRequest(oauthRequest) if isJSON: headers = {'Content-Type': 'application/json'} else: headers = {'Content-Type': 'application/atom+xml'} headers.update(oauthRequest.to_header()) self.connection.request(method, url, body=body, headers=headers) resp = self.connection.getresponse() data = resp.read() self.__destroyConnection() return resp.status, data Example On Using BuzzOAuth Class This example uses the BuzzOAuth class to get the list of Buzzes for the user to read (The list of his/her friends’ Buzzes).\nfrom BuzzOAuth import BuzzOAuth boauth = BuzzOAuth() boauth.requestToken() boauth.authorizeToken() boauth.setTokenVerifier(raw_input('Enter the verifier please: ')) boauth.convertToAccessToken() boauth.saveTokenToFile() status, data = boauth.request('GET', 'https://www.googleapis.com/buzz/v1/activities/@me/@consumption?alt=json') print status print \"\" print data The method request uses the Access Token to do the request passed to it and returns a tuple of the status code and data returned by the request.\nIn line 8 the call for method saveTokenToFile saves the Access Token to a binary file called token.tok by default, so that the application can later just use this token like this:\nfrom BuzzOAuth import BuzzOAuth boauth = BuzzOAuth() boauth.loadTokenFromFile() status, data = boauth.request('GET', 'https://www.googleapis.com/buzz/v1/activities/@me/@consumption?alt=json') print status print \"\" print data Download You can download this class (BuzzOAuth.py) from here: http://www.box.net/shared/2m9srr12z7\nLicense This work is licensed under the GNU Public License (GPL). To view a copy of this license, visit http://www.gnu.org/copyleft/gpl.html.\n","permalink":"https://mpcabd.xyz/google-buzz-oauth-and-python/","summary":"\u003cp\u003e\u003ca href=\"http://www.google.com/buzz\"\u003eGoogle Buzz\u003c/a\u003e is a social networking and messaging tool from Google Inc. that’s integrated into \u003ca href=\"http://www.gmail.com\"\u003eGMail\u003c/a\u003e. Google Buzz was released in early February this year (9th Feb 2010), and since then it has emerged as an important social network for GMail users, and many people (including me) prefer it now to other social networking platforms such as \u003ca href=\"http://www.facebook.com\"\u003eFacebook\u003c/a\u003e.\u003c/p\u003e\n\u003cfigure id=\"attachment_268\" style=\"width: 145px\" class=\"wp-caption alignleft\"\u003e\u003ca href=\"http://mpcabd.xyz/wp-content/uploads/2010/09/GoogleBuzzOAuthPython.png\" rel=\"lightbox[264]\" title=\"Logos of Google Buzz, OAuth And Python\"\u003e\u003cimg src=\"http://mpcabd.xyz/wp-content/uploads/2010/09/GoogleBuzzOAuthPython.png\" alt=\"Logos of Google Buzz, OAuth And Python\" title=\"Logos of Google Buzz, OAuth And Python\" width=\"145\" height=\"150\" class=\"size-full wp-image-268\" /\u003e\u003c/a\u003e\u003cfigcaption class=\"wp-caption-text\"\u003eLogos of Google Buzz, OAuth And Python\u003c/figcaption\u003e\u003c/figure\u003e\n\u003cp\u003eIn May Google revealed the \u003ca href=\"http://code.google.com/apis/buzz/docs/\"\u003eBuzz API\u003c/a\u003e to the public so developers around the world could write applications to interact with Google Buzz to read and/or write.\u003c/p\u003e","title":"Google Buzz, OAuth And Python"},{"content":"I\u0026rsquo;m Abdullah Diab, an Engineering Manager, based in Dubai, UAE, with over 20 years of experience in software engineering and technical leadership. Originally from Damascus, Syria, I hold a Bachelor\u0026rsquo;s degree in Software Engineering from Damascus University and have built and led engineering teams across Syria, Dubai, London, and Amsterdam, and worked in startups, SMEs, and big tech companies.\nI\u0026rsquo;m also an active open-source contributor, best known for Python Arabic Reshaper, a widely used library for rendering Arabic text correctly, along with other projects over the years. I\u0026rsquo;m fluent in Arabic, English, and Dutch.\nThis blog is where I occasionally write about software engineering, open source, tech, Islam, and other things I\u0026rsquo;ve learned along the way.\nHappy to have you here reading this.\n","permalink":"https://mpcabd.xyz/about-me/","summary":"\u003cp\u003eI\u0026rsquo;m Abdullah Diab, an Engineering Manager, based in Dubai, UAE, with over 20 years of experience in software engineering and technical leadership. Originally from Damascus, Syria, I hold a Bachelor\u0026rsquo;s degree in Software Engineering from Damascus University and have built and led engineering teams across Syria, Dubai, London, and Amsterdam, and worked in startups, SMEs, and big tech companies.\u003c/p\u003e\n\u003cp\u003eI\u0026rsquo;m also an active open-source contributor, best known for Python Arabic Reshaper, a widely used library for rendering Arabic text correctly, along with other projects over the years. I\u0026rsquo;m fluent in Arabic, English, and Dutch.\u003c/p\u003e","title":"About Me"},{"content":"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.\nSince I know that Google Talk uses XMPP 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:\nThe basic idea behind status changing Since Google Talk uses XMPP 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.\nI searched to see if there were an API to communicate with Google Talk from any other program but I had no luck.\nSo the solution was to use XMPP’s Presence Priority attribute.\nIn XMPP, 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.\nProgramming it I used Java for developing the program. There is no direct reason for using Java but that’s what I used 🙂\nTo be able to use XMPP I used the Smack XMPP Library because it is simple and serves me well.\nThe whole mechanism is too simple:\nLogin. Calculate difference between now and the targeted date. Send the presence. Using Smack makes the whole process so easy.\nLogin import org.jivesoftware.smack.XMPPConnection;\rpublic void connect() {\rXMPPConnection connection = new XMPPConnection(server); //Server is gmail.com for Google Talk.\rconnection.connect();\rconnection.login(username, password); //Username and password.\r}\rCalculate difference between now and the targeted date This process is done using Java Calendar and Date objects:\nimport java.util.Calendar;\rimport java.util.Date;\r{\rCalendar calendar1 = Calendar.getInstance();\rDate d = new Date();\rcalendar1.setTime(d);\rCalendar calendar2 = Calendar.getInstance();\rcalendar2.setTime(endLine); //End line is the date we're counting to.\rlong milliseconds1 = calendar1.getTimeInMillis();\rlong milliseconds2 = calendar2.getTimeInMillis();\rlong diff = milliseconds2 - milliseconds1;\rlong diffDays = diff / (24 * 60 * 60 * 1000);\rdiff = diff % (24 * 60 * 60 * 1000);\rlong diffHours = diff / (60 * 60 * 1000);\rdiff = diff % (60 * 60 * 1000);\rlong diffMinutes = diff / (60 * 1000);\rdiff = diff % (60 * 1000);\r}\rThis code calculates the difference between the two dates in days, hours and minutes.\nSend the presence After calculating the difference all we have to do is to send the presence:\nimport org.jivesoftware.smack.packet.Presence;\r{\rString remaining = Long.toString(diffDays) + \" day(s), \" + Long.toString(diffHours) + \" hour(s), \" + Long.toString(diffMinutes) + \" minute(s) \" + message; //Message is usually: Until \"something\".\rPresence presence = new Presence(Presence.Type.available);\rpresence.setStatus(remaining);\rpresence.setPriority(24); //Highest priority in Google Talk\rpresence.setMode(presenceMode); //This is one of XMPP modes (Available, Chat, DND, Away, XA).\rconnection.sendPacket(presence);\r}\rAfter 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 ;)).\nTesting Last note 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.\nAnd BTW, you can use this program with any XMPP account, not just Google Talk. And it’s cross platform 😉\nDownload Google Talk Status Countdown on GitHub\nSmack library is attached to the files already, no need to download it separately.\nSource Code Executable Jar File Hope you use it 🙂\n","permalink":"https://mpcabd.xyz/google-talk-status-countdown/","summary":"\u003cp\u003eA 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.\u003c/p\u003e\n\u003cp\u003eSince I know that Google Talk uses \u003ca href=\"http://www.xmpp.org\"\u003eXMPP\u003c/a\u003e 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:\u003c/p\u003e\n\u003cp\u003e\u003ca href=\"http://mpcabd.xyz/wp-content/uploads/2010/05/XMPPStatusChanger.png\" rel=\"lightbox[231]\" title=\"XMPP Status Changer\"\u003e\u003cimg 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\" /\u003e\u003c/a\u003e\u003c/p\u003e","title":"Google Talk Status Countdown"},{"content":"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.\nWhile I was working on iCommunity website, 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.\nI searched the internet and found a solution that’s working.\nAfter trying it I decided to try developing a module for doing that (just like the author of the solution suggested).\nI’m a newbie in developing for Drupal but I knew how to dig my way through it 😀\n(You’d be shocked if you knew that I don’t know PHP 😛 I just write code!)\nSo 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 🙂\nI named the module Taxonomy subterms. 😀\nSo the process is just re-implement the function ‘theme_taxonomy_term_page’ from taxonomy module, but to override it I needed to let Drupal call the function in my module when the user requests ‘/taxonomy/term/’ so to do that I needed to add the ‘hook_menu’ function.\nfunction taxonomy_subterms_menu() { $items['taxonomy/term/%'] = array(\r'title' =\u0026gt; 'Taxonomy term',\r'page callback' =\u0026gt; 'taxonomy_subterms_term_page',\r'page arguments' =\u0026gt; array(2),\r'access arguments' =\u0026gt; array('access content'),\r'type' =\u0026gt; MENU_CALLBACK,\r);\rreturn $items;\r}\rBut 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’\nThen I re-implemented the ‘theme_taxonomy_term_page’ function so I can add the sub-terms section (just like the solution I mentioned did):\nfunction theme_taxonomy_term_page($tids, $result) {\rdrupal_add_css(drupal_get_path('module', 'taxonomy') . '/taxonomy.css');\rdrupal_add_css(drupal_get_path('module', 'taxonomy_subterms') . '/taxonomy_subterms.css');\r$output = '';\r// Only display the description if we have a single term, to avoid clutter and confusion.\rif (count($tids) == 1) {\r$term = taxonomy_get_term($tids[0]);\r$children = taxonomy_get_children($tids[0]);\r$description = $term-\u0026gt;description;\rif (!empty($description) || sizeof($children) \u0026gt; 0) {\r$output .= '\u0026lt;div class=\"taxonomy-details-wrapper\"\u0026gt;';\r$is_wrapped = true;\r} else {\r$is_wrapped = false;\r}\r// Check that a description is set.\rif (!empty($description)) {\r$output .= '\u0026lt;div class=\"taxonomy-term-description\"\u0026gt;';\r$output .= filter_xss_admin($description);\r$output .= '\u0026lt;/div\u0026gt;';\r}\rif (sizeof($children) \u0026gt; 0) {\r$output .= '\u0026lt;div class=\"sub-terms-list\"\u0026gt;\u0026lt;h3\u0026gt;' . t('Sub-Terms:') . '\u0026lt;/h3\u0026gt; \u0026lt;ul class=\"sub-terms inline\"\u0026gt;';\rforeach($children as $child) {\r$output .= '\u0026lt;li\u0026gt;' . l($child-\u0026gt;name, taxonomy_term_path($child)) . '\u0026lt;/li\u0026gt;';\r}\r$output .= '\u0026lt;/ul\u0026gt;\u0026lt;/div\u0026gt;';\r}\rif ($is_wrapped) {\r$output .= '\u0026lt;/div\u0026gt;';\r}\r}\r$output .= taxonomy_render_nodes($result);\rreturn $output;\r}\rThen I had my module working and installed it in the website (you can check it out here. The page is in Arabic but you can easily find the sub terms).\nDownload You can download the module here (I didn’t maintain a project @ Drupal because I’m not yet ready to do that, this is just a small experiment).\n","permalink":"https://mpcabd.xyz/display-sub-terms-in-drupal-term-page/","summary":"\u003cp\u003eAfter 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.\u003c/p\u003e\n\u003cp\u003eWhile I was working on \u003ca href=\"http://www.communityi.net\"\u003eiCommunity website\u003c/a\u003e, 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.\u003c/p\u003e","title":"Display Sub-terms In Drupal Term Page"},{"content":"As I said in my previous post, I’m working on upgrading Computer Science in Syria website to Drupal 6.\nI 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)\nI used Simple Modal by Eric Martin to display the preview in a model instead of a new page.\nThe code is easy too like the previous post’s code, I edited also the drupal.js file and added the following code:\nif (location.pathname.match('^' + Drupal.settings.basePath + 'node/\\\\d')) {\r$('#edit-preview').click(function () {\r$.modal('\u0026lt;div\u0026gt;\u0026lt;h1\u0026gt;Preview\u0026lt;/h1\u0026gt;\u0026lt;div id=\"previewContent\"\u0026gt;\u0026lt;img style=\"width: 126px; height: 22px;\" class=\"previewing\" src=\"' + Drupal.settings.basePath + 'misc/previewing.gif\" alt=\"Loading ...\" /\u0026gt;\u0026lt;/div\u0026gt;\u0026lt;/div\u0026gt;');\rvar comment = $('#edit-comment').val();\rif ($('#wysiwyg-toggle-edit-comment').text() == Drupal.settings.wysiwyg.disable) {\r$('#wysiwyg-toggle-edit-comment').click();\rcomment = $('#edit-comment').val();\r$('#wysiwyg-toggle-edit-comment').click();\r}\r$.post(\r$('form#comment-form').attr('action'),\r{\r'comment' : comment,\r'form_build_id' : $('form#comment-form input[name=\"form_build_id\"]').val(),\r'form_id' : 'comment_form',\r'form_token' : $('form#comment-form input[name=\"form_token\"]').val(),\r'op' : $('form#comment-form input#edit-preview').val(),\r},\rfunction (html) {\r$('div#previewContent img').remove();\r$('div#previewContent').append($(html).children().find('div.preview div.content').html());\r$('form#comment-form input[name=\"form_token\"]').val($(html).children().find('form#comment-form input[name=\"form_token\"]').val());\r$('form#comment-form input[name=\"form_build_id\"]').val($(html).children().find('form#comment-form input[name=\"form_build_id\"]').val());\r}\r);\rreturn false;\r});\r}\rThe process is too simple:\n@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. @line 03: I show the user a modal with a loading image @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. @lines 10~18: I gather the data of the form and post them. @line 20: I remove the loading image. @line 21: I append the HTML data from the response to the modal content. @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. @line 26: I return false so the browser doesn’t post the data again to the new page. Here is an example:\nSimple 😉\n","permalink":"https://mpcabd.xyz/simple-ajax-comment-preview-in-drupal-6/","summary":"\u003cp\u003eAs I said in my previous post, I’m working on upgrading \u003ca href=\"http://www.csc-sy.net\"\u003eComputer Science in Syria\u003c/a\u003e website to Drupal 6.\u003c/p\u003e\n\u003cp\u003eI 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)\u003c/p\u003e","title":"Simple AJAX Comment Preview in Drupal 6"},{"content":"I’ve been upgrading the forum of Computer Science in Syria for a week now.\nThe forum uses Drupal, and it ran a beta version of Drupal 4, and I upgraded it to the latest Drupal version now.\nI 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)\nThe 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 jQuery loaded in it 🙂\nI added the following code to /misc/drupal.js file:\n$('a.quote, li.quote a').click(function () {\r$(this).after($('\u0026nbsp;\u0026lt;img style=\"width: 16px; height: 16px;\" class=\"quoting\" src=\"/misc/quoting.gif\" alt=\"loading\" /\u0026gt;'));\r$.ajax({\rurl: $(this).attr('href'),\rcache: false,\rsuccess: function(html){\r$('img.quoting').remove();\rvar changed = false;\rif ($('#wysiwyg-toggle-edit-comment').text() == Drupal.settings.wysiwyg.disable) {\r$('#wysiwyg-toggle-edit-comment').click();\rchanged = true;\r}\r$('#edit-comment').val($('#edit-comment').val() + ($('#edit-comment').val() == '' ? '' : '\\n') + $(html).children().find('#edit-comment').val());\rvar $target = $('#edit-comment');\r$target = $target.length \u0026\u0026 $target || $('[name=' + this.hash.slice(1) +']');\rif ($target.length) {\rvar targetOffset = $target.offset().top;\r$('html,body').animate({scrollTop: targetOffset}, 1000);\r}\rif (changed)\r$('#wysiwyg-toggle-edit-comment').click();\r$('#edit-comment').scrollTop($('#edit-comment')[0].scrollHeight);\r}\r});\rreturn false;\r});\rYou can see that I used this image to be displayed while loading the quote into the textarea because it matches the colors of the forum style.\nThe process is too simple:\n@line 02: Display a loading image. @line 03: Request the quoting page which is located in the href attribute of the quote link. @line 07: Remove the image. @lines 08 ~ 12: Checking if the HTML editor is enabled, and disabling it so I can assign the value directly to the textarea. @line 13: Assigning the value of the textarea in the quote page to the textarea in this page. @lines 14 ~ 19: Scrolling the page’s vertical scroll to reach the textarea. @lines 20 ~ 21: Re-enabling the editor if I disabled it. @line 22: Scrolling the textarea’s vertical scroll to reach the end of the text. @line 25: Returning false to the browser so it doesn’t redirect the page to the quoting page. You see? it is as simple as this 🙂\nI’ll soon post some other modifications that made the forum more simple 🙂\n","permalink":"https://mpcabd.xyz/simple-ajax-quote-in-drupal-6/","summary":"\u003cp\u003eI’ve been upgrading the forum of \u003ca href=\"http://www.csc-sy.net/\" target=\"_blank\"\u003eComputer Science in Syria\u003c/a\u003e for a week now.\u003c/p\u003e\n\u003cp\u003eThe forum uses Drupal, and it ran a beta version of Drupal 4, and I upgraded it to the latest Drupal version now.\u003c/p\u003e\n\u003cp\u003eI 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)\u003c/p\u003e","title":"Simple AJAX Quote in Drupal 6"},{"content":"I use Python everyday, it has become my first tool to use when I need to do anything. In Arabic (in Syrian Arabic specifically) I’d say that Python has become my hand and leg 😛\nYesterday 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 😉\nI 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 Run In Python command in it?”. So as usual I got pissed off and decided to create my own plugin to have that command in Notepad++ 8)\nThe Reference I searched on the net, I found this Notepad++ Plugin Template, I edited it a little bit and I managed to do it 🙂\nYou can read below about the process and how it works, but if you just came here to download it click here.\nThe Process To run a Python script; the plugin must do the following:\nGet the path of the selected file in Notepad++. Get the path of Python executable file, since not everyone has Python in the PATH environment variable. Building the run command. Execute the run command. Get The Path of The Selected File In Notepad++ I also searched the net and found the following code:\nstd::wstring getCurrentFile(bool \u0026ok)\r{\rLRESULT result = ::SendMessage(nppData._nppHandle, NPPM_SAVECURRENTFILE, 0, 0);\rTCHAR path[MAX_PATH];\r::SendMessage(nppData._nppHandle, NPPM_GETFULLCURRENTPATH, MAX_PATH, (LPARAM)path);\rstd::wstring wPath(path);\rif (result == 0) {\rok = false;\rfor (int i = 0; i \u0026lt; wPath.length() \u0026\u0026 !ok; i++)\rif (wPath[i] == '\\\\')\rok = true;\r}\relse\rok = true;\rreturn wPath;\r}\rThe 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.\nThen the function sends a message to Notepad++ asking it to put the full path of the currently selected file into a specific variable.\nNow 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.\nWhen 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.\nGet The Path Of Python Executable File 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.\nbool pythonExists(std::wstring foldername) {\rstd::wstring path = L\"C:\\\\\";\rpath += foldername;\rpath += L\"\\\\python.exe\";\rWIN32_FIND_DATA data;\rHANDLE h = FindFirstFile(const_cast\u0026lt;LPCWSTR\u0026gt;(path.c_str()), \u0026data);\rreturn (h != INVALID_HANDLE_VALUE);\r}\r//This code will be run before the plugin calls the function 'getPythonLocation'\rstd::wstring pythonLoc = L\"\";\rbool pythonInstalled = false;\rWIN32_FIND_DATA data;\rHANDLE h = FindFirstFile(L\"c:\\\\python*\", \u0026data);\rif( h != INVALID_HANDLE_VALUE ) {\rdo {\rif (!(data.dwFileAttributes \u0026 FILE_ATTRIBUTE_DIRECTORY))\rcontinue;\rchar* nPtr = new char [lstrlen( data.cFileName ) + 1];\rfor( int i = 0; i \u0026lt; lstrlen( data.cFileName ); i++ )\rnPtr[i] = char( data.cFileName[i] );\rnPtr[lstrlen( data.cFileName )] = '\u0026#92;\u0026#48;';\rif (pythonExists(const_cast\u0026lt;LPWSTR\u0026gt;(data.cFileName)))\r{\rpythonLoc = L\"C:\\\\\";\rpythonLoc += const_cast\u0026lt;LPWSTR\u0026gt;(data.cFileName);\rpythonLoc += L\"\\\\\";\rpythonInstalled = true;\rbreak;\r}\r} while (FindNextFile(h, \u0026data));\r}\rThe Python installation path exists in the Windows Registry, so I wrote a small function to search the registry for the path and return it:\nbool getPythonLocationFromRegistry(std::wstring \u0026loc, HKEY baseKey) {\r{\rHKEY hKey;\rif(RegOpenKeyEx(baseKey, TEXT(\"Software\\\\Python\\\\PythonCore\"), 0,\rKEY_READ, \u0026hKey) != ERROR_SUCCESS)\r{\rreturn false;\r}\rDWORD dwIdx=0;\rTCHAR szKeyName[1024];\rDWORD dwSize=1024;\rFILETIME fTime;\rTCHAR pyPath[MAX_PATH];\rDWORD length = MAX_PATH;\rif (RegEnumKeyEx(hKey, dwIdx, szKeyName, \u0026dwSize, NULL, NULL, NULL, \u0026fTime) == ERROR_SUCCESS)\r{\rHKEY hSubKey;\rif (RegOpenKeyEx(hKey, szKeyName, 0, KEY_READ, \u0026hSubKey) == ERROR_SUCCESS)\r{\rLONG x = RegOpenKeyEx(hSubKey, TEXT(\"InstallPath\"), 0, KEY_READ, \u0026hSubKey);\rif (x == ERROR_SUCCESS)\r{\rif(RegQueryValueEx(\rhSubKey,\rTEXT(\"\"),\rNULL,\rNULL,\r(LPBYTE)pyPath,\r\u0026length) != ERROR_SUCCESS)\r{\rreturn false;\r}\rloc = loc.append(pyPath);\rreturn true;\r}\relse\rreturn false;\r}\relse\rreturn false;\r}\relse\rreturn false;\r}\rThe code above accepts the root key as a parameter, and the code that calls it will call it twice, once with HKEY_CURRENT_USER and the other with HKEY_LOCAL_MACHINE, so it will try to find it in both locations HKEY_CURRENT_USER\\Software\\Python\\PythonCore and HKEY_LOCAL_MACHINE\\Software\\Python\\PythonCore.\nBuilding The Run Command 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 😉\nThis one would be very simple, just concatenate: Python installation path, “python.exe” and the full path of the current file.\nstd::wstring buildRunCommand(std::wstring \u0026filePath, std::wstring \u0026pypath, bool isW = false, bool isI = false)\r{\rstd::wstring command = pypath;\rcommand += TEXT(\"python\");\rif (isW)\rcommand += TEXT(\"w\");\rcommand += TEXT(\".exe \");\rif (isI)\rcommand += TEXT(\"-i \");\rcommand += TEXT(\"\\\"\");\rcommand += filePath;\rcommand += TEXT(\"\\\"\");\rreturn command;\r}\rExecute The Run Command 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.\nThis one is also simple, just create a new process with the run command.\nbool launchPython(std::wstring \u0026command, std::wstring \u0026path)\r{\rSTARTUPINFOW si;\rPROCESS_INFORMATION pi;\rmemset(\u0026si, 0, sizeof(si));\rmemset(\u0026pi, 0, sizeof(pi));\rsi.cb = sizeof(si);\rreturn CreateProcess(\rNULL,\rconst_cast\u0026lt;LPWSTR\u0026gt;(command.c_str()),\rNULL,\rNULL,\rFALSE,\rCREATE_DEFAULT_ERROR_MODE,\rNULL,\rpath.c_str(),\r\u0026si,\r\u0026pi) != 0;\r}\rScreenshot License This work is licensed under GNU General Public License v3.\nDownload PyNPP v1.2 on GitHub GitHub\nPlugin DLL: Plugin DLL\nSource Code Source Code\nUpdate History 18, April 2010: PyNPP will search for Python in its default path C:\\Python[VER]\\. 13, December 2010: PyNPP will allow the user to run the file in three modes: normal, interactive and GUI. As suggested by Andrew here. 13, December 2010: PyNPP will run the file in its folder, so it can read/write files next to it. As suggested by Andrew here. 03, January 2011: PyNPP will search for Python in both HKEY_CURRENT_USER\\Software\\Python\\PythonCore and HKEY_LOCAL_MACHINE\\Software\\Python\\PythonCore. 05, January 2011: PyNPP will save the file before trying to run it.\nFixed a bug in setting the current folder while running the process. 12, August 2011: PyNPP allows you to select the Python folder using an options dialog. As suggested by Hönes here. 21, December 2011: PyNPP moved to GitHub. 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. 30, March 2015: v1.2 released, PyNPP supports debugging the file with PDB. As suggested by fdufnews. ","permalink":"https://mpcabd.xyz/notepad-plugin-to-run-python-scripts/","summary":"\u003cp\u003eI use Python everyday, it has become my first tool to use when I need to do anything. In Arabic (in \u003ca href=\"http://en.wikipedia.org/wiki/Syria\" target=\"_blank\"\u003eSyrian\u003c/a\u003e Arabic specifically) I’d say that Python has become my hand and leg 😛\u003c/p\u003e\n\u003cp\u003eYesterday 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 😉\u003c/p\u003e\n\u003cp\u003eI 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 \u003cem\u003eRun In Python\u003c/em\u003e command in it?”. So as usual I got pissed off and decided to create my own plugin to have that command in Notepad++ 8)\u003c/p\u003e","title":"Notepad++ Plugin To Run Python Scripts"},{"content":"What is brainfuck? Brainfuck is a programming language\nThis is the definition from Wikipedia:\nThe brainfuck programming language is an esoteric programming language noted for its extreme minimalism. It is a Turing tarpit, designed to challenge and amuse programmers, and is not suitable for practical use. Its name has been variously bowdlerized. The name of the language is generally not capitalized, although it is a proper noun.\nThis programming language is very easy to learn, very hard to do work with. As the Wikipedia article describes it; the language is an esoteric language, which means it was created for fun I discovered the language while I was reading an article about writing the perfect settings file for Django. The author used DPaste website to link to pieces of code. DPaste website says that it uses Pygments for syntax highlighting. Pygments say that their syntax highlighter even supports brainfuck. And that’s how I got to brainfuck After I read articles about the language I wanted to test some code of it, I found some online interpreters, but I wanted to test some code on my machine. I found a compiler 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 Brainfuck in simple description The language consists of 8 symbols \u0026lt; \u0026gt; . , + – [ ]\nThe language deals with a 30,000 bytes array, at the start of the application all the items of that array are zeros.\nThe symbols can just deal with a pointer on that array to do specific jobs.\nPLY I mentioned in a previous post 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.\nSince I’m a Python-Lover I searched for Python lexer and parser tools, and I came across the great PLY.\nPLY (Python Lex-Yacc) is an implementation of lex and yacc parsing tools for Python.\nThe usage of PLY is not the target of this post.\nWriting a lexer for brainfuck The lexer would be so simple, since the language only has 8 symbols, and capturing them requires almost nothing.\nThe lexer file is the following\nimport ply.lex as lex\rtokens = [\r'GoLeft',\r'GoRight',\r'Print',\r'Read',\r'Increase',\r'Decrease',\r'WhileStart',\r'WhileEnd'\r]\rt_GoLeft = r'\\\u0026lt;'\rt_GoRight = r'\\\u0026gt;;'\rt_Print = r'\\.'\rt_Read = r','\rt_Increase = r'\\+'\rt_Decrease = r'\\-'\rt_WhileStart = r'\\['\rt_WhileEnd = r'\\]'\rdef t_error(t):\rt.lexer.skip(1)\rlexer = lex.lex()\rif __name__ == \"__main__\":\rlex.runmain()\rIt simply captures the symbols of the language and ignores any other symbol. Simple isn’t it 🙂\nWriting a parser for brainfuck 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.\nThe parser will ask the lexer to capture the symbols, while the parser will be responsible for making instructions from symbols.\nSparse matrix 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 Sparse Matrix.\nImplementing a simple sparse matrix is nothing more than a dictionary:\nclass sparseMatrix:\rdef __init__(self):\rself.dict = {}\rdef __getitem__(self, index):\rif self.dict.has_key(index):\rreturn self.dict[index]\relse:\rreturn 0\rdef __setitem__(self, index, value):\rself.dict[index] = value\rBuilding the tree 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.\nWhile 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.\ndef p_start(p):\r\"\"\"\rstart : code\r| empty\r\"\"\"\rif p[1]:\rexecuteStatements(p[1])\rdef p_empty(p):\r'empty : '\rpass\rdef p_code(p):\r\"\"\"\rcode : code statement\r| code whilestatement\r| statement\r| whilestatement\r\"\"\"\rif len(p) == 2:\rp[0] = [p[1]]\relse:\rp[0] = p[1][:]\rp[0].extend([p[2]])\rdef p_statement(p):\r\"\"\"\rstatement : GoLeft\r| GoRight\r| Print\r| Read\r| Increase\r| Decrease\r\"\"\"\rif p[1] == '\u0026lt;':\rp[0] = ('GoLeft', None)\relif p[1] == '\u0026gt;':\rp[0] = ('GoRight', None)\relif p[1] == '.':\rp[0] = ('Print', None)\relif p[1] == ',':\rp[0] = ('Read', None)\relif p[1] == '+':\rp[0] = ('Increase', None)\relif p[1] == '-':\rp[0] = ('Decrease', None)\rdef p_whilestatement(p):\r'whilestatement : WhileStart code WhileEnd'\rp[0] = ('While', p[2])\rExecuting the tree 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.\nSo I wrote a method to execute a list of tree elements and it can execute while loops using recursive calling to itself.\nThe 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.\ndef executeStatements(tuplesList):\rglobal matrix\rglobal index\rglobal MAX_INDEX\rfor node in tuplesList:\rif node[0] == 'GoLeft':\rif index \u0026gt; 0:\rindex -= 1\relse:\rraise Exception, \"Index out of array bounds!\"\relif node[0] == 'GoRight':\rif index \u0026lt; MAX_INDEX:\rindex += 1\relse:\rraise Exception, \"Index out of array bounds!\"\relif node[0] == 'Print':\rprint(chr(matrix[index]), sep='', end='')\relif node[0] == 'Read':\rmatrix[index] = ord(raw_input()[0])\relif node[0] == 'Increase':\rmatrix[index] += 1\relif node[0] == 'Decrease':\rmatrix[index] -= 1\relif node[0] == 'While':\rwhile matrix[index] != 0:\rexecuteStatements(node[1])\rTesting the interpreter After running the interpreter, I tried the Hello World example in Wikipedia and I got the result:\nBrainFuck\u0026gt; ++++++++++[\u0026gt;+++++++\u0026gt;++++++++++\u0026gt;+++\u0026gt;+\u0026lt;\u0026lt;\u0026lt;\u0026lt;-]\u0026gt;++.\u0026gt;+.+++++++..+++.\u0026gt;++.\u0026lt;\u0026lt;+++++++++++++++.\u0026gt;.+++.------.--------.\u0026gt;+.\u0026gt;.\rHello World!\rBrainFuck\u0026gt;\rDownload source code You can download and test the interpreter from here.\n","permalink":"https://mpcabd.xyz/brainfuck-python-interpreter/","summary":"\u003ch1 id=\"what-is-brainfuck\"\u003eWhat is brainfuck?\u003c/h1\u003e\n\u003cp\u003eBrainfuck is a programming language\u003cimg loading=\"lazy\" src=\"http://www.zu14.cn/coolemotion/emotions/zz_8.gif\"\u003e\u003c/p\u003e\n\u003cp\u003eThis is the definition from \u003ca href=\"http://en.wikipedia.org/wiki/Brainfuck\" target=\"_blank\"\u003eWikipedia\u003c/a\u003e:\u003c/p\u003e\n\u003cblockquote\u003e\n\u003cp\u003eThe \u003cstrong\u003ebrainfuck\u003c/strong\u003e programming language is an \u003ca href=\"http://en.wikipedia.org/wiki/Esoteric_programming_language\"\u003eesoteric programming language\u003c/a\u003e noted for its extreme minimalism. It is a \u003ca href=\"http://en.wikipedia.org/wiki/Turing_tarpit\"\u003eTuring tarpit\u003c/a\u003e, designed to challenge and amuse \u003ca href=\"http://en.wikipedia.org/wiki/Programmer\"\u003eprogrammers\u003c/a\u003e, and is not suitable for practical use. Its name has been variously \u003ca href=\"http://en.wikipedia.org/wiki/Expurgation\"\u003ebowdlerized\u003c/a\u003e. The name of the language is generally not capitalized, although it is a \u003ca href=\"http://en.wikipedia.org/wiki/Proper_noun\"\u003eproper noun\u003c/a\u003e.\u003c/p\u003e\n\u003c/blockquote\u003e\n\u003cp\u003eThis programming language is very easy to learn, very hard to do work with. As the \u003ca href=\"http://en.wikipedia.org/wiki/Brainfuck\" target=\"_blank\"\u003eWikipedia article\u003c/a\u003e describes it; the language is an esoteric language, which means it was created for fun \u003cimg loading=\"lazy\" src=\"http://www.zu14.cn/coolemotion/emotions/zz_14.gif\"\u003e\u003c/p\u003e\n\u003cp\u003eI discovered the language while I was reading an article about \u003ca href=\"http://blog.damonjablons.com/2009/10/15/the-perfect-django-settings-file/\" target=\"_blank\"\u003ewriting the perfect settings file for Django\u003c/a\u003e. The author used \u003ca href=\"http://dpaste.com/\" target=\"_blank\"\u003eDPaste\u003c/a\u003e website to link to pieces of code. DPaste website says that it uses \u003ca href=\"http://pygments.org/\" target=\"_blank\"\u003ePygments\u003c/a\u003e for syntax highlighting. Pygments say that their syntax highlighter even supports \u003ca href=\"http://www.muppetlabs.com/~breadbox/bf/\" target=\"_blank\"\u003ebrainfuck\u003c/a\u003e. And that’s how I got to brainfuck \u003cimg loading=\"lazy\" src=\"http://www.zu14.cn/coolemotion/emotions/zz_2.gif\"\u003e\u003c/p\u003e\n\u003cp\u003eAfter I read articles about the language I wanted to test some code of it, I found some \u003ca href=\"http://koti.mbnet.fi/villes/php/bf.php\" target=\"_blank\"\u003eonline interpreters\u003c/a\u003e, but I wanted to test some code on my machine. I found a \u003ca href=\"http://home.arcor.de/partusch/html_en/bfd.html\" target=\"_blank\"\u003ecompiler\u003c/a\u003e 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 \u003cimg loading=\"lazy\" src=\"http://www.zu14.cn/coolemotion/emotions/zz_3.gif\"\u003e\u003c/p\u003e","title":"Brainfuck Python Interpreter"},{"content":"In my faculty – Informatics Engineering, Damascus University -, in the 4th year of Software Engineering Department, we have to build a compiler :shock:.\nI 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++.\nThe first two phases of implementing a compiler are: building a lexer (tokenizer) and building a parser. The lexer is implemented using GNU Flex while the parser is implemented using GNU Bison.\nThe Problem The first problem I faced when starting the project was to tell NetBeans how to handle the lex file:\nThe lex file must be passed to the flex tool to generate a C++ code file.\nThe second problem was that when the code file is generated it contains errors:\n#ifdef __cplusplus\r#include \u0026lt;stdlib.h\u0026gt;\rclass istream;\r#include \u0026lt;unistd.h\u0026gt;\rWhen 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).\nThe first problem: Binding NetBeans with Flex From NetBeans –\u0026gt; Projects Side Tab –\u0026gt; right click on the lex file –\u0026gt; Properties:\nCategories –\u0026gt; General:\nUncheck “Excluded From Build”.\nSelect “Custom Build Tool” in the Tool drop down list.\nCategories –\u0026gt; Custom Build Step:\nEnter in the Command Line field: flex lex.l Assuming that your lex file is called lex.l\nEnter in the Outputs field: lex.yy.cc\nEnter in the Description: Running Flex …\nPress Ok.\nNow when you compile the solution your lex file will be passed the the flex tool.\nThe second problem: Fixing the error 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:\nAssuming that the output file of the lex file is called lex.yy.cc:\nf = open('lex.yy.cc')\rlines = f.readlines()\ri = 0\rfor i in range(len(lines)):\rif lines[i] == 'class istream;\\n':\rbreak;\relse:\rreturn;\rlines[i] = '#include \u0026lt;iostream\u0026gt;\\n'\rlines.insert(i + 1, 'using namespace std;\\n')\rf.close()\rf = open('lex.yy.cc', 'w')\rf.writelines(lines)\rf.close()\rThe script is easy, it opens the file, changes the line from “class istream;” to “#include ”, inserts “using namespace std;” next.\nPut the file next to your sources and run it after the build process to fix the error.\nFixing both problems without executing anything manually: After a while I got bored of executing the script manually and I decided that the script must be executed automatically.\nTo 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”.\nNow the fixer script is called to build the lex file, so the script must change to call the flex from the script itself:\nimport os\ros.system(\"flex token.l\")\rf = open('lex.yy.cc')\rlines = f.readlines()\ri = 0\rfor i in range(len(lines)):\rif lines[i] == 'class istream;\\n':\rbreak;\relse:\rreturn;\rlines[i] = '#include \u0026lt;iostream\u0026gt;\\n'\rlines.insert(i + 1, 'using namespace std;\\n')\rf.close()\rf = open('lex.yy.cc', 'w')\rf.writelines(lines)\rf.close()\rNow all my problems are solved, hope that yours will be solved too 🙂\n","permalink":"https://mpcabd.xyz/binding-netbeans-with-flex/","summary":"\u003cp\u003eIn my faculty – Informatics Engineering, Damascus University -, in the 4th year of Software Engineering Department, we have to build a compiler :shock:.\u003c/p\u003e\n\u003cp\u003eI 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++.\u003c/p\u003e\n\u003cp\u003eThe first two phases of implementing a compiler are: building a lexer (tokenizer) and building a parser. The lexer is implemented using \u003ca href=\"http://www.gnu.org/software/flex/\" target=\"_blank\"\u003eGNU Flex\u003c/a\u003e while the parser is implemented using \u003ca href=\"http://www.gnu.org/software/bison/\" target=\"_blank\"\u003eGNU Bison\u003c/a\u003e.\u003c/p\u003e\n\u003ch1 id=\"the-problem\"\u003eThe Problem\u003c/h1\u003e\n\u003cp\u003eThe first problem I faced when starting the project was to tell NetBeans how to handle the lex file:\u003c/p\u003e\n\u003cp\u003e\u003cem\u003eThe lex file must be passed to the flex tool to generate a C++ code file.\u003c/em\u003e\u003c/p\u003e\n\u003cp\u003eThe second problem was that when the code file is generated it contains errors:\u003c/p\u003e\n\u003cpre class=\"lang:c++ decode:true\"\u003e#ifdef __cplusplus\r\n\r\n#include \u0026lt;stdlib.h\u0026gt;\r\nclass istream;\r\n#include \u0026lt;unistd.h\u0026gt;\r\n\u003c/pre\u003e\n\u003cp\u003e\u003cem\u003eWhen 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).\u003c/em\u003e\u003c/p\u003e","title":"Binding NetBeans with Flex"},{"content":"I was upgrading my Django Bookmarks site, and I wanted to list the online users. I searched the internet and I found a simple method, but it doesn’t work properly. So I developed my own method.\nWhy the simple method didn’t work? 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.\nImagine the following scenario:\nThe user X logs in @ 1:00 pm.\nThe user X posts a new post @ 1:30 pm.\nThe user X comments on a previous post @ 1:35 pm.\nThe user X leaves the website @ 1:40 pm.\nThe user X comes back to the website @ 3:00 pm.\nThe user X is logged in since the session cookie has not expired yet.\nThe user X posts a new post @ 3:15 pm.\nA guest enters the website, and looks at the online users corner.\nThe 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.\nUPDATE 8th May 2013 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.\nSo what is missing here? 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.\nIn ASP .NET there is a field called LastActivityDate in the users table, and it is used for this specific mission.\nWhen to update last activity date? In ASP .NET you have to update the last activity manually, and there is a good way to do it; in global.asax:\nprivate void Application_AuthenticateRequest(Object source, EventArgs e) {\r//Your Code Goes Here\r}\rIn this method you can access the request, get the current user, update his/her last activity date.\nSo basically updating last activity date is done on the request, when the user makes a request to your application and he/she is authenticated.\nBut there is no last activity date in Django’s user model? 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.\nAnd where am I going to write the code that will update the last activity date? In Django we have Middleware; a Middleware is a layer that handles something on each request, its input is the request and it can process it or modify it.\nSo I simply created a new Middleware that takes the request and finds the user, then updates his/her last activity.\nI installed the middleware in the settings module, I appended its name after ‘django.contrib.auth.middleware.AuthenticationMiddleware’ in MIDDLEWARE_CLASSES.\nThere 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!\nThe 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.\nThe skip list will contain regular expressions just like the url_patterns dictionary.\nMaking the solution generic I wanted to publish this solution, and it had to be generic so you can use it without editing its code.\nMaking it generic required small modifications:\nMaking a new application called lastActivityDate.\nPasting the extended user model inside models.py.\nModifying the settings module and add lastActivityDate to the INSTALLED_APPS list.\nExtending the user module from django.db import models\rfrom django.contrib.auth.models import User\rfrom datetime import datetime\rclass UserActivity(models.Model):\rlast_activity_ip = models.IPAddressField()\rlast_activity_date = models.DateTimeField(default = datetime(1950, 1, 1))\ruser = models.OneToOneField(User, primary_key=True)\rSince the User and UserActivity models are now related one-to-one we can now type:\na = User.objects.get(username__exact='mpcabd')\rprint a.useractivity.last_activity_ip\rb = UserActivity.objects.get(user=a)\rprint b.user.username\rThe Middleware from models import UserActivity\rfrom datetime import datetime\rfrom django.conf import settings\rfrom django.contrib.sites.models import Site\rimport re\rcompiledLists = {}\rclass LastActivityMiddleware(object):\rdef process_request(self, request):\rif not request.user.is_authenticated():\rreturn\rurlsModule = __import__(settings.ROOT_URLCONF, {}, {}, [''])\rskipList = getattr(urlsModule, 'skip_last_activity_date', None)\rskippedPath = request.path\rif skippedPath.startswith('/'):\rskippedPath = skippedPath[1:]\rif skipList is not None:\rfor expression in skipList:\rcompiledVersion = None\rif not compiledLists.has_key(expression):\rcompiledLists[expression] = re.compile(expression)\rcompiledVersion = compiledLists[expression]\rif compiledVersion.search(skippedPath):\rreturn\ractivity = None\rtry:\ractivity = request.user.useractivity\rexcept:\ractivity = UserActivity()\ractivity.user = request.user\ractivity.last_activity_date = datetime.now()\ractivity.last_activity_ip = request.META['REMOTE_ADDR']\ractivity.save()\rreturn\ractivity.last_activity_date = datetime.now()\ractivity.last_activity_ip = request.META['REMOTE_ADDR']\ractivity.save()\rThe compiled list is for enhancing performance, each regular expression is compiled one time; when it is accessed the first time.\nYou 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.\nIn 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.\nIn 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.\nModifying the URLs module In the urls.py file insert the following code:\nskip_last_activity_date = [\r#Your expressions go here\r]\rModifying the settings module In the settings.py file insert the following code:\n#Your settings code\rMIDDLEWARE_CLASSES = (\r#Your middleware classes go here\r'django.contrib.sessions.middleware.SessionMiddleware',\r'django.contrib.auth.middleware.AuthenticationMiddleware',\r'lastActivityDate.LastActivityMiddleware.LastActivityMiddleware',\r#Your middleware classes go here\r)\r#Your settings code\rINSTALLED_APPS = (\r#Your installed apps\r'YOUR_APP_FOLDER.lastActivityDate',\r#Your installed apps\r)\r#Your settings code\rReplace YOUR_APP_FOLDER with the folder of your application, such that the directory tree is like this:\nYourAppFolder:\r--\u0026gt; appFolder\r--\u0026gt; …\r--\u0026gt; __init__.py\r--\u0026gt; views.py\r--\u0026gt; models.py\r--\u0026gt; …\r--\u0026gt; lastActivityDate\r--\u0026gt; __init__.py\r--\u0026gt; LastActivityMiddleware.py\r--\u0026gt; models.py\r--\u0026gt; urls.py\r--\u0026gt; settings.py\r--\u0026gt; __init__.py\r--\u0026gt; manage.py\rP.S. Do not forget to synchronize the database using “manage.py syncdb” so that Django creates the lastactivitydate_useractivity table in the database.\nGetting online users After this long trip here is how to get online users:\nfrom django.contrib.auth.models import User\rfrom datetime import datetime, timedelta\rfrom lastActivityDate.models import UserActivity\rdef get_online_users(num):\rfifteen_minutes = datetime.now() - timedelta(minutes=15)\rsql_datetime = datetime.strftime(fifteen_minutes, '%Y-%m-%d %H:%M:%S')\rusers = UserActivity.objects.filter(last_activity_date__gte=sql_datetime, user__is_active__exact=1).order_by('-last_activity_date')[:num]\rreturn [u.user for u in users]\rThis 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.\nDownload source code Here is the link to download source code of the lastActivityDate application:\nlastActivityDate.tar.gz\nNotice that the code is written using Python 2.6 and Django 1.0. If you have different version(s) you might encounter a problem.\nLicense This work is licensed under the Creative Commons Attribution-Share Alike 3.0 License.\nTo view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/.\n","permalink":"https://mpcabd.xyz/get-online-users-in-django/","summary":"\u003cp\u003eI was upgrading my \u003ca href=\"http://mpcabd.alwaysdata.net/\" target=\"_blank\"\u003eDjango Bookmarks\u003c/a\u003e site, and I wanted to list the online users. I searched the internet and I found a \u003ca href=\"http://www.djangosnippets.org/snippets/947/\" target=\"_blank\"\u003esimple method\u003c/a\u003e, but it doesn’t work properly. So I developed my own method.\u003c/p\u003e\n\u003ch1 id=\"why-the-simple-method-didnt-work\"\u003eWhy the simple method didn’t work?\u003c/h1\u003e\n\u003cp\u003eThe 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.\u003c/p\u003e\n\u003cp\u003eImagine the following scenario:\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003e\n\u003cp\u003eThe user X logs in @ 1:00 pm.\u003c/p\u003e\n\u003c/li\u003e\n\u003cli\u003e\n\u003cp\u003eThe user X posts a new post @ 1:30 pm.\u003c/p\u003e\n\u003c/li\u003e\n\u003cli\u003e\n\u003cp\u003eThe user X comments on a previous post @ 1:35 pm.\u003c/p\u003e\n\u003c/li\u003e\n\u003cli\u003e\n\u003cp\u003eThe user X leaves the website @ 1:40 pm.\u003c/p\u003e\n\u003c/li\u003e\n\u003cli\u003e\n\u003cp\u003eThe user X comes back to the website @ 3:00 pm.\u003c/p\u003e\n\u003c/li\u003e\n\u003cli\u003e\n\u003cp\u003eThe user X is logged in since the session cookie has not expired yet.\u003c/p\u003e\n\u003c/li\u003e\n\u003cli\u003e\n\u003cp\u003eThe user X posts a new post @ 3:15 pm.\u003c/p\u003e\n\u003c/li\u003e\n\u003cli\u003e\n\u003cp\u003eA guest enters the website, and looks at the online users corner.\u003c/p\u003e\n\u003c/li\u003e\n\u003c/ul\u003e\n\u003cp\u003eThe 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.\u003c/p\u003e","title":"Get Online Users in Django"},{"content":" I'm Learning Python part 10 \u0026lt;p\u0026gt; \u0026lt;h1 style=\u0026quot;font-size:18pt;font-family:Verdana;\u0026quot;\u0026gt; (last one) \u0026lt;/h1\u0026gt; \u0026lt;p\u0026gt; \u0026lt;img src=\u0026quot;http://www.python.org/images/python-logo.gif\u0026quot; alt=\u0026quot;Python Logo\u0026quot; title=\u0026quot;Python Logo\u0026quot; /\u0026gt; \u0026lt;/div\u0026gt; \u0026lt;h1 style=\u0026quot;font-family:Georgia;\u0026quot;\u0026gt; Back to blogging \u0026lt;/h1\u0026gt; \u0026lt;p\u0026gt; As usual, I will apologize for not blogging for a long time.\u0026lt;br /\u0026gt; I have been very busy, university exams, university projects, job projects, teaching and learning. \u0026lt;/p\u0026gt; \u0026lt;h1 style=\u0026quot;font-family:Georgia;\u0026quot;\u0026gt; Python Course \u0026lt;/h1\u0026gt; \u0026lt;p\u0026gt; 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.\u0026lt;br /\u0026gt; As far as I know this course was the first Python course in Damascus University.\u0026lt;br /\u0026gt; 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.\u0026lt;br /\u0026gt; As far as I know too, students understood it and found it great, and I hope they\u0026amp;#8217;ll be using this great language more in their programs. \u0026lt;/p\u0026gt; \u0026lt;h1 style=\u0026quot;font-family:Georgia;\u0026quot;\u0026gt; Why last one? \u0026lt;/h1\u0026gt; \u0026lt;p\u0026gt; The tour with Python ends here, while it ends here it starts here too, it ends here because so far you\u0026amp;#8217;ve learned what you need to start your own path in Python. And it starts here because you\u0026amp;#8217;re fully equipped with the base tool to discover more tools, I\u0026amp;#8217;ll let you discover the standard library and 3rd-party libraries on your own, because everyone differs in his/her interests.\u0026lt;br /\u0026gt; I\u0026amp;#8217;ll be blogging more on more technical issues but they might not be I\u0026amp;#8217;m Learning Python series :).\u0026lt;br /\u0026gt; Let\u0026amp;#8217;s stop talking here and move directly to the heart of our last lesson.\u0026lt;br /\u0026gt; \u0026lt;h1 style=\u0026quot;font-family:Georgia;\u0026quot;\u0026gt; Revision \u0026lt;/h1\u0026gt; \u0026lt;p\u0026gt; The last part introduced classes, how to define them, how to use them. This lesson will continue to explain classes and functions more.\u0026lt;br /\u0026gt; Defining a function: \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:true\u0026quot;\u0026gt;\rdef functionName(param0, param1, ...):\r#Your function code goes here.\r#You can return values using:\rreturn values\r\u0026lt;p\u0026gt; Defining a class: \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:true\u0026quot;\u0026gt;\rclass ClassName(BaseClass0, BaseClass1, ...):\r#Your class code goes here.\r#Your class ends whenever you go out of the scope (you go back one tab).\r\u0026lt;p\u0026gt; The constructor of the class is defined using the special name __init__: \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:true\u0026quot;\u0026gt;\rclass A:\rdef __init__(self, param0, ...):\r#Constructor code goes here.\r\u0026lt;p\u0026gt; The method inside a class is just a function which receives the object instance as its first parameter: \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:true\u0026quot;\u0026gt;\rclass A:\rdef myMethod(self, param0, ...):\r#method is just a function\r\u0026lt;p\u0026gt; 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. \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:true\u0026quot;\u0026gt;\rclass A:\r@property\rdef Id(self):\rreturn self.__id\r@Id.setter\rdef setId(self, value):\rself.__id = value\rdef __init__(self):\rself.__id = 0\r\u0026lt;p\u0026gt; Defining an object instance of the class is done by calling the class constructor: \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:true\u0026quot;\u0026gt;\ra = A()\r\u0026lt;p\u0026gt; If the constructor takes a list of parameters you \u0026lt;b\u0026gt;might\u0026lt;/b\u0026gt; specify them when calling it:\u0026lt;br /\u0026gt;: \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:true\u0026quot;\u0026gt;\rclass B:\rdef __init__(self, name):\rself.name = name\rb = B('some name')\r\u0026lt;p\u0026gt; Properties after defining an object instance can be used as if they were fields: \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:true\u0026quot;\u0026gt;\ra.Id = 10\rprint a.Id\r\u0026lt;h1 style=\u0026quot;font-family:Georgia;\u0026quot;\u0026gt; More and more about functions \u0026lt;/h1\u0026gt; \u0026lt;p\u0026gt; Functions can be used in many ways. \u0026lt;/p\u0026gt; \u0026lt;h2\u0026gt; Functions with default values \u0026lt;/h2\u0026gt; \u0026lt;p\u0026gt; You can let the parameters of the functions have default values, so that if the user didn\u0026amp;#8217;t supply them they\u0026amp;#8217;ll have valid values: \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:true\u0026quot;\u0026gt;\rdef f(id = 1, name = 'some name', age = 10):\rprint(str(id) + ' ' + name + ' at age ' + str(age))\r#All of the following calls are valid\rf()\t#Will print: 1 some name at age 10\rf(2)\t#Will print: 2 some name at age 10\rf(2, 'a')\t#Will print: 2 a at age 10\rf(2, 'a', 3)\t#Will print: 2 a at age 3\r\u0026lt;p\u0026gt; What if I want to supply the second paramter without supplying the first one and the third one? The solution is by: \u0026lt;/p\u0026gt; \u0026lt;h2\u0026gt; Passing specified parameters \u0026lt;/h2\u0026gt; \u0026lt;p\u0026gt; You can choose the paramters you want to supply and with any order you want: \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:true\u0026quot;\u0026gt;\r#All of the following calls are valid\rf(age = 3)\t#Wil print: 1 some name at age 3\rf(age = 3, id = 2)\t#Will print: 2 some name at age 3\rf(name = 'a', age = 3, id = 2)\t#Will print: 2 a at age 3\r\u0026lt;p\u0026gt; You can see that this way is useful, you can choose which parameters to pass and in what order :). \u0026lt;/p\u0026gt; \u0026lt;h2\u0026gt; Passing unlimited count of paramters \u0026lt;/h2\u0026gt; \u0026lt;p\u0026gt; Yes you can do it, you can call a function and pass it any count of parameters you want: \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:true\u0026quot;\u0026gt;\rdef u(*args):\rs = ''\rfor arg in args:\rs += arg + ' '\rprint s\r#All of the following calls are valid\ru()\t#Will print nothing\ru(1)\t#Will print: 1\ru(1, 2)\t#Will print: 1 2\ru(1, 2, 3)\t#Will print: 1 2 3\r\u0026lt;p\u0026gt; So args actually is enumerable type, may be a list ;). \u0026lt;/p\u0026gt; \u0026lt;h2\u0026gt; Passing unlimited named parameters \u0026lt;/h2\u0026gt; \u0026lt;p\u0026gt; Hmmmm, yes you can too specify names for those unlimited parameters of yours: \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:true\u0026quot;\u0026gt;\rdef uu(**kargs):\rs = ''\rfor k, v in kargs.iteritems():\rs += k + ' =\u0026amp;gt; ' + v + ', '\rprint s\r#All of the following calls are valid\ruu()\t#Will print nothing\ruu(a = 1)\t#Will print: a =\u0026amp;gt; 1\ruu(a = 1, b = 2)\t#Will print: a =\u0026amp;gt; 1, b =\u0026amp;gt; 2,\ruu(a = 1, b = 'asd', c = 0.5)\t#Will print: a =\u0026amp;gt; 1, b =\u0026amp;gt; 'asd', c =\u0026amp;gt; 0.5,\r\u0026lt;p\u0026gt; So kargs actually is a dictionary.\u0026lt;br /\u0026gt; If you don\u0026amp;#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.\u0026lt;br /\u0026gt; dictionary.iteritems is a great method for iterating over a dictionary of unknown keys. \u0026lt;/p\u0026gt; \u0026lt;h2\u0026gt; Overloading and why I don\u0026amp;#8217;t need it here \u0026lt;/h2\u0026gt; \u0026lt;p\u0026gt; Overloading is simply more than one instance of the same function with one or more of the following points achieved in them:\u0026lt;br /\u0026gt; * The count of parameters differs between them.\u0026lt;br /\u0026gt; * The types of the parameters differ between them.\u0026lt;br /\u0026gt; * The prder of the parameters differ between them. \u0026lt;/p\u0026gt; \u0026lt;p\u0026gt; Using what we\u0026amp;#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.\u0026lt;br /\u0026gt; The second point can also be achieved using one function since Python has no strict data types to variables and parameters.\u0026lt;br /\u0026gt; The third point can also be achieved using one function, by using paramters names while calling you can change the order of parameters passed.\u0026lt;br /\u0026gt; And so I can continue coding without overloading. \u0026lt;/p\u0026gt; \u0026lt;h1 style=\u0026quot;font-family:Georgia;\u0026quot;\u0026gt; Last Words \u0026lt;/h1\u0026gt; \u0026lt;p\u0026gt; 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\u0026amp;#8217;t find difficulties in using it as your main programming language.\u0026lt;br /\u0026gt; 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 \u0026amp;#8211; The book was: \u0026lt;a href=\u0026quot;http://www.packtpub.com/django-1-0-website-development-2nd-edition\u0026quot;\u0026gt;Django 1.0 Website Development\u0026lt;/a\u0026gt;, by my colleague and friend \u0026lt;a href=\u0026quot;http://www.aymanh.com\u0026quot;\u0026gt;Ayman Hourieh\u0026lt;/a\u0026gt; -, the website is for sharing bookmarks, it is now hosted for free at AlwaysData here \u0026lt;a href=\u0026quot;http://mpcabd.alwaysdata.net\u0026quot;\u0026gt;http://mpcabd.alwaysdata.net\u0026lt;/a\u0026gt;\u0026lt;br /\u0026gt; You can do in Python whatever you want with less coding. Enjoy your life more. \u0026lt;/p\u0026gt; \u0026lt;h1 style=\u0026quot;font-family:Georgia;\u0026quot;\u0026gt; The End \u0026lt;/h1\u0026gt; \u0026lt;p\u0026gt; It is the end of this course but the start of your path.\u0026lt;br /\u0026gt; I hope you enjoyed it, and that I could give you the information in a nice and easy way.\u0026lt;br /\u0026gt; For any questions or suggestions you can leave your comments here.\u0026lt;br /\u0026gt; Thanks for being patient :).\u0026lt;br /\u0026gt; \u0026amp;#8212; Abd Allah Diab \u0026lt;/div\u0026gt; ","permalink":"https://mpcabd.xyz/im-learning-python-part-10-last-one/","summary":"\u003cdiv dir=\"ltr\"\u003e\n  \u003cdiv style=\"text-align:center;\" align=\"center\"\u003e\n    \u003ch1 style=\"font-size:18pt;font-family:Verdana;\"\u003e\n      I'm Learning Python part 10\n    \u003c/h1\u003e\n\u003cpre\u003e\u003ccode\u003e\u0026lt;p\u0026gt;\n  \u0026lt;h1 style=\u0026quot;font-size:18pt;font-family:Verdana;\u0026quot;\u0026gt;\n    (last one)\n  \u0026lt;/h1\u0026gt;\n  \n  \u0026lt;p\u0026gt;\n    \u0026lt;img src=\u0026quot;http://www.python.org/images/python-logo.gif\u0026quot; alt=\u0026quot;Python Logo\u0026quot; title=\u0026quot;Python Logo\u0026quot; /\u0026gt; \u0026lt;/div\u0026gt; \n    \n    \u0026lt;h1 style=\u0026quot;font-family:Georgia;\u0026quot;\u0026gt;\n      Back to blogging\n    \u0026lt;/h1\u0026gt;\n    \n    \u0026lt;p\u0026gt;\n      As usual, I will apologize for not blogging for a long time.\u0026lt;br /\u0026gt; I have been very busy, university exams, university projects, job projects, teaching and learning.\n    \u0026lt;/p\u0026gt;\n    \n    \u0026lt;h1 style=\u0026quot;font-family:Georgia;\u0026quot;\u0026gt;\n      Python Course\n    \u0026lt;/h1\u0026gt;\n    \n    \u0026lt;p\u0026gt;\n      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.\u0026lt;br /\u0026gt; As far as I know this course was the first Python course in Damascus University.\u0026lt;br /\u0026gt; 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.\u0026lt;br /\u0026gt; As far as I know too, students understood it and found it great, and I hope they\u0026amp;#8217;ll be using this great language more in their programs.\n    \u0026lt;/p\u0026gt;\n    \n    \u0026lt;h1 style=\u0026quot;font-family:Georgia;\u0026quot;\u0026gt;\n      Why last one?\n    \u0026lt;/h1\u0026gt;\n    \n    \u0026lt;p\u0026gt;\n      The tour with Python ends here, while it ends here it starts here too, it ends here because so far you\u0026amp;#8217;ve learned what you need to start your own path in Python. And it starts here because you\u0026amp;#8217;re fully equipped with the base tool to discover more tools, I\u0026amp;#8217;ll let you discover the standard library and 3rd-party libraries on your own, because everyone differs in his/her interests.\u0026lt;br /\u0026gt; I\u0026amp;#8217;ll be blogging more on more technical issues but they might not be I\u0026amp;#8217;m Learning Python series :).\u0026lt;br /\u0026gt; Let\u0026amp;#8217;s stop talking here and move directly to the heart of our last lesson.\u0026lt;br /\u0026gt; \n\u003c/code\u003e\u003c/pre\u003e","title":"I’m Learning Python part 10 (last one)"},{"content":" I have copied the following post from this site. Discover the mission The premise is simple: Internet Explorer 6 is antiquated, doesn’t support key web standards, and should be phased out. This isn’t about being anti-Microsoft, it’s about Microsoft’s lack of development in the browser market. With IE7/8 not available for Windows 2000, IE6 accounts for up to 20% of web usage, primarily via business users. Clients pressure designers to ‘force’ sites to work in IE6, and designers, not wanting to lose business, comply, using hacks and workarounds. This wastes time and money. Microsoft needs to fix this, designers need to unite, and we all need to move on. Read the article \u0026lt;p\u0026gt; In our article, ‘\u0026lt;a href=\u0026quot;http://www.bringdownie6.com/bring-down-ie-6.html\u0026quot;\u0026gt;Calling time on IE6\u0026lt;/a\u0026gt;’, we ask designers and developers if it’s finally time to take IE6 behind the shed and shoot it. Major names in the web industry debate our mission, talking about the pros and cons behind dumping IE6. How feasible is it to shun the browser entirely? What can you do to minimise the impact IE6 has on you and your clients (and increasingly tight budgets)? And what can and should Microsoft do to help us all move the web and web standards on? \u0026lt;a href=\u0026quot;http://www.bringdownie6.com/bring-down-ie-6.html\u0026quot;\u0026gt;Find out by reading the article\u0026lt;/a\u0026gt;, or just ‘skip to the end’ by looking to the right and getting involved.\u0026lt;br /\u0026gt; \u0026lt;div class=\u0026quot;column\u0026quot;\u0026gt; \u0026lt;h2\u0026gt; Get involved \u0026lt;/h2\u0026gt; \u0026lt;ul\u0026gt; \u0026lt;li\u0026gt; \u0026lt;a href=\u0026quot;http://www.netmag.co.uk/files/bd.png\u0026quot;\u0026gt;Put our logo on your site\u0026lt;/a\u0026gt; and then \u0026lt;a href=\u0026quot;http://www.bringdownie6.com/\u0026quot;\u0026gt;link to this site\u0026lt;/a\u0026gt;. \u0026lt;a href=\u0026quot;http://www.twitter.com/netmag\u0026quot;\u0026gt;Follow us on Twitter\u0026lt;/a\u0026gt;. \u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; Educate your colleagues, users and clients regarding calling time on IE6. \u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; Ensure sites work in IE6, but don\u0026amp;#8217;t waste a lot of time fixing non-critical issues. \u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; Provide an upgrade notice for IE6 users by adding this code to your page: \u0026lt;pre class=\u0026quot;lang:html decode:true\u0026quot;\u0026gt;\r\u0026lt;style type=\u0026ldquo;text/css\u0026rdquo;\u0026gt; #ie6Warning { background:#E3E3E3 none repeat scroll 0 0; border:1px solid #BBBBBB; margin-bottom:10px; padding:10px 10px 1px; } #ie6Warning h2 { background:transparent url(http://www.bringdownie6.com/assets/ie6-warning.gif) no-repeat scroll 0 50%; padding-left:40px; } \u0026lt;/style\u0026gt; \u0026lt;!–[if lt IE 7]\u0026gt; \u0026lt;div id=\u0026ldquo;ie6Warning\u0026rdquo;\u0026gt; \u0026lt;h2\u0026gt;Time to upgrade your browser\u0026lt;/h2\u0026gt; \u0026lt;p\u0026gt;If you\u0026rsquo;re reading this, you\u0026rsquo;re surfing using Internet Explorer 6, an eight-year-old browser that cannot cope with the demands of the modern internet. For the best web experience, we strongly recommend upgrading to \u0026lt;a xhref=\u0026ldquo;http://www.getfirefox.com/\u0026quot;\u0026amp;gt;Firefox\u0026amp;lt;/a\u0026amp;gt;, \u0026lt;a xhref=\u0026ldquo;http://www.opera.com/\u0026quot;\u0026amp;gt;Opera\u0026amp;lt;/a\u0026amp;gt;, \u0026lt;a xhref=\u0026ldquo;http://www.apple.com/safari/\u0026quot;\u0026amp;gt;Safari\u0026amp;lt;/a\u0026amp;gt;, \u0026lt;a xhref=\u0026ldquo;http://www.google.com/chrome\u0026quot;\u0026amp;gt;Google Chrome\u0026lt;/a\u0026gt;, or a more recent version of \u0026lt;a xhref=\u0026ldquo;http://www.microsoft.com/windows/downloads/ie/getitnow.mspx\u0026quot;\u0026amp;gt;Internet Explorer\u0026lt;/a\u0026gt;.\u0026lt;/p\u0026gt; \u0026lt;/div\u0026gt; \u0026lt;![endif]–\u0026gt; \u0026lt;li\u0026gt; Spread the word \u0026lt;/li\u0026gt; \u0026lt;/ul\u0026gt; \u0026lt;/div\u0026gt; ","permalink":"https://mpcabd.xyz/bring-down-ie6/","summary":"\u003cdiv class=\"column\"\u003e\n  \u003ch2\u003e\n  \u003c/h2\u003e\n  \u003cp\u003e\n    I have copied the following post from \u003ca href=\"http://www.bringdownie6.com/\"\u003ethis site\u003c/a\u003e.\n  \u003c/p\u003e\n  \u003cp\u003e\n    \u003cimg class=\"aligncenter\" title=\"Bring IE6 Down\" src=\"http://www.netmag.co.uk/files/bd.png\" alt=\"\" width=\"117\" height=\"120\" /\u003e\n  \u003c/p\u003e\n  \u003ch2\u003e\n    Discover the mission\n  \u003c/h2\u003e\n  \u003cp\u003e\n    The premise is simple: Internet Explorer 6 is antiquated, doesn’t support key web standards, and should be phased out. This isn’t about being anti-Microsoft, it’s about Microsoft’s lack of development in the browser market. With IE7/8 not available for Windows 2000, IE6 accounts for up to 20% of web usage, primarily via business users. Clients pressure designers to ‘force’ sites to work in IE6, and designers, not wanting to lose business, comply, using hacks and workarounds. This wastes time and money. Microsoft needs to fix this, designers need to unite, and we all need to move on.\n  \u003c/p\u003e\n  \u003cdiv class=\"column\"\u003e\n    \u003ch2\u003e\n      Read the article\n    \u003c/h2\u003e\n\u003cpre\u003e\u003ccode\u003e\u0026lt;p\u0026gt;\n  In our article, ‘\u0026lt;a href=\u0026quot;http://www.bringdownie6.com/bring-down-ie-6.html\u0026quot;\u0026gt;Calling time on IE6\u0026lt;/a\u0026gt;’, we ask designers and developers if it’s finally time to take IE6 behind the shed and shoot it. Major names in the web industry debate our mission, talking about the pros and cons behind dumping IE6. How feasible is it to shun the browser entirely? What can you do to minimise the impact IE6 has on you and your clients (and increasingly tight budgets)? And what can and should Microsoft do to help us all move the web and web standards on? \u0026lt;a href=\u0026quot;http://www.bringdownie6.com/bring-down-ie-6.html\u0026quot;\u0026gt;Find out by reading the article\u0026lt;/a\u0026gt;, or just ‘skip to the end’ by looking to the right and getting involved.\u0026lt;br /\u0026gt; \n\u003c/code\u003e\u003c/pre\u003e","title":"Bring Down IE6"},{"content":" I\u0026#8217;m Learning Python part 9 \u0026lt;p\u0026gt; \u0026lt;img title=\u0026quot;Python Logo\u0026quot; src=\u0026quot;http://www.python.org/images/python-logo.gif\u0026quot; alt=\u0026quot;Python Logo\u0026quot; /\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;h1 style=\u0026quot;font-family:Georgia;\u0026quot;\u0026gt; Classes In Python \u0026lt;/h1\u0026gt; \u0026lt;div dir=\u0026quot;ltr\u0026quot;\u0026gt; As I told you before, Python is a powerful programming language, and powerful it won\u0026amp;#8217;t be without Object Oriented design. \u0026lt;/div\u0026gt; \u0026lt;div dir=\u0026quot;ltr\u0026quot;\u0026gt; Python supports both Pure Object Oriented Programming (Every thing must be in a class) and Structural Programming (You can type code everywhere). \u0026lt;/div\u0026gt; \u0026lt;div dir=\u0026quot;ltr\u0026quot;\u0026gt; It supports also other programming paradigms like Functional Programming. I won\u0026amp;#8217;t write about OOP and its uses, why we should use it, I\u0026amp;#8217;ll just give you the keys to use OOP in Python. \u0026lt;/div\u0026gt; \u0026lt;h1 style=\u0026quot;font-family:Georgia;\u0026quot;\u0026gt; Defining a Class \u0026lt;/h1\u0026gt; \u0026lt;p\u0026gt; Classes in Python are defined like this: \u0026lt;/p\u0026gt; \u0026lt;p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:true\u0026quot;\u0026gt;\rclass CLASS_NAME (BASE0,BASE1,BASE2): \u0026ldquo;\u0026ldquo;\u0026ldquo;OPTIONAL DOC STRING\u0026rdquo;\u0026rdquo;\u0026rdquo; #Class Code . . . \u0026lt;div dir=\u0026quot;ltr\u0026quot;\u0026gt; Yes, I know what you\u0026amp;#8217;re thinking of, Python supports multiple inheritance. \u0026lt;/div\u0026gt; \u0026lt;div dir=\u0026quot;ltr\u0026quot;\u0026gt; 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\u0026amp;#8217;s because before Python 3.0 you could make a classic class that doesn\u0026amp;#8217;t inherit any class, not even object. \u0026lt;/div\u0026gt; \u0026lt;div dir=\u0026quot;ltr\u0026quot;\u0026gt; Because of Python\u0026amp;#8217;s dynamic data typing you don\u0026amp;#8217;t need interfaces in Python, so there is no implicit syntax for declaring interfaces. \u0026lt;/div\u0026gt; \u0026lt;h1 style=\u0026quot;font-family:Georgia;\u0026quot;\u0026gt; Sample \u0026lt;/h1\u0026gt; \u0026lt;div dir=\u0026quot;ltr\u0026quot;\u0026gt; Let\u0026amp;#8217;s create a sample class, I always implement the stack when I want to show OOP examples, I don\u0026amp;#8217;t know why but that\u0026amp;#8217;s what I\u0026amp;#8217;m gonna do now: \u0026lt;/div\u0026gt; \u0026lt;div dir=\u0026quot;ltr\u0026quot;\u0026gt; I always start implementing stack by implementing its unit type, a class called StackItem. \u0026lt;/div\u0026gt; \u0026lt;div dir=\u0026quot;ltr\u0026quot;\u0026gt; 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: \u0026lt;/div\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:true\u0026quot;\u0026gt;\rclass StackItem(object): def init(self, value): self.Value = value self.Next = None\n@property\rdef Value(self):\rreturn self.__value\r@Value.setter\rdef Value(self, value):\rself.__value = value\r@property\rdef Next(self):\rreturn self.__next\r@Next.setter\rdef Next(self, value):\rself.__next = value\r\u0026lt;p\u0026gt; Let\u0026amp;#8217;s describe the whole scene of code: \u0026lt;/p\u0026gt; \u0026lt;ol\u0026gt; \u0026lt;li\u0026gt; StackItem inherits object, it is a way of saying \u0026amp;#8220;Everything is an object\u0026amp;#8221; 🙂 \u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; __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). \u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; @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).\u0026lt;br /\u0026gt; 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.\u0026lt;br /\u0026gt; @property created a property called Value inside StackItem class, and it bounded its value to a private variable called __value.\u0026lt;br /\u0026gt; You\u0026amp;#8217;d ask how come __value is a private variable?\u0026lt;br /\u0026gt; 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\u0026amp;#8217;t see it, so it is a way of creating private variables. \u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; @Value.setter is another decorator which binds the setting of the Value property tho the given function. \u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; Next is like Value, a property.\u0026lt;br /\u0026gt; A property can be used later by calling its name only, just like any variable: e.g.:\u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:true\u0026quot;\u0026gt;\rs.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. \u0026lt;li\u0026gt; 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).\u0026lt;br /\u0026gt; When not passing self to the function you\u0026amp;#8217;re declaring that this function doesn\u0026amp;#8217;t need an instance of the class to be called, in other words, you\u0026amp;#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.:\u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:true\u0026quot;\u0026gt;\rclass C(object): def NonStatic(self): print (\u0026ldquo;NonStatic\u0026rdquo; ) @staticmethod def Static(): print(\u0026ldquo;Static\u0026rdquo; )\ncObj = 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. \u0026lt;p\u0026gt; The other part must be easy for you after understanding the first one, now we\u0026amp;#8217;ll implement the Stack class: \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:true\u0026quot;\u0026gt;\rclass Stack(object): @property def Head(self): return self.__head\n@property\rdef Count(self):\rreturn self.__count\rdef __init__(self):\rself.__head = None\rself.__count = 0\rdef Push(self, value):\rif (self.__head is None):\rself.__head = StackItem(value)\relse:\rtemp = StackItem(value)\rtemp.Next = self.__head\rself.__head = temp\rself.__count += 1\rdef Pop(self):\rif (self.__head is None):\rraise Exception(\u0026quot;Empty Stack\u0026quot; )\relse:\rtemp = self.__head\rself.__head = self.__head.Next\rself.__count -= 1\rreturn temp.Value\rdef PopAll(self):\rwhile (self.__count \u0026amp;gt; 0):\ryield self.Pop()\r\u0026lt;p\u0026gt; Notes: \u0026lt;/p\u0026gt; \u0026lt;ol\u0026gt; \u0026lt;li\u0026gt; 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). \u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; The constructor sets the Count to 0 and the Head to None. \u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; Push takes two arguments, the stack to push into, and the value to be pushed. \u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; 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 \u0026amp;#8220;Empty Stack\u0026amp;#8221;. \u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; PopAll is called a Generator, it generates values from a data structure, it can be used with for loops. e.g.: \u0026lt;pre class=\u0026quot;lang:python decode:true\u0026quot;\u0026gt;\rfor value in s.PopAll(): print(value) \u0026lt;p\u0026gt; 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.\u0026lt;/li\u0026gt; \u0026lt;/ol\u0026gt; \u0026lt;p\u0026gt; Now we can use our stack freely 🙂 \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:true\u0026quot;\u0026gt;\rS = Stack()\nmap(S.Push, range(1, 10))\nfor value in S.PopAll(): print value \u0026lt;div dir=\u0026quot;ltr\u0026quot;\u0026gt; Simple code, right? \u0026lt;/div\u0026gt; \u0026lt;div dir=\u0026quot;ltr\u0026quot;\u0026gt; Notes: \u0026lt;/div\u0026gt; \u0026lt;ol\u0026gt; \u0026lt;li\u0026gt; S = Stack() initializes a new Stack and put its reference in S. \u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; 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.: \u0026lt;pre class=\u0026quot;lang:python decode:true\u0026quot;\u0026gt;\rprint(rang(1, 10)) #prints from 1 to 9 \u0026lt;p\u0026gt; range can also take three numbers, the third would be the step between each two numbers. e.g.: \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:true\u0026quot;\u0026gt;\rprint(range(1, 10, 2)) #prints 1, 3, 5, 7, 9 \u0026lt;p\u0026gt; So map(S.Push, range(1, 10)) will fill the stack with values from 1 to 9.\u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; I used the PopAll method which is a generator to iterate over the StackItems and print them. \u0026lt;/li\u0026gt;\u0026lt;/ol\u0026gt; \u0026lt;h1 style=\u0026quot;font-family:Georgia;\u0026quot;\u0026gt; Overriding and Overloading \u0026lt;/h1\u0026gt; \u0026lt;div dir=\u0026quot;ltr\u0026quot;\u0026gt; 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). \u0026lt;/div\u0026gt; \u0026lt;div dir=\u0026quot;ltr\u0026quot;\u0026gt; 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. \u0026lt;/div\u0026gt; \u0026lt;div dir=\u0026quot;ltr\u0026quot;\u0026gt; To override a method you simply have to define it in the sub-class. e.g: \u0026lt;/div\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:true\u0026quot;\u0026gt;\rclass A(object): def M(self): print (self.X) def init(self): self.X = 5 class B(A): def M(self): print (self.X + 1)\nb = B() b.M() #Will print 6 \u0026lt;div dir=\u0026quot;ltr\u0026quot;\u0026gt; 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). \u0026lt;/div\u0026gt; \u0026lt;div dir=\u0026quot;ltr\u0026quot;\u0026gt; e.g.: \u0026lt;/div\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:true\u0026quot;\u0026gt;\rclass C(B): def M(self): B.M(self) print (\u0026ldquo;This is C\u0026rdquo; ) c = C() c.M() #Will print 6 This is C \u0026lt;div dir=\u0026quot;ltr\u0026quot;\u0026gt; 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. \u0026lt;/div\u0026gt; \u0026lt;div dir=\u0026quot;ltr\u0026quot;\u0026gt; A def statement is roughly executed like this: \u0026lt;/div\u0026gt; \u0026lt;ol\u0026gt; \u0026lt;li\u0026gt; Compile the body of the function. \u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; Build a function object __f \u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; Assign it: FunctionName = __f \u0026lt;/li\u0026gt; \u0026lt;/ol\u0026gt; \u0026lt;h1 style=\u0026quot;font-family:Georgia;\u0026quot;\u0026gt; Bottom Line: \u0026lt;/h1\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;div dir=\u0026quot;ltr\u0026quot;\u0026gt; Python supports Pure Object Oriented strongly, You can write pure Object Oriented programs using Python, so why don\u0026amp;#8217;t you start writing your programs now? \u0026lt;/div\u0026gt; \u0026lt;div dir=\u0026quot;ltr\u0026quot;\u0026gt; Cheers. \u0026lt;/div\u0026gt; ","permalink":"https://mpcabd.xyz/im-learning-python-part-9/","summary":"\u003cdiv dir=\"ltr\"\u003e\n  \u003cdiv style=\"text-align:center;\"\u003e\n    \u003ch1 style=\"font-size:18pt;font-family:Verdana;\"\u003e\n      I\u0026#8217;m Learning Python part 9\n    \u003c/h1\u003e\n\u003cpre\u003e\u003ccode\u003e\u0026lt;p\u0026gt;\n  \u0026lt;img title=\u0026quot;Python Logo\u0026quot; src=\u0026quot;http://www.python.org/images/python-logo.gif\u0026quot; alt=\u0026quot;Python Logo\u0026quot; /\u0026gt;\u0026lt;/div\u0026gt; \n  \n  \u0026lt;h1 style=\u0026quot;font-family:Georgia;\u0026quot;\u0026gt;\n    Classes In Python\n  \u0026lt;/h1\u0026gt;\n  \n  \u0026lt;div dir=\u0026quot;ltr\u0026quot;\u0026gt;\n    As I told you before, Python is a powerful programming language, and powerful it won\u0026amp;#8217;t be without Object Oriented design.\n  \u0026lt;/div\u0026gt;\n  \n  \u0026lt;div dir=\u0026quot;ltr\u0026quot;\u0026gt;\n    Python supports both Pure Object Oriented Programming (Every thing must be in a class) and Structural Programming (You can type code everywhere).\n  \u0026lt;/div\u0026gt;\n  \n  \u0026lt;div dir=\u0026quot;ltr\u0026quot;\u0026gt;\n    It supports also other programming paradigms like Functional Programming. I won\u0026amp;#8217;t write about OOP and its uses, why we should use it, I\u0026amp;#8217;ll just give you the keys to use OOP in Python.\n  \u0026lt;/div\u0026gt;\n  \n  \u0026lt;h1 style=\u0026quot;font-family:Georgia;\u0026quot;\u0026gt;\n    Defining a Class\n  \u0026lt;/h1\u0026gt;\n  \n  \u0026lt;p\u0026gt;\n    Classes in Python are defined like this:\n  \u0026lt;/p\u0026gt;\n  \n  \u0026lt;p\u0026gt;\n\u003c/code\u003e\u003c/pre\u003e","title":"I’m Learning Python part 9"},{"content":" I\u0026#8217;m Learning Python part 8 \u0026lt;p\u0026gt; \u0026lt;img title=\u0026quot;Python\u0026quot; src=\u0026quot;//www.python.org/images/python-logo.gif\u0026quot; alt=\u0026quot;Python\u0026quot; /\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;h1 style=\u0026quot;font-family:Georgia;\u0026quot;\u0026gt; Python 3.0 \u0026lt;/h1\u0026gt; \u0026lt;p\u0026gt; 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). \u0026lt;/p\u0026gt; \u0026lt;p\u0026gt; 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. \u0026lt;/p\u0026gt; \u0026lt;p\u0026gt; Don\u0026amp;#8217;t worry that much, the language has become more useful, and also there is \u0026lt;a href=\u0026quot;//docs.python.org/library/2to3.html\u0026quot;\u0026gt;2to3 source-to-source conversion tool\u0026lt;/a\u0026gt; which converts your Python 2.x code to meet the requirements of Python 3.0 🙂 \u0026lt;/p\u0026gt; \u0026lt;p\u0026gt; To find more about change in Python please refer to \u0026lt;a title=\u0026quot;What's\u0026quot; href=\u0026quot;//docs.python.org/3.0/whatsnew/3.0.html\u0026quot;\u0026gt;Python website\u0026lt;/a\u0026gt;. \u0026lt;/p\u0026gt; \u0026lt;p\u0026gt; P.S. \u0026lt;p\u0026gt; From now on all the code will be written in Python 3.0. \u0026lt;/p\u0026gt; \u0026lt;h1 style=\u0026quot;font-family:Georgia;\u0026quot;\u0026gt; Decimal vs. float \u0026lt;/h1\u0026gt; \u0026lt;p\u0026gt; Please try the following code in your python console: \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:1\u0026quot;\u0026gt;\rd = 0.1 print(d) print(str(d)) \u0026lt;p\u0026gt; You\u0026amp;#8217;d get this output: \u0026lt;/p\u0026gt; \u0026lt;div\u0026gt; \u0026lt;strong\u0026gt;\u0026lt;span style=\u0026quot;color:#666666;font-family:verdana;\u0026quot;\u0026gt;0.10000000000000001\u0026lt;/span\u0026gt;\u0026lt;/strong\u0026gt; \u0026lt;/div\u0026gt; \u0026lt;p\u0026gt; \u0026lt;strong\u0026gt;\u0026lt;span style=\u0026quot;color:#666666;font-family:verdana;\u0026quot;\u0026gt;0.1\u0026lt;br /\u0026gt; \u0026lt;/span\u0026gt;\u0026lt;/strong\u0026gt;Strange ain\u0026amp;#8217;t it?\u0026lt;br /\u0026gt; The second value is the one you put in the variable.\u0026lt;br /\u0026gt; The first one is the real value represented in memory. This is not Python\u0026amp;#8217;s fault, this happens because of the way computer store float values in memory as 0\u0026amp;#8217;s and 1\u0026amp;#8217;s, computers use floating point IEEE-745 representation. \u0026lt;/p\u0026gt; \u0026lt;p\u0026gt; Using this representation unfortunately we can\u0026amp;#8217;t represent any float value using 0\u0026amp;#8217;s and 1\u0026amp;#8217;s, and 0.1 is one of those poor values (The reason is that it can\u0026amp;#8217;t be represented in sum of powers of 0.5). \u0026lt;/p\u0026gt; \u0026lt;p\u0026gt; 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\u0026amp;#8217;t. \u0026lt;/p\u0026gt; \u0026lt;p\u0026gt; Try this code in Java if you have: \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:1\u0026quot;\u0026gt;\rpublic class NoDifference{ public static void main(String[] args){ double a = 0.1; System.out.println(a); a = 0.10000000000000001; System.out.println(a); } } \u0026lt;p\u0026gt; You\u0026amp;#8217;d get this output: \u0026lt;/p\u0026gt; \u0026lt;div\u0026gt; \u0026lt;strong\u0026gt;\u0026lt;span style=\u0026quot;color:#666666;font-family:verdana;\u0026quot;\u0026gt;0.1\u0026lt;/span\u0026gt;\u0026lt;/strong\u0026gt; \u0026lt;/div\u0026gt; \u0026lt;p\u0026gt; \u0026lt;strong\u0026gt;\u0026lt;span style=\u0026quot;color:#666666;font-family:verdana;\u0026quot;\u0026gt;0.1\u0026lt;/span\u0026gt;\u0026lt;/strong\u0026gt; \u0026lt;/p\u0026gt; \u0026lt;p\u0026gt; \u0026lt;strong\u0026gt;\u0026lt;/strong\u0026gt;So Java doesn\u0026amp;#8217;t differ those two values while they\u0026amp;#8217;re different. (Such a difference could make a disaster in a nuclear reactor :twisted:)\u0026lt;br /\u0026gt; If you want to go with the flow and ignore this difference in your calculations you\u0026amp;#8217;d have to use another data type than float, you\u0026amp;#8217;ll have to use Decimal. \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:1\u0026quot;\u0026gt;\rfrom decimal import Decimal d = Decimal(\u0026ldquo;0.1\u0026rdquo;) print(d) \u0026lt;p\u0026gt; \u0026lt;strong\u0026gt;\u0026lt;span style=\u0026quot;color:#666666;font-family:verdana;\u0026quot;\u0026gt;0.1\u0026lt;/span\u0026gt;\u0026lt;/strong\u0026gt; \u0026lt;/p\u0026gt; \u0026lt;p\u0026gt; \u0026lt;strong\u0026gt;\u0026lt;/strong\u0026gt;Decimal data type allows you to represent any decimal value you want 🙂 \u0026lt;/p\u0026gt; \u0026lt;p\u0026gt; It also supports addition, subtraction, multiplication, division and modulo, but the two sides must be Decimals. \u0026lt;/p\u0026gt; \u0026lt;h1 style=\u0026quot;font-family:Georgia;\u0026quot;\u0026gt; Functions \u0026lt;/h1\u0026gt; \u0026lt;p\u0026gt; Let\u0026amp;#8217;s write a function that prints Fibonacci series to a given boundary: \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:1\u0026quot;\u0026gt;\rdef fib(n): \u0026ldquo;\u0026ldquo;\u0026ldquo;Prints Fibonacci series up to n\u0026rdquo;\u0026rdquo;\u0026rdquo; a, b = 0, 1 while b \u0026lt; n: print(b, end = \u0026quot; \u0026ldquo;) a, b = b, a + b #Now we can call the function by its name fib(2000) \u0026lt;p\u0026gt; \u0026lt;strong\u0026gt;\u0026lt;span style=\u0026quot;color:#666666;font-family:verdana;\u0026quot;\u0026gt;1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597\u0026lt;/span\u0026gt;\u0026lt;/strong\u0026gt; \u0026lt;/p\u0026gt; \u0026lt;p\u0026gt; Now let\u0026amp;#8217;s describe what we have done: \u0026lt;/p\u0026gt; \u0026lt;ol\u0026gt; \u0026lt;li\u0026gt; def is a keyword in Python, def defines 🙂 it defines methods and classes. \u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; fib is the method\u0026amp;#8217;s name, method\u0026amp;#8217;s name must meet the same requirements for variable\u0026amp;#8217;s name. (first character a-z, A-Z or _, other characters a-z, A-Z, 0-9, _) \u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; (n) is the list of parameters, notice that no type names in this list. parameters are comma separated. \u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; : defines the scope of the method. All statements under this scope must be tab-aligned. \u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; \u0026amp;#8220;\u0026amp;#8221;\u0026amp;#8221;Prints \u0026amp;#8230;\u0026amp;#8221;\u0026amp;#8221;\u0026amp;#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. \u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; a, b = 0, 1. define two variables and give them two values. a handy way 🙂 \u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; a, b = b, a + b. also assign two values to two variables. \u0026lt;/li\u0026gt; \u0026lt;/ol\u0026gt; \u0026lt;p\u0026gt; The previous code defines a procedure (not a function) because it doesn\u0026amp;#8217;t return a value, let\u0026amp;#8217;s modify the code so it builds an array of Fibonacci values instead of printing them: \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:1\u0026quot;\u0026gt;\rdef fib(n): \u0026ldquo;\u0026ldquo;\u0026ldquo;Prints Fibonacci series up to n\u0026rdquo;\u0026rdquo;\u0026rdquo; a, b = 0, 1 result = [] while b \u0026lt; n: result.append(b) a, b = b, a + b return result f = fib(100) print(f) \u0026lt;p\u0026gt; \u0026lt;strong\u0026gt;\u0026lt;span style=\u0026quot;color:#666666;font-family:verdana;\u0026quot;\u0026gt;[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]\u0026lt;/span\u0026gt;\u0026lt;/strong\u0026gt; \u0026lt;/p\u0026gt; \u0026lt;p\u0026gt; What we have added is the return statement only, which returns a value to the caller. \u0026lt;/p\u0026gt; \u0026lt;p\u0026gt; One more thing to be told is default arguments: \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:1\u0026quot;\u0026gt;\rdef askYesNoQuestion(question, retries = 4, complaint = \u0026ldquo;Please write Yes or No only!\u0026rdquo;): while retries \u0026gt; 0: answer = raw_input(question) if answer in [\u0026lsquo;y\u0026rsquo;, \u0026lsquo;ye\u0026rsquo;, \u0026lsquo;yes\u0026rsquo;, \u0026lsquo;yep\u0026rsquo;]: return True if answer in [\u0026rsquo;n\u0026rsquo;, \u0026rsquo;no\u0026rsquo;, \u0026rsquo;nop\u0026rsquo;]: return False retries -= 1 print(complaint) raise IOError, \u0026ldquo;stupid user\u0026rdquo; #Now we can call it askYesNoQuestion(\u0026ldquo;Are you sure?\u0026rdquo;, 1, \u0026ldquo;What?!\u0026rdquo;) askYesNoQuestion(\u0026ldquo;Overwrite?\u0026rdquo;, 1) #Same as askYesNoQuestion(\u0026ldquo;Overwrite?\u0026rdquo;, 1, \u0026ldquo;Please write Yes or No only!\u0026rdquo;) askYesNoQuestion(\u0026ldquo;Do you know me?\u0026rdquo;) #Same as askYesNoQuestion(\u0026ldquo;Do you know me?\u0026rdquo;, 4, \u0026ldquo;Please write Yes or No only!\u0026rdquo;) askYesNoQuestion(\u0026ldquo;Do you have a pen?\u0026rdquo;, complaint = \u0026ldquo;You can say no if you want!\u0026rdquo;) #Same as askYesNoQuestion(\u0026ldquo;Do you have a pen?\u0026rdquo;, 4, \u0026ldquo;You can say no if you want!\u0026rdquo;) \u0026lt;p\u0026gt; Default arguments are assigned a default value if they aren\u0026amp;#8217;t when called.\u0026lt;br /\u0026gt; You can set arguments values when calling by writing Name = Value.\u0026lt;br /\u0026gt; Default parameters can\u0026amp;#8217;t be followed by non-default arguments.\u0026lt;br /\u0026gt; \u0026lt;strong\u0026gt;Important note\u0026lt;/strong\u0026gt;:\u0026lt;br /\u0026gt; Default arguments are evaluated only once, so the following code will accumulate the values: \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:1\u0026quot;\u0026gt;\rdef f(a, L = []): L.append(a) return L f(1) print(f) \u0026lt;p\u0026gt; \u0026lt;strong\u0026gt;\u0026lt;span style=\u0026quot;color:#666666;font-family:verdana;\u0026quot;\u0026gt;[1]\u0026lt;/span\u0026gt;\u0026lt;/strong\u0026gt; \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:1\u0026quot;\u0026gt;\rf(2) print(f) \u0026lt;p\u0026gt; \u0026lt;strong\u0026gt;\u0026lt;span style=\u0026quot;color:#666666;font-family:verdana;\u0026quot;\u0026gt;[1, 2]\u0026lt;/span\u0026gt;\u0026lt;/strong\u0026gt; \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:1\u0026quot;\u0026gt;\rf(3) print(f) \u0026lt;p\u0026gt; \u0026lt;strong\u0026gt;\u0026lt;span style=\u0026quot;color:#666666;font-family:verdana;\u0026quot;\u0026gt;[1, 2, 3]\u0026lt;/span\u0026gt;\u0026lt;/strong\u0026gt;\u0026lt;br /\u0026gt; If you don\u0026amp;#8217;t want the function to behave like this you can write: \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:1\u0026quot;\u0026gt;\rdef f(a, L = None): if L is None: L = [] L.append(a) return L \u0026lt;p\u0026gt; Let\u0026amp;#8217;s explain what I meant by saying \u0026amp;#8220;are evaluated only once\u0026amp;#8221;:\u0026lt;br /\u0026gt; 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.\u0026lt;br /\u0026gt; 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.\u0026lt;br /\u0026gt; The second code actually referenced to None, so every time you call the function it will assign None to L.\u0026lt;br /\u0026gt; By understanding what I meant you can consider the following example: \u0026lt;/p\u0026gt; \u0026lt;pre class=\u0026quot;lang:python decode:1\u0026quot;\u0026gt;\ri = 10 def f(a, b = i): return a + b i = 11 print(f(2)) # Will it print 12 or 13? \u0026lt;p\u0026gt; \u0026lt;strong\u0026gt;\u0026lt;span style=\u0026quot;color:#666666;font-family:verdana;\u0026quot;\u0026gt;12\u0026lt;/span\u0026gt;\u0026lt;/strong\u0026gt;\u0026lt;br /\u0026gt; That\u0026amp;#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. \u0026lt;/p\u0026gt; \u0026lt;h1 style=\u0026quot;font-family:Georgia;\u0026quot;\u0026gt; Bottom Line \u0026lt;/h1\u0026gt; \u0026lt;p\u0026gt; Not that much I presented in this part, but you should consider upgrading your Python knowledge to Python 3.0 for the next time.\u0026lt;br /\u0026gt; And by the way, I\u0026amp;#8217;m sorry, I\u0026amp;#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 🙂\u0026lt;br /\u0026gt; Cheers. \u0026lt;/p\u0026gt;\u0026lt;/div\u0026gt; ","permalink":"https://mpcabd.xyz/im-learning-python-part-8/","summary":"\u003cdiv\u003e\n  \u003cdiv style=\"text-align:center;\"\u003e\n    \u003ch1 style=\"font-size:18pt;font-family:Verdana;\"\u003e\n      I\u0026#8217;m Learning Python part 8\n    \u003c/h1\u003e\n\u003cpre\u003e\u003ccode\u003e\u0026lt;p\u0026gt;\n  \u0026lt;img title=\u0026quot;Python\u0026quot; src=\u0026quot;//www.python.org/images/python-logo.gif\u0026quot; alt=\u0026quot;Python\u0026quot; /\u0026gt;\u0026lt;/div\u0026gt; \n  \n  \u0026lt;h1 style=\u0026quot;font-family:Georgia;\u0026quot;\u0026gt;\n    Python 3.0\n  \u0026lt;/h1\u0026gt;\n  \n  \u0026lt;p\u0026gt;\n    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).\n  \u0026lt;/p\u0026gt;\n  \n  \u0026lt;p\u0026gt;\n    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.\n  \u0026lt;/p\u0026gt;\n  \n  \u0026lt;p\u0026gt;\n    Don\u0026amp;#8217;t worry that much, the language has become more useful, and also there is \u0026lt;a href=\u0026quot;//docs.python.org/library/2to3.html\u0026quot;\u0026gt;2to3 source-to-source conversion tool\u0026lt;/a\u0026gt; which converts your Python 2.x code to meet the requirements of Python 3.0 🙂\n  \u0026lt;/p\u0026gt;\n  \n  \u0026lt;p\u0026gt;\n    To find more about change in Python please refer to \u0026lt;a title=\u0026quot;What's\u0026quot; href=\u0026quot;//docs.python.org/3.0/whatsnew/3.0.html\u0026quot;\u0026gt;Python website\u0026lt;/a\u0026gt;.\n  \u0026lt;/p\u0026gt;\n  \n  \u0026lt;p\u0026gt;\n\u003c/code\u003e\u003c/pre\u003e","title":"I’m Learning Python part 8"},{"content":"I mentioned many times before that I was planning to make a workshop about Free Open Source Software (FOSS) in Damascus, and thankfully I did 🙂\nThe Idea The idea was to spread the culture of FOSS between the interested people here in Damascus.\nWhat I noticed was that almost 99% of computer science students didn’t know what Free Software is and what Open Source software is!\nThe Process So I started contacting engineers and people who I know that they’re capable of teaching this culture to our faculty students, and I managed to make 3 people agree on lecturing in the workshop.\nAfter a while I realized that I can’t make the workshop as I thought, I won’t be able to make lectures inside the faculty because of some freaky stupid bureaucracy.\nSo the solution came with the idea of iCommunity, and thankfully it solve the problem.\niCommunity iCommunity is a committee inside SCS – Syrian Computer Society, which is responsible of connecting the youth\ncomputer science interested people with the SCS and other governmental offices.\nIt has the power that SCS gave to it, which is to think and prepare for projects that young people want to do and they can’t.\nBy having iCommunity we can achieve almost what we want with some powerful support from SCS.\nAnd I’m one of the 6 managers of iCommunity, together we decieded that we will make this FOSS Workshop a reality.\nThe Workshop The workshop took place in Damascus, Tishreen Park, SCS Center. From February 3rd to February 5th.\nEveryday had lectures, coffee break and installation festival.\nThe First Day 03/Feb/2009 We had 3 lectures:\nWhat is Free Software? What is Open Source Software? and Why?_ Eng. Firas Kassem \u0026amp; Eng. Humam Hawasly._ What are the licenses of Free and Open Source Software? Eng. Nada Al Benni. What is Creative Commons? Eng. Zyiad Maraqa from Jordan. The Second Day 04/Feb/2009 We had 2 lectures:\nArabic Free Open Source projects, and managing them. Php-ar as an example. Eng. Khaled Al Shamaa. Linux is a great choice for an operating system. Eng. Emad Mahayni. The Third Day 05/Feb/2009 We had 3 lectures:\nBuilding unified communication using IP-Telephoney by open source projects. Eng. Ahmad Osman. Practical experiment with using Free Open Source Software in a daily life. Eng. Hani Al Safadi. Finding Free Open Source alternatives to proprietary software. Abd Allah Diab. The Installation Festivals We told people to bring their laptops so we can teach them how to install Ubuntu 8.10 Intrepid Ibex on it.\nThere were many interested people so the festival was great.\nMy friends in the college helped us in the festival, I can’t find any way to thank them.\nWe also played this video, that describes what would have happened if The Matrix was real and ran on Windows 🙂\nDVDs We distributed two DVD’s to the audience, the first one was Ubuntu 8.10 Desktop Edition DVD i386, and the other was an Open DVD which included a debian repository and free open source software for both operating systems Linux and Windows.\nMedia Coverage and Articles Creative Commons website wrote about Zyiad’s lecture in the worksop:\nZiad Maraqa, co-Project Lead from CC Jordan, spoke yesterday in Damascus at the iCommunity FOSS Workshop, a notable gathering for the Syrian Free Software community.\nAl Watan Newspaper in Syria wrote about the workshop daily (Arabic):\nhttp://www.alwatan.sy/dindex.php?idn=50788\nhttp://www.alwatan.sy/dindex.php?idn=50843\neSyria, Syria blog website wrote about the workshop daily in its Damascus website (Arabic):\nhttp://www.edamascus.sy/_activities.php?filename=200902021845011\nhttp://www.edamascus.sy/_business.php?filename=200902031620011\nhttp://www.edamascus.sy/_news.php?filename=200902041650013\nhttp://www.edamascus.sy/_news.php?filename=200902060300011\nPhotos This is a photo of the iCommunity Managers:\nThis is a photo of the installation team, 4 iCommunity managers, and some students:\nI’m the one with the gray suit and glasses in the middle 8)\nAnd this one is from above of more students, 5 iCommunity Managers (the 6th is the one behind the camera) and the installation team 🙂\nWe had wonderful time, and we got great feedback of people attended the workshop.\n","permalink":"https://mpcabd.xyz/icommunity-foss-09/","summary":"\u003cp\u003eI mentioned many times before that I was planning to make a workshop about Free Open Source Software (FOSS) in Damascus, and thankfully I did 🙂\u003c/p\u003e\n\u003ch1 id=\"the-idea\"\u003eThe Idea\u003c/h1\u003e\n\u003cp\u003eThe idea was to spread the culture of FOSS between the interested people here in Damascus.\u003c/p\u003e\n\u003cp\u003eWhat I noticed was that almost 99% of computer science students didn’t know what Free Software is and what Open Source software is!\u003c/p\u003e","title":"iCommunity FOSS 09"},{"content":"After a month of not blogging, I’m back to blogging for Python.\nThis month had a lot in it:\nComputer Science exams @ Damascus University, so I had to study a lot. Scientific Calculations Project, the project of this semester. FOSS Workshop, which my friends and I arranged to in Damascus, and it was more than wonderful. After finishing my Scientific Calculations Project I made the choice of removing Windows for good from my computer, I’m going to make Ubuntu my only operating system to use.\nThe workshop was more than I expected, I witnessed the great participation and work from my friends to make this workshop a successful story to be told.\nYou can see here that the FOSS workshop was a notable event in Damascus and Syria.\nZiad Maraqa, co-Project Lead from CC Jordan, spoke yesterday in Damascus at the iCommunity FOSS Workshop, a notable gathering for the Syrian Free Software community.\nAnd here are some articles about the event but they’re in Arabic:\nAl Watan Newspaper:\nhttp://www.alwatan.sy/dindex.php?idn=50788\nhttp://www.alwatan.sy/dindex.php?idn=50843\neDamscus:\nhttp://www.edamascus.sy/_activities.php?filename=200902021845011\nhttp://www.edamascus.sy/_business.php?filename=200902031620011\nhttp://www.edamascus.sy/_news.php?filename=200902041650013\nhttp://www.edamascus.sy/_news.php?filename=200902060300011\nThank you all for waiting a month 🙂\nI’m Learning Python part 8 will be here soon.\n","permalink":"https://mpcabd.xyz/and-were-back/","summary":"\u003cp\u003eAfter a month of not blogging, I’m back to blogging for Python.\u003c/p\u003e\n\u003cp\u003eThis month had a lot in it:\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003eComputer Science exams @ Damascus University, so I had to study a lot.\u003c/li\u003e\n\u003cli\u003eScientific Calculations Project, the project of this semester.\u003c/li\u003e\n\u003cli\u003eFOSS Workshop, which my friends and I arranged to in Damascus, and it was more than wonderful.\u003c/li\u003e\n\u003c/ul\u003e\n\u003cp\u003eAfter finishing my Scientific Calculations Project I made the choice of removing Windows for good from my computer, I’m going to make Ubuntu my only operating system to use.\u003c/p\u003e","title":"And we’re back"},{"content":" Hello, if you don\u0026#8217;t know already, I\u0026#8217;m a Computer Science student from Damascus University Syria. My friends and I are working on an Open Source Free Software workshop here at the faculty of Computer Science, the workshop will take place on February 2009, but we are gathering some resources and information from now. The workshop will have lectures about Open Source, Free Software, Licenses, Open Source Free alternative for Commercial Proprietary software, and of course Linux OS. The workshop will also contain an Installation Festival where we are going to install Ubuntu 8.10 Intrepid Ibex for students on their devices and teach them how to use it. I\u0026#8217;m gonna put some questions here and I\u0026#8217;ll ask you to answer it, whether you own an Open Source company or you work for one. I\u0026#8217;m neither a journalist nor an analyst seeker, but I want some answers from you to introduce you the way you want to students, please don\u0026#8217;t waste this message because I\u0026#8217;m not a journalist, we want to spread the culture of Free Open Source Software here between students and contributing to the workshop would be very kind of you. Please allow me to ask you to answer the following questions: 1. When did you start your company and who started it? 2. How did you start your company? 3. Why Free Open Source Software? What was the base idea of your company? Did you consider that offering Free Open Source Software might not give you much money? Or money wasn\u0026#8217;t your concern at first? 4. What problems did you have to go through till the first line of code was written? 5. Most people ask; where and how do you make money? This question needs to be fully described because in my humble opinion it is the most question people and especially students would care about. 6. Starting a company needs a hard working faithful staff, how did you start collecting your staff? How did you convinced people to work with you knowing that you offer Free Open Source Software? 7. After you finished your first prototype, how did you advertise it? 8. What was the reaction of people who tested the first software of yours? 9. How many people contributed to the first version of your product? And how many downloaded it and used it? 10. You must have received thousands of feedback messages after your first product; do you remember the approximate count? 11. Competition with know software is indeed hard, how did you manage to make your path between your competitors? 12. What are the phases that your company had been in till now? What difficulties and problems did you face? 13. How many people contributed to the second version of your product? 14. How many people contributed to the last version of your product? 15. How many people did you count using your software? 16. Do you advice students to start their companies and follow your path, or do you advice them to look for jobs in companies like yours? 17. What must the student of Computer Science study to be able to work for you? What techniques? Programming Languages? Tools? What do you seek in your workers to have and know? 18. If by any means you had the chance to talk to our students and give them a message, what would it be? You can of course answer as much as you want of the questions above, but I hope you answer all of them for the sake of Free Open Source Software and knowledge. Thank you from all my heart, and on behalf of my friends and colleagues I thank you, we appreciate your efforts and your contributions. Abd Allah Diab \u0026lt;p dir=\u0026quot;ltr\u0026quot; style=\u0026quot;direction: ltr; text-align: left;\u0026quot;\u0026gt; Computer Science Faculty \u0026lt;/p\u0026gt; \u0026lt;p dir=\u0026quot;ltr\u0026quot; style=\u0026quot;direction: ltr; text-align: left;\u0026quot;\u0026gt; Damascus University \u0026lt;/p\u0026gt; \u0026lt;p dir=\u0026quot;ltr\u0026quot; style=\u0026quot;direction: ltr; text-align: left;\u0026quot;\u0026gt; Syria \u0026lt;/p\u0026gt; ","permalink":"https://mpcabd.xyz/foss-workshop/","summary":"\u003cp dir=\"ltr\" style=\"direction: ltr; text-align: left;\"\u003e\n  Hello, if you don\u0026#8217;t know already, I\u0026#8217;m a Computer Science student from Damascus University Syria.\n\u003c/p\u003e\n\u003cp dir=\"ltr\" style=\"direction: ltr; text-align: left;\"\u003e\n  My friends and I are working on an Open Source Free Software workshop here at the faculty of Computer Science, the workshop will take place on February 2009, but we are gathering some resources and information from now.\n\u003c/p\u003e\n\u003cp dir=\"ltr\" style=\"direction: ltr; text-align: left;\"\u003e\n  The workshop will have lectures about Open Source, Free Software, Licenses, Open Source Free alternative for Commercial Proprietary software, and of course Linux OS.\n\u003c/p\u003e\n\u003cp dir=\"ltr\" style=\"direction: ltr; text-align: left;\"\u003e\n  The workshop will also contain an Installation Festival where we are going to install Ubuntu 8.10 Intrepid Ibex for students on their devices and teach them how to use it.\n\u003c/p\u003e\n\u003cp dir=\"ltr\" style=\"direction: ltr; text-align: left;\"\u003e\n  I\u0026#8217;m gonna put some questions here and I\u0026#8217;ll ask you to answer it, whether you own an Open Source company or you work for one.\n\u003c/p\u003e\n\u003cp dir=\"ltr\" style=\"direction: ltr; text-align: left;\"\u003e\n  I\u0026#8217;m neither a journalist nor an analyst seeker, but I want some answers from you to introduce you the way you want to students, please don\u0026#8217;t waste this message because I\u0026#8217;m not a journalist,  we want to spread the culture of Free Open Source Software here between students and contributing to the workshop would be very kind of you.\n\u003c/p\u003e","title":"FOSS Workshop"},{"content":"I’m sorry to announce that I won’t be able to post any posts until the end of January 2009, and that’s because of my university exams 🙂\nThank you for visiting me, and see ya soon 😉\nP.S.\nWish me luck and high marks 😀\n","permalink":"https://mpcabd.xyz/just-a-month/","summary":"\u003cp\u003eI’m sorry to announce that I won’t be able to post any posts until the end of January 2009, and that’s because of my university exams 🙂\u003c/p\u003e\n\u003cp\u003eThank you for visiting me, and see ya soon 😉\u003c/p\u003e\n\u003cp\u003eP.S.\u003c/p\u003e\n\u003cp\u003eWish me luck and high marks 😀\u003c/p\u003e","title":"Just a month"},{"content":" I\u0026#8217;m Learning Python (part 7) \u0026lt;p\u0026gt; \u0026lt;img title=\u0026quot;Python Logo\u0026quot; src=\u0026quot;http://www.python.org/images/python-logo.gif\u0026quot; alt=\u0026quot;Python Logo\u0026quot; /\u0026gt; \u0026lt;/p\u0026gt; Apology: First of all I wanna apologize for being late with this part, I\u0026#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.\nNumbers: Numbers in Python are divided into 5 sections: Integers: Such as: 1234, -1234, 0 Long Integers (unlimited size): Such as: 71632487932648921735413278645238947231659821365213847L 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: /\u003e\u003e\u003e TheLongVariable = 99999999999999999999999999 /\u003e\u003e\u003e TheLongVariable 99999999999999999999999999L Floating Point Numbers: Such as: 1.234, 3.14e-10, 4.01e+12 You can define them using points, e or E. Octal and hex literals: Such as: 0172, 0x9fab, 0X3FBC 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. Complex Numbers: Such as: 3+4j, 3.0-5.1j, 3J 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: 1 + 3j, 3j, 5J, -10.1j Python has lots of built-in numeric tools: Of course you can use +, -, *, /, \u003c, \u003e, ==, !=, \u003c\u003e as any other programming language, but Python has more: **: Power, 2 ** 3 is 8. //: Is truncated division, 5 // 2 is 2 %: Remainder, 5 % 2 is 1 You can use also bitwise operations: /\u003e\u003e, \u003c\u003c shift right and left, 5 \u003c\u003c 2 is 20, 24 \u003e\u003e 3 is 3. |, \u0026 Or and And, 4 | 3 is 7, 7 \u0026 2 is 2. Just as any other programming language, Python deals with expressions using operator precedence: 3 + 4 * 2 is 11 because * is done before +. Of course you can use parentheses to define the way you want to deal with the expression, (3+ 4) * 2 is 14. 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: Integers \u003c Long Integers \u003c Floating Points \u003c Complex Numbers. 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). Variables: During our trip in Python till now we used variables but we haven\u0026#8217;t talked about them: Variables are created once they are assigned a value. Variables are replaced with their values in expressions. You can\u0026#8217;t use an unassigned variable, because simply you don\u0026#8217;t have the variable yet. Variables are references to objects. repr \u0026 str: Try this /\u003e\u003e\u003e a = 3 /\u003e\u003e\u003e b = 4 /\u003e\u003e\u003e b / (2.0 + a) 0.80000000000000004 /\u003e\u003e\u003e print b / (2.0 + a) 0.8 We\u0026#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. More Functions: Python provides functions for Octal and Hex conversion: /\u003e\u003e\u003e oct(64) \u0026#8216;0100\u0026#8217; /\u003e\u003e\u003e oct(8 ) \u0026#8216;010\u0026#8217; /\u003e\u003e\u003e hex(255) \u0026#8216;0xff\u0026#8217; And vice versa, Python provides functions for retrieving integers out of Hex and Oct: /\u003e\u003e\u003e int(\u0026#8216;0234\u0026#8217;) 234 /\u003e\u003e\u003e int(\u0026#8216;0234\u0026#8217;, 8 ) 256 /\u003e\u003e\u003e int(\u0026#8216;0234\u0026#8242;, 16) 564 And it also provides a way to format numbers in strings, which we will cover in another part, but a small example won\u0026#8217;t hurt: /\u003e\u003e\u003e \u0026#8220;%o %x\u0026#8221; % (25, 21) \u0026#8217;31 15\u0026#8217; Other built-in functions and methods are in math module, which you can import and use: /\u003e\u003e\u003e import math /\u003e\u003e\u003e math.pi, math.e (3.1415926535897931, 2.7182818284590451) /\u003e\u003e\u003e math.sin(math.pi / 2) 1.0 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\nBottom Line: 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. Cheers. ","permalink":"https://mpcabd.xyz/im-learning-python-part-7/","summary":"\u003cdiv dir=\"ltr\"\u003e\n  \u003cdiv dir=\"ltr\" style=\"text-align: center;\"\u003e\n    \u003ch1 style=\"font-size: 18pt; font-family: Verdana;\"\u003e\n      I\u0026#8217;m Learning Python (part 7)\n    \u003c/h1\u003e\n\u003cpre\u003e\u003ccode\u003e\u0026lt;p\u0026gt;\n  \u0026lt;img title=\u0026quot;Python Logo\u0026quot; src=\u0026quot;http://www.python.org/images/python-logo.gif\u0026quot; alt=\u0026quot;Python Logo\u0026quot; /\u0026gt;\n\u0026lt;/p\u0026gt;\n\u003c/code\u003e\u003c/pre\u003e\n  \u003c/div\u003e\n  \u003ch1 style=\"font-family: Georgia;\"\u003e\n    Apology:\n  \u003c/h1\u003e\n  \u003cp\u003e\n    First of all I wanna apologize for being late with this part, I\u0026#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.\u003cbr /\u003e","title":"I’m Learning Python part 7"},{"content":" I\u0026#8217;m Learning Python (part 6) \u0026lt;p\u0026gt; \u0026lt;img title=\u0026quot;Python Logo\u0026quot; src=\u0026quot;http://www.python.org/images/python-logo.gif\u0026quot; alt=\u0026quot;Python Logo\u0026quot; /\u0026gt; \u0026lt;/p\u0026gt; Dictionaries 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\u0026#8217;t have two identical keys with different values. Dictionaries are defined using curly braces { and } as the following: \u003e\u003e\u003e D = {\u0026#8216;name\u0026#8217; : \u0026#8216;Abd Allah Diab\u0026#8217;, \u0026#8216;age\u0026#8217; : 19, \u0026#8216;job\u0026#8217; : \u0026#8216;Web Developer\u0026#8217;} Now we can access any of the pairs using only the key: \u003e\u003e\u003e D[\u0026#8216;age\u0026#8217;] 19 Dictionaries are mutable objects, which means we can change their values in place: \u003e\u003e\u003e D[\u0026#8216;age\u0026#8217;] += 1 \u003e\u003e\u003e D[\u0026#8216;age\u0026#8217;] 20 We can add new pairs also easily: \u003e\u003e\u003e D[\u0026#8216;eyes\u0026#8217;] = \u0026#8216;brown\u0026#8217; \u003e\u003e\u003e D {\u0026#8216;job\u0026#8217; : \u0026#8216;Web Developer\u0026#8217;, \u0026#8216;age\u0026#8217; : 20\u0026#8242;, \u0026#8216;eyes\u0026#8217; : \u0026#8216;brown\u0026#8217;, \u0026#8216;name\u0026#8217; : \u0026#8216;Abd Allah Diab\u0026#8217;} 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.\nTo sort a dictionary you should sort its keys and then print the values of the keys after sorting like the following: \u003e\u003e\u003e keys = D.keys() \u003e\u003e\u003e keys [\u0026#8216;job\u0026#8217;, \u0026#8216;age\u0026#8217;, \u0026#8216;eyes\u0026#8217;, \u0026#8216;name\u0026#8217;] \u003e\u003e\u003e keys.sort() \u003e\u003e\u003e keys [\u0026#8216;age\u0026#8217;, \u0026#8216;eyes\u0026#8217;, \u0026#8216;job\u0026#8217;, \u0026#8216;name\u0026#8217;] \u003e\u003e\u003e for key in keys: print key, \u0026#8216;=\u003e\u0026#8217;, D[key] age =\u003e 20 eyes =\u003e brown job =\u003e Web Developer name =\u003e Abd Allah Diab Here we used a for loop which I haven\u0026#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). Please notice the indentation, after the for declaration you must hit the \u0026#8216;tab\u0026#8217; for each line inside the for loop, and to exit the loop just don\u0026#8217;t hit the \u0026#8216;tab\u0026#8217; (press \u0026#8216;enter\u0026#8217; in interactive mode). You can make use of a new method called \u0026#8216;sorted\u0026#8217; which takes any iteratable object (like a sequence or a string etc): \u003e\u003e\u003e for key in sorted(D) print key, \u0026#8216;=\u003e\u0026#8217;, D[key] age =\u003e 20 eyes =\u003e brown job =\u003e Web Developer name =\u003e Abd Allah Diab Nesting 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 \u0026#8216;name\u0026#8217; in the dictionary, and to save a list of jobs inside the \u0026#8216;job\u0026#8217; in the dictionary, I\u0026#8217;d do that just like I nested matrices last time: \u003e\u003e\u003e D = {\u0026#8216;name\u0026#8217; : {\u0026#8216;first\u0026#8217; : \u0026#8216;Abd Allah\u0026#8217;, \u0026#8216;last\u0026#8217; : \u0026#8216;Diab\u0026#8217;}, \u0026#8216;age\u0026#8217; : 19, \u0026#8216;job\u0026#8217; : [\u0026#8216;Web Developer\u0026#8217;, \u0026#8216;Teacher\u0026#8217;, \u0026#8216;Student\u0026#8217;]} Now let\u0026#8217;s see how we can access what we\u0026#8217;ve built: \u003e\u003e\u003e D[\u0026#8216;name\u0026#8217;] {\u0026#8216;first\u0026#8217; : \u0026#8216;Abd Allah\u0026#8217;, \u0026#8216;last\u0026#8217; : \u0026#8216;Diab\u0026#8217;} \u003e\u003e\u003e D[\u0026#8216;name\u0026#8217;][\u0026#8216;first\u0026#8217;] \u0026#8216;Abd Allah\u0026#8217; \u003e\u003e\u003e D[\u0026#8216;name\u0026#8217;][\u0026#8216;last\u0026#8217;] \u0026#8216;Diab\u0026#8217; \u003e\u003e\u003e D[\u0026#8216;job\u0026#8217;] [\u0026#8216;Web Developer\u0026#8217;, \u0026#8216;Teacher\u0026#8217;, \u0026#8216;Student\u0026#8217;] \u003e\u003e\u003e D[\u0026#8216;job\u0026#8217;][0] \u0026#8216;Web Developer\u0026#8217; \u003e\u003e\u003e D[\u0026#8216;job\u0026#8217;][-1] \u0026#8216;Student\u0026#8217; Pretty easy right? 🙂 Memory issue Did you ask yourself where did the old D dictionary go? 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. Missing keys When accessing a dictionary you should be careful to missing keys, especially when the dictionary is filled dynamically. Accessing a missing key will be a mistake: \u003e\u003e\u003e D[\u0026#8216;FFF\u0026#8217;] #Will give you a key error.\nTo avoid this mistake you can ask the dictionary if it has the key then you can access it: \u003e\u003e\u003e if not D.has_key(\u0026#8216;fff\u0026#8217;): print \u0026#8216;MISS\u0026#8217; MISS Here we used the if control, which takes this form: if : Block1 elif : Block2 .\n. elif : BlockN else: Block Notice the indentation, \u0026#8216;cuz in Python the scope is defined using indention not curly braces or Begin and End. For Loops, List Comprehensions and Performance Every list comprehension can be done using a for loop instead: \u003e\u003e\u003e squares = [x ** 2 for x in [1, 2, 3, 4, 5]] \u003e\u003e\u003e squares [1, 4, 9, 16, 25] Can be done: \u003e\u003e\u003e squares = [] \u003e\u003e\u003e for x in [1, 2, 3, 4, 5] squares.append(x ** 2) \u003e\u003e\u003e squares [1, 4, 9, 16, 25] But the former is faster than the latter (sometimes it is twice faster), that\u0026#8217;s because Python is optimized, and every new version is faster and optimized more than old ones. So the rule in Python is \u0026#8220;Code for simplicity and readability firs, and worry about performance later\u0026#8221; but in most cases you will stop after writing a readable program, \u0026#8216;cuz Python is optimized by itself. Tuples Tuples (pronounced \u0026#8216;tooples\u0026#8217;) are just like lists but they are immutable, which mean that they can\u0026#8217;t be changed once the are created, but like strings support type methods (split, len, \u0026#8230;) and nesting and sequence operations. Tuples are defined in parentheses ( ): \u003e\u003e\u003e T = (1, 2, 3, 4) \u003e\u003e\u003e T (1, 2, 3, 4) \u003e\u003e\u003e T[2] 3 \u003e\u003e\u003e T[-1] 4 \u003e\u003e\u003e T = T + (5, 6, 7) \u003e\u003e\u003e T (1, 2, 3, 4, 5, 7) 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\u0026#8217;t want it to be changed, or when you send lists through your program and you don\u0026#8217;t want them to be changed, you\u0026#8217;ll use tuples then. Other File Types Those types we discussed aren\u0026#8217;t the only types, there exist more types, such as sets, which are like mathematical sets (a container for a list of objects): \u003e\u003e\u003e X = set([1, 2, 3, 4]) \u003e\u003e\u003e X set([1, 2, 3, 4]) \u003e\u003e\u003e X.add(5) \u003e\u003e\u003e X set([1, 2, 3, 4, 5]) \u003e\u003e\u003e Y = set([1, 6, 3]) \u003e\u003e\u003e X \u0026 Y #Intersection set([1, 3]) \u003e\u003e\u003e X | Y #Union set([1, 2, 3, 4, 5, 6]) \u003e\u003e\u003e X \u0026#8211; Y #Difference\nset([2, 4, 5]) Python also supports lots of types, but we won\u0026#8217;t cover them all here (or at least now :)). User-defined Types You can build your own classes in Python: \u003e\u003e\u003e class Man: def __intit__(self, name, age): #Constructor which takes two parameters and saves them self.name = name #self is the object that we\u0026#8217;re calling the method on. self.age = age def lastname(self): #A method to get the last name of the man. return self.name.split(\u0026#8216; \u0026#8216;)[-1] Now you can use your class: \u003e\u003e\u003e me = Man(\u0026#8216;Abd Allah Diab\u0026#8217;, 19) #Initialize a new instance of Man \u003e\u003e\u003e me.lastname() \u0026#8216;Diab\u0026#8217; \u003e\u003e\u003e me.age 19 We won\u0026#8217;t discuss classes and objects here, but I wanted to show you that you can have your own type easily. Bottom Line Here we come to the end of our tour on built in primitive types of Python, Next time we\u0026#8217;ll start our detailed trip to Numbers 🙂 Until then keep coding and make mistakes, and don\u0026#8217;t forget to learn of your mistakes 😀 Cheers. ","permalink":"https://mpcabd.xyz/im-learning-python-part-6/","summary":"\u003cdiv dir=\"ltr\"\u003e\n  \u003cdiv style=\"text-align: center;\"\u003e\n    \u003ch1 style=\"font-size: 18pt; font-family: Verdana;\"\u003e\n      I\u0026#8217;m Learning Python (part 6)\n    \u003c/h1\u003e\n\u003cpre\u003e\u003ccode\u003e\u0026lt;p\u0026gt;\n  \u0026lt;img title=\u0026quot;Python Logo\u0026quot; src=\u0026quot;http://www.python.org/images/python-logo.gif\u0026quot; alt=\u0026quot;Python Logo\u0026quot; /\u0026gt;\n\u0026lt;/p\u0026gt;\n\u003c/code\u003e\u003c/pre\u003e\n  \u003c/div\u003e\n  \u003ch1 style=\"font-family: Georgia;\"\u003e\n    Dictionaries\n  \u003c/h1\u003e\n  \u003cdiv dir=\"ltr\"\u003e\n    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\u0026#8217;t have two identical keys with different values.\n  \u003c/div\u003e\n  \u003cp\u003e","title":"I’m Learning Python part 6"},{"content":" I\u0026#8217;m Learning Python (part 5) \u0026lt;p\u0026gt; \u0026lt;img title=\u0026quot;Python Logo\u0026quot; src=\u0026quot;http://www.python.org/images/python-logo.gif\u0026quot; alt=\u0026quot;Python Logo\u0026quot; /\u0026gt; \u0026lt;/p\u0026gt; String Is Immutable? Last time I told you to try to change a specified character, you must have failed if you tried:\n\u003e\u003e\u003e s[0] = \u0026#8216;c\u0026#8217;\nThe error you\u0026#8217;d get is:\nTypeError: \u0026#8216;str\u0026#8217; object does not support item assignment\nThis 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.\nMore Methods? All the previous methods and operations are sequence operations, but strings have more methods:\n\u003e\u003e\u003e s = \u0026#8216;My Text\u0026#8217;\n\u003e\u003e\u003e s.find(\u0026#8216;Tex\u0026#8217; ) #returns the index of the first occurrence of the parameter\n3\n\u003e\u003e\u003e s.find(\u0026#8216;abc\u0026#8217; ) #if the parameter wasn\u0026#8217;t found it will return -1\n-1\n\u003e\u003e\u003e s.replace(\u0026#8216;Text\u0026#8217;, \u0026#8216;Code\u0026#8217; ) #replaces every occurrence of the first parameter with the second one \u0026#8216;My Code\u0026#8217; \u003e\u003e\u003e s #notice that the string hasn\u0026#8217;t changed\n\u0026#8216;My Text\u0026#8217;\n\u003e\u003e\u003e s = \u0026#8216;aa,bb,cc,dd\u0026#8217;\n\u003e\u003e\u003e s.split(\u0026#8216;,\u0026#8217; ) #splits the string into a list of values separated with the parameter\n[\u0026#8216;aa\u0026#8217;, \u0026#8216;bb\u0026#8217;, \u0026#8216;cc\u0026#8217;, \u0026#8216;dd\u0026#8217;]\n\u003e\u003e\u003e s =\u0026#8217;My Text\\n\u0026#8217;\n\u003e\u003e\u003e s.rstrip() #removes white space characters from the right of the string\n\u0026#8216;My Text\u0026#8217;\n\u003e\u003e\u003e s #don\u0026#8217;t forget that the string hasn’t changed 😉\n\u0026#8216;My Text\\n\u0026#8217;\n\u003e\u003e\u003e len(s) #returns the length of the string\n8\n\u003e\u003e\u003e ord(\u0026#8216;\\n\u0026#8217; ) #returns the ASCII code for the given character\n10\n\u003e\u003e\u003e s = \u0026#8216;MyTextA\u0026#8217; # is the null character though it doesn\u0026#8217;t terminate the string ?\n\u003e\u003e\u003e len(s)\n9\n\u003e\u003e\u003e s\n\u0026#8216;MyTextA\u0026#8217;\nWanna Get More? Of course I can\u0026#8217;t talk about every method for every type, but I\u0026#8217;ll give you a simple way to get more, in Python there is a method called \u0026#8220;dir\u0026#8221; which lists the object\u0026#8217;s methods and properties:\n\u003e\u003e\u003e dir(s)\n[\u0026#8216;__add__\u0026#8217;, \u0026#8216;__class__\u0026#8217;, \u0026#8216;__contains__\u0026#8217;, \u0026#8216;__delattr__\u0026#8217;, \u0026#8216;__doc__\u0026#8217;, \u0026#8216;__eq__\u0026#8217;, \u0026#8216;__format__\u0026#8217;, __ge__\u0026#8217;, \u0026#8216;__getattribute__\u0026#8217;, \u0026#8216;__getitem__\u0026#8217;, \u0026#8216;__getnewargs__\u0026#8217;, \u0026#8216;__getslice__\u0026#8217;, \u0026#8216;__gt__\u0026#8217;, __hash__\u0026#8217;, \u0026#8216;__init__\u0026#8217;, \u0026#8216;__le__\u0026#8217;, \u0026#8216;__len__\u0026#8217;, \u0026#8216;__lt__\u0026#8217;, \u0026#8216;__mod__\u0026#8217;, \u0026#8216;__mul__\u0026#8217;, \u0026#8216;__ne__\u0026#8217;, \u0026#8216;__new__\u0026#8217;, __reduce__\u0026#8217;, \u0026#8216;__reduce_ex__\u0026#8217;, \u0026#8216;__repr__\u0026#8217;, \u0026#8216;__rmod__\u0026#8217;, \u0026#8216;__rmul__\u0026#8217;, \u0026#8216;__setattr__\u0026#8217;, __sizeof__\u0026#8217;, __str__\u0026#8217;, \u0026#8216;__subclasshook__\u0026#8217;, \u0026#8216;_formatter_field_name_split\u0026#8217;, \u0026#8216;_formatter_parser\u0026#8217;, \u0026#8216;capitalize\u0026#8217;, center\u0026#8217;, \u0026#8216;count\u0026#8217;, \u0026#8216;decode\u0026#8217;, \u0026#8216;encode\u0026#8217;, \u0026#8216;endswith\u0026#8217;, \u0026#8216;expandtabs\u0026#8217;, \u0026#8216;find\u0026#8217;, \u0026#8216;format\u0026#8217;, \u0026#8216;index\u0026#8217;, isalnum\u0026#8217;, isalpha\u0026#8217;, \u0026#8216;isdigit\u0026#8217;, \u0026#8216;islower\u0026#8217;, \u0026#8216;isspace\u0026#8217;, \u0026#8216;istitle\u0026#8217;, \u0026#8216;isupper\u0026#8217;,\u0026#8217;join\u0026#8217;, \u0026#8216;ljust\u0026#8217;, \u0026#8216;lower\u0026#8217;, \u0026#8216;lstrip\u0026#8217;, \u0026#8216;partition\u0026#8217;, replace\u0026#8217;, \u0026#8216;rfind\u0026#8217;, \u0026#8216;rindex\u0026#8217;, \u0026#8216;rjust\u0026#8217;, \u0026#8216;rpartition\u0026#8217;, \u0026#8216;rsplit\u0026#8217;, \u0026#8216;rstrip\u0026#8217;, \u0026#8216;split\u0026#8217;, \u0026#8216;splitlines\u0026#8217;, \u0026#8216;startswith\u0026#8217;, \u0026#8216;strip\u0026#8217;, \u0026#8216;swapcase\u0026#8217;, \u0026#8216;title\u0026#8217;, \u0026#8216;translate\u0026#8217;, \u0026#8216;upper\u0026#8217;, \u0026#8216;zfill\u0026#8217;]\nDon\u0026#8217;t care about those who has underscores, but the rest are methods.\nNow to know more about a specified method you can use the \u0026#8220;help\u0026#8221; method:\n\u003e\u003e\u003e help(s.count)\nHelp on built-in function count:\ncount(\u0026#8230;)\nS.count(sub[, start[, end]]) -\u003e int\nReturn the number of non-overlapping occurrences of substring sub in string S[start:end].\nOptional arguments start and end are interpreted as in slice notation.\nWhat About Regular Expressions? Users with a background about regular expressions will definitely ask about it, and the answer is yes you can use them with strings:\n\u003e\u003e\u003e import re\n\u003e\u003e\u003e match = re.match(\u0026#8216;Hello[ \\t]*(.*)world\u0026#8217;, \u0026#8216;Hello Python world\u0026#8217; )\n\u003e\u003e\u003e match.group(1)\n\u0026#8216;Python\u0026#8217;\n\u003e\u003e\u003e match = re.match(\u0026#8216;/(.*)/(.*)/(.*)/\u0026#8217;, \u0026#8216;/usr/lib/bin/\u0026#8217; )\n\u003e\u003e\u003e match.groups()\n(\u0026#8216;usr\u0026#8217;, \u0026#8216;lib\u0026#8217;, \u0026#8216;bin\u0026#8217; )\nOf course you can do more as you know with regular expressions like replacing and splitting, try \u0026#8220;dir\u0026#8221; and \u0026#8220;help\u0026#8221; for more 😉 What Is The Difference Between \u0026#8216;Text\u0026#8217; And \u0026#8220;Text\u0026#8221;? There is no difference at all, but there is a third way to write strings:\n\u003e\u003e\u003e s = \u0026#8220;\u0026#8221;\u0026#8221;Text\u0026#8221;\u0026#8221;\u0026#8221;\nThis way preserves the text formatting, which means you can write:\n\u003e\u003e\u003e s = \u0026#8220;\u0026#8221;\u0026#8221;\n\u0026#8217;I Love \u0026#8220;Python\u0026#8221;\u0026#8216;\n\u0026#8220;\u0026#8221;\u0026#8221;\n\u003e\u003e\u003e s\n\u0026#8216;\\n\\n\\n\\n\u0026#8217;I Love \u0026#8220;Python\u0026#8221;\u0026#8216;\\n\\n\\n\u0026#8217;\nYou can use this way to write pre-formatted text just like XML and HTML. Lists And Sequences: 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:\n\u003e\u003e\u003e L = [123, \u0026#8216;mpcabd\u0026#8217;, 1.23] #lists support multi-types 🙂\n\u003e\u003e\u003e len(L)\n3\n\u003e\u003e\u003e L[0]\n123\n\u003e\u003e\u003e L[-1]\n1.23\n\u003e\u003e\u003e L[:-1]\n[123, \u0026#8216;mpcabd\u0026#8217;]\n\u003e\u003e\u003e L + [4, 5, 6]\n[123, \u0026#8216;mpcabd\u0026#8217;, 1.23, 4, 5, 6]\n\u003e\u003e\u003e L\n[123, \u0026#8216;mpcabd\u0026#8217;, 1.23]\nLists are so much like arrays but they have no fixed size, so you can append to them and delete from them:\n\u003e\u003e\u003e L.append(111)\n\u003e\u003e\u003e L\n[123, \u0026#8216;mpcabd\u0026#8217;, 1.23, 111]\n\u003e\u003e\u003e L.pop(0)\n[\u0026#8216;mpcabd, 1.23, 111]\nYou can even sort and reverse them:\n\u003e\u003e\u003e L = [\u0026#8216;a\u0026#8217;, \u0026#8216;z\u0026#8217;, \u0026#8216;c\u0026#8217;]\n\u003e\u003e\u003e L.sort()\n\u003e\u003e\u003e L\n[\u0026#8216;a\u0026#8217;, \u0026#8216;c\u0026#8217;, \u0026#8216;z\u0026#8217;]\n\u003e\u003e\u003e L.reverse()\n[\u0026#8216;z\u0026#8217;, \u0026#8216;c\u0026#8217;, \u0026#8216;a\u0026#8217;]\nTo find more try \u0026#8220;dir\u0026#8221; and \u0026#8220;help\u0026#8221; 🙂 What abound boundaries? Try the following and you\u0026#8217;d see an error:\n\u003e\u003e\u003e L = [\u0026#8216;a\u0026#8217;, \u0026#8216;b\u0026#8217;, \u0026#8216;c\u0026#8217;]\n\u003e\u003e\u003e L[9]\nIndexError: list index out of range\nThis means that Python checks for boundaries not like C and C++. Can I Nest Lists? Yes 😀\n\u003e\u003e\u003e M = [\n[ 1, 2, 3 ], [ 4, 5, 6 ],\n[ 7, 8, 9 ] ]\n\u003e\u003e\u003e M\n[ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]\n\u003e\u003e\u003e M[1] [4, 5, 6]\n\u003e\u003e\u003e M[1][2]\n6\nThis is a good way to define matrices, but I advise you to use NumPy for mathematical operations, \u0026#8216;cuz it is optimized for fast use. What Are List Comprehensions? Python includes along with what we\u0026#8217;ve discussed a powerful methods called \u0026#8220;List Comprehension Expressions\u0026#8221;, suppose we wanna extract the second column of our previous matrix (M), what would you do? Python provides a good way:\n\u003e\u003e\u003e col2 = [row[1] for row in M]\n\u003e\u003e\u003e col2\n[2, 5, 8]\nNot good enough? Take this:\n\u003e\u003e\u003e [row[1] + 1 for row in M]\n[3, 6, 9]\n\u003e\u003e\u003e [row[1] for row in M if row[1] % 2 == 0]\n[2, 8]\nNot enough yet? Take this one and take a nap 🙂\n\u003e\u003e\u003e [M[i][i] for i in [0, 1, 2]]\n[1, 5, 9]\nNot enough? I\u0026#8217;ll kill you then 😈\nFor more wait for me to study 🙂 Bottom Line: I\u0026#8217;m sorry I was late this time but I\u0026#8217;m really having a busy phase @ work, please wait for more and don\u0026#8217;t get bored. Cheers. ","permalink":"https://mpcabd.xyz/im-learning-python-part-5/","summary":"\u003cdiv dir=\"ltr\"\u003e\n  \u003cdiv style=\"text-align: center;\"\u003e\n    \u003ch1 style=\"font-size: 18pt; font-family: Verdana;\"\u003e\n      I\u0026#8217;m Learning Python (part 5)\n    \u003c/h1\u003e\n\u003cpre\u003e\u003ccode\u003e\u0026lt;p\u0026gt;\n  \u0026lt;img title=\u0026quot;Python Logo\u0026quot; src=\u0026quot;http://www.python.org/images/python-logo.gif\u0026quot; alt=\u0026quot;Python Logo\u0026quot; /\u0026gt;\n\u0026lt;/p\u0026gt;\n\u003c/code\u003e\u003c/pre\u003e\n  \u003c/div\u003e\n  \u003ch1 style=\"font-family: Georgia;\"\u003e\n    String Is Immutable?\n  \u003c/h1\u003e\n  \u003cp\u003e\n    Last time I told you to try to change a specified character, you must have failed if you tried:\u003cbr /\u003e \u003cem\u003e\u003e\u003e\u003e s[0] = \u0026#8216;c\u0026#8217;\u003c/em\u003e\u003cbr /\u003e The error you\u0026#8217;d get is:\u003cbr /\u003e \u003cem\u003eTypeError: \u0026#8216;str\u0026#8217; object does not support item assignment\u003cbr /\u003e \u003c/em\u003eThis 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.\u003cbr /\u003e","title":"I’m Learning Python (part 5)"},{"content":" I\u0026#8217;m Learning Python (part 4) \u0026lt;p\u0026gt; \u0026lt;img title=\u0026quot;Python Logo\u0026quot; src=\u0026quot;http://www.python.org/images/python-logo.gif\u0026quot; alt=\u0026quot;Python Logo\u0026quot; /\u0026gt; \u0026lt;/p\u0026gt; Why Use Built-In Types? Most of the time in programming you\u0026#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, \u0026#8216;cuz some of them are written in C and C++.\nWhat Core Data Types Does Python Provide? As in any language, Python provides the usual list of types besides other data types: Numbers: 1234, 3.1415, 999L, 3+4j, Decimal String: \u0026#8216;Some text\u0026#8217;, \u0026#8220;a Text\u0026#8221; Lists: [1, [2, \u0026#8216;Three\u0026#8217;], 4] Dictionaries: {\u0026#8216;food\u0026#8217; : \u0026#8216;Lemon\u0026#8217;, \u0026#8216;taste\u0026#8217; : \u0026#8216;Yummy!\u0026#8217; } Tuples: (1, \u0026#8216;Name\u0026#8217;, 5, \u0026#8216;u\u0026#8217; ) Files: myFile = open(\u0026#8216;someFile\u0026#8217;, \u0026#8216;r\u0026#8217; ) Other Types: Sets, Types, Boolean, Object, None And don\u0026#8217;t forget that everything is an object at the end 😉\nAlthough 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.\nNow let\u0026#8217;s discuss the types in a glance \u0026#8216;cuz we\u0026#8217;ll talk about them in depth later. Numbers: Python provides: integers (1234), floating point (3.1415), unlimited precision long (43251278364218357642386321984621734982137469321856412L), complex numbers (4568 + 789j), fixed precision decimals and sets.\nPython also provides the simple operations:\n+ is used for addition, \u0026#8211; for subtraction, * for multiplication, ** for exponents, / for division.\nYou can calculate whatever you want (2 ** 1000000, but you don\u0026#8217;t wanna print 300000 digit ;)).\nWhen printing numbers there are two methods of printing, the first one is called \u0026#8216;repr\u0026#8217; (object as code) and it prints the number with full precision, the second one is called \u0026#8216;str\u0026#8217; which prints the number in a user-friendly way:\n\u003e\u003e\u003e 3.1415000000000002 * 2 #repr\n6.2830000000000004\n\u003e\u003e\u003e print 3.1415000000000002 * 2 #str\n6.283\nWe\u0026#8217;ll discuss this method later when we introduce classes 🙂\nBesides basic operations Python provides a module called \u0026#8216;math\u0026#8217; which has useful methods and variables:\n\u003e\u003e\u003e import math\n\u003e\u003e\u003e math.pi\n3.1415926535897931\n\u003e\u003e\u003e math.sqrt(123)\n11.090536506409418\nAnd it also provides a module called \u0026#8216;random\u0026#8217; which generates random numbers:\n\u003e\u003e\u003e import random\n\u003e\u003e\u003e random.random()\n0.8591504308650737 #You might get another value 😉\n\u003e\u003e\u003e random.choice([1, 2, 3, 4])\n4 #You might also get another value 😉\nWe\u0026#8217;ll discuss more numbers types soon, but now let\u0026#8217;s move to another type. Strings: Strings as you might all now are arrays of characters (in Python we call the array a sequence).\nSome of the sequence operations:\n\u003e\u003e\u003e s = \u0026#8216;My Text\u0026#8217;\n\u003e\u003e\u003e len(s)\n7\n\u003e\u003e\u003e s[0]\n\u0026#8216;M\u0026#8217;\n\u003e\u003e\u003e s[3]\n\u0026#8216;T\u0026#8217;\nA good indexing way is the negative indexing, which starts from left to right:\n\u003e\u003e\u003e s[-1] #Equivalent to s[len(s) – 1]\n\u0026#8216;t\u0026#8217;\n\u003e\u003e\u003e s[-2] #Equivalent to s[len(s) – 2]\n\u0026#8216;x\u0026#8217;\nSlicing is another way of indexing in sequences, and it is used to extract a portion of the sequence:\n\u003e\u003e\u003e s[3:6] #A slice starts from 3 and ends at 5 not 6\n\u0026#8216;Tex\u0026#8217;\nIn slicing the left parameter\u0026#8217;s default value is 0, and the right\u0026#8217;s is the length of the sequence, which leads to some other slicing operations:\n\u003e\u003e\u003e s[:]\n\u0026#8216;My Text\u0026#8217;\n\u003e\u003e\u003e s[1:]\n\u0026#8216;y Text\u0026#8217;\n\u003e\u003e\u003e s[1:len(s)] #Same as s[1:]\n\u0026#8216;y Text\u0026#8217;\n\u003e\u003e\u003e s #Notice that s hasn\u0026#8217;t changed, we were given new objects.\n\u0026#8216;My Text\u0026#8217;\n\u003e\u003e\u003es[:-1] #Everything but the last character 😉\n\u0026#8216;My Tex\u0026#8217;\nAs 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.\nAs sequences, strings support concatenation and repetition:\n\u003e\u003e\u003e s + \u0026#8216; Is Beautiful\u0026#8217;\n\u0026#8216;My Text Is Beautiful\u0026#8217;\n\u003e\u003e\u003e s #s hasn\u0026#8217;t changed\n\u0026#8216;My Text\u0026#8217;\n\u003e\u003e\u003e s * 5\n\u0026#8216; My TextMy TextMy TextMy TextMy Text\u0026#8217;\nYou see, + is used here for concatenation while in numbers it is used for addition, this is called operator overloading in other languages. Bottom Line: We\u0026#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?\nCheers. ","permalink":"https://mpcabd.xyz/im-learning-python-part-4/","summary":"\u003cdiv dir=\"ltr\"\u003e\n  \u003cdiv style=\"text-align: center;\"\u003e\n    \u003ch1 style=\"font-size: 18pt; font-family: Verdana;\"\u003e\n      I\u0026#8217;m Learning Python (part 4)\n    \u003c/h1\u003e\n\u003cpre\u003e\u003ccode\u003e\u0026lt;p\u0026gt;\n  \u0026lt;img title=\u0026quot;Python Logo\u0026quot; src=\u0026quot;http://www.python.org/images/python-logo.gif\u0026quot; alt=\u0026quot;Python Logo\u0026quot; /\u0026gt;\n\u0026lt;/p\u0026gt;\n\u003c/code\u003e\u003c/pre\u003e\n  \u003c/div\u003e\n  \u003ch1 style=\"font-family: Georgia;\"\u003e\n    Why Use Built-In Types?\n  \u003c/h1\u003e\n  \u003cp\u003e\n    Most of the time in programming you\u0026#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, \u0026#8216;cuz some of them are written in C and C++.\u003cbr /\u003e","title":"I’m Learning Python part 4"},{"content":" I\u0026#8217;m Learning Python (part 3) \u0026lt;p\u0026gt; \u0026lt;img title=\u0026quot;Python Logo\u0026quot; src=\u0026quot;http://www.python.org/images/python-logo.gif\u0026quot; alt=\u0026quot;Python Logo\u0026quot; /\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;h1 style=\u0026quot;font-family: Georgia;\u0026quot;\u0026gt; What Is Interactive Mode? \u0026lt;/h1\u0026gt; \u0026lt;p\u0026gt; When you install Python on your platform you\u0026amp;#8217;ll find an executable called \u0026amp;#8216;python\u0026amp;#8217;, when you run it you\u0026amp;#8217;ll find a terminal and you\u0026amp;#8217;ll see something like the following:\u0026lt;br /\u0026gt; \u0026lt;em\u0026gt;Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win32\u0026lt;br /\u0026gt; Type \u0026amp;#8220;help\u0026amp;#8221;, \u0026amp;#8220;copyright\u0026amp;#8221;, \u0026amp;#8220;credits\u0026amp;#8221; or \u0026amp;#8220;license\u0026amp;#8221; for more information.\u0026lt;br /\u0026gt; \u0026gt;\u0026gt;\u0026gt;\u0026lt;/em\u0026gt;\u0026lt;br /\u0026gt; This is called interactive coding (or interactive mode), here you can write Python statements and the interpreter will execute them directly, let\u0026amp;#8217;s try:\u0026lt;br /\u0026gt; \u0026lt;em\u0026gt;\u0026gt;\u0026gt;\u0026gt; print \u0026amp;#8220;I Love Python\u0026amp;#8221;\u0026lt;br /\u0026gt; I Love Python\u0026lt;br /\u0026gt; \u0026gt;\u0026gt;\u0026gt; print 2 ** 10\u0026lt;br /\u0026gt; 1024\u0026lt;br /\u0026gt; \u0026gt;\u0026gt;\u0026gt;\u0026lt;/em\u0026gt;\u0026lt;br /\u0026gt; You can write any statement here (even those who are more than on line as we’ll see later).\nIf 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.\nTo do so you can run the “exec” statement like this:\n\u0026raquo;\u0026gt; exec “print \u0026amp;#8221;I Love Python\u0026amp;#8221;”\nI Love Python\n\u0026raquo;\u0026gt;\nHere 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).\nYou must have noticed using the escape character \u0026amp;#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.\nAnother 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:\n\u0026raquo;\u0026gt; “I Love Python”\n‘I Love Python’\n\u0026raquo;\u0026gt;\nBut beware, you must 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.\nYou might ask, what about statements that don’t return values, what would the interactive mode print for them? The answer is: simply nothing 🙂\n\u0026raquo;\u0026gt; text = “I Love Python”\n\u0026raquo;\u0026gt;\nThe previous statement is an assignment statement, which declares a string called “text” and has the value of “I Love Python”.\nTo exit the interactive code you use the break character (Ctrl+Z in Windows, Ctrl+D in Linux) and hit return. \u0026lt;h1 style=\u0026quot;font-family: Georgia;\u0026quot;\u0026gt; What Are Modules? \u0026lt;/h1\u0026gt; \u0026lt;p\u0026gt; Let\u0026amp;#8217;s here explain the Python program hierarchy:\u0026lt;br /\u0026gt; Each program consists of modules -\u0026gt; Each module consists of statements -\u0026gt; Each statement consists of expressions -\u0026gt; Each expression creates and processes objects -\u0026gt; Objects are the raw materials you\u0026amp;#8217;ll use 🙂\u0026lt;br /\u0026gt; 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.\u0026lt;br /\u0026gt; We\u0026amp;#8217;ll use modules (for now) to run our code multiple times without the need of re-typing it again.\u0026lt;br /\u0026gt; You can access another module using \u0026amp;#8220;import\u0026amp;#8221; statement, so let\u0026amp;#8217;s try something: \u0026lt;/p\u0026gt; \u0026lt;ul\u0026gt; \u0026lt;li\u0026gt; Open your editor and write the following in it:\u0026lt;br /\u0026gt; text = \u0026amp;#8220;I Love Python\u0026amp;#8221;\u0026lt;br /\u0026gt; print text \u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; Save the file somewhere with the name \u0026amp;#8220;module1.py\u0026amp;#8221; \u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; Now start a new file and write the following in it:\u0026lt;br /\u0026gt; import module1\u0026lt;br /\u0026gt; module1.text = \u0026amp;#8220;You Know I Love Python\u0026amp;#8221;\u0026lt;br /\u0026gt; print module1.text \u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; Save the file in the same folder which has \u0026amp;#8220;module1.py\u0026amp;#8221; with the name \u0026amp;#8220;module2.py\u0026amp;#8221; \u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; Now let the Python interpreter run your module2 file:\u0026lt;br /\u0026gt; python [SOME FOLDER]/module2.py \u0026lt;/li\u0026gt; \u0026lt;li\u0026gt; You must see the following:\u0026lt;br /\u0026gt; I Love Python\u0026lt;br /\u0026gt; You Know I Love Python \u0026lt;/li\u0026gt; \u0026lt;/ul\u0026gt; \u0026lt;p\u0026gt; What happened here? In module2 I only printed the variable after editing it, why was it printed before it was edited?\u0026lt;br /\u0026gt; When you import a module, you\u0026amp;#8217;re simply running it, so the Python interpreter ran module1, and executed the print statement so you see \u0026amp;#8220;I Love Python\u0026amp;#8221;, then it executed module2, it edited the value of the variable in module1, then executed the print statement in module2, and you see \u0026amp;#8220;You Know I Love Python\u0026amp;#8221;.\u0026lt;br /\u0026gt; So importing means running, but what if I needed to run the code again? Knowing that you can\u0026amp;#8217;t import a module more than one, what should we do?\u0026lt;br /\u0026gt; There is another statement \u0026amp;#8220;reload\u0026amp;#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.\u0026lt;br /\u0026gt; Try adding this line to your code in module2.py:\u0026lt;br /\u0026gt; reload(module1)\u0026lt;br /\u0026gt; Re-run your module2 and you must see:\u0026lt;br /\u0026gt; I Love Python\u0026lt;br /\u0026gt; You Know I Love Python\u0026lt;br /\u0026gt; I Love Python\u0026lt;br /\u0026gt; The third line is actually the print statement in module1 file. \u0026lt;/p\u0026gt; \u0026lt;h1 style=\u0026quot;font-family: Georgia;\u0026quot;\u0026gt; What Is The Difference Between \u0026amp;#8220;import [MODULE]\u0026amp;#8221; And \u0026amp;#8220;from [MODULE] import\u0026amp;#8221;? \u0026lt;/h1\u0026gt; \u0026lt;p\u0026gt; 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\u0026amp;#8217;s name followed by a period before the variable\u0026amp;#8217;s name.\u0026lt;br /\u0026gt; The second – from [MODULE] import – imports the specified variables from the module, so to import the \u0026amp;#8220;text\u0026amp;#8221; variable from \u0026amp;#8220;module1\u0026amp;#8221; in the previous example you write:\u0026lt;br /\u0026gt; from module1 import text\u0026lt;br /\u0026gt; To import more than one variable separate them with columns:\u0026lt;br /\u0026gt; from [MODULE] impor [VAR1], [VAR2], …, [VARN]\u0026lt;br /\u0026gt; Notice that importing a variable lets you use the variable without the need to write the module\u0026amp;#8217;s name before it, you can simply use the \u0026amp;#8220;text\u0026amp;#8221; variable in module2 after importing it without writing module1.text.\u0026lt;br /\u0026gt; Beware that importing a variable that has the same name of a local variable will replace the local one, for instance:\u0026lt;br /\u0026gt; in module1.py write:\u0026lt;br /\u0026gt; text = \u0026amp;#8220;I Love Python\u0026amp;#8221;\u0026lt;br /\u0026gt; in module2.py write:\u0026lt;br /\u0026gt; text = \u0026amp;#8220;You Know I Love Python\u0026amp;#8221;\u0026lt;br /\u0026gt; from module1 import text\u0026lt;br /\u0026gt; print text \u0026lt;/p\u0026gt; \u0026lt;p\u0026gt; Executing module2 will give you: I Love Python. \u0026lt;/p\u0026gt; \u0026lt;h1 style=\u0026quot;font-family: Georgia;\u0026quot;\u0026gt; How can I write hints and comments in Python? \u0026lt;/h1\u0026gt; \u0026lt;p\u0026gt; Using the sharp \u0026amp;#8211; # \u0026amp;#8211; character will hint the following text until the end of the line:\u0026lt;br /\u0026gt; text = \u0026amp;#8220;I Love Python\u0026amp;#8221; \u0026lt;em\u0026gt;#a declaration of a variable named text\u0026lt;/em\u0026gt; \u0026lt;/p\u0026gt; \u0026lt;h1 style=\u0026quot;font-family: Georgia;\u0026quot;\u0026gt; Bottom Line: \u0026lt;/h1\u0026gt; \u0026lt;p\u0026gt; Next time we\u0026amp;#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. \u0026lt;/p\u0026gt; \u0026lt;p\u0026gt; Cheers. \u0026lt;/p\u0026gt;\u0026lt;/div\u0026gt; ","permalink":"https://mpcabd.xyz/im-learning-python-part-3/","summary":"\u003cdiv dir=\"ltr\"\u003e\n  \u003cdiv style=\"text-align: center;\" align=\"center\"\u003e\n    \u003ch1 style=\"font-size: 18pt; font-family: Verdana;\"\u003e\n      I\u0026#8217;m Learning Python (part 3)\n    \u003c/h1\u003e\n\u003cpre\u003e\u003ccode\u003e\u0026lt;p\u0026gt;\n  \u0026lt;img title=\u0026quot;Python Logo\u0026quot; src=\u0026quot;http://www.python.org/images/python-logo.gif\u0026quot; alt=\u0026quot;Python Logo\u0026quot; /\u0026gt;\u0026lt;/div\u0026gt; \n  \n  \u0026lt;h1 style=\u0026quot;font-family: Georgia;\u0026quot;\u0026gt;\n    What Is Interactive Mode?\n  \u0026lt;/h1\u0026gt;\n  \n  \u0026lt;p\u0026gt;\n    When you install Python on your platform you\u0026amp;#8217;ll find an executable called \u0026amp;#8216;python\u0026amp;#8217;, when you run it you\u0026amp;#8217;ll find a terminal and you\u0026amp;#8217;ll see something like the following:\u0026lt;br /\u0026gt; \u0026lt;em\u0026gt;Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win32\u0026lt;br /\u0026gt; Type \u0026amp;#8220;help\u0026amp;#8221;, \u0026amp;#8220;copyright\u0026amp;#8221;, \u0026amp;#8220;credits\u0026amp;#8221; or \u0026amp;#8220;license\u0026amp;#8221; for more information.\u0026lt;br /\u0026gt; \u0026gt;\u0026gt;\u0026gt;\u0026lt;/em\u0026gt;\u0026lt;br /\u0026gt; This is called interactive coding (or interactive mode), here you can write Python statements and the interpreter will execute them directly, let\u0026amp;#8217;s try:\u0026lt;br /\u0026gt; \u0026lt;em\u0026gt;\u0026gt;\u0026gt;\u0026gt; print \u0026amp;#8220;I Love Python\u0026amp;#8221;\u0026lt;br /\u0026gt; I Love Python\u0026lt;br /\u0026gt; \u0026gt;\u0026gt;\u0026gt; print 2 ** 10\u0026lt;br /\u0026gt; 1024\u0026lt;br /\u0026gt; \u0026gt;\u0026gt;\u0026gt;\u0026lt;/em\u0026gt;\u0026lt;br /\u0026gt; \n\u003c/code\u003e\u003c/pre\u003e","title":"I’m Learning Python part 3"},{"content":" I\u0026#8217;m Learning Python (part 2) \u0026lt;p\u0026gt; \u0026lt;img title=\u0026quot;Python Logo\u0026quot; src=\u0026quot;http://www.python.org/images/python-logo.gif\u0026quot; alt=\u0026quot;Python Logo\u0026quot; /\u0026gt; \u0026lt;/p\u0026gt; Who Uses Python? In the world there are more than 1 million Python user, that\u0026#8217;s because it\u0026#8217;s\nopen source, and because it is implemented for every platform, and it comes\nincluded within Linux distributions and Macintosh computers and more. Google uses Python in its web search system, and it employs the Python\u0026#8217;s\ncreator. YouTube is largely written in Python. BitTorrent file sharing system is a Python program. Intel, Cisco, HP, Seagate, Qualcomm and IB\u003c use Python for hardware\ntesting. Industrial Light \u0026 Magic, Pixar, and others use Python in the production\nof movie animation. NASA, Los Alamos, Fermilab, JPL, and others use Python for scientific\nprogramming. iRobot uses Python to develop commercial robotic vacuum cleaners 🙂 NSA uses Python for cryptography and intelligence analysis. See Python website for more.\nHow Does Python work? Python is not compiled (almost), it is interpreted. So when you run the program\nthe interpreter will run it line by line without compilation. You might say \u0026#8220;Why did you say almost?\u0026#8221;, the answer is, Python as described\nbefore can be compiled into byte code, so it\u0026#8217;ll be faster for the interpreter\nto execute it than the source code, just like Java\u0026#8217;s byte code and .NET\u0026#8217;s MSIL. Python files have a .py extension normally, so when you write Python code you\nshould save it with a .py extension. Let\u0026#8217;s try and write our first Hello World Python program: Open the editor you use (Emacs, Notepad, Notepad++, …). Write this line inside it: print \u0026#8220;Hello World, It\u0026#8217;s My First Python Program\u0026#8221; Save the file as .py file. Now you should tell the Python interpreter to run your file, depending\non your platform you should have the Python interpreter in (\u0026#8220;C:\\Python[VER]\\\u0026#8221;\nin Windows where [VER] is the version of the Python release you have [24,\n25, 26,…]) or in (\u0026#8220;/usr/bin/\u0026#8221; in Linux). In Windows open a command prompt and guide it to the location of your\nPython. In Linux open a terminal and go to the location of your Python interpreter. Now you can execute the following command on both platforms:python [FILE]Where [File] is the location of your .py file. Now you should see some thing like this:python [FILE]Hello World, It\u0026#8217;s My First Python Program Very easy, right? Although it is not that big program but you can run your files this way :). Now let\u0026#8217;s understand what happened: The Python interpreter was given a file to run. If it has write privileges it\u0026#8217;ll compile it into byte code and you\u0026#8217;ll see that\na new file was created next to your file with a .pyc extension, if it doesn\u0026#8217;t\nit\u0026#8217;ll run it as source code. It reads the first line (which is a print statement) and runs it and you see\nthe result, the execution takes place inside the PVM – Python Virtual Machine,\nwhich handles the execution of Python byte code and source code to run on more\nthan one platform without change in code. If you have a background in C or C++ you might find a change in the way of running\nand compiling code, \u0026#8216;cuz there is no making and linking in Python, and it is\nnot compiled into machine code (binary file), instead it runs inside a virtual\nmachine, that\u0026#8217;s why some Python code will run faster in C++ and C. But don\u0026#8217;t be afraid, 90% of the time you\u0026#8217;ll be running your programs as if they\nwere written in C or C++, there won\u0026#8217;t be any difference in the time of execution,\nand that’s because of the Python simplicity which makes the program in Python\nshorter and simpler than C or C++, and because it\u0026#8217;s optimization which we\u0026#8217;ll\ndescribe later. In Python you\u0026#8217;ll notice that the compiler and the execution environment are\none thing, the compiler always present in runtime, and that leads to rapid development\ncycle, with no linking and making stage. CPython runs inside the PVM, while Jython runs inside the JVM and IronPython\n.NET runs inside .NET Framework or Mono. Jython and IronPython .NET allows the Python program to use Java and .NET classes\nrespectively. If you don\u0026#8217;t wanna use Java or .NET classes you should use CPython, \u0026#8216;cuz it\u0026#8217;s\nfaster and the most complete, CPython runs like C and C++ so it is the fastest. In Jython the Python byte code is translated into Java byte code to be run inside\nthe JVM, while in .NET it is translated to MSIL. What Are The Frozen Binaries? Python has something called Frozen Binaries, which are the executables, if you\nchose to create a frozen binary for your program, you\u0026#8217;d end up with an executable\nthat runs on a specified platform (exe for Windows). This executable has a great feature; it includes your program along with its\ndependencies and the Python interpreter. Yes you don\u0026#8217;t have to tell the user\nto install a Python interpreter to be able to use your program, he/she doesn\u0026#8217;t\nhave to know that your program is a Python program. You can use Py2Exe to get an exe of your program (Which runs only in Windows),\nor PyInstaller which gives you the ability to create a frozen binary for Windows,\nLinux or UNIX. And you can use Freeze the original one. Those are available\nfree of charge, you can check Python website or Vaults of Parnassus (http://www.vex.net/parnassus). What IDE\u0026#8217;s To Use With Python? Python comes with a simple IDE called IDLE you can use it, or you can use Emacs, but IMHO\nEclipse with PyDev make a great IDE for you and Python. Bottom Line: Today it was just a description on how Python runs your program, and we wrote\nour Hello World program. For the next part, try to use the ** operator \u0026#8211; which is the power operator\nin Python – to see how much you can do in Python, e.g.: print 2 ** 10 1024 Try huge numbers and see 😉 Cheers. ","permalink":"https://mpcabd.xyz/i%E2%80%99m-learning-python-part-2/","summary":"\u003cdiv dir=\"ltr\"\u003e\n  \u003cdiv style=\"text-align: center;\"\u003e\n    \u003cp\u003e\n      \u003cspan style=\"font-size: large; font-family: georgia,palatino;\"\u003eI\u0026#8217;m Learning Python (part 2)\u003c/span\u003e\n    \u003c/p\u003e\n\u003cpre\u003e\u003ccode\u003e\u0026lt;p\u0026gt;\n  \u0026lt;img title=\u0026quot;Python Logo\u0026quot; src=\u0026quot;http://www.python.org/images/python-logo.gif\u0026quot; alt=\u0026quot;Python Logo\u0026quot; /\u0026gt;\n\u0026lt;/p\u0026gt;\n\u003c/code\u003e\u003c/pre\u003e\n  \u003c/div\u003e\n  \u003ch1 style=\"font-family: Georgia;\"\u003e\n    Who Uses Python?\n  \u003c/h1\u003e\n  \u003cp\u003e\n    In the world there are more than 1 million Python user, that\u0026#8217;s because it\u0026#8217;s\u003cbr /\u003e open source, and because it is implemented for every platform, and it comes\u003cbr /\u003e included within Linux distributions and Macintosh computers and more.\n  \u003c/p\u003e\n  \u003col\u003e\n    \u003cli\u003e\n      Google uses Python in its web search system, and it employs the Python\u0026#8217;s\u003cbr /\u003e creator.\n    \u003c/li\u003e\n    \u003cli\u003e\n      YouTube is largely written in Python.\n    \u003c/li\u003e\n    \u003cli\u003e\n      BitTorrent file sharing system is a Python program.\n    \u003c/li\u003e\n    \u003cli\u003e\n      Intel, Cisco, HP, Seagate, Qualcomm and IB\u003c use Python for hardware\u003cbr /\u003e testing.\n    \u003c/li\u003e\n    \u003cli\u003e\n      Industrial Light \u0026 Magic, Pixar, and others use Python in the production\u003cbr /\u003e of movie animation.\n    \u003c/li\u003e\n    \u003cli\u003e\n      NASA, Los Alamos, Fermilab, JPL, and others use Python for scientific\u003cbr /\u003e programming.\n    \u003c/li\u003e\n    \u003cli\u003e\n      iRobot uses Python to develop commercial robotic vacuum cleaners 🙂\n    \u003c/li\u003e\n    \u003cli\u003e\n      NSA uses Python for cryptography and intelligence analysis.\n    \u003c/li\u003e\n  \u003c/ol\u003e\n  \u003cp\u003e\n    See Python website for more.\u003cbr /\u003e","title":"I’m Learning Python part 2"},{"content":" I\u0026#8217;m Learning Python I’ll start posting this series of blogs on WordPress and CSC, here I’ll write what I’m gonna learn on my way to learning Python.\nIf 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.\nWhat is Python? Python is a programming language, this programming language was created in 1990, this programming language has proved its power through the last 18 years she’s been with us.\nWhy should I be interested in learning a new language? The most points that will catch your interest in this language are:\nIt’s Object Oriented:\nPython supports classes, inheritance, multiple inheritance, polymorphism, operator overloading and more.\nPython 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.\nIt’s Free:\nPython 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.\nIt’s Portable:\nPython 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, …).\nEverything is portable, that’s because Python code is compiled into byte-code (Like .NET and Java), and so it can be run on any platform with a Python interpreter.\nIt’s Powerful:\nPython 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.\nWhile sitting on more than one chair at the same time, Python provides the simplicity in writing a fully readable code.\nFrom its most powerful features I’ll write some and I’ll explain them deeply when I understand them 😀\nDynamic Typing. Automatic Memory Management: 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. Programming for large systems using OOP allows you to develop components and systems so you can reuse them in most of your applications. Built-in tools used for manipulating built-in types such as lists and collections. Libraries from regular expressions to networking, all libraries can be used easily. Third-party utilities: since Python is open source developers from around the globe can build their tools and libraries and everybody can use them. It’s Mixable:\nYou 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.\nIt’s easy to use and learn:\nYou’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.\nWhat can I do with Python? 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.\nSystem Programming:\nBecause 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.\nGUIs:\nUsing 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.\nInternet Scripting:\nYou can develop web applications using Python, you can do Server scripting, Server-Client Scripting and Client Scripting.\nA lot of websites already use Python now.\nYou can use FTP to transfer files, parse XML files, parse HTML and you can generate HTML based on Python code.\nGluing:\nPython can be glued to C, C++, .NET and Java applications.\nPython 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.\nDatabase Applications:\nPython can use Sybase, Oracle, Informix, ODBC, MySql, PostgreSQL, SQLite and more.\nPython 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.\nNumeric and Scientific Programming:\nPython can be used easily to create scientific applications, there is an extension called NumPy which can do more than Matlab!\nYou can calculate 22000 in milliseconds:\n114813069527425452423283320117768198402231770208869\n520047764273682576626139237031385665948631650626991\n844596463898746277344711896086305533142593135616665\n318539129989145312280000688779148240044871428926990\n063486244781615463646388363947317026040466353970904\n996558162398808944629605623311649536164221970332681\n344168908984458505602379484807914058900934776500429\n002716706625830522008132236281291761267883317206598\n995396418127021779858404042159853183251540889433902\n091920554957783589672039160081957216630582755380425\n583726015528348786419432054508915275783882625175435\n528800822842770817965453762184851149029376.\nYou don’t have to wait to get this value 😀\nMore:\nPython can be used in more fields, XML, Gaming, Graphics, Robots, Networking and more, everything is possible 🙂\nBottom Line: That’s enough for today, hope I’ll tell you more on my next blog.\nFor now I’d suggest you to read more about the language and its features from the language website: www.Python.org.\nAnd also don’t forget to download the appropriate built for your platform.\nCheers.\n","permalink":"https://mpcabd.xyz/im-learning-python-part-1/","summary":"\u003cdiv style=\"text-align: center;\"\u003e\n  \u003cspan style=\"font-family: georgia,palatino; font-size: large;\"\u003e I\u0026#8217;m Learning Python \u003c/span\u003e\u003cbr /\u003e \u003cimg title=\"Python Logo\" src=\"http://www.python.org/images/python-logo.gif\" alt=\"Python Logo\" width=\"211\" height=\"71\" border=\"0\" /\u003e\n\u003c/div\u003e\n\u003cp\u003eI’ll start posting this series of blogs on \u003ca title=\"Magic PC On WordPress\" href=\"http://magicpc.wordpress.com\" target=\"_blank\"\u003eWordPress\u003c/a\u003e and \u003ca title=\"mpcabd's Bolg On CSC\" href=\"/blog/2300\" target=\"_blank\"\u003eCSC\u003c/a\u003e, here I’ll write what I’m gonna learn on my way to learning Python.\u003c/p\u003e\n\u003cp\u003eIf 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.\u003c/p\u003e","title":"I’m Learning Python part 1"},{"content":"Hi all .Net developers and programmers.\nIf 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.\nFor 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.\nI 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.\nAll the shapes you draw must be placed in a ShapeContainer that handles the drawing according to the Z-Order between shapes. The following links are for the class and the testing project in VB .Net 2005: The Class \u0026#8211; The Testing Project. The testing project shows how to draw, rotate and move shapes, you can start using my class directly after downloading it. P.S.: The whole project is still Beta but I wanted to share the first build with you. Have fun, and please tell me what do you think. ","permalink":"https://mpcabd.xyz/your-drawings-are-objects-in-gdi/","summary":"\u003cp\u003eHi all .Net developers and programmers.\u003c/p\u003e\n\u003cp\u003eIf 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.\u003c/p\u003e\n\u003cp\u003eFor 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.\u003c/p\u003e","title":"Your drawings are Objects in GDI+"}]