def build_markdown(): # Build the markdown in stages. Live matches first, then past matches markdown_template = '' if strafe.live_matches and strafe.live_match_stats: try: markdown_template = read('template/strafe_widget_md_template.txt') markdown_template = build_live_match(markdown_template) if strafe.past_matches: markdown_template = build_past_matches(markdown_template) except IOError: logging.exception('{} - IOError opening md template!'.format( datetime.now().strftime('%Y-%m-%d %H:%M:%S'))) elif strafe.past_matches: try: markdown_template = read( 'template/strafe_widget_md_nolive_template.txt') markdown_template = build_past_matches(markdown_template) except IOError: logging.exception('{} - IOError opening md template!'.format( datetime.now().strftime('%Y-%m-%d %H:%M:%S'))) # If the markdown template isn't empty, save a copy # to our cache and begin the upload process if markdown_template != '' and strafe.past_matches: save('app-cache/finished_markdown.txt', markdown_template) r.widget_markdown = markdown_template upload_widget()
def input_partners_manual(data): """ This is used if there is no partners.prtnrs file. :param data: Empty list. User will populate this and then it will be saved back to partners.prtnrs. :return: list of partners to be used elsewhere """ count = input('Number of partners: ') print(type(int(count)), ' ' + count) for x in range(0, int(count)): partner = {'name': '', 'hours': 0, 'tips': 0} partner['index'] = x partner['name'] = input('Partner Name: ') data.append(partner) file_manager.save('partners', data) return list
def save(relative_path, data): global config_path return file_manager.save(config_path + relative_path, data)
def handle_post_thread(self, data, path): self.send_response(HTTPStatus.OK) self.send_header("Content-type", "application/JSON") self.end_headers() if "code[]" not in data: data["code[]"] = [""] if path == "/cancel": self.cancellation_event.set() if path == "/process2": self.cancellation_event.clear( ) # Make sure we don't have lingering cancellation requests from before code = data["code[]"] curr_i = int(data["curr_i"][0]) curr_f = int(data["curr_f"][0]) global_frame_id = int(data["globalFrameID"][0]) visualize_tail_calls = data["tailViz"][0] == "true" self.wfile.write( bytes( handle(code, curr_i, curr_f, global_frame_id, visualize_tail_calls, cancellation_event=self.cancellation_event), "utf-8")) elif path == "/save": code = data["code[]"] filename = data["filename"][0] do_save = data["do_save"][0] == "true" if do_save: save(code, filename) self.wfile.write( bytes( json.dumps({ "result": "success", "stripped": strip_comments(code) }), "utf-8")) elif path == "/instant": code = data["code[]"] global_frame_id = int(data["globalFrameID"][0]) self.wfile.write(bytes(instant(code, global_frame_id), "utf-8")) elif path == "/reformat": code = data["code[]"] javastyle = data["javastyle"][0] == "true" self.wfile.write( bytes( json.dumps({ "result": "success", "formatted": prettify(code, javastyle) }), "utf-8")) elif path == "/test": self.cancellation_event.clear( ) # Make sure we don't have lingering cancellation requests from before output = cancelable_subprocess_call( self.cancellation_event, (sys.argv[0], os.path.splitext(ok_interface.__file__)[0] + ".py"), -1, sys.executable, subprocess.PIPE, subprocess.PIPE, None) self.wfile.write(output.split(ok_interface.BEGIN_OUTPUT)[1]) elif path == "/list_files": self.wfile.write(bytes(json.dumps(get_scm_files()), "utf-8")) elif path == "/read_file": filename = data["filename"][0] self.wfile.write(bytes(json.dumps(read_file(filename)), "utf-8")) elif path == "/new_file": filename = data["filename"][0] self.wfile.write( bytes(json.dumps({"success": new_file(filename)}), "utf-8")) elif path == "/save_state": global state for key, val in json.loads(data["state"][0]).items(): if key == "states": if "states" not in state: state["states"] = val else: merge(state["states"], val) else: state[key] = val if "settings" in state: save_config("settings", state["settings"]) elif path == "/load_state": if "states" not in state: self.wfile.write(b"fail") else: self.wfile.write(bytes(json.dumps(state), "utf-8")) elif path == "/load_settings": try: if "settings" not in state: state["settings"] = {} for key, val in load_config("settings").items(): state["settings"][key] = val except FileNotFoundError: self.wfile.write(b"fail") else: self.wfile.write(bytes(json.dumps(state["settings"]), "utf-8")) elif path == "/documentation": query = data.get("query", [""])[0] self.wfile.write(bytes(json.dumps(search(query)), "utf-8")) elif path == "/kill": # This is (only) fine because we're in a different thread than the actual server self.server.shutdown() self.server.socket.close()
def main(): # Spin up the object detector obj_detect = edgeiq.ObjectDetection("alwaysai/" + OBJECT_DETECTION_MODEL) obj_detect.load(engine=edgeiq.Engine.DNN_CUDA, accelerator=edgeiq.Accelerator.NVIDIA) print("Engine: {}".format(obj_detect.engine)) print("Accelerator: {}\n".format(obj_detect.accelerator)) print("Model:\n{}\n".format(obj_detect.model_id)) print("Labels:\n{}\n".format(obj_detect.labels)) # Prepare to track frames per second calculations fps = edgeiq.FPS() # Load any prior instance of the tracker, otherwise spin up a new one centroid_tracker = file_manager.load( CENTROID_TRACKER, edgeiq.CentroidTracker(deregister_frames=TRACKER_DEREGISTER_FRAMES, max_distance=TRACKER_MAX_DISTANCE)) # Load any prior instance of the metrics data, otherwise start a new one metrics = file_manager.load(METRICS_MANAGER, metrics_manager.MetricsManager()) try: if IP_CAMERA_FEED is not None: stream_details = edgeiq.IPVideoStream(IP_CAMERA_FEED) else: stream_details = edgeiq.WebcamVideoStream(cam=0) with stream_details as video_stream, \ edgeiq.Streamer() as streamer: # Allow Webcam to warm up time.sleep(2.0) fps.start() # Loop detection and centroid tracker while True: metrics.newLoop() frame = video_stream.read() results = obj_detect.detect_objects( frame, confidence_level=DETECT_CONFIDENCE_THRESHOLD) # Ignore detections of anything other than people filter = edgeiq.filter_predictions_by_label( results.predictions, ['person']) # Adding info for streamer display text = ["Model: {}".format(obj_detect.model_id)] text.append("Inference time: {:1.3f} s".format( results.duration)) text.append("People currently detected:") objects = centroid_tracker.update(filter) # Store active predictions for just this loop predictions = [] # Store the active object ids for just this loop if len(objects.items()) == 0: # No people detected text.append("-- NONE") for (object_id, prediction) in objects.items(): metrics.addTimeFor(object_id) timeForId = metrics.timeForId(object_id) # Correcting for fact that index 0 is first object in an array idAdjusted = object_id + 1 # Display text with bounding box in video new_label = "Person {i} | {t} sec".format(i=idAdjusted, t=timeForId) prediction.label = new_label text.append(new_label) predictions.append(prediction) # Add metrics to text going to streamer m = metrics.currentMetrics() text.append("") # Spacing text.append("Total people seen: {}".format(m["count"])) text.append("Total time: {} sec".format(m["total"])) text.append("Average time: {0:.1f} sec".format(m["avg"])) text.append("Longest individual time: {} sec".format(m["max"])) # Update output streamer frame = edgeiq.markup_image(frame, predictions) streamer.send_data(frame, text) fps.update() if streamer.check_exit(): break finally: fps.stop() # TODO: Update to save every few seconds in case a crash occurs file_manager.save(metrics, METRICS_MANAGER) file_manager.save(centroid_tracker, CENTROID_TRACKER) print("elapsed time: {:.2f}".format(fps.get_elapsed_seconds())) print("approx. FPS: {:.2f}".format(fps.compute_fps())) print("Program Ending")
def handle_post_thread(self, data, path): if (b'code[]' not in data): data[b'code[]'] = [b''] if (path == '/cancel'): self.cancellation_event.set() self.send_response(HTTPStatus.OK, 'test') self.send_header('Content-type', 'application/JSON') self.end_headers() if (path == '/process2'): self.cancellation_event.clear() code = [x.decode('utf-8') for x in data[b'code[]']] curr_i = int(data[b'curr_i'][0]) curr_f = int(data[b'curr_f'][0]) global_frame_id = int(data[b'globalFrameID'][0]) self.send_response(HTTPStatus.OK, 'test') self.send_header('Content-type', 'application/JSON') self.end_headers() self.wfile.write( bytes( handle(code, curr_i, curr_f, global_frame_id, cancellation_event=self.cancellation_event), 'utf-8')) elif (path == '/save'): code = [x.decode('utf-8') for x in data[b'code[]']] filename = data[b'filename'][0] do_save = (data[b'do_save'][0] == b'true') if do_save: save(code, filename) self.send_response(HTTPStatus.OK, 'test') self.send_header('Content-type', 'application/JSON') self.end_headers() self.wfile.write( bytes( json.dumps({ 'result': 'success', 'stripped': strip_comments(code), }), 'utf-8')) elif (path == '/instant'): code = [x.decode('utf-8') for x in data[b'code[]']] global_frame_id = int(data[b'globalFrameID'][0]) self.send_response(HTTPStatus.OK, 'test') self.send_header('Content-type', 'application/JSON') self.end_headers() self.wfile.write(bytes(instant(code, global_frame_id), 'utf-8')) elif (path == '/reformat'): code = [x.decode('utf-8') for x in data[b'code[]']] javastyle = (data[b'javastyle'][0] == b'true') self.send_response(HTTPStatus.OK, 'test') self.send_header('Content-type', 'application/JSON') self.end_headers() self.wfile.write( bytes( json.dumps({ 'result': 'success', 'formatted': prettify(code, javastyle), }), 'utf-8')) elif (path == '/test'): self.cancellation_event.clear() output = cancelable_subprocess_call( self.cancellation_event, (sys.argv[0], (os.path.splitext(ok_interface.__file__)[0] + '.py')), (-1), sys.executable, subprocess.PIPE, subprocess.PIPE, None) self.send_response(HTTPStatus.OK, 'test') self.send_header('Content-type', 'application/JSON') self.end_headers() self.wfile.write(output) elif (path == '/list_files'): self.send_response(HTTPStatus.OK, 'test') self.send_header('Content-type', 'application/JSON') self.end_headers() self.wfile.write(bytes(json.dumps(get_scm_files()), 'utf-8')) elif (path == '/read_file'): filename = data[b'filename'][0] self.send_response(HTTPStatus.OK, 'test') self.send_header('Content-type', 'application/JSON') self.end_headers() self.wfile.write(bytes(json.dumps(read_file(filename)), 'utf-8')) elif (path == '/new_file'): filename = data[b'filename'][0].decode('utf-8') self.send_response(HTTPStatus.OK, 'test') self.send_header('Content-type', 'application/JSON') self.end_headers() self.wfile.write( bytes(json.dumps({ 'success': new_file(filename), }), 'utf-8')) elif (path == '/save_state'): global state for (key, val) in json.loads(data[b'state'][0].decode('utf-8')).items(): if (key == 'states'): if ('states' not in state): state['states'] = val else: merge(state['states'], val) else: state[key] = val if ('settings' in state): save_config('settings', state['settings']) self.send_response(HTTPStatus.OK, 'test') self.send_header('Content-type', 'application/JSON') self.end_headers() elif (path == '/load_state'): self.send_response(HTTPStatus.OK, 'test') self.send_header('Content-type', 'application/JSON') self.end_headers() if ('states' not in state): self.wfile.write(b'fail') else: self.wfile.write(bytes(json.dumps(state), 'utf-8')) elif (path == '/load_settings'): self.send_response(HTTPStatus.OK, 'test') self.send_header('Content-type', 'application/JSON') self.end_headers() try: if ('settings' not in state): state['settings'] = {} for (key, val) in load_config('settings').items(): state['settings'][key] = val except FileNotFoundError: self.wfile.write(b'fail') else: self.wfile.write(bytes(json.dumps(state['settings']), 'utf-8')) elif (path == '/documentation'): self.send_response(HTTPStatus.OK, 'test') self.send_header('Content-type', 'application/JSON') self.end_headers() query = data.get(b'query', [b''])[0].decode('utf-8') self.wfile.write(bytes(json.dumps(search(query)), 'utf-8')) elif (path == '/kill'): self.server.shutdown() self.server.socket.close()
def run_loop(data): """ Main loop for getting the user's tip information :param data: The list of partners at the store :return: - """ while True: cmd = input( '[E]nter tip data, [R]emove Partners, [A]dd partners, [L]ist, or [Q]uit : ').lower() if cmd == 'e': if file_manager.temp_file_check() is True: print_hours(data) # TODO This shit is broke AF while True: try: cmd = int(input('Index: ')) if cmd < 0: if debug is True: print("Would save here.") break else: file_manager.save_temp(data) break else: for x in data: if x["index"] == cmd: try: cmd = float(input(x['name'] + ': ')) except ValueError: print("you must enter an integer") if float(cmd) < 0: continue else: x['hours'] = float(cmd) break # print(data) except ValueError: print("you must enter an integer") sum_hours = 0 # if the user enters -1 then the program closes nicely if file_manager.temp_file_check() is False: data = get_input.input_hours(data, debug) if data is None: print('No data entered.') continue # print(data) # TODO Fix so that it handles unexpected results. if file_manager.temp_file_check() is True: print( "Total Tips is {}. Enter a new value or -1 to keep this value.".format(total_money)) input_val = float(input('Total tips: ')) if input_val > -1: total_money = input_val for x in data: sum_hours += x['hours'] tips_per_hour = calculate.tph(sum_hours, total_money) tips_per_hour = float("%.3f" % tips_per_hour) print(tips_per_hour) calculate.itph(tips_per_hour, data) tip_total_under = calculate.under(data) print("Tips Under {}".format(total_money - tip_total_under)) od = calculate.sort_dec(data) final_list = calculate.distribute_under( od, total_money, tip_total_under, debug) if debug is True: checksum = 0 for s in data: checksum += int(s['tips']) print(checksum) final_list = sort_by_index(final_list) # pretty_print(final_list) pretty_print_plus(final_list, tips_per_hour) file_manager.save_temp(data) elif cmd == 'r': for idx, x in enumerate(data): print(idx + 1, x) print( 'Please enter the name of the partner you need to remove\n' ' (Enter a -1 to cancel.)\n') while True: try: cmd = int(input('Index: ')) if cmd < 0: if debug is True: print("Would save here.") break else: file_manager.save('partners', data) break else: data = file_manager.remove_entry(cmd - 1, data) for idx, x in enumerate(data): print(idx + 1, x) except ValueError: print("you must enter an integer") elif cmd == 'a': new_partner = 'Empty' new_partner_dict = {'name': '', 'hours': 0, 'tips': 0} pos = 0 print('Please enter the name of the new partner,\nthen the position in the list.\n' ' (1 is the first position in the list, 2 is the second position and so on.)\n' ' (type "print" to see current list)\n' ' (type "done" when finished)') while new_partner.lower() != 'done' or new_partner.lower() != 'd': new_partner = input('Input: ') if new_partner.lower() == 'done' or new_partner.lower() == 'd' or new_partner == '-1': file_manager.save('partners', data) break elif new_partner.lower() == 'p' or new_partner.lower() == 'print': for x in data: print(x) print('') else: while True: try: pos = int(input('Index: ')) break except ValueError: print("you must enter an integer") new_partner_dict['name'] = new_partner new_partner_dict['index'] = pos - 1 file_manager.add_entry(data, new_partner_dict) elif cmd == 'l': pretty_print(data) elif cmd == "q": print('quitting program.') if file_manager.temp_file_check() is True: file_manager.remove_temp() break else: print("oops that's not a command. Please try again.") print()
def init_index(data): count = 0 for x in data: x['index'] = count count = count + 1 file_manager.save('partners', data)
def re_init(data): for x in data: x['hours'] = 0 x['tips'] = 0 file_manager.save('partners', data)
def main(): # Declare local variables. choice = 0 # ISBN storage. isbn10 = '0000000000' isbn13 = '0000000000000' # ISBN display storage. isbn_pr = '' isbn_pr = '' # Call the isbn_format function to format ISBN numbers for display. isbn10_pr, isbn13_pr = isbn_format.hyphenate(isbn10, isbn13) while choice != EXIT: # Display the menu display_menu(isbn10_pr, isbn13_pr) # Get the user's choice. choice = int(input('Enter your choice: ')) # Perform the selected action. if choice == VERIFY_10: # Option to use current ISBN-10. memory = str(input('Would you like to verify the current ' 'ISBN-10 in memory? (y/n) ' )) if memory == 'y' or memory == 'Y': # Convert characters to uppercase. isbn10 = isbn10.upper() # Call the function to verify the check digit of the ISBN-10. isbn10 = verify.verify10(isbn10) else: # Get an ISBN-10 from the user. isbn10 = str(input('Enter an ISBN-10 (without hyphens): ')) # Call the isbn10_check function to validate data. isbn10 = isbn10_check(isbn10) isbn10 = isbn10.upper() isbn10 = verify.verify10(isbn10) isbn10_pr, isbn13_pr = isbn_format.hyphenate(isbn10, isbn13) elif choice == VERIFY_13: # Option to use current ISBN-13. memory = str(input('Would you like to verify the current ' 'ISBN-13 in memory? (y/n) ' )) if memory == 'y' or memory == 'Y': # Call the function to verify the check digit of the ISBN-13. isbn13 = verify.verify13(isbn13) else: # Get an ISBN-13 from the user. isbn13 = str(input('Enter an ISBN-13 (without hyphens): ')) # Call the isbn13_check function to validate data. isbn13 = isbn13_check(isbn13) isbn13 = verify.verify13(isbn13) isbn10_pr, isbn13_pr = isbn_format.hyphenate(isbn10, isbn13) elif choice == TEN_TO_THIRTEEN: # Option to use current ISBN-10. memory = str(input('Would you like to convert the current ' 'ISBN-10 in memory? (y/n) ' )) if memory == 'y' or memory == 'Y': # Convert characters to uppercase. isbn10 = isbn10.upper() # Call the function to convert an ISBN-10 to an ISBN-13. isbn13 = convert.convert10(isbn10) else: # Get an ISBN-10 from the user. isbn10 = str(input('Enter an ISBN-10 (without hyphens): ')) # Call the isbn10_check function to validate data. isbn10 = isbn10_check(isbn10) isbn10 = isbn10.upper() isbn13 = convert.convert10(isbn10) isbn10_pr, isbn13_pr = isbn_format.hyphenate(isbn10, isbn13) elif choice == THIRTEEN_TO_TEN: # Option to use current ISBN-13. memory = str(input('Would you like to convert the current ' 'ISBN-13 in memory? (y/n) ' )) if memory == 'y' or memory == 'Y': # Call the function to convert an ISBN-13 to an ISBN-10. isbn10 = convert.convert13(isbn13) else: # Get an ISBN-13 from the user. isbn13 = str(input('Enter an ISBN-13 (without hyphens): ')) # Call the isbn13_check function to validate data. isbn13 = isbn13_check(isbn13) isbn10 = convert.convert13(isbn13) isbn10_pr, isbn13_pr = isbn_format.hyphenate(isbn10, isbn13) elif choice == LOAD: # Call the function to load ISBN numbers from a file. isbn10, isbn13 = file_manager.load(isbn10, isbn13) isbn10_pr, isbn13_pr = isbn_format.hyphenate(isbn10, isbn13) elif choice == SAVE: # Call the function to save the ISBN numbers to a file. file_manager.save(isbn10, isbn13) elif choice == EXIT: # Call the function to exit program. print('Exiting the program...') else: print('Error: Invalid selection.')