Review : Automate the boring stuff with python

- - Python

Some while ago, I got myself enrolled in one of the best video lectures at Udemy. I have recently completed the lectures and would like to brief about it. The course is named Automate the boring stuff with python. Well, it is an excellent video lecture A.I Sweigart has brought up. It is good to go for people with any skill level. The video lectures gradually leaps upwards the ladder underlying the basics at the initial few videos. I would say it is a motivation to a new-comer in python. Continue Reading

What are the must know features of python programming language

- - Python

List comprehensions

One of the major features of python is list comprehension. It is a natural way of creating a new list where each element is the result of some operations applied to each member of another sequence of an iterable. The construct of a list comprehension is such that it consists of brackets containing an expression followed by a for clause then by zero or more for or if clause. List comprehensions always returns a list.

Simple example

squares = [x**2 for x in range(10)]

In a rather real usage scenarios, the expression after the bracket ‘[‘ is a call to a method/function.

some_list = [function_name(x) for x in some_iterable]

Generators

Before learning about generators, it is important and essential to understand what an iterable is. Putting it simple, an iterable is an object that can be looped over. Therefore, a list, string, dictionary, file, etc are iterable objects.

A generator is something that simplifies creating iterators. More specifically, a generator is a function that produces a sequence of results instead of a single value.

When a generator function is called, it returns a generator object without even beginning execution of the called function. Now when the next method is called for the first time, the function starts executing until it reaches yeild statement. Hence yeilded value is returned by the next call.

Sample Example

def gen_example():
    print “Begining of the function”
    for i in range(5):
        print “before yeild”
        yield I
        print “after yeild” 
    print “End of the function”

Generators Expressions

It is the generator version of list comprehension. Everything is same as the list comprehension except that it returns a generator.

Sample Example

squares = (x**2 for x in range(5))

Docstrings

A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object. In fact, every module should have a docstring. Additionally all the functions and classes exported by a module should have a docstrings. Also, the public methods including constructor should also have docstrings.

Sample Example

def sum_elements(elements):
    “““Returns the sum of elements of the passed list”””
    return sum(elements)

*args and **kwargs

*args and *kwargs allow you to pass a variable number of arguments to a function. It is not know before hand about how many arguments can be passed to your function.

*args is used to send a non-keyworded variable length argument list to the function.

def func_with_args(*argv):
    for arg in argv:
        print arg


func_with_args('gopal', 'ramesh', 'paresh')

The above code produces the result as follows:

gopal

ramesh

paresh

On the other hand, **kwargs allows you to pass keyworded variable length of arguments to a function. Below is a basic example

def  func_with_kwargs(**kwargs):
    if kwargs is not None:
        for key, value in kwargs.iteritems():
            print “%s == %s” %(key, value)

func_with_kwargs(customer= “Gopal”, salesman = “Ramesh”)

Following is the output of the above code:

customer == Gopal

salesman == Ramesh

This is an open-ended article. Please comment below about the features you think should not be missed. Thanks for reading.

Cryptography with an interpreter

- - Python, Technology, Tutorials, Web

Hey Guys, it’s been a long time since I published my last article. Apologies for the delay. Anyway, straight into the topic, Cryptography. Well, cryptography with python. This semester(V of Bsc CS) I choose Cryptography as an elective over Neural Network and I am enjoying it. So far I have learned Ceasar Cipher, Playfair Cipher, Vigenere Cipher, Vernom Cipher, Hill Cipher and Rail Fence Cipher. It’s just the beginning anyway. I have implemented these learnings via python programming language. Here is link to the github repository containing the implementations. The repo will be updated as I go further into learning throughout the semester.

Quick walk

Cryptography is the science that is used to hide the information. Mathematically defined as a tuple of five members (M, C, E, D, K) where,

M → Message (Plain Text)

C → Cipher Text

K → Set of Keys

E → Encryption Algorithm E: M*K → C

D → Decryption Algorithm D: C*K → M

On the other hand, cryptanalysis is the study of cipher systems with the view of finding the weaknesses in them that will enable us to retrieve the plain text.

Furthermore, ciphers can be classified into various types based on their properties. Well cipher in general is an algorithm to perform encryption and decryption. We could group Substitution and Transposition into Historical ciphers. Substitution cipher may further be monoalphabetic or polyalphabetic. Modern ciphers are either based on input data or based on key. Stream cipher and Block cipher are the types of modern cipher based on input data. Based on key there are symmetric(private) and asymmetric(public) ciphers.

Following are one of the implementations of ciphers I’ve learned so far. For complete package, follow this link to the repository.

Vernom Cipher

#sample plain text : hello
#sample key : axhjb

def make_chunks(text, text_length, key_length):
    for i in range(0, text_length, key_length):
        yield text[i : i + key_length]


def encryptdecrypt(cipher_generator):
    final_text = ""
    for item in cipher_generator:
        for i in range(0, len(item)):
            final_text += alphabets[alphabets.index(key[i]) ^ alphabets.index(item[i])]
    return final_text

alphabets = "abcdefghijklmnopqrstuvwxyz"

plain_text = raw_input("Enter the plain text: ")

key = raw_input("Enter the key: ")

plain_text = plain_text.replace(" ", "")

p_generator = make_chunks(plain_text, len(plain_text), len(key))

cipher_text = encryptdecrypt(p_generator)

print "The cipher text is : ", cipher_text

c_generator = make_chunks(cipher_text, len(cipher_text), len(key))

decrypted_text = encryptdecrypt(c_generator)

print "The decrypted text is : ", decrypted_text


Tell me how you felt the article was in the comments section below or shoot me a message at bbhishan@gmail.com . And there is always thanks for reading. Cheers 🙂

How To Split And Merge PDF Documents

- - Applications

Not the type of posts I usually produce. A promotional review of a tool.

Everyone knows that PDF files are hard to work with. Apart from figuring out how to convert PDF documents, oftentimes we’re also trying to put together the best PDF document possible from other content.

But when those content sources are already in the PDF format, it can seem like an uphill battle just to get the content separated. More often than not, we need to figure out how to manipulate PDF documents at the page level. Continue Reading

Bits of selenium, time, tkinter, pyvirtualdisplay – Get jokes timely while you work

- - Applications, Python, Technology, Web

Making use of libraries available and building something useful has always been my favorite. However, I haven’t yet been involved in making/contributing to one. I don’t even know the procedure to be involved in building libraries. My latest program also makes use of various libraries such as selenium, time, tkinter. In a nutshell, the program fetches jokes from www.laughfactory.com and displays a message box with a joke in a timely interval. I usually run the program while I am at work(internship). I’ve set 10 minutes interval between the jokes to be shown. By the way, I used time module and it’s time.sleep(time_in_seconds) method for dealing with intervals between each message box to appear. The program isn’t full fledged and you can make additions to it on your own for customization according to your need. The earlier statement, I guess seemed very professional for a small program. Please bear with me 🙂 Continue Reading

Finding Facebook Fanpage of Startups – selenium and facepy usage

- - Applications, Python, Technology, Web

As a regular activity of the Software Club at my college, we have a weekly meetups where we discuss various ideas and code anything that is possible within an hour or so. We make groups of 3 or 4 and each group works on different ideas. At this point I really feel tech giants(Google, FB, etc…) should also consider colleges at Nepal and similar countries for their internship programs. Yesterday(Jan 3), we discussed several ideas and my group worked on something cool too. However, I will only talk about my portion. Continue Reading

Automation with Python – Python codes to create Dropbox apps

As promised in the article earlier on Automate DropBox Signups using python, I have come up with an article along with the codes to create an app and fetch the API keys for it which then allows us to access the files in dropbox. Well, again we stick to selenium module for an ease. In the last article, I’ve explained a python script to automate the signups for dropbox. Now that we have enough cloud space in different accounts. We now need to access the files in those spaces so we can use it as a file server. DropBox provides a feature to create apps on dropbox and gives API keys to hence access the files in the account. Since we’ve got multiple dropbox accounts we would stick towards automating the procedure to get the api key for accessing the files. Continue Reading

Compiling my year with an Interpreter

- - Applications, Python, Technology

To my dear readers, without whom this blog would have been a dead planet. Thanks for spending your valuable time here. I wish you a Happy New Year. 2015 is gone with almost an end to my sophomore year. I wouldn’t say year 2015 was any new to me than the others. Few achievements, life lessons and never ending learning curve. My very first article for 2016 will sum up my pythonic experience from 2015. I used some python throughout this semester/year to ease my life. Bear with novice’s automations 🙂 Continue Reading

Automated chat using python – Automation using selenium and python

- - Applications, Python, Tutorials, Web

Putting two clever bots into conversation

Keeping the promise to come up with a nice article, I present you two bots into conversation. This week I’ve bridged two clever bot’s for a nice conversation. Well starting with the background for this article, I had an assignment to print out a conversation of mine with cleverbot. After I had made the submission, I realized that I wanted to put the bot itself into conversation with another bot. I had recently researched about selenium module in python, hence thought to take help of selenium to make the talk between the bots possible. You can read an article of mine on Making a google search via selenium to get the hang of this cool module in python. Continue Reading