def season_retire(self): # Decides if a player retired and if so, sets retired = True # Returns True if retired, False if not # & Run once per season age_norm = HelperMethods.normalize(self.age, PLAYER_GLOBALS["MIN_AGE"], PLAYER_GLOBALS["MAX_AGE"]) skill_norm = HelperMethods.normalize(self.skill, PLAYER_GLOBALS["MIN_SKILL"], PLAYER_GLOBALS["MAX_SKILL"]) if age_norm >= 1: self.retired = True return True elif age_norm >= 0.9: if random.random() >= 0.5: self.retired = True return True elif age_norm >= 0.8: if skill_norm <= 0.15: self.retired = True return True else: if random.random() >= 0.25: self.retired = True return True elif age_norm >= 0.7 and skill_norm <= 0.1: self.retired = True return True return False
def signUp(): # check if fields are empty, if password match and if email is in correct format if hm.check_fields_inputs( fNameEntry=f_name_entry, middleInitialEntry=middle_initial_entry, lNameEntry=l_name_entry, instEntry=inst_entry, passwordEntry=password_entry, reEnterPasswordEntry=retype_password_entry, emailEntry=email_entry, checkEmailFormat=email_entry.get()): get_values() print(self.first_name) print(self.middle_Initial) print(self.last_name) print(self.institution) # Check if email is already in use by another researcher if conn.email_exist(email_entry.get()): hm.showerror( "Error", "\u2022 This email is already registered.\n Please use another email" ) else: # Call the function to hash pw and save it to variable hashed_pw = hash_password(self.pw) # Save new researcher into Azure database conn.insert(conn.researcher, self.email, hashed_pw, self.first_name, self.middle_Initial, self.last_name, self.institution) controller.show_login_frame()
def season_training_increase_per_turn(self): # Sets increase_per_turn -> how much a player trains per turn # Returns True if worked, False if not # & Run once per season if self.age >= PLAYER_GLOBALS["MIN_AGE"]: age_int = PLAYER_GLOBALS["AGE_TRAINING_INF"] inc_int = PLAYER_GLOBALS["TRAINING_PER_AGE"] age_norm = HelperMethods.normalize(self.age, PLAYER_GLOBALS["MIN_AGE"], PLAYER_GLOBALS["MAX_AGE"]) skill_norm = HelperMethods.normalize(self.skill, PLAYER_GLOBALS["MIN_SKILL"], PLAYER_GLOBALS["MAX_SKILL"]) skill_inf = 1 if skill_norm >= 0.85: skill_inf = 0.5 for index, age_range in enumerate(age_int): if age_norm < age_range: x1 = age_int[index] x2 = age_int[index - 1] y1 = inc_int[index] y2 = inc_int[index - 1] increase = HelperMethods.ysolver(point1=(x1, y1), point2=(x2, y2), x=age_norm) break self.increase_per_turn = (increase * skill_inf) / float( GAME_GLOBALS["TOTAL_TURNS"]) return True return False
def save_count_per_day_to_file(h_list, hyrax_dict): date_times = h.initialize_specific_range() for i in h_list: for j in h_list: if i != j: if os.path.isfile(list_prefix.format('day', str(i), str(j))): continue days_count = [0] * 61 night_count = [0] * 61 mtx_a = h.load_lil(h.get_npz_file_name(i, j)) non_zero = mtx_a.nonzero()[1] for v in non_zero: date, time, night = h.get_time_of_day(date_times, v) delta = date - start_date if night == 1: night_count[delta.days] += 1 else: days_count[delta.days] += 1 save_list(list_prefix.format('day', str(i), str(j)), days_count) save_list(list_prefix.format('night', str(i), str(j)), night_count)
def findPath(gdict, fig, ax, limits, startPoint, endPoint, line, type): '''findPath Finds the shortest path with the algorithm specified by 'type'. calls: Helper.findClosestNode() finds the valid node closest to specified start/end points PathOptimizer.*() path optimization algorithm args: gdict edge graph with distances fig a figure ax an axis limits the limits of the bounding box startPoint starting point of the path endPoint end point of the path line 2d matplotlib line object type algorithm type, accepts 'd[ijkstra]' or 'a[star]' return: None ''' #The big ugly function gets the keys into a list of tuples [(1,2),(3,4),...] r1 = Helper.findClosestNode(list(zip(*zip(*gdict.keys()))), startPoint) r2 = Helper.findClosestNode(list(zip(*zip(*gdict.keys()))), endPoint) sys.setrecursionlimit(1500) try: t1 = time.time() if (type.lower().startswith('a')): sp = PathOptimization.AStar(gdict, r1, r2) elif (type.lower().startswith('d')): sp = PathOptimization.dijkstra(gdict, r1, r2) pass t2 = time.time() print(sp[1]) print(r1) print(r2) pathlength = sp[0] foundPath = sp[1] foundPath.insert(0,startPoint) foundPath.append(endPoint) print(foundPath) print("Time taken: {0}s".format(t2 - t1)) # sp contains sp[0] - the path length, sp[1] the nodes taken; we set line data to the nodes line.set_xdata([p[0] for p in foundPath]) line.set_ydata([p[1] for p in foundPath]) except Exception as e: print("Not a valid path optimizer!") print("We will still return though.") print(str(e)) pass
def main(argv): with open(argv[1], 'r') as wf: window = int(wf.read()) # stick data into memory since other way took too long and was wrong with open(argv[2], 'r') as af: actualData = HM.makeDictionary(af.read()) with open(argv[3], 'r') as pf: predictedData = HM.makeDictionary(pf.read()) # del predictedData[None] try: predictedKeys = HM.sortedKeys(predictedData) except TypeError as e: print(e) sys.exit() resultDict = {} for hour in predictedKeys: # gives us sequential access to hours # so have numbers n ... n+n # need to calculate diff between two dictionaries hourError, numError = HM.diffDictionaries(predictedData[hour], \ actualData[hour]) resultDict[hour] = (hourError, numError) head = predictedKeys[0] tail = head + window - 1 with open(sys.argv[4], 'w') as outFile: while tail <= predictedKeys[-1]: missingT, missingH = False, False try: headIndex = predictedKeys.index(head) except ValueError as e: missingH = True try: tailIndex = predictedKeys.index(tail) except ValueError as e: missingT = True errorTotal = sum([ resultDict[e][0] for e in predictedKeys[headIndex:tailIndex + 1] ]) numErrors = sum([ resultDict[e][1] for e in predictedKeys[headIndex:tailIndex + 1] ]) if missingT and missingH: windowError = 'NA' outFile.write("{}|{}|{}\n".format(head, tail, windowError)) missingT, missingH = False, False else: windowError = errorTotal / numErrors outFile.write("{}|{}|{:.2f}\n".format(head, tail, windowError)) head += 1 tail += 1
def analsys_graph(G): #print("Drawing the graph") #helpers.draw_graph(G) print("analysing the graph") print("Nodes: ", G.number_of_nodes()) print("Edges: ", G.number_of_edges()) # Draw loglog graph... #DG = G.to_directed() print("Drawing the loglog graph") helpers.plot_degseq(G, False) print('')
def __init__(self, params, master=None): Frame.__init__(self, width=300, height=100, bg="black" ) global label_time_text, label_date_text label_time_text = StringVar() label_time = Label(self, textvariable=label_time_text, background='black', foreground="white", bd=0, font=("SFNS Display", 40), anchor=W, justify=LEFT) label_time_text.set(HelperMethods.getFormattedTime()) label_time.place(x=0, y=0, anchor=NW) label_date_text = StringVar() label_date = Label(self, textvariable=label_date_text, background='black', foreground="white", bd=0, font=("SFNS Display", 16), anchor=W, justify=LEFT) label_date_text.set(HelperMethods.getFormattedDate()) label_date.place(x=0, y=70, anchor=NW)
def training(self): # Trains all players in team # & Run once per turn ground_norm = HelperMethods.normalize(5, TEAM_GLOBALS["MIN_TRAINING_GROUND"], TEAM_GLOBALS["MAX_TRAINING_GROUND"]) for player in self.players: skill_norm = HelperMethods.normalize(player.skill, PLAYER_GLOBALS["MIN_SKILL"], PLAYER_GLOBALS["MAX_SKILL"]) if ground_norm >= skill_norm: ground_inf = 1 else: ground_inf = min(max(1 - 3 * (skill_norm - ground_norm), 0), 1) player.turn_training(ground_inf)
def analyse_directed_graph(): graph = load_graph('college', True) # helpers.draw_graph(graph) #print("Graph nodes: ", graph.number_of_nodes()) #print("Graph edges: ", graph.number_of_edges()) # already has edges from dataset... print(nx.info(graph)) analyse_strongly_connected_components(graph) # Draw loglog graph... helpers.plot_degseq(graph, False) # wait at end... input("Press Enter to Continue ...")
def main(): graph = load_graph("facebook") helpers.plot_degseq(graph, False) num_nodes = graph.number_of_nodes() x = [random.random() for i in range(num_nodes)] y = [random.random() for i in range(num_nodes)] x = np.array(x) y = np.array(y) pos = dict() for i in range(num_nodes): pos[i] = x[i], y[i] print("Graph nodes: ", graph.number_of_nodes()) print("Graph edges: ", graph.number_of_edges()) # already has edges from dataset... print("Pos nodes: ", len(pos)) # plot the graph... A = nx.adjacency_matrix(graph) graph = nx.Graph(A) print("Graph nodes after rebuild: ", graph.number_of_nodes()) print("Graph edges after rebuild: ", graph.number_of_edges()) # already has edges from dataset... # Plot the nodes only plot_graph(graph, pos, 1, False) # plot the nodes and edges plot_graph(graph, pos, 2) # reposition with the eigenvectors eigenv_pos, V = repos_with_eigs(A, num_nodes) plot_graph(graph, eigenv_pos, 3) print("Plotting spring layout") pos = nx.spring_layout(graph) plot_graph(graph, pos, 4) # Look at the clustering features = np.column_stack((V[:, 1], V[:, 2])) cluster_nodes_from_original_example(graph, features, pos, eigenv_pos) # Finally, use the columns of A directly for clustering # cluster_nodes_from_original_example(graph, A.todense(), pos, eigenv_pos) # wait at end... input("Press Enter to Continue ...")
def calc_price(self): apparent_skill = self.skill starting_values = PLAYER_GLOBALS["PRICE_AGE"] factors = PLAYER_GLOBALS["PRICE_SKILL"] power = [0, 0, 0, 0, 0, 0] age_norm = HelperMethods.normalize(self.age, PLAYER_GLOBALS["MIN_AGE"], PLAYER_GLOBALS["MAX_AGE"]) age_inf_price = int(age_norm * (len(starting_values) - 2)) point1 = (age_inf_price, starting_values[age_inf_price]) point2 = (age_inf_price + 1, starting_values[age_inf_price + 1]) start_value = Line.Line((point1, point2)).solve_for_y(age_norm * (len(starting_values) - 2)) get_lastpower = (apparent_skill - PLAYER_GLOBALS["MIN_SKILL"]) / 10 get_howmuchpower = (apparent_skill - PLAYER_GLOBALS["MIN_SKILL"]) % 10 for i in range(get_lastpower + 1): power[i] = 3 if i == get_lastpower: power[i] = get_howmuchpower / 3.0 price = start_value * pow(factors[0],power[0]) * pow(factors[1],power[1]) * pow(factors[2],power[2]) * pow(factors[3],power[3]) * pow(factors[4],power[4]) * 1000 if price / 100 >= 1: return int(price) - int(price) % 10 else: return int(price)
def analyse_strongly_connected_components(G): try: num_strongly_connected_components = nx.number_strongly_connected_components( G) print("Strongly Connected Component Count - ", num_strongly_connected_components) comps = helpers.get_strongly_connected_components(G) Gcc = comps[0] print("Biggest connected component size: ", len(Gcc)) # Get in degree incount = 0 for node in G.nodes_iter(): if node not in Gcc: found = False for successor in G.successors(node): if successor in Gcc and not found: incount += 1 found = True print("In degree - ", incount) # Get the out degree outcount = 0 for node in Gcc: # Count number of connections that are not in teh GCC > 0 increments outcount node_out = 0 for neighbour in G.neighbors(node): if neighbour not in Gcc: node_out += 1 if node_out > 0: outcount += 1 print("Outdegree = ", outcount) except Exception as e: print("Exception: - ", e)
def main(): args = parse_arguments() input_path = args.input_path scale = 0.23 if not os.path.exists(args.output_path): os.makedirs(args.output_path) analyzer = DocumentAnalyzer(model=args.model) names = os.listdir(input_path) if not os.path.exists(args.output_path): os.makedirs(args.output_path) length = len(names) count = 0 for img in names: filename, file_extension = os.path.splitext(img) if file_extension.lower() in allowed_extensions: analyzer.__scale = scale coordinates, img_height, img_width = analyzer.get_document_paragraphs(input_path + img, no_layout=args.n) xml_string = HelperMethods.create_page_xml(coordinates, img_width, img_height, filename) with open('{}/{}.xml'.format(args.output_path, os.path.splitext(filename)[0]), 'wb') as f: f.write(xml_string) count += 1 print('Completed: {}/{}'.format(count, length)) return 0
def calc_price(self): apparent_skill = self.skill starting_values = PLAYER_GLOBALS["PRICE_AGE"] factors = PLAYER_GLOBALS["PRICE_SKILL"] power = [0, 0, 0, 0, 0, 0] age_norm = HelperMethods.normalize(self.age, PLAYER_GLOBALS["MIN_AGE"], PLAYER_GLOBALS["MAX_AGE"]) age_inf_price = int(age_norm * (len(starting_values) - 2)) point1 = (age_inf_price, starting_values[age_inf_price]) point2 = (age_inf_price + 1, starting_values[age_inf_price + 1]) start_value = Line.Line( (point1, point2)).solve_for_y(age_norm * (len(starting_values) - 2)) get_lastpower = (apparent_skill - PLAYER_GLOBALS["MIN_SKILL"]) / 10 get_howmuchpower = (apparent_skill - PLAYER_GLOBALS["MIN_SKILL"]) % 10 for i in range(get_lastpower + 1): power[i] = 3 if i == get_lastpower: power[i] = get_howmuchpower / 3.0 price = start_value * pow(factors[0], power[0]) * pow( factors[1], power[1]) * pow(factors[2], power[2]) * pow( factors[3], power[3]) * pow(factors[4], power[4]) * 1000 if price / 100 >= 1: return int(price) - int(price) % 10 else: return int(price)
def minute(self): if self.minutes < MATCH_GLOBALS["TOTAL_TURNS"]: self.home.update_skill_tactic() self.away.update_skill_tactic() self.minutes += 1 self.events = {"Home Possession": False, "Goal": False} home_tactic_inf = [(self.home.tactic[0] - self.away.tactic[2]) * MATCH_GLOBALS["TACTIC_INFLUENCE"], (self.home.tactic[1] - self.away.tactic[1]) * MATCH_GLOBALS["TACTIC_INFLUENCE"], (self.home.tactic[2] - self.away.tactic[0]) * MATCH_GLOBALS["TACTIC_INFLUENCE"]] home_concedes_rat = (self.home.skill[0] - self.away.skill[2]) / float(PLAYER_GLOBALS["MAX_SKILL"]) + home_tactic_inf[0] home_possession_rat = (self.home.skill[1] - self.away.skill[1]) / float(PLAYER_GLOBALS["MAX_SKILL"]) + home_tactic_inf[1] home_scores_rat = (self.home.skill[2] - self.away.skill[0]) / float(PLAYER_GLOBALS["MAX_SKILL"]) + home_tactic_inf[2] home_scores_prob = Line.Line(((-1, MATCH_GLOBALS["MIN_GOAL_PER_POSS"]), (1, MATCH_GLOBALS["MAX_GOAL_PER_POSS"]))).solve_for_y(home_scores_rat) home_possession_prob = Line.Line(((-1, 1 - MATCH_GLOBALS["MAX_POSSESSION"]),(1, MATCH_GLOBALS["MAX_POSSESSION"]))).solve_for_y(home_possession_rat) home_concedes_prob = Line.Line(((-1, MATCH_GLOBALS["MAX_GOAL_PER_POSS"]), (1, MATCH_GLOBALS["MIN_GOAL_PER_POSS"]))).solve_for_y(home_concedes_rat) poss_rand = random.uniform(0, 1) goal_rand = random.uniform(0, 1) #ANTI GOLEADAS: if self.result[0] >= 3 + self.result[1]: home_scores_prob = home_scores_prob * MATCH_GLOBALS["ANTI_GOLEADAS"] elif self.result[1] >= 3 + self.result[0]: home_concedes_prob = home_concedes_prob * MATCH_GLOBALS["ANTI_GOLEADAS"] #PROBABILIDADE HUMANA DE MARCAR NO FINAL min_norm = HelperMethods.normalize(self.minutes, 0, MATCH_GLOBALS["TOTAL_TURNS"]) if min_norm <= 0.2: if self.away.manager.human: home_scores_prob = home_scores_prob * MATCH_GLOBALS["GOAL_BEGINNING_END_MULTI"] if self.home.manager.human: home_concedes_prob = home_concedes_prob * MATCH_GLOBALS["GOAL_BEGINNING_END_MULTI"] if min_norm >= 0.8: if self.home.manager.human: home_scores_prob = home_scores_prob * MATCH_GLOBALS["GOAL_BEGINNING_END_MULTI"] if self.away.manager.human: home_concedes_prob = home_concedes_prob * MATCH_GLOBALS["GOAL_BEGINNING_END_MULTI"] if poss_rand <= home_possession_prob: self.events["Home Possession"] = True self.possession[0] += 1 if goal_rand <= home_scores_prob: self.result[0] += 1 self.events["Goal"] = True self.set_goalscorer(True) else: self.events["Home Possession"] = False self.possession[1] += 1 if goal_rand <= home_concedes_prob: self.result[1] += 1 self.events["Goal"] = True self.set_goalscorer(False) return True else: return False
def drawSequences(self, sequences): fitness = hm.completeFitness(sequences) #finding out the ids of the triangles _raw = [s for seq in sequences for s in seq] tris = list(self.triangles) ids = [self.triangles.index(r) + 1 for r in _raw] self.ids = ids peak = hm.sequenceToEdges(sequences) edges = [] #moved together _edges = hm.moveTogether(peak[0]) if _edges[1] < 0: fitness += _edges[1] edges = _edges[0] else: edges = [] for a in peak[0]: for b in a: edges.append(b) tris = [edges[i * 3:i * 3 + 3] for i in range(int(len(edges) / 3))] self.coordinates = [ set([tuple(point) for edge in t for point in edge]) for t in tris ] self.distance = fitness hm.save(edges, fitness, "peak.txt") hm.draw(edges, 0.9, self.filename.replace("txt", "svg"))
def txt(self, language): # Returns a dict of strings for the GUI turn_skill_change = '' if self.turn_skill_change is not None: if self.turn_skill_change >= 1: turn_skill_change = ' [+1]' elif self.turn_skill_change <= (-1): turn_skill_change = ' [-1]' txt = { "player_name": str(self.name), "player_age": str(self.age), "player_skill": str(self.skill) + str(turn_skill_change), "player_pos": language["pos" + str(self.pos)], "player_salary": str(HelperMethods.num2str(self.season_salary)), "player_value": str(HelperMethods.num2str(self.value)), } return txt
def save_count_per_hour_to_file(h_list): date_times = h.initialize_specific_range() for i in h_list: for j in h_list: if i != j: if os.path.isfile(list_hours_prefix.format(i, j)): continue days_count = [] for e in range(61): days_count.append([0] * 24) # days_count = [[0] * 24] * 61 # days_count[2][4] = 5 mtx_a = h.load_lil(h.get_npz_file_name(i, j)) non_zero = mtx_a.nonzero()[1] for v in non_zero: date, time, night = h.get_time_of_day(date_times, v) delta_days = date - start_date days_count[delta_days.days][time.hour] += 1 save_list(list_hours_prefix.format(i, j), days_count)
def main(): args = parse_arguments() input_path = args.input_path analyzer = DocumentAnalyzer(model=args.model) show_img = True names = os.listdir(input_path) images_names = [ filename for filename in names if filename.endswith('.jpg') ] if not os.path.exists(args.output_path): os.makedirs(args.output_path) length = len(images_names) count = 0 for img in images_names: filename = img.replace('.jpg', '') xml_name = img.replace('.jpg', '.xml') coordinates, img_height, img_width = analyzer.get_document_paragraphs( input_path + img, line_coords=HelperMethods.get_line_coords(input_path + xml_name)) xml_string = HelperMethods.create_page_xml(coordinates, img_width, img_height, filename) if show_img: in_img = misc.imread(input_path + img, mode="RGB") res = get_img_coords(in_img, coordinates) fig = plt.figure() f, axarr = plt.subplots(1, 1, dpi=1000) axarr.axis('off') axarr.imshow(res) plt.savefig('{}/{}.jpg'.format(args.output_path, filename), bbox_inches='tight') plt.close(fig) with open('{}/{}.xml'.format(args.output_path, filename), 'wb') as f: f.write(xml_string) count += 1 print('Completed: {}/{}'.format(count, length)) return 0
def txt(self, language): # Returns a dict of strings for the GUI turn_skill_change = '' if self.turn_skill_change is not None: if self.turn_skill_change >= 1: turn_skill_change = ' [+1]' elif self.turn_skill_change <= (-1): turn_skill_change = ' [-1]' txt = { "player_name" : str(self.name), "player_age" : str(self.age), "player_skill": str(self.skill) + str(turn_skill_change), "player_pos" : language["pos" + str(self.pos)], "player_salary" : str(HelperMethods.num2str(self.season_salary)), "player_value" : str(HelperMethods.num2str(self.value)), } return txt
def plotPathWithResults(pack,pdict,startPoint,endPoint,line=None): '''plotPathWithResults Uses results from findAllPaths() to plot the shortest path between two points args: pack needed for the figure axis, returned by findAllPaths() pdict the primary results from findAllPaths(); hashtable of all paths startPoint starting point of your path endPoint end point of your path kwargs: line a line object returned by this method. If you want subsequent calls to this function to overwrite the last found paths then input the line object returned by this method. return: line the line object created by this method. Used to overwrite past lines in subsequent calls. ''' if not line: line = lines.Line2D([], [], lw=2, c='red') ax = pack[2] ax.add_line(line) pass r1 = Helper.findClosestNode(list(zip(*zip(*pdict.keys()))), startPoint) r2 = Helper.findClosestNode(list(zip(*zip(*pdict.keys()))), endPoint) foundPath = [] if r1 != r2: foundPath = pdict[r1][r2] pass foundPath.insert(0,startPoint) foundPath.append(endPoint) line.set_xdata([p[0] for p in foundPath]) line.set_ydata([p[1] for p in foundPath]) return line
def fitness(self, basepairs): bs = basepairs bs = [a for a in bs if a != []] f = hm.fitness(bs) f += self.add for seq in bs: a_sum = sum([s[0] for s in seq]) if a_sum > 180: return 0.00001 return (100000 / f)**10
def check_credentials(): """ Validates email and password when logging into the database """ if hm.check_fields_inputs(emailEntry=email_entry, passwordEntry=password_entry, checkEmailFormat=email_entry.get()): # Get list of emails from db and check if input email is in that list if conn.email_exist(email_entry.get()): stored_pw = conn.select('passwrd', conn.researcher, 'email', email_entry.get()) # If email is in the list verify the password and allow access, else prompt error if verify_password(stored_pw, password_entry.get()): hm.current_researcher = conn.select( 'researcher_id', conn.researcher, 'email', email_entry.get()) controller.show_patientLog_frame() else: hm.showerror("Authentication Error", "\u2022 Wrong Password. Try again") else: hm.showerror("Error", "\u2022 This email is not registered")
def bestRemaining(self, remaining, times): min = [None, None] for _ in range(times): random.shuffle(remaining) new = FindBestSequence(remaining).finalSequence v = hm.fitness(new) if min[0] == None or v <= min[0]: min[0] = v min[1] = new return min[1]
def run(self, triangles, pop_size, sec, head, tail): add = hm.completeFitness( [head, tail]) #hm.sequenceToEdges([self.head, self.tail])[1] print(add, "here") sequences = ga.optimization(triangles, pop_size, 700.0, sec, add) for s in sequences: s = self.sortSequence(s) sequences.insert(0, head) sequences.append(tail) return sequences
def __init__(self, title, master=None): Frame.__init__(self, width=400, height=300, bg="black") global main_icon, main_temp, main_highlow, day_labels, day_icons, day_temps main_icon = StringVar() main_temp = StringVar() main_highlow = StringVar() weatherDays = weather() day_labels = []; day_icons = []; day_temps = []; day_hilows = []; main_temp_label = Label(self, textvariable=main_temp, font=("Meteocons", 60), bg="black", foreground="white") # main_temp.set("R") main_temp.set(weatherDays[0]['icon']) main_temp_label.place(x=0,y=0) main_icon_label = Label(self, textvariable=main_icon, font=("SFNS Display", 36), bg="black", foreground="white") # main_icon.set(u"71\xb0") main_icon.set(u"%d\xb0" % weatherDays[0]['temp']) main_icon_label.place(x=130,y=-5) main_highlow_label = Label(self, textvariable=main_highlow, font=("SFNS Display", 18), bg="black", foreground="white") main_highlow.set(u"( %d\xb0 | %d\xb0 )" % (weatherDays[0]['hi'], weatherDays[0]['lo'])) main_highlow_label.place(x=100,y=50) currentday = HelperMethods.getCurrentDay_ShortName() #HARDCODED WEATHER # icons = ["B", "H", "Y", "F", "G"]; # temps = [u"68\xb0", u"65\xb0", u"54\xb0", u"42\xb0", u"18\xb0"] # hilows = [u"( 72\xb0 | 55\xb0 )", u"( 70\xb0 | 61\xb0 )", u"( 59\xb0 | 48\xb0 )", u"( 50\xb0 | 36\xb0 )", u"( 21\xb0 | 16\xb0 )"] for num in range(0, len(weatherDays) - 1): day_labels.append(self.getNextDay(currentday)) currentday = day_labels[num] day_labels[num] = Label(self, text=currentday, font=("SFNS Display", 14), bg="black", foreground="white", anchor=E) day_labels[num].place(y=(100 + (num*30)), x=15, width=50) day_icons.append(Label(self, text=weatherDays[num+1]['icon'], font=("Meteocons", 14), bg="black", foreground="white") ) day_icons[num].place(y=(102 + (num*30)), x = 70) day_temps.append(Label(self, text=u"%d\xb0"%weatherDays[num+1]['temp'], font=("SFNS Display", 14), bg="black", foreground="white")) day_temps[num].place(y=(100 + (num*30)), x = 100) day_hilows.append(Label(self, text=u"( %d\xb0 | %d\xb0 )" % (weatherDays[num+1]['hi'], weatherDays[num+1]['lo']), font=("SFNS Display", 12), bg="black", foreground="white")) day_hilows[num].place(y=(102 + (num*30)), x = 140)
def season_training_increase_per_turn(self): # Sets increase_per_turn -> how much a player trains per turn # Returns True if worked, False if not # & Run once per season if self.age >= PLAYER_GLOBALS["MIN_AGE"]: age_int = PLAYER_GLOBALS["AGE_TRAINING_INF"] inc_int = PLAYER_GLOBALS["TRAINING_PER_AGE"] age_norm = HelperMethods.normalize(self.age, PLAYER_GLOBALS["MIN_AGE"], PLAYER_GLOBALS["MAX_AGE"]) skill_norm = HelperMethods.normalize(self.skill, PLAYER_GLOBALS["MIN_SKILL"], PLAYER_GLOBALS["MAX_SKILL"]) skill_inf = 1 if skill_norm >= 0.85: skill_inf = 0.5 for index, age_range in enumerate(age_int): if age_norm < age_range: x1 = age_int[index] x2 = age_int[index - 1] y1 = inc_int[index] y2 = inc_int[index - 1] increase = HelperMethods.ysolver(point1=(x1, y1), point2=(x2, y2), x = age_norm) break self.increase_per_turn = (increase * skill_inf) / float(GAME_GLOBALS["TOTAL_TURNS"]) return True return False
def txt(self, language): # Returns a dict of strings for the GUI goal_difference = self.league_stats.goal_difference if goal_difference >= 0: goal_difference = '+' + str(goal_difference) else: goal_difference = str(goal_difference) txt = { "team_name" : str(self.name), "team_league_points" : str(self.league_stats.points), "team_goal_difference" : goal_difference, "team_money" : str(HelperMethods.num2str(self.money)), "team_league_position" : str(self.league_position), } return txt
def create_skill(skill, avg_skill): # Returns int with player starting skill # TODO: Add age influence! # if avg_skill: # skill_variation = int(round(PLAYER_GLOBALS["MAX_SKILL"] * 0.02, 0)) # random_var = random.randint(-skill_variation, skill_variation) # skill += random_var skill_age_inf = PLAYER_GLOBALS["MAX_SKILL"] * 0.05 + skill * 0.2 age_inf = 1 - 2 * HelperMethods.normalize(age, PLAYER_GLOBALS["MIN_AGE"], PLAYER_GLOBALS["MAX_AGE"]) if age_inf > 0: skill -= skill_age_inf * age_inf skill = min(max(int(round(skill, 0)), PLAYER_GLOBALS["MIN_SKILL"]), PLAYER_GLOBALS["MAX_SKILL"]) return skill
def create_skill(skill, avg_skill): # Returns int with player starting skill # TODO: Add age influence! # if avg_skill: # skill_variation = int(round(PLAYER_GLOBALS["MAX_SKILL"] * 0.02, 0)) # random_var = random.randint(-skill_variation, skill_variation) # skill += random_var skill_age_inf = PLAYER_GLOBALS["MAX_SKILL"] * 0.05 + skill * 0.2 age_inf = 1 - 2 * HelperMethods.normalize( age, PLAYER_GLOBALS["MIN_AGE"], PLAYER_GLOBALS["MAX_AGE"]) if age_inf > 0: skill -= skill_age_inf * age_inf skill = min(max(int(round(skill, 0)), PLAYER_GLOBALS["MIN_SKILL"]), PLAYER_GLOBALS["MAX_SKILL"]) return skill
def __init__(self, filename): self.filename = filename LOG_FORMAT = "%(levelname)s %(asctime)s - %(message)s" logging.basicConfig(filename="henning.log", level=logging.DEBUG, format=LOG_FORMAT, filemode="w") logger = logging.getLogger() logger.info("beginning") triangles = hm.textToTriangles(self.filename) self.triangles = list(triangles) logger.info("calculating the triangles") sequences = None if sum([t[0] for t in triangles]) <= 180: sequences = [] sequences.append(list(triangles)) else: result = self.head(triangles) head = result[0] triangles = result[1] result = self.head(triangles) tail = result[0] triangles = result[1] if sum([t[0] for t in triangles]) <= 180: if triangles != []: sequences = [head, triangles, tail] else: sequences = [head, tail] else: pop_size = 20 sec = 5 sequences = self.rest(list(triangles)) sequences.insert(0, head) sequences.append(tail) sequences = self.run(triangles, pop_size, sec, head, tail) #self.plotFile() self.drawSequences(sequences) print("input filename: ", self.filename) print("Total distance: ", self.distance) print("Coordinates: ", self.coordinates) print("output filename: ", self.filename.replace("txt", "svg"))
def get_values(): """ Validates all fields in LogPatient frame for correct input """ if hm.check_fields_inputs( ageEntry=age_entry, heightEntryFt=height_entry_ft, heightEntryIn=height_entry_in, weightEntry=weight_entry, ethnicityOption=self.ethnicity_option_selected.get(), genderOption=self.gender_option_selected.get(), skinColorOption=self.skin_color_type.get()): self.age_value = int(age_entry.get()) self.height_value_ft = int(height_entry_ft.get()) self.height_value_in = int(height_entry_in.get()) self.weight_value = int(weight_entry.get()) return True else: return False
def set_goalscorer(self, home_goal): if home_goal: team = self.home team_index = 0 else: team = self.away team_index = 1 if len(team.squad) == 0: self.goalscorers[team_index].append((Player.Player(skill=1, age=20, pos=3, name="Ricardo"), self.minutes)) else: player_list = [] prob_scoring_per_pos = (0, 0.1, 0.3, 0.6) sorted_players = sorted(team.squad, key=lambda player: player.skill, reverse=True) for player in sorted_players: player_list.append((player, player.skill * +prob_scoring_per_pos[player.pos])) self.goalscorers[team_index].append((HelperMethods.weighted_choice(player_list), self.minutes)) return True
def set_goalscorer(self, home_goal): if home_goal: team = self.home team_index = 0 else: team = self.away team_index = 1 if len(team.squad) == 0: self.goalscorers[team_index].append((Player.Player(skill = 1, age = 20, pos = 3, name = "Ricardo"), self.minutes)) else: player_list = [] prob_scoring_per_pos = (0, 0.1, 0.3, 0.6) sorted_players = sorted(team.squad, key=lambda player: player.skill, reverse = True) for player in sorted_players: player_list.append((player, player.skill * + prob_scoring_per_pos[player.pos])) self.goalscorers[team_index].append((HelperMethods.weighted_choice(player_list), self.minutes)) return True
from ContentAnalyticsAPIWrapper import ContentAnalyticsAPI from datetime import datetime import sys, time, urllib, os import HelperMethods as h secret_key = sys.argv[4] access_id = sys.argv[3] api_address= "http://127.0.0.1/rest_api/" csv_upload_dir = "/opt/trillionmonkeys.com/tm/date/uploads/" ca = ContentAnalyticsAPI(access_id, secret_key, api_address) batch_id = int(sys.argv[1]) file_name = sys.argv[2] h.upload_batch_file(csv_upload_dir + file_name, file_name, batch_id, ca) h.crawl_batch(batch_id, ca) h.process_batch(batch_id, ca)
DataFolder = "" OutputFolder = "" # Read command line args parser = argparse.ArgumentParser() parser.add_argument('--i') parser.add_argument('--out') args = parser.parse_args() DataFolder = args.i OutputFolder = args.out #DataFolder = r"C:\Users\Rylan\source\repos\SequenceAnalysis\PRRSAnalysis\bin\Debug\_TempData" # temp #OutputFolder = r"C:\Users\Rylan\Documents\SequenceAnalysisProgram\Output\Test" # temp # Get data variables Sequences = HelperMethods.readJson(DataFolder + "/Sequences.json") PercentIdentityData = HelperMethods.readJson(DataFolder + "/PercentIdentities.json") RecombinationData = HelperMethods.readJson(DataFolder + "/Recombination.json") AnalysisNames = HelperMethods.readJson(DataFolder + "/AnalysisNames.json") Trees = HelperMethods.readJson(DataFolder + "/Trees.json") # Create output folders HelperMethods.createDir(OutputFolder) HelperMethods.createDir(OutputFolder + "/PercentIdentity_Heatmaps/") HelperMethods.createDir(OutputFolder + "/PhyloGeneticTrees/") HelperMethods.createDir(OutputFolder + "/ReportParts/") ## Non Report Items ## # Heatmaps
from ContentAnalyticsAPIWrapper import ContentAnalyticsAPI from datetime import datetime import sys, time, urllib, os, logging import HelperMethods as h secret_key = sys.argv[2] access_id = sys.argv[3] api_address= "http://127.0.0.1/rest_api/" ca = ContentAnalyticsAPI(access_id, secret_key, api_address) log_file = "/tmp/crawl_generate_results.log" logging.basicConfig(filename=log_file,level=logging.DEBUG, format="%(levelname)-5s [%(asctime)s] %(message)s") batch_id = int(sys.argv[1]) print(str(datetime.now()) + ": Start batch " + str(batch_id)) response = ca.get_batch_crawl_status_from_id(batch_id) if int(response["queued"]) == 0: h.crawl_batch(batch_id, ca) #h.process_batch(batch_id, ca) #h.call_zabbix_sender(batch_id, 0) else: logging.error("Already crawling/generating results for this batch. Exiting.") h.call_zabbix_sender(batch_id, 1)
def autograde(url): ingredientsDict = scraper.scrapeIngredients(url) directionsList = scraper.getDirections(url) HelperMethods.identifyIngredients(ingredientsDict) HelperMethods.identifyTools(directionsList) HelperMethods.identifyCookingMethods(directionsList) result = {'url':url, 'ingredients':[]} numOfIngredients = 0 numOfCookMethods = 0 numOfTools = 0 numOfPrimMethods = 0 for ingObject in HelperMethods.ingredientList: #These lists hold names, desciptors, preparation and preparation description #for each ingredient. These will be directly pushed to the dictionary. nameList = [] descriptorList = [] preparationList = [] prepDescList = [] #Push different combinations of ingredient names (ingredient name + descriptor(s)) name = ingObject.m_IngName nameList.append(name) for descriptor in ingObject.m_IngDescriptor: name = descriptor + " " + name #Push all descriptors in descriptor list descriptorList.append(descriptor) nameList.append(name) #Push all preparations in preparation list for preparation in ingObject.m_IngPreparation: preparationList.append(preparation) #Push all preparation descriptors in preparation description list for prepDesc in ingObject.m_IngPrepDescriptor: prepDescList.append(prepDesc) entry = {} entry['name'] = nameList entry['quantity'] = ingObject.m_quantAutoGrade entry['measurement'] = ingObject.m_IngMeasurement entry['descriptor'] = ' '.join(descriptorList) entry['preparation'] = ' '.join(preparationList) entry['prepDescList'] = ' '.join(prepDescList) result['ingredients'].append(entry) numOfIngredients = numOfIngredients + 1 result['primary cooking method'] = '' #Add cooking methods methodsList = [] for methodObj in HelperMethods.cookingMethodsList: if(len(methodObj.m_MethodName)>0): for index in range(0,len(methodObj.m_MethodName)): methodsList.append(methodObj.m_MethodName[index]) numOfCookMethods = numOfCookMethods + 1 retVal = checkMethodType(methodObj.m_MethodName[index]) if retVal == True: result['primary cooking method'] = methodObj.m_MethodName[index] #print methodsList result['cooking methods'] = ' '.join(methodsList) #Add cooking tools toolsList = [] for toolObj in HelperMethods.toolsList: toolsList.append(toolObj.m_ToolName) numOfTools = numOfTools + 1 result['cooking tools'] = ' '.join(toolsList) #result['max'] = {'ingredients':numOfIngredients, 'primary cooking method':numOfPrimMethods, 'cooking tools':numOfTools, 'cooking methods':numOfCookMethods} return result
def updateTime(self): global label_time_text, label_date_text label_time_text.set(HelperMethods.getFormattedTime()) label_date_text.set(HelperMethods.getFormattedDate())
from ContentAnalyticsAPIWrapper import ContentAnalyticsAPI from datetime import datetime import sys, time, urllib, os import HelperMethods as h api_address= "http://127.0.0.1/rest_api/" csv_upload_dir = "/opt/trillionmonkeys.com/tm/date/uploads/" secret_key = sys.argv[1] access_id = sys.argv[2] csv_dir = sys.argv[3] batch_name = sys.argv[4] workflow = sys.argv[5] run_instances = sys.argv[6] ca = ContentAnalyticsAPI(access_id, secret_key, api_address) file_array = ca.UploadCsv(csv_dir) batch_id = ca.create_batch(batch_name) file_name = file_array['files'][0]['name'] status = ca.upload_batch_file(csv_upload_dir + file_name, file_name, batch_id, workflow, run_instances) print batch_id print status h.crawl_batch(batch_id, ca) #if batch_id != -1: # os.system("python /var/www/tmeditor/python/crawl_and_generate_results.py " + str(batch_id) + " \"" + file_name + "\" \"" + access_id + "\" \"" + secret_key + "\" >> /tmp/crawl_generate_results.log 2>&1 &")
def minute(self): if self.minutes < MATCH_GLOBALS["TOTAL_TURNS"]: self.home.update_skill_tactic() self.away.update_skill_tactic() self.minutes += 1 self.events = {"Home Possession": False, "Goal": False} home_tactic_inf = [ (self.home.tactic[0] - self.away.tactic[2]) * MATCH_GLOBALS["TACTIC_INFLUENCE"], (self.home.tactic[1] - self.away.tactic[1]) * MATCH_GLOBALS["TACTIC_INFLUENCE"], (self.home.tactic[2] - self.away.tactic[0]) * MATCH_GLOBALS["TACTIC_INFLUENCE"], ] home_concedes_rat = (self.home.skill[0] - self.away.skill[2]) / float( PLAYER_GLOBALS["MAX_SKILL"] ) + home_tactic_inf[0] home_possession_rat = (self.home.skill[1] - self.away.skill[1]) / float( PLAYER_GLOBALS["MAX_SKILL"] ) + home_tactic_inf[1] home_scores_rat = (self.home.skill[2] - self.away.skill[0]) / float( PLAYER_GLOBALS["MAX_SKILL"] ) + home_tactic_inf[2] home_scores_prob = Line.Line( ((-1, MATCH_GLOBALS["MIN_GOAL_PER_POSS"]), (1, MATCH_GLOBALS["MAX_GOAL_PER_POSS"])) ).solve_for_y(home_scores_rat) home_possession_prob = Line.Line( ((-1, 1 - MATCH_GLOBALS["MAX_POSSESSION"]), (1, MATCH_GLOBALS["MAX_POSSESSION"])) ).solve_for_y(home_possession_rat) home_concedes_prob = Line.Line( ((-1, MATCH_GLOBALS["MAX_GOAL_PER_POSS"]), (1, MATCH_GLOBALS["MIN_GOAL_PER_POSS"])) ).solve_for_y(home_concedes_rat) poss_rand = random.uniform(0, 1) goal_rand = random.uniform(0, 1) # ANTI GOLEADAS: if self.result[0] >= 3 + self.result[1]: home_scores_prob = home_scores_prob * MATCH_GLOBALS["ANTI_GOLEADAS"] elif self.result[1] >= 3 + self.result[0]: home_concedes_prob = home_concedes_prob * MATCH_GLOBALS["ANTI_GOLEADAS"] # PROBABILIDADE HUMANA DE MARCAR NO FINAL min_norm = HelperMethods.normalize(self.minutes, 0, MATCH_GLOBALS["TOTAL_TURNS"]) if min_norm <= 0.2: if self.away.manager.human: home_scores_prob = home_scores_prob * MATCH_GLOBALS["GOAL_BEGINNING_END_MULTI"] if self.home.manager.human: home_concedes_prob = home_concedes_prob * MATCH_GLOBALS["GOAL_BEGINNING_END_MULTI"] if min_norm >= 0.8: if self.home.manager.human: home_scores_prob = home_scores_prob * MATCH_GLOBALS["GOAL_BEGINNING_END_MULTI"] if self.away.manager.human: home_concedes_prob = home_concedes_prob * MATCH_GLOBALS["GOAL_BEGINNING_END_MULTI"] if poss_rand <= home_possession_prob: self.events["Home Possession"] = True self.possession[0] += 1 if goal_rand <= home_scores_prob: self.result[0] += 1 self.events["Goal"] = True self.set_goalscorer(True) else: self.events["Home Possession"] = False self.possession[1] += 1 if goal_rand <= home_concedes_prob: self.result[1] += 1 self.events["Goal"] = True self.set_goalscorer(False) return True else: return False
if __name__ == "__main__": print("\t\t\t\tRECIPE MANAGER: Your personal cooking guide.\n") # print ("Enter the recipe you want to explore: ") # recipeName = raw_input() # recipeURL = "" #recipeURL = input("Enter the recipe you want to explore: ") recipeURL = "http://allrecipes.com/Recipe/Chilly-Day-Chili/Detail.aspx?event8=1&prop24=SR_Thumb&e11=chilli%20chicken&e8=Quick%20Search&event10=1&e7=Recipe&soid=sr_results_p1i1" print("Please wait while I understand the recipe...\n") ingredientsDict = scraper.scrapeIngredients(recipeURL) directionsList = scraper.getDirections(recipeURL) #ProjectDictionary.populateTools() print("Reading ingredients...\n") HelperMethods.identifyIngredients(ingredientsDict) HelperMethods.identifyTools(directionsList) HelperMethods.identifyCookingMethods(directionsList) HelperMethods.identifyIngredientType() HelperMethods.ingredientList HelperMethods.cookingMethodsList ## Take the user input and ask them for the transformation print("Ready!!!\n") ## Harsh Code from here ### for ingredient in HelperMethods.ingredientList: output = '-->' toolName = '' for method in HelperMethods.cookingMethodsList: if ingredient.m_IngName in method.m_ingredientUsed:
else: outputUnchanged = outputUnchanged + transformObj.m_originalIng + '\n' print "The following remain unchanged:" print outputUnchanged #the main routine if __name__ == "__main__": print ("\t\t\t\tRECIPE MANAGER: Your personal cooking guide.\n") recipeURL = input("Enter the URL of the recipe you want to explore: ") print("Please wait while I understand the recipe...\n") ingredientsDict = scraper.scrapeIngredients(recipeURL) directionsList = scraper.getDirections(recipeURL) #scraper.populateTools() print("Reading ingredients...\n") #parse ingredients, cooking methods and tools HelperMethods.identifyIngredients(ingredientsDict) HelperMethods.identifyTools(directionsList) HelperMethods.identifyCookingMethods(directionsList) print("Ready!!!\n") scraper.getPrepTimeRating(recipeURL) print "\tIngredients:" for ingredient in HelperMethods.ingredientList: output = '' if(ingredient.m_IngQuantity != ''): output = output + ingredient.m_IngQuantity + ' ' if(ingredient.m_IngMeasurement != ''): output = output + ingredient.m_IngMeasurement + ' ' if(len(ingredient.m_IngDescriptor) == 0): output = output + ingredient.m_IngName + ' ' else: for descriptor in ingredient.m_IngDescriptor: