def ranking(ladder: str) -> flask.Response: """Get the players ranked by their skill.""" if not ladder_exists(ladder): return flask.jsonify({'exists': False}) rnk = Ranking(ladder, flask.g.dbh) rnk.recalculate() result = { 'exists': True, 'ranking': [dict(player) for player in rnk.standings()] } return flask.jsonify(result)
def update_ranking_page(key = None): page = Ranking(dsn = app.config['dsn']) if request.method == 'GET': return page.open_update_player(id = key) elif 'updateplayer' in request.form: name = request.form['name'] surname = request.form['surname'] country = request.form['country'] club = request.form['club'] rating = request.form['rating'] ranking = request.form['ranking'] age = request.form['age'] gender = request.form['gender'] return page.update_player(key, name, surname, country, club, rating, ranking, age, gender) else: return redirect(url_for('home_page'))
def getRankingForFile(self, filename) -> Ranking: repetition = defaultdict(lambda: 0) for baseWord in self._generate(filename): repetition[baseWord] += 1 ranking = sorted(repetition.items(), key=itemgetter(1), reverse=True) return Ranking(ranking)
def human_rank(self): from data_apis import top_human_squads ths = top_human_squads(self.game) squad_score = [ x['human_points'] for x in ths if x['squad_id'] == self.id ][0] scores = [x['human_points'] for x in ths] return (Ranking(scores, start=1).rank(squad_score), len(ths))
def zombie_rank(self): from data_apis import top_zombie_squads tzs = top_zombie_squads(self.game) squad_score = [ x['zombie_points'] for x in tzs if x['squad_id'] == self.id ][0] scores = [x['zombie_points'] for x in tzs] return (Ranking(scores, start=1).rank(squad_score), len(tzs))
def human_rank(self): from data_apis import top_humans th = top_humans(self.game) player_score = [ x['human_points'] for x in th if x['player_id'] == self.id ][0] scores = [x['human_points'] for x in th] return (Ranking(scores, start=1).rank(player_score), len(th))
def get_ranking(self): """ returns a ranking list, containing the ranks of the included target translations @return: the ranking list @rtype: Ranking """ return Ranking([s.get_rank() for s in self.tgt])
def update_countries1_page(key = None): page = Ranking(dsn = app.config['dsn']) if request.method == 'GET': return page.open_updatecountries(id = key) elif 'updatecountries' in request.form: country_name = request.form['country_name'] average = request.form['average'] gm = request.form['gm'] im = request.form['im'] total_titled = request.form['total_titled'] total_top = request.form['total_top'] country_rank = request.form['country_rank'] best_player = request.form['best_player'] highest_rating = request.form['highest_rating'] return page.update_countriess(key, country_name, average, gm, im, total_titled, total_top, country_rank, best_player, highest_rating) else: return redirect(url_for('home_page'))
def update_player_info_page1(key = None): page = Ranking(dsn = app.config['dsn']) if request.method == 'GET': return page.open_update_player_info(id = key) elif 'updateplayer_info' in request.form: name = request.form['name'] surname = request.form['surname'] country = request.form['country'] club = request.form['club'] best_rating = request.form['best_rating'] best_ranking = request.form['best_ranking'] best_tournament = request.form['best_tournament'] best_tournament_result = request.form['best_tournament_result'] curr_rating = request.form['curr_rating'] curr_ranking = request.form['curr_ranking'] return page.update_player_info(key, name, surname, country, club, best_rating, best_ranking, best_tournament, best_tournament_result, curr_rating, curr_ranking) else: return redirect(url_for('home_page'))
def testAddUsersFromDB(self): self.R.reset() self.R.c.executemany(queries.INSERT_KNOWN_USERS, USERS) R = Ranking(1, conn=self.R.conn) self.assertTrue(all([user[0] in R.known_users for user in USERS]), "All of the users were not added from DB")
def test_capsuled_scores(): class User(object): def __init__(self, score): self.score = score def __lt__(self, other): raise NotImplemented def __gt__(self, other): raise NotImplemented users = [User(100), User(80), User(80), User(79)] with raises(TypeError): list(Ranking(users)) key = lambda user: user.score ranking = Ranking(users, key=key) assert ranks(ranking) == [0, 1, 1, 3] assert isinstance(next(iter(ranking))[1], User)
def testAddDualsFromDB(self): self.R.c.executemany(queries.INSERT_DUALS, DUALS) self.R.c.executemany(queries.INSERT_RATINGS, RATINGS) R = Ranking(1, self.R.conn) submitters = [user[0] for user in USERS] self.assertTrue( all(dual.submitter[0] in submitters for dual in R.duals), "All of the duals were not added from the DB")
def sort_user_results_with_rankings(results: List[UserEventResults], event_format: EventFormat) -> List[Tuple[int, str, UserEventResults]]: """ Sorts a list of UserEventResults based on the event format (for tie-breaking), and then applies rankings (identical results receive identical rankings). Returns a list of tuples of the form (ranking, visible_ranking, userEventResult), where ranking is the raw numerical rank and visible_ranking is the same as ranking except duplicate ranks show as an empty string. """ # Best-of-N results are only ranked by singles if event_format in [EventFormat.Bo1, EventFormat.Bo3]: results.sort(key=__sort_user_event_results_by_result) # Average/mean results are sorted by single first, to ensure any ties by overall result (average/mean) are broken # by the singles. else: results.sort(key=__sort_user_event_results_by_single) results.sort(key=__sort_user_event_results_by_result) # Build a list of tuples (average/mean, single), to be fed into the ranking mechanism. # If the time value cannot be interpreted as an int, it's a "DNF" or None, so just assign it some humongous value # which would sorted at the end. times_values = list() for result in results: try: average = int(result.result) except (ValueError, TypeError): average = 9999999999999 try: single = int(result.single) except (ValueError, TypeError): single = 9999999999999 times_values.append((average, single)) # Rank the list of times tuples. Legitimately tied results will have the same rank, so we also send back a # "visible rank" which facilitates showing the results nicely. Ranks with ties will look something like this: # # Place Result # ----- ------ # 1 10.2 # 2 15 # 15 # 4 17.84 ranks_seen = set() ranked_results = list() for i, r in enumerate(Ranking(times_values, start=1, reverse=True)): rank = r[0] if rank not in ranks_seen: ranks_seen.add(rank) visible_rank = str(rank) else: visible_rank = '' ranked_results.append((rank, visible_rank, results[i])) return ranked_results
def zombie_rank(self): from data_apis import top_zombies tz = top_zombies(self.game) try: player_score = [ x['zombie_points'] for x in tz if x['player_id'] == self.id ][0] except: return None scores = [x['zombie_points'] for x in tz] return (Ranking(scores, start=1).rank(player_score), len(tz))
def testAddSinglesFromDB(self): self.R.reset() self.R.c.executemany(queries.INSERT_SINGLES, SINGLES) self.R.c.executemany(queries.INSERT_RATINGS, RATINGS) R = Ranking(1, self.R.conn) submitters = [user[0] for user in USERS] self.assertTrue( all(match.submitter[0] in submitters for match in R.singles), "All of the matches were not added from the DB")
def guarda_puntajes(self): partida = Ranking(self.master.master.puntaje.get(), self.master.master.nombre.get(), self.master.master.dificultad.get(), self.tiempo_juego_total, constantes.RANKING) if partida.es_puntaje_alto(): t = Timer(1.1, lambda: [self.aviso_puntaje_alto()]) t.start() partida.guarda_partida_csv() partida.ordena_puntaje_cvs()
async def load_all(self): self.messages = load_messages() self.player_manager = PlayerManager() await self.player_manager.load_data() await self.update_mentions() ranking_config = load_ranking_config("base") self.ranking = Ranking(self.player_manager, **ranking_config) await self.ranking.fetch_data(self.matchboard)
def convertToRanks(freqDistBigrams): #print("In RANKING") #print(freqDistBigrams) freqList = [x[1] for x in freqDistBigrams] #print(freqList) rankList = list(Ranking(freqList, start=1)) #print(rankList) freDist_New = [ tuple([x[0], y[0]]) for x, y in zip(freqDistBigrams, rankList) ] #print(freDist_New) return freDist_New
def testFlush(self): cards1 = [{ "rank": "5", "suit": "diamonds" }, { "rank": "2", "suit": "diamonds" }, { "rank": "7", "suit": "diamonds" }, { "rank": "8", "suit": "clubs" }, { "rank": "8", "suit": "diamonds" }, { "rank": "J", "suit": "diamonds" }] r = Ranking(cards1) self.assertTrue(r.hasFlush())
def search(): query_str = request.args.get('q') if (request.method == 'POST'): query_str = request.form['q'] print(f'query_str[{query_str}]') ranking = Ranking() dao = Dao() pr_list = dao.getContent(query_str) pr_list = ranking.rank_and_sort(pr_list, query_str) print('search results', len(pr_list)) dao.close() r_count = '{:,}'.format(len(pr_list)) return render_template('home.html', title=page_title, data=pr_list, searchTerm=query_str, resultCount=r_count)
async def exp_ranking(cmd, mu, sigma, beta, tau): t = time.time() async with cmd.typing(): player_manager = PlayerManager() await player_manager.load_data() await kamlbot.update_mentions(player_manager=player_manager) kamlbot.experimental_ranking = Ranking(player_manager, mu=eval(mu), sigma=eval(sigma), beta=eval(beta), tau=eval(tau)) await kamlbot.experimental_ranking.fetch_data(kamlbot.matchboard) dt = time.time() - t await cmd.channel.send(f"Experimental ranking initialized in {dt:.2f} s.")
def list(self, request): try: date_from = request.GET.get('date_from', '2.1.1410') date_from = datetime.datetime.strptime(date_from, '%d.%m.%Y') except ValueError: date_from = datetime.date(1410, 8, 15) date_from -= datetime.timedelta(days=1) try: date_to = request.GET.get('date_to', '31.12.9999') date_to = datetime.datetime.strptime(date_to, '%d.%m.%Y') except ValueError: date_to = datetime.date(9999, 12, 31) # cmnt = Movie.objects.filter( # Q(comment__date__range=(date_from, date_to)) | # Q(comment__date__isnull=True)).values("id").annotate( # total_comments=Count("comment")).order_by('-total_comments') # SQL STMT that can do all above and adds 0 for movies with no comments # but much easier sql_qry = \ 'SELECT "movies_movie"."id" AS "movie_id", ' \ 'SUM(CASE WHEN "movies_comment"."date" ' \ 'BETWEEN datetime("%s") AND datetime("%s") ' \ 'THEN 1 ELSE 0 end) as "total_comments" ' \ 'FROM "movies_movie" LEFT OUTER JOIN "movies_comment" ' \ 'ON ("movies_movie"."id" = "movies_comment"."movie_id_id") ' \ 'GROUP BY "movies_movie"."id" ' \ 'ORDER BY "total_comments" DESC' % (date_from, date_to) with connection.cursor() as c: c.execute(sql_qry) "Return all rows from a cursor as a dict" columns = [col[0] for col in c.description] cmnt = [dict(zip(columns, row)) for row in c.fetchall()] # add rank total_comments = [c['total_comments'] for c in cmnt] ranked_comments = list(Ranking(total_comments, strategy=DENSE)) for i in range(len(cmnt)): cmnt[i]['rank'] = ranked_comments[i][0] + 1 return Response(cmnt)
def ranking(self, obj, scoreing_class = None, validation_class = None, scoreing_args = None, validation_args = None, reverse = False): """ Get a ranking for a Rankable object @param obj: ranked object (Category, Course, ...) @param scoreing_class: scoreing strategy used, None for default strategy @param validation_class: validation strategy used, None for default strategy @param scoreing_args: scoreing args, None for default args @param validation_args: validation args, None for default args @param reverse: produce reversed ranking """ if type(obj) == OpenRuns: scoreing_class = scoreing_class or ControlPunchtimeScoreing validation_class = validation_class or ControlPunchtimeScoreing validation_args = validation_args or scoreing_args reverse = True return Ranking(obj, self, scoreing_class, validation_class, scoreing_args, validation_args, reverse)
def mainLoop(): global config global ranking global chatIds config = util.readConfig() ranking = Ranking(config) chatIds = util.readChatIds() tg.readRequestUrl() callbacks = [(checkUpcomingContest, 60, 0), (tg.startPolling, 1, 0)] while True: for i in range(len(callbacks)): (fun, timeIt, lastTimeStamp) = callbacks[i] if time.time() - lastTimeStamp >= timeIt: callbacks[i] = (fun, timeIt, time.time()) try: fun() except Exception as e: traceback.print_exc() print(traceback.format_exc()) time.sleep(0.01)
def _determine_ranks(personal_bests): """ Takes an ordered list of PersonalBestRecords and assigns each PersonalBestRecord a rank. Ranks are the same for PersonalBestRecords with identical times. Ex: [12, 13, 14, 14, 15] would have ranks [1, 2, 3, 3, 5] """ # If `personal_bests` is empty, we can't use the ranking mechanism below, so just return # the empty list if not personal_bests: return personal_bests # Build a list of just the time values of the personal bests, to be fed into the ranking # mechanism. If the PB time value cannot be interpreted as an int, it's probably a DNF so # just pretend it's some humongous value which would sorted at the end times_values = list() for personal_best in personal_bests: try: times_values.append(int(personal_best.personal_best)) except ValueError: times_values.append(9999999999999) # Rank the list of times. The result from this is (rank, time value) where the index # of the element for each time value doesn't change from the input to the output ranked_times = list(Ranking(times_values, start=1, reverse=True)) # Give each PersonalBestRecord its rank from the corresponding element in ranked_times ranks_seen = set() for i, personal_best in enumerate(personal_bests): rank = ranked_times[i][0] if rank not in ranks_seen: ranks_seen.add(rank) personal_best.rank = rank personal_best.numerical_rank = rank else: personal_best.rank = '' personal_best.numerical_rank = rank return personal_bests
def main(): """Download data from Google Sheets, convert it into three spreadsheets for consumption by the Jekyll app """ # Get the raw answers write_to_csv(RAW_SOURCE, './_data/hospitality-coi-raw.csv') # Get the trust names and addresses write_to_csv(TRUSTS_SOURCE, './_data/trusts.csv') # Get the scores download = requests.get(SCORES_SOURCE) content = download.content reader = csv.reader([x.decode('utf8') for x in content.splitlines()], delimiter=',') fieldnames = [x.lower().replace(' ', '_').replace('?', '') for x in next(reader)] scores_with_entity = sorted(list(reader), key=lambda x: (-int(x[7]), x[1])) scores_only = [x[7] for x in scores_with_entity] with open('./_data/hospitality-coi-scores.csv', 'w') as csvfile: writer = csv.writer(csvfile) writer.writerow(['rank'] + fieldnames) prev_rank = None current_rank = 1 enumerated_ranking = list(enumerate(Ranking(scores_only, start=1))) for i, (rank, row) in enumerated_ranking: current_rank = rank if (i + 1) < len(enumerated_ranking): next_rank = enumerated_ranking[i + 1][0] else: next_rank = None if prev_rank == current_rank or next_rank == current_rank: rank = "={}".format(rank) writer.writerow([rank] + scores_with_entity[i]) prev_rank = current_rank
def testMatchesPerUser(self): self.R.reset() self.R.c.executemany(queries.INSERT_KNOWN_USERS, USERS) self.R.c.executemany(queries.INSERT_RATINGS, RATINGS) # Use a fresh Ranking to load the information from DB R = Ranking(1, conn=self.R.conn) for dual in DUALS: R.add_dual_match((dual[0], dual[4]), (dual[1], dual[5]), (dual[2], dual[6]), (dual[3], dual[7]), dual[8], dual[9], dual[10]) try: R.matches_per_user() except Exception: self.fail( "Calculating the number of matches per user should not throw error." )
def testPairs(self): cards = [{ "rank": "6", "suit": "hearts" }, { "rank": "K", "suit": "spades" }, { "rank": "A", "suit": "spades" }, { "rank": "A", "suit": "hearts" }, { "rank": "6", "suit": "clubs" }] r = Ranking(cards) self.assertTrue(r.hasPair()) self.assertTrue(r.hasTwoPairs()) self.assertFalse(r.hasDrill()) self.assertFalse(r.hasFull()) self.assertFalse(r.hasPoker())
X_repeat = np.repeat(X_all[idx1,:MERGED_SIZE/2].reshape((1,MERGED_SIZE/2)),X_all.shape[0], axis = 0) X_right = np.concatenate((X_repeat, X_all[:,:MERGED_SIZE/2]), axis = 1) X_rel = np.ones((X_all.shape[0],1)) X_rel.fill(meta_dict['dicts']['rel_idx'][r]) b = np.random.choice(range(N_BATCH)) scores_left = getFinalClone(X_left[b*BATCH_SIZE: (b+1)*BATCH_SIZE],X_rel[b*BATCH_SIZE: (b+1)*BATCH_SIZE]) scores_right = getFinalClone(X_right[b*BATCH_SIZE: (b+1)*BATCH_SIZE],X_rel[b*BATCH_SIZE: (b+1)*BATCH_SIZE]) score_correct = getFinalClone(np.concatenate((X_all[idx1,:MERGED_SIZE/2].reshape((1,MERGED_SIZE/2)),X_all[idx2,:MERGED_SIZE/2].reshape((1,MERGED_SIZE/2))), axis = 1), np.array(meta_dict['dicts']['rel_idx'][r]).reshape((1,1)) ) if instance % 10000 == 0: print >> sys.stderr, "instance %d/%d " % (instance+1, len(lines)) l_list = scores_left.reshape((scores_left.shape[0],)).tolist() + score_correct.tolist()[0] r_list = scores_right.reshape((scores_right.shape[0],)).tolist() + score_correct.tolist()[0] l_set = set(l_list) r_set = set(r_list) r_left = Ranking(sorted(l_list,reverse = True)) r_right = Ranking(sorted(r_list,reverse = True)) left_rank = r_left.rank(score_correct[0][0]) right_rank = r_right.rank(score_correct[0][0]) llist += [left_rank] rlist += [right_rank] print sys.argv[1],':',np.mean(llist), np.mean(rlist)
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Jan 6 21:08:20 2018 @author: shashank """ from ranking import Ranking from ranking import num_there r = Ranking() r.deleteValues() games = r.readCSV('matches.csv') for i in games: if (i[0] not in r.ratings): r.addPlayer(i[0]) if (i[1] not in r.ratings): r.addPlayer(i[1]) if (i[2] not in r.ratings and not num_there(i[2])): r.addPlayer(i[2]) if (i[3] not in r.ratings and not num_there(i[3])): r.addPlayer(i[3]) if not num_there(i[2]): r.playDoubles(i[0], i[1], i[2], i[3]) else: r.playSingles(i[0], i[1]) r.printLeaderboard(toCSV=True, path='leaderboard.csv')
def get_baseline_ranking_scores(data, baseline_name, original_rank_name, invert_ranks = False, filter_ref = True, suffix = "", prefix = "", **kwargs): predicted_rank_vectors = [] original_rank_vectors = [] for parallelsentence in data.get_parallelsentences(): if filter_ref: #get a vector with all the rank_strings labels from all systems apart from the references original_rank_vector = parallelsentence.get_filtered_target_attribute_values(original_rank_name, filter_attribute_name="system", filter_attribute_value="_ref") else: original_rank_vector = parallelsentence.get_target_attribute_values(original_rank_name) ranking_length = len(original_rank_vector) if baseline_name == "fixed": predicted_rank_vector = [1] * ranking_length elif baseline_name == "random": random.seed() predicted_rank_vector = [random.randint(1, ranking_length) for i in range(ranking_length)] elif baseline_name == "random_noties": random.seed() predicted_rank_vector = range(1, ranking_length+1) random.shuffle(predicted_rank_vector) elif baseline_name == "alphabetical": system_names = parallelsentence.get_filtered_target_attribute_values("system", filter_attribute_name="system", filter_attribute_value="_ref") sorted_system_names = sorted(system_names) predicted_rank_vector = [sorted_system_names.index(name)+1 for name in system_names] elif baseline_name == "alphabetical_inv": system_names = parallelsentence.get_filtered_target_attribute_values("system", filter_attribute_name="system", filter_attribute_value="_ref") sorted_system_names = sorted(system_names, reverse=True) predicted_rank_vector = [sorted_system_names.index(name)+1 for name in system_names] else: raise Exception("You provided a baseline name that is not supported {}".format(baseline_name)) try: predicted_ranking = Ranking(predicted_rank_vector) original_ranking = Ranking(original_rank_vector) #invert rankings if requested if invert_ranks: predicted_ranking = predicted_ranking.reverse() #original_ranking = original_ranking.reverse() except Exception as e: logging.error("Error while processing Parallelsentence with attributes {}".format(parallelsentence.get_attributes())) logging.error("ranking that caused the error: predicted: {}, original: {}".format(predicted_ranking, original_ranking)) raise Exception(e) #add the ranking in the big vector with all previous parallel sentences predicted_rank_vectors.append(predicted_ranking) original_rank_vectors.append(original_ranking) stats = OrderedDict() #process the list of rankings with all metric functions and collect the #results in an ordered dict for callback in SET_METRIC_FUNCTIONS: current_stats = callback(predicted_rank_vectors, original_rank_vectors) stats.update(current_stats) #add the requested preffix and suffix to every value stats = OrderedDict([("{}-{}{}".format(prefix, key, suffix),value) for key,value in stats.iteritems()]) return stats
class Main(QtGui.QMainWindow): def __init__(self): QObject.__init__(self) self.cuadros = [] self.casillas = [] QtGui.QMainWindow.__init__(self) QtGui.QMessageBox.information(self, "Bienvenido a sudoku", "Bienvenido a QSudoku. Version 0.2.05") self.ui=Ui_MainTable() self.ui.setupUi(self) self.initGuiCelda() self.initMenuBar() self.initTeclado() #formulario de niveles self.level = Nivel() QObject.connect(self.level, SIGNAL("nivel"), self.iniciarJuego) self.ui.crono.display("00:00") self.bandera = True def initGuiCelda(self): self.ui.cmdVerificar.setEnabled(False) self.ui.cmdHint.setEnabled(False) self.ui.tablero.setHorizontalSpacing(8) self.ui.tablero.setVerticalSpacing(8) self.casillas = [] z=0 fil = 0 col = 0 for i in range(0,3): fil = i*3 for j in range(0,3): col = j*3 cuadro = QtGui.QGridLayout() cuadro.setHorizontalSpacing(1) cuadro.setVerticalSpacing(1) for l in range(0,3): for m in range(0,3): cas = Celda(fil, col, 0) self.casillas.append(cas) cuadro.addWidget(cas,l,m) z = z+1 col = col +1 fil = fil +1 col = j*3 self.ui.tablero.addLayout(cuadro, i, j) fil = i*3 self.celdaRuntime = Celda(0,0,0) self.tm = QTime(0,0,0,0) def initCrono(self): self.tiempo = QTimer(self) QObject.connect(self.tiempo, SIGNAL("timeout()"), self.timeRefresh) self.tiempo.start(1000) self.tiempoIni = QTime.currentTime() QTimer.singleShot(1000, self.timeRefresh) def timeRefresh(self): actual = QTime.currentTime() m_ini = self.tiempoIni.minute() s_ini = self.tiempoIni.second() ms_ini = self.tiempoIni.msec() m_act = actual.minute() s_act = actual.second() ms_act = actual.msec() if ms_act < ms_ini: ms_act = 1000 + ms_act s_act = s_act +1 if s_act < s_ini: s_act = 60 + s_act m_act = m_act - 1 m = m_act - m_ini s = s_act - s_ini ms = ms_act - ms_ini #actualizo el tiempo self.tm.setHMS(0, m, s, ms) self.ui.crono.display(self.tm.toString("mm:ss")) def initMenuBar(self): QObject.connect(self.ui.actionAcerca_de, SIGNAL("triggered()"), self.acercaDe) QObject.connect(self.ui.actionNueva, SIGNAL("triggered()"), self.nuevaPartida) QObject.connect(self.ui.actionGuardar, SIGNAL("triggered()"), self.guardarPartida) QObject.connect(self.ui.actionCargar, SIGNAL("triggered()"), self.cargarPartida) QObject.connect(self.ui.actionSalir, SIGNAL("triggered()"), self.salirJuego) QObject.connect(self.ui.actionRanking, SIGNAL("triggered()"), self.verRanking) def verRanking(self): self.ranking = Ranking() self.ranking.setWindowModality(Qt.ApplicationModal) self.ranking.show() def salirJuego(self): puntaje = self.calcularPuntaje() QtGui.QMessageBox.about(self, "Salir", "Su puntaje fue de : "+ str(puntaje)) self.close() self.destroy() def acercaDe(self): print "entra a acerca de :)" self.ab = About() self.ab.setWindowModality(Qt.ApplicationModal) self.ab.show() def nuevaPartida(self): self.level.show() def iniciarJuego(self, nivel): self.level.hide() self.activarTeclado() self.setCeldasBlanco() self.setTableroInicio() self.setTableroInicialSegunNivel(nivel) self.setTableroEnPantalla() while True: self.nombre, valor = QtGui.QInputDialog.getText(self, "Sudoku", "Ingrese su nombre") if self.nombre == "" or valor==False: QtGui.QMessageBox.warning(self, "Mensaje", "No se ha ingresado texto") else: break self.ui.lbl_jugador.setText(self.nombre) if nivel==0: self.ui.lbl_level.setText("Novato") self.hints = 12 self.dificultad = 0 elif nivel==1: self.ui.lbl_level.setText("Intermedio") self.hints = 8 self.dificultad = 1 elif nivel==2: self.ui.lbl_level.setText("Profesional") self.hints = 4 self.dificultad = 2 elif nivel==3: self.ui.lbl_level.setText("Leyenda") self.hints = 2 self.dificultad = 3 self.initCrono() self.ui.cmdHint.setText("Hints "+str(self.hints)) def setTableroEnPantalla(self): for i in range(0,9): for j in range(0,9): tmp = self.tableroActual[i][j] if tmp!= 0: self.ui.tablero.itemAtPosition(i/3, j/3).itemAtPosition(i%3, j%3).widget().setValue(tmp) else: self.ui.tablero.itemAtPosition(i/3, j/3).itemAtPosition(i%3, j%3).widget().setValue(0) def setTableroInicialSegunNivel(self, nivel): if nivel==0: for i in range(0,50): fila = randint(0,8) col = randint(0,8) self.tableroActual[fila][col] = self.matriz[fila][col] if nivel==1: for i in range(0,40): fila = randint(0,8) col = randint(0,8) self.tableroActual[fila][col] = self.matriz[fila][col] if nivel==2: for i in range(0,30): fila = randint(0,8) col = randint(0,8) self.tableroActual[fila][col] = self.matriz[fila][col] if nivel==3: for i in range(0,25): fila = randint(0,8) col = randint(0,8) self.tableroActual[fila][col] = self.matriz[fila][col] print self.tableroActual def setTableroInicio(self): matrizSolucion = GenMatriz() self.matriz = [ [ 0 for i in range(9) ] for j in range(9) ] self.tableroActual = [ [ 0 for i in range(9) ] for j in range(9) ] self.matriz = matrizSolucion.matriz print "imprimiendo matriz de juego main: \n" print self.matriz def setCeldasBlanco(self): for i in range(0,9): for j in range(0,9): self.ui.tablero.itemAtPosition(i/3, j/3).itemAtPosition(i%3, j%3).widget().setBackColor("white") def activarTeclado(self): for i in range(0,10): self.teclado[i].setEnabled(True) self.ui.cmdHint.setEnabled(True) self.ui.cmdVerificar.setEnabled(True) QObject.connect(self.ui.cmdHint, SIGNAL("clicked()"), self.cmdHint_clicked) QObject.connect(self.ui.cmdVerificar, SIGNAL("clicked()"), self.cmdVerificar_clicked) for i in range(0,81): cas = self.casillas[i] QObject.connect(cas, SIGNAL("clicked()"), cas.setEmpty) QObject.connect(cas, SIGNAL("clicked()"), self.getCeldaRuntime) def initTeclado(self): z=0 self.teclado = [] for i in range(0,3): for j in range(0,3): cmd = QtGui.QPushButton(str(z+1)) cmd.setEnabled(False) self.teclado.append(cmd) QObject.connect(self.teclado[z], SIGNAL("clicked()"), self.numPressed) print "entra "+str(z) self.ui.tecladoNum.addWidget(self.teclado[z],i,j) z = z+1 cmd = QtGui.QPushButton("0") cmd.setEnabled(False) self.teclado.append(cmd) QObject.connect(self.teclado[z], SIGNAL("clicked()"), self.numPressed) self.ui.tecladoNum.addWidget(self.teclado[z], 4, 1) def numPressed(self): numeroASetear = int(self.sender().text()) self.celdaRuntime.setValue(numeroASetear) def getCeldaRuntime(self): if self.celdaRuntime: print "entra a resetear y colocar borde" self.celdaRuntime.reset() self.celdaRuntime.setBlackBorder() if self.bandera == False: self.volverTableroNormal() self.bandera = True self.celdaRuntime = self.sender() self.setTableroActual() self.setPistas() def setTableroActual(self): print "dentro de setTableroActual" try: print self.tableroActual for i in range(0,9): for j in range(0,9): tmp = self.ui.tablero.itemAtPosition(i/3, j/3).itemAtPosition(i%3, j%3).widget().getValue() self.tableroActual[i][j] = tmp except AttributeError: print "Aun no se inicializado tableroActual... :(" def setPistas(self): pistas = [1,2,3,4,5,6,7,8,9] fila = self.celdaRuntime.fila columna = self.celdaRuntime.columna print "fila: " +str(fila) + "columna: " +str(columna) print "pista en fila" try: for i in range(0,9): tmp = self.tableroActual[fila][i] print tmp if tmp!=0: pistas[tmp-1]=0 print "pista en columna" for j in range(0,9): tmp = self.tableroActual[j][columna] print tmp if tmp!= 0: pistas[tmp-1]=0 l = (((columna/3)+1)+(fila/3)*3) for i in range((((l-1)/3)*3),((((l-1)/3)*3)+3)): for j in range((((l-1)%3)*3),((((l-1)%3)*3)+3)): tmp = self.tableroActual[i][j] if tmp != 0: pistas[tmp-1]=0 except AttributeError: print "Aun no se inicializado tableroActual... :(" k = 0 print "pistas: " print pistas for j in range(0,9): tmp = pistas[j] if tmp!=0 & k<5: self.celdaRuntime.addHints(tmp) k = k+1 def guardarPartida(self): g = Guardar() try: self.setTableroActual() g.guardarValores(self.matriz, self.tableroActual, self.nombre, self.ui.lbl_level.text(), self.tm.toString()) if g.crearArchivo() == True: print "se creo archivo" else: print "cancelo o ocurrio algun error :(" except AttributeError: print "no ha empezado a jugar..." QtGui.QMessageBox.about(self, "Mensaje", "Aun no has empezado a jugar... intentalo :)") def cargarPartida(self): g = Guardar() if g.leerArchivo() == True: self.tableroActual = g.matriz self.matriz = g.matriz self.nombre = g.nombre self.ui.lbl_jugador.setText(g.nombre) self.ui.lbl_level.setText(g.nivel) self.setTableroEnPantalla() self.activarTeclado() self.setCeldasBlanco() self.initCrono() else: return def checkFila(self, fila, col): for i in range(0,9): if i!=col: if self.tableroActual[fila][i] == self.tableroActual[fila][col]: print "Error en fila "+str(fila+1) return False return True def checkColumna(self, fila, col): for i in range(0,9): if i!=fila: if self.tableroActual[i][col] == self.tableroActual[fila][col]: print "Error en la columna " + str(col+1) return False return True def chechCuadro(self, fila, col): v_cuadro = int(fila/3) h_cuadro = int(col/3) for i in range(v_cuadro*3,v_cuadro*3+3): for j in range(h_cuadro*3,h_cuadro*3+3): if i != fila or j != col: if self.tableroActual[fila][col] == self.tableroActual[i][j]: print "Error en el cuadro: "+str(fila)+","+str(col) return False return True def cmdVerificar_clicked(self): t = True self.setTableroActual() for i in range(0,9): for j in range(0,9): self.ui.tablero.itemAtPosition(i/3, j/3).itemAtPosition(i%3, j%3).widget().setBackColor("white") if self.checkFila(i, j)==False: #pintar las celdas de Rojo self.ui.tablero.itemAtPosition(i/3, j/3).itemAtPosition(i%3, j%3).widget().setBackColor("red") self.ui.tablero.itemAtPosition(i/3, j/3).itemAtPosition(i%3, j%3).widget().setBlackBorder() t = False if self.checkColumna(i, j)==False: #pintar las celdas de rojo self.ui.tablero.itemAtPosition(i/3, j/3).itemAtPosition(i%3, j%3).widget().setBackColor("red") self.ui.tablero.itemAtPosition(i/3, j/3).itemAtPosition(i%3, j%3).widget().setBlackBorder() t = False if self.chechCuadro(i, j)==False: #pintar las celdas de rojo self.ui.tablero.itemAtPosition(i/3, j/3).itemAtPosition(i%3, j%3).widget().setBackColor("red") self.ui.tablero.itemAtPosition(i/3, j/3).itemAtPosition(i%3, j%3).widget().setBlackBorder() t = False if t==True: QtGui.QMessageBox.about(self, "Felicitaciones", "Sudoku Resuleto Correctamente") else: QtGui.QMessageBox.about(self, "Mensaje", "Sudoku resuleto incorrectamente") self.bandera = False def volverTableroNormal(self): for i in range(0,9): for j in range(0,9): self.ui.tablero.itemAtPosition(i/3, j/3).itemAtPosition(i%3, j%3).widget().setBackColor("white") def cmdHint_clicked(self): print "proximamente lo implementaremos" if self.hints > 0: self.hints = self.hints-1 self.sender().setText("Hints "+str(self.hints)) self.setTableroActual() while True: irnd = randint(1,8) jrnd = randint(1,8) if self.tableroActual[irnd][jrnd] == 0: break self.tableroActual[irnd][jrnd] = self.matriz[irnd][jrnd] self.ui.tablero.itemAtPosition(irnd/3, jrnd/3).itemAtPosition(irnd%3, jrnd%3).widget().setValue(self.tableroActual[irnd][jrnd]) self.setTableroEnPantalla() else: QtGui.QMessageBox.about(self, "Mensaje", "No le quedan mas ayudas :(") self.ui.cmdHint.setEnabled(False) def calcularPuntaje(self): b=0 for i in range(0,9): for j in range(0,9): try: a = self.tableroActual[i][j] except AttributeError: print "aun no ha empezado a jugar" return 0 if a!=0: b = b+1 if self.dificultad == 0: return (b-30)*10-self.tm.minute() if self.dificultad == 1: return (b-30)*10-self.tm.minute() if self.dificultad == 2: return (b-30)*10-self.tm.minute() if self.dificultad == 3: return (b-30)*10-self.tm.minute() return 0
if args.plotHist: # Show histogram for data split by meta data value. useMeta = True if args.plotKernel: # Add all target and non target data together, i.e. do not use meta data label info. useMeta = False histogram = Histogram(data, config, expName, 'normal', debug, useMeta) histogram.plot() if args.plotMatrix: matrix = MatrixPlot(data, config, expName, debug) matrix.plot() if args.plotRanking: if (len(data.getTargetCnt()) > 0) and (len(data.getNonTargetCnt()) > 0): ranking = Ranking(data, config, expName, debug) ranking.plot() else: print("Not enough data.") if args.plotRoc: if (len(data.getTargetCnt()) > 0) and (len(data.getNonTargetCnt()) > 0): roc = Roc(data, eerObject, cllrObject, config, expName, debug) roc.plot() else: print("Not enough data.") if args.plotTippet: if (len(data.getTargetCnt()) > 0) and (len(data.getNonTargetCnt()) > 0): tippet = Tippett(data, eerObject, cllrObject, config, expName, debug) tippet.plot()
def index(): race_classes = [ (race_class_id.id, race_class_id.name) for race_class_id in RaceClass.query.with_entities( RaceClass.id, RaceClass.name) .join(Race) .group_by(RaceClass.id) .order_by(RaceClass.name)] year_race_class_ids = [race_class_id for race_class_id, _ in race_classes] try: req_race_class_id = int(request.args.get('race_class_id')) except (ValueError, TypeError): req_race_class_id = None race_class_id = ( req_race_class_id if req_race_class_id in year_race_class_ids else (year_race_class_ids[0] if year_race_class_ids else None)) earliest_date_qr = ( Race.query .filter(Race.class_id == race_class_id) .order_by(Race.date) .limit(1)).one_or_none() earliest_date = earliest_date_qr.date if earliest_date_qr else datetime.date.today() individual_points = [ {'racer_id': r.racer_id, 'racer_name': r.racer_name, 'rank': rank, 'points': r.points} for rank, r in Ranking( Racer.query.with_entities( Racer.id.label('racer_id'), Racer.name.label('racer_name'), func.sum(Participant.points).label('points')) .join(Participant, Participant.racer_id == Racer.id) .join(Race, Race.id == Participant.race_id) .filter(Race.points_race) .filter(Race.class_id == race_class_id) .group_by(Racer.id) .having(func.sum(Participant.points) > 0) .order_by(func.sum(Participant.points).desc()), key=lambda r: r.points, start=1)] mar_points = [ {'racer_id': r.racer_id, 'racer_name': r.racer_name, 'rank': rank, 'mar_points': r.mar_points} for rank, r in Ranking( Racer.query.with_entities( Racer.id.label('racer_id'), Racer.name.label('racer_name'), func.sum(Participant.mar_points).label('mar_points')) .join(Participant, Participant.racer_id == Racer.id) .join(Race, Race.id == Participant.race_id) .filter(Race.points_race) .filter(Race.class_id == race_class_id) .group_by(Racer.id) .having(func.sum(Participant.mar_points) > 0) .order_by(func.sum(Participant.mar_points).desc()), key=lambda r: r.mar_points, start=1)] wins = [{ 'racer_id': r.racer_id, 'racer_name': r.racer_name, 'rank': rank, 'wins': r.wins, 'points_wins': r.points_wins} for rank, r in Ranking( Racer.query.with_entities( Racer.id.label('racer_id'), Racer.name.label('racer_name'), func.count(1).label('wins'), func.sum(case([(Race.points_race, 1)], else_=0)).label('points_wins')) .join(Participant, Participant.racer_id == Racer.id) .join(Race, Race.id == Participant.race_id) .filter(Race.class_id == race_class_id) .filter(Participant.place == 1) .group_by(Racer.id) .order_by( func.count(1).label('wins').desc(), func.sum(case([(Race.points_race, 1)], else_=0)).desc()), key=lambda r: r.wins, start=1)]
def testRanking(self): # r=Player() # r.get cards = [{ "rank": "6", "suit": "hearts" }, { "rank": "K", "suit": "spades" }, { "rank": "A", "suit": "spades" }, { "rank": "Q", "suit": "hearts" }, { "rank": "6", "suit": "clubs" }] r = Ranking(cards) self.assertEqual(1, r.getRanking()) cards = [{ "rank": "6", "suit": "hearts" }, { "rank": "K", "suit": "spades" }, { "rank": "A", "suit": "spades" }, { "rank": "A", "suit": "hearts" }, { "rank": "6", "suit": "clubs" }] r = Ranking(cards) self.assertEqual(2, r.getRanking()) cards = [{ "rank": "6", "suit": "hearts" }, { "rank": "K", "suit": "spades" }, { "rank": "6", "suit": "spades" }, { "rank": "A", "suit": "hearts" }, { "rank": "6", "suit": "clubs" }] r = Ranking(cards) self.assertEqual(3, r.getRanking()) cards = [{ "rank": "10", "suit": "spades" }, { "rank": "8", "suit": "diamonds" }, { "rank": "J", "suit": "hearts" }, { "rank": "9", "suit": "spades" }, { "rank": "Q", "suit": "clubs" }] r = Ranking(cards) self.assertEqual(4, r.getRanking()) cards = [{ "rank": "5", "suit": "diamonds" }, { "rank": "2", "suit": "diamonds" }, { "rank": "7", "suit": "diamonds" }, { "rank": "8", "suit": "clubs" }, { "rank": "8", "suit": "diamonds" }, { "rank": "J", "suit": "diamonds" }] r = Ranking(cards) self.assertEqual(5, r.getRanking()) cards = [{ "rank": "6", "suit": "hearts" }, { "rank": "A", "suit": "spades" }, { "rank": "6", "suit": "spades" }, { "rank": "A", "suit": "hearts" }, { "rank": "6", "suit": "clubs" }] r = Ranking(cards) self.assertEqual(6, r.getRanking()) cards = [{ "rank": "A", "suit": "diamonds" }, { "rank": "A", "suit": "spades" }, { "rank": "6", "suit": "spades" }, { "rank": "A", "suit": "hearts" }, { "rank": "A", "suit": "clubs" }] r = Ranking(cards) self.assertEqual(7, r.getRanking()) cards = [{ "rank": "8", "suit": "spades" }, { "rank": "J", "suit": "spades" }, { "rank": "Q", "suit": "spades" }, { "rank": "10", "suit": "spades" }, { "rank": "9", "suit": "spades" }] r = Ranking(cards) self.assertEqual(8, r.getRanking())
def compute_p_value(self, test_statistic, null_distribution): dist = np.append(null_distribution, test_statistic) dist.sort() r = Ranking(dist[::-1]) return r.rank(test_statistic)/float(len(dist))
try: if len(sys.argv) < 2: raise ValueError('É necessário informar um arquivo como parametro') p = Persistencia(sys.argv[1]) inicio = Inicio(None) inicio.title('UniPoker') inicio.mainloop() player = inicio.nome.title() seed = inicio.seed random.seed(seed) while True: jogo = Jogo(None, player, seed) jogo.title('UniPoker') jogo.mainloop() credito = jogo.credito r = Ranking(None, player, credito, seed) r.title('Ranking') r.mainloop() if not r.reini: break except Exception as e: print(e) sys.exit()
def __init__ (self, num_players, Y): Ranking.__init__(self, num_players) self.Y = Y
def __init__(self): self.conn = sqlite3.connect(":memory:") self.c = self.conn.cursor() Ranking.__init__(self, 1, conn=self.conn)
def get_ranking_scores(data, predicted_rank_name, original_rank_name, invert_ranks = False, filter_ref = True, suffix = "", prefix = "", replace_predicted = None, **kwargs): predicted_rank_vectors = [] original_rank_vectors = [] missing_predicted_values = 0 for parallelsentence in data.get_parallelsentences(): if filter_ref: #get a vector with all the rank_strings labels from all systems apart from the references try: predicted_rank_vector = parallelsentence.get_filtered_target_attribute_values(predicted_rank_name, filter_attribute_name="system", filter_attribute_value="_ref") except Exception as e: logging.error("Could not get desired rank_name '{}' from parallelsentence with attributes: \n{}".format(predicted_rank_name, parallelsentence.get_attributes())) missing_predicted_values += 1 raise Exception(e) original_rank_vector = parallelsentence.get_filtered_target_attribute_values(original_rank_name, filter_attribute_name="system", filter_attribute_value="_ref") else: #get a vector with all the rank_strings labels predicted_rank_vector = parallelsentence.get_target_attribute_values(predicted_rank_name) original_rank_vector = parallelsentence.get_target_attribute_values(original_rank_name) #construct ranking objects try: predicted_ranking = Ranking(predicted_rank_vector) original_ranking = Ranking(original_rank_vector) #invert rankings if requested if invert_ranks: predicted_ranking = predicted_ranking.reverse() #original_ranking = original_ranking.reverse() except Exception as e: logging.error("Error while processing Parallelsentence with attributes {}".format(parallelsentence.get_attributes())) logging.error("ranking that caused the error: predicted: {}, original: {}".format(predicted_ranking, original_ranking)) raise Exception(e) #add the ranking in the big vector with all previous parallel sentences predicted_rank_vectors.append(predicted_ranking) original_rank_vectors.append(original_ranking) if missing_predicted_values: logging.warning("{} sentences where missing the {}".format(missing_predicted_values, predicted_rank_name)) stats = OrderedDict() #process the list of rankings with all metric functions and collect the #results in an ordered dict for callback in SET_METRIC_FUNCTIONS: current_stats = callback(predicted_rank_vectors, original_rank_vectors) stats.update(current_stats) #add the requested preffix and suffix to every value stats = OrderedDict([("{}-{}{}".format(prefix, key, suffix),value) for key,value in stats.iteritems()]) return stats
def ranking(self): r = Ranking() active_players = [p for p in self._players if p.is_active()] for p in active_players: r.add_entry(p, self._match_log.times_match_win(p)) return r
if algorithm == 'BM25': if cache_flag == 'cache': BM25.useCache = True query_structure = _pickle.load( open(os.path.join(os.curdir, "cache/query_structure_cache"), "rb")) document_structure = _pickle.load( open(os.path.join(os.curdir, "cache/paragraph_structure"), "rb")) print("No of queries" + str(len(query_structure))) print("No of documents" + str(len(document_structure))) BM25.number_of_words_in_the_collection_s = \ _pickle.load(open(os.path.join(os.curdir, "cache/no_of_words_in_the_collection"), "rb")) BM25.all_words_freq_dict = _pickle.load( open(os.path.join(os.curdir, "cache/all_terms_freq_dict"), "rb")) logic_instance = BM25(query_structure, document_structure) else: ranking = Ranking(query_cbor, paragraphs_cbor, passages_extract) query_structure = ranking.gather_queries() document_structure = ranking.gather_paragraphs() print("No of queries" + str(len(query_structure))) print("No of documents" + str(len(document_structure))) logic_instance = BM25(query_structure, document_structure) elif algorithm == 'PROX': if cache_flag == 'cache': BM25.useCache = True query_structure = _pickle.load( open(os.path.join(os.curdir, "cache/query_structure_cache"), "rb")) document_structure = _pickle.load( open(os.path.join(os.curdir, "cache/paragraph_structure"), "rb")) print("No of queries" + str(len(query_structure))) print("No of documents" + str(len(document_structure)))
def index(): db = get_db() players = db.execute(''' SELECT * FROM player WHERE active = 1 ORDER BY exposure DESC;''') players = Ranking(players.fetchall(), start=1, key=lambda x: x['exposure']) aliases = db.execute('SELECT alias FROM player ORDER BY alias;') recents = db.execute(''' SELECT w.alias, l.alias, winscore, losescore, scheduled FROM match JOIN player w ON winner = w.id JOIN player l ON loser = l.id ORDER BY date DESC LIMIT 10;''') games = db.execute('SELECT COUNT(id) FROM match;').fetchone() # get or regenerate the schedule weekrow = db.execute('SELECT * FROM week;').fetchone(); week = datetime.now().isocalendar()[1] if weekrow is None or weekrow['week'] != week: db.execute('DELETE FROM schedule;') db.execute('DELETE FROM week;') db.execute('INSERT INTO week VALUES (?);', (week,)) players2 = db.execute(''' SELECT * FROM player WHERE active = 1 ORDER BY exposure DESC;''').fetchall() match_offset = min((week % 5) + 1, len(players2)//2) # shuffle bottom of ladder so players get new opponents players2 = players2[:-match_offset] + shuffle(players2[-match_offset:]) while len(players2) > match_offset: p1 = players2.pop(0) p2 = players2.pop(match_offset) matches.append((p1['id'], p2['id'])) while len(players) > 1: p1 = players2.pop(0) p2 = players2.pop(1) matches.append((p1['id'], p2['id'])) db.executemany(''' INSERT INTO schedule (p1, p2) VALUES (?, ?);''', matches) db.commit() schedule = db.execute(''' SELECT p1.alias, p2.alias, p1.mu, p1.sigma, p2.mu, p2.sigma FROM schedule JOIN player p1 ON p1 = p1.id JOIN player p2 ON p2 = p2.id;''').fetchall() qualities = [] for match in schedule: r1 = ts.Rating(match[2], match[3]) r2 = ts.Rating(match[4], match[5]) qualities.append(ts.quality_1vs1(r1, r2) * 100) return render_template('index.html', players=players, aliases=aliases, recents=recents, games = games[0], schedule=zip(schedule, qualities), rankedweek=(week%2==1))
def rankings_page(key = None): page = Ranking(dsn = app.config['dsn']) if key == 1: return page.open_page("name") elif key == 2: return page.open_page("surname") elif key == 3: return page.open_page("country") elif key == 4: return page.open_page("club") elif key == 5: return page.open_page("age") elif key == 6: return page.open_page("rating") elif key == 7: return page.open_page("ranking") elif key == 8: return page.open_page("gender") elif key == 9: return page.open_page("country_name") elif key == 10: return page.open_page("average") elif key == 11: return page.open_page("gm") elif key == 12: return page.open_page("im") elif key == 13: return page.open_page("total_titled") elif key == 14: return page.open_page("total_top") elif key == 15: return page.open_page("country_rank") elif key == 16: return page.open_page("best_player") elif key == 17: return page.open_page("highest_rating") elif request.method == 'GET': try: return page.open_page() except: return page.init_table() elif 'initializeTable' in request.form: return page.init_table() elif 'addplayer' in request.form: name = request.form['name'] surname = request.form['surname'] country = request.form['country'] club = request.form['club'] rating = request.form['rating'] ranking = request.form['ranking'] age = request.form['age'] gender = request.form['gender'] return page.add_player(name, surname, country, club, rating, ranking, age, gender) elif 'addcountry' in request.form: country_name = request.form['country_name'] average = request.form['average'] gm = request.form['gm'] im = request.form['im'] total_titled = request.form['total_titled'] total_top = request.form['total_top'] country_rank = request.form['country_rank'] best_player = request.form['best_player'] highest_rating = request.form['highest_rating'] return page.add_country(country_name, average, gm, im, total_titled, total_top, country_rank, best_player, highest_rating) elif 'addplayer_info' in request.form: name = request.form['name'] surname = request.form['surname'] country = request.form['country'] club = request.form['club'] best_rating = request.form['best_rating'] best_ranking = request.form['best_ranking'] best_tournament = request.form['best_tournament'] best_tournament_result = request.form['best_tournament_result'] curr_rating = request.form['curr_rating'] curr_ranking = request.form['curr_ranking'] return page.add_player_info(name, surname, country, club, best_rating, best_ranking, best_tournament, best_tournament_result, curr_rating, curr_ranking) elif 'deleteplayer' in request.form: name = request.form['name'] surname = request.form['surname'] return page.delete_player(name, surname) elif 'deletecountry' in request.form: country_name = request.form['country_name'] return page.delete_country(country_name) elif 'deleteplayer_info' in request.form: name = request.form['name'] surname = request.form['surname'] return page.delete_player(name, surname) elif 'findcountry' in request.form: country_name = request.form['country_name'] return page.find_country(country_name) elif 'deleteplayerwithid' in request.form: id = request.form['id'] return page.delete_player_with_id(id) elif 'findplayer' in request.form: name = request.form['name'] surname = request.form['surname'] return page.find_player(name, surname) elif 'findplayerbycountry' in request.form: search = request.form['country'] return page.find_player_by_country(search) elif 'findplayer_info' in request.form: name = request.form['name'] surname = request.form['surname'] return page.find_player_info(name, surname) else: return redirect(url_for('home_page'))
def betRequest(self, game_state): bet = 0 all_my_money = 0 try: myself = game_state["players"][game_state["in_action"]] cards_hand = myself["hole_cards"] cards_desk = game_state["community_cards"] cards_all = cards_hand + cards_desk all_my_money = int(myself["stack"]) ranking_service_all_cards = Ranking(cards_all) ranking_service_hand = Ranking(cards_hand) #ranking = Ranking(cards_hand) chen_ranking = ranking_service_all_cards.get_chen_ranking() ranking = ranking_service_all_cards.getRanking() is_preflop = len(game_state["community_cards"]) == 0 active_player_count = len( filter(lambda player: player["status"] == "active", game_state["players"])) all_in_value = myself["stack"] minimum_raise = int(game_state["minimum_raise"]) small_blind = int(game_state["small_blind"]) if is_preflop: if active_player_count == 2: if chen_ranking >= 4.5: bet = all_in_value elif active_player_count == 3: if chen_ranking >= 5.5: bet = all_in_value elif active_player_count == 4: if chen_ranking >= 6: bet = all_in_value if bet != all_in_value: did_somebody_raise = minimum_raise >= small_blind * 2 if not did_somebody_raise: bet = minimum_raise * 2 if minimum_raise > small_blind * 8 and chen_ranking >= 7.5: bet = all_in_value else: TWO_PAIRS = 2 if ranking == 0: bet = 0 elif ranking == 1: bet = 2 * small_blind # desk_card_values = [c for c in cards_desk] # largest_desk_card_value = m elif ranking >= TWO_PAIRS: bet = all_in_value #out_player_count = #bet = max(100, int(game_state["minimum_raise"])) except: print "Meghaltam :(" return int(min(bet, all_my_money))
def verRanking(self): self.ranking = Ranking() self.ranking.setWindowModality(Qt.ApplicationModal) self.ranking.show()