Posts Tagged ‘tutorial’

Hi guys, this is a post on creating a simple text mode menu in Python 2.7.x. Hope this helps! Below is the output of the sample menu that we will be creating:

Sample Menu

------------------------------ MENU ------------------------------
1. Menu Option 1
2. Menu Option 2
3. Menu Option 3
4. Menu Option 4
5. Exit
-------------------------------------------------------------------
Enter your choice [1-5]: 

Here we have a function print_menu() which is used only to print the menu and the options available. This function does not take any inputs.

The source we have here creates a menu with 5 options with the 5th option to exit the menu.

Here, we create a Boolean variable named “loop” and set its value to “True“. Then we create a while loop which will run until the value of “loop” is “False”.

And within the while loop, we call the function print_menu() in which the user is presented with a menu and the list of options. We now request the user input and store it in a variable named “choice” [NOTE: The input must be a number and not any character or else it will through a error].

Now, we use create if statements to check the value of choice. For example: the first if statement checks if choice==1 and if it prints “Menu 1 has been selected”. Similar, We make use of elif statements to check other values of choice.

And when choice==5, we change the value of “loop” to “False” , which will end the while loop as it will only run when the value of “loop” is “True“.

Finally, for all other numbers other than 1,2,3,4 and 5, we simply print and error message and requests the user to enter a valid input and to try again.

Source Code:

## Text menu in Python
     
def print_menu():       ## Your menu design here
    print 30 * "-" , "MENU" , 30 * "-"
    print "1. Menu Option 1"
    print "2. Menu Option 2"
    print "3. Menu Option 3"
    print "4. Menu Option 4"
    print "5. Exit"
    print 67 * "-"
 
loop=True       
 
while loop:          ## While loop which will keep going until loop = False
    print_menu()    ## Displays menu
    choice = input("Enter your choice [1-5]: ")
    
    if choice==1:     
        print "Menu 1 has been selected"
        ## You can add your code or functions here
    elif choice==2:
        print "Menu 2 has been selected"
        ## You can add your code or functions here
    elif choice==3:
        print "Menu 3 has been selected"
        ## You can add your code or functions here
    elif choice==4:
        print "Menu 4 has been selected"
        ## You can add your code or functions here
    elif choice==5:
        print "Menu 5 has been selected"
        ## You can add your code or functions here
        loop=False # This will make the while loop to end as not value of loop is set to False
    else:
        # Any integer inputs other than values 1-5 we print an error message
        raw_input("Wrong option selection. Enter any key to try again..")

Feel feel to leave a comment if you have any queries or want to reach out to me. You can also Follow/Subscribe to my blog to get future blog posts! Happy Bloggin! 🙂

Regards
ΞXΤЯΞМΞ

This is a quick tutorial on reverse loops in Python 2.7.x  and also will be showing you an example on how to reverse a list. There are many methods you can do achieve this. In this tutorial, we will not be using the list.reverse() method which is simpler but will be using a simple loop and another method i.e. using the reversed() function to learn more about reverse loops.Hope this helps!

Lets say we have some numbers stored in a list (u can make use of any random numbers, here I have used numbers 0-9 for simplicity) as follows:

number_list= [0,1,2,3,4,5,6,7,8,9]

And now if we need to store & display these numbers in reverse order, we can use the reverse loop as follows:

## Reverse Loops in Python 2.7.x
number_list= [0,1,2,3,4,5,6,7,8,9]       ## Sample list 

print "Original List = ", number_list  ## Displays list

reversed_list=[]        ## Create an empty list named reversed_list

for item in number_list[::-1]:      ## Reverse Loop
    reversed_list.append(item)      ## Add/Append current item to reversed_list

print "Reversed List = ", reversed_list ## Print Reversed List

Output:

Original List =  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Reversed List =  [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Alternative Method  (using reversed function):

Consider the below list:

number_list= [0,1,2,3,4,5,6,7,8,9]

First, we will calculate the size/length of the list, by using the function len() and storing it into a variable size_of_list

size_of_list=len(number_list)

Here, the value of  the size_of_list will be 10.

[NOTE :Here range(10) will be a list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] . And we use reversed(range(10)) function to reverse the values of range list, and then use the for loop to assign the first value of item as 9, second value as 8 and so on. ]

## Reverse Loop in Python 2.7.x using reversed function

number_list= [0,1,2,3,4,5,6,7,8,9]       ## Sample list
print "Original List = ", number_list  ## Displays list

reversed_list=[]            ## Create an empty list named reversed_list
size_of_list=len(number_list) ## Store Size/length of list , (here length is 10)

for item in reversed(range(size_of_list)): ## Reverse loop
    reversed_list.append(number_list[item]) ## Add/Append current item to reversed_list

print "Reversed List = " , reversed_list  ## Print Reversed List

Output:

Orginal List =  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Reversed List =  [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Feel feel to leave a comment if you have any queries or want to reach out to me. You can also Follow/Subscribe to my blog to get future blog posts! Happy Bloggin! 🙂

Regards
ΞXΤЯΞМΞ

I have just installed CentOS 6.5 (minimal)  in Virtual Box on my Windows 8.1 pc. This is how I installed CentOS. Hope this helps.

[Update: The updated version of this article with screenshots for CentOS 6.7 can be found here.]

Requirements:

  1. CentOS 6.5 32-bit ISO : Download Link (~330 MB)
  2. Virtual Box : Download Link (~110 MB)
  3. Atleast 8 GB of free disk space.

Installation Procedure:

First, thing you need to  do is to set up your Virtual Box. Go ahead download and install Virtual Box (the download link is given above in the requirements).

Press “New“, Type Name as “CentOS 6.5 32 bit” or anything you want. Set the type as “Linux“, Version as “Red Hat 32 bit“. And press “Next”.

create vm

name and type of OS pic

Allocate RAM to 512 MB RAM or higher , then click “Next“.

select ram size pic

Then select the option “Create a virtual hard drive now “, then click on “Create“.

create hd pic

Select hard drive file type as the first option “VDI” , then click on “Next“.

hard disk type: vdi pic

Select type as “Dynamically allocated“. Choose the amount of hard disk space you want to allocate for your CentOS system. Select atleast 8Gb-10GB or higher and then click on “Create“.

VM HD size pic

Now, you would see the home screen of the Oracle Virtual box, Click on the CentOS VM you have created and then click “Start“.

start vm

Then click on the yellow folder icon and select the ISO file that you have downloaded.

Select ISO location

Then click on “Start“.

start boot

Wait for a few seconds and you will see the CentOS boot menu. Now, select the first option “Install or upgrade an existing system“.

Boot menu picture

 

[Note: To scroll through different options, you can either use the Arrow keys in your keyboard or the TAB key to move through different options . You may also use SPACE bar in your keyboard or ENTER key to make selections]

Now, you will probably get a message box saying “Disk Found” and if you want to verify the contents in the CD. Press “Skip”. If you need, you can press “OK” and verify the contents but it might take a while.

Using your arrow keys, select “Skip” and then hit “Enter“.

Disk check pic

loading screen

Hit “OK“.

CentOS Welcome

Now, select the language and then use the TAB key and then select “Ok” and hit ENTER.

select language

Now, select the model of the keyboardand then select “OK“.

keyboard selection pic

If you get a “Warning Message” such as the one below, just chooseRe-initialize all“.

Re-initialize all picture

Now, select your time zone and then hit “OK“. Then select a password for your “root” (or admin account), you can use TAB keys to reach the next box, and finally select “OK” and hit ENTER.

create root password

Now, select the option “Use entire drive“, and select “OK”.

allocate hard drive picture

Now, select “Write changes to disk” and the installer should start right up.

installation picture

installation progress pic

After, it is done installing , you will see a message saying “Congratulations, your CentOS installation is complete“. Select “Reboot” and hit ENTER.

installation complete -Reboot

Now, it should boot right up.

centos bootup picture

now, type login as: root , Then hit ENTER. Then type the password and hit ENTER. You should see now be able to see the terminal window with the # symbol.

root login pic

 

And voilà ! You have successfully installed CentOS 6.5 in Virtual Box.

This is a minimal mode CentOS and so many application packages are not installed. You will also have to configure the network to access the internet.

[UPDATE: To configure network in CentOS 6.5 (which is the same as configuring centos 6.3), I have made a detailed guide with screenshots, you can find it here.]

If you have any sort of queries on regarding this installation, just leave a comment and will get back at you. Don’t forget to follow my blog to get future updates! :D

Regards
ΞXΤЯ3МΞ

This is a simple guide on installing Python 2.7.8 in Windows 8.1 operating system with screenshots.

Requirements:

  1. Windows 8.1 / Windows 8 OS
  2. Python 2.7.8 : Download Link (~15.92 MB)

Step 1: Installation

Download the python setup file mentioned above and run the installer.

 

installer window picture

Click “Next”.

2

Leave it to the defaults and then click “Next“,

installation directory picture

Now in customize screen, you may see a RED X next to “Add python.exe to Path”.

Customization Screen picture

Click on the RED X and then select the first option option “Will be installed on local hard drive”.

custom selection picture

So finally you will have the below screen:

customization final

Then click on “Next“, and follow the on screen instructions:

progress picture

Finally, click on “Finish“.

python installation complete

 

Step 2: Running the Python Interpreter.

Now, to open Python Interpreter in your Windows 8.1 machine, Press Windows key+X (Press Windows key and while pressing CTRL , tap the letter R once) , you will see a context menu (shown below), click on “Command Prompt (Admin)“. (Click Yes if prompted from User Account Control)

cmd run as admin picture

You will now see the windows command prompt window as shown below:

command prompt admin window picture

Now, type python and then “Enter” in your keyboard to start using the DOS interactive python interpreter.

12

Now, you test it by writing a simple print statement, such as:

print “Hi EXTR3ME”

and then hit “Enter“, you will see the output in the next line as shown below:

python dos shell output

You should have by now installed Python 2.7.8 in your Windows 8/8.1 systems and also written a sample program to test it.

Hope this helps. Feel free to leave a comment below or if have any further queries. 

Don’t forget to subscribe to get future updates! 🙂

Regards
ΞXΤЯ3МΞ

If you are not able to find the Developer options after updating to Android 4.3 in your Xperia (mine is a Xperia M ), then do the following:

In your phone open “Settings” page, then click on “About phone”  scroll down to “Build Number” and keep tapping on it until you get the message “You are now a developer”. 🙂

Build option

Now, Go to Settings and then scroll all the way down, and just above “About Phone” you would see “Developer Options”and click on it.

Developer options

Click on it. Then Make sure the top “Developer options” is selected, and then check the option “USB Debugging”.

USB debugging option

Then click on “OK“.

confirmation screen

Finally, you will have :

USB debugging turned on

Hope this helps! Don’t forget to follow my blog to get future updates! Hope you have great day. Happy Blogging!  🙂

Regards,
ΞXΤЯ3МΞ

This is a guide on how to install Zorin OS 7 (64-bit) in Virtual Box. Hope this helps!

Requirements:

  1. Zorin OS Core ISO : Download Link (~1.5GB)
  2. Virtual Box : Download Link  (~96 MB)
  3. Atleast 8 GB of free hard disk space.

Installation Procedure:

First, download and install Virtual Box in your computer using the download link mentioned above. Also, download the Zorin OS ISO to any location of your choice.

Open Virtual Box, click on “New“:

1

Now, enter “Name” anything as you wish, Type asLinux” and Version asUbuntu (64-bit)“. Then, click on “Next“.

Name and Operating system

Now, select the amount of RAM you want to allocate for your Zorin OS Virtual machine. I would recommend a minimum of 512MB-1024MB. I have allocated 1024 MB (i.e. 1 GB of RAM) for my Zorin OS VM.

Memory Size

We need to create a virtual hard drive. Click on “Create a virtual hard drive now” and click on “Create“.

Create Hard Drive

Now, select the option ” VDI(Virtual disk Image) ” and click on “Next”.

Hard Disk Type

Now, select “Dynamically allocated“. {NOTE: You can also go with fixed size if you want but it will take longer time to create but is faster to use }

Storage Type

Now , you can select the size of your virtual hard disk by dragging the slider across. You can also choose a custom location where you want to save your Zorin OS by clicking on the red box that I have highlighted. Make sure you allocate a minimum of 8 GB. After selecting the appropriate options, click on “Create“.

7

Now, Click on the Virtual machine, you created and click on “Start“.

9

Now, click on the small folder icon which I have highlighted in red and browse to the ZorinOS ISO file you have downloaded earlier.

10

11

Now, click on “Start” once you have selected the ISO file.

12

To start the installation, select the option “Start the installer directly“.

13

Wait a few moments for the installer to load.

14

Select the Language of your choice and click on “Continue“.

15

Click on “Continue“.

16

Select “Erase disk and install Zorin“.

17

After this step, you would be prompted to select your location. You can click on the map to select your location and click on “Continue“. Then select the keyboard layout of your choice and click on “Continue“.

19

Now, you can enter “Your Name” , “Your computer’s name” , “username” and a “password” of your choice and click on “Continue“.

20a

Now, it will copy the nessasry files and install the Zorin OS.

21

This may take a while depending on your computer configuration.

23

You will get a prompt stating that the Installation is complete. Click on “Restart Now“.

24

Hit on the “ENTER” key when prompted.

25

Select the first option “Zorin” and hit “ENTER” in your keyboard.

26

This should boot up your installed Zorin OS.

27

Enter your login credentials that you created earlier during the installation phase.

28

You should be able to see your home screen and the Z button which is similar to the start button in Windows based systems in the lower left corner. Clicking that should bring up the menu which is very classy in my opinion and easy for newbies who are migrating from Windows to Linux.

30

You can open up the terminal by simply searching terminal in the search box and it should bring up the terminal.

31

And here is the terminal!

32a

So Hurrayy!! You have successfully installed Zorin OS in Virtual Box !!

I just installed ZorinOS a few days back, and felt that it is a great OS especially for users who are migrating from Windows to Linux. I am still playing around with it and so far I must say it looks interesting. So go ahead, try it out and let me  know what you think. Feel free to leave a comment about it in the comments section below.

If you have any sort of queries on regarding this installation, just leave a comment below and will get back to you. Don’t forget to follow my blog to get future updates! :D

 
ΞXΤЯ3МΞ

This is a guide on how we can generate Stirling numbers using Python programming language.

Stirling Number S(n,k) :

A Stirling Number of the second kind, S(n, k), is the number of ways of splitting “n” items in “k” non-empty sets.

The formula used for calculating Stirling Number is:

S(n, k) = k* S(n-1, k) + S(n-1, k-1)

 
Example 1:

If you want to split a group of 3 items into 2 groups where {A, B, C} are the elements, and {Group 1} and {Group 2} are two groups, you can split them are follows:

{Group 1}                    {Group 2}

A, B                                    C

A                                        B, C

B                                        A, C

So, the number of ways of splitting 3 items into 2 groups = 3.

Therefore,  the Stirling number , S(3, 2) = 3

Example 2:

If you want to split a group of 5 elements into 2 groups where {A,B,C,D,E} are the items and {Group 1} and {Group 2} are two groups, it can be done in a total of 7 ways. So,

S(4, 2) = 7

Code:
This is the code that I have written to generate Stirling Numbers.

# Stirling Algorithm
# Cod3d by EXTR3ME
# https://extr3metech.wordpress.com

def stirling(n,k):
    n1=n
    k1=k
    if n<=0:
        return 1
    
    elif k<=0:
        return 0
    
    elif (n==0 and k==0):
        return -1
    
    elif n!=0 and n==k:
        return 1
    
    elif n<k:
        return 0

    else:
        temp1=stirling(n1-1,k1)
        temp1=k1*temp1
        return (k1*(stirling(n1-1,k1)))+stirling(n1-1,k1-1)

print   stirling(1,1)
# Output = 1

print stirling(5,2)
# Output  = 15

print stirling(5,3)
# Output  = 25

print stirling(5,4)
# Output  = 10

print stirling(5,5)
# Output  = 1

print stirling(20,15)
# Output  =  452329200

#print stirling(30,10)

# End of Code

Note: When the values of n and k are large , it will take longer to calculate. For example, I have hashed out print stirling(30, 10) , as it can take a while to calculate. You can always unhash it and test how long it takes to calculate in your computer. Feel free to leave any comments or feedback.

Hope this helps. You can always subscribe to my blog to get more updates! Happy Coding!

ΞXΤЯ3МΞ

Hey guys, been reading OpenCV for python and thought of posting a tutorial on Programming a Grayscale Image Convertor. I encourage you to google them , there are lots and lots of examples and code snippets. This is on how to a convert any image to gray scale using Python and OpenCV.

A sample input image and output image are shown below (YEah, I am big Iron Man Fan! :B). You can click on image to enlarge:

I have placed an image named “ironman.png” in the current working directory (i.e. I have the original image in the same directory as the  place where I have saved my Python code).

First we import the cv2 module:

import cv2

Then ,read the image to a variable named “image” :

image = cv2.imread('ironman.png')

Now, to convert to gray-scale image and store it to another variable named “gray_image” use the function cv2.cvtColor() with parameters as  the “image” variable and  “cv2.COLOR_BGR2GRAY” :

gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

So, now the variable “gray_image” will hold the gray-scale version of the input image.

Now, to write/save the converted gray-scale image to the hard disk, we use the function “cv2.imwrite()” with parameters as “the name of converted image” and the variable “gray_image” to which the converted image was stored:

cv2.imwrite('gray_image.png',gray_image)

So, now if you open the directory where you saved your python code, you can see a new image there : gray_image.png! Wow! 😀

Now, to display the original and the gray-scale ,we use function “cv2.imshow()” with parameters as the “window title” and the “image variable” :

cv2.imshow('color_image',image)             
cv2.imshow('gray_image',gray_image) 

Complete Code for GrayScale Image convertor:

# GrayScale Image Convertor
# https://extr3metech.wordpress.com

import cv2
image = cv2.imread('ironman.png')
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imwrite('gray_image.png',gray_image)
cv2.imshow('color_image',image)
cv2.imshow('gray_image',gray_image) 
cv2.waitKey(0)                 # Waits forever for user to press any key
cv2.destroyAllWindows()        # Closes displayed windows

#End of Code

 
Hope you enjoyed this post, feel free to comment and don’t forget to follow my blog! 😀
 
ΞXΤЯ3МΞ

There are many ways in which you can get help with commands. One way of getting help with a command is by using the “man” command which provides the manual page.

For example, if you want to know more about how to use the “cp” command, you can read its manual page by using the following command in the terminal:

# man cp

Another way is to use the “–help” command. This will give you a brief outline of the arguments that can used with the command.

For example, if want to find what all options or parameters can be used along with the command “mv” or remove command, you can use it by typing the following:

# mv –help

 

 ΞXΤЯ3МΞ

In the server side, we have to create a socket, Bind the socket to the address and port, and then set it to listening state and waits for the client to connect. When a client requests a connection, the server then accepts the connection.

Make sure you opened up two Python Shells (or Python IDLEs) so that you can run both the client and server.

This is a very basic program that sends a string of data from the server to the client and displays it to the client.

TCP SERVER

# TCP Server Code

host="127.0.0.1"			    # Set the server address to variable host
port=4446 				    # Sets the variable port to 4446
from socket import *	 		    # Imports socket module

s=socket(AF_INET, SOCK_STREAM)

s.bind((host,port))     		    # Binds the socket. Note that the input to
                                            # the bind function is a tuple

s.listen(1) 		        	    # Sets socket to listening state with a  queue
                                            # of 1 connection

print "Listening for connections.. "

q,addr=s.accept()			    # Accepts incoming request from client and returns
                                            # socket and address to variables q and addr

data=raw_input("Enter data to be send:  ")  # Data to be send is stored in variable data from
                                            # user

q.send(data) 		        	    # Sends data to client

s.close()

# End of code

 ___________________________________________________________________________________

TCP Client

In the TCP Client, we need to create the socket first, then connect to the server by using the socketname.connect((ipaddress,port)) . Then you need to receive the data which is send from the server, this is done by using the function socketname.recv(size)

# TCP Client Code

host="127.0.0.1" 			# Set the server address to variable host

port=4446 				# Sets the variable port to 4446

from socket import *			 # Imports socket module

s=socket(AF_INET, SOCK_STREAM)		# Creates a socket

s.connect((host,port))			# Connect to server address

msg=s.recv(1024)			# Receives data upto 1024 bytes and stores in variables msg

print "Message from server : " + msg

s.close()                            # Closes the socket
# End of code

Happy Coding!

CheerS!!

ΞXΤRΞМΞ-X