Skip to content

Tic-tac-toe: Beginning Python

I found a script I made back while trying to learn Python. It’s a pretty basic example of the game. It’s not much but might be useful for someone learning Python.

# PyTicTacToe

# Load the board
board = " 1 | 2 | 3\n-----------\n 4 | 5 | 6\n-----------\n 7 | 8 | 9"

# Set the winning combinations. Paired off in threes
# For example: 123 is a winning combo. So is 147.

# Set Space Holder

# movehandler function

# This function takes the players choice and makes sure it
# has not been used. If not, set the move.

def moveHandler(board,spaces,checkboard,player,n):
	# set X for player one, or O for player 2
	if player==1:
	# Check if block is used.
	while spaces.count(n)==0:
		print "\nInvalid Space"

	# Remove block from spaces array

	# Replace block with check mark in board

	# Replace space with check mark in checkboard array
	for c in range(len(checkboard)):
		if checkboard[c]==n:

	# Run the checkwinner function
	status = checkwinner(checkboard,check)

	return board,status

# Checkwinner function

# This function checks whether or not a player has a winning
# combination based on the checkboard array.

def checkwinner(checkboard,check):
	# Set the array element variables

	#Loop through checkboard to check winner
	while a<=21:
		combo = [checkboard[a],checkboard[b],checkboard[c]]

		# If we have three 'X' or 'O' we have a winner
		if combo.count(check) == 3:
			status =1
			status =0

	# Iterate to the next combo

# Return status of the game
	return status

def playerinput(player):
		key = int(raw_input('\n\nPlayer ' + str(player) + ': Please select a space '))
	except ValueError:
		print "Invalid Space"
		key = playerinput(player)

	return key

#Start Game
while True:
	player = len(spaces)%2 +1
	if player == 1:
		player = 2
		player =1

	print "\n\n" + board
	key = playerinput(player)
	board,status =moveHandler(board,spaces,checkboard,player,key)

	if status == 1:
		print '\n\nPlayer ' + str(player) + ' is the winner!!!'
		print board
	elif len(spaces)==0:
		print "No more spaces left. Game ends in a TIE!!!"
		print board

Posted in Code. Tagged with , .

Make Permanent Change to Terminal

My friend Nick was asking me how to customize the terminal which he was able to do. However, he was unable to keep the changes after he would restart his terminal. This is a little screencast that I did. He needs to edit his .bashrc and make permanent changes to the appropriate variable.

For optimal viewing, watch in fullscreen.

A special thanks to Nick also for working on a Droid app for

Posted in Tutorials. Tagged with , .

Check if current user is root

I have a script that mounts my campus network drive to my machine, but in order to mount successfully, I must have root/super user privileges and run the script as one. In order to do this, it is important to know that each user has a number assigned to it stored as UID. A superuser is assigned 0 and all others are positive integers. Seeing this in practice:

pjob@mario:~$ whoami
pjob@mario:~$ echo $EUID
pjob@mario:~$ su
mario:/home/pjob$ whoami
mario:/home/pjob$ echo $EUID

To accomplis the task if a user is root, all you need to do is check if the user id is 0. This would look like:

if [[ $EUID -ne 0 ]]; then
        echo "You must be a root user" 2>&1
        exit 1
        # Do something that requires root

Posted in Tutorials. Tagged with , , .

New Version of GradeMate Released!

After months of hard work by Mike, Jason, Alex, and countless users, the team has released a new version of GradeMate. Some of the new features they list on their blog are:

  1. Reporting tools for teachers and students
  2. Exporting and importing GradeMate courses and information
  3. Parent accounts and increased communication from Teacher <-> Parent <-> Student
  4. Blog pages, Project pages, and new, exciting ways to share and collaborate

GradeMate is free online organizer for teachers and students to keep track of homework, files, exams, and due dates. Currently there is no seed money but are willing to work with schools to provide a premium service. Get in touch with them at

Be sure to also check out other products from the members of  3Ten Design: Apokalips webcomic, image hosting, and Sabrstats!

Posted in Reviews. Tagged with , , .

Vectorize Your MATLAB

The first time I heard of vectorizing loops in MATLAB was in a Convection Heat Transfer class where the project required thousands of iterations before the system would converge. In order for this to happen in a timely matter, it was important to vectorize iterations where applicable.

The following example randomly places points at different locations. The first 1000 points are then changed to another location. Finally, there is a count to see how many points are less than .5.

Observe the two code snippets
First, using a ‘for’ and ‘if’ statement.


N = 1e6;    % Number of points
mol = zeros(N,1);
mol = rand(N,1);

for i = 1:N

    % Change first 1000 elements
    if i <= 1000
        mol(i) = 2*rand()-1;

    if mol(i) < .5
        count = count+1;

 % Print result
fprintf('Number of points < .5 = %f\n',count)


And now the vectorized version


N = 1e6;    % Number of points
mol = rand(N,1);

% Change first 1000 points
mol(1:1000) = 2*rand()-1;
% Check for points less than .5
count = sum (mol < .5 );   

 % Print result
fprintf('Number of points < .5 = %f\n',count)


The vectorized code besides using less number of lines will also run quicker. Observe also that there are no for nor if statements in the second code. It should be pretty easy to see where the vectorization comes into play. Be sure to leave a comment and perhaps show off your vectorized code.

Posted in Tutorials. Tagged with , , .

Solution to “cifs_mount failed w/return code = -22″

When trying to mount my network drive from campus at home I received the following message in dmesg:

CIFS VFS: cifs_mount failed w/return code = -22

Well it turns out that I needed to have the smbfs package installed. This quickly solved my problem.

sudo apt-get install smbfs

Posted in Solutions. Tagged with , .

Quick Remote Editing With Vim

I am sure that anyone who has created their own website has had to make simple edits. There are many ways that one may connect, edit, and then publish the changes and all of these ways accomplish the task at hand. I wish to show a quick and easy way to edit remote files using Vim.

user@local~$ vim ftp://hostip/

OK that’s it. Told you it was quick. Save and quit (:wq) and your file is updated and published.

There is a huge learning curve to Vim but I think that with time, you will find yourself being more efficient.

Posted in Tutorials. Tagged with , , .

Search Youtube in Totem

I never knew this, but you can search youtube videos through Totem. Watch the video below

Posted in Tutorials. Tagged with , , , .

March Madness on your Conky

March Madness is here and and what better way to keep track of the action than with a scoreboard tracker at the bottom of your screen. Check out the image below:

This is accomplished by combining a python script with the conky variable scroll. The python script will get the data, parse it and put it into a acceptable format for conky to handle the display. I’ve talked about conky earlier and using displaying the last instant message.

Copy the following code and save it as

import urllib
# Open html page
fweb = urllib.urlopen("")

# Manipulate str for unneccessary chars
raw=raw.replace('%20',' ');

# Open data storage
f=open('bottom.dat', 'w')
f=open('bottom.dat', 'r')

# Parse each line, get game, create str, append str
for line in f:
    if line.find('_left')>1:
        score= score + gamestr + '  |  '

print score

My conky script is as follows. Save this

#avoid flicker
double_buffer yes

#own window to run simultanious 2 or more conkys
own_window  yes
own_window_transparent no
own_window_type normal
own_window_hints undecorate,sticky,skip_taskbar,skip_pager, above

draw_borders no
border_margin 0

draw_shades no

gap_x 0
gap_y 0
alignment bottom_middle

update_interval 1

default_color  8f8f8f
#default_shade_color 000000
own_window_colour 262626

text_buffer_size 1400

use_xft yes
xftfont bauhaus:pixelsize=10

#to prevent window from moving
use_spacer none
minimum_size 1400

${color e0e0e0} ${scroll 2847 ${execpi 60 python ~/scripts/}}

Remember to edit your .conkyrc to run the right path to You may need to edit certain parameters for your screen resolution but this should give you a good start. Any questions, post a comment.
Pro Tip:To run multiple conky screens:”conky -c .conkyrc2″

Posted in Code, Conky, Linux, Ubuntu. Tagged with , , , .

How To: MPD/MPC with Ubuntu

For a few months now I wanted to try mpd mainly out of curiosity. Music Player Daemon (mpd) is a music server and mpc will be the client used to interact with the server. This how to will look at a localhost server of mpd.

Prereqs: Enable universal repositores in /etc/apt/sources.list

Installing & Configuring Software:
In terminal:

sudo apt-get install mpd mpc paprefs

Next we need to set up Pulse Audio.

Go to System->Preferences->Pulse Audio Preferences
Check “enable network access to local sound device” & “Don’t require authentication”

Set up mpd.conf (use your favorite text editor)

sudo gedit /etc/mpd.conf

Add the following to the config file:

audio_output {
type "pulse"
name "Local MPD Output"

In the mpd.conf file, look for “music_directory” and change the corresponding path to your music directory.

Next, we shall build the database. In terminal, type:

sudo mpd --create-db

Finally, restart mpd by:

sudo /etc/init.d/mpd restart

Using mpc: mpd/mpc is higly scriptable so I recommend create some bash files for yourself. You will find the manual to mpc here:

Example: Add Radiohead to current playlist

mpc search artist Radiohead | mpc add
mpc play

Good luck

Further Reading:

Posted in Tutorials, Ubuntu. Tagged with , , , , .