January 2013
2 posts
2 tags
Grabbing all of the links to a Youtube Playlist in...
My friend Jesse wanted a way to grab all of the links to videos on a YouTube playlist. That’s no problem. I can easily cycle through links and spit them out into an HTML page.
There’s just one bug that I can’t seem to fix. Each and every link in the output goes to Rick Astley - Never Gonna Give You Up. I guess some bugs were never meant to be solved.
2 tags
Mandelbrot Set in Matlab
I wanted to see if I could create a Mandelbrot Fractal image in Matlab. After quickly looking at the Mandelbrot Set entry on Wikipedia, I coded up the following and ran it:
I’m kinda surprised that it took so little code to create the image. I’m pleased with the results.
September 2012
1 post
1 tag
Finding a 3D Rotation Matrix for two vectors in...
Update: The formulation of the input has been updated to allow two matrices of 3 by n column vectors and return a 3 by 3 by n matrix of rotation matrices.
Here’s the problem:
I have a 3 by 1 vector and I need to know the rotation matrix to manipulate that vector to another 3 by 1 vector.
Let’s call the first vector ‘u’ and the second vector ‘v’. I’m...
August 2012
1 post
1 tag
Solving Many, Many 3 by 3 Eigenvalue Problems...
My research is requiring me to solve many, many small eigenvalue problems, all of which are 3 by 3 matrices. Rather than use the built-in “eig” function, I wrote my own.
June 2012
1 post
1 tag
Determining the Circumcircles of a list of...
Imagine that we have a set of two dimensional points scattered across a space. For each point, the X coordinates are in variable X, and the Y coordinates are in variable Y. We can passed these coordiantes into the “delaunay” function and get “TRI”, which is a list of triangles. We can view the triangle mesh of the Delaunay triangulation by passing it to the MATLAB function...
March 2012
1 post
1 tag
Distance from point to the nearest point along a...
December 2011
2 posts
4 tags
Examining Exit Codes of 4 simple programs with...
Strict type checking is an aspect of the compiler to make sure that your programs have properly declared all of the necessary variable names prior to their use. I believe it is essential to all modern languages to implement proper errors in the event that an undefined variable is used. Let’s look at 4 popular scripting languages to see how they handle this problem.
For each program, we...
1 tag
Top 10 List for Categorical Data in MySQL
Let’s say that you have a table with some categorical data. You want to make a Top 10 list of the most frequently visited categories. Here is an example table:
In this case, we have a table called “example” with one column called “label”. This is a bad example, in that it only has 10 items in the whole table.
mysql> SELECT * FROM example;
+-------+
| label...
October 2011
1 post
1 tag
Linear Regression in Matlab
June 2011
1 post
1 tag
Determining if a graph is connected in Matlab
I needed a quick script to tell me if a graph was connected or not. My adviser usually tells me “MATLAB has everything!” No, it doesn’t, and that’s why we need to write simple code like this just to get more complicated jobs done.
Since I haven’t posted in a while, let’s do another script. This one will determine if a graph is symmetrical, which is another...
May 2011
1 post
1 tag
Rotating Points around 3 axes in Matlab
I wrote this based on the content found on the Wikipedia page for Rotation Matrix and it worked on the first try. I fell like I need a victory lap.
April 2011
2 posts
1 tag
Simplified Plotting (At least for me) in Matlab
Graph plotting in Matlab is rich with features that allow the user to create fantastic, beautiful plots. The downside to all of this is that when the user wants to create something simple, they must first return to the Matlab manuals.
I don’t care for any of this. I want to create simple 2D and 3D plots and I don’t really care about the current shape of the vector used in my...
1 tag
Solving the Monty Hall Problem with a Monte Carlo...
March 2011
2 posts
2 tags
mpipypi.py - Computing Pi using MPI Python...
1 tag
Dijkstra's Algorithm in Matlab
February 2011
1 post
1 tag
Splitting Pages of a PDF in Python
For the past month, I’ve programmed in nothing but Matlab. Kinda sad, because I don’t even care for Matlab. I prefer Python.
I was going through a store called Tuesday Morning to look at the stuff for sale. It’s a bit of a junk store. They had a DVD for sale containing every Fantastic Four comic book on PDF from 1961 to 2004 for only $15. Being a comic fan, I had to get it.
...
January 2011
5 posts
My O'Reilly Wish List
O’Reilly is currently holding a $500 giveaway. My entry form is a blog about the books, ebooks, and videos that I would purchase with $500. Beside every title is the dollar value of the product rounded up to the nearest dollar. After rounding, my wishlist totals $499. I think I hit the mark pretty close.
Paperback Books:
The Definitive ANTLR Reference - 37
Language Implementation Patterns...
1 tag
3D Visualization of an Adjacency Matrix in Matlab
An adjacency matrix is a data model to represent an undirected graph. Most adjacency matrices are two dimensional, which means you can use the built-in Matlab function “gplot” to visualize it. This function “gplot3” allows you to visualize adjacency matrices in 3D.
I created the above demonstration using Matlab’s built in Bucky Ball creator.
» [B XY] = bucky;
»...
1 tag
A Slinky in Matlab
I made this because I need to learn about 3D graphics, but I’m too lazy to learn Blender. This was made with 1 line of Matlab.
>> x = linspace(0, 200*pi, 10000); y = sin(x/100)+sin(x); z = cos(x); plot3(x, y, z)
1 tag
Comparing Stock Volatility Using R
In my last post, I wrote a quick Python script to download 1 years worth of a stock’s history into a CSV file for given a list of stocks. Today, we are going to take those stocks an compare the volatility between each stock’s daily price change.
Measuring volatility is a simple calculation of the standard deviation of the percentage of the stock’s price change over a given year....
1 tag
Downloading Stock Market Data via Yahoo using...
"""
In my spare time, I'm an investor. I figure I should
should use my powers in math and computer science and
help build for myself a better future.
This program will download the past year's stock
history for a list of ticker symbols defined by the
'symbols' list variable. Each stock's data will be
downloaded to your computer into a CSV file, which
can easily be viewed with Microsoft...
December 2010
3 posts
1 tag
Ulam Spiral in Processing
/*
So I found the YouTube Channel of ViHart. She's got these
quirky, awesome math videos involving lots of doodles.
Her most recent video is on the Ulam Spiral, so I thought
I would try to recreate it in processing.
Enjoy. Here's the video of her drawing.
http://www.youtube.com/watch?v=Yhlv5Aeuo_k
*/
void setup() {
size(400, 400);
background(255);
}
void draw() {
int cy = height...
1 tag
Reading OBJ files in MATLAB
% Not the most exciting code that I've written recently.
% Can you tell that it's finals week and I'm a little busy?
% readobj
% Reads the obj file format.
function [v, vt, vn, f] = readobj(filename)
fid = fopen(filename, 'r');
vcount = 0;
vtcount = 0;
vncount = 0;
fcount = 0;
v = [];
vt = [];
vn = [];
f = [];
% Iterate through each line of the OBJ file.
while ~feof(fid)
line =...
1 tag
Simple Animations in Python
from graphics import *
import time
"""
In the CS 141 class that I teach at Rhodes College we
use a simple graphics library written by Dr. John Zelle
to demonstrate basic object oriented programming topics.
My assignment to the class was to use the graphics library
to tell a simple story. This program tells the story
of a frog sitting on a lily pad made of gold coins (I'm
not sure why I put in...
November 2010
10 posts
1 tag
Run Length Encoding using Lisp
;; This is my first attempt at any Lisp programming.
;; Lisp programming has a long tradition, so I'm sure
;; some things could be better in this program.
;;
;; My goal was to write something in Lisp, so I wrote
;; Run Length Encoding.
;;
;; -James
;; drop - drops the first n elements in a list
;; The same function exists in Haskell.
(defun drop (mylist n)
(if (eq n 0)
mylist
...
1 tag
Eyeballs that Follow Your Cursor in Processing
void setup() {
size(400, 400);
background(204);
}
void draw() {
drawTwoEyesLookingAtMouse(200, 200);
}
void drawTwoEyesLookingAtMouse(int cx, int cy) {
int eye_y = 200;
int left_eye_x = cx - 70;
int right_eye_x = cx + 70;
drawEyeLookingAtMouse(left_eye_x, eye_y);
drawEyeLookingAtMouse(right_eye_x, eye_y);
}
void drawEyeLookingAtMouse(int cx, int cy) {
int...
1 tag
Adding Two Numbers in a Java Swing GUI
/**
* Last Friday I was approached in my office by our
* CS Department's Head Lab Assistant and the TA
* responsible for teaching our Java 3 course.
*
* The Head Lab Assistant told me that the TA (standing
* right beside her) was sick and unable to teach.
* Someone needed to fill in the course for him.
* I'm the fall back up guy for these kinds of emergencies,
* so it fell to me to teach...
1 tag
Stripping Non-printable Characters out of a File...
#include <stdio.h>
/*
* I had a PDF document that I needed to post
* onto a Wiki, so I used a tool called
* pdftotext to convert the PDF into text.
*
* The pdftotext converter converted several
* of the characters to unprintable onces.
* The characters don't show up when you read
* the file, but they still exist. This was
* creating problems for the Wiki I was using.
*
* I needed...
1 tag
Filtering a BibTeX file by terms used in the...
import sys
import re
"""
Author: James Church
Date: November 16, 2010
Filename: filterByKeyword.py
This program will gather up all of the citations in a BibTeX
file that share a keyword passed to it on the command line.
For example, say you have a list of citations in a file
"docs.bib", but some docs are tagged with the keyword
"ants" and other are tagged with the keyword "beetles".
Let's get a...
1 tag
Simple Heap Data Structure in Ruby
class Heap
# Initialize our Heap
# To use: my_heap = Heap.new
def initialize
@storage = Array.new
end
# Test if the Heap is empty.
# To use: my_heap.empty?
def empty?
return @storage.length == 0
end
# Insert an item into the Heap
# Increases the size of the Heap by 1
# To use: my_heap.insert(item)
def insert(item)
@storage...
1 tag
Computing the First 20 Fibonacci Numbers in Erlang
#!/usr/bin/env escript
fib(0) -> 0;
fib(1) -> 1;
fib(N) -> fib(N-1) + fib(N-2).
print_list([H|T]) -> io:format("~p~n", [H]),
print_list(T);
print_list([]) -> true.
main(_) ->
print_list( [ fib(X) || X <- lists:seq(1,20) ] ).
1 tag
Floyd's Algorithm in C++
/* Floyd's Shortest Distance Algorithm
This function takes an adjacency matrix as input.
Then the algorithm modifies the cells in the adjacency matrix
so that all of the edge placements are replaced with the shortest
distance to that edge.
The internal "graph" structure is overwritten, so you'd better
make a copy!
*/
void floyds(int **graph, int size) {
for (int k = 0; k...
1 tag
1 tag
The Coin Change Problem in Python
def coin_change(amount, denominations, collection=[]):
"""
Given an amount of money and some coin denominations, this
function prints every combination of coins needed to express
the desired amount using the input denominations.
amount - an amount, in the smallest unit.
denominations - a list of coin denominations, from largest to smallest.
"""
for coin in...
October 2010
10 posts
1 tag
Swapping Pointers to Pointers to Values in C
#include <stdio.h>
// Imagine that we need to swap the values contained in two pointers.
// This requires a pointer to a pointer to a value in C.
void swap_pointers(int **a, int **b) {
int temp = **a;
**a = **b;
**b = temp;
}
// This function takes two values passed pointer.
// It takes those two pointers and passes them to swap_pointers
void print_but_swap_later(int *a, int...
1 tag
Newton's Method in Python
def sqrt(n):
"""
This method calculates the square root
of a value using Newton's method to an
accuracy of within sigma.
"""
sigma = 0.0001
# The first guess is n / 2
# (which only works when n is 4)
guess = n / 2
while abs(n - guess * guess) > sigma:
# Compute the quotient
quotient = n / guess
# Average the quotient and the...
1 tag
Estimating Pi with the Pythagorean Theorem and...
import random
def main():
TOTAL_PECKS = 100000
hits = 0
i = 0
while i < TOTAL_PECKS:
x = random.random() * 2 - 1
y = random.random() * 2 - 1
if x * x + y * y <= 1:
hits += 1
i += 1
pi = 4.0 * float(hits) / TOTAL_PECKS
print "Estimate Pi:", pi
main()
1 tag
1 tag
1 tag
Rabin-Miller in Python
import random
import sys
def isProbablyPrime(n, k=5):
"""
This algorithm computes if 'n' is probably prime
through a series of 'k' trials using Rabin-Miller. Set k to
be something reasonable, like 5.
http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
"""
if n%2 == 0:
return False
d = n - 1
s = 0
while d % 2 == 0:
d /= 2
...
1 tag
SVD in Ruby →
1 tag
Knowledge of Religion →
It’s a quick pop quiz you can take to measure basic facts of major religions.
2 tags
1 tag
Data Analysis with Gawk and Histo →
September 2010
4 posts
1 tag
1 tag
Finding all of the permutations of a sequence...
def permutations(seq):
if len(seq) == 1:
return [seq]
i = 0
perms = []
while i < len(seq):
elem = seq.pop(i)
latter_perms = permutations(seq)
for perm in latter_perms:
perms.append([elem] + perm)
seq.insert(i, elem)
i += 1
return perms
1 tag
1 tag
The digital divide becomes more painfully apparent, as newsroom cutbacks mean...
– Samantha Yeargin (via kleinheider)