Template Method Design Pattern

Template Method Design Pattern

This is a continuation of the design pattern series.

I had blogged about Singleton once, when I was using it very frequently. This blog post is about the use of the Template Design Pattern. So let’s discuss the pattern and then we can dive into the code and its implementation and see a couple of use cases.

The Template Method Design Pattern is a actually a pattern to follow when there are a series of steps, which need to be followed in a particular order. Well, the next question that arises is, ‚ÄúIsn’t every program a series of steps that has to be followed in a particular order?‚ÄĚ

The answer is Yes!

This pattern diverges when it becomes a series of functions that has to be executed in the given order. As the name suggests it is a Template Method Design pattern, with stress on the word method, because that is what makes it a different ball game all together.

Let’s understand this with an example of Eating in a Buffet. Most of us have follow a set of similar specific steps, when eating at a Buffet.¬†We all go for the starters first, followed by main course and then finally, dessert. (Unless it is Barbeque Nation then it’s starters, starters and starters :))

So this is kind of a template for everyone Starters --> Main course --> Desserts.

Keep in mind that content in each category can be different depending on the person but the order doesn’t change which gives a way to have a template in the code. The primary use of any design pattern¬†is to reduce duplicate code or solve a specific problem. Here this concept solves the problem of code duplication.

The concept of Template Method Design Pattern depends on, or rather  is very tightly coupled with Abstract Classes. Abstract Classes themselves are a template for derived classes to follow but Template Design Pattern takes it one notch higher, where you have a template in a template. Here’s an example of a BuffetHogger class.

from abc import ABC, abstractmethod

class BuffetHogger(ABC):

    @abstractmethod
    def starter_hogging(self):
        pass

    @abstractmethod
    def main_course_hogging(self):
        pass

    @abstractmethod
    def dessert_hogging(self):
        pass

    def template_hogging(self):
        self.starter_hogging()
        self.main_course_hogging()
        self.dessert_hogging()

So if you see here the starter_hogging, main_course_hogging and dessert_hogging are abstract class that means base class has to implement it while template_hogging uses these methods and will be same for all base class.

Let’s have a Farhaan¬†class who is a BuffetHogger¬†and see how it goes.

class Farhaan(BuffetHogger):
    def starter_hogging(self):
        print("Eat Chicken Tikka")
        print("Eat Kalmi Kebab")

    def __call__(self):
        self.template_hogging()

    def main_course_hogging(self):
        print("Eat Biryani")

    def dessert_hogging(self):
        print("Eat Phirni")
Now you can spawn as many  BuffetHogger  classes as you want, and they’ll all have the same way of hogging. That’s how we solve the problem of code duplication
Hope this post inspires you to use this pattern in your code too.
Happy Hacking!
Advertisements

Home Theatre!

Due to a lot of turmoils in my life in the recent past, I had to shift with a friend. Abhinav has been an old friend and college mate, we have hacked on a lot of software and hardware projects together but this one is on of the coolest hack of all time and since we are flatmates now it solved a lot of issues. We also had his brother Abhishek so the hack became more fun.

The whole idea began with the thoughts of making the old laptops which we have to be used as servers, we just thought what can we do to make the best of the machines we have. He has already done few set ups but then we landed up on doing a htpc, it stands for Home Theatre PC or media centre, basically a one stop shop for all the need, movies, tv shows and music. And we came up with a nice arrangement which requires few things, the hardware we have:

  1. Dell Studio 1558
  2. Raspberry Pi 3
  3. And a TV to watch these on ūüėČ

When we started configuring this setup we had a desktop version of Ubuntu 18.04 installed but we figured out that this was slowing down the machine so we switched to Ubuntu Server edition. This was some learning because I have never installed any server version of operating system. I use to wonder always what kind of interface will these versions give. Well without any doubt it just has a command-line utility for every thing, from partition to network connection.

Once the server was installed we just had to turn that server into a machine which can support our needs, basically installed few packages.

We landed up on something called as Atomic Toolkit. A big shoutout for the team to develop this amazing installed which has a ncurses like interface and can run anywhere. Using this toolkit we kind of installed and configured CouchePotato, Emby and Headphones.

This slideshow requires JavaScript.

This was more than enough we could automate a lot of things in our life with this kind of set up, from Silicon Valley to Mr. Robot. CouchePotato help us to get the best quality of videos and Emby gives us a nice dashboard to show all the content we have.

I don’t use Headphones much because I love another Music Application but then Headphones being a one stop shop is not wrong too. All this was done on the Dell Studio Machine we had, also we stuck a static IP on it so to know which IP to hit.

Our sever was up, running and configured. Now, we needed a client to listen to this server we kind of have a TV but that TV is not smart enough so we used a Raspberry Pi 3 and attached it to the TV using the HDMI port.

We installed OSMC on the Raspberry Pi and configured it to use Emby and listen to the Emby server once we booted it up it was very straight forward. This made our TV look good and also a little smart and it opened our ways for 1000s of movies, music and podcast. Although I don’t know if setting up this system was more fun or watching those movies will be.

 

Writing Chuck – Joke As A Service

Writing Chuck – Joke As A Service

Recently I really got interested to learn Go, and to be honest I found it to be a beautiful language. I personally feel that it has that performance boost factor from a static language background and easy prototype and get things done philosophy from dynamic language background.

The real inspiration to learn Go was these amazing number of tools written and the ease with which these tools perform although they seem to be quite heavy. One of the good examples is Docker. So I thought I would write some utility for fun, I have been using fortune, this is a Linux utility which gives random quotes from a database. I thought let me write something similar but let me do something with jokes, keeping this mind I was actually searching for what can I do and I landed up on jokes about Chuck Norris or as we say it facts about him. I landed up on chucknorris.io they have an API which can return different jokes about Chuck, and there it was my opportunity to put something up and I chose Go for it.

JSON PARSING

The initial version of the utility which I put together was way simple, it use to make a GET request stream the data in put in the given format and display the joke. But even with this implementation I learnt a lot of things, the most prominent one was how a variable is exported in Go i.e how can it be made available across scope and how to parse a JSON from a received response to store the beneficial information in a variable.

Now the mistake I was doing with the above code is I was declaring the fields of the struct with a small letters this caused a problem because although the value get stored in the struct¬†I can’t use them outside the function I have declared it in. I actually took a while to figure it out and it was really nice to actually learn about this. I actually learnt about how to make a GET¬†request and parse¬†the JSON and use the given values.

Let’s walk through the code, the initial part is a struct¬†and I have few fields inside it, the Category field is a slice¬†of string, which can have as many elements as it receives the interesting part is the way you can specify the key¬†from the received JSON how the value of received JSON is stored in the variable or the field of the struct. You can see the json:"categories"¬†that is the way to do it.

With the rest of the code if you see I am making a GET request to the given URL and if the it returns a response it will be res and if it returns an error it will be handled by err. The key part here is how marshaling and unmarshaling of JSON takes place.

This is basically folding and un-folding JSON once that is done and the values are stored to retrieve the value we just use a dot notation and done. There is one more interesting part if you see we passed &joke which if you have a C background you will realize is passing the memory address, pass by reference, is what you are looking at.

This was working good and I was quite happy with it but there were two problems I faced:

  1. The response use to take a while to return the jokes
  2. It doesn’t work without internet

So I showed it to Sayan and he suggested why not to build a joke caching mechanism this would solve both the problems since jokes will be stored internally on the file system it will take less time to fetch and there is no dependency on the internet except the time you are caching jokes.

So I designed the utility in a way that you can cache as may number of jokes as you want you just have to run chuck --index=10 this will cache 10 jokes for you and will store it in a Database. Then from those jokes a random joke is selected and is shown to you.

I learnt to use flag¬†in go and also how to integrate a sqlite3¬†database in the utility, the best learning was handling files, so my logic was anytime you are caching you should have a fresh set of jokes so when you cache I completely delete the database and create a new one for the user. To do this I need to check of the Database is already existing and if it is then remove it. I landed up looking for the answer on how to do that in Go, there are a bunch of inbuilt APIs which help you to do that but they were misleading for me. There is os.Stat, os.IsExist¬†and os.IsNotExist. What I understood is os.Stat¬†will give me the status of the file, while the other two can tell me if the file exists or it doesn’t, to my surprise things don’t work like that. The IsExist¬†and IsNotExist¬†are two different error wrapper and guess what not¬†of IsExist¬†is not IsNotExist, good luck wrapping your head around it. I eventually ended up answering this on stackoverflow.

After a few iteration of using it on my own and fixing few bugs the utility is ready except the fact that it is missing test cases which I will soon integrate, but this has helped me learn Go a lot and I have something fun to suggest to people. Well, I am open to contribution and hope you will enjoy this utility as much as I do.

Here is a link to chuck!

Give it a try and till then Happy Hacking and Write in GO! 

Featured Image: https://gopherize.me/

Design Pattern: Singleton

“Beauty!”, when I see some really amazing code that is my first reaction, but what makes a piece of code beautiful? Is it neatly named variables? Is it the uniform indentation?

Well the answer is yes but there is something a little more than these factors and that is an elegant  solution to the problem. When I say elegant solution what is that I am talking about ? What makes a solution elegant? It is the way you approach a problem.

Design Patterns in the programming world adds to the beauty of the solution, it sometimes feels that it is the missing piece of the puzzle. And the solution so magically fits to solve the problem. The various patterns that I came across are Singleton, Mixin, Pub-Sub etc. The way I approached it and studied them is a little different, design patterns are actually tailored way to react to a given situation.

Let me elaborate on that now suppose there is an emergency and somebody got hurt, what is the first thought that comes to your mind ? It is to handle it using First Aid, this is actually a catered thought which has been imbibed in us from ages and people have design First Aid boxes in such a way that it has all the first come fixes for all the emergencies.

For me I see Design Pattern in the same manner it has gone through the test of time and proved to be the best way to solve a specific type of problem.  It is like a ready made template but you should be aware enough to know the problem and to know the pattern that solves that problem. 

I have read about a lot of design patterns but to be very frank I have seldom seen one being applied in the code-base that I have came across, this could be because I have not appreciated it much and also because I was not able to observe the pattern. It was very recently when I was working with Gautham Sir I began to appreciate the beauty of it. We were writing a utility in jnaapti using EcmaScript 6. He made me feel to appreciate the beauty of it and taught me how to implement it as well.

Let us break it down more and see the type of problems in which Singleton design pattern can be used.

What is Singleton design pattern?

A Singleton¬†design pattern puts a restriction of returning the same object irrespective of how many times the class¬†is being instantiated. This makes sure that whatever is the state¬†of object that state is preserved. Don’t be overwhelmed if you are not able to understand it now it will make more sense once you see the code.

The benefit you get is having a kind of a global store where you can put in data and retrieve it when you desire to.

Lets us make it more clear imagine there is a class Library now through out the life cycle of the software what we want is there should be only one Library object and when ever I get this object I should be able to add and delete books from the library hence modifying the library now when I do this the library object anywhere being use should get this information.

Lets chalk out some code and try to understand it, I have 3 files Library.js, Customer.js and LibraryPlayGround.js.  The content of those file are very straight forward.

es6-12
Library.js

Now we need customers or readers for simplifying things i have only included on one method that is return books.

es6-2
Customer.js

Once all this is done we need a playground where we can see things happening and experiment with it.

es6-3
LibraryPlaygroud.js

Now if you see the code farhaan object has tried to access the same Library object that is being exported. No matter what it well return the same instance which has been instantiated in the beginning of the lifecycle of the software. This is how I tried implementing Singleton .

I have used ECMAScript here to demonstrate that concept and to implement it, I am a learner so there could have been certain things I wouldn’t have made clear, you can leave a comment regarding the same, if you have something to add I would love to know.

Till then Happy Hacking

Weechat-Tmux

Weechat-Tmux

Recently I have been to pycon-india (will blog about that too!) there Sayan and Vivek introduced me to weechat which is a terminal based IRC client, from the time I saw Sayan’s weechat configuration I was hooked to it.

The same night I started configuring my weechat , it’s such a beautiful IRC client I was regretting why did I not use it before. It just transforms your terminal into IRC window.

For fedora you need to do:

sudo dnf install weechat

Some of the configuration and plugins you need are :

  1. buffer
  2. notify-send

That’s pretty much it but that doesn’t stop there you can make that client little more aesthetic. ¬†You can set weechat by using their documentation.

The clean design kind of makes you feel happy, plus adding plugin is not at all a pain. In the weechat window you just say /script install buffer.pl and it just installs it in no time.  There are various external plugin in case you want to use them and writing plugin is actually fun , I have not tried that yet.

screenshot-from-2016-09-30-23-02-13

I also use to use bigger font but now I find this size more soothing to eyes. It is because of weechat I got to know or explore about this beautiful tool called tmux ,  because on normal terminal screen weechat lags , what I mean by lag is the keystroke somehow reach after like 5-6 seconds which makes the user experience go bad.  I pinged people on IRC in #weechat channel with the query the community is amazing they helped me to set it up and use it efficiently , they only told me to use tmux or screen . With tmux my session are persistent and without any lag.

To install tmux on fedora:

sudo install tmux

tmux is a terminal multiplexer which means it can extend one terminal screen into many screen . I got to learn a lot of concepts in tmux like session, pane and windows. Once you know these things in tmux its really a funride. Some of the blogs I went through for configuring and using tmux the best I found was hamvoke , the whole series is pretty amazing . So basically my workflow goes for every project I am working on I have a tmux session named after it, which is done by the command:

tmux new-session -s <name_session>

Switching between two session can be done by attach¬†and detach. And I have one constant session running of weechat. I thought I have explored every thing in tmux but that can’t be it , I came to know that there is a powerline¬†for tmux¬†too. That makes it way more amazing so this is how a typical tmux¬†session with powerline¬†looks like.

screenshot-from-2016-09-30-23-31-10

I am kind of loving the new setup and enjoying it. I am also constantly using tmux cheatsheet¬†ūüėõ because it’s good to look up what else you can do and also I saw various screencast on youtube where ¬†tmux+vim¬†makes things amazing.

Do let me know how you like my setup or how you use it .

Till then, Happy Hacking! ūüôā

 

Vacation Of Code

Vacation Of Code

This all started when pingou gave me the opportunity to write a utility which helps to user to edit comment on pagure.Now for those who don’t know what pagure is , so pagure is open source equivalent of Github, to be precise :

Pagure is a light-weight git-centered forge based on pygit2. Currently, Pagure offers a web-interface for git repositories, a ticket system and possibilities to create new projects, fork existing ones and create/merge pull-requests across or within projects.

So the utility that was allotted to me was an edit button that privilege the owner of the comment to modify the comment on the pull request. That sounds really simple but writing the whole code and modifying others code are two different things.

I finally started exploring Flask and its feature so Flask is framework  that helps you write servers , Server as the name suggest is use to serve request.I had a brief idea about the type of request but never got the chance to explore it.

There are many types of request that help the client and server to talk to each other  famous ones are POST and GET.

The GET method

The GET method is the method used by the browser to ask the server to send back a given resource: “Hey server, I want to get this resource.” In this case, the browser sends an empty body. Because the body is empty, if a form is sent using this method, the data sent to the server is appended to the URL.

The POST method

The POST method is a little different. It’s the method the browser sends the server to ask for a response that takes into account the data provided in the body of the HTTP request: “Hey server, take a look at this data and send me back an appropriate result.” If a form is sent using this method, the data is appended to the body of the HTTP request.

Source: MDN

So in first attempt I wrote a shabby code and somehow make it work , but as I told it was really shabby so pingou and subho told me to use hidden form technique which is used to trigger certain functions without actually making the user know what is going on . It is more of a hack to get things done your way.The problem I faced was delete comment and edit comment use the same form to send request so both have the same end point hence inside the function that deletes comment I devised a way to distinguish how to differentiate when to edit comment and when to delete it.

The algorithm was simple get comment id , get new comment , replace the old comment by new one and make entry in the database.The code snippet that really helped me to understand things to a new depth was:

Example

Consider the following form:

<form action="http://foo.com" method="get">
  <input name="say" value="Hi">
  <input name="to" value="Mom">
  <button>Send my greetings</button>
</form>
With the GET method, the HTTP request looks like this:
GET /?say=Hi&to=Mom
HTTP/1.1 Host: foo.com
Example

Consider this form (the same one as above):

<form action="http://foo.com" method="post">
  <input name="say" value="Hi">
  <input name="to" value="Mom">
  <button>Send my greetings</button>
</form>

When sent using the POST method, the HTTP request looks like this:

POST / HTTP/1.1
Host: foo.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 13

say=Hi&to=Mom
 My Pull request is still under consideration so you can actually check what I did in pagure. Do let me know what you think about it.

Telegram Bot, this is how you do it!

Telegram Bot, this is how you do it!

I have been wondering about writing telegram bots, so while searching about it I landed on this link Python telegram api. This fueled my curiosity to write my first telegram bot. I searched for many ideas and I was too late to implement them because others have already implemented it.

Then while having a conversation we came across the idea of having a lmgtfy bot to answer silly question , then tools met requirements and voila  lmgtfyou_bot was born. (Yeah! you got it right, every other name was taken.)

So, yeah you need to install a pip package mentioned in the link above. Before going into details let me discuss something about ‘polling’.

There are two type of models namely polling and observer model. Polling means the function keeps on pinging the application to see if something changed while in observer model it’s like tell me if something changed.

Imagine a very irritating waiter who is disturbing you in every 10s about your order now that is polling while you calling a waiter when you are ready is observer pattern.

Here Telegram api is using a polling pattern to get change in the event , for us it is new messages.Now there is a lot of things that is happening in the code. Let me walk you through it

try:
 LAST_UPDATE_ID = bot.getUpdates()[-1].update_id
except IndexError:
 LAST_UPDATE_ID = None

So let’s see whats going on here. getUpdates() function returns a list of updates which is a composite data containing various metadata about the message like text, username , date etc. Here, update_id is taken from the latest update i.e message hence [-1]. update_id keeps on increasing with every incoming message. We use this to control our script which running in an infinite loop.

 while True:
   fetch_url(bot)

fetch_url is being called infinite number of times which is being controlled by LAST_UPDATE_ID variable.

def fetch_url(bot):
 global LAST_UPDATE_ID

 # Following is a dictionary of commands that the bot can use

 commands = {'/help':"You can add me in any group or text me! I don't have aceess to the group message so you need to call me by my name i.e @lmgtfyou_bot or start your senstence with '/' , I listen to the keyword 'means' ", '/start':'I am always listening to you. Just use magical words'}

 magic_words = ['means','mean','/means','/mean']

 for update in bot.getUpdates(offset=LAST_UPDATE_ID, timeout=10):
     chat_id = update.message.chat_id
     message = update.message.text.encode('utf-8')
     message_list = message.split()

     if(message in commands):
         bot.sendMessage(chat_id=chat_id, text=commands[message])
         LAST_UPDATE_ID = update.update_id + 1

     if ( list_compare(magic_words, message_list)!= -1):
         search = message_list[list_compare(magic_words, message_list)-1]
         url='http://lmgtfy.com/?q='+search
         bot.sendMessage(chat_id=chat_id,text=url)
         LAST_UPDATE_ID = update.update_id + 1

Most of the code is self explaining, but last line of the if block is kind of a base case which is helping to control the actions.

You can host the code on openshift for free, just set up an instance write the code in app-deployment folder and ssh into the instance. Now, in the instance run the script normally and put it in the background.That’s all for this time have a nice hack.

Feel free to fork and contribute to my repo on GitHub.