def output_status_data(self, result, status_data): for output_sublist in status_data: print(" ".join(output_sublist)) if self.display == "True": sys.stdout = sys.stderr display.display(result, self.exchange)
def main(): display.display() message = input("\t\tChoose Option: ") print() if message == '1': display.displayBook() main() elif message == '2': services.borrowBook() main() elif message == '3': services.returnBook() main() elif message == '4': print("\t\tExiting...\n") sys.exit() else: print("\t\tSorry! Invalid input.\n") ans = input("\t\tDo you want to continue(y/n):") print() if ans == 'y': main() elif ans == 'n': print("\t\tExiting...\n") sys.exit() else: print("\t\tInvalid input.\nExiting...") sys.exit()
def main(): global resetSwitch, frequencySwitch, stopSwitch, displaySwitch, SPICLK, SPIMISO, SPIMOSI, SPICS, state, displayData, start_time #run initialisation init.initPins(resetSwitch, frequencySwitch, stopSwitch, displaySwitch) GPIO.add_event_detect(frequencySwitch, GPIO.FALLING, callback=frequencyChange, bouncetime=200) GPIO.add_event_detect(stopSwitch, GPIO.FALLING, callback=stopButton, bouncetime=200) GPIO.add_event_detect(displaySwitch, GPIO.FALLING, callback=displayButton, bouncetime=400) GPIO.add_event_detect(resetSwitch, GPIO.FALLING, callback=resetButton, bouncetime=200) timer = 0 display.display(["Time", " Timer", "Pot", "Temp", "Light"]) while (True): while (state): #will run until reset button is bushed data = [] data = sensors.getData() time.sleep(delay) end_time = time.time() timer = round(end_time - start_time, 0) data[1] = datetime.timedelta(seconds=timer) displayData.append(data[:]) display.display(displayData[len(displayData) - 1])
def displayBookList(self, event): if self.key_word == '': box = wx.MessageDialog(None, 'No input detected!', 'Input Error!', wx.OK) box.ShowModal() else: filepath = '../export_files/booklist_of_' + self.key_word display(filepath)
def game_loop(self): """The actual game loop itself""" while True: os.system("clear") # print(self.game_map.map) display(self.score, self.game_map.map, self.player) self.game_map.step() self.player.update(self.game_map) tty.setraw(stdin) start_time = time.perf_counter() fds = self.inpoll.poll(500) poll_time = time.perf_counter() - start_time sleep_time = max(0, (0.2 - (self.speed * 0.05)) - poll_time) if fds != []: character = stdin.read(1) stdin.flush() if character == 'q': break elif character == 'f': self.speed += 5 self.player.x += 1 elif character == 'b': self.speed -= 5 self.player.x -= 1 elif character == 'j': self.player.jump() self.score += 10 + (5 * self.speed) print(self.game_map.map) time.sleep(sleep_time) terminal.restore()
def tryJump(board, playerTurn, x1, y1, x2, y2): #attempts to do the jump the user wants to do if abs(x1 - x2) != 2 or abs( y1 - y2) != 2: #checks first if its the right number of spaces away. debugInfo("Invalid jump ammount") returnValues = [False, board] return returnValues if isValidJump(board, x1, y1, x2, y2): #checks if its a valid jump using this function debugInfo("Valid") board = movePiece(board, x1, y1, x2, y2) board[int(abs((y1 + y2) / 2))][int(abs((x1 + x2) / 2))] = { "Color": "Valid", "Type": "Valid" } while canDouble(x2, y2): redLeft, blackLeft = getPiecesLeft(board) display.display().start(board, playerTurn, redLeft, blackLeft) print( "Double Jump To Move you only have to input move (destination)" ) changeState, board, x3, y3 = getInput( board, playerTurn, x2, y2 ) #repolls for input to get the user to get where the user wants to move to if changeState: #change state is just a variable x2 = x3 y2 = y3 board = kingMe(board, playerTurn, x2, y2) returnValues = [True, board] return returnValues debugInfo("Nothing applied") returnValues = [False, board] return returnValues
def main(): port = sys.argv[1] bp = busPirate.BusPirate(port) if bp.isConnected(): display.display(bp) else: print('Nothing found on port')
def play(m, diff): s, p, c, a, bp, bc, gL, t, h = m.play(diff) while c != 3: result = m.guess(p, a, bp, bc) if result == None: continue elif result == 'menu': print("\n" * 100) #clear screen main() else: [p, a, bp, bc] = result if p != 3: c, bc, gL, t, h = m.compGuess(c, bc, gL, t, h, diff) else: d.displayBoth(bp, bc) print( "\nYY YY OOOO UU UU WW WW IIIIII NN NN !!\nYY YY OO OO UU UU WW WW II NNN NN !!\n YYYY OO OO UU UU WW WW WW II NNNNNN !!\n YY OO OO UU UU WWWWWWWW II NN NNN !!\n YY OO OO UU UU WWW WWW II NN NN \n YY OOOO UUUU WW WW IIIIII NN NN !!\n" ) again(m, diff) d.displayBoth(bp, bc) print( "\nYY YY OOOO UU UU LL OOOO SSSS EEEEEE\nYY YY OO OO UU UU LL OO OO SS SS EE \n YYYY OO OO UU UU LL OO OO SS EEEE \n YY OO OO UU UU LL OO OO SS EE \n YY OO OO UU UU LL OO OO SS SS EE \n YY OOOO UUUU LLLLLL OOOO SSSS EEEEEE\n" ) print("The boat was here:\n") for i in range(s): for j in range(s): if a[i][j] == "X": bp[j + 5][i + 1] = a[i][j] else: continue d.display(bp) again(m, diff)
def sphere_two(point, vector, radius): h = (math.pow(vector[0], 2) + math.pow(vector[1], 2) + math.pow(vector[2], 2)) i = ((2 * point[0] * vector[0]) + (2 * point[1] * vector[1]) + (2 * point[2] * vector[2])) j = (math.pow(point[0], 2) + math.pow(point[1], 2) + math.pow(point[2], 2) - math.pow(radius, 2)) display.display(h, i, j, point, vector)
def pubTweets(api): self.publicTweet = self.api.home_timeline() for self.tweets in self.publicTweet: self.out = self.tweets.text print( self.out.decode("utf-8").encode('cp850', 'replace').decode('cp850')) display().divider(50, "=")
def main(): if (len(argv) != 2): print('Usage: %s [data_file.csv]' % argv[0]) exit() data = Data(argv[1]) data.guess_thetas() data.save() display(data)
def api_main(): parser = argparse.ArgumentParser(description='api') parser.add_argument('-inst', required = True, dest='filename', action='store', help='Input file name') parser.add_argument('-forChinese', required = False, dest='forChinese', action='store', help='Chinese or total') parser.add_argument('-key', required = True, dest='keywords', action='store', help='keywords used') parser.add_argument('-filter', required = False, dest='filter', action='store', help='filter used') args = parser.parse_args() display(filename = args.filename, forChinese=args.forChinese, keywords = args.keywords, filter = args.filter)
def api_message(): if request.headers['Content-Type'] == 'text/plain': display.display(request.data) return "Text Message: " + request.data elif request.headers['Content-Type'] == 'application/json': display.display(request.json['message']) return "JSON Message: " + json.dumps(request.json)
def cycle(self): display(self.world, self.life_cycles) update_world(self.world_width, self.world_height, self.world) sleep(self.cycle_time) sp.call('clear', shell=True) self.life_cycles += 1 if self.life_cycles >= self.life_cycle_limit: self.do_what_next()
def loop(self): i = -1 temp = round(self.get_temp()) while True: sleep(.001) i += 1 if i % 100 == 0: # Update buffers self.get_angle() temp = self.get_temp() display.display(str(temp).ljust(4)) if i % 10 == 0: if self.motor.remainingSteps > 0: self.motor.step() # temp = round(self.get_temp()) # print("Temp", temp) # print("Angle", self.get_angle()) if i % 10000 == 0: metrics.save_metric("temperature", self.get_temp()) metrics.save_metric("angle", self.get_angle()) if i % 200000 == 0: print("[+] i=%d, Temp=%d, Angle=%d, Stepper=%d" % (i, temp, self.get_angle(), self.motor.remainingSteps)) print(self.tmp_buffer, self.angle_buffer) target_temperature = self.get_target_temperature() print("[+] Target Temperature", target_temperature) if temp < target_temperature: print("[-] Temp below target") if self.get_angle() < MAX_ANGLE_DEGREE: print("[***] Already max angle") continue self.motor.direction = -1 self.motor.remainingSteps = round(ANGLE_CHANGE * motor.STEPS_PER_DEGREE) print("[-] Adding motorSteps=%d" % self.motor.remainingSteps) if temp > target_temperature: print("[-] Temp above target") if self.get_angle() > MIN_ANGLE_DEGREE: print("[***] Already min angle") continue self.motor.direction = 1 self.motor.remainingSteps = round(ANGLE_CHANGE * motor.STEPS_PER_DEGREE) print("[-] Adding motorSteps=%d" % self.motor.remainingSteps)
def anim_marche(self, fenetre, fond, pos,groupe_blocks,sens): if sens == "gauche": for img in self.images[0]: self.image = img display.display(fenetre, fond, pos, self, groupe_blocks) if sens == "droite": for img in self.images[1]: self.image = img display.display(fenetre, fond, pos, self, groupe_blocks)
def cone_2(point, vector, radius): angle = ((90 - radius) * math.pi) / 180 a = math.pow(vector[0], 2) + math.pow( vector[1], 2) - (math.pow(vector[2], 2) / math.pow(math.tan(angle), 2)) b = (2 * point[0] * vector[0]) + (2 * point[1] * vector[1]) - ( (2 * point[2] * vector[2]) / math.pow(math.tan(angle), 2)) c = math.pow(point[0], 2) + math.pow( point[1], 2) - (math.pow(point[2], 2) / math.pow(math.tan(angle), 2)) display.display(a, b, c, point, vector)
def FindTSPTour(filename): p = tsp.utils.load_problem(filename, special=distance) p.edge_weight_type = 'SPECIAL' p.special = distance graphMST = graph(p) heuristics = [ graphMST.getTour_NoHeuristic, graphMST.getTour_nnHeuristic, graphMST.getTour_nChildHeuristic, graphMST.getTour_nnAtLeaf, graphMST.getTour_2opt ] disp = [] for title in [ "No Heuristic", "Nearest Neighbour", "Nearest Child First", "Nearest Neighbour at Leaf", "2-OPT over NN at Leaf" ]: disp.append(display(f'{filename} - {title}')) dispMST = display(f'{filename} - MST') print(f'File Name : {filename}') print("Number of Nodes: ", len(list(p.get_nodes()))) print("Number of Edges: ", len(list(p.get_edges()))) print("Distance between nodes (1,2): ", p.wfunc(1, 2)) graphMST.kruskalMSTEdges() graphMST.genTree() dispMST.addPoints(p.node_coords) dispMST.addRootNode(p.node_coords[graphMST.rootNode]) dispMST.addEdges(p, graphMST.result) for d in disp: d.addPoints(p.node_coords) d.addRootNode(p.node_coords[graphMST.rootNode]) tourLengths = [] for h, d in zip(heuristics, disp): t = time.time() d.addTour(p.node_coords, h()) length = graphMST.calcTourLength() tourLengths.append(length) print(f'{d.title} : {length:.3f}') print(f'{d.title} : Time - {(time.time() - t):.3f} S') d.displayTourLength(length) graphMST.writeTourFile(filename) # ============================================================================= # dispMST.saveFigure("Results/Images") # for d in disp: # d.saveFigure("Results/Images") # ============================================================================= return tourLengths
def cylinder_two(point, vector, radius): if (math.pow(point[0], 2) + math.pow(point[1], 2) - math.pow(radius, 2)) == 0: print("There is an infinite number of intersection points.") return 0 else: a = float((math.pow(vector[0], 2) + math.pow(vector[1], 2))) b = float((2 * point[0] * vector[0]) + (2 * point[1] * vector[1])) c = float((math.pow(point[0], 2) + math.pow(point[1], 2) - math.pow(radius, 2))) display.display(a, b, c, point, vector) return 0
def construct(thing): global smte smte.cursor.execute("BEGIN TRANSACTION;") smte.connect(thing) thing.redo(smte.model) display.display(smte.model) smte.draw_all() smte.save(smte.cursor) smte.cursor.execute("END TRANSACTION;")
def displayUnit(self, offsetX, offsetY, unit, step=1): for x in range(8): for y in range(8): red = unit[x][y] + 128 if red < 0: red = 0 elif red > 255: red = 255 # print red display().drawPoint(offsetX + x * step, offsetY + y * step, (red, 0, 0), step)
def query(word, k): ''' Get an image data and returns top k images that are similar ''' print("start query") e_word = Tensor(we.embed_caption(word)[np.newaxis,:]) print("normalizing") e_word = normalize(e_word) top_ids = find_top_k(e_word, k) display(top_ids)
def cleandata(self, filename, iminfo=None, prodir='.', interp='linear', cleanup=True, clobber=False, logfile='saltclean.log', reduce_image=True, display_image=False, verbose=True): """Start the process to reduce the data and produce a single mosaicked image""" #print filename status = 0 #create the input file name infile = os.path.basename(filename) rawpath = os.path.dirname(filename) outpath = './' outfile = outpath + 'mbxp' + infile #print infile, rawpath, outpath #If it is a bin file, pre-process the data if filename.count('.bin'): print "I can't handle this yet" #ignore bcam files if infile.startswith('B'): return iminfo #check to see if it exists and return if clobber is no if os.path.isfile(outfile) and not clobber: return iminfo #handle HRS data print filename if infile.startswith('H') or infile.startswith('R'): outfile = os.path.basename(filename) + 's' print filename, outfile if not os.path.isfile(outfile): os.symlink(filename, outfile) #display the image if display_image: print "Displaying %s" % outfile try: display(outfile) except Exception, e: print e try: log = None #open(logfile, 'a') sdb = saltmysql.connectdb(self.sdbhost, self.sdbname, self.sdbuser, self.password) sdbloadfits(outfile, sdb, log, False) print 'SDBLOADFITS: SUCCESS' except Exception, e: print 'SDBLOADFITSERROR:', e
def main(): loop = asyncio.get_event_loop() with aiohttp.ClientSession(loop=loop) as session: proxies = Proxies( session, 30, 'http://gimmeproxy.com/api/getProxy?protocol=http&supportsHttps=true&maxCheckPeriod=3600' ) area = Area('https://www.freecycle.org/browse/UK/London') groups = loop.run_until_complete( area.get_groups(session, proxies, SEARCH_TERMS, FROM, TO)) display(groups)
def usr(self): import display self.f.destroy() display.display(self.master) #root = Tk() #mb = Admin(root) #root.mainloop()
def watcher(): while os.path.exists(process): print eval( file( filterfile , "r" ).read() ) if eval( file( filterfile , "r" ).read() ) == []: print "no filters, stopping..." os.remove(process) break #test = sportsfr.get_current_match() #save_stats(test) result= sportsfr.get_last_changes() if result != "pas de r‚f‚rences" and result != False: #os.system('cls') #print_all_stat(result) all_update = [] for update in result: #print "filtered: %s" % check_filter(update) if update['diff'] and check_filter(update): #print update all_update.append(update) if int(XBMC_SETTINGS.getSetting( "visualisation" )) == 0: try: print "%s %s | %s %s - %s %s" % ( update['sport'] , update['country'] , update['A_name'] , update['A_score'] , update['B_score'] , update['B_name'] ) except: print_exc() if "A" in update and "B" in update or update['sport'] == "tennis": print "both scored or tennis" try:img = os.path.join ( img_path , update['sport'] , "default.png" ) except:print "no image for %s" % update['B_name'] B_name = coloring( update['B_name'] , "yellow" , update['B_name'] ) A_name = coloring( update['A_name'] , "yellow" , update['A_name'] ) elif "A" in update: print "A" try:img = os.path.join ( img_path , update['sport'] , "%s.png" % update['A_name'] ) except: print "no image for %s" % update['A_name'] A_name = coloring( update['A_name'] , "green" , update['A_name'] ) B_name = coloring( update['B_name'] , "red" , update['B_name'] ) elif "B" in update: print "B" try:img = os.path.join ( img_path , update['sport'] , "%s.png" % update['B_name'] ) except:print "no image for %s" % update['B_name'] B_name = coloring( update['B_name'] , "green" , update['B_name'] ) A_name = coloring( update['A_name'] , "red" , update['A_name'] ) lign2 = ("%s %s - %s" % ( update['sport'] , update['country'] , update['part'] )).strip( "- ") lign1 = "%s %s - %s %s" % ( A_name , update['A_score'] , update['B_score'] , B_name ) xbmc.executebuiltin("XBMC.Notification(%s,%s,5000,%s)"%(lign1,lign2,img)) time.sleep(3) if int(XBMC_SETTINGS.getSetting( "visualisation" )) == 1: display.display( all_update ) if os.path.exists(process):time.sleep(15) if os.path.exists(process):time.sleep(10)
def guess(attempts, hits, answer, blank, cL): display(blank) if attempts == 1 and (cL[-1] == 1): print("You have 1 attempt and 1 ship left.") elif attempts == 1: print("You have 1 attempt and {0} ships left.".format(cL[-1])) elif cL[-1] == 1: print("You have {0} attempts and 1 ship left.".format(attempts)) else: print("You have {0} attempts and {1} ships left.".format( attempts, cL[-1])) if attempts == 40: g = input("Enter your guess (eg. D2): " ) #variable 'g' to not confuse with guess() else: g = input("Enter your guess: ") g = "".join(g.split()) if (len(g) > 0) and g.lower() in [ 'menu', 'quit', 'back', 'kill', 'no', 'nope', 'exit' ]: return "menu" elif (len(g) < 2) or (g[0].upper() not in [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' ]) or (g[1:] not in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']): print("\nINVALID GUESS. Try again.\n") return None else: x, y = guessIdentify(g) if blank[y + 3][ x + 1] != '.': # to navigate "filler" text for display to work properly print("\nYou already guessed here. Try again.\n") return None else: blank[y + 3][x + 1] = answer[x][y] if answer[x][y] == "O": print( "\nMM MM IIIIII SSSS SSSS \nMMM MMM II SS SS SS SS\nMMMMMMMM II SS SS \nMM MM MM II SS SS \nMM MM II SS SS SS SS\nMM MM IIIIII SSSS SSSS \n" ) elif answer[x][y] == "X": print( "\nHH HH IIIIII TTTTTT !!\nHH HH II TT !!\nHHHHHH II TT !!\nHH HH II TT !!\nHH HH II TT \nHH HH IIIIII TT !!\n" ) hits += 1 checkBoats(answer[-1], [x, y], cL) else: print("ERROR") #should never run, but just in case attempts -= 1 return [attempts, hits, answer, blank, cL]
def navigator(args): print(args) if args.a != None: # print(f'Note name {args.t}/{args.a}') if args.t is None: args.t = "general" jio = notes(args.t, args.a) jio.create(args.d) return if args.e != None: print(f'Editing note {args.e}') return if args.u: print(f'update notes') return if args.l or args.lnotes: mlt = master_list_tag() tags = mlt.get_list() if args.lnotes: d = display() d.list_tag_note_name(args.t) # if args.t is None: # for tag in tags: # if not pathlib.Path(f'{tag}.json').exists(): # print(f'Error: Tag {tag} not found, may have been deleted') # continue # js = jsonio() # tag_file = js.read(f'{tag}.json') # for note in tag_file[constants.CONTENT]: # print(f't: {tag[:8]}.. n {note[constants.NAME]}') if len(tag) > 10 else\ # print(f't: {tag.ljust(10)} n: {note[constants.NAME]}') # else: # tag = args.t # if not pathlib.Path(f'{tag}.json').exists(): # print(f'Error: Tag {tag} not found') # return # js = jsonio() # tag_file = js.read(f'{tag}.json') # for note in tag_file[constants.CONTENT]: # print(f't: {tag[:8]}.. n {note[constants.NAME]}') if len(tag) > 10 else\ # print(f't: {tag.ljust(10)} n: {note[constants.NAME]}') else: d = display() d.list_tag() # for tag in tags: # print(f't: {tag[:8]}..') if len(tag) > 10 else print(f't: {tag.ljust(10)}') return
def load(name, cached=set()): if isall(name): if google and not (name in cached): download('data/levels.txt') with open('data/levels.txt') as f: levels = f.readlines() with open('data/all.txt') as f: data = f.read() with open('data/error.txt') as f: error = list(f.read()) error.pop() points = [list(x) for x in display.display(data)] number = int(name[3:]) min = number * 18 max = min + 18 if number == 0: points[4][6:38] = [' '] * 32 else: string = str(number - 1) + '.' points[4][13:13 + len(string)] = list(string) if max >= len(levels): points[23][6:38] = [' '] * 32 else: string = str(number + 1) + '.' points[23][13:13 + len(string)] = list(string) for i in range(18): if min + i >= len(levels): points[i + 5][6] = ' ' points[i + 5][8:8 + len(error)] = error else: level = list(levels[min + i]) level[-1] = '.' points[i + 5][10:10 + len(level)] = level string = str(number) points[1][22:22 + len(string)] = list(string) return points try: if google and not (name in cached): download('levels/{}.txt'.format(name)) with open('levels/{}.txt'.format(name)) as f: data = f.read() return [list(x) for x in display.display(data)] except FileNotFoundError: with open('data/404.txt') as f: data = f.read() points = [list(x) for x in display.display(data)] for i in range(len(name)): points[1][i + 2] = name[i] return points
def cleandata(self, filename, iminfo=None, prodir='.', interp='linear', cleanup=True, clobber=False, logfile='saltclean.log', reduce_image=True, display_image=False, verbose=True): """Start the process to reduce the data and produce a single mosaicked image""" #print filename status=0 #create the input file name infile=os.path.basename(filename) rawpath=os.path.dirname(filename) outpath='./' outfile=outpath+'mbxp'+infile #print infile, rawpath, outpath #If it is a bin file, pre-process the data if filename.count('.bin'): print "I can't handle this yet" #ignore bcam files if infile.startswith('B'): return iminfo #check to see if it exists and return if clobber is no if os.path.isfile(outfile) and not clobber: return iminfo #handle HRS data print filename if infile.startswith('H') or infile.startswith('R'): outfile = os.path.basename(filename) +'s' print filename, outfile if not os.path.isfile(outfile): os.symlink(filename, outfile) #display the image if display_image: print "Displaying %s" % outfile try: display(outfile) except Exception, e: print e try: log=None #open(logfile, 'a') sdb=saltmysql.connectdb(self.sdbhost, self.sdbname, self.sdbuser, self.password) sdbloadfits(outfile, sdb, log, False) print 'SDBLOADFITS: SUCCESS' except Exception, e: print 'SDBLOADFITSERROR:', e
def index(self,key= None): returnstring = """ <html> <head> <script>""" + file('jquery.js').read() + """</script> <style> """ + file('style.css').read() + """ </style> </head> <body> """ if key == None: key = "" rawkey = None else: rawkey = key key = [str(i) for i in key.split(",")] returnstring += "<a class=homelink href='/' >home</a>" tagsdict = display.display(key) returnstring += "<nav class=keys>" for dictkey in tagsdict.keys(): returnstring += "<a class=scale href='?key=%s' style='font-size:%s px' >%s</a>"%(dictkey,size_text(tagsdict[dictkey]),str(dictkey)) returnstring += "</nav ><div class=notes>" for note in display.filterForHashtags(key): returnstring += "<article class=note>%s</article>"%(display.displayify(note,rawkey)) returnstring += """ </body> </html> """ return returnstring
def display_favorite(self): system("cls") all_fav = Favourites.display_all_favourite_product() element_to_search = {} if all_fav != []: for element in all_fav: element_to_search[element[0]] = element[1] C_EMPTY.append( Product.display_product(["name_product"], "id_product", element[0])[0][0]) C_EMPTY.append(MAIN_MENU) C_EMPTY.append(SUPRESS) qst_all_fav = Question(QUESTIONER, Q5, clean=1).answer if qst_all_fav != SUPRESS and qst_all_fav != MAIN_MENU: favourite_prod = Product.display_product(["id_product"], "name_product", qst_all_fav)[0][0] Favourites.display_favourite_product( str(favourite_prod), str(element_to_search[favourite_prod])) all_fav.clear() C_EMPTY.clear() elif qst_all_fav == SUPRESS: Favourites.suppress_all() all_fav.clear() C_EMPTY.clear() return MAIN_MENU elif qst_all_fav == MAIN_MENU: C_EMPTY.clear() return MAIN_MENU else: Question(display(150, "=", NO_FAV_PRODUCT, 1, "|", "left"), clean=1) return MAIN_MENU
def main(): if len(sys.argv) == 2 and sys.argv[1] == '-': starting_food_count = 100 starting_cell_count = 100 elif len(sys.argv) == 3: starting_food_count = int(sys.argv[1]) starting_cell_count = int(sys.argv[2]) else: starting_food_count = input('Enter starting amount of food: ') starting_cell_count = input('Enter starting amount of cells: ') World = environment.Environment(starting_food_count,starting_cell_count) # dis is a thread dis = display.display(World) worldClock = pygame.time.Clock() # i is a tick counter i = 0 while True: i += 1 # if the user exited pygame, close the rest of the program if dis.isAlive() == False: sys.exit() print 'Tick:',i,'\t\tfood: ',len(World.food_set),'\t\tcells: ',len(World.cell_list) print 'Resistance: ', environment.Environment().resistance #print 'Tick: ',i,'\t\tfood: ',len(World.food_set),'\t\tcells: ',len(World.cell_list) #print 1000/ (worldClock.tick(60) + 0.00000000001) World.tick() World.print_table("Main_Test.txt","Tick: "+str(i)) # if the main loop is over, close the graphics thread dis._Thread__stop()
def insert_product_values(self, print_count_values=False): product_insert = 0 product_already_check = 0 for element in self.json_products.products: all_products = product_insert + product_already_check VERIF = ["Vérification des produits enregistrés.", "Produits dans la base de données :", f"{all_products} / {len(self.json_products.products)}"] if all_products %10 == 0: system("cls") if print_count_values: print(display(150, "=", VERIF, 2, "|")) self.brow_value = Make_Query(SQL_CONNECTORS, f'SELECT name_product FROM product WHERE name_product = "{element[0]}"', "READ", DTB).result if self.brow_value == []: self.category_id = int(Make_Query(SQL_CONNECTORS, f"SELECT id FROM category WHERE name='{element[1]}'", "READ", DTB).result[0][0]) Make_Query(SQL_CONNECTORS, f'INSERT INTO product(name_product, category_ID,\ nutrition_grades_product, store_product, \ description_product, url_product)\ VALUES("{element[0]}","{self.category_id}","{element[2].upper()}",\ "{element[3]}","{element[4]}","{element[5]}")', "UPDATE", DTB) product_insert += 1 self.all_prod.append(element[0]) else: product_already_check +=1 return self.all_prod
def TicketCheck(self): #余票查询 #查询接口 url = 'https://kyfw.12306.cn/otn/leftTicket/queryO?leftTicketDTO.train_date={}' \ '&leftTicketDTO.from_station={}' \ '&leftTicketDTO.to_station={}' \ '&purpose_codes=ADULT'.format(self.train_date,self.from_station,self.to_station) headers['Referer'] = 'https://kyfw.12306.cn/otn/leftTicket/init' try: res1 = self.Session.get(url=API.leftTicket_init, headers=headers) res = self.Session.get(url, headers=headers) TicketData = json.loads(res.text)['data']['result'] train_data = [] for i in TicketData: data = i.split('|') into = { '车次': data[3], '日期': data[13], '起始站': data[4], '终点站': data[5], '出发站': data[6], '到达站': data[7], '出发时间': data[8], '到达时间': data[9], '历时': data[10], '一等座': data[31], '二等座': data[30], '高级软卧': data[21], '软卧': data[23], '硬卧': data[28], '硬座': data[29], 'secretStr': data[0] } train_data.append(into) str = json.dumps(train_data, ensure_ascii=False) with codecs.open('train_data.txt', 'w+', encoding='utf-8') as f: f.write(str) display(train_data) InputData = int(input("输入选择的序号:")) self.select_train = train_data[InputData] print('选择的序号为{},车次为{}'.format(InputData, self.select_train['车次'])) except: print('error') pass
def menu(): print(""" 1. Start new database. 2. Continue simulation. 3. Display animation. 4. Quit. """) option = input("Enter a number: ") if option == '1': # Create mass objects globals.mass_list = mass.create_mass_list(1) # Create database with mass names database.create_mass_names_db(globals.mass_list) # Create solar database or empty existing one database.create_solar_db() # Run simulation db_density = int( input( "Enter a value for database density parameter (integer, minimum 1): " )) mass.run_simulation(db_density) # Return to menu menu() elif option == '2': # Create mass objects globals.mass_list = mass.create_mass_list(0) # Run simulation db_density = int( input( "Enter a value for database density parameter (integer, minimum 1): " )) mass.run_simulation(db_density) # Return to menu menu() elif option == '3': # Display animation anim_speed = int( input("Enter an animation speed (integer, minimum 1): ")) display.display(anim_speed) # Return to menu menu() elif option == '4': pass else: print("Choose from 1 to 4.") menu()
def __init__(self, cursor): make_thing = \ { ROOT: make_root, INSERT: make_insert, LEFT: make_left, RIGHT: make_right, UP: make_up, DOWN: make_down, DELETE: make_delete, BACKSPACE: make_backspace } memento.Memento.__init__(self, cursor, make_thing) self.model = model.Model(cursor) self.goto(self.model, self.current) display.display(self.model) display.set_focus()
def tirer(self, screen, fond, blocks, surrondings, fichier): if self.get_img() == self.images[1]: #tire à droite tir = Bullet(self.rect.right + 5, self.rect.top + 5) target = tir.rect.right + 700 while tir.rect.right < target and tir.canMoveRight(surrondings): screen.blit(tir.get_img(), tir.rect) pygame.display.flip() screen.blit display.display(screen, fond, [0,0], self, blocks) tir.rect = tir.rect.move(10,0) centre = self.getPositionCarreau() surrondings = fichier.getSurrondings(centre[0],centre[1]) self.movement(surrondings) for event in pygame.event.get(): if event.type == pygame.QUIT: os._exit(1) if event.type == pygame.KEYDOWN and event.key == pygame.K_UP: self.jump(screen, fond, blocks, surrondings, fichier)
def main(): quit = "y" while (quit == 'y' or quit == 'Y'): x = PrettyTable(["A R A B I D O P S I S T H A L I A N A D A T A B A S E"]) x.align["A R A B I D O P S I S T H A L I A N A D A T A B A S E"] = "l" x.padding_width = 1 x.add_row(["1. Create the Genes table"]) x.add_row(["2. Display the Genes"]) x.add_row(["3. Insert a new Gene"]) x.add_row(["4. Delete a Gene"]) x.add_row(["5. Blast a Gene"]) print x ## Get input ### choice = raw_input('Enter your choice [1-5] : ') ### Convert string to int type ## choice = int(choice) ### Take action as per selected menu-option ### if choice == 1: create.create() #this will create the tables and popululate the data elif choice == 2: display.display() # display both the tables from the database elif choice == 3: insert.insert() # insert a new gene record in the database elif choice == 4: delete.delete() # delete a gene record from the database elif choice == 5: name = raw_input("Please enter the name of the gene to perform blast: ") Blast.fn(name) # Calls the BLAST module Blast.show() # Calls the module that prints image downloaded from Google Search else: ## default ## print ("Invalid input. Please enter the correct input...") quit = raw_input('Do you wanna Continue : ')
def main(): """Runs Cellular II""" #Retrieve user input from command line # If dash in is input as first arg to Cellular II, default to 100 for food and cell count # System arguments numbering starts from python command, e.g. { python Cellular-II.py $foo $bar } # where $1 is Cellular-II.py $2 is $foo and $3 is $bar if len(sys.argv) == 2 and sys.argv[1] == '-': #Evaluates for the case: { python Cellular-II.py - } (one arg && arg=='-') starting_food_count = 100 starting_cell_count = 100 elif len(sys.argv) == 3: #Evaluates for the case: { python Cellular-II.py $2 $3 } (two args) starting_food_count = int(sys.argv[1]) starting_cell_count = int(sys.argv[2]) else: #Evaluates for the case { python Cellular-II.py } (no args) unexpected number of args starting_food_count = input('Enter starting amount of food: ') starting_cell_count = input('Enter starting amount of cells: ') # Initialize World Object World = environment.Environment(starting_food_count,starting_cell_count) # Where dis is a thread dis = display.display(World) # Initial Tick worldClock = pygame.time.Clock() i = 0 #Tick Counter # ###MAIN LOOP BEGIN### while True: i += 1 # If the user closes pygame, close the rest of the program if dis.isAlive() == False: #If thread is stopped, isAlive() evaluates False sys.exit() # Terminal output print 'Tick:',i,'\t\tfood: ',len(World.food_set),'\t\tcells: ',len(World.cell_list) print 'Resistance: ', environment.Environment().resistance # ###----------Obsolete Code----------### # #print 'Tick: ',i,'\t\tfood: ',len(World.food_set),'\t\tcells: ',len(World.cell_list) # #print 1000/ # ###--------END Obsolete Code--------### (worldClock.tick(60) + 0.00000000001) World.tick() World.print_table("Main_Test.txt","Tick: "+str(i)) # ###MAIN LOOP END### # Closes the graphics thread if the main loop is broken dis._Thread__stop()
def start(self): "start all motors,sensor,rc" self.camera.start() self.camserver.start() self.sensor.start() self.server.start() self.rc.start() #self.speaker.start() self.display = display(self.data) self.display.start()
def test(self, fImgs, fLbls, fName): '''Neural network testing after training. INPUT : Images set, labels set (None for autoencoders), name for save. OUTPUT : Nothing''' if PREPROCESSING: fImgs, _key = ld.normalization(fName, fImgs) print "Testing the neural networks..." _out = self.propagation(fImgs.T) _cost = self.error(_out[-1], fImgs.T) / len(fImgs) print "Cost {0}\n".format(_cost) # Save output in order to have a testset for next layers if fName is not None: self.save_output(fName, "test", fImgs) # Displaying the results if PREPROCESSING: _decrypt = np.dot(_out[-1],_key.T) dy.display(fName, "out", fImgs, _decrypt.T) else: dy.display(fName, "out", fImgs, _out[-1].T) # Approximated vision of first hidden layer neurons dy.display(fName, "neurons", self.neurons_vision())
def updatetabs(self, infile): name=str(infile) imlist=self.obsdict[name] detmode=imlist[headerList.index('DETMODE')].strip().upper() obsmode=imlist[headerList.index('OBSMODE')].strip().upper() #update the information panel try: self.infoTab.update(name, self.obsdict[name]) print("UPDATING tabs with %s" % name) except Exception as e: print(e) return if self.thread.isRunning() and self.nothread: self.nothread=False #update the DQ tab try: self.dqTab.updatetab(name, self.obsdict[name]) #self.dqTab=DQWidget(name, self.obsdict[name]) #self.tabWidget.removeTab(1) #self.tabWidget.insertTab(1, self.dqTab, 'DQ') except Exception as e: print(e) return #display the image try: rfile='mbxp'+name cfile=rfile.replace('.fits', '.cat') display(rfile, cfile) except Exception as e: print(e) #update the spectra plot if obsmode=='SPECTROSCOPY': self.updatespecview(name)
def main(options): # print('__main__') options = Options.from_arguments(arguments) if options.collecting_data: data_collection = DataCollection(options) data_collection.collect_data() elif options.display_data: display(options) elif options.test: print('running tests...') suite = unittest.TestSuite() for t in [test.split('.')[0] for test in glob.glob('test_*.py')]: try: # If the module defines a suite() function, call it to get the suite. mod = __import__(t, globals(), locals(), ['suite']) suitefn = getattr(mod, 'suite') suite.addTest(suitefn()) except (ImportError, AttributeError): # else, just load all the test cases from the module. suite.addTest(unittest.defaultTestLoader.loadTestsFromName(t)) unittest.TextTestRunner().run(suite)
def __init__(self): self.commands = { "help": self.print_help, "start": self.start_game, "test": self.test, } self.direction_to_const = { "horizontal": board.Board.HORIZONTAL, "vertical": board.Board.VERTICAL } self.ship_type_to_index = {} for i in range(0, len(constants.SHIPS)): self.ship_type_to_index[constants.SHIPS[i][0]] = i self.display = display.display()
def main(): bar = Bar('Processing',max = parameters.numGenerations) individualList = generateFirstGen(parameters.numSets, parameters.startingStrategyDistribution)#Makes the first generation actionsPlayed = [] for gen in range(parameters.numGenerations):#Plays the game for the number of generations specified playerSetList = makeSets(individualList)#Groups players randomly to play together for playerSet in playerSetList: gameMoves = playGame(playerSet, gen >= (parameters.numGenerations - parameters.collectGenerations))#Players are put through the game, and get payoffs dependant upon their strategies actionsPlayed += gameMoves individualList = birthGen(individualList)#Takes the payoffs of the old game and makes the new generation mutatePlayers(individualList)#Takes a new generation, and with some probability mutates players bar.next() # diplay the resultant strategies display(individualList,actionsPlayed) bar.finish()
def mainloop(self, ROM, FPS, sfile): self.initialize() self.load(ROM) self.display = display() clock = pygame.time.Clock() # self.process_events() may set self.running to False, # that's why it is in the while loop # # I am using `or` because self.process_events always returns None, # and we don't really care about it. It is just there to be # executed before the loop body starts while self.process_events(): self.cycle() clock.tick(FPS)
def commonhashtags(self,key=None,numberOfHashtags=3): if key == None: key = "" else: key = key.split(",") adict = display.display(key) returnstring = "[" for i in range(int(numberOfHashtags)): try: m = max(adict, key=adict.get) returnstring = returnstring + '"%s",'%(m) del adict[m] except ValueError: break returnstring = returnstring[:-1] return returnstring + "]"
def display(self): if self.HIDE_EMPTY and len(self.matches) == 0: return display(config.TITLE_FORMAT, name=self.NAME, count=len(self.matches)) if len(self.displays) == 0: return for issue in self.displays: display(config.PREFIX_FORMAT + self.FORMAT, issue=issue, browse=config.URL + 'browse/') display()
def main(): global gameinfo gameinfo = readmap.ReadMap('1.map') newmover = mover.Mover(x=gameinfo.gamemap.start[0]*32,y=gameinfo.gamemap.start[1]*32, direction=0, speed=0) cam = camera.cam(newmover.x, newmover.y, width, height, gameinfo.gamemap.width()*32, gameinfo.gamemap.height()*32) ui = display.display() while True: pygame.event.pump() newmover.loop(gameinfo, screen) #Gamemap display for k in gameinfo.gamemap.map(): for i in k: screen.blit(i.mat, (i.posx*32-cam.x,i.posy*32-cam.y)) #Entity display for ent in gameinfo.entlist.entlist: offcount = (32-ent.height,32-ent.width) screen.blit(ent.mat, (ent.position()[0]+offcount[0]/2-cam.x, ent.position()[1]+offcount[1]-cam.y)) #Player display screen.blit(newmover.image, (newmover.x-cam.x,newmover.y-cam.y)) #UI elements ui.ui(screen, cam, newmover, gameinfo) #Camera update cam.move(newmover.x, newmover.y) pygame.display.flip() clock.tick(90)
def run(e, n_termites=1, n_woods=1, size=100, ticks=100000, command_line=True): w = world(density=0.3, size=size, n_woods=n_woods) for _ in range(n_termites): w.add_termite(termite(x=random.randint(0, size-1), y=random.randint(0, size-1))) if not command_line: disp = display(size=size, scale=4) running = True out = [] while running: if not command_line: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False w.tick() if w.ticks % e is 0: out.append((w.ticks, w.pile_count())) if not command_line: disp.redraw(w) if w.ticks > ticks: running = False return out
def __init__(self, n_bees, n_flowers, width, height, depth): self.bee_count = 40 self.flower_count = 80 self.width = width self.height = height self.depth = depth self.hive = (width / 2, height / 2, depth / 2) self.total = 1 self.bee = list() self.bee_old = list() self.flower = list() self.bee_net = list() self.fit = list() self.gen_count = 0 self.timer = 0 self.disp = display.display(width, height) for i in range(0, self.bee_count): self.fit.append(0.0) for i in range(0, self.flower_count): x = random.randrange(50, self.width - 50) z = random.randrange(50, self.depth - 50) self.flower.append((x, self.hive[1] - 60, z, 0))
def normalization(fName, fSets): print "Data preprocessing...\n" dy.display(fName, "input", fSets) _sets = fSets # Mean subtraction _shifted = _sets - np.mean(_sets, 0) # Covariance _cov = np.dot(_shifted.T, _shifted) / _shifted.shape[0] # SVD factorisation _U, _S, _V = np.linalg.svd(_cov) # Decorrelation _decorrelated = np.dot(_shifted, _U) del(_shifted) dy.display(fName, "decorrelated", np.dot(_decorrelated, _U.T)) # Whitening _whitened = _decorrelated / np.sqrt(_S + 1e-2) del(_decorrelated) dy.display(fName, "whitened", np.dot(_whitened, _U.T)) return _whitened, _U
framerate = 60 #Since it's going to be used a ton, short name gv for global variable access #TODO add in config.ini class to fill in globalvars gv = globalvars.globalvars(size, framerate) gv.version = "Flippy Pad 0.3" #should toss time in a class eventually gv.Clock = pygame.time.Clock() gv.Clock.tick() displayinstance = display.display(gv) consoleinstance = console.console(gv) eventsinstance = events.events(gv) flippy = flippy_pad.flippy(gv) #gv.console.log("MAIN: TEST LOG ENTRY - WEE!") while 1: eventsinstance.handleEvents() flippy.update() consoleinstance.begin()
def saltfpringfit(images, outfile, section=None, bthresh=5, niter=5, displayimage=True, clobber=True,logfile='salt.log',verbose=True): with logging(logfile,debug) as log: # Check the input images infiles = saltio.argunpack ('Input',images) # read in the section if section is None: section=saltio.getSection(section) msg='This mode is not supported yet' raise SaltError(msg) else: section=saltio.getSection(section) print section # open each raw image file for img in infiles: #open the fits file struct=saltio.openfits(img) data=struct[0].data #only keep the bright pixels y1,y2,x1,x2=section bmean, bmedian, bstd=iterstat(data[y1:y2,x1:x2], sig=bthresh, niter=niter, verbose=False) message="Image Background Statistics\n%30s %6s %8s %8s\n%30s %5.4f %5.4f %5.4f\n" % \ ('Image', 'Mean', 'Median', 'Std',img, bmean, bmedian, bstd) log.message(message, with_stdout=verbose) mdata=data*(data-bmean>bthresh*bstd) #prepare the first guess for the image ring_list=findrings(data, thresh=5, niter=5, minsize=10) if displayimage: regfile=img.replace('.fits', '.reg') print regfile if clobber and os.path.isfile(regfile): fout=saltio.delete(regfile) fout=open(regfile, 'w') fout.write("""# Region file format: DS9 version 4.1 # Filename: %s global color=green dashlist=8 3 width=1 font="helvetica 10 normal roman" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1 physical """ % img) for ring in ring_list: print ring fout.write('circle(%f, %f, %f)\n' % (ring.xc,ring.yc,ring.prad)) fout.write('circle(%f, %f, %f)\n' % (ring.xc,ring.yc,ring.prad-5*ring.sigma)) fout.write('circle(%f, %f, %f)\n' % (ring.xc,ring.yc,ring.prad+5*ring.sigma)) fout.close() display(img, catname=regfile, rformat='reg') #write out the result for viewing struct[0].data=mdata saltio.writefits(struct, 'out.fits', clobber=True) message = 'Ring Parameters' log.message(message)
#self.tabWidget.removeTab(1) #self.tabWidget.insertTab(1, self.dqTab, 'DQ') except Exception, e: print e return #display the image try: if name.startswith('S') or name.startswith('P'): rfile='mbxp'+name cfile=rfile.replace('.fits', '.cat') else: rfile = name + 's' cfile = None display(rfile, cfile) except Exception, e: print e #update the spectra plot if obsmode=='SPECTROSCOPY': self.updatespecview(name) def clickfordata(self, event): #print self.watcher, dir(self.watcher) #look for new data self.checkfordata(self.obsdate, self.imdir)
def X__str__(self): g = list(row.to_pytuple() for row in self) return '\n'.join(display.display(g,self.names))
def solution(grid): vals = solve(grid) d.display(vals)
import display from numpy import zeros from time import sleep data = zeros([150]) data[0:3] = 255 # print data sockets = display.make_sockets(["36"]) while 1: print "do what with data?" r = input(">") data[0:3] = r # import pdb; pdb.set_trace() display.display(data, sockets[0]) sleep(0.001)
dispPlyrs = [] for p in plyrs: if p == "": continue pName, cards, mny, bet = p.split(",") if len(cards) == 0: cards = (None,None) else: cards = [card(cards[0], cards[1]), card(cards[2], cards[3])] dispPlyrs.append((pName, cards,int(mny),int(bet))) i = 0 print tblCards dispTblCards = [] while i < len(tblCards): dispTblCards.append(card(tblCards[i],tblCards[i+1])) i += 2 display.display(dispPlyrs, dispTblCards, int(pot), name, actPlyr, btn, nxtBlndRs, [int(b) for b in blnds.split('/')], msg) s.send("OK") elif nxtMsg[0] == "MSG": display.displayMsg(nxtMsg[1]) msg = nxtMsg[1] s.send("OK") elif nxtMsg[0] == "QUIT": break s.close() display.exit()