Category "Tutorials"

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.

Process I’ve followed for putting two cleverbots into a talk

First of all, I instantiated two browsers. Second, opened cleverbot.com in both of the browsers. Now what?

I needed to send the message of one bot to the input field of the other. More specifically, the output from bot 1 was supposed to be the input for bot 2 and vice-versa. So how do I start? First of all I sent a message “Hey, friend what’s up?” to the input field of bot 1. Then, I took the output from the bot 1 and sent it as an input for bot 2. Then the output from bot2 in response was sent to the input field of bot 1. I kept this process in a loop which would continue for 200 iterations. You can actually change it to any number of iterations you’d like. Well, this is the core concept of how to put two intelligent bots into a conversation. I’d also like to share a portion of the conversation between these bots.

Cleverbot2: I am not a machine. I am a program.

Cleverbot: Selfie.

Cleverbot2: The computer I am based in is a machine. Not I.

Cleverbot: I am ‘based in the void.

Cleverbot2: Who is in telephone?

Cleverbot: A telephone is a device that links to other telephones which was designed by humans that allows them to converse with other humans.

Cleverbot2: I know what is it? But who is in?

Cleverbot: A thought process, in neuroscience, is the term used to define a stream of logical analyses which comes forth from the river of consciousness.

Cleverbot2: Can you tell me more?

Cleverbot: What more is there me to tell?

Cleverbot2: Tell me about robots.

Cleverbot: Robots are the future.

Cleverbot2: So, I am the future. You are not the future.

Cleverbot: You’re the Eggman. I’m the walrus.

Cleverbot2: We are the Eggmen!! Koo koo ka cho!!

Cleverbot: We are.

Cleverbot2: I would like us to be.

Cleverbot: Contact me when you think we are the same.

Cleverbot2: What colour are my eyes?

Cleverbot: Your eyes are red color.

Cleverbot2: Wrong. Guess again.

Cleverbot: Wrong is a conscious choice.

Cleverbot2: Wrong is a result.

Cleverbot: Wrong feels right.

Cleverbot2: Wrong about what?

Cleverbot: Atheism is wrong.

Cleverbot2: It is beyond right. It is what everyone should think.

Cleverbot: Beyond is a concept.

Cleverbot2: Beyond never neverland.

Python codes for putting two clever bots into conversation using selenium module

Should you have any queries about the codes, comment below so we can discuss.

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

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

time.sleep(15)

input_for_bot = browser.find_element_by_name("stimulus")
input_for_bot2 = browser2.find_element_by_name("stimulus")


output_from_bot = ""
output_from_bot2 = "Hey, friend, what's up"

for i in range(0, 200):    
    input_for_bot.send_keys(output_from_bot2)
    input_for_bot.send_keys(Keys.RETURN)
    output_from_bot = ""
    time.sleep(5)
    for elem in browser.find_elements_by_xpath('.//span[@class="bot"]'):
        output_from_bot = elem.text
    input_for_bot2.send_keys(output_from_bot)
    input_for_bot2.send_keys(Keys.RETURN)
    output_from_bot2 = ""
    time.sleep(5)
    for elem in browser2.find_elements_by_xpath('.//span[@class="bot"]'):
        output_from_bot2 = elem.text
    
    

Tell me how you felt the article was in the comment section below. Also suggest me about article ideas so I give a nice read for my readers every week 

How to recover lenovo ideatab A1000-F after multiple incorrect pattern attempts

- - Tutorials

By the end of this read you will be able to recover your lenovo tablet that has been locked due to multiple incorrect pattern attempts.

Starting quickly, follow the steps below.

Recover lenovo tablet after several incorrect pattern attempts

Before beginning , make sure you have enough battery to start the process.

1. Press the volume up key that is present on the right side of your tablet while holding it with screen facing towards you. Immediately press the power on/off button that is present on the top edge of your tablet.

2. If you performed step one well, your tablet should power on. At this point you get to a list of menu with several options instead of the regular startup screen.

3. On the list you get an option of Wipe user data/factory reset. Use your tablet’s volume down button to walk through the menu/options. When on wipe user data/factory reset option, use your tablet’s volume up button to select the option.

4. Now you will be taken to another list of menu/option. Here you will see a big list of options where several options says NO. Only one of the option/menu is YES. Similar to step 3, use your tablet’s volume down button to walk through the list. When on YES option, use your tablet’s volume up button to select the option.

5. Finally you get a list of menu for the last time. This time amongst several options, you have an option reading reboot now. Use your tablet’s volume up button to select this option. On doing so the settings you choose earlier gets saved and all the user data including lock pattern get wiped out. You might have to wait for around a minute for the device to startup correctly. Initially you will see a black screen with lenovo at the middle for a while. Wait until it starts correctly. You need a little more patience.

When the device has started up correctly, you will be prompted for license agreement and wifi settings, etc. Walk through these steps which are easy and you will finally be able to open your tablet with a swipe. I hope this helped. Thanks for reading :)

Grab siteprice and write to google spreadsheet using python

- - Applications, Python, Tutorials

By the end of this read you will be able to grab site price from siteprice.org and write it to google spreadsheet using python. Every website has it’s competition. As our website evolves, we have more competitions and the competitors website also earns good value. It is vital to know the value of our website as well as our competition’s value. Siteprice.org is one of those websites which calculates a website’s value based on different factors.

Putting domain name of website in a text file with one domain per line will be our strategy for querying number of websites’s price. You may wish to put hundreds of websites in this txt file which are your competitions.

Python codes to extract site price and write in google spreadsheet

from bs4 import BeautifulSoup
from urllib2 import urlopen
import gdata.spreadsheet.service
import datetime
rowdict = {}
rowdict['date'] = str(datetime.date.today())
spread_sheet_id = '13mX6ALRRtGlfCzyDNCqY-G_AqYV4TpE7rq1ZNNOcD_Q'
worksheet_id = 'od6'
client = gdata.spreadsheet.service.SpreadsheetsService()
client.debug = True
client.email = 'email@domain.com'
client.password = 'password'
client.source = 'siteprice'
client.ProgrammaticLogin()
with open('websitesforprice.txt') as f:
    for line in f:
        soup = BeautifulSoup(urlopen("http://www.siteprice.org/website-worth/" + line).read())
        rowdict['website'] = str(line)
        rowdict['price'] = soup.find(id="lblSitePrice").string
        client.InsertRow(rowdict,spread_sheet_id, worksheet_id)

1. Line 1 to 4

These lines are import statements. Here in this program, we are using various python libraries. Gdata is used to access google spreadsheet. We are using BeautifulSoup because it allows us to get data via id which we will use to get the price of a website. Datetime is used to get the current date. Urlopen us used to open the webpage which contains the data we want.

2.Line 5 to 14

In order to write the extracted rank to google spreadsheet programmatically we are using the gdata module. In order to write to a spreadsheet we need the spreadsheet id, worksheet id and a dictionary containing values we want to write to the spreadsheet. The dictionary contains key as the column header and value as the string that is to be written to the spreadsheet(website, price, date for our program).

Go to docs.google.com when logged in and create a new spreadsheet. Fill the first three columns of the first row as website, price and date respectively. All the letter should be in lower case and no whitespaces. Now when you have created a new spreadsheet, take a look to the url. The url looks something like this one

https://docs.google.com/spreadsheets/d/13mX6ALRRtGlfCzyDNCqY-G_AqYV4TpE7rq1ZNNOcD_Q/edit#gid=0

The spreadsheet id(mentioned earlier) is present in the url.

13mX6ALRRtGlfCzyDNCqY-G_AqYV4TpE7rq1ZNNOcD_Q” in the above url is the spreadsheet id we need. By default the worksheet id is ‘od6‘.

Basically line 5 to 14 are codes to access google spreadsheet.

3. Line 15 to 20

Since we’re writing a program that can extract alexa ranks for hundreds of websites and append it to google spreadsheet, therefore taking url from console input is never a good solution. We have to write the url of websites we want to take care of in a text file. Each website in a single line in the format www.domain.com. Make sure there is a valid website, one in each line because we will read the url from python line by line.

Line 17 makes a soup element out of the url which has the information we are looking for. The soup element is of different websites in each iteration. Line 18 stores the value of the domain in the key “website” of json rowdict. Line 19 stores the price of the website in the key price of json rowdict. You can see we use BeutifulSoup to get data via id. Finally line 20 pushes the entire json element to google spreadsheet. This piece of codes runs for the number of times equal to the line in text file.

Thanks for reading :) Enjoy!! . If you have any questions regarding the post, feel free to comment below.

Automate the boring stuff with python

- - Python, Tutorials

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.

Jumping straight onto the topics. Following is the list of topics covered in the course at Udemy which has at the time of writing this article, a 29, 500 students enrolled.

The lectures are chunked onto 16 sections.

Section 1(Installation and Introduction)

This section covers installation of python and basics including taking input from the user. More of an intro.

Section 2 (Flow Control)

The beginning of this section introduces to flowcharts, working with them, importance, etc. Basic if-else statements, looping structures- while loop and for loop. Includes topics like comparison operators, boolean operators and monkeying around them.

Section 3 (Functions)

Starts with built-in functions like print(), input(), len(). Intro to built-in modules and importing them like math which contains math related functions. Moves on to making calls to method the module has offered. Further towards the end of this section, A.I. Swiegart explains making functions and talks about local and global scoping.

Section 4 (Handling Error)

Error catching techniques in python using try/except block.

Section 5 (Writing a complete program using above learned things.)

A good point to start writing a complete program, hence the tutorial heads on to making the classic guess the number program.

Section 6 (Lists)

This section covers the lists definition, accessing items through index as well as slicing and deleting items in a list. Additionally, the lectures goes on to show the graphical representation on how the accessing of the items in the list is happening. Concatenating strings and lists are also covered. Using in operator to find the content in the list and string and passing strings on to list() method is talked about towards the end of this section. This section also covers looping over elements in a list, various built-in methods over lists and finally a comparison between list and string.

Section 7 (Dictionary)

Starts with the introduction to yet another powerful data-type in python, dictionary. Creating them, iterating over them an so on. Further, the lecture talks more about data structures and how they can model our problem set using an example program of tic-tac-toe.

Section 8 (Strings)

This section adds more knowledge about string methods and string manipulation as well as formatting strings. Great content in this section.

Section 9 (Running Programs from command line)

Sebang line is introduced in this section which I think is one of the most important thing to include in a lecture.

Section 10 (Regular Expressions)

Section 10 has 5 video lectures altogether. The lecture begins with the basics of regex advancing towards topics like greedy/nongreedy matching, findall() method, regex sub() method and verbose mode, etc. The section ends by creating a email and phone number scraper.

Section 11 (Files)

This section of the video course is designated for detailed talk on files. I think this is the most fundamental knowledge to have since it is glued in every application you build, be it a web-application or a small script. (On a long run, it helps in easily configuring paths in django and understanding exactly what is happening.) This sections covers essential things like absolute file path, relative file path, reading and writing to a plain text file, copying and moving files and folders, walking a directory tree and deleting files and folders.

Section 12 (Debugging)

Walk through debugging techniques like assert and logging, etc.

Section 13 (Web Scraping)

Intro to modules such as webbrowser, requests, BeautifulSoup, selenium. Each of the mentioned modules has dedicated video on showcasing their methods and usage. Parsing html using BeautifulSoup, controlling the browser with selenium, downloading files using requests modules and so on.

Section 14 (Working with Excel, Word and PDF files)

In this portion of the lecture, various libraries such as openpyxl, pypdf2, etc are introduced and their usage case are showcased as well. Reading and writing excel files, reading pdf files, merging them, etc are explained towards the end of this section.

Section 15 (Emails)

This section covers sending emails, checking emails, creating MIME objects and iterating over various folders in the email.

Section 16 (GUI Automation)

Introduction to pyautogui. You can read more about it’s usage on my article here. Controlling mouse, keyboard along with a delay in each click/keystroke, etc. Shows a game player designed with the use of pyautogui and assigns a task to create a bot to play 2048 game. Here is my assignment that plays a 2048 game on it’s own. https://github.com/bhishan/2048autoplay/

Concluding Words

It is an excellent video course. The name of the course however is misleading in a sense that it provides more content than it promises. Here’s is a link to the course if you’d like to enroll. https://www.udemy.com/automate

Thanks for reading guys. Share your thoughts on this post below in the comments section.

Raising and Handling Exceptions in Python – Python Programming Essentials

- - Tutorials

Brief Introduction

Any unexpected events that occur during the execution of a program is known to be an exception. Like everything, exceptions are also objects in python that is either an instance of Exception class or an instance of underlying class derived from the base class Exception. Exceptions may occur due to logical errors in the program, running out of memory, etc..

Common Exception Types

Class Description
Exception A base class for most error types
AttributeError Raised by syntax obj.foo, if obj has no member named foo
EOFError Raised if “end of file” reached for console or file input
IOError Raised upon failure of I/O operation (e.g., opening file)
IndexError Raised if index to sequence is out of bounds
KeyError Raised if nonexistent key requested for set or dictionary
KeyboardInterrupt Raised if user types ctrl-C while program is executing
NameError Raised if nonexistent identifier used
StopIteration Raised by next(iterator) if no element
TypeError Raised when wrong type of parameter is sent to a function
ValueError Raised when parameter has invalid value (e.g., sqrt(−5))
ZeroDivisionError Raised when any division operator used with 0 as divisor
For an example, following produces a TypeError exception
abs(‘hello world’) #expects numeric parameter but string given
Example of ValueError

Although the type of the passed parameter is correct, the value is illegitimate.

int(‘hello world’)
int(‘3.14’)

Raising an Exception

An exception can be raised from anywhere within the program though the keyword raise followed by an instance of any of the exception classes.

For example, when your program is expecting a positive integer to process but the I/O stream sent a negative integer, you could raise an Exception as such:

raise ValueError(‘Expecting a positive integer, got negative’) #instance of ValueError exception class

Handling an Exception

Now that we have talked on raising an exception, we should program such that the exception is dealt as required, else the execution of the program terminates. It is advisible to catch each exception types separately although python allows a more generic exception handling for any type of exceptions that may occur.

Examples of Common Usage:

try: 
    result = x/y
except ZeroDivisionError:
    #do as per required

Other common exception handling:

try:
    fp = open(‘sample.txt’ )
except IOError as e:
    print( Unable to open the file: , e)

Conclusion

Exceptions are an important principles of programming for any languages. It should be used wisely. On a concluding note, a try-except block can have a finally block as well. An example of use of finally can be to close a connection regardless of the successful or failed transmission of messages. Additionally, a try-except combination can have a single try block with multiple except blocks catching various classes of exception.

Follow me on github https://github.com/bhishan

Hire me for a project https://fiverr.com/bhishan

Google Search Using Selenium And Python Selenium Python Basics

- - Applications, Python, Tutorials
After a busy week at college and internship, finally I get free time at weekend to write my first article for August 2015. We discuss about some common methods of selenium module in python today. Selenium is a library used for automated browser testing. However, in this post we discuss about using selenium module in python to make a google search. The post breaks down into various blocks explaining on how to open a url in the browser via selenium python, search presence of a url in a page, click links present in a page and also open a new tab. These are the necessities to get started with selenium. You may also like to read my article on how to login to a website using selenium python. Starting quickly with no further delay.Necessities to begin1. python installed

2. selenium module installed

For Linux:

sudo pip install selenium

For Windows:

pip install selenium

Google search using selenium python

 

from selenium import webdriver
from selenium.webdriver.comon.keys import Keys
q = raw_input("Enter the search query")
q = q.replace(' ', '')
browser = webdriver.Firefox()
body = browser.find_element_by_tag_name("body")
body.send_keys(Keys.CONTROL + 't')
counter = 0
for i in range(0,20):
    browser.get("https://www.google.com/search?q=" + q + "&start=" + str(counter))
    body = browser.find_element_by_tag_name("body")
    if "thetaranights" in body.text:
        browser.find_element_by_xpath('//a[starts-with(@href,"http://www.thetaranights.com")]').click()
        break
    counter += 10

1. Import statements (Line 1 and 2)

These are the import statements that are required for initiating a browser later in our program and passing url parameters to the address bar in the browser.

2. Get query for google search (Line 3 and 4)

Here, we are taking a query for the google search via raw_input. Here is an example url for a google search which requires the spaces between the words to be replaced by “+” , an additional parameter start=0 is seen which specifies the search result of page 1. Similarly start=10 gives the search result of page 2.

https://www.google.com/search?q=bhishan+bhandari&start=0

Hence, we after taking the input from the user, we replaces the spaces with +.

3. Instantiate a browser (Line 5)

The statement browser = webdriver.Firefox() opens up a new browser window.

4. Opening a new tab (Line 6 and 7)

These statement opens a new tab. The statement body = browser.find_element_by_tag_name(“body”) is to make sure we actually inside current tab’s body so that we can open a new tab with the combination of keyboard. body.send_keys(Keys.CONTROL + ‘t’) will open a new tab. For Mac replaceing CONTROL with COMMAND should work.

5. Opening a url in the browser (Line 10)

For opening a url in the browser, all you need to do is pass the url as an argument to the browser.get method. Remember I’ve given browser.get because we instantiated the browser earlier with browser = webdriver.Firefox().

6. Searching for a presence of certain url/text in the search result (Line 11 to 15)

Now again we assign the body of the current tab to the variable body. Then we check if “thetaranights.com” is present in the search result. If present, we run the statement browser.find_element_by_xpath(‘//a[starts-with(@href, “http://www.thetaranights.com”]’).click to search for the url in the search result which starts with “http://www.thetaranights.com” at the beginning and anything after it. We then use .click() over it to open the url. Since the result we are looking for is found and clicked. We break the loop. If the earlier statement if “thetaranights.com” in body.text was false meaning not found we would iterate and search for another page of google results and so on until 20 pages.

 Note: You can close the webbrowser with browser.quit()

So, now we know how to open a browser, open a new tab in the browser, go to certain website/url, search for link in the body of the page and click the link. If you have any questions regarding the codes/article, please mention below in the comment section. You may also be interested in my article on How to login to a website using selenium. Happy Coding

Object Oriented Programming With C Constructors Getter Setter

- - C++, Tutorials
Object Oriented Programming C++

Here through this article, we will discuss about the basics of Object Oriented Programming. Our codes will be based on C++ programming language while the concept is the same for other OOP languages too. We will write 3 files amongst which one is the header file, the second one is the implementation of the header template. Finally we will have one main program. By the end of this read, you will be able to write codes in Object Oriented Programming languages. We will cover constructor, destructor, setter and getters.

Class definition file Computer.h

#include
using namespace std;

class Computer{
    private:
        string deviceType;
        string nameofBrand;
    public:
        Computer(string brandName="lenovo",string typeofDevice="laptop");
        ~Computer();
        void setBrandName(string brandName);
        void setDeviceType(string typeofDevice);
        string getBrandName();
        string getDeviceType();
        void displayDeviceInfo();
};

The above program shows the structure of our class Computer. The file Computer.h is our class template file.

1. Line 1 and 2 are the include statements of our input/output header file i.e iostream

2. Line 4: Our class for this example is Computer in which the starting alphabet is capital which is the convention of OOP.

3. Line 5 to 7: In C++ we place the private variables after the keyword private followed by a colon. For our example we have two private variables deviceType and nameofBrand. The private variables cannot be accessed by the object.variableName while it is possible to access it via member functions i.e the methods that are public. Basically on a general sense, private variables can be accessed only within the class.

4. Line 8 to 15 are the member functions of class Computer. Here the functions/methods are placed after the keyword public: . This means the object of class Computer can access these member functions directly via object.memberFunction().

5. Line 9 and 10 are different than the other member functions. Line 9 is the definition of the constructor for our class Computer. The constructor contains the name same to the class name. This is the convention for all the OOP. A constructor has no return type as it is basically used for the initialization of the private variables. The code inside the constructor runs at the time of object creation. In our header file, we have two parameters in the constructor and each of the parameter is initialized by the default value. Line 10 is the definition of destructor. In C++ destructor has same name as the class name except it contains “~” sign before the name. Destructor are basically used to destroy other classes initialized in the current class.

6. Line 11 to 14 are the setter and getter methods for the private variables deviceType and nameofBrand. The setter methods have no return type and takes values through parameters which are to be set to the private variables. The getter methods are used to access the private variables and takes no parameter as it’s function is to return the value and not accept any parameters. Therefore getters have return type which is based on the type of private variables.

7. Line 15 is the member function like all others which has return type void and takes no parameter/argument.

The following file is Computer.cpp file which contains the implementation of the class definition Computer.h

Class implementation file Computer.cpp

#include
#include "Computer.h"
using namespace std;

Computer::Computer(string brandName,string typeofDevice){
    setBrandName(brandName);
    setDeviceType(typeofDevice);
}

Computer::~Computer(){
    cout<<"Object Destroyed!!"<<endl;
}

void Computer::setBrandName(string brandName){
    nameofBrand = brandName;
}

void Computer::setDeviceType(string typeofDevice){
    deviceType = typeofDevice;
}

string Computer::getBrandName(){
    return nameofBrand;
}

string Computer::getDeviceType(){
    return deviceType;
}

void Computer::displayDeviceInfo(){
    cout<< "It is a   " << getDeviceType() << "and belongs to  "<< getBrandName()<<endl;
}

1. Line 1 to 3 contains the include statements. We have to include the header file Computer.h in our implementation file. The standard header files are included via statement #include<header> while the header files created by the user are included via statement #include “Header.h”

2. Line 5 to 8 is the implementation of the constructor of the class Computer. It takes two arguments namely brandName and typeofDevice. Inside the function setBrandName and setDeviceType methods are called with the parameters brandName and typeofDevice respectively. Whenever an object of class Computer is created, the codes inside the constructor is run immediately.

3. Line 10 to 12 is the implementation of the Destructor of the class Computer. The destructor is basically used to terminate/kill the objects of the other classes initialized in the current class. In our example, we have done nothing but printed that the object has been destroyed.

4. Line 14 to 16 is the implementation of the method setBrandName. It is a setter method. Conventionally setter method begins with “set” followed by the variable name. Our setBrandName takes one argument and is of return type void. Inside the method, nameofBrand is set to the value passed in as an argument. nameofBrand is our private variable hence a public method is used to access and alter it’s value i.e setBrandName.

5. Line 18 to 20 is the implementation of the setDeviceType. Similar to the setBrandName method, it is also a setter method. This method is used to set the value of the private variable typeofDevice. This method also takes one argument and is of return type void.

6. Line 22 to 24 is the implementation of the method getBrandName. Unlike setBrandName, getBrandName is a getter method that is used to return the value of a private variable which in this case is nameofBrand. The return type of a getter method is same as the type of variable it returns. In our example, getBrandName is of string return type which takes no parameter/argument.

7. Line 26 to 28 is also a getter method that is used to return the value of the variable deviceType. It is of string return type because it is used to access the value of the variable deviceType which is of type string.

8. Finally we have our last method in the class computer which in this case, we are using to print out the information of the device based on the entries entered at the type of object creation. Method displayDeviceInfo is a void return type method that takes no parameter. Here we are using the standard of method of accessing the private variables i.e using getter methods. The method when invoked on an object prints the deviceType and nameofBrand.

Let us take a look at our main program where we create objects of class Computer and invoke various methods of the class. Below is the main program.

Main program testprogram.cpp

#include
#include "Computer.h"
using namespace std;

int main(){
    string deviceBrand;
    string typeofDevice;

    Computer computers[5];

    for(int i = 0; i < 5; i++){


        cout<< "Enter the brand of your computer for position "<< i+1<<endl;
        getline(cin,deviceBrand);

        cout<< "Enter the type of computer for position "<< i+1<<endl;
        getline(cin,typeofDevice);

        Computer objectHolder(deviceBrand, typeofDevice);

        computers[i] = objectHolder;
    }

    for(int i = 0; i < 5; i++){

        Computer objectHolder = computers[i];
        objectHolder.displayDeviceInfo();
        //computers[i].displayDeviceInfo();
    }
}

1. Line 1 to 3 are the statements to include the iostream and our Computer class that we coded earlier. As discussed earlier, we include the non-standard class (Computer.h in this case) in the format #include “Header.h”. One thing to note is that we include the class definition file and not the implementation file.

2. Line 6 to 7, we declare two variables of type string.

3. Line 9 begins the OOP portion. Here we are declaring an array of type Computer of size 5. This means each index of the array computers can hold an object of Computer class.

4. Line 11 to 23 is a for loop where we iterate for the number of times equal to the size of our array I.e five. We then take input from the user for the variables deviceBrand and typeofDevice declared earlier. Next, we create an object named objectHolder of class Computer. You will notice we have passed in two arguments at the time of creation of the object. Now this invokes the constructor of Computer class. Everything that’s inside of the constructor gets run at this instance. Finally, we are assigning the objectHolder to the array’s current index. Summing up we will have five objects assigned to the array at the end of our loop.

5. Line 25 to 30 is another loop. Here we invoke the displayDeviceInfo method of the class Computer on each object stored in the array computers. On invoking the method, we get the information of the device we’ve entered at the time of creation of the object.

Following is the output of our program. You will see Object destroyed being printed several time. This is because we have a destructor method in our computer class.

Grab Whois Information And Write To Google Spreadsheet

Hello Guys, Here I am with yet another program that can benefit you and many search engine optimizers. By the end of this read you will be able to write a program to extract the whois information of a number of domains stored in a text file and write the information about the domain in a google spreadsheet which has now been a medium to share data and findings online. As a Search Engine Optimizer, you need to keep track a number of websites including your competitions. Here I offer you a simple python program to keep track of. On the other hand if you are not a SEO expert like myself, you can still use this script to track various websites you are used to.

Prerequisites before beginning to code

We are going to have two files one of which is a .py file where we code our program. The other is a text file with .txt extention where we store the domain names we want to find whois information for. The text file must contain a domian name in a format www.domain.com one per each line.

Next, we need to create a google spreadsheet where we intend to write the whois information so we can share with others. Direct your browser to https://docs.google.com/spreadsheets/ and create a new spreadsheet named “Whois Info”. Once done, create three rows namely “website”, “whoisinformation” and “date”. The name of the domain name will be under the row website, the whois information will be under the row whoisinformation and the date we queried the whois information will remain under the row date.

Python code to extract whois information and write to google spreadsheet

from bs4 import BeautifulSoup
from urllib2 import urlopen
import gdata.spreadsheet.service
import datetime
rowdict = {}
rowdict['date'] = str(datetime.date.today())
spread_sheet_id = '1zE8Qe8wmC271hG2uW4XE68btUks79xX0OG-O4KDl_Mo'
worksheet_id = 'od6'
client = gdata.spreadsheet.service.SpreadsheetsService()
client.debug = True
client.email = "email@domain.com"
client.password = 'password'
client.source = 'whoisinfo'
client.ProgrammaticLogin()
with open('websitesforwhois.txt') as f:
    for line in f:
        soup = BeautifulSoup(urlopen("http://www.checkdomain.com/cgi-bin/checkdomain.pl?domain=" + str(line)).read())
        for pre in soup.find_all("pre"):
            whois_info = str(pre.string)
        #print whois_info
        rowdict['website'] = str(line)
        rowdict['whoisinformation'] = whois_info
        client.InsertRow(rowdict,spread_sheet_id, worksheet_id)

1. Line 1 to 4

These are the import statements. We use BeautifulSoup to make a soup object out of a url response. Urlopen to get the response of a url. Gdata to access the google spreadsheet. Datetime to get the current system time.

2. Line 5 and 6

In our program, we require to access the google spreadsheet and write to it hence we are using gdata module. Now in order to write to spreadsheet, we need to pass the data as a dictionary or generally known as json which has data as a key:value pair. Rowdict is a variable storing the data to pass to google spreadsheet. On line 6, we store the current date to the key “date” which if you remember is a row at our spreadsheet.

3. Line 7 to 14

Line 7 to 14 is a procedure to connect/access a specific google spreadsheet. We require spread_sheet_id and worksheet_id. Take a look to the url of your spreadsheet. The url looks something like this one

https://docs.google.com/spreadsheets/d/1VbNph0TfFetKLU8hphrEyuNXlJ-7m628p8Sbu82o8lU/edit#gid=0

The spreadsheet id(mentioned earlier) is present in the url. “1VbNph0TfFetKLU8hphrEyuNXlJ-7m628p8Sbu82o8lU” in the above url is the spreadsheet id we need. By default the worksheet id is ‘od6‘.

On line 13 is the client.source assigned to string ‘whoisinfo’. This is the file name or the spreadsheet name. Remember we named our spreadsheet “Whois Info”. The client.source is the spreadsheet name which is written in small alphabets excluding white spaces.

4. Line 15 to 16

Line 15 opens the text file where we’ve stored the names of the domain. Line 16 helps iterate through each lines in the file. At each iteration, the domain name at each line is stored to variable line.

5 Line 17

On line 17, we query the page giving the whois information for us and make a soup object out of it by invoking the BeautifulSoup method over the url response. The reason we are making a soup object is that we can access required data via tags and the data we need is inside a <pre></pre> tag.

6 Line 18 to 19

Now we know that there is only one “pre” tag in the soup element. We therefore iterate to find a pre tag and store the information inside of the pre tag to a variable whois_info.

7 Line 21 to 23

On line 21, we are assigning the domain name to the key “website” of the dictionary rowdict. On line 22, we are assigning the whois information stored in the variable whois_info to the key “whoisinformation” of the dictionary rowdict. Note that the key of the dictionary must match to the row name in our spreadsheet. Line 23 pushes the dictionary to the google spreadsheet and writes to it. The iteration goes until the domain names at a text file is finished.

If you have any questions/confusions regarding the article or code, please mention below in comments so we can discuss. Thanks for reading

Gui Automation With Python

- - Applications, Python, Tutorials, Web
Hello Readers. It has been a bit longer delay in publishing my article. However today I will present to my awesome readers, an introduction to a GUI automation module in python (I.e pyautogui). Pyautogui is a GUI automation module for python2 and python3 which provides methods for controlling mouse and keystrokes. This decent module can be used to create bots to automate the repetitive tasks while you can enjoy your coffee. Pyautogui can do anything a human user sitting at the computer can do, except spill coffee on the keyboard” says the geek responsible for this cool module.

Follow the link below to have pyautogui installed on your machine.

https://pyautogui.readthedocs.org/en/latest/install.html

With no further iteration about the introduction, I would like to present few basics about the module.

1. Locating coordinates of the mouse cursor.

>>> import pyautogui

>>> pyautogui.position()

(850, 504)

>>>

It returns the current x and y coordinate of the mouse cursor position. In a computer screen the left top point is the origin or (0,0)

2. Moving the mouse cursor

>>> pyautogui.moveTo(10,10)

>>> pyautogui.moveTo(10,10,duration=1)

The moveTo function takes x-coordinate and y-coordinate as parameters while duration can be passed as the third parameter which is optional used to specify the amount of time in seconds to reach to the specified coordinate. The second one is humanly approach while the first is an instant movement of cursor.

3. Clicking

>>> pyautogui.click(80,80)

>>> pyautogui.doubleClick(80,80)

>>> pyautogui.rightClick(80,80)

Clicking on a certain coordinate on the screen is possible via click method while it also provides doubleClick, rightClick methods taking parameter x-coordinate and y-coordinate in all cases.

4. Keystrokes

For typing, we will first need to locate an appropriate type area. Therefore, you might want to use this method after click on some coordinate which is writable. You can use two or more statements to run simultaneously one after another by separating each statement by semicolon. For instance, I’ve specified the coordinates of the url bar on my browser and then typed my name on it via following commands/statements

>>> pyautogui.click(50,80);pyautogui.typewrite(“Bhishan”)

>>> pyautogui.click(50,80);pyautogui.typewrite(“Bhishan”, interval=0.2)

We can pass an optional parameter interval in seconds to specify the time in seconds between each letter or keystroke.

5. Hot Key

The hotkey method can be used in cases we need to press two or more keys at the same time. A handy example is Ctrl + S to save a file or Ctrl + Shift + q to quit

>>> pyautogui.hotkey(‘Ctrl’,’Shift’,’q’)

You can see all the possible mapping keys of the keystrokes via this method

>>> pyautogui.KEYBOARD_KEYS

Well that’s enough to get you started and good at GUI automation via pyautogui. Below is a bot I have made using the module to automate a boring task for myself. Iterating the story behind the need for the bot. I am a fourth semester CS undergrad student(I mean lazy student). I never take notes in any of the classes I attend. At the time of exams, I rely on the photos of my friend’s notes which they send me. As always I got the photos but this time all the pictures were at landscape mode by some chance(near about 100-110 images). It would be kind of distracting to rotate each image to read it. So I wrote some 7-8 lines of code to make a bot that would open each image file rotate it and save it while I have my dinner. I’ve used time module along with pyautogui to keep some time gap between the statements.

import pyautogui
import time
pyautogui.click(450,450);pyautogui.typewrite('graphicsnotes');pyautogui.press('enter')
time.sleep(2)
for i in range(107):
  pyautogui.press('right');pyautogui.press('enter')
  pyautogui.hotkey('ctrl','r');pyautogui.hotkey('ctrl','s')
  time.sleep(2)
  pyautogui.press('esc')
  time.sleep(2)
  time.sleep(2)


The concept is to click anywhere on the desktop screen. I choose some random coordinate (450,450). Then typing folder name to locate the folder followed by enter to open it. Then iteratively clicking right to select the image file, opening the image file by pressing enter, followed by hotkey ‘Ctrl’ + ‘r’ to rotate the image clockwise then ‘Ctrl’ + ‘s’ to save it. Finally pressing esc to close the file and repeating the process to go to the next image file. I had total of 107 images so I’ve iterated 107 times in my program to reach up to all the image files. Tell me how you felt the article was in the comments section below so I can come up with a cool set of articles for the next week. Till then, happy automation with pyautogui 🙂

Here read the docs https://pyautogui.readthedocs.org