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.

#!/usr/bin/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.
checkboard=[1,2,3,4,5,6,7,8,9,1,4,7,2,5,8,3,6,9,1,5,9,3,5,7]

# Set Space Holder
spaces=range(1,10)

# 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="X"
	else:
		check="O"
	# Check if block is used.
	while spaces.count(n)==0:
		print "\nInvalid Space"
		n=playerinput(player)

	# Remove block from spaces array
	spaces=spaces.remove(n)

	# Replace block with check mark in board
	board=board.replace(str(n),check)

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

	# 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
	a,b,c=0,1,2

	#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
			break
		else:
			status =0

	# Iterate to the next combo
		a+=3
		b+=3
		c+=3

# Return status of the game
	return status

#
def playerinput(player):
	try:
		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
	else:
		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
		break
	elif len(spaces)==0:
		print "No more spaces left. Game ends in a TIE!!!"
		print board
		break
	else:
		continue

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 obdit.com

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
pjob@mario:~$ echo $EUID
1000
pjob@mario:~$ su
Password:
mario:/home/pjob$ whoami
root
mario:/home/pjob$ echo $EUID
0

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
else
        # Do something that requires root
fi

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 info@mygrademate.com

Be sure to also check out other products from the members of  3Ten Design: Apokalips webcomic, img2.me 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.

tic;
clear;

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;
    end

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

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

toc;

And now the vectorized version

tic;
clear;

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)

toc;

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/file.py

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 bottomscore.py

#!/usr/bin/python
import urllib
# Open html page
fweb = urllib.urlopen("http://scores.espn.go.com/ncb/bottomline/scores")

gamestr=''
score=''
# Manipulate str for unneccessary chars
raw=str(fweb.readline())
raw=raw.replace('%20',' ');
raw=raw.replace('^','');
raw=raw.replace('&','\n')

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

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

f.close()
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

#borders
draw_borders no
border_margin 0

#shades
draw_shades no

#position
gap_x 0
gap_y 0
alignment bottom_middle

#behaviour
update_interval 1

#colour
default_color  8f8f8f
#default_shade_color 000000
own_window_colour 262626

text_buffer_size 1400

#font
use_xft yes
xftfont bauhaus:pixelsize=10

#to prevent window from moving
use_spacer none
minimum_size 1400

TEXT
${color e0e0e0} ${scroll 2847 ${execpi 60 python ~/scripts/bottomscore.py}}

Remember to edit your .conkyrc to run the right path to bottomscore.py. 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: http://linux.die.net/man/1/mpc

Example: Add Radiohead to current playlist

mpc search artist Radiohead | mpc add
mpc play

Good luck

Further Reading:
http://mpd.wikia.com/wiki/What_MPD_Is_and_Is_Not
http://mpd.wikia.com/wiki/Hacks

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