def main(): cur_user = users.add_user() while True: create = Create(shared, cur_user) edit = Edit(shared, cur_user) read = Read(shared, cur_user) print(f"\nCurrent User: {cur_user}") choice = main_menu_funct() if choice == 0: break if choice == 1: create.create() if choice == 2: read.read_by_date() if choice == 3: read.read_all() if choice == 4: edit.modify() if choice == 5: edit.remove() if choice == 6: cur_user = users.add_user() if choice == 7: cur_user = users.load_user() if choice == 8: save()
def main(_): from create import Create create = Create() create.create() from train import NLKExtract train = NLKExtract() train.train()
def main(self): c = Create(.5) p1 = Process(1.0, 2) p21 = Process(4.0, 1) p22 = Process(3.0, 2) p3 = Process(1.2, 1) print('id0 = {} id1= {} '.format(c.getId(), p1.getId())) c.setNextElement(p1) p1.setMaxqueue(5) p21.setMaxqueue(3) p22.setMaxqueue(2) p3.setMaxqueue(2) c.setName('CREATOR') p1.setName('PROCESSOR1') p21.setName('PROCESSOR21') p22.setName('PROCESSOR22') p3.setName('PROCESSOR3') c.setDistribution('exp') p1.setDistribution('exp') p21.setDistribution('exp') p22.setDistribution('exp') p3.setDistribution('exp') p1.setNextElements([p21, p22]) p21.setNextElements([p3]) p22.setNextElements([p3]) elementsList = [c, p1, p21, p22, p3] model = Model(elementsList) model.simulate(1000.0)
def createElements(self, count): c = Create(2) c.name = 'CREATOR' elementsList = [c] for i in range(1, count): e = Process(random.choice(self.delays), 1) e.maxQueue = 124325435 e.name = 'PROCESSOR {}'.format(i) c.nextElements.append(e) elementsList.append(e) return elementsList
def mainMenu(): print('''Main Menu -------------------------------------------- 1. View Data 2. Create Data 3. Update Data --------------------------------------------''') mainMenuInput = input("Input choice(q to Quit): ") mainMenuInput = mainMenuInput.lower() if mainMenuInput == "1": viewMenuOutput = View.viewMenu() if viewMenuOutput == "b": ProgramUI.mainMenu() elif viewMenuOutput == "q": return viewMenuOutput elif mainMenuInput == "2": createMenuOutput = Create.createMenu() if createMenuOutput == "b": ProgramUI.mainMenu() elif createMenuOutput == "q": return createMenuOutput elif mainMenuInput == "3": updateMenuOutput = Update.updateMenu() if updateMenuOutput == "b": ProgramUI.mainMenu() elif updateMenuOutput == "q": return updateMenuOutput elif mainMenuInput == "q": return mainMenuInput else: print("Wrong input, try again") ProgramUI.mainMenu()
def main(self): c = Create(15) c.setDistribution('exp') c.setName('creator') p0 = Doctor(0, 0, 2) p0.setName('doctors') p0.setDistribution('exp') p1 = Process(3, 8, 3) p1.setName('chambers') p1.setDistribution('unif') #p1.setDistribution('exp') p2 = Process(3, 4.5, 1) p2.setName('registration') #p2.set_distribution('erlang') p2.setDistribution('exp') #p2.maxQueue = 2 p3 = Labs(2, 4, 2) p3.setName('lab') p3.setDistribution('exp') #p3.set_distribution('erlang') #p0.chambers = p1 #p0.registration = p2 c.nextElement = p0 p0.setNextElements([p1, p2]) p2.setNextElements([p3]) p3.setNextElements([p0]) elementsList = [c, p0, p1, p2, p3] model = Model(elementsList) model.simulate(10000.0)
def main(): print('Available Options: C=Create, R=Read, U=Update, D=Delete ') choice = input('Choose your option = ') if choice == 'C': createObj=Create() createObj.func_CreateData() elif choice == 'R': readObj = Read() readObj.func_ReadData() elif choice == 'U': updateObj = Update() updateObj.func_UpdateData() elif choice == 'D': deleteObj = Delete() deleteObj.func_DeleteData() else: print('Wrong choice, You are going exist.')
def createdriver(): try: if request.method == "GET": logging.debug("incoming GET request: " + str(dict(request.args))) driver_number = request.args["number"] response = Create.check_driver_repetition(driver_number) logging.debug("createdriver returned: " + str(response)) return response if request.method == "POST": logging.debug("incoming POST request: " + str(request.form)) driver_name = request.form["name"] driver_number = request.form["number"] response = Create.create_user(driver_number, driver_name) logging.debug("createuser returned:\n" + str(response)) return response except RuntimeError as e: logging.critical("failure in v1/createuser with error: " + str(e)) return default_error
def main(): while 1: print( 'Available Options: C=Create, R=Read, U=Update, D=Delete, E=Exit ') choice = input('Choose your option = ') if choice == 'C': createObj = Create() createObj.func_CreateData() elif choice == 'R': readObj = Read() readObj.func_ReadData() elif choice == 'U': updateObj = Update() updateObj.func_UpdateData() elif choice == 'D': deleteObj = Delete() deleteObj.func_DeleteData() elif choice == 'E': break
def createuser(): try: if request.method == "GET": logging.info(" Incoming request:\n" + str(request.args)) user_number = request.args["number"] response = Create.check_user_repetition(user_number) logging.info(" Response:\n" + str(response)) with app.app_context(): response = make_response(response) return response if request.method == "POST": logging.info(" Incoming request:\n" + str(request.args)) user_name = request.form["name"] user_number = request.form["number"] response = Create.create_user(user_number, user_name) logging.info(" Response:\n" + str(response)) with app.app_context(): response = make_response(response) return response except RuntimeError as e: logging.critical(" Failure in v1/createuser with error: " + str(e)) return default_error
def updatedriver(): try: if request.method == "POST": number = request.form["number"] name = request.form["name"] photo_link = request.args["profile_pic_link"] response = Create.update_user(number, name, photo_link) logging.debug("Responded to update driver request") return response except RuntimeError as e: logging.critical("failure in v1/updateriver with error: " + str(e) + " |for request: " + str(dict(request.args))) return default_error
def __init__(self): super().__init__() self.__create = Create(self) self.btn_restart = QPushButton('Start', self) self.new_game = QPushButton('New game', self) self.set_chip = QPushButton('Set chip', self) self.btn_show_statistic = QPushButton('Show statistic', self) self.le = QLineEdit(self) self.text = QTextEdit(self) self.set_player1 = QComboBox(self) self.set_player2 = QComboBox(self) self.init_comboBox() self.init_base_ui()
def __init__(self): pygame.init() # Setting variables self.pathToProjects = "" # Getting launcher settings self.getLauncherSettings() # Launcher window self.window = pygame.display.set_mode(SIZE) pygame.display.set_caption("Launcher") # Launcher icon launcherIcon = loadImage("launcher/icon.png") pygame.display.set_icon(launcherIcon) # Current folder self.currentFolder = os.getcwd() # Boolean variables self.running = True # Clock self.clock = pygame.time.Clock() # Launcher self.launcher = Launcher() # Create self.create = Create(self.pathToProjects) # Path self.path = "" # Gameloop self.loop()
def updateuser(): try: if request.method == "POST": logging.info(" Incoming request:\n" + str(request.form)) number = request.form["number"] name = request.form["name"] photo_link = request.form["profile_pic_link"] response = Create.update_user(number, name, photo_link) logging.info(" Response:\n" + str(response)) with app.app_context(): response = make_response(response) return response except RuntimeError as e: logging.critical(" Failure in v1/updateuser with error: " + str(e)) return default_error
def main(self): c = Create(2) p1 = Process(.6, 1) p2 = Process(.3, 1) p3 = Process(.4, 1) p4 = Process(.1, 2) print('id0 = {} id1= {} '.format(c.getId(), p1.getId())) c.setNextElement(p1) c.setName('CREATOR') p1.setName('PROCESSOR1') p2.setName('PROCESSOR2') p3.setName('PROCESSOR3') p4.setName('PROCESSOR4') c.setDistribution('exp') p1.setDistribution('exp') p2.setDistribution('exp') p3.setDistribution('exp') p4.setDistribution('exp') p1.setNextElements([p2, p3, p4, None]) p1.elementsProbabilities = [0.15, 0.13, 0.3, 0.42] p2.setNextElements([p1]) p3.setNextElements([p1]) p4.setNextElements([p1]) elementsList = [c, p1, p2, p3, p4] model = Model(elementsList) model.simulate(1000000.0) res = model.returnResult() res['theoretical_mean_queue'] = [1.786, 0.003, 0.004, 0.00001] res['theoretical_workload'] = [0.714, 0.054, 0.062, 0.036] res['queue_accuracy'] = 100 * ( abs(res.eval('mean - theoretical_mean_queue')) / res['theoretical_mean_queue']) res['workload_accuracy'] = 100 * ( abs(res.eval('workload - theoretical_workload')) / res['theoretical_workload']) print(res)
def setUp(self): self.sideFrame = Frame(self.root, width=200, height=500, bg="pink") self.topFrame = Frame(self.root, width=600, height=25, bg="blue") self.bottomFrame = Frame(self.root, width=600, height=25, bg="brown") self.homeFrame = Frame(self.root, width=600, height=450) self.createFrame = Frame(self.root, width=600, height=450) self.sideFrame.grid(row=0, column=0, sticky="w") self.topFrame.grid(row=0, column=1, sticky="n") self.bottomFrame.grid(row=0, column=1, sticky="s") self.homeFrame.grid(row=0, column=1) self.createFrame.grid(row=0, column=1) self.panels = {"home": self.homeFrame, "create": self.createFrame} home = Home(self.homeFrame, self.panels) create = Create(self.createFrame, self.panels) self.panels["home"].tkraise()
def main(self): p11 = Process(.3, .3, 1) p12 = Process(.3, .3, 1) p11.otherProcess = p12 p12.otherProcess = p11 c = Create(.5) c.setNextElements([p11, p12]) p11.setMaxqueue(3) p12.setMaxqueue(3) p11.state = 1 p12.state = 1 c.tnext = 0.1 p11.queue = 2 p12.queue = 2 c.setName('CREATOR') p11.setName('PROCESSOR21') p12.setName('PROCESSOR22') c.setDistribution('exp') p11.setDistribution('exp') p12.setDistribution('exp') elementsList = [c, p11, p12] model = Model(elementsList) model.simulate(10000.0)
def verify_otp(number, otp): conn = None try: conn, cur = Sql.get_connection() logging.debug("Connection and cursor received") sql_query = "select session_id from driver_otp where number = " + str(number) cur.execute(sql_query) data = cur.fetchone() session_id = str(data[0]) print(session_id) response = requests.get("https://2factor.in/API/V1/" + str(config.api_key_2factor) + "/SMS/VERIFY/" + str(session_id)+ "/" + str(otp)) response = dict(response.json()) if response["Status"] == "Success" and response["Details"] == "OTP Matched" : sql_query = "update driver_otp set otp_verified = 1 where number = " + str(number) cur.execute(sql_query) conn.commit() response = Create.check_user_repetition(number) if "present" in response: if response["present"] == 1: result = Response.make_response(200, "OTP matched", "OTP matched successfully", action = "login", match = 1) if response["present"] == 0: result = Response.make_response(200, "OTP matched", "OTP matched successfully", action = "signUp", match = 1) logging.debug("OTP verified successfully") conn.close() return result else: conn.close() error = Response.make_response(500, "System failure", "Oops something went wrong !") return error else: logging.debug("OTP could not be verified") error = Response.make_response(200, "OTP mismatched", "OTP does not match", match = 0) conn.close() return error except Exception as e: if conn is not None: conn.close() logging.error("Error in verify_otp: " + str(e)) error = Response.make_response(500, "System failure", "Oops something went wrong !") return error
def __init__(self, video_src, port, baud): self.cam = cv2.VideoCapture(video_src) ret, self.frame = self.cam.read() cv2.namedWindow('Create Tracker') cv2.setMouseCallback('Create Tracker', self.mouse) self.selection = None self.drag_start = None self.tracking_state = 0 self.dest = None self.state = 'Servo: Pivot' self.pivot_dir = 'l' # default pivot direction left self.move_dir = 'f' # default move direction forward if not port: port = '/dev/ttyUSB0' if not baud: baud = 115200 self.robot = Create(port, baud) self.robot.sendCommandASCII('128') self.robot.sendCommandASCII('131') self.prev_angle = 0 self.prev_dist = 0 self.counter = 0
def setup_video(device='/dev/video7'): set_resolution = subprocess.Popen( "v4l2-ctl -v width=160,height=120".split()) set_resolution.wait() return subprocess.Popen([ 'cvlc', '--no-audio', 'v4l2://' + device + ':width=160:height=120:fps=5:chroma=mjpg', '--sout=#standard{access=http,mux=mpjpeg,dst=0.0.0.0:8080}', '--sout-http-mime=multipart/x-mixed-replace;boundary=--7b3cc56e5f51db803f790dad720ed50a' ]) controller = None last_control = time() c = Create('/dev/ttyO0', FULL_MODE) drive_speed = 0 turn_speed = 0 class CreateHandler(BaseHTTPRequestHandler): def do_GET(self): global controller, last_control request_client = self.client_address[0] try: request, commands = self.path.split("?") except: if self.path == '/jquery.js': self.set_mime_type('text/javascript') self.send_file('jquery.js') return
r.go(fwd_velocity) r.waitDistance(fwd_distance) r.stop() sleep(.25) in_file.close() def via(r, filename): """Drive the robot according to data on each line in file. Keyword arguments: r -- robot object and serial connection filename -- data file with waypoints Returns: nothing, moves to points in filename. """ pass #sense distance #waitAngle #waitDistance #sleep(long) #shutdown if __name__ == '__main__': r = Create(SERIAL_PORT) filename = input("Please enter name of data file: ") load_numbers(r, filename) sleep(50) r.shutdown()
from create import Create from read import Read from update import Update from delete import Delete from raw_crud import connection_to_server conn = connection_to_server() #Default localhost i połączenie z bazą TheShips if conn: while True: print('c=Create, r=Read, u=Update, d=Delete, anything else=Exit ') choice = input('What do you want to do? Choose one option: ') if choice == 'c': create1 = Create() create1.insert_row(conn) elif choice == 'r': read1 = Read() read1.display_table(conn) elif choice == 'u': update1 = Update() update1.update_rows(conn) elif choice == 'd': delete1 = Delete() delete1.delete_rows(conn) else: print('Bye :)') break else: print('Failed to connect to database')
class CreateTracker(object): def __init__(self, video_src, port, baud): self.cam = cv2.VideoCapture(video_src) ret, self.frame = self.cam.read() cv2.namedWindow('Create Tracker') cv2.setMouseCallback('Create Tracker', self.mouse) self.selection = None self.drag_start = None self.tracking_state = 0 self.dest = None self.state = 'Servo: Pivot' self.pivot_dir = 'l' # default pivot direction left self.move_dir = 'f' # default move direction forward if not port: port = '/dev/ttyUSB0' if not baud: baud = 115200 self.robot = Create(port, baud) self.robot.sendCommandASCII('128') self.robot.sendCommandASCII('131') self.prev_angle = 0 self.prev_dist = 0 self.counter = 0 def mouse(self, event, x, y, flags, param): ''' Actions on mouse click. ''' if event == cv2.EVENT_LBUTTONDOWN: self.drag_start = (x, y) if self.tracking_state == 1: self.dest = (x,y) self.state = 'Servo: Pivot' else: self.tracking_state = 0 elif event == cv2.EVENT_LBUTTONUP: h, w = self.frame.shape[:2] xo, yo = self.drag_start x0, y0 = np.maximum(0, np.minimum([xo, yo], [x, y])) x1, y1 = np.minimum([w, h], np.maximum([xo, yo], [x, y])) self.selection = None if x1-x0 > 0 and y1-y0 > 0: self.selection = (x0, y0, x1, y1) self.tracking_state = 1 def dist(self, pt1, pt2): ''' Calculate distance between two points. ''' return ((pt1[0] - pt2[0])**2 + (pt1[1] - pt2[1])**2)**0.5 def doAction(self, diff, center): ''' Handle actions and state changes ''' # Test default direction if self.state == 'Servo: Pivot': self.prev_angle = diff self.robot.sendCommand(self.pivot_dir) self.state = 'Pivot: Wait' # Wait 4 cycles elif self.state == 'Pivot: Wait': self.counter += 1 if self.counter == 4: self.counter = 0 self.robot.sendCommand('s') self.state = 'Determine Direction' # If default pivot direction wrong, change direction elif self.state == 'Determine Direction': if ( (abs(diff) > abs(self.prev_angle) and abs(self.prev_angle) < 90) or (abs(diff) < abs(self.prev_angle) and abs(self.prev_angle) > 90) ): if self.pivot_dir == 'l': self.pivot_dir = 'r' else: self.pivot_dir = 'l' self.robot.sendCommand(self.pivot_dir) self.state = 'Turning' # Continue turning until angle between lines is small elif self.state == 'Turning': d = self.dist(center, self.dest) if d < 30: self.state = 'Done' self.robot.sendCommand('s') if abs(diff) < 5 or abs(diff) > 175: self.state = 'Correct' self.robot.sendCommand('s') # Correc the angle slightly elif self.state == 'Correct': if self.pivot_dir == 'l': self.robot.sendCommand('r') else: self.robot.sendCommand('l') self.state = 'Correct: Wait' # Wait 3 cycles elif self.state == 'Correct: Wait': self.counter += 1 if self.counter == 3: self.counter = 0 self.robot.sendCommand('s') self.state = 'Servo: Move' # Test default movement direction elif self.state == 'Servo: Move': self.prev_dist = self.dist(center, self.dest) self.robot.sendCommand(self.move_dir) self.state = 'Move: Wait' # Wait 6 cycles -- Movement direction is more critical, so wait longer elif self.state == 'Move: Wait': self.counter += 1 if self.counter == 6: self.counter = 0 self.robot.sendCommand('s') self.state = 'Determine Motion' # If movement direction wrong, change direction elif self.state == 'Determine Motion': d = self.dist(center, self.dest) if d > self.prev_dist: if self.move_dir == 'f': self.move_dir = 'b' else: self.move_dir = 'f' self.robot.sendCommand(self.move_dir) self.state = 'Moving' # Move until distance is small or if angle becomes too large elif self.state == 'Moving': if abs(diff) > 45 and abs(diff) < 135: self.state = 'Servo: Pivot' self.robot.sendCommand('s') d = self.dist(center, self.dest) if d < 30: self.robot.sendCommand('s') self.state = 'Done' def run(self): ''' Main loop. ''' while True: # read image from camera ret, self.frame = self.cam.read() vis = self.frame.copy() hsv = cv2.cvtColor(self.frame, cv2.COLOR_BGR2HSV) # create mask mask = cv2.inRange(hsv, np.array((0., 60., 32.)), np.array((180., 255., 255.))) # track the selected object if self.selection: x0, y0, x1, y1 = self.selection self.track_window = (x0, y0, x1-x0, y1-y0) hsv_roi = hsv[y0:y1, x0:x1] mask_roi = mask[y0:y1, x0:x1] hist = cv2.calcHist( [hsv_roi], [0], mask_roi, [16], [0, 180] ) cv2.normalize(hist, hist, 0, 255, cv2.NORM_MINMAX); self.hist = hist.reshape(-1) vis_roi = vis[y0:y1, x0:x1] cv2.bitwise_not(vis_roi, vis_roi) vis[mask == 0] = 0 if self.tracking_state == 1: self.selection = None prob = cv2.calcBackProject([hsv], [0], self.hist, [0, 180], 1) prob &= mask term_crit = ( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1 ) track_box, self.track_window = cv2.CamShift(prob, self.track_window, term_crit) # show center of ellipse center = (int(track_box[0][0]), int(track_box[0][1])) cv2.circle(vis, center, 8, (0,255,0), -1) # show destination cv2.circle(vis, self.dest, 8, (0,0,255), -1) # red circle at destination # show direction line if self.dest: cv2.line(vis, self.dest, center, (255,0,0), 2) # blue line to destination # calculate orientation or_angle = track_box[2] # show orientation axis pt2_x = int(round(center[0] + 100 * math.sin(-math.pi/180 * or_angle), 0)) pt2_y = int(round(center[1] + 100 * math.cos(-math.pi/180 * or_angle), 0)) pt2 = (pt2_x, pt2_y) try: cv2.line(vis, center, pt2, (0, 255, 0), 2) # green line through orientation axis except: pt2 = (center[0], center[1] + 30) cv2.line(vis, center, pt2, (0, 255, 0), 2) print(center) try: cv2.ellipse(vis, track_box, (0, 255, 0), 2) # green ellipse around selection except: print(track_box) # Arduino calculations and movement if self.dest: # Calculate angle difference # Note that angles will be measured from horizontal and in degrees or_angle = 90 - or_angle # correct orientation angle for consistent angle measure dir_dx = center[0] - self.dest[0] dir_dy = center[1] - self.dest[1] dir_angle = math.atan2(dir_dy, dir_dx) # atan2 is better than atan dir_angle = 180 - dir_angle * 180/math.pi # correct direction angle diff = dir_angle - or_angle if diff > 180: diff = 180 - diff self.doAction(diff, center) cv2.imshow('Create Tracker', vis) # Quit on ESC ch = 0xFF & cv2.waitKey(5) if ch == 27: break self.robot.sendCommand('s') cv2.destroyAllWindows()
class Main: def __init__(self): pygame.init() # Setting variables self.pathToProjects = "" # Getting launcher settings self.getLauncherSettings() # Launcher window self.window = pygame.display.set_mode(SIZE) pygame.display.set_caption("Launcher") # Launcher icon launcherIcon = loadImage("launcher/icon.png") pygame.display.set_icon(launcherIcon) # Current folder self.currentFolder = os.getcwd() # Boolean variables self.running = True # Clock self.clock = pygame.time.Clock() # Launcher self.launcher = Launcher() # Create self.create = Create(self.pathToProjects) # Path self.path = "" # Gameloop self.loop() # Getting launcher settings def getLauncherSettings(self): settings = codecs.open("launcher/settings.vn", "r", "utf-8") content = clearLines(settings.read().split("\n")) for line in content: line = line.replace(" ", "") setting, value = line.split("=") if setting == "PATHTOPROJECTS": self.pathToProjects = value self.pathToProjects = os.getcwd() + "/projects/" # Handling events def events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.end() # Handling buttons for button in self.launcher.buttons: if event.type == pygame.MOUSEMOTION: if mouseCollision(button.xy, button.wh, event.pos): button.hover = True else: button.hover = False if event.type == pygame.MOUSEBUTTONDOWN: if mouseCollision(button.xy, button.wh, event.pos): button.click = True self.buttonActions(button) else: button.click = False # Handling links for link in self.launcher.links: if event.type == pygame.MOUSEMOTION: if mouseCollision(link.xy, link.twh, event.pos): link.hover = True else: link.hover = False if event.type == pygame.MOUSEBUTTONDOWN: if mouseCollision(link.xy, link.twh, event.pos): link.selected = True else: link.selected = False # Button actions def buttonActions(self, button): # Start selected project if button.name == "startproject": # Getting the name of the selected project projectname = "" for link in self.launcher.links: if link.selected == True: projectname = link.rtrn if projectname == "": return self.startProject(projectname) # Create new project elif button.name == "createproject": self.create.createProject("new") self.launcher.createProjectList() # Updating the list of projects elif button.name == "updatelistcprojects": self.launcher.createProjectList() # Deleting the selected project elif button.name == "deleteproject": projectname = "" for link in self.launcher.links: if link.selected == True: projectname = link.rtrn if projectname == "": return self.create.deleteProject(projectname) self.launcher.createProjectList() # Intermediant calculations def update(self): self.clock.tick(FPS) self.events() # Rendering game objects def render(self): self.window.fill(WHITE) # scImage(self.window, "launcher/background.jpg", (0,0), SIZE) self.launcher.drawObjects(self.window) pygame.display.update() # Gameloop def loop(self): while self.running: self.update() self.render() # Start project def startProject(self, projectName): self.path = self.pathToProjects + projectName self.end() # Turn off the launcher def end(self): self.running = False
# ----------------------------------- 小艾 ------------------------------------------ xiaoai = XiaoAi() # 将任务加入小艾的队列 for item in aim_page: xiaoai.add_task(item) for item in aim_tax: xiaoai.add_task(item) # 开始执行自动化生成 xiaoai.start() # ----------------------------------- 创建文件 ------------------------------------------ # 选择路径 设置为存储路径 # tk.select_folder('AIM_FOLDER') # path = setting.AIM_FOLDER total_list = page + tax tk.select_folder('AIM_FOLDER') # 创建文件 create = Create(folder=tk.aim_folder,file_list=total_list) create.create_file()
#!/usr/bin/env python #http://docs.python.org/library/optparse.html from sys import argv import os from create import Create from destroy import Destroy from optparse import OptionParser parser = OptionParser() parser.add_option('-c', '--create', dest='create_action', help="create a new app") parser.add_option('-d', '--destroy', dest='destroy_action', help="destroy an existing app") (options, args) = parser.parse_args(argv) if options.create_action: app_name = options.create_action Create(app_name) elif options.destroy_action: app_name = options.destroy_action Destroy(app_name) else: parser.print_help()
r.waitDistance(fwd_distance) r.stop() sleep(.25) in_file.close() def via(r, filename): """Drive the robot according to data on each line in file. Keyword arguments: r -- robot object and serial connection filename -- data file with waypoints Returns: nothing, moves to points in filename. """ pass #sense distance #waitAngle #waitDistance #sleep(long) #shutdown if __name__ == '__main__': r = Create(SERIAL_PORT) filename = input("Please enter name of data file: ") load_numbers(r, filename) sleep(50) r.shutdown()
# PROJET PYTHON KAROLAK 2017 # BURBAUD Pierre - GNERUCCI Maxime # Script pour inscrire un fichier csv dans une base de donnée. # Programme principal # /!\ Le CSV doit contenir des dates de naissance pour tous les utilisateurs. /!\ #!/usr/bin/env python # -*- coding: utf-8 -*- import os from update import Update from create import Create # Vérifie si la base existe déjà, si elle existe : utilise la fonction update autrement la fonction create. if os.path.isfile("./file_db.db"): Update() else: Create()
class View(QWidget): def __init__(self): super().__init__() self.__create = Create(self) self.btn_restart = QPushButton('Start', self) self.new_game = QPushButton('New game', self) self.set_chip = QPushButton('Set chip', self) self.btn_show_statistic = QPushButton('Show statistic', self) self.le = QLineEdit(self) self.text = QTextEdit(self) self.set_player1 = QComboBox(self) self.set_player2 = QComboBox(self) self.init_comboBox() self.init_base_ui() def init_comboBox(self): list_of_players = self.__create.get_list_of_players() for i in list_of_players: self.set_player1.addItem(i) self.set_player2.addItem(i) def init_base_ui(self): self.setGeometry(600, 600, 600, 600) self.text.setTextInteractionFlags(Qt.TextSelectableByMouse) self.btn_restart.setEnabled(False) self.set_player1.setEnabled(False) self.set_player2.setEnabled(False) self.set_chip.setEnabled(False) self.le.setEnabled(False) midL = QVBoxLayout() midL.addWidget(self.le) midL.addWidget(self.set_chip) midL.addWidget(self.text) midL.addWidget(self.btn_restart) midL.addWidget(self.new_game) leftL = QVBoxLayout() leftL.addWidget(self.set_player1) leftL.addStretch(1) rightL = QVBoxLayout() rightL.addWidget(self.set_player2) rightL.addStretch(1) rightL.addWidget(self.btn_show_statistic) mainVL = QHBoxLayout() mainVL.addLayout(leftL) mainVL.addLayout(midL) mainVL.addLayout(rightL) self.setLayout(mainVL) self.set_chip.clicked.connect(self.show_set_chip) self.new_game.clicked.connect(self.new_game_clicked) self.btn_restart.clicked.connect(self.restart_clicked) self.set_player1.activated[str].connect(self.on_activated_player1) self.set_player2.activated[str].connect(self.on_activated_player2) self.btn_show_statistic.clicked.connect(self.show_statistic) self.setWindowTitle('6v6') self.show() def new_game_clicked(self): self.btn_restart.setEnabled(False) self.set_player1.setEnabled(False) self.set_player2.setEnabled(False) self.btn_show_statistic.setEnabled(True) self.le.setEnabled(False) self.le.setText('') self.text.setText('') self.__create.def_param() self.set_chip.setEnabled(True) def restart_clicked(self): self.__create.new_game() self.__create.game.start_in_view() self.btn_restart.setEnabled(False) def show_statistic(self): text, ok = QInputDialog.getText(self, 'Input Dialog', 'Enter name:') temp = Statistic.get_player_stat(text) self.text.insertPlainText('\n' + text + ' - games: ' + str(temp[0]) + ' win rate: ' + str(temp[1]) + ' chip rate: ' + str(temp[2]) + '\n') self.text.ensureCursorVisible() def show_set_chip(self): text, ok = QInputDialog.getInt(self, 'Input Dialog', 'Enter chip:') if ok: self.le.setText(str(text)) self.set_chip.setEnabled(False) self.__create.set_chip(int(text)) self.set_player1.setEnabled(True) self.btn_show_statistic.setEnabled(False) def on_activated_player1(self, text): self.text.insertPlainText('\n'+text+'\n') self.text.ensureCursorVisible() self.set_player1.setEnabled(False) list_of_players = self.__create.get_list_of_players() if text == list_of_players[0]: name, ok1 = QInputDialog.getText(self, 'Input Dialog', 'Enter name:') self.__create.set_player_ov(1, text, name) else: self.__create.set_player_ov(1, text, text) self.set_player2.setEnabled(True) def on_activated_player2(self, text): self.text.insertPlainText('\n'+text+'\n') self.text.ensureCursorVisible() self.set_player2.setEnabled(False) list_of_players = self.__create.get_list_of_players() if text == list_of_players[0]: name, ok1 = QInputDialog.getText(self, 'Input Dialog', 'Enter name:') self.__create.set_player_ov(2, text, name) else: self.__create.set_player_ov(2, text, text) self.btn_restart.setEnabled(True) def choose_for_man(self, pull): check = 0 text = 0 while check == 0: text, ok = QInputDialog.getInt(self, 'Input Dialog', 'Enter chip:') check = text in pull if check == 0: self.text.insertPlainText("\nyou don't have this chip, try again.") self.text.ensureCursorVisible() return text def print_score(self, name1, name2, score1, score2): self.text.insertPlainText("\n[" + name1 + " : " + name2 + "] " + str(score1) + " : " + str(score2)) self.text.ensureCursorVisible() def print_pull(self, name, pull): self.text.insertPlainText("\n"+name + " chips: " + str(pull)) self.text.ensureCursorVisible() def print_value(self, name, value): self.text.insertPlainText("\n"+name + " choose: " + str(value)) self.text.ensureCursorVisible() def print_winner(self, winner): self.text.insertPlainText("\n"+winner) self.text.ensureCursorVisible() self.btn_show_statistic.setEnabled(True)