def __init__(self, parent=None): super().__init__(parent) self.setupUi(self) self.sql_helper = SQLHelper('decisions.db') self.decision_list = [] self.refresh_decision_list() self.tmp_decision = Decision(None, "") self.search_list = [] # Buttons self.pushButtonAdd.clicked.connect(self.add_decision_button) self.pushButtonAddOptions.clicked.connect(self.add_option_button) self.pushButtonClear.clicked.connect(self.clear_button) self.pushButtonDelete.clicked.connect(self.delete_button) self.pushButtonDecide.clicked.connect(self.decide_button) self.pushButtonModify.clicked.connect(self.modify_button) self.pushButtonClearFilter.clicked.connect(self.clear_filter_button) # Search Input self.lineEditSearch.textChanged.connect(self.search) self.refresh_decision_list()
def startExperiment(self): if not self.isConfigLoaded: messagebox.showerror("Error", "Please load configuration file") elif not self.isArdConnected: messagebox.showerror("Error", "Please connect Arduino") else: try: sessionName = self.sessionNameEntry.get() numOfTrials = self.numOfTrialsEntry.get() if sessionName == "" or numOfTrials == "": raise Exception("Please fill in all values") numOfTrials = int(numOfTrials) self.experiment = Decision(self.ard) self.experiment.startExperiment(sessionName, numOfTrials, self.configFileName) except Exception as e: messagebox.showerror("Error", e)
def add_decision_button(self): self.tmp_decision.string = self.lineEditDecision.text() if self.tmp_decision.string == "": QMessageBox.warning(self, "Missing parameter", "Please add a valid decision decision!") return if len(self.tmp_decision.options) < 2: QMessageBox.warning(self, "Missing parameter", "You need more options!") return self.sql_helper.add_decision_object(self.tmp_decision) self.tmp_decision = Decision(None, "") self.lineEditDecision.clear() self.listWidgetOptions.clear() self.refresh_decision_list() self.lineEditDecision.setFocus()
def get_decision(self, q_id): sql = "SELECT * FROM decisions WHERE decision_id={}".format(q_id) self.cursor.execute(sql) decision = self.cursor.fetchall() if decision: ret = Decision(decision[0][0], decision[0][1]) sql = "SELECT * FROM options WHERE decision_id={}".format(q_id) self.cursor.execute(sql) options = self.cursor.fetchall() for option in options: ret.options.append(Option(option[1], option[0], option[2])) return ret
def sign_up_page(): if request.method == 'GET': return render_template("sign_up.html") else: username = request.form['reg_username'] password = request.form['reg_password'] #for the salt create 16 character long salt and use it for hash user_id = "" for i in range(16): user_id = user_id + (random.choice(ALPHABET)) #hashed_password = hash.sha512_crypt.using(salt=salt).hash(password) hashed_password = hash.sha512_crypt.using(salt_size=4).hash(password) #k = hash.sha512_crypt.verify(password, hashed_password) for verifying hash email = request.form['reg_email'] name = request.form['reg_name'] surname = request.form['reg_surname'] if request.form['reg_gender'] == "male": gender = 'M' else: gender = 'F' new_user = User(username=username, email=email, name=name, surname=surname, password=hashed_password, user_id=user_id, gender=gender, reg_date=datetime.now()) session.add(new_user) '''Abstract decision ''' abstracts = get_abstract_id() for abs in abstracts: new_decision = Decision(email, abs.abstract_id, None, None, None) session.add(new_decision) try: session.commit() form = LoginForm() next_page = request.args.get('next', url_for('sign_in.sign_in_page')) return redirect(next_page) except exc.SQLAlchemyError: flash("Problem!!") session.rollback() flash('Invalid Credentials') return render_template("home.html")
def getIndexOfDecision(array): decisions = getDecisions(array) result = [] for x in decisions: decisionObject = Decision() decisionObject.setDecision(x) list = [] for i in range(len(array)): if array[i][len(array[i]) - 1] == x: list.append(i) decisionObject.setIndexList(list) result.append(decisionObject) return result
class DecisionScreen(QMainWindow, DecisionScreen.Ui_MainWindow): def __init__(self, parent=None): super().__init__(parent) self.setupUi(self) self.sql_helper = SQLHelper('decisions.db') self.decision_list = [] self.refresh_decision_list() self.tmp_decision = Decision(None, "") self.search_list = [] # Buttons self.pushButtonAdd.clicked.connect(self.add_decision_button) self.pushButtonAddOptions.clicked.connect(self.add_option_button) self.pushButtonClear.clicked.connect(self.clear_button) self.pushButtonDelete.clicked.connect(self.delete_button) self.pushButtonDecide.clicked.connect(self.decide_button) self.pushButtonModify.clicked.connect(self.modify_button) self.pushButtonClearFilter.clicked.connect(self.clear_filter_button) # Search Input self.lineEditSearch.textChanged.connect(self.search) self.refresh_decision_list() def search(self): search_string = self.lineEditSearch.text() if not search_string: # Show original self.refresh_decision_list() else: self.clearDecisionList() for decision in self.decision_list: if fnmatch.fnmatch(decision.string, "*{}*".format(search_string)): self.listWidgetDecisions.addItem(decision.string) def add_option_button(self): dialog = AddOptionDialog(self.tmp_decision) self.listWidgetOptions.clear() if dialog.exec_() == QDialog.Accepted: for option in self.tmp_decision.options: self.listWidgetOptions.addItem(option) def add_decision_button(self): self.tmp_decision.string = self.lineEditDecision.text() if self.tmp_decision.string == "": QMessageBox.warning(self, "Missing parameter", "Please add a valid decision decision!") return if len(self.tmp_decision.options) < 2: QMessageBox.warning(self, "Missing parameter", "You need more options!") return self.sql_helper.add_decision_object(self.tmp_decision) self.tmp_decision = Decision(None, "") self.lineEditDecision.clear() self.listWidgetOptions.clear() self.refresh_decision_list() self.lineEditDecision.setFocus() def clear_filter_button(self): self.lineEditSearch.clear() self.search() def clear_button(self): self.tmp_decision.clear() self.clearDecisionList() self.lineEditDecision.clear() self.lineEditDecision.setFocus() def clearDecisionList(self): while self.listWidgetDecisions.count() > 0: self.listWidgetDecisions.takeItem(0) def decide_button(self): row = self.listWidgetDecisions.selectedIndexes() if (row): decision_string = self.listWidgetDecisions.currentItem().text() decision = self.sql_helper.get_decision_string(decision_string) option_index = random.randint(0, len(decision.options) - 1) option = decision.options[option_index].string reply = "Decision: \n\n{}".format(option) QMessageBox.question(self, decision.string, reply, QMessageBox.Ok) else: QMessageBox.warning(self, "", "Decision must be selected first", QMessageBox.Ok) def delete_button(self): row = self.listWidgetDecisions.selectedIndexes() if (row): decision_string = self.listWidgetDecisions.currentItem().text() self.sql_helper.remove_decision_string(decision_string) self.refresh_decision_list() self.search() else: QMessageBox.warning(self, "", "Decision must be selected first", QMessageBox.Ok) def modify_button(self): row = self.listWidgetDecisions.selectedIndexes() if (row): decision_string = self.listWidgetDecisions.currentItem().text() decision = self.sql_helper.get_decision_string(decision_string) dialog = EditOptionDialog(decision, self.sql_helper) if dialog.exec_() == QDialog.Accepted: self.refresh_decision_list() self.search() else: QMessageBox.warning(self, "", "Decision must be selected first", QMessageBox.Ok) def refresh_decision_list(self): self.listWidgetDecisions.clear() self.decision_list = self.sql_helper.get_all_decisions() for decision in self.decision_list: self.listWidgetDecisions.addItem(decision.string) self.listWidgetDecisions.show()
from flask import Flask, jsonify, request, Response from flask_cors import CORS, cross_origin from Scraper import Scraper from Decision import Decision app = Flask(__name__) cors = CORS(app) app.config['CORS_HEADERS'] = 'Content-Type' scraper = Scraper() analyser = Decision() # We call scrape after the button has been clicked to check the review @app.route('/should-i-buy', methods=['GET']) @cross_origin() def check_product(): url = request.args.get('url') if url: try: json_data = scraper.scrape(url) except: return 'No reviews found', 404 else: # figure out error handling here return Response('No url provided', status=400) # call sentiment analysis class on the data # received, returns the decision, clean the image url decision = analyser.sentiment_analysis(json_data)
elif sys.argv[1] == "approche": demo = 3 elif sys.argv[1] == "ramasse": demo = 4 elif sys.argv[1] == "approcheRamasse": demo = 5 elif sys.argv[1] == "lancer": demo = 6 else: print "Paramètre ", sys.argv[1], " inconnu" exit(1) while True: try: print "start" de = Decision() de.initialisation() if calibrage is True: filtre = FilterColor() filtre.calibrage() calibrage = False #Calibrage effecté, on ne le recommencera pas de.run(demo) #On lance notre demonstration break except KeyboardInterrupt: break """ except Exception as e:#en cas d'exception non prévu par les développeurs le code redémarre print "error ",e print "restart dans 3 secondes"
class DecisionGui: def __init__(self, root=Tk()): self.root = root self.root.title("Decision Experiment") self.root.configure(bg=BACKGROUND_COLOR) self.titleLabel = Label(self.root, text='Decision Experiment', font=STATUS_FONT, bg=BACKGROUND_COLOR) self.ard = None self.experiment = None self.isConfigLoaded = False self.isArdConnected = False self.isPumpOn = False self.estTime = StringVar() self.lickCount = IntVar() self.lickCount.set(0) self.isSoundOn = BooleanVar() self.stopUpdating = threading.Event() self.ardUpdater = threading.Thread(target=self.updateVariable) port = MouseArduino.getUnoPort() #Frames self.master = Frame(root, bg=BACKGROUND_COLOR) self.master.grid_rowconfigure(0) self.master.grid_rowconfigure(1) self.master.grid_rowconfigure(2, weight=5) self.master.grid_columnconfigure(0, weight=1) self.master.grid_columnconfigure(1, weight=1) self.master.grid_columnconfigure(2, weight=1) self.ardInitFrame = Frame(self.master, bd=3, relief='groove', bg=BACKGROUND_COLOR) self.ardControlFrame = Frame(self.master, bd=3, relief='groove', bg=BACKGROUND_COLOR) self.initFrame = Frame(self.master, bd=3, relief='groove', bg=BACKGROUND_COLOR) self.argFrame = Frame(self.master, bd=3, relief='groove', bg=BACKGROUND_COLOR) self.finalControlFrame = Frame(self.master, bd=3, relief='groove', bg=BACKGROUND_COLOR) #ardInitFrame self.ardInitFrameLabel = Label(self.ardInitFrame, text="Connect to Hardware", bg=HEADER_COLOR, font=LARGE_FONT, fg='black', borderwidth=2, width=40) self.comLabel = Label(self.ardInitFrame, bg=BACKGROUND_COLOR, text="Com Port:", font=TEXT_FONT) self.comEntry = Entry(self.ardInitFrame, font=TEXT_FONT) self.baudrateLabel = Label(self.ardInitFrame, bg=BACKGROUND_COLOR, text="Baudrate:", font=TEXT_FONT) self.baudrateEntry = Entry(self.ardInitFrame, font=TEXT_FONT) self.connectButton = Button(self.ardInitFrame, text="Connect", font=STATUS_FONT, command=self.connect) self.ardInitFrameLabel.grid(row=0, columnspan=2, padx=40, pady=10) self.comLabel.grid(row=1, column=0, sticky=tk.E) self.comEntry.grid(row=1, column=1, sticky=tk.W) self.baudrateLabel.grid(row=2, column=0, sticky=tk.E) self.baudrateEntry.grid(row=2, column=1, sticky=tk.W) self.connectButton.grid(row=3, columnspan=2, pady=10) self.comEntry.insert(0, port) self.baudrateEntry.insert(0, 115200) #ardControlFrame self.ardControlFrameLabel = Label(self.ardControlFrame, text='Pre-experiment Control', bg=HEADER_COLOR, font=LARGE_FONT, fg='black', borderwidth=2, width=40) self.sendStringEntry = Entry(self.ardControlFrame, font=TEXT_FONT, width=20) self.sendStringButton = Button(self.ardControlFrame, text='Send String', font=TEXT_FONT, bg=BACKGROUND_COLOR, command=self.sendString) self.rewardButton = Button(self.ardControlFrame, text='Reward(R)', font=STATUS_FONT, width=10, bg=BACKGROUND_COLOR, command=self.deliverReward, height=1) self.pumpButton = Button(self.ardControlFrame, text='Pump Water(P)', font=STATUS_FONT, command=self.togglePump, bg=OFF_COLOR, width=12, height=1) self.lickLabel = Label(self.ardControlFrame, text='LICK', bg=LICK_OFF_COLOR, font=LICK_FONT, width=10, height=1) self.lickCountLabel = Label(self.ardControlFrame, text='Lick Count :', bg=BACKGROUND_COLOR, font=LARGE_FONT) self.lickCountButton = Button(self.ardControlFrame, textvariable=self.lickCount, font=LARGE_FONT, bg=BACKGROUND_COLOR, command=lambda: self.lickCount.set(0)) self.soundCheckButton = Checkbutton(self.ardControlFrame, text='Lick Sound', variable=self.isSoundOn, bg=BACKGROUND_COLOR) self.ardControlFrameLabel.grid(row=0, columnspan=2, padx=40, pady=10) self.sendStringEntry.bind('<Return>', self.sendString) self.sendStringEntry.grid(row=1, column=0, padx=5, sticky=tk.E) self.sendStringEntry.bind('<Escape>', lambda x: self.master.focus()) self.sendStringButton.grid(row=1, column=1, padx=5, sticky=tk.W) self.rewardButton.grid(row=2, column=0, pady=10) self.pumpButton.grid(row=2, column=1, pady=10) self.lickLabel.grid(row=3, columnspan=2, pady=15) self.lickCountLabel.grid(row=4, column=0, sticky=tk.E) self.lickCountButton.grid(row=4, column=1, sticky=tk.W) self.soundCheckButton.grid(row=5, columnspan=2) #initFrame self.initFrameLabel = Label(self.initFrame, text="Session Configuration", font=LARGE_FONT, bg=HEADER_COLOR, fg='black', borderwidth=2, width=40) self.loadButton = Button(self.initFrame, text="Load Config(L)", font=STATUS_FONT, command=self.selectFile) self.sessionNameLabel = Label(self.initFrame, text="Session Name:", font=TEXT_FONT, bg=BACKGROUND_COLOR) self.sessionNameEntry = Entry(self.initFrame, font=TEXT_FONT) self.numOfTrialsLabel = Label(self.initFrame, text="Number of Trials:", font=TEXT_FONT, bg=BACKGROUND_COLOR) self.numOfTrialsEntry = Entry(self.initFrame, font=TEXT_FONT) self.numOfTrialsEntry.bind('<KeyRelease>', self.updateTime) self.numOfTrialsEntry.bind('<Escape>', lambda x: self.master.focus()) self.initFrameLabel.grid(row=0, columnspan=2, padx=40, pady=10) self.sessionNameLabel.grid(row=1, column=0, sticky=tk.E) self.sessionNameEntry.grid(row=1, column=1, sticky=tk.W) self.sessionNameEntry.bind('<Escape>', lambda x: self.master.focus()) self.numOfTrialsLabel.grid(row=2, column=0, sticky=tk.E) self.numOfTrialsEntry.grid(row=2, column=1, sticky=tk.W) self.loadButton.grid(row=3, columnspan=2, pady=10) #finalControlFrame self.finalControlFrameLabel = Label(self.finalControlFrame, text='Experiment Control', bg=HEADER_COLOR, font=LARGE_FONT, fg='black', bd=2, width=40) self.estTimeLabel = Label(self.finalControlFrame, textvariable=self.estTime, font=STATUS_FONT, bg=BACKGROUND_COLOR) self.startButton = Button(self.finalControlFrame, text="START EXPERIMENT", font='Helvetica 20 bold', command=self.startExperiment) self.finalControlFrameLabel.grid(padx=40, pady=10) self.estTimeLabel.grid(pady=10) self.startButton.grid(pady=15) #master self.titleLabel.pack(pady=5) self.master.pack(padx=20, pady=20) self.initFrame.grid(row=0, column=0) self.ardInitFrame.grid(row=1, column=0) self.finalControlFrame.grid(row=2, column=0, sticky='NSWE') self.argFrame.grid(row=0, column=1, rowspan=3, sticky='NSWE') for frame in [ self.master, self.initFrame, self.ardInitFrame, self.finalControlFrame, self.argFrame ]: frame.bind('r', self.deliverReward) frame.bind('p', self.togglePump) frame.bind('l', self.selectFile) frame.bind('R', self.deliverReward) frame.bind('P', self.togglePump) frame.bind('L', self.selectFile) frame.bind("<Button-1>", lambda e: self.master.focus_set()) self.updateTime() def run(self): self.master.mainloop() def selectFile(self, event=None): fileName = filedialog.askopenfilename() self.configFileName = fileName for widget in self.argFrame.winfo_children(): widget.destroy() self.argFrameLabel = Label(self.argFrame, text="Experiment Configuration: " + os.path.basename(fileName), font=LARGE_FONT, bg=HEADER_COLOR, fg='black', bd=2, width=40).grid(columnspan=2, padx=40, pady=10) try: with open(fileName) as f: self.args = json.load(f) except Exception as e: print(e) argToLen = lambda x: len(str(x)) maxArgNameLength = argToLen( max(self.args.keys(), key=lambda x: argToLen(x))) maxArgValueLength = argToLen( max(self.args.values(), key=lambda x: argToLen(x))) self.trialDuration = self.args["Rule duration"] +\ self.args["Delay duration"] +\ self.args["Stimulus duration"] + \ self.args["Wrong response flash duration"] + \ self.args["Wrong response rest duration"] for i, (argName, value) in enumerate( sorted(self.args.items(), key=lambda item: item[0])): lName = Label(self.argFrame, text=str(argName) + " :", font='Helvetica 12 bold', bg=BACKGROUND_COLOR).grid(row=i + 3, column=0, sticky=tk.E) lValue = Label(self.argFrame, text=str(value), bg=BACKGROUND_COLOR).grid( row=i + 3, column=1, sticky=tk.W, ) self.updateTime() self.isConfigLoaded = True def connect(self): try: comport = self.comEntry.get() baudrate = self.baudrateEntry.get() if comport == "" or baudrate == "": raise Exception("Please fill in all values") baudrate = int(baudrate) self.ard = MouseArduino(comport, baudrate) self.ard.start() self.ardInitFrame.destroy() self.ardUpdater.start() self.ardControlFrame.grid(row=1, column=0) self.isArdConnected = True except Exception as e: messagebox.showerror( "Error", "Could not connect to Arduino. Make sure port is correct or other program isn't grabbing the port :" + str(e)) def deliverReward(self, event=None): self.ard.deliverReward() def sendString(self, event=None): self.ard.write(self.sendStringEntry.get()) self.sendStringEntry.delete(0, 'end') def updateVariable(self): while not self.stopUpdating.is_set(): if self.ard.newMsg.wait(1): while not self.ard.msgQueue.empty(): self.ard.newMsg.clear() msg = self.ard.msgQueue.get() print(msg) args = Utilities.parse(msg) arg = args[1].strip() if arg == 'LK': self.lickCount.set(self.lickCount.get() + 1) self.lickLabel.configure(bg=ON_COLOR) if self.isSoundOn.get(): Sound.cue(0.05) time.sleep(0.2) self.lickLabel.configure(bg=LICK_OFF_COLOR) elif arg == 'startpump': self.pumpButton.configure(bg=ON_COLOR) self.isPumpOn = True elif arg == 'stoppump': self.pumpButton.configure(bg=OFF_COLOR) self.isPumpOn = False def togglePump(self, event=None): if self.isPumpOn: self.ard.stopPump() else: self.ard.startPump() def updateTime(self, event=None): numOfTrials = self.numOfTrialsEntry.get() try: totalDuration = self.trialDuration * int(numOfTrials) tmin = totalDuration // 60 tsec = totalDuration % 60 timeStr = "{:.0f} Min {:.0f} Sec".format(tmin, tsec) except Exception as e: timeStr = "" print(e) self.estTime.set("Estimated duration: {:>10}".format(timeStr)) def startExperiment(self): if not self.isConfigLoaded: messagebox.showerror("Error", "Please load configuration file") elif not self.isArdConnected: messagebox.showerror("Error", "Please connect Arduino") else: try: sessionName = self.sessionNameEntry.get() numOfTrials = self.numOfTrialsEntry.get() if sessionName == "" or numOfTrials == "": raise Exception("Please fill in all values") numOfTrials = int(numOfTrials) self.experiment = Decision(self.ard) self.experiment.startExperiment(sessionName, numOfTrials, self.configFileName) except Exception as e: messagebox.showerror("Error", e)