<commit_before>from PyQt4 import QtCore, QtGui

import ReactionMaker.inversion as inversion
import ReactionMaker.duplicate as duplicate
import ReactionMaker.increment as increment
import ReactionMaker.decrement as decrement
import ReactionMaker.multiply as multiply
import ReactionMaker.logarithm as logarithm
import ReactionMaker.power as power

import Simulator.XMLParser as XMLParser
import Simulator.plot as plot

from ExpressionSolver.solver import *

def getHistoryFileName(xmlFileName):
	y = xmlFileName[:-3]
	return 'history_' + y + 'txt'

class MainWindow(QtGui.QMainWindow):

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.central_widget = QtGui.QStackedWidget()
        self.setCentralWidget(self.central_widget)
        self.addWidgets()

    def addWidgets(self):
		mainMenu=self.menuBar()
		mainMenu.setNativeMenuBar(False)

		# Creating main menus of GUI
		examples=mainMenu.addMenu('Examples')
		simulate= mainMenu.addMenu('Simulate')

		# Creating sub menus of examples menu
		examples.addAction("Basic Examples")
		examples.addAction("Advanced Examples")
		examples.triggered[QtGui.QAction].connect(self.exampletrigger)

		# Creating sub menus of simulate menu
		simulate.addAction("Import XML")
		simulate.addAction("Import txt")
		simulate.addAction("Expression Solver")
		simulate.triggered[QtGui.QAction].connect(self.simulatetrigger)

		# Adding main welcome widget to the screen
		welcome_widget = WelcomeScreen(self)
		self.central_widget.addWidget(welcome_widget)
		self.central_widget.setCurrentWidget(welcome_widget)

 	# Function for executuing any sub menu choosen from examples menu
    def exampletrigger(self,q):
	    if q.text() == "Basic Examples":
			print q.text()
			basic_widget = BasicWidget(self)
			self.central_widget.addWidget(basic_widget)
			self.central_widget.setCurrentWidget(basic_widget)
	    else:
			print q.text()
			advanced_widget = AdvancedWidget(self)
			self.central_widget.addWidget(advanced_widget)
			self.central_widget.setCurrentWidget(advanced_widget)

	# Function for executuing any sub menu choosen from simulate menu
    def simulatetrigger(self,q):
		if q.text() =="Expression Solver":

			expression, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter Expression :')

			if ok:
				expression=str(expression)
				expression=expression.replace(" ","")
				op_out = []    #This holds the operators that are found in the string (left to right)
				num_out = []   #this holds the non-operators that are found in the string (left to right)
				operators = set('+-*/')
				buff = []
				for c in expression:  #examine 1 character at a time
				    if c in operators:
				        #found an operator.  Everything we've accumulated in `buff` is
				        #a single "number". Join it together and put it in `num_out`.
				        num_out.append(''.join(buff))
				        buff = []
				        op_out.append(c)
				    else:
				        #not an operator.  Just accumulate this character in buff.
				        buff.append(c)
				num_out.append(''.join(buff))
				af=[]
				for i in range(0,len(num_out)):
					af.append(num_out[i])
					if i==len(num_out)-1:
						break
					af.append(op_out[i])
				for i in range(0,len(af)):
				    if i==0:
				        solver = Solver(int(af[i]))
				    else:
				        if af[i]=="+":
				            solver.add(int(af[i+1]))
				        elif af[i]=="*":
				            solver.multiply(int(af[i+1]))

				solver.printTxt('expression.txt')
				print 'Expression.txt created'
			else:
				return

		if q.text() == "Import XML":
			fname = QtGui.QFileDialog.getOpenFileName(self, 'Select XML to Import','/home')
			print fname
		elif q.text() == "Import txt":
			fname = QtGui.QFileDialog.getOpenFileName(self, 'Select Text file to simulate','/home')
			print fname
		else:
			fname = "expression.txt"

		if q.text() != "Expression Solver":
			simulationtime, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter Simulation time:')
		else:
			simulationtime = solver.getEstimatedTimeForCompletion()
			ok = True

		if ok:
			print simulationtime
		else:
			return

		if q.text() != "Expression Solver":
			reactantslist, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter Reactants to be plotted seperated by , for eg A,B,C')
			if ok:
				if "," in str(reactantslist):
					reactantslist = str(reactantslist)
					reactantslist = reactantslist.split(",")
					print reactantslist
				else:
					c=[]
					c.append(str(reactantslist))
					reactantslist = c
					print reactantslist
			else:
				return
		else:
			reactantslist = solver.getListOfReactionsToPlot()

		if q.text() == "Import XML":
			print "Plotting From XML File"
			plot.plotFromXML(fname,int(simulationtime),reactantslist)
		else:
			print "Plotting From Text File"
			plot.plotFromTxt(fname,int(simulationtime),reactantslist)

class WelcomeScreen(QtGui.QWidget):
    def __init__(self,parent=None):
		super(WelcomeScreen,self).__init__(parent)
		layout=QtGui.QHBoxLayout()
		self.label=QtGui.QLabel('WELCOME!')
		layout.addWidget(self.label)
		self.setLayout(layout)

class BasicWidget(QtGui.QWidget):
    def __init__(self, parent=None):
		super(BasicWidget, self).__init__(parent)
		layout = QtGui.QHBoxLayout()

		self.inversion = QtGui.QPushButton('1) Inversion')
		layout.addWidget(self.inversion)

		self.duplication = QtGui.QPushButton('2) Duplication/Copy')
		layout.addWidget(self.duplication)

		self.decrementation = QtGui.QPushButton('3) Decrementation')
		layout.addWidget(self.decrementation)

		self.incrementation = QtGui.QPushButton('4) Incrementation')
		layout.addWidget(self.incrementation)

		self.setLayout(layout)

		self.inversion.clicked.connect(self.dinversion)
		self.duplication.clicked.connect(self.dduplication)
		self.decrementation.clicked.connect(self.ddecrementation)
		self.incrementation.clicked.connect(self.dincrementation)

    def dinversion(self):
		print "Inversion"

		X, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter value you want to invert')

		if ok:
			print X
		else:
			return

		outputFileName,chemicalList = inversion.execute(X)

		print 'Result File ' + outputFileName + ' Created'

		timeOfSimulation, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter Time Of Simulation')

		if ok:
			print timeOfSimulation
		else:
			return

		sim = XMLParser.getSimulator(outputFileName)
		sim.simulate(int(timeOfSimulation),getHistoryFileName(outputFileName))
		sim.plot(chemicalList)

    def dduplication(self):
		print "Duplicate"

		X, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter value you want to duplicate')

		if ok:
			print X
		else:
			return

		outputFileName,chemicalList = duplicate.execute(X)

		print 'Result File ' + outputFileName + ' Created'

		timeOfSimulation, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter Time Of Simulation')

		if ok:
			print timeOfSimulation
		else:
			return

		sim = XMLParser.getSimulator(outputFileName)
		sim.simulate(int(timeOfSimulation),getHistoryFileName(outputFileName))
		sim.plot(chemicalList)

    def ddecrementation(self):
		print "Decrement"

		X, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter value you want to decrement 1 from')

		if ok:
			print X
		else:
			return

		outputFileName,chemicalList = decrement.execute(X)

		print 'Result File ' + outputFileName + ' Created'

		timeOfSimulation, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter Time Of Simulation')

		if ok:
			print timeOfSimulation
		else:
			return

		sim = XMLParser.getSimulator(outputFileName)
		sim.simulate(int(timeOfSimulation),getHistoryFileName(outputFileName))
		sim.plot(chemicalList)

    def dincrementation(self):
		print "Increment"

		X, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter value you want to increment 1 to')

		if ok:
			print X
		else:
			return

		outputFileName,chemicalList = increment.execute(X)

		print 'Result File ' + outputFileName + ' Created'

		timeOfSimulation, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter Time Of Simulation')

		if ok:
			print timeOfSimulation
		else:
			return

		sim = XMLParser.getSimulator(outputFileName)
		sim.simulate(int(timeOfSimulation),getHistoryFileName(outputFileName))
		sim.plot(chemicalList)

class AdvancedWidget(QtGui.QWidget):
    def __init__(self, parent=None):
		super(AdvancedWidget, self).__init__(parent)
		layout = QtGui.QHBoxLayout()

		self.multiplication = QtGui.QPushButton('1) Multiplication')
		layout.addWidget(self.multiplication)

		self.logarithm = QtGui.QPushButton('2) Logarithm')
		layout.addWidget(self.logarithm)

		self.power = QtGui.QPushButton('3) Power')
		layout.addWidget(self.power)

		self.setLayout(layout)

		self.multiplication.clicked.connect(self.dmultiplication)
		self.logarithm.clicked.connect(self.dlogarithm)
		self.power.clicked.connect(self.dpower)

    def dmultiplication(self):
		print "Multiplication"

		X, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter first value you want to multiply')

		if ok:
			print X
		else:
			return

		Y, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter second value you want to multiply')

		if ok:
			print Y
		else:
			return

		outputFileName,chemicalList = multiply.execute(X,Y)

		print 'Result File ' + outputFileName + ' Created'

		timeOfSimulation, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter Time Of Simulation')

		if ok:
			print timeOfSimulation
		else:
			return

		sim = XMLParser.getSimulator(outputFileName)
		sim.simulate(int(timeOfSimulation),getHistoryFileName(outputFileName))
		sim.plot(chemicalList)

    def dlogarithm(self):
		print "Ceiling of logarithm"

		X, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter value you want to take ceiling logarithm of')

		if ok:
			print X
		else:
			return

		outputFileName,chemicalList = logarithm.execute(X)

		print 'Result File ' + outputFileName + ' Created'

		timeOfSimulation, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter Time Of Simulation')

		if ok:
			print timeOfSimulation
		else:
			return

		sim = XMLParser.getSimulator(outputFileName)
		sim.simulate(int(timeOfSimulation),getHistoryFileName(outputFileName))
		sim.plot(chemicalList)

    def dpower(self):
		print "Power"

		X, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter value of base')

		if ok:
			print X
		else:
			return

		Y, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter vaue of exponent')

		if ok:
			print Y
		else:
			return

		outputFileName,chemicalList = multiply.execute(X,Y)

		print 'Result File ' + outputFileName + ' Created'

		timeOfSimulation, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter Time Of Simulation')

		if ok:
			print timeOfSimulation
		else:
			return

		sim = XMLParser.getSimulator(outputFileName)
		sim.simulate(int(timeOfSimulation),getHistoryFileName(outputFileName))
		sim.plot(chemicalList)

app = QtGui.QApplication([])
window = MainWindow()
window.show()
app.exec_()

<commit_msg>Resolve confict of two modules with same name 'multiply'<commit_after>from PyQt4 import QtCore, QtGui

import ReactionMaker.inversion as inversion
import ReactionMaker.duplicate as duplicate
import ReactionMaker.increment as increment
import ReactionMaker.decrement as decrement
import ReactionMaker.multiply as multiply1
import ReactionMaker.logarithm as logarithm
import ReactionMaker.power as power

import Simulator.XMLParser as XMLParser
import Simulator.plot as plot

from ExpressionSolver.solver import *

def getHistoryFileName(xmlFileName):
	y = xmlFileName[:-3]
	return 'history_' + y + 'txt'

class MainWindow(QtGui.QMainWindow):

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.central_widget = QtGui.QStackedWidget()
        self.setCentralWidget(self.central_widget)
        self.addWidgets()

    def addWidgets(self):
		mainMenu=self.menuBar()
		mainMenu.setNativeMenuBar(False)

		# Creating main menus of GUI
		examples=mainMenu.addMenu('Examples')
		simulate= mainMenu.addMenu('Simulate')

		# Creating sub menus of examples menu
		examples.addAction("Basic Examples")
		examples.addAction("Advanced Examples")
		examples.triggered[QtGui.QAction].connect(self.exampletrigger)

		# Creating sub menus of simulate menu
		simulate.addAction("Import XML")
		simulate.addAction("Import txt")
		simulate.addAction("Expression Solver")
		simulate.triggered[QtGui.QAction].connect(self.simulatetrigger)

		# Adding main welcome widget to the screen
		welcome_widget = WelcomeScreen(self)
		self.central_widget.addWidget(welcome_widget)
		self.central_widget.setCurrentWidget(welcome_widget)

 	# Function for executuing any sub menu choosen from examples menu
    def exampletrigger(self,q):
	    if q.text() == "Basic Examples":
			print q.text()
			basic_widget = BasicWidget(self)
			self.central_widget.addWidget(basic_widget)
			self.central_widget.setCurrentWidget(basic_widget)
	    else:
			print q.text()
			advanced_widget = AdvancedWidget(self)
			self.central_widget.addWidget(advanced_widget)
			self.central_widget.setCurrentWidget(advanced_widget)

	# Function for executuing any sub menu choosen from simulate menu
    def simulatetrigger(self,q):
		if q.text() =="Expression Solver":

			expression, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter Expression :')

			if ok:
				expression=str(expression)
				expression=expression.replace(" ","")
				op_out = []    #This holds the operators that are found in the string (left to right)
				num_out = []   #this holds the non-operators that are found in the string (left to right)
				operators = set('+-*/')
				buff = []
				for c in expression:  #examine 1 character at a time
				    if c in operators:
				        #found an operator.  Everything we've accumulated in `buff` is
				        #a single "number". Join it together and put it in `num_out`.
				        num_out.append(''.join(buff))
				        buff = []
				        op_out.append(c)
				    else:
				        #not an operator.  Just accumulate this character in buff.
				        buff.append(c)
				num_out.append(''.join(buff))
				af=[]
				for i in range(0,len(num_out)):
					af.append(num_out[i])
					if i==len(num_out)-1:
						break
					af.append(op_out[i])
				for i in range(0,len(af)):
				    if i==0:
				        solver = Solver(int(af[i]))
				    else:
				        if af[i]=="+":
				            solver.add(int(af[i+1]))
				        elif af[i]=="*":
				            solver.multiply(int(af[i+1]))

				solver.printTxt('expression.txt')
				print 'Expression.txt created'
			else:
				return

		if q.text() == "Import XML":
			fname = QtGui.QFileDialog.getOpenFileName(self, 'Select XML to Import','/home')
			print fname
		elif q.text() == "Import txt":
			fname = QtGui.QFileDialog.getOpenFileName(self, 'Select Text file to simulate','/home')
			print fname
		else:
			fname = "expression.txt"

		if q.text() != "Expression Solver":
			simulationtime, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter Simulation time:')
		else:
			simulationtime = solver.getEstimatedTimeForCompletion()
			ok = True

		if ok:
			print simulationtime
		else:
			return

		if q.text() != "Expression Solver":
			reactantslist, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter Reactants to be plotted seperated by , for eg A,B,C')
			if ok:
				if "," in str(reactantslist):
					reactantslist = str(reactantslist)
					reactantslist = reactantslist.split(",")
					print reactantslist
				else:
					c=[]
					c.append(str(reactantslist))
					reactantslist = c
					print reactantslist
			else:
				return
		else:
			reactantslist = solver.getListOfReactionsToPlot()

		if q.text() == "Import XML":
			print "Plotting From XML File"
			plot.plotFromXML(fname,int(simulationtime),reactantslist)
		else:
			print "Plotting From Text File"
			plot.plotFromTxt(fname,int(simulationtime),reactantslist)

class WelcomeScreen(QtGui.QWidget):
    def __init__(self,parent=None):
		super(WelcomeScreen,self).__init__(parent)
		layout=QtGui.QHBoxLayout()
		self.label=QtGui.QLabel('WELCOME!')
		layout.addWidget(self.label)
		self.setLayout(layout)

class BasicWidget(QtGui.QWidget):
    def __init__(self, parent=None):
		super(BasicWidget, self).__init__(parent)
		layout = QtGui.QHBoxLayout()

		self.inversion = QtGui.QPushButton('1) Inversion')
		layout.addWidget(self.inversion)

		self.duplication = QtGui.QPushButton('2) Duplication/Copy')
		layout.addWidget(self.duplication)

		self.decrementation = QtGui.QPushButton('3) Decrementation')
		layout.addWidget(self.decrementation)

		self.incrementation = QtGui.QPushButton('4) Incrementation')
		layout.addWidget(self.incrementation)

		self.setLayout(layout)

		self.inversion.clicked.connect(self.dinversion)
		self.duplication.clicked.connect(self.dduplication)
		self.decrementation.clicked.connect(self.ddecrementation)
		self.incrementation.clicked.connect(self.dincrementation)

    def dinversion(self):
		print "Inversion"

		X, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter value you want to invert')

		if ok:
			print X
		else:
			return

		outputFileName,chemicalList = inversion.execute(X)

		print 'Result File ' + outputFileName + ' Created'

		timeOfSimulation, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter Time Of Simulation')

		if ok:
			print timeOfSimulation
		else:
			return

		sim = XMLParser.getSimulator(outputFileName)
		sim.simulate(int(timeOfSimulation),getHistoryFileName(outputFileName))
		sim.plot(chemicalList)

    def dduplication(self):
		print "Duplicate"

		X, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter value you want to duplicate')

		if ok:
			print X
		else:
			return

		outputFileName,chemicalList = duplicate.execute(X)

		print 'Result File ' + outputFileName + ' Created'

		timeOfSimulation, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter Time Of Simulation')

		if ok:
			print timeOfSimulation
		else:
			return

		sim = XMLParser.getSimulator(outputFileName)
		sim.simulate(int(timeOfSimulation),getHistoryFileName(outputFileName))
		sim.plot(chemicalList)

    def ddecrementation(self):
		print "Decrement"

		X, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter value you want to decrement 1 from')

		if ok:
			print X
		else:
			return

		outputFileName,chemicalList = decrement.execute(X)

		print 'Result File ' + outputFileName + ' Created'

		timeOfSimulation, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter Time Of Simulation')

		if ok:
			print timeOfSimulation
		else:
			return

		sim = XMLParser.getSimulator(outputFileName)
		sim.simulate(int(timeOfSimulation),getHistoryFileName(outputFileName))
		sim.plot(chemicalList)

    def dincrementation(self):
		print "Increment"

		X, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter value you want to increment 1 to')

		if ok:
			print X
		else:
			return

		outputFileName,chemicalList = increment.execute(X)

		print 'Result File ' + outputFileName + ' Created'

		timeOfSimulation, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter Time Of Simulation')

		if ok:
			print timeOfSimulation
		else:
			return

		sim = XMLParser.getSimulator(outputFileName)
		sim.simulate(int(timeOfSimulation),getHistoryFileName(outputFileName))
		sim.plot(chemicalList)

class AdvancedWidget(QtGui.QWidget):
    def __init__(self, parent=None):
		super(AdvancedWidget, self).__init__(parent)
		layout = QtGui.QHBoxLayout()

		self.multiplication = QtGui.QPushButton('1) Multiplication')
		layout.addWidget(self.multiplication)

		self.logarithm = QtGui.QPushButton('2) Logarithm')
		layout.addWidget(self.logarithm)

		self.power = QtGui.QPushButton('3) Power')
		layout.addWidget(self.power)

		self.setLayout(layout)

		self.multiplication.clicked.connect(self.dmultiplication)
		self.logarithm.clicked.connect(self.dlogarithm)
		self.power.clicked.connect(self.dpower)

    def dmultiplication(self):
		print "Multiplication"

		X, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter first value you want to multiply')

		if ok:
			print X
		else:
			return

		Y, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter second value you want to multiply')

		if ok:
			print Y
		else:
			return

		outputFileName,chemicalList = multiply1.execute(X,Y)

		print 'Result File ' + outputFileName + ' Created'

		timeOfSimulation, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter Time Of Simulation')

		if ok:
			print timeOfSimulation
		else:
			return

		sim = XMLParser.getSimulator(outputFileName)
		sim.simulate(int(timeOfSimulation),getHistoryFileName(outputFileName))
		sim.plot(chemicalList)

    def dlogarithm(self):
		print "Ceiling of logarithm"

		X, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter value you want to take ceiling logarithm of')

		if ok:
			print X
		else:
			return

		outputFileName,chemicalList = logarithm.execute(X)

		print 'Result File ' + outputFileName + ' Created'

		timeOfSimulation, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter Time Of Simulation')

		if ok:
			print timeOfSimulation
		else:
			return

		sim = XMLParser.getSimulator(outputFileName)
		sim.simulate(int(timeOfSimulation),getHistoryFileName(outputFileName))
		sim.plot(chemicalList)

    def dpower(self):
		print "Power"

		X, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter value of base')

		if ok:
			print X
		else:
			return

		Y, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter vaue of exponent')

		if ok:
			print Y
		else:
			return

		outputFileName,chemicalList = power.execute(X,Y)

		print 'Result File ' + outputFileName + ' Created'

		timeOfSimulation, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter Time Of Simulation')

		if ok:
			print timeOfSimulation
		else:
			return

		sim = XMLParser.getSimulator(outputFileName)
		sim.simulate(int(timeOfSimulation),getHistoryFileName(outputFileName))
		sim.plot(chemicalList)

app = QtGui.QApplication([])
window = MainWindow()
window.show()
app.exec_()

<|endoftext|>


<commit_before>"""
2015/XX/XX

Group 22, CPSC 231

Murray Cobbe
Nathan Meulenbroek
Sharjeel Junaid

Description:
This part of the game is in charge of prompting the user for input & displaying it out on a graphical overlay while allowing user input
"""
import turtle
import time
import math
import random
from ASCII import printOutASCII

# Initialize global constants (necessary for when functions are called from a different file)
halfBoardWidth = -250.0
halfBoardHeight = -halfBoardWidth
boardOutlineColour = "White"
boardBackgroundColour = "Brown"
player1Colour = "White"
player2Colour = "Black"
playerPieceData = [1, 0, 0]

# Initialize board 8x8 matrix (2D array)
boardMatrix = [[0 for boardMatrixIndex in range(9)] for boardMatrixIndex in range(9)]

# Initialize the display out & the first turtle
displayOut = turtle.Screen()
turtle1 = turtle.Turtle()
displayOut.bgcolor(boardBackgroundColour)
displayOut.title("Reversi By Group 22")
displayOut.setup(abs(halfBoardWidth * 2 + halfBoardWidth * 1 / 4), abs(halfBoardHeight * 2 + halfBoardHeight * 1 / 4))

# Function to print out the ASCII intro to the display overlay & waits 10 seconds before running the program
def printOutIntro():
    teleportToTile(6, 1)
    turtle1.write(printOutASCII(), align="Left", font=("Arial", int(abs(halfBoardWidth) * 1 / 25)))
    time.sleep(10)
    turtle1.clear()

# Function to print out the reversi table. Clears display before printing and sets color to contrast BG
# Takes no params, accesses global variable boardOutlineColour
def printOutTable():
    turtle1.clear()
    turtle1.color(boardOutlineColour)

    # For loop to teleport the turtle through generating the board. Starts top left
    for indexCounter in range(9):
        # Lift turtle and teleport to left hand side of the following row, top left if first row
        # Then draw line
        turtle1.up()
        turtle1.goto(halfBoardWidth, halfBoardHeight - indexCounter * halfBoardHeight / 4)
        turtle1.down()
        turtle1.forward(-halfBoardWidth * 2)

        # Turn turtle to print columnal line, follows same steps as above
        # Then turns the turtle back to the horizontal for the next row
        turtle1.right(90)
        turtle1.up()
        turtle1.goto(halfBoardWidth - indexCounter * halfBoardWidth / 4, halfBoardHeight)
        turtle1.down()
        turtle1.forward(halfBoardHeight * 2)
        turtle1.left(90)

    turtle1.color("Black")

# Function to check whether coordinates are valid - returns boolean
# Params:
#   inputRow - x coordinate in numerical value
#   inputColumn - y coordinate in numerical
# Implied:
#   boardMatrix[8][8] - from global variables. Is mutable, but not changed
def checkIfValidMove(inputRow, inputColumn):
    if inputRow <= 8 and inputColumn <= 8 and inputRow >= 1 and inputColumn >= 1:
        # Checks to see whether the entry index in the matrix is free
        if boardMatrix[inputRow][inputColumn] == 0:
            return True
        else:
            return False
    else:
        return False

# Function to teleport the turtle to a different position without leaving a trail
# Params:
#   inputRow - x coordinate in numerical value
#   inputColumn - y coordinate in numerical value
def teleportToTile(inputRow, inputColumn):
    turtle1.up()
    turtle1.goto(halfBoardWidth - (math.floor(inputColumn) - 0.5) * halfBoardWidth / 4, halfBoardHeight - math.floor(inputRow) * halfBoardHeight / 4)
    turtle1.down()

# Function to calculate the tile requested by the coordinates given (Used to convert raw click Data)
# Params:
#   inputX - x coordinate in numerical value
#   inputY - y coordinate in numerical value
def coordinatesCalculateTile(inputX, inputY):
    # Calculates row and column based on input
    calculatedColumn = math.floor(abs(((inputY - halfBoardHeight) / (halfBoardHeight / 4))) + 1)
    calculatedRow = math.floor(abs(((inputX - halfBoardWidth) / (halfBoardWidth / 4))) + 1)

    # Stores The Row & Column Values Of The Piece That Is Being Added
    playerPieceData[1] = calculatedColumn
    playerPieceData[2] = calculatedRow

# Function to return the row at which the user added his piece
def getUserPieceRow():
    return playerPieceData[1]

# Function to return the column at which the user added his piece
def getUserPieceColumn():
    return playerPieceData[2]

# Function to add a piece to the board
# Params:
#   inputRow - x coordinate in numerical value
#   inputColumn - y coordinate in numerical value
#   moveCount - the numerical value of the move number
def addPieceToBoard(inputRow, inputColumn, moveCount):
    # Starts the fill method to fill the printed circle
    turtle1.begin_fill()

    # If move even, fill piece with player1Colour and store that they occupied said space.
    # If move odd, fill piece with player2Color and store that they occupied said space
    if moveCount % 2 == 0:
        turtle1.fillcolor(player1Colour)
        boardMatrix[inputRow][inputColumn] = player1Colour
    else:
        turtle1.fillcolor(player2Colour)
        boardMatrix[inputRow][inputColumn] = player2Colour

    # Print out circle with radius of 1/16 of board and end fill method
    turtle1.circle(abs(halfBoardWidth / 8))
    turtle1.end_fill()

# Function to run and call other functions when the GUI is clicked
# Params:
#   inputX - x coordinate in numerical value
#   inputY - y coordinate in numerical value
def graphicalOverlayClicked(inputX, inputY):
    # Calculate tile clicked
    coordinatesCalculateTile(inputX, inputY)

    # Validate move, then store that a piece has been played and draw the piece in the correct location
    if checkIfValidMove(playerPieceData[1], playerPieceData[2]):
        playerPieceData[0] += 1
        teleportToTile(playerPieceData[1], playerPieceData[2])
        addPieceToBoard(playerPieceData[1], playerPieceData[2], playerPieceData[0])

# Function to perform initial setup for the GUI
def performInitialSetup():
    # Resets The Display Overlay & The Turtle
    displayOut.reset()
    turtle1.reset()

    # Hides The Turtle & Makes The Animation Speed / Delay Instantaneous
    turtle1.hideturtle()
    turtle1.speed(0)
    displayOut.delay(0)

    # Calls The Functions To Print Out The Intro & Board
    printOutIntro()
    printOutTable()

    # Adds The Default Tiles To The Board
    teleportToTile(4, 4)
    addPieceToBoard(4, 4, 1)
    teleportToTile(4, 5)
    addPieceToBoard(4, 5, 2)
    teleportToTile(5, 4)
    addPieceToBoard(5, 4, 2)
    teleportToTile(5, 5)
    addPieceToBoard(5, 5, 1)

    # Randomly Allows Either Player 1 Or Player 2 To Go First
    playerPieceData[0] = random.randint(1, 2)

# Main function to run gui separate from other files
def main():
    # Call initial setup, then wait for user action, then loop though wait for user action
    performInitialSetup()
    displayOut.onclick(graphicalOverlayClicked)
    displayOut.listen()
    displayOut.mainloop()

if __name__=='__main__'
    main()

<commit_msg>Updated GUI.py<commit_after>"""
2015/XX/XX

Group 22, CPSC 231

Murray Cobbe
Nathan Meulenbroek
Sharjeel Junaid

Description:
This part of the game is in charge of prompting the user for input & displaying it out on a graphical overlay while allowing user input
"""
import turtle
import time
import math
import random
from ASCII import printOutASCII

# Initialize global constants (necessary for when functions are called from a different file)
halfBoardWidth = -250.0
halfBoardHeight = -halfBoardWidth
boardOutlineColour = "White"
boardBackgroundColour = "Brown"
player1Colour = "White"
player2Colour = "Black"
playerPieceData = [1, 0, 0]

# Initialize board 8x8 matrix (2D array)
boardMatrix = [[0 for boardMatrixIndex in range(9)] for boardMatrixIndex in range(9)]

# Initialize the display out & the first turtle
displayOut = turtle.Screen()
turtle1 = turtle.Turtle()
displayOut.bgcolor(boardBackgroundColour)
displayOut.title("Reversi By Group 22")
displayOut.setup(abs(halfBoardWidth * 2 + halfBoardWidth * 1 / 4), abs(halfBoardHeight * 2 + halfBoardHeight * 1 / 4))

# Function to print out the ASCII intro to the display overlay & waits 10 seconds before running the program
def printOutIntro():
    teleportToTile(6, 1)
    turtle1.write(printOutASCII(), align="Left", font=("Arial", int(abs(halfBoardWidth) * 1 / 25)))
    time.sleep(10)
    turtle1.clear()

# Function to print out the reversi table. Clears display before printing and sets color to contrast BG
# Takes no params, accesses global variable boardOutlineColour
def printOutTable():
    turtle1.clear()
    turtle1.color(boardOutlineColour)

    # For loop to teleport the turtle through generating the board. Starts top left
    for indexCounter in range(9):
        # Lift turtle and teleport to left hand side of the following row, top left if first row
        # Then draw line
        turtle1.up()
        turtle1.goto(halfBoardWidth, halfBoardHeight - indexCounter * halfBoardHeight / 4)
        turtle1.down()
        turtle1.forward(-halfBoardWidth * 2)

        # Turn turtle to print columnal line, follows same steps as above
        # Then turns the turtle back to the horizontal for the next row
        turtle1.right(90)
        turtle1.up()
        turtle1.goto(halfBoardWidth - indexCounter * halfBoardWidth / 4, halfBoardHeight)
        turtle1.down()
        turtle1.forward(halfBoardHeight * 2)
        turtle1.left(90)

    turtle1.color("Black")

# Function to check whether coordinates are valid - returns boolean
# Params:
#   inputRow - x coordinate in numerical value
#   inputColumn - y coordinate in numerical
# Implied:
#   boardMatrix[8][8] - from global variables. Is mutable, but not changed
def checkIfValidMove(inputRow, inputColumn):
    if inputRow <= 8 and inputColumn <= 8 and inputRow >= 1 and inputColumn >= 1:
        # Checks to see whether the entry index in the matrix is free
        if boardMatrix[inputRow][inputColumn] == 0:
            return True
        else:
            return False
    else:
        return False

# Function to teleport the turtle to a different position without leaving a trail
# Params:
#   inputRow - x coordinate in numerical value
#   inputColumn - y coordinate in numerical value
def teleportToTile(inputRow, inputColumn):
    turtle1.up()
    turtle1.goto(halfBoardWidth - (math.floor(inputColumn) - 0.5) * halfBoardWidth / 4, halfBoardHeight - math.floor(inputRow) * halfBoardHeight / 4)
    turtle1.down()

# Function to calculate the tile requested by the coordinates given (Used to convert raw click Data)
# Params:
#   inputX - x coordinate in numerical value
#   inputY - y coordinate in numerical value
def coordinatesCalculateTile(inputX, inputY):
    # Calculates row and column based on input
    calculatedColumn = math.floor(abs(((inputY - halfBoardHeight) / (halfBoardHeight / 4))) + 1)
    calculatedRow = math.floor(abs(((inputX - halfBoardWidth) / (halfBoardWidth / 4))) + 1)

    # Stores The Row & Column Values Of The Piece That Is Being Added
    playerPieceData[1] = calculatedColumn
    playerPieceData[2] = calculatedRow

# Function to return the row at which the user added his piece
def getUserPieceRow():
    return playerPieceData[1]

# Function to return the column at which the user added his piece
def getUserPieceColumn():
    return playerPieceData[2]

# Function to add a piece to the board
# Params:
#   inputRow - x coordinate in numerical value
#   inputColumn - y coordinate in numerical value
#   moveCount - the numerical value of the move number
def addPieceToBoard(inputRow, inputColumn, moveCount):
    # Starts the fill method to fill the printed circle
    turtle1.begin_fill()

    # If move even, fill piece with player1Colour and store that they occupied said space.
    # If move odd, fill piece with player2Color and store that they occupied said space
    if moveCount % 2 == 0:
        turtle1.fillcolor(player1Colour)
        boardMatrix[inputRow][inputColumn] = player1Colour
    else:
        turtle1.fillcolor(player2Colour)
        boardMatrix[inputRow][inputColumn] = player2Colour

    # Print out circle with radius of 1/16 of board and end fill method
    turtle1.circle(abs(halfBoardWidth / 8))
    turtle1.end_fill()

# Function to run and call other functions when the GUI is clicked
# Params:
#   inputX - x coordinate in numerical value
#   inputY - y coordinate in numerical value
def graphicalOverlayClicked(inputX, inputY):
    # Calculate tile clicked
    coordinatesCalculateTile(inputX, inputY)

    # Validate move, then store that a piece has been played and draw the piece in the correct location
    if checkIfValidMove(playerPieceData[1], playerPieceData[2]):
        playerPieceData[0] += 1
        teleportToTile(playerPieceData[1], playerPieceData[2])
        addPieceToBoard(playerPieceData[1], playerPieceData[2], playerPieceData[0])

# Function to perform initial setup for the GUI
def performInitialSetup():
    # Resets The Display Overlay & The Turtle
    displayOut.reset()
    turtle1.reset()

    # Hides The Turtle & Makes The Animation Speed / Delay Instantaneous
    turtle1.hideturtle()
    turtle1.speed(0)
    displayOut.delay(0)

    # Calls The Functions To Print Out The Intro & Board
    printOutIntro()
    printOutTable()

    # Adds The Default Tiles To The Board
    teleportToTile(4, 4)
    addPieceToBoard(4, 4, 1)
    teleportToTile(4, 5)
    addPieceToBoard(4, 5, 2)
    teleportToTile(5, 4)
    addPieceToBoard(5, 4, 2)
    teleportToTile(5, 5)
    addPieceToBoard(5, 5, 1)

    # Randomly Allows Either Player 1 Or Player 2 To Go First
    playerPieceData[0] = random.randint(1, 2)

# Main function to run gui separate from other files
def main():
    # Call initial setup, then wait for user action, then loop though wait for user action
    performInitialSetup()
    displayOut.onclick(graphicalOverlayClicked)
    displayOut.listen()
    displayOut.mainloop()

if __name__=='__main__':
    main()

<|endoftext|>


<commit_before>from Main import main, __version__ as ESVersion
from argparse import Namespace
import random

from tkinter import Checkbutton, OptionMenu, Tk, LEFT, RIGHT, BOTTOM, TOP, StringVar, IntVar, Frame, Label, W, E, Entry, Spinbox, Button, filedialog, messagebox

def guiMain(args=None):
    mainWindow = Tk()
    mainWindow.wm_title("Entrance Shuffle %s" % ESVersion)

    topFrame = Frame(mainWindow)
    rightHalfFrame = Frame(topFrame)
    checkBoxFrame = Frame(rightHalfFrame)

    createSpoilerVar = IntVar()
    createSpoilerCheckbutton = Checkbutton(checkBoxFrame, text="Create Spoiler Log", variable=createSpoilerVar)
    suppressRomVar = IntVar()
    suppressRomCheckbutton = Checkbutton(checkBoxFrame, text="Do not create patched Rom", variable=suppressRomVar)
    quickSwapVar = IntVar()
    quickSwapCheckbutton = Checkbutton(checkBoxFrame, text="Enabled L/R Item quickswapping", variable=quickSwapVar)
    dungeonItemsVar = IntVar()
    dungeonItemsCheckbutton = Checkbutton(checkBoxFrame, text="Place Dungeon Items (Compasses/Maps)", onvalue=0, offvalue=1, variable=dungeonItemsVar)
    beatableOnlyVar = IntVar()
    beatableOnlyCheckbutton = Checkbutton(checkBoxFrame, text="Only ensure seed is beatable, not all items must be reachable", variable=beatableOnlyVar)

    createSpoilerCheckbutton.pack(expand=True, anchor=W)
    suppressRomCheckbutton.pack(expand=True, anchor=W)
    quickSwapCheckbutton.pack(expand=True, anchor=W)
    dungeonItemsCheckbutton.pack(expand=True, anchor=W)
    beatableOnlyCheckbutton.pack(expand=True, anchor=W)

    fileDialogFrame = Frame(rightHalfFrame)

    romDialogFrame = Frame(fileDialogFrame)
    baseRomLabel = Label(romDialogFrame, text='Base Rom')
    romVar = StringVar()
    romEntry = Entry(romDialogFrame, textvariable=romVar)
    def RomSelect():
        rom = filedialog.askopenfilename()
        romVar.set(rom)
    romSelectButton = Button(romDialogFrame, text='Select Rom', command=RomSelect)

    baseRomLabel.pack(side=LEFT)
    romEntry.pack(side=LEFT)
    romSelectButton.pack(side=LEFT)

    spriteDialogFrame = Frame(fileDialogFrame)
    baseSpriteLabel = Label(spriteDialogFrame, text='Link Sprite')
    spriteVar = StringVar()
    spriteEntry = Entry(spriteDialogFrame, textvariable=spriteVar)

    def SpriteSelect():
        sprite = filedialog.askopenfilename()
        spriteVar.set(sprite)

    spriteSelectButton = Button(spriteDialogFrame, text='Select Sprite', command=SpriteSelect)

    baseSpriteLabel.pack(side=LEFT)
    spriteEntry.pack(side=LEFT)
    spriteSelectButton.pack(side=LEFT)

    romDialogFrame.pack()
    spriteDialogFrame.pack()

    checkBoxFrame.pack()
    fileDialogFrame.pack()

    drowDownFrame = Frame(topFrame)

    modeFrame = Frame(drowDownFrame)
    modeVar = StringVar()
    modeVar.set('standard')
    modeOptionMenu = OptionMenu(modeFrame, modeVar, 'standard', 'open', 'swordless')
    modeOptionMenu.pack(side=RIGHT)
    modeLabel = Label(modeFrame, text='Game Mode')
    modeLabel.pack(side=LEFT)

    logicFrame = Frame(drowDownFrame)
    logicVar = StringVar()
    logicVar.set('noglitches')
    logicOptionMenu = OptionMenu(logicFrame, logicVar, 'noglitches', 'minorglitches')
    logicOptionMenu.pack(side=RIGHT)
    logicLabel = Label(logicFrame, text='Game logic')
    logicLabel.pack(side=LEFT)

    goalFrame = Frame(drowDownFrame)
    goalVar = StringVar()
    goalVar.set('ganon')
    goalOptionMenu = OptionMenu(goalFrame, goalVar, 'ganon', 'pedestal', 'dungeons', 'starhunt', 'triforcehunt')
    goalOptionMenu.pack(side=RIGHT)
    goalLabel = Label(goalFrame, text='Game goal')
    goalLabel.pack(side=LEFT)

    difficultyFrame = Frame(drowDownFrame)
    difficultyVar = StringVar()
    difficultyVar.set('normal')
    difficultyOptionMenu = OptionMenu(difficultyFrame, difficultyVar, 'normal', 'timed', 'timed-ohko', 'timed-countdown')
    difficultyOptionMenu.pack(side=RIGHT)
    difficultyLabel = Label(difficultyFrame, text='Game difficulty')
    difficultyLabel.pack(side=LEFT)

    algorithmFrame = Frame(drowDownFrame)
    algorithmVar = StringVar()
    algorithmVar.set('restrictive')
    algorithmOptionMenu = OptionMenu(algorithmFrame, algorithmVar, 'freshness', 'flood', 'vt21', 'vt22', 'restrictive')
    algorithmOptionMenu.pack(side=RIGHT)
    algorithmLabel = Label(algorithmFrame, text='Item distribution algorithm')
    algorithmLabel.pack(side=LEFT)

    shuffleFrame = Frame(drowDownFrame)
    shuffleVar = StringVar()
    shuffleVar.set('full')
    shuffleOptionMenu = OptionMenu(shuffleFrame, shuffleVar, 'vanilla', 'simple', 'restricted', 'full', 'madness', 'insanity', 'dungeonsfull', 'dungeonssimple')
    shuffleOptionMenu.pack(side=RIGHT)
    shuffleLabel = Label(shuffleFrame, text='Entrance shuffle algorithm')
    shuffleLabel.pack(side=LEFT)

    heartbeepFrame = Frame(drowDownFrame)
    heartbeepVar = StringVar()
    heartbeepVar.set('normal')
    heartbeepOptionMenu = OptionMenu(heartbeepFrame, heartbeepVar, 'normal', 'half', 'quarter', 'off')
    heartbeepOptionMenu.pack(side=RIGHT)
    heartbeepLabel = Label(heartbeepFrame, text='Heartbeep sound rate')
    heartbeepLabel.pack(side=LEFT)

    modeFrame.pack(expand=True, anchor=E)
    logicFrame.pack(expand=True, anchor=E)
    goalFrame.pack(expand=True, anchor=E)
    difficultyFrame.pack(expand=True, anchor=E)
    algorithmFrame.pack(expand=True, anchor=E)
    shuffleFrame.pack(expand=True, anchor=E)
    heartbeepFrame.pack(expand=True, anchor=E)

    bottomFrame = Frame(mainWindow)

    seedLabel = Label(bottomFrame, text='Seed #')
    seedVar = StringVar()
    seedEntry = Entry(bottomFrame, textvariable=seedVar)
    countLabel = Label(bottomFrame, text='Count')
    countVar = StringVar()
    countSpinbox = Spinbox(bottomFrame, from_=1, to=100, textvariable=countVar)

    def generateRom():
        guiargs = Namespace
        guiargs.seed = int(seedVar.get()) if seedVar.get() else None
        guiargs.count = int(countVar.get()) if countVar.get() != '1' else None
        guiargs.mode = modeVar.get()
        guiargs.logic = logicVar.get()
        guiargs.goal = goalVar.get()
        guiargs.difficulty = difficultyVar.get()
        guiargs.algorithm = algorithmVar.get()
        guiargs.shuffle = shuffleVar.get()
        guiargs.heartbeep = heartbeepVar.get()
        guiargs.create_spoiler = bool(createSpoilerVar.get())
        guiargs.suppress_rom = bool(suppressRomVar.get())
        guiargs.nodungeonitems = bool(dungeonItemsVar.get())
        guiargs.beatableonly = bool(beatableOnlyVar.get())
        guiargs.quickswap = bool(quickSwapVar.get())
        guiargs.rom = romVar.get()
        guiargs.sprite = spriteVar.get() if spriteVar.get() else None
        try:
            if guiargs.count is not None:
                seed = guiargs.seed
                for i in range(guiargs.count):
                    main(seed=seed, args=guiargs)
                    seed = random.randint(0, 999999999)
            else:
                main(seed=guiargs.seed, args=guiargs)
        except Exception as e:
            messagebox.showerror(title="Error while creating seed", message=str(e))
        else:
            messagebox.showinfo(title="Success", message="Rom patched successfully")

    generateButton = Button(bottomFrame, text='Generate Patched Rom', command=generateRom)

    seedLabel.pack(side=LEFT)
    seedEntry.pack(side=LEFT)
    countLabel.pack(side=LEFT)
    countSpinbox.pack(side=LEFT)
    generateButton.pack(side=LEFT)

    drowDownFrame.pack(side=LEFT)
    rightHalfFrame.pack(side=RIGHT)
    topFrame.pack(side=TOP)
    bottomFrame.pack(side=BOTTOM)

    if args is not None:
        # load values from commandline args
        createSpoilerVar.set(int(args.create_spoiler))
        suppressRomVar.set(int(args.suppress_rom))
        if args.nodungeonitems:
            dungeonItemsVar.set(int(not args.nodungeonitems))
        beatableOnlyVar.set(int(args.beatableonly))
        quickSwapVar.set(int(args.quickswap))
        if args.count:
            countVar.set(str(args.count))
        if args.seed:
            seedVar.set(str(args.seed))
        modeVar.set(args.mode)
        difficultyVar.set(args.difficulty)
        goalVar.set(args.goal)
        algorithmVar.set(args.algorithm)
        shuffleVar.set(args.shuffle)
        heartbeepVar.set(args.heartbeep)
        logicVar.set(args.logic)
        romVar.set(args.rom)
        if args.sprite is not None:
            spriteVar.set(args.sprite)

    mainWindow.mainloop()

if __name__ == '__main__':
    guiMain()
<commit_msg>Gui needs to provide (unused) jsonout args parameter<commit_after>from Main import main, __version__ as ESVersion
from argparse import Namespace
import random

from tkinter import Checkbutton, OptionMenu, Tk, LEFT, RIGHT, BOTTOM, TOP, StringVar, IntVar, Frame, Label, W, E, Entry, Spinbox, Button, filedialog, messagebox

def guiMain(args=None):
    mainWindow = Tk()
    mainWindow.wm_title("Entrance Shuffle %s" % ESVersion)

    topFrame = Frame(mainWindow)
    rightHalfFrame = Frame(topFrame)
    checkBoxFrame = Frame(rightHalfFrame)

    createSpoilerVar = IntVar()
    createSpoilerCheckbutton = Checkbutton(checkBoxFrame, text="Create Spoiler Log", variable=createSpoilerVar)
    suppressRomVar = IntVar()
    suppressRomCheckbutton = Checkbutton(checkBoxFrame, text="Do not create patched Rom", variable=suppressRomVar)
    quickSwapVar = IntVar()
    quickSwapCheckbutton = Checkbutton(checkBoxFrame, text="Enabled L/R Item quickswapping", variable=quickSwapVar)
    dungeonItemsVar = IntVar()
    dungeonItemsCheckbutton = Checkbutton(checkBoxFrame, text="Place Dungeon Items (Compasses/Maps)", onvalue=0, offvalue=1, variable=dungeonItemsVar)
    beatableOnlyVar = IntVar()
    beatableOnlyCheckbutton = Checkbutton(checkBoxFrame, text="Only ensure seed is beatable, not all items must be reachable", variable=beatableOnlyVar)

    createSpoilerCheckbutton.pack(expand=True, anchor=W)
    suppressRomCheckbutton.pack(expand=True, anchor=W)
    quickSwapCheckbutton.pack(expand=True, anchor=W)
    dungeonItemsCheckbutton.pack(expand=True, anchor=W)
    beatableOnlyCheckbutton.pack(expand=True, anchor=W)

    fileDialogFrame = Frame(rightHalfFrame)

    romDialogFrame = Frame(fileDialogFrame)
    baseRomLabel = Label(romDialogFrame, text='Base Rom')
    romVar = StringVar()
    romEntry = Entry(romDialogFrame, textvariable=romVar)
    def RomSelect():
        rom = filedialog.askopenfilename()
        romVar.set(rom)
    romSelectButton = Button(romDialogFrame, text='Select Rom', command=RomSelect)

    baseRomLabel.pack(side=LEFT)
    romEntry.pack(side=LEFT)
    romSelectButton.pack(side=LEFT)

    spriteDialogFrame = Frame(fileDialogFrame)
    baseSpriteLabel = Label(spriteDialogFrame, text='Link Sprite')
    spriteVar = StringVar()
    spriteEntry = Entry(spriteDialogFrame, textvariable=spriteVar)

    def SpriteSelect():
        sprite = filedialog.askopenfilename()
        spriteVar.set(sprite)

    spriteSelectButton = Button(spriteDialogFrame, text='Select Sprite', command=SpriteSelect)

    baseSpriteLabel.pack(side=LEFT)
    spriteEntry.pack(side=LEFT)
    spriteSelectButton.pack(side=LEFT)

    romDialogFrame.pack()
    spriteDialogFrame.pack()

    checkBoxFrame.pack()
    fileDialogFrame.pack()

    drowDownFrame = Frame(topFrame)

    modeFrame = Frame(drowDownFrame)
    modeVar = StringVar()
    modeVar.set('standard')
    modeOptionMenu = OptionMenu(modeFrame, modeVar, 'standard', 'open', 'swordless')
    modeOptionMenu.pack(side=RIGHT)
    modeLabel = Label(modeFrame, text='Game Mode')
    modeLabel.pack(side=LEFT)

    logicFrame = Frame(drowDownFrame)
    logicVar = StringVar()
    logicVar.set('noglitches')
    logicOptionMenu = OptionMenu(logicFrame, logicVar, 'noglitches', 'minorglitches')
    logicOptionMenu.pack(side=RIGHT)
    logicLabel = Label(logicFrame, text='Game logic')
    logicLabel.pack(side=LEFT)

    goalFrame = Frame(drowDownFrame)
    goalVar = StringVar()
    goalVar.set('ganon')
    goalOptionMenu = OptionMenu(goalFrame, goalVar, 'ganon', 'pedestal', 'dungeons', 'starhunt', 'triforcehunt')
    goalOptionMenu.pack(side=RIGHT)
    goalLabel = Label(goalFrame, text='Game goal')
    goalLabel.pack(side=LEFT)

    difficultyFrame = Frame(drowDownFrame)
    difficultyVar = StringVar()
    difficultyVar.set('normal')
    difficultyOptionMenu = OptionMenu(difficultyFrame, difficultyVar, 'normal', 'timed', 'timed-ohko', 'timed-countdown')
    difficultyOptionMenu.pack(side=RIGHT)
    difficultyLabel = Label(difficultyFrame, text='Game difficulty')
    difficultyLabel.pack(side=LEFT)

    algorithmFrame = Frame(drowDownFrame)
    algorithmVar = StringVar()
    algorithmVar.set('restrictive')
    algorithmOptionMenu = OptionMenu(algorithmFrame, algorithmVar, 'freshness', 'flood', 'vt21', 'vt22', 'restrictive')
    algorithmOptionMenu.pack(side=RIGHT)
    algorithmLabel = Label(algorithmFrame, text='Item distribution algorithm')
    algorithmLabel.pack(side=LEFT)

    shuffleFrame = Frame(drowDownFrame)
    shuffleVar = StringVar()
    shuffleVar.set('full')
    shuffleOptionMenu = OptionMenu(shuffleFrame, shuffleVar, 'vanilla', 'simple', 'restricted', 'full', 'madness', 'insanity', 'dungeonsfull', 'dungeonssimple')
    shuffleOptionMenu.pack(side=RIGHT)
    shuffleLabel = Label(shuffleFrame, text='Entrance shuffle algorithm')
    shuffleLabel.pack(side=LEFT)

    heartbeepFrame = Frame(drowDownFrame)
    heartbeepVar = StringVar()
    heartbeepVar.set('normal')
    heartbeepOptionMenu = OptionMenu(heartbeepFrame, heartbeepVar, 'normal', 'half', 'quarter', 'off')
    heartbeepOptionMenu.pack(side=RIGHT)
    heartbeepLabel = Label(heartbeepFrame, text='Heartbeep sound rate')
    heartbeepLabel.pack(side=LEFT)

    modeFrame.pack(expand=True, anchor=E)
    logicFrame.pack(expand=True, anchor=E)
    goalFrame.pack(expand=True, anchor=E)
    difficultyFrame.pack(expand=True, anchor=E)
    algorithmFrame.pack(expand=True, anchor=E)
    shuffleFrame.pack(expand=True, anchor=E)
    heartbeepFrame.pack(expand=True, anchor=E)

    bottomFrame = Frame(mainWindow)

    seedLabel = Label(bottomFrame, text='Seed #')
    seedVar = StringVar()
    seedEntry = Entry(bottomFrame, textvariable=seedVar)
    countLabel = Label(bottomFrame, text='Count')
    countVar = StringVar()
    countSpinbox = Spinbox(bottomFrame, from_=1, to=100, textvariable=countVar)

    def generateRom():
        guiargs = Namespace
        guiargs.seed = int(seedVar.get()) if seedVar.get() else None
        guiargs.count = int(countVar.get()) if countVar.get() != '1' else None
        guiargs.mode = modeVar.get()
        guiargs.logic = logicVar.get()
        guiargs.goal = goalVar.get()
        guiargs.difficulty = difficultyVar.get()
        guiargs.algorithm = algorithmVar.get()
        guiargs.shuffle = shuffleVar.get()
        guiargs.heartbeep = heartbeepVar.get()
        guiargs.create_spoiler = bool(createSpoilerVar.get())
        guiargs.suppress_rom = bool(suppressRomVar.get())
        guiargs.nodungeonitems = bool(dungeonItemsVar.get())
        guiargs.beatableonly = bool(beatableOnlyVar.get())
        guiargs.quickswap = bool(quickSwapVar.get())
        guiargs.rom = romVar.get()
        guiargs.jsonout = None
        guiargs.sprite = spriteVar.get() if spriteVar.get() else None
        try:
            if guiargs.count is not None:
                seed = guiargs.seed
                for i in range(guiargs.count):
                    main(seed=seed, args=guiargs)
                    seed = random.randint(0, 999999999)
            else:
                main(seed=guiargs.seed, args=guiargs)
        except Exception as e:
            messagebox.showerror(title="Error while creating seed", message=str(e))
        else:
            messagebox.showinfo(title="Success", message="Rom patched successfully")

    generateButton = Button(bottomFrame, text='Generate Patched Rom', command=generateRom)

    seedLabel.pack(side=LEFT)
    seedEntry.pack(side=LEFT)
    countLabel.pack(side=LEFT)
    countSpinbox.pack(side=LEFT)
    generateButton.pack(side=LEFT)

    drowDownFrame.pack(side=LEFT)
    rightHalfFrame.pack(side=RIGHT)
    topFrame.pack(side=TOP)
    bottomFrame.pack(side=BOTTOM)

    if args is not None:
        # load values from commandline args
        createSpoilerVar.set(int(args.create_spoiler))
        suppressRomVar.set(int(args.suppress_rom))
        if args.nodungeonitems:
            dungeonItemsVar.set(int(not args.nodungeonitems))
        beatableOnlyVar.set(int(args.beatableonly))
        quickSwapVar.set(int(args.quickswap))
        if args.count:
            countVar.set(str(args.count))
        if args.seed:
            seedVar.set(str(args.seed))
        modeVar.set(args.mode)
        difficultyVar.set(args.difficulty)
        goalVar.set(args.goal)
        algorithmVar.set(args.algorithm)
        shuffleVar.set(args.shuffle)
        heartbeepVar.set(args.heartbeep)
        logicVar.set(args.logic)
        romVar.set(args.rom)
        if args.sprite is not None:
            spriteVar.set(args.sprite)

    mainWindow.mainloop()

if __name__ == '__main__':
    guiMain()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

"""
Script to load the results of DetectWhichImageIsRadiography.py and show it in
such a way that we can make a conclusion.
"""

import sys
import os
import matplotlib.pyplot as plt
import numpy as np
import random

from functions import myLogger
from functions import get_git_hash
from functions import distance
from functions import estimate_image_noise

StartingFolder = ('/afs/psi.ch/project/EssentialMed/MasterArbeitBFH/' +
        'XrayImages/')

# Go through all the results in the folder and show the images.
Files = [os.path.join(dirpath, f)
    for dirpath, dirnames, files in os.walk(StartingFolder)
    for f in files if f.endswith('.image.corrected.stretched.png')]
print 'I found', len(Files), 'images to work with in', StartingFolder

# Select some files
randomizator = True
if randomizator:
    # Randomly select some files
    Files = random.sample(Files, 50)
else:
    # Select every n'th image (http://stackoverflow.com/a/1404229/323100)
    Files = [Files[i] for i in xrange(0, len(Files), 12)]

print 'Reading', len(Files), 'images in', \
    os.path.dirname(os.path.commonprefix(Files))

# Extract data from the images
ExperimentID = [os.path.split(i)[1].split('.')[0] for i in Files]
ExperimentFolder = [os.path.join(os.path.dirname(i),
                                 os.path.basename(i).split('.')[0]) for
    i in Files]
Folder = [os.path.dirname(i) for i in Files]
Images = [plt.imread(i) for i in Files]
Mean = [np.mean(i) * 255 for i in Images]
STD = [np.std(i) * 255 for i in Images]
ScintillatorDistance = [distance(i, ) for i in ExperimentFolder]
#~ Weed out the ones images we cannot read...
#~ for c, i in enumerate(Files):
    #~ print 'rm', os.path.join(Folder[c], '*.png')
    #~ estimate_noise(plt.imread(i))
Noise = [estimate_image_noise(i) * 255 for i in Images]

#~ # Give out info
#~ for c, item in enumerate(ExperimentID):
    #~ print str(c).rjust(2), 'of', len(ExperimentID), '| Mean:', \
        #~ str(round(Mean[c], 1)).rjust(5), '| STD:', \
        #~ str(round(STD[c], 1)).rjust(4), '|', \
        #~ os.path.join(Folder[c],
            #~ ExperimentID[c] + '.image.corrected.stretched.png')

# Sort according to something
sort = 'noise'
HighestFirst = True
if sort == 'std':
    sortedIDs = [x for (y, x) in sorted(zip(STD, ExperimentID),
        reverse=HighestFirst)]
    sortedImages = [x for (y, x) in sorted(zip(STD, Images),
        reverse=HighestFirst)]
    sortedMean = [x for (y, x) in sorted(zip(STD, Mean),
        reverse=HighestFirst)]
    sortedSTD = [x for (y, x) in sorted(zip(STD, STD),
        reverse=HighestFirst)]
    sortedFolder = [x for (y, x) in sorted(zip(STD, Folder),
        reverse=HighestFirst)]
    sortedNoise = [x for (y, x) in sorted(zip(STD, Noise),
        reverse=HighestFirst)]
elif sort == 'mean':
    sortedIDs = [x for (y, x) in sorted(zip(Mean, ExperimentID),
        reverse=HighestFirst)]
    sortedImages = [x for (y, x) in sorted(zip(Mean, Images),
        reverse=HighestFirst)]
    sortedMean = [x for (y, x) in sorted(zip(Mean, Mean),
        reverse=HighestFirst)]
    sortedSTD = [x for (y, x) in sorted(zip(Mean, STD),
        reverse=HighestFirst)]
    sortedFolder = [x for (y, x) in sorted(zip(Mean, Folder),
        reverse=HighestFirst)]
    sortedNoise = [x for (y, x) in sorted(zip(Mean, Noise),
        reverse=HighestFirst)]
    sortedDistance = [x for (y, x) in sorted(zip(Mean, ScintillatorDistance),
        reverse=HighestFirst)]
elif sort == 'id':
    sortedIDs = [x for (y, x) in sorted(zip(ExperimentID, ExperimentID),
        reverse=HighestFirst)]
    sortedImages = [x for (y, x) in sorted(zip(ExperimentID, Images),
        reverse=HighestFirst)]
    sortedMean = [x for (y, x) in sorted(zip(ExperimentID, Mean),
        reverse=HighestFirst)]
    sortedSTD = [x for (y, x) in sorted(zip(ExperimentID, STD),
        reverse=HighestFirst)]
    sortedFolder = [x for (y, x) in sorted(zip(ExperimentID, Folder),
        reverse=HighestFirst)]
    sortedNoise = [x for (y, x) in sorted(zip(ExperimentID, Noise),
        reverse=HighestFirst)]
    sortedDistance = [x for (y, x) in sorted(zip(ExperimentID,
        ScintillatorDistance), reverse=HighestFirst)]
elif sort == 'noise':
    sortedIDs = [x for (y, x) in sorted(zip(Noise, ExperimentID),
        reverse=HighestFirst)]
    sortedImages = [x for (y, x) in sorted(zip(Noise, Images),
        reverse=HighestFirst)]
    sortedMean = [x for (y, x) in sorted(zip(Noise, Mean),
        reverse=HighestFirst)]
    sortedSTD = [x for (y, x) in sorted(zip(Noise, STD),
        reverse=HighestFirst)]
    sortedFolder = [x for (y, x) in sorted(zip(Noise, Folder),
        reverse=HighestFirst)]
    sortedNoise = [x for (y, x) in sorted(zip(Noise, Noise),
        reverse=HighestFirst)]
    sortedDistance = [x for (y, x) in sorted(zip(Noise,
        ScintillatorDistance), reverse=HighestFirst)]
elif sort == 'distance':
    sortedIDs = [x for (y, x) in sorted(zip(ScintillatorDistance,
        ExperimentID), reverse=HighestFirst)]
    sortedImages = [x for (y, x) in sorted(zip(ScintillatorDistance, Images),
        reverse=HighestFirst)]
    sortedMean = [x for (y, x) in sorted(zip(ScintillatorDistance, Mean),
        reverse=HighestFirst)]
    sortedSTD = [x for (y, x) in sorted(zip(ScintillatorDistance, STD),
        reverse=HighestFirst)]
    sortedFolder = [x for (y, x) in sorted(zip(ScintillatorDistance, Folder),
        reverse=HighestFirst)]
    sortedNoise = [x for (y, x) in sorted(zip(ScintillatorDistance, Noise),
        reverse=HighestFirst)]
    sortedDistance = [x for (y, x) in sorted(zip(ScintillatorDistance,
        ScintillatorDistance), reverse=HighestFirst)]

# Select n top items from sorting criterion
n = 10
print 'Selecting', n, 'images, sorted from',
if HighestFirst:
    print 'highest to lowest',
else:
    print 'lowest to highest',
print sort
sortedIDs = sortedIDs[:n]
sortedImages = sortedImages[:n]
sortedMean = sortedMean[:n]
sortedSTD = sortedSTD[:n]
sortedNoise = sortedNoise[:n]
sortedFolder = sortedFolder[:n]
sortedDistance = sortedDistance[:n]

# Give out info
for c, item in enumerate(sortedIDs):
    print str(c).rjust(2), 'of', len(sortedIDs), '| Mean:', \
        str(round(sortedMean[c], 1)).rjust(5), '| STD:', \
        str(round(sortedSTD[c], 1)).rjust(4), '| Noise', \
        str(round(sortedNoise[c], 1)).rjust(4), '| Distance', \
        str(sortedDistance[c]), '| Experiment', \
        sortedIDs[c].rjust(8), '| Image', os.path.join(sortedFolder[c],
            sortedIDs[c] +
            '.image.corrected.stretched.png')[len(StartingFolder):]

plt.figure(figsize=[23, 10])
for c, i in enumerate(sortedImages):
    plt.subplot(2, len(sortedImages) / 2, c + 1)
    plt.imshow(i, cmap='gray')
    plt.title(' '.join([str(c), '|', sortedIDs[c], '\nMean',
        str(round(sortedMean[c], 1)), '\nSTD',
        str(round(sortedSTD[c], 1)), '\nNoise',
        str(round(sortedNoise[c], 1)), '\nDistance',
        str(sortedDistance[c]), 'mm\n',
        sortedFolder[c].split('/')[8], '-', sortedFolder[c].split('/')[9],
        '-', sortedFolder[c].split('/')[10]]))
    plt.axis('off')
if HighestFirst:
    plt.suptitle(' '.join(['Images sorted from highest to lowest', sort]))
else:
    plt.suptitle(' '.join(['Images sorted from lowest to highest', sort]))
plt.tight_layout()
plt.show()
exit()

# full screen figure
plt.figure(figsize=[23, 10])

for c, i in enumerate(sortedImages):
    sys.stdout.write(''.join(['\rImage %d/' % (c + 1), str(len(Images))]))
    if len(Files) > 10:
        plt.subplot(int(np.ceil(len(Files) / 4)),
            int(np.ceil(len(Files) / 3)), c + 1)
    else:
        plt.subplot(1, len(sortedImages), c + 1)
    plt.imshow(i, cmap='bone')
    currentDirName = os.path.dirname(Files[ExperimentID.index(sortedIDs[1])])[
        len(os.path.dirname(os.path.commonprefix(Files))) + 1:]
    plt.title(' '.join([sortedIDs[c], '| Mean', str(round(sortedMean[c], 1)),
        '| STD', str(round(sortedSTD[c], 1))]))
    plt.subplots_adjust(wspace=0.05)
    plt.subplots_adjust(hspace=0.05)
    plt.axis('off')
    #~ plt.subplot(2, len(Files), c + len(Files) + 1)
    #~ plt.hist(i.flatten(), bins=256, histtype='stepfilled')
    #~ plt.ylim([0, 1.2e5])
    sys.stdout.flush()

print '\nShowing plot'
plt.suptitle(' '.join(['sorted by', sort]))
plt.tight_layout()
plt.show()
<commit_msg>Remove some cruft at the end of the file<commit_after># -*- coding: utf-8 -*-

"""
Script to load the results of DetectWhichImageIsRadiography.py and show it in
such a way that we can make a conclusion.
"""

import sys
import os
import matplotlib.pyplot as plt
import numpy as np
import random

from functions import myLogger
from functions import get_git_hash
from functions import distance
from functions import estimate_image_noise

StartingFolder = ('/afs/psi.ch/project/EssentialMed/MasterArbeitBFH/' +
        'XrayImages/')

# Go through all the results in the folder and show the images.
Files = [os.path.join(dirpath, f)
    for dirpath, dirnames, files in os.walk(StartingFolder)
    for f in files if f.endswith('.image.corrected.stretched.png')]
print 'I found', len(Files), 'images to work with in', StartingFolder

# Select some files
randomizator = True
if randomizator:
    # Randomly select some files
    Files = random.sample(Files, 100)
else:
    # Select every n'th image (http://stackoverflow.com/a/1404229/323100)
    Files = [Files[i] for i in xrange(0, len(Files), 12)]

print 'Reading', len(Files), 'images in', \
    os.path.dirname(os.path.commonprefix(Files))

# Extract data from the images
ExperimentID = [os.path.split(i)[1].split('.')[0] for i in Files]
ExperimentFolder = [os.path.join(os.path.dirname(i),
                                 os.path.basename(i).split('.')[0]) for
    i in Files]
Folder = [os.path.dirname(i) for i in Files]
Images = [plt.imread(i) for i in Files]
Mean = [np.mean(i) * 255 for i in Images]
STD = [np.std(i) * 255 for i in Images]
ScintillatorDistance = [distance(i, ) for i in ExperimentFolder]
#~ Weed out the ones images we cannot read...
#~ for c, i in enumerate(Files):
    #~ print 'rm', os.path.join(Folder[c], '*.png')
    #~ estimate_noise(plt.imread(i))
Noise = [estimate_image_noise(i) * 255 for i in Images]

#~ # Give out info
#~ for c, item in enumerate(ExperimentID):
    #~ print str(c).rjust(2), 'of', len(ExperimentID), '| Mean:', \
        #~ str(round(Mean[c], 1)).rjust(5), '| STD:', \
        #~ str(round(STD[c], 1)).rjust(4), '|', \
        #~ os.path.join(Folder[c],
            #~ ExperimentID[c] + '.image.corrected.stretched.png')

# Sort according to something
sort = 'noise'
HighestFirst = True
if sort == 'std':
    sortedIDs = [x for (y, x) in sorted(zip(STD, ExperimentID),
        reverse=HighestFirst)]
    sortedImages = [x for (y, x) in sorted(zip(STD, Images),
        reverse=HighestFirst)]
    sortedMean = [x for (y, x) in sorted(zip(STD, Mean),
        reverse=HighestFirst)]
    sortedSTD = [x for (y, x) in sorted(zip(STD, STD),
        reverse=HighestFirst)]
    sortedFolder = [x for (y, x) in sorted(zip(STD, Folder),
        reverse=HighestFirst)]
    sortedNoise = [x for (y, x) in sorted(zip(STD, Noise),
        reverse=HighestFirst)]
elif sort == 'mean':
    sortedIDs = [x for (y, x) in sorted(zip(Mean, ExperimentID),
        reverse=HighestFirst)]
    sortedImages = [x for (y, x) in sorted(zip(Mean, Images),
        reverse=HighestFirst)]
    sortedMean = [x for (y, x) in sorted(zip(Mean, Mean),
        reverse=HighestFirst)]
    sortedSTD = [x for (y, x) in sorted(zip(Mean, STD),
        reverse=HighestFirst)]
    sortedFolder = [x for (y, x) in sorted(zip(Mean, Folder),
        reverse=HighestFirst)]
    sortedNoise = [x for (y, x) in sorted(zip(Mean, Noise),
        reverse=HighestFirst)]
    sortedDistance = [x for (y, x) in sorted(zip(Mean, ScintillatorDistance),
        reverse=HighestFirst)]
elif sort == 'id':
    sortedIDs = [x for (y, x) in sorted(zip(ExperimentID, ExperimentID),
        reverse=HighestFirst)]
    sortedImages = [x for (y, x) in sorted(zip(ExperimentID, Images),
        reverse=HighestFirst)]
    sortedMean = [x for (y, x) in sorted(zip(ExperimentID, Mean),
        reverse=HighestFirst)]
    sortedSTD = [x for (y, x) in sorted(zip(ExperimentID, STD),
        reverse=HighestFirst)]
    sortedFolder = [x for (y, x) in sorted(zip(ExperimentID, Folder),
        reverse=HighestFirst)]
    sortedNoise = [x for (y, x) in sorted(zip(ExperimentID, Noise),
        reverse=HighestFirst)]
    sortedDistance = [x for (y, x) in sorted(zip(ExperimentID,
        ScintillatorDistance), reverse=HighestFirst)]
elif sort == 'noise':
    sortedIDs = [x for (y, x) in sorted(zip(Noise, ExperimentID),
        reverse=HighestFirst)]
    sortedImages = [x for (y, x) in sorted(zip(Noise, Images),
        reverse=HighestFirst)]
    sortedMean = [x for (y, x) in sorted(zip(Noise, Mean),
        reverse=HighestFirst)]
    sortedSTD = [x for (y, x) in sorted(zip(Noise, STD),
        reverse=HighestFirst)]
    sortedFolder = [x for (y, x) in sorted(zip(Noise, Folder),
        reverse=HighestFirst)]
    sortedNoise = [x for (y, x) in sorted(zip(Noise, Noise),
        reverse=HighestFirst)]
    sortedDistance = [x for (y, x) in sorted(zip(Noise,
        ScintillatorDistance), reverse=HighestFirst)]
elif sort == 'distance':
    sortedIDs = [x for (y, x) in sorted(zip(ScintillatorDistance,
        ExperimentID), reverse=HighestFirst)]
    sortedImages = [x for (y, x) in sorted(zip(ScintillatorDistance, Images),
        reverse=HighestFirst)]
    sortedMean = [x for (y, x) in sorted(zip(ScintillatorDistance, Mean),
        reverse=HighestFirst)]
    sortedSTD = [x for (y, x) in sorted(zip(ScintillatorDistance, STD),
        reverse=HighestFirst)]
    sortedFolder = [x for (y, x) in sorted(zip(ScintillatorDistance, Folder),
        reverse=HighestFirst)]
    sortedNoise = [x for (y, x) in sorted(zip(ScintillatorDistance, Noise),
        reverse=HighestFirst)]
    sortedDistance = [x for (y, x) in sorted(zip(ScintillatorDistance,
        ScintillatorDistance), reverse=HighestFirst)]

# Select n top items from sorting criterion
n = 10
print 'Selecting', n, 'images, sorted from',
if HighestFirst:
    print 'highest to lowest',
else:
    print 'lowest to highest',
print sort
sortedIDs = sortedIDs[:n]
sortedImages = sortedImages[:n]
sortedMean = sortedMean[:n]
sortedSTD = sortedSTD[:n]
sortedNoise = sortedNoise[:n]
sortedFolder = sortedFolder[:n]
sortedDistance = sortedDistance[:n]

# Give out info
for c, item in enumerate(sortedIDs):
    print str(c).rjust(2), 'of', len(sortedIDs), '| Mean:', \
        str(round(sortedMean[c], 1)).rjust(5), '| STD:', \
        str(round(sortedSTD[c], 1)).rjust(4), '| Noise', \
        str(round(sortedNoise[c], 1)).rjust(4), '| Distance', \
        str(sortedDistance[c]), '| Experiment', \
        sortedIDs[c].rjust(8), '| Image', os.path.join(sortedFolder[c],
            sortedIDs[c] +
            '.image.corrected.stretched.png')[len(StartingFolder):]

plt.figure(figsize=[23, 10])
for c, i in enumerate(sortedImages):
    plt.subplot(2, len(sortedImages) / 2, c + 1)
    plt.imshow(i, cmap='gray', interpolation='bicubic')
    plt.title(' '.join([str(c), '|', sortedIDs[c], '\nMean',
        str(round(sortedMean[c], 1)), '\nSTD',
        str(round(sortedSTD[c], 1)), '\nNoise',
        str(round(sortedNoise[c], 1)), '\nDistance',
        str(sortedDistance[c]), 'mm\n',
        sortedFolder[c].split('/')[8], '-', sortedFolder[c].split('/')[9],
        '-', sortedFolder[c].split('/')[10]]))
    plt.axis('off')
if HighestFirst:
    plt.suptitle(' '.join(['Images sorted from highest to lowest', sort]))
else:
    plt.suptitle(' '.join(['Images sorted from lowest to highest', sort]))

plt.subplots_adjust(wspace=0.05)
plt.subplots_adjust(hspace=0.05)
plt.axis('off')
plt.tight_layout()

print '\nShowing plot'
plt.show()
<|endoftext|>


<commit_before>from thinglang.common import ValueType
from thinglang.lexer.symbols import LexicalGroupEnd
from thinglang.lexer.symbols.arithmetic import FirstOrderLexicalBinaryOperation, SecondOrderLexicalBinaryOperation
from thinglang.lexer.symbols.base import LexicalParenthesesOpen, LexicalParenthesesClose, LexicalSeparator, \
    LexicalAccess, LexicalAssignment, LexicalIdentifier
from thinglang.lexer.symbols.functions import LexicalReturnStatement, LexicalArgumentListIndicator, \
    LexicalDeclarationMethod, LexicalDeclarationThing
from thinglang.lexer.symbols.logic import LexicalComparison, LexicalConditional, LexicalElse
from thinglang.parser.tokens.arithmetic import ArithmeticOperation
from thinglang.parser.tokens.base import AssignmentOperation
from thinglang.parser.tokens.classes import ThingDefinition, MethodDefinition
from thinglang.parser.tokens.functions import Access, ArgumentListPartial, ArgumentList, MethodCall, ReturnStatement, \
    ArgumentListDecelerationPartial
from thinglang.parser.tokens.logic import Conditional

FIRST_PASS_PATTERNS = [

    ((LexicalDeclarationThing, LexicalIdentifier), ThingDefinition),  # thing Program
    ((LexicalDeclarationMethod, LexicalIdentifier, LexicalGroupEnd), MethodDefinition),  # does start
    ((LexicalDeclarationMethod, LexicalIdentifier, ArgumentList), MethodDefinition),  # does start with a, b

    ((LexicalArgumentListIndicator, ValueType), ArgumentListDecelerationPartial),  # with a

    ((LexicalIdentifier, LexicalAccess, LexicalIdentifier), Access),  # person.name

    ((ValueType, SecondOrderLexicalBinaryOperation, ValueType), ArithmeticOperation),  # 4 * 2
    ((ValueType, FirstOrderLexicalBinaryOperation, ValueType), ArithmeticOperation),  # 4 + 2

    ((ArgumentListPartial, SecondOrderLexicalBinaryOperation, ValueType), ArgumentListPartial),  # (4 * 2
    ((ArgumentListPartial, FirstOrderLexicalBinaryOperation, ValueType), ArgumentListPartial),  # (4 + 2

    ((LexicalParenthesesOpen, LexicalParenthesesClose), ArgumentList),  # ()

    ((LexicalParenthesesOpen, ValueType), ArgumentListPartial),  # (2

    ((ArgumentListDecelerationPartial, LexicalSeparator, ValueType), ArgumentListDecelerationPartial),  # (2, 3
    ((ArgumentListPartial, LexicalSeparator, ValueType), ArgumentListPartial),  # (2, 3

    ((ArgumentListPartial, LexicalParenthesesClose), ArgumentList),  # (2, 3)
    ((ArgumentListDecelerationPartial, LexicalGroupEnd), ArgumentList),  # (2, 3)

    ((LexicalConditional, ValueType, LexicalComparison, ValueType), Conditional),  # if x eq y

    ((Access, ArgumentList), MethodCall),  # person.walk(...)

    ((LexicalIdentifier, LexicalIdentifier, LexicalAssignment, ValueType), AssignmentOperation),  # number n = 1
    ((LexicalIdentifier, LexicalAssignment, ValueType), AssignmentOperation),  # n = 2,

]

SECOND_PASS_PATTERNS = [
    ((LexicalReturnStatement, ValueType), ReturnStatement),  # return 2
    ((LexicalElse,), UnconditionalElse),
]

REPLACEMENT_PASSES = FIRST_PASS_PATTERNS, SECOND_PASS_PATTERNS
<commit_msg>Fix parse patterns to distinguish between conditional and unconditional else branches<commit_after>from thinglang.common import ValueType
from thinglang.lexer.symbols import LexicalGroupEnd
from thinglang.lexer.symbols.arithmetic import FirstOrderLexicalBinaryOperation, SecondOrderLexicalBinaryOperation
from thinglang.lexer.symbols.base import LexicalParenthesesOpen, LexicalParenthesesClose, LexicalSeparator, \
    LexicalAccess, LexicalAssignment, LexicalIdentifier
from thinglang.lexer.symbols.functions import LexicalReturnStatement, LexicalArgumentListIndicator, \
    LexicalDeclarationMethod, LexicalDeclarationThing
from thinglang.lexer.symbols.logic import LexicalComparison, LexicalConditional, LexicalElse
from thinglang.parser.tokens.arithmetic import ArithmeticOperation
from thinglang.parser.tokens.base import AssignmentOperation
from thinglang.parser.tokens.classes import ThingDefinition, MethodDefinition
from thinglang.parser.tokens.functions import Access, ArgumentListPartial, ArgumentList, MethodCall, ReturnStatement, \
    ArgumentListDecelerationPartial
from thinglang.parser.tokens.logic import Conditional, UnconditionalElse, ConditionalElse

FIRST_PASS_PATTERNS = [

    ((LexicalDeclarationThing, LexicalIdentifier), ThingDefinition),  # thing Program
    ((LexicalDeclarationMethod, LexicalIdentifier, LexicalGroupEnd), MethodDefinition),  # does start
    ((LexicalDeclarationMethod, LexicalIdentifier, ArgumentList), MethodDefinition),  # does start with a, b

    ((LexicalArgumentListIndicator, ValueType), ArgumentListDecelerationPartial),  # with a

    ((LexicalIdentifier, LexicalAccess, LexicalIdentifier), Access),  # person.name

    ((ValueType, SecondOrderLexicalBinaryOperation, ValueType), ArithmeticOperation),  # 4 * 2
    ((ValueType, FirstOrderLexicalBinaryOperation, ValueType), ArithmeticOperation),  # 4 + 2

    ((ArgumentListPartial, SecondOrderLexicalBinaryOperation, ValueType), ArgumentListPartial),  # (4 * 2
    ((ArgumentListPartial, FirstOrderLexicalBinaryOperation, ValueType), ArgumentListPartial),  # (4 + 2

    ((LexicalParenthesesOpen, LexicalParenthesesClose), ArgumentList),  # ()

    ((LexicalParenthesesOpen, ValueType), ArgumentListPartial),  # (2

    ((ArgumentListDecelerationPartial, LexicalSeparator, ValueType), ArgumentListDecelerationPartial),  # (2, 3
    ((ArgumentListPartial, LexicalSeparator, ValueType), ArgumentListPartial),  # (2, 3

    ((ArgumentListPartial, LexicalParenthesesClose), ArgumentList),  # (2, 3)
    ((ArgumentListDecelerationPartial, LexicalGroupEnd), ArgumentList),  # (2, 3)

    ((LexicalConditional, ValueType, LexicalComparison, ValueType), Conditional),  # if x eq y

    ((LexicalConditional, ValueType), Conditional),  # if x
    ((LexicalElse, Conditional), ConditionalElse),

    ((Access, ArgumentList), MethodCall),  # person.walk(...)

    ((LexicalIdentifier, LexicalIdentifier, LexicalAssignment, ValueType), AssignmentOperation),  # number n = 1
    ((LexicalIdentifier, LexicalAssignment, ValueType), AssignmentOperation),  # n = 2,

]

SECOND_PASS_PATTERNS = [
    ((LexicalReturnStatement, ValueType), ReturnStatement),  # return 2
    ((LexicalElse,), UnconditionalElse),

]

REPLACEMENT_PASSES = FIRST_PASS_PATTERNS, SECOND_PASS_PATTERNS
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
INSTALL:
    apt-get install postgresql-contrib-9.1

RUN IN DBSHELL
   CREATE EXTENSION IF NOT EXISTS unaccent;

USAGE:

DATABASES = {
    'default': {
        'ENGINE': 'opps.db.postgresql_psycopg2',
        ...
    }
}

SOUTH_DATABASE_ADAPTERS = {
    'default': 'south.db.postgresql_psycopg2'
}

DATABASE_POOL_ARGS = {
    'max_overflow': 10,
    'pool_size': 5,
    'recycle': 300
}
"""
import logging
from functools import partial

from sqlalchemy import event
from sqlalchemy.pool import manage, QueuePool
from psycopg2 import InterfaceError, ProgrammingError, OperationalError

from django.conf import settings
from django.db.backends.postgresql_psycopg2.base import *
from django.db.backends.postgresql_psycopg2.base import \
    DatabaseWrapper as Psycopg2DatabaseWrapper
from django.db.backends.postgresql_psycopg2.base import \
    CursorWrapper as DjangoCursorWrapper
from django.db.backends.postgresql_psycopg2.creation \
    import DatabaseCreation as Psycopg2DatabaseCreation

class DatabaseOperations(DatabaseOperations):
    def lookup_cast(self, lookup_type):
        if lookup_type in('icontains', 'istartswith'):
            return "UPPER(unaccent(%s::text))"
        else:
            return super(DatabaseOperations, self).lookup_cast(lookup_type)

"""
# Uncomment this class to disable the pool
class DatabaseWrapper(DatabaseWrapper):
    def __init__(self, *args, **kwargs):
        super(DatabaseWrapper, self).__init__(*args, **kwargs)
        self.operators['icontains'] = 'LIKE UPPER(unaccent(%s))'
        self.operators['istartswith'] = 'LIKE UPPER(unaccent(%s))'
        self.ops = DatabaseOperations(self)

# comment everything below to disable the pool
"""

POOL_SETTINGS = 'DATABASE_POOL_ARGS'

# DATABASE_POOL_ARGS should be something like:
# {'max_overflow':10, 'pool_size':5, 'recycle':300}
pool_args = getattr(settings, POOL_SETTINGS, {})
db_pool = manage(Database, **pool_args)

log = logging.getLogger('z.pool')

def _log(message, *args):
    log.debug(message)

# Only hook up the listeners if we are in debug mode.
if settings.DEBUG:
    event.listen(QueuePool, 'checkout', partial(_log, 'retrieved from pool'))
    event.listen(QueuePool, 'checkin', partial(_log, 'returned to pool'))
    event.listen(QueuePool, 'connect', partial(_log, 'new connection'))

def is_disconnect(e, connection, cursor):
    """
    Connection state check from SQLAlchemy:
    https://bitbucket.org/sqlalchemy/sqlalchemy/src/tip/
        lib/sqlalchemy/dialects/postgresql/psycopg2.py
    """
    if isinstance(e, OperationalError):
        # these error messages from libpq: interfaces/libpq/fe-misc.c.
        # TODO: these are sent through gettext in libpq and we can't
        # check within other locales - consider using connection.closed
        return 'terminating connection' in str(e) or \
               'closed the connection' in str(e) or \
               'connection not open' in str(e) or \
               'could not receive data from server' in str(e)
    elif isinstance(e, InterfaceError):
        # psycopg2 client errors, psycopg2/conenction.h, psycopg2/cursor.h
        return 'connection already closed' in str(e) or \
               'cursor already closed' in str(e)
    elif isinstance(e, ProgrammingError):
        # not sure where this path is originally from, it may
        # be obsolete.   It really says "losed", not "closed".
        return "losed the connection unexpectedly" in str(e)
    else:
        return False

class CursorWrapper(DjangoCursorWrapper):
    """
    A thin wrapper around psycopg2's normal cursor class so that we can catch
    particular exception instances and reraise them with the right types.

    Checks for connection state on DB API error and invalidates
    broken connections.
    """

    def __init__(self, cursor, connection):
        self.cursor = cursor
        self.connection = connection

    def execute(self, query, args=None):
        try:
            return self.cursor.execute(query, args)
        except Database.IntegrityError, e:
            raise utils.IntegrityError, utils.IntegrityError(
                *tuple(e)), sys.exc_info()[2]
        except Database.DatabaseError, e:
            if is_disconnect(e, self.connection.connection, self.cursor):
                log.error("invalidating broken connection")
                self.connection.invalidate()
            raise utils.DatabaseError, utils.DatabaseError(
                *tuple(e)), sys.exc_info()[2]

    def executemany(self, query, args):
        try:
            return self.cursor.executemany(query, args)
        except Database.IntegrityError, e:
            raise utils.IntegrityError, utils.IntegrityError(
                *tuple(e)), sys.exc_info()[2]
        except Database.DatabaseError, e:
            if is_disconnect(e, self.connection.connection, self.cursor):
                log.error("invalidating broken connection")
                self.connection.invalidate()
            raise utils.DatabaseError, utils.DatabaseError(
                *tuple(e)), sys.exc_info()[2]

class DatabaseCreation(Psycopg2DatabaseCreation):
    def destroy_test_db(self, *args, **kw):
        """Ensure conn pool is disposed before trying to drop database."""
        self.connection._dispose()
        super(DatabaseCreation, self).destroy_test_db(*args, **kw)

class DatabaseWrapper(Psycopg2DatabaseWrapper):
    """SQLAlchemy FTW."""

    def __init__(self, *args, **kwargs):
        super(DatabaseWrapper, self).__init__(*args, **kwargs)
        self.creation = DatabaseCreation(self)
        self.operators['icontains'] = 'LIKE UPPER(unaccent(%s))'
        self.operators['istartswith'] = 'LIKE UPPER(unaccent(%s))'
        self.ops = DatabaseOperations(self)

    def _cursor(self):
        if self.connection is None or self.connection.is_valid is False:
            self.connection = db_pool.connect(**self._get_conn_params())
            self.connection.set_client_encoding('UTF8')
            tz = 'UTC' if settings.USE_TZ else self.settings_dict.get(
                'TIME_ZONE')
            if tz:
                try:
                    get_parameter_status = self.connection.get_parameter_status
                except AttributeError:
                    # psycopg2 < 2.0.12 doesn't have get_parameter_status
                    conn_tz = None
                else:
                    conn_tz = get_parameter_status('TimeZone')

                if conn_tz != tz:
                    # Set the time zone in autocommit mode (see #17062)
                    self.connection.set_isolation_level(
                        psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
                    self.connection.cursor().execute(
                        self.ops.set_time_zone_sql(), [tz])
            self.connection.set_isolation_level(self.isolation_level)
            self._get_pg_version()
            connection_created.send(sender=self.__class__, connection=self)
        cursor = self.connection.cursor()
        cursor.tzinfo_factory = utc_tzinfo_factory if settings.USE_TZ else None
        return CursorWrapper(cursor, self.connection)

    def _commit(self):
        if self.connection is not None and self.connection.is_valid:
            return self.connection.commit()

    def _rollback(self):
        if self.connection is not None and self.connection.is_valid:
            return self.connection.rollback()

    def _dispose(self):
        """Dispose of the pool for this instance, closing all connections."""
        self.close()
        # _DBProxy.dispose doesn't actually call dispose on the pool
        conn_params = self._get_conn_params()
        key = db_pool._serialize(**conn_params)
        try:
            pool = db_pool.pools[key]
        except KeyError:
            pass
        else:
            pool.dispose()
            del db_pool.pools[key]

    def _get_conn_params(self):
        settings_dict = self.settings_dict
        if not settings_dict['NAME']:
            from django.core.exceptions import ImproperlyConfigured
            raise ImproperlyConfigured(
                "settings.DATABASES is improperly configured. "
                "Please supply the NAME value.")
        conn_params = {
            'database': settings_dict['NAME'],
        }
        conn_params.update(settings_dict['OPTIONS'])
        if 'autocommit' in conn_params:
            del conn_params['autocommit']
        if settings_dict['USER']:
            conn_params['user'] = settings_dict['USER']
        if settings_dict['PASSWORD']:
            conn_params['password'] = settings_dict['PASSWORD']
        if settings_dict['HOST']:
            conn_params['host'] = settings_dict['HOST']
        if settings_dict['PORT']:
            conn_params['port'] = settings_dict['PORT']
        return conn_params
<commit_msg>Fix docstring on postgresql db backend<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
INSTALL:
    apt-get install postgresql-contrib-9.1

RUN IN DBSHELL
   CREATE EXTENSION IF NOT EXISTS unaccent;

USAGE:

DATABASES = {
    'default': {
        'ENGINE': 'opps.db.backends.postgresql_psycopg2',
        ...
    }
}

SOUTH_DATABASE_ADAPTERS = {
    'default': 'south.db.postgresql_psycopg2'
}

DATABASE_POOL_ARGS = {
    'max_overflow': 10,
    'pool_size': 5,
    'recycle': 300
}
"""
import logging
from functools import partial

from sqlalchemy import event
from sqlalchemy.pool import manage, QueuePool
from psycopg2 import InterfaceError, ProgrammingError, OperationalError

from django.conf import settings
from django.db.backends.postgresql_psycopg2.base import *
from django.db.backends.postgresql_psycopg2.base import \
    DatabaseWrapper as Psycopg2DatabaseWrapper
from django.db.backends.postgresql_psycopg2.base import \
    CursorWrapper as DjangoCursorWrapper
from django.db.backends.postgresql_psycopg2.creation \
    import DatabaseCreation as Psycopg2DatabaseCreation

class DatabaseOperations(DatabaseOperations):
    def lookup_cast(self, lookup_type):
        if lookup_type in('icontains', 'istartswith'):
            return "UPPER(unaccent(%s::text))"
        else:
            return super(DatabaseOperations, self).lookup_cast(lookup_type)

"""
# Uncomment this class to disable the pool
class DatabaseWrapper(DatabaseWrapper):
    def __init__(self, *args, **kwargs):
        super(DatabaseWrapper, self).__init__(*args, **kwargs)
        self.operators['icontains'] = 'LIKE UPPER(unaccent(%s))'
        self.operators['istartswith'] = 'LIKE UPPER(unaccent(%s))'
        self.ops = DatabaseOperations(self)

# comment everything below to disable the pool
"""

POOL_SETTINGS = 'DATABASE_POOL_ARGS'

# DATABASE_POOL_ARGS should be something like:
# {'max_overflow':10, 'pool_size':5, 'recycle':300}
pool_args = getattr(settings, POOL_SETTINGS, {})
db_pool = manage(Database, **pool_args)

log = logging.getLogger('z.pool')

def _log(message, *args):
    log.debug(message)

# Only hook up the listeners if we are in debug mode.
if settings.DEBUG:
    event.listen(QueuePool, 'checkout', partial(_log, 'retrieved from pool'))
    event.listen(QueuePool, 'checkin', partial(_log, 'returned to pool'))
    event.listen(QueuePool, 'connect', partial(_log, 'new connection'))

def is_disconnect(e, connection, cursor):
    """
    Connection state check from SQLAlchemy:
    https://bitbucket.org/sqlalchemy/sqlalchemy/src/tip/
        lib/sqlalchemy/dialects/postgresql/psycopg2.py
    """
    if isinstance(e, OperationalError):
        # these error messages from libpq: interfaces/libpq/fe-misc.c.
        # TODO: these are sent through gettext in libpq and we can't
        # check within other locales - consider using connection.closed
        return 'terminating connection' in str(e) or \
               'closed the connection' in str(e) or \
               'connection not open' in str(e) or \
               'could not receive data from server' in str(e)
    elif isinstance(e, InterfaceError):
        # psycopg2 client errors, psycopg2/conenction.h, psycopg2/cursor.h
        return 'connection already closed' in str(e) or \
               'cursor already closed' in str(e)
    elif isinstance(e, ProgrammingError):
        # not sure where this path is originally from, it may
        # be obsolete.   It really says "losed", not "closed".
        return "losed the connection unexpectedly" in str(e)
    else:
        return False

class CursorWrapper(DjangoCursorWrapper):
    """
    A thin wrapper around psycopg2's normal cursor class so that we can catch
    particular exception instances and reraise them with the right types.

    Checks for connection state on DB API error and invalidates
    broken connections.
    """

    def __init__(self, cursor, connection):
        self.cursor = cursor
        self.connection = connection

    def execute(self, query, args=None):
        try:
            return self.cursor.execute(query, args)
        except Database.IntegrityError, e:
            raise utils.IntegrityError, utils.IntegrityError(
                *tuple(e)), sys.exc_info()[2]
        except Database.DatabaseError, e:
            if is_disconnect(e, self.connection.connection, self.cursor):
                log.error("invalidating broken connection")
                self.connection.invalidate()
            raise utils.DatabaseError, utils.DatabaseError(
                *tuple(e)), sys.exc_info()[2]

    def executemany(self, query, args):
        try:
            return self.cursor.executemany(query, args)
        except Database.IntegrityError, e:
            raise utils.IntegrityError, utils.IntegrityError(
                *tuple(e)), sys.exc_info()[2]
        except Database.DatabaseError, e:
            if is_disconnect(e, self.connection.connection, self.cursor):
                log.error("invalidating broken connection")
                self.connection.invalidate()
            raise utils.DatabaseError, utils.DatabaseError(
                *tuple(e)), sys.exc_info()[2]

class DatabaseCreation(Psycopg2DatabaseCreation):
    def destroy_test_db(self, *args, **kw):
        """Ensure conn pool is disposed before trying to drop database."""
        self.connection._dispose()
        super(DatabaseCreation, self).destroy_test_db(*args, **kw)

class DatabaseWrapper(Psycopg2DatabaseWrapper):
    """SQLAlchemy FTW."""

    def __init__(self, *args, **kwargs):
        super(DatabaseWrapper, self).__init__(*args, **kwargs)
        self.creation = DatabaseCreation(self)
        self.operators['icontains'] = 'LIKE UPPER(unaccent(%s))'
        self.operators['istartswith'] = 'LIKE UPPER(unaccent(%s))'
        self.ops = DatabaseOperations(self)

    def _cursor(self):
        if self.connection is None or self.connection.is_valid is False:
            self.connection = db_pool.connect(**self._get_conn_params())
            self.connection.set_client_encoding('UTF8')
            tz = 'UTC' if settings.USE_TZ else self.settings_dict.get(
                'TIME_ZONE')
            if tz:
                try:
                    get_parameter_status = self.connection.get_parameter_status
                except AttributeError:
                    # psycopg2 < 2.0.12 doesn't have get_parameter_status
                    conn_tz = None
                else:
                    conn_tz = get_parameter_status('TimeZone')

                if conn_tz != tz:
                    # Set the time zone in autocommit mode (see #17062)
                    self.connection.set_isolation_level(
                        psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
                    self.connection.cursor().execute(
                        self.ops.set_time_zone_sql(), [tz])
            self.connection.set_isolation_level(self.isolation_level)
            self._get_pg_version()
            connection_created.send(sender=self.__class__, connection=self)
        cursor = self.connection.cursor()
        cursor.tzinfo_factory = utc_tzinfo_factory if settings.USE_TZ else None
        return CursorWrapper(cursor, self.connection)

    def _commit(self):
        if self.connection is not None and self.connection.is_valid:
            return self.connection.commit()

    def _rollback(self):
        if self.connection is not None and self.connection.is_valid:
            return self.connection.rollback()

    def _dispose(self):
        """Dispose of the pool for this instance, closing all connections."""
        self.close()
        # _DBProxy.dispose doesn't actually call dispose on the pool
        conn_params = self._get_conn_params()
        key = db_pool._serialize(**conn_params)
        try:
            pool = db_pool.pools[key]
        except KeyError:
            pass
        else:
            pool.dispose()
            del db_pool.pools[key]

    def _get_conn_params(self):
        settings_dict = self.settings_dict
        if not settings_dict['NAME']:
            from django.core.exceptions import ImproperlyConfigured
            raise ImproperlyConfigured(
                "settings.DATABASES is improperly configured. "
                "Please supply the NAME value.")
        conn_params = {
            'database': settings_dict['NAME'],
        }
        conn_params.update(settings_dict['OPTIONS'])
        if 'autocommit' in conn_params:
            del conn_params['autocommit']
        if settings_dict['USER']:
            conn_params['user'] = settings_dict['USER']
        if settings_dict['PASSWORD']:
            conn_params['password'] = settings_dict['PASSWORD']
        if settings_dict['HOST']:
            conn_params['host'] = settings_dict['HOST']
        if settings_dict['PORT']:
            conn_params['port'] = settings_dict['PORT']
        return conn_params
<|endoftext|>