Skip to content

Instantly share code, notes, and snippets.

@flexchar
Created November 13, 2017 11:39
Show Gist options
  • Save flexchar/c0f282b6bbc61f0a34c28dcfd8b9e7da to your computer and use it in GitHub Desktop.
Save flexchar/c0f282b6bbc61f0a34c28dcfd8b9e7da to your computer and use it in GitHub Desktop.
Code dump for uni assignment `pip install mysqlclient, matplotlib`
print('\nBooting...\n');
# Import modules
import MySQLdb;
import matplotlib.pyplot as plt;
from math import pi;
def bye():
print("\nDone, shutting down...\n");
exit();
# Establish MySQL connection
try:
db_conn = MySQLdb.connect(
host = "localhost",
user = "root",
passwd = "",
db = "dev"
);
db = db_conn.cursor();
except MySQLdb.Error as e:
print("Error Establishing A Database Connection");
print("Error %d: %s" % (e.args[0], e.args[1])+"\n");
bye();
# Ask to Input userId
def inputUser(usersList=None):
global user;
if (usersList):
print('Available Users in the Database:');
print(*usersList, sep=', ');
try:
user = int(input("Enter User ID: "));
except ValueError:
print("You must enter digit");
inputUser(usersList);
except KeyboardInterrupt:
bye();
# Get list of users in the database
try:
db.execute("SELECT DISTINCT Answer_ID_User FROM answers");
users = db.fetchall();
newusers = [];
for u in users:
newusers.extend(u[0][0]);
newusers.sort();
inputUser(newusers);
except MySQLdb.Error as e:
print("Error fetching users list from database");
print("Error %d: %s" % (e.args[0], e.args[1])+"\n");
print("You may manually enter the userId, however there is no guarantee it will work");
print("\n(You may terminate execution with Ctrl+C)\n");
inputUser();
# Fetch data
try:
db.execute("SELECT * FROM answers WHERE Answer_ID_User ='"+ str(user) + "' ORDER BY Answer_Question");
data = db.fetchall();
if len(data) == 0:
print('\nFound no entries for this user.');
bye();
except MySQLdb.Error as e:
print("Error fetching records from database");
print("Error %d: %s" % (e.args[0], e.args[1])+"\n");
# Close DB connection
db.close();
db_conn.close();
# Question letter list in order respectively to questioniere
# Sequence important!
datalist = ['a','e','h','f','b','g','e','a',
'h','g','f','b','e','g','d','c',
'g','f','e','d','g','h','c','e',
'c','b','c','h','c','a','f','d',
'b','a','f','b','d','h','a','d'];
# Assing letters to questions, sequence here is important! used for calculation later
newdata = [];
for i in range(0, 40):
tmp = [];
tmp.extend(data[i]);
tmp.extend(datalist[i]);
tmp.pop(0) #Remove indexId
tmp.pop(0) #Remove userId
newdata.append(tmp);
# Calculate Points
# Using lettersAsInt'eger, 'cause Python doesn't support strings as key in arrays
# following sequence is important and directly represents the letter in letters array
# A as 1, B as 2 <...> G as 7 and H as 8
lettersAsInt = [1,2,3,4,5,6,7,8];
letters = ['a','b','c','d','e','f','g','h'];
# The sequence of [thinking] ways also depend on letters.
ways = ['Enthusiastic','Practical','Imaginative','Logical','Auditive','Visual','Kinestetic \n(Emotional)','Kinestetic \n(Touching)'];
for row in newdata:
# the line below, well, it's nice one
# row[2] returns letter of the question
# letters.index(row[2]) returns the int for where that letter stands
# lettersAsInt adds points from row[1] to total list using that int
lettersAsInt[letters.index(row[2])] += row[1];
# Adjust points
for i in range(0,8):
lettersAsInt[i] = (lettersAsInt[i]-5)*5;
# Paint image
def paintImage(cat, values):
N = len(cat)
x_as = [n / float(N) * 2 * pi for n in range(N)]
# Because our chart will be circular we need to append a copy of the first
# value of each list at the end of each list with data
values += values[:1]
x_as += x_as[:1]
# Set color of axes
plt.rc('axes', linewidth=0.5, edgecolor="#888888")
# Create polar plot
ax = plt.subplot(111, polar=True)
# Set clockwise rotation. That is:
ax.set_theta_offset(pi / 2)
ax.set_theta_direction(-1)
# Set position of y-labels
ax.set_rlabel_position(0)
# Set color and linestyle of grid
ax.xaxis.grid(True, color="#888888", linestyle='solid', linewidth=0.5)
ax.yaxis.grid(True, color="#888888", linestyle='solid', linewidth=0.5)
# Set number of radial axes and remove labels
plt.xticks(x_as[:-1], [])
# Set yticks
plt.yticks([20, 40, 60, 80, 100], ["20", "40", "60", "80", "100"])
# Plot data
ax.plot(x_as, values, linewidth=0, linestyle='solid', zorder=3)
# Fill area
ax.fill(x_as, values, 'b', alpha=0.3)
# Set axes limits
plt.ylim(0, 100)
# Draw ytick labels to make sure they fit properly
for i in range(N):
angle_rad = i / float(N) * 2 * pi
if angle_rad == 0:
ha, distance_ax = "center", 10
elif 0 < angle_rad < pi:
ha, distance_ax = "left", 1
elif angle_rad == pi:
ha, distance_ax = "center", 1
else:
ha, distance_ax = "right", 1
ax.text(angle_rad, 100 + distance_ax, cat[i], size=10, horizontalalignment=ha, verticalalignment="center")
# Show polar plot
plt.show()
paintImage(ways,lettersAsInt);
# Inform about completed excecution
bye();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment