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 ????

Enroll In 100 Off Courses At Udemy Automatically Python Codes To Get Paid Courses

- - Applications, Python, Tutorials
Udemy is a teaching and learning platform with loads of courses in various categories. Now very often different coupon codes are available for purchasing courses in minimal amount or with a 100% discount. Various websites serve these coupon codes. One of those websites which I rely on is GrowthCoupon.com

Now, I am not writing a review of 100% off coupon providers. Through this post I will explain my code which I am using to extract the 100% off coupon codes from growthcoupon.com and then get those courses automatically. I have automated my code so that I do not need to worry about new coupon codes available and can save my time. The below code enrolls you in 10 latest 100% off courses available at growthcoupon.com when run a single time. You may wish to automate the script every hour or so.

Get 100%off Udemy courses automatically using python

from json import loads
from bs4 import BeautifulSoup
import mechanize
api_key = "8def4868-509c-4f34-8667-f28684483810%3AS7obmNY1SsOfHLhP%2Fft6Z%2Fwc46x8B2W3BaHpa5aK2vJwy8VSTHvaPVuUpSLimHkn%2BLqSjT6NERzxqdvQ%2BpQfYA%3D%3D"
growth_coupon_url = "https://api.import.io/store/data/a5ef05a9-784e-410c-9f84-51e1e8ff413c/_query?input/webpage/url=http%3A%2F%2Fgrowthcoupon.com%2Fcoupon-category%2F100-discount%2F&_user=8def4868-509c-4f34-8667-f28684483810&_apikey=" + api_key
br = mechanize.Browser()
br.set_handle_robots(False)
br.addheaders = [("User-agent","Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13")]
sign_in = br.open("https://www.udemy.com/join/login-popup/")
br.select_form(nr=3)
br["email"] = "email@domain.com"
br["password"] = "password"
logged_in = br.submit()

growth_coupon = br.open(growth_coupon_url)
json_obj = loads(growth_coupon.read())

for course_link in json_obj["results"]:
    try:
        course_page = br.open(str(course_link["couponcode_link"]))
        soup = BeautifulSoup(course_page)
        for link in soup.find_all("a"):
            req_link = link.get('href')
            if 'https://www.udemy.com/payment/checkout' in str(req_link):
                print req_link
                br.open(str(req_link))
                print "success"
                break
    except (mechanize.HTTPError,mechanize.URLError) as e:
        print e.code

The above program is a pure python code that extracts 10 latest 100% off coupon codes from GrowthCoupon.com and then enrolls you in those courses automatically.

1. Line 1 to 3

The first three lines are the import statements. In our program, we are using three python libraries. Amongst them, mechanize is used to login to the udemy account. BeautifulSoup is used to get the data on the basis of tags. Here in our program we use BeautifulSoup to get the links in certain page. Json’s loads is used to load the json response.

2. Line 4 and 5

We are using import.io API in order to extract data from growthcoupon. I got to know about this very cool resource in my Programming Synthesis class at my college. Here’s How to get and use import.io API. We store the API in a variable api_key. Then concatenate to the growth_coupon_url which is the standard post request url to get data in json format from growthcoupon.

3. Line 6 to 13

From line 6 to 13 is the procedure to login to a website (udemy in our case). Line 6 initializes a browser. Line 7 says ignore the robots.txt file. Line 8 adds a user agent to the browser. Line 9 opens the login url in the browser we initiated earlier.

The next thing you will need is the form you want to work with. By this I mean this is the login form. All you need to do is go to the username box ->> right click on it->> go to the inspect elements option. Now scroll up until you find the first form tag. In most cases you will find the form name attribute but some of the websites do not have this. If there exists then the value given to the name attribute under the form tag is the thing you need to access the form. Another way to access forms is by their index. The first form is indexed 0. Now in case the form name is not available, you will need to find how many forms are present in the login url(basically most of the websites have only one form because all you want the login page to do is login if authenticated). In this case the form index is 3.

Now you need to know the variable name that is assigned to take the value you enter to the email/username and password section. To get these values inspect element when you are inside the fields email/username and password. Below is a snapshot to give you insights of the variables you want to take care of.

udemyloginform

4. Line 15 and 16

Here on line 15, we are opening the url that gives us the data from growthcoupon in json format. Line 16 loads the url as a json object.

5. Line 18

Our json object is stored in json_obj variable. But the data we need is stored inside an array which is the value for the key “results” Hence we are iterating through this array.

6. Line 20

Now we open the couponcode link which is the value of the key “couponcode_link”. This url is present in each index of the array. On each loop the particular index’s url’s response is stored in variable course_page.

7. Line 21

We then convert the page response to a soup element by invoking the BeautifulSoup method over course_page.

8. Line 22 to 27

Now we want to iterate through each links found in the soup element. The url for enrolling in the udemy course starts with the string “https://www.udemy.com/payment/checkout”. Hence we check if the string is a substring of the link at each iteration. If the condition satisfies, we open that link to enroll ourselves in that course. Well that’s the end of the code that works.

Thanks for reading :) Enjoy ! If you have any questions regarding the codes/post, comment below.

How To Swap Values Without Temporary Variable

My dear readers, this article will be invested in explaining about swapping two integers without the use of temporary variable. The reason I am writing this article is because it has been asked several times in an interview for a CS internship/job. In fact, a friend of mine who applied for an internship at a local company was asked the same question. The problem tends to test your analytical skills as well as understanding of programming fundamentals. However, in practice one should never use the following approaches which I will explain why towards the end of the article. Starting with no further delay, there are two approaches to the problem. 1. Using XOR operator

2. Using addition and subtraction operators

Throughout the article we use ‘^’ symbol for representing XOR.

Below is a table showing the results of XOR operation

A B A^B
0 0 0
0 1 1
1 0 1
1 1 0

This concludes that for different value of A and B, the XOR operation gives 1 while it gives 0 for the same value of A and B.

XOR also termed as exclusive-or has following properties

1. Self – inversed

A ^ A = 0

Any value XOR’d with itself gives 0.

2. Identity

A ^ 0 = A

Any value XOR’d with 0 remains unchanged.

3. Associative

A ^ (B ^ C) = (A ^ B) ^ C

The order does not matter.

4. Commutative

A ^ B = B ^ A

How to swap two integers using XOR

It is simple and underlies on the above mentioned properties/principles.

Say for an instance a = 2 and b = 3

The XOR operation is performed between two corresponding bits of the numbers.

In binary 2 = 0010 and 3 = 0011

For instance, while performing a ^ b, the most significant bit of a is XOR’d with the most significant bit of b and so on.

The following three statements swaps values of a and b.

a = a ^ b

b = a ^ b

a = a ^ b

Congratulations, you’ve swapped values in a and b without the use of a temporary variable. How?

What going on in the first statement, lets see it in a table.

a b Final value of a = a ^ b
0 0 0 (from self-inversed)
0 0 0 (from self-inversed)
1 1 0 (from self-inversed)
0 1 1 (from Identity)

At the end of the first statement, the value of a = 0001 = 1

Now the value of a = a ^ b,

What’s going on in the second statement, lets see it in a table.

a = a ^ b b Final value of b = (a ^ b) ^ b
0 0 0 (from self-inversed)
0 0 0 (from self-inversed)
0 1 1 (from Identity)
1 1 0 (from self-inversed)

Voila, we’ve got the initial value of a I.e 2 to be held by b now. It worked but how? It’s nothing but the combination of self-inversed property followed by identity over the integers. For the second statement

b = a ^ b // After the first statement the value of a is equal to a ^ b, so

b = (a ^ b) ^ b

This can be rearranged by associative property and written as

b = a ^ (b ^ b)

We know from self-inversed rule, anything XOR’d with itself gives 0 . So we may now write

b = a ^ (0)

From Identity rule, we know something XOR’d to 0 will leave the number unchanged. Therefore we get

b = a

That’s how we got the initial value of a to be stored to b at the end of second statement.

Moving on to the third statement which is

a = a ^ b // By now the value of a is a ^ b and value of b is the initial value of a

so we may also write

a = a ^ b ^ a

Now this can be written as

a = a ^ a ^ b

Using self-inversed rule

a = 0 ^ b

Using identity rule

a = b

Through Table

A = a ^ b B = a A = a ^ b ^ a
0 0 0
0 0 0
0 1 1
1 0 1

At the end of the computation, we have b = 0010 = 2 and

a = 0011 = 3

Why you shouldn’t use XOR for swapping values?

For an instance, say

int a = 2

int *aptr = &a

int *bptr = &a

In the above set of statements, aptr and bptr are pointers to a. Using what we just learned

*aptr = *aptr ^ *bptr

*bptr = *aptr ^ *bptr

*aptr = *aptr ^ *bptr

Now since both the pointers are pointing to the number in the same location so all the above statements are making change at the same location whose result is data loss.

Swapping using addition and subtraction operators

a = a + b

b = a – b

a = a – b

This is pretty straight forward. Say for an instance

a = 5 and b = 10

Then the result of the first statement will be

a = a + b yields

a = 5 + 10

a = 15 and b is unchanged I.e b = 10

Now when the second statement is run, we have

b = a -b yields

b = 15 – 10

b = 5 (which is the initial value of a. Note that the value of a has already been changed to 15)

Running the third statement

a = a – b

a = 15 – 5

a = 10 (which is the initial value of b. Note that the value of b has already changed to 5)

So what do we have at the end

a = 10 and b = 5 (values swapped)

Why addition and subtraction shouldn’t be used to swap values

Say for an instance the values of a and b are large integers. We are performing addition on the first statement which can lead to overflow since we have large integers.

Should you have any questions, do comment below.

Finding Facebook Fanpage Of Startups Selenium And Facepy Usage

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.

In a nutshell, I extracted all the startups in Nepal and found their facebook page. The data was then used by other members in my group to do something cool which I can’t discuss here.

Extract startups in Nepal and find FB page

from selenium import webdriver
from facepy import GraphAPI
import json
import time 

startup_fan_pages = {}


access_token = "access_token"   # get it here https://developers.facebook.com/tools/explorer/

graph = GraphAPI(access_token)

browser = webdriver.Firefox()
browser.get("http://startupsinnepal.com")

time.sleep(40) #wait for the browser to completely load the page


startups = browser.find_elements_by_class_name("panel-title") #returns a list of objects having class="panel-title"
print("startups found")

for startup in startups:
    #print(startup.text)
    r = graph.search(startup.text.lower(), "page", page=False, retry=3) #page=False is to refuse to get a generator, 
    if len(r['data']) > 0:
        startup_fan_pages[r['data'][0]['name']] = str(r['data'][0]['id'])

#print(startup_fan_pages)
with open('startupsinnepalfanpages.json', 'w') as fp:
    json.dump(startup_fan_pages, fp)

Startupsinnepal.com is a listing of all the startups in Nepal. I used selenium to extract all the startups from the website. In order to find their corresponding facebook fan page, I made use of facepy which allows an easy and quick way to make queries to the Graph API. All you need is the access token which you can get from https://developers.facebook.com/tools/explorer/

In the real implementation the data is stored in a google spreadsheet so it is available to the other portion of the program to do further computation. If you are interested on how to push data to spreadsheet via python, go ahead and read Grab alexa rank and write to google spreadsheet using python. Keep the comments coming and please don’t use adblockers(Adsense is the only source for this site’s income), it keeps me motivated to publish good content.

Sorting An Array Containing Json Elements With Specific Key In The Json Using Javascript

- - JavaScript, Tutorials, Web

Example of sorting an array containing json elements

The following function takes two parameter. The prior one expects an array with json elements within it while the later one expects a string i.e the key member of the json on whose basis the array is supposed to be sorted. For this example we would use “first_name” as the key for the basis of sorting. We use .toUpperCase() method to avoid the sorting based upon the small and big alphabetical letters.

We define a variable personal_infromations which holds an array of jsons. We alert the value stored in it  so that the proof of sorting being done is seen clearly. We store the value returned from sortByKey method to a variable sorted_personal_informations. Now when alerting the value, we see that the json has been sorted based upon the key “first_name”.

function sortByKey(array, key) {
    return array.sort(function(a, b) {
        var x = a[key].toUpperCase();
        var y = b[key].toUpperCase();
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
}
var personal_informations = [{"first_name":"Bhishan","last_name":"Bhandari","email":"bbhishan@gmail.com","country":"Nepal","phone_number":"9849060230"},{"first_name":"Ankit","last_name":"Pradhan","email":"ankit@ankit.com","country":"Nepal","phone_number":"9999999999"}, {"first_name":"Aalok","last_name":"Koirala","email":"aalok@aalok.com","country":"Nepal","phone_number":"8888888888"}, {"first_name":"Subigya","last_name":"Nepal","email":"subigya@subigya.com","country":"USA","phone_number":"6666666666"}];

alert(personal_informations);

var sorted_personal_informations = sortByKey(personal_informations, "first_name");

alert(sorted_personal_informations);

All You Need To Know To Build Applications With Phonegap

- - JavaScript, Phonegap
Warm greetings to my readers and a sincere apology for not being able to publish article the earlier week. The reason being the biggest App Camp in Nepal followed by college and internship. However, these are just excuses. Getting into details of this article : NCELL APP CAMP is about building a product for mobile devices that scales and solves a major problem of the country or worldwide. Having options to compete in categories as follows :

1. Health

2. Tourism

3. Games & Entertainment

4. Utilities

We(group of 5 students) decided to make application to disseminate information and save lives of expected mothers. Idea selection is now complete with 150 top idea selected in various categories. We made it through the top 150(38 selected in Health Category). Needed to build MVP for the second round. You may watch the demo of the application below.

We had around 2 months for the development. We are students and we procrastinate whenever possible. Wait, we had one week remaining for the submission of the MVP with nothing done yet. Saying one week isn’t fair because reducing college time + internship time + assignments. Excuses again :p . Anyway, we had already done the task division. Two of my friends were to design the database and make API. Two others were to write about product, cost estimation, etc, etc (They required us to write a lot). I were to work on the mobile development. It was too late to produce a full fledged application therefore, we opted to make a prototype of the final product we were to have with no API. The product we had was just a prototype with no back-end service. We didn’t make it to the top 26. Procrastination pays good ???? .

I started with phonegap and jquery mobile. It’s easier to build multi-platform applications with phonegap and jquery mobile than it is to brew coffee. I mean it. Let me tell you, it’s a bunch of

$(“.class-name”).on('click', function(e){

});

 

$(“#id-name”).on(‘click’, function(e){

});

 

$(“#id-name”).html(“some html content”)

 

function nameOfFunction(params){

}

 

$(“#id-name”).show();

 

$(“#id-name”).hide();

 

window.location.hash = “#id-name”;

 

window.localStorage.setItem(‘key’, ‘value’);

 

window.localStorage.getItem(‘key”);

 

$.ajax({
type: “GET” // “POST”,
url: “http://someapi”
data: data,
success: function(data){

}, error : function(e){

}
});

While you can make good working application with the above set of outlines. However, most of the time, you need to utilize the API of the OS. For example schedule a notification, send sms, etc. Don’t be surprised when I tell you it’s even easier to have those features in your application than it is to go to a barber to get your hair trimmed.

All you need, is to find a good plugin to talk to the OS’s API to perform things like sending sms via application, scheduling a local notification, etc. Comparably, plugins are the set of barbers with specialization in different hair styles. All you need to do is invoke a method they(plugins) provide at appropriate place like it is to go to a barber who knows how to trim your hair in specific style.

Below is the link to the github repository which contains the codes for the application prototype I built.

https://github.com/bhishan/ncellappcamp

I hope you enjoyed the article. Do comment below to say how you felt the article was or share your view on it. Will come up with a new article another week. Till then Happy Coding ???? Good bye !

Using Import Io To Extract Data Easily Example Usage Of Import Io Api

- - JavaScript, Tutorials, Web
Hey Guys, here in this post I will explain about one the most reliable and easy to use extraction api provider which is an open source tool named import.io

What is import.io?

Import.io is an open source, web-based data extraction platform which enables general users to access data from websites without writing any code. Import.io also serves API for extraction of necessary data which makes it very essential for programmers needing dynamic data from certain websites or data sources. Using import.io’s feature, data from websites can be queried easily either manually or with the use of an API. Using the service, the whole web can be considered as a big database for the machines and other applications to read the essential data which would definitely be more cumbersome while doing manually.

There can be numerous cases where a website does not provide API for data extraction. In cases like this, coding tactics to extract the right piece of information is possible but not very easy. Hence, import.io is the best fit because it provides API to extract the dataset more easily.

Example use of import.io’s API to extract data

1. Open up your browser and type in the following url to get to the coolest platform import.io . SignUp there, it’s free.

http://import.io

2. For this example, we are using a webpage of seasky.org. Below is the url where the dataset we want is present.

http://www.seasky.org/astronomy/astronomy-calendar-2015.html

3. Type in the url in the placeholder as shown below and press the Get Data button. Below is the similar screen-shot.

importdotiodataextract

4. Now we get the dataset we were looking for. Below is the screenshot of how it looks. At the buttom right corner is a button Get API. Press the button to get the API of import.io to extract the dataset. Now press copy this to my data.

importdotiogetdata

5. You now are able to query the dataset in various formats including JSON and TSV. Click on the Get API tab to see the structure of the url for query the dataset.

importdotiogetapi

6. At the end of the url is the parameter _apikey=YOUR API KEY. While using the url in your application you need to replace the YOUR API KEY with the alphanumeric api key provided by import.io. You can view this key by pressing on the parameter and typing your password for import.io account.

Using import.io API in code

Below is the piece of code I am using in my application to get the dynamic data from seasky.org

function getCalenderInfoFromServer(calenderYear){
    $.ajax({
        url: baseUrlDefault + calenderYear + baseUrlEnd + baseAPI,
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            console.log(data);
            parseEventDetails(data.results);
        },
        error: function (e) {
            alert(e);
        }
    });

}

Thanks for reading.

How To Setup And Remotely Access A Linux Machine With Openssh Via Putty Exe

- - Applications, Python, Tutorials
Hello Readers. Here in this post, I will be explaining on how to setup the essentials accessing a device remotely from another device in some other network. Follow along .

To better understand the tutorial, read the background behind writing this article here

How to reserve an ip for your device?

I will be explaining on reserving an ip for a device via router’s settings. My router’s model is TL-WR740N, brand TP-Link. However the sole concept and procedure is similar for all the routers. First, go to your router’s settings,

192.168.0.1 (in my case)

Now provide valid credentials for user and password. For most of the routers, the default username and password is admin

Click on the DHCP option, present in the menu in left side in case of TP-Link

Now go ahead and click on Address Reservation

Click Add New so you can reserve an ip address for a device. You will be required to enter the Mac Address of the device.

Open up terminal with the combination of keys Ctrl + Alt + T in your linux machine and enter the following command.

ifconfig

Since I connect via WI-FI, I look for Hwaddr under wlan0.

Go ahead and paste this mac address to the address reservation menu.

After this, enter a desired ip address, in my case 192.168.0.106. Check enable and save the settings.

Once done, you will be required to reboot the router to save these settings. That’s all for a static local ip.

Setting up openssh-server and port Forwarding

It is dead simple to set up openssh server in linux machine. Follow along,

Enter the following command to get openssh-server

sudo apt-get install openssh-server

Now, to keep the openssh running, hit the following command

sudo service ssh start

The default port for ssh is 22

Another step is to forward the incoming traffic to my router’s public ip in port 22 to the local ip of the linux device. In my case to 192.168.0.106

For this, we again go to the router’s settings. Open up browser and go to 192.168.0.1 or something similar to open the router’s settings.

Find the menu named Forwarding or something similar and click the option. Now under the sub-menu click on virtual servers.

Once done click Add New

Fill the details :

Service Port : 22

Internal Port : 22

IP Address: 192.168.0.106 (the local ip of the machine with openssh running)

Protocol: All (TCP/UDP)

Status: Enabled

Go ahead and save it.

What have we done so far? Assigned a static ip to a device. Installed openssh-server in the linux machine and run it. Forwarded the incomming traffic to port 22 of the router to the local ip of the machine.

Another step. Based on your ISP, the public ip for your internet surfing may change but is static most of the time. In my case the ip barely changes. So all I have to do is rot the public ip which is what I did.

How to access a device remotely via ssh while on Windows machine

Prerequisite: The machine running openssh-server must be powered on. However it is not necessary to login. Also openssh-server remains in running state by default when device is powered on.

Download putty.exe from here. Putty is a telnet and ssh client for windows. The size of the software is very small and you need not install it. It’s a download and run software.

Once downloaded, run putty.exe. Enter the public ip of your home network, specify port 22 and check ssh then press open. This will open a terminal. If the connection was established meaning both the home network and the network you are at is connected to internet, you will be prompted for login credentials of your remote device. Providing the correct login credentials will give you access to your device at home network via command line.

Search for a file and send an email with attachment remotely via ssh and some python

Now that you have access to your linux machine remotely. You can use ls commands to find the location of the file you are looking for.

In my case, it’s present inside /home/bhishan/lispcognitive.odt

To send this file via email, we will be using python interactive shell.

Run the command to open python shell

python

We will be using two standard modules in python namely smtplib and email to send email with an attachment.

The snapshot shows the codes I used to send email

python codes to send email attachment

python codes to send email attachment

Below, I’ve nicely formatted the codes in a more readable way.

import smtplib
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mine.text import MIMEText
from email.utils import formatdate

me = "fromemail@domain.com"
you = "toemail@domain.com"
password = "password"
msg = MIMEMultipart(
    From = me,
    To = you,
    Date = formatdate(localtime=True),
    Subject = "Sending email with attachment via python"
)
msg.attach(MIMEApplication(file("/home/bhishan/listcognitive.odt").read()))

s = smtplib.SMTP_SSL("smtp.gmail.com")
s.login(me, password)
s.sendmail(me, [you], msg.as_string())
s.quit()

If you have any questions regarding the post or the codes, comment below, so we can discuss.