From 284b0c1f38e0353d146c4b976188d7cd6091300c Mon Sep 17 00:00:00 2001 From: Eric Blade Date: Mon, 30 Nov 2009 08:14:03 -0500 Subject: [PATCH 01/10] fix return tuple in import_file_dict, fix text from autoimport to actually show up in autoimport window --- pyfpdb/fpdb.py | 15 +++++++-------- pyfpdb/fpdb_import.py | 11 ++++++++--- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/pyfpdb/fpdb.py b/pyfpdb/fpdb.py index d5f4faec..b960da05 100755 --- a/pyfpdb/fpdb.py +++ b/pyfpdb/fpdb.py @@ -115,7 +115,7 @@ class fpdb: self.pages.append(new_page) self.tabs.append(event_box) self.tab_names.append(new_tab_name) - + #self.nb.append_page(new_page, gtk.Label(new_tab_name)) self.nb.append_page(page, event_box) self.nb_tabs.append(new_tab_name) @@ -135,12 +135,12 @@ class fpdb: self.nb.set_current_page(tab_no) def create_custom_tab(self, text, nb): - #create a custom tab for notebook containing a + #create a custom tab for notebook containing a #label and a button with STOCK_ICON eventBox = gtk.EventBox() tabBox = gtk.HBox(False, 2) tabLabel = gtk.Label(text) - tabBox.pack_start(tabLabel, False) + tabBox.pack_start(tabLabel, False) eventBox.add(tabBox) if nb.get_n_pages() > 0: @@ -157,7 +157,7 @@ class fpdb: return eventBox def add_icon_to_button(self, button): - iconBox = gtk.HBox(False, 0) + iconBox = gtk.HBox(False, 0) image = gtk.Image() image.set_from_stock(gtk.STOCK_CLOSE, gtk.ICON_SIZE_SMALL_TOOLBAR) gtk.Button.set_relief(button, gtk.RELIEF_NONE) @@ -168,8 +168,8 @@ class fpdb: iconBox.pack_start(image, True, False, 0) button.add(iconBox) iconBox.show() - return - + return + # Remove a page from the notebook def remove_tab(self, button, data): (nb, text) = data @@ -183,7 +183,7 @@ class fpdb: #print " removing page", page del self.nb_tabs[page] nb.remove_page(page) - # Need to refresh the widget -- + # Need to refresh the widget -- # This forces the widget to redraw itself. #nb.queue_draw_area(0,0,-1,-1) needed or not?? @@ -752,7 +752,6 @@ This program is licensed under the AGPL3, see docs"""+os.sep+"agpl-3.0.txt") sys.stderr.write("fpdb starting ...") def window_state_event_cb(self, window, event): - print "window_state_event", event if event.changed_mask & gtk.gdk.WINDOW_STATE_ICONIFIED: # -20 = GWL_EXSTYLE can't find it in the pywin32 libs #bits = win32api.GetWindowLong(self.window.window.handle, -20) diff --git a/pyfpdb/fpdb_import.py b/pyfpdb/fpdb_import.py index 19bf18d1..b6cfb821 100644 --- a/pyfpdb/fpdb_import.py +++ b/pyfpdb/fpdb_import.py @@ -359,10 +359,15 @@ class Importer: # print "file",counter," updated", os.path.basename(file), stat_info.st_size, self.updatedsize[file], stat_info.st_mtime, self.updatedtime[file] try: if not os.path.isdir(file): - self.caller.addText("\n"+file) + self.caller.addText("\n"+os.path.basename(file)) except KeyError: # TODO: What error happens here? pass - self.import_file_dict(self.database, file, self.filelist[file][0], self.filelist[file][1], None) + (stored, duplicates, partial, errors, ttime) = self.import_file_dict(self.database, file, self.filelist[file][0], self.filelist[file][1], None) + try: + if not os.path.isdir(file): + self.caller.addText(" %d stored, %d duplicates, %d partial, %d errors (time = %d)" % (stored, duplicates, partial, errors, ttime)) + except KeyError: # TODO: Again, what error happens here? fix when we find out .. + pass self.updatedsize[file] = stat_info.st_size self.updatedtime[file] = time() else: @@ -393,7 +398,7 @@ class Importer: if os.path.isdir(file): self.addToDirList[file] = [site] + [filter] - return + return (0,0,0,0,0) conv = None (stored, duplicates, partial, errors, ttime) = (0, 0, 0, 0, 0) From 8c8fdba7c845886609f56eb77b9e7fd4c131df91 Mon Sep 17 00:00:00 2001 From: Eric Blade Date: Mon, 30 Nov 2009 09:08:30 -0500 Subject: [PATCH 02/10] ttime = float with us to ms resolution --- pyfpdb/fpdb_import.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/pyfpdb/fpdb_import.py b/pyfpdb/fpdb_import.py index b6cfb821..541b018f 100644 --- a/pyfpdb/fpdb_import.py +++ b/pyfpdb/fpdb_import.py @@ -21,7 +21,7 @@ import os # todo: remove this once import_dir is in fpdb_import import sys -from time import time, strftime, sleep +from time import time, strftime, sleep, clock import traceback import math import datetime @@ -101,6 +101,8 @@ class Importer: self.NEWIMPORT = Configuration.NEWIMPORT + clock() # init clock in windows + #Set functions def setCallHud(self, value): self.callHud = value @@ -365,7 +367,7 @@ class Importer: (stored, duplicates, partial, errors, ttime) = self.import_file_dict(self.database, file, self.filelist[file][0], self.filelist[file][1], None) try: if not os.path.isdir(file): - self.caller.addText(" %d stored, %d duplicates, %d partial, %d errors (time = %d)" % (stored, duplicates, partial, errors, ttime)) + self.caller.addText(" %d stored, %d duplicates, %d partial, %d errors (time = %f)" % (stored, duplicates, partial, errors, ttime)) except KeyError: # TODO: Again, what error happens here? fix when we find out .. pass self.updatedsize[file] = stat_info.st_size @@ -477,10 +479,13 @@ class Importer: self.pos_in_file[file] = inputFile.tell() inputFile.close() + x = clock() (stored, duplicates, partial, errors, ttime, handsId) = self.import_fpdb_lines(db, self.lines, starttime, file, site, q) db.commit() - ttime = time() - starttime + y = clock() + ttime = y - x + #ttime = time() - starttime if q is None: log.info("Total stored: %(stored)d\tduplicates:%(duplicates)d\terrors:%(errors)d\ttime:%(ttime)s" % locals()) From 9953e76c9e1e8566e79e9c02acaa35aa6ccdf57e Mon Sep 17 00:00:00 2001 From: Eric Blade Date: Mon, 30 Nov 2009 09:51:47 -0500 Subject: [PATCH 03/10] trap IOError on hud pipe write when hud closed without autoimport stopping, turn off hud --- pyfpdb/fpdb_import.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/pyfpdb/fpdb_import.py b/pyfpdb/fpdb_import.py index 541b018f..d735de04 100644 --- a/pyfpdb/fpdb_import.py +++ b/pyfpdb/fpdb_import.py @@ -564,7 +564,11 @@ class Importer: #print "call to HUD here. handsId:",handsId #pipe the Hands.id out to the HUD # print "fpdb_import: sending hand to hud", handsId, "pipe =", self.caller.pipe_to_hud - self.caller.pipe_to_hud.stdin.write("%s" % (handsId) + os.linesep) + try: + self.caller.pipe_to_hud.stdin.write("%s" % (handsId) + os.linesep) + except IOError: # hud closed + self.callHud = False + pass # continue import without hud except Exceptions.DuplicateError: duplicates += 1 db.rollback() From bec343abfdcd15ea541193b0f0e502c630da6f1a Mon Sep 17 00:00:00 2001 From: Eric Blade Date: Tue, 1 Dec 2009 06:58:33 -0500 Subject: [PATCH 04/10] argh at whitespace churn, do i have my editor settings screwey? trap error 2003 on mysql connect (same as 2002, but for tcp) --- pyfpdb/Database.py | 270 ++++++++++++++++++++++----------------------- pyfpdb/fpdb.py | 2 +- pyfpdb/fpdb_db.py | 2 +- 3 files changed, 137 insertions(+), 137 deletions(-) diff --git a/pyfpdb/Database.py b/pyfpdb/Database.py index cd6ad298..d71f8ab1 100755 --- a/pyfpdb/Database.py +++ b/pyfpdb/Database.py @@ -4,17 +4,17 @@ Create and manage the database objects. """ # Copyright 2008, Ray E. Barker -# +# # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA @@ -63,7 +63,7 @@ class Database: # Data Structures for index and foreign key creation # drop_code is an int with possible values: 0 - don't drop for bulk import # 1 - drop during bulk import - # db differences: + # db differences: # - note that mysql automatically creates indexes on constrained columns when # foreign keys are created, while postgres does not. Hence the much longer list # of indexes is required for postgres. @@ -102,7 +102,7 @@ class Database: # {'tab':'Players', 'col':'name', 'drop':0} unique indexes not dropped # {'tab':'Hands', 'col':'siteHandNo', 'drop':0} unique indexes not dropped {'tab':'Hands', 'col':'gametypeId', 'drop':0} - , {'tab':'HandsPlayers', 'col':'handId', 'drop':0} + , {'tab':'HandsPlayers', 'col':'handId', 'drop':0} , {'tab':'HandsPlayers', 'col':'playerId', 'drop':0} , {'tab':'HandsPlayers', 'col':'tourneyTypeId', 'drop':0} , {'tab':'HandsPlayers', 'col':'tourneysPlayersId', 'drop':0} @@ -147,7 +147,7 @@ class Database: # (fkcol is used for foreigh key name) # mysql to list indexes: - # SELECT table_name, index_name, non_unique, column_name + # SELECT table_name, index_name, non_unique, column_name # FROM INFORMATION_SCHEMA.STATISTICS # WHERE table_name = 'tbl_name' # AND table_schema = 'db_name' @@ -183,16 +183,16 @@ class Database: # create index indexname on tablename (col); - def __init__(self, c, sql = None): + def __init__(self, c, sql = None): log.info("Creating Database instance, sql = %s" % sql) self.config = c self.fdb = fpdb_db.fpdb_db() # sets self.fdb.db self.fdb.cursor and self.fdb.sql self.do_connect(c) - + if self.backend == self.PGSQL: from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT, ISOLATION_LEVEL_READ_COMMITTED, ISOLATION_LEVEL_SERIALIZABLE #ISOLATION_LEVEL_AUTOCOMMIT = 0 - #ISOLATION_LEVEL_READ_COMMITTED = 1 + #ISOLATION_LEVEL_READ_COMMITTED = 1 #ISOLATION_LEVEL_SERIALIZABLE = 2 @@ -262,11 +262,11 @@ class Database: def disconnect(self, due_to_error=False): """Disconnects the DB (rolls back if param is true, otherwise commits""" self.fdb.disconnect(due_to_error) - + def reconnect(self, due_to_error=False): """Reconnects the DB""" self.fdb.reconnect(due_to_error=False) - + def get_backend_name(self): """Returns the name of the currently used backend""" if self.backend==2: @@ -283,7 +283,7 @@ class Database: c.execute(self.sql.query['get_table_name'], (hand_id, )) row = c.fetchone() return row - + def get_table_info(self, hand_id): c = self.connection.cursor() c.execute(self.sql.query['get_table_name'], (hand_id, )) @@ -304,18 +304,18 @@ class Database: c.execute(self.sql.query['get_last_hand']) row = c.fetchone() return row[0] - + def get_xml(self, hand_id): c = self.connection.cursor() c.execute(self.sql.query['get_xml'], (hand_id)) row = c.fetchone() return row[0] - + def get_recent_hands(self, last_hand): c = self.connection.cursor() c.execute(self.sql.query['get_recent_hands'], {'last_hand': last_hand}) return c.fetchall() - + def get_hand_info(self, new_hand_id): c = self.connection.cursor() c.execute(self.sql.query['get_hand_info'], new_hand_id) @@ -549,7 +549,7 @@ class Database: query = query.replace("", 'signed ') else: query = query.replace("", '') - + subs = (self.hand_1day_ago, hand, hero_id, seats_min, seats_max , hero_id, h_seats_min, h_seats_max) c = self.get_cursor() @@ -577,7 +577,7 @@ class Database: elif name.lower() not in ('hand_id', 'player_id', 'seat', 'screen_name', 'seats'): stat_dict[playerid][name.lower()] += val n += 1 - if n >= 10000: break # todo: don't think this is needed so set nice and high + if n >= 10000: break # todo: don't think this is needed so set nice and high # prevents infinite loop so leave for now - comment out or remove? row = c.fetchone() else: @@ -587,7 +587,7 @@ class Database: #print "session stat_dict =", stat_dict #return stat_dict - + def get_player_id(self, config, site, player_name): c = self.connection.cursor() c.execute(self.sql.query['get_player_id'], (player_name, site)) @@ -596,7 +596,7 @@ class Database: return row[0] else: return None - + def get_player_names(self, config, site_id=None, like_player_name="%"): """Fetch player names from players. Use site_id and like_player_name if provided""" @@ -606,7 +606,7 @@ class Database: c.execute(self.sql.query['get_player_names'], (like_player_name, site_id, site_id)) rows = c.fetchall() return rows - + #returns the SQL ids of the names given in an array # TODO: if someone gets industrious, they should make the parts that use the output of this function deal with a dict # { playername: id } instead of depending on it's relation to the positions list @@ -666,7 +666,7 @@ class Database: # tmp = cursor.fetchall() # for n in tmp: # result.append(n[0]) - # + # # return result @@ -760,7 +760,7 @@ class Database: if 'dropHudCache' not in settings or settings['dropHudCache'] != 'drop': self.storeHudCache(self.backend, base, category, gametype_id, hand_start_time, player_ids, hudImportData) t5 = time() - #print "fills=(%4.3f) saves=(%4.3f,%4.3f,%4.3f)" % (t2-t0, t3-t2, t4-t3, t5-t4) + print "fills=(%4.3f) saves=(%4.3f,%4.3f,%4.3f)" % (t2-t0, t3-t2, t4-t3, t5-t4) return hands_id #end def ring_holdem_omaha @@ -827,7 +827,7 @@ class Database: #end def tourney_stud def prepareBulkImport(self): - """Drop some indexes/foreign keys to prepare for bulk import. + """Drop some indexes/foreign keys to prepare for bulk import. Currently keeping the standalone indexes as needed to import quickly""" stime = time() c = self.get_cursor() @@ -845,7 +845,7 @@ class Database: "FROM information_schema.KEY_COLUMN_USAGE " + #"WHERE REFERENCED_TABLE_SCHEMA = 'fpdb' "WHERE 1=1 " + - "AND table_name = %s AND column_name = %s " + + "AND table_name = %s AND column_name = %s " + "AND referenced_table_name = %s " + "AND referenced_column_name = %s ", (fk['fktab'], fk['fkcol'], fk['rtab'], fk['rcol']) ) @@ -862,7 +862,7 @@ class Database: print "dropping pg fk", fk['fktab'], fk['fkcol'] try: # try to lock table to see if index drop will work: - # hmmm, tested by commenting out rollback in grapher. lock seems to work but + # hmmm, tested by commenting out rollback in grapher. lock seems to work but # then drop still hangs :-( does work in some tests though?? # will leave code here for now pending further tests/enhancement ... c.execute( "lock table %s in exclusive mode nowait" % (fk['fktab'],) ) @@ -881,13 +881,13 @@ class Database: else: print "Only MySQL and Postgres supported so far" return -1 - + for idx in self.indexes[self.backend]: if idx['drop'] == 1: if self.backend == self.MYSQL_INNODB: print "dropping mysql index ", idx['tab'], idx['col'] try: - # apparently nowait is not implemented in mysql so this just hangs if there are locks + # apparently nowait is not implemented in mysql so this just hangs if there are locks # preventing the index drop :-( c.execute( "alter table %s drop index %s;", (idx['tab'],idx['col']) ) except: @@ -903,13 +903,13 @@ class Database: #print "after lock, status:", c.statusmessage try: # table locked ok so index drop should work: - #print "drop index %s_%s_idx" % (idx['tab'],idx['col']) + #print "drop index %s_%s_idx" % (idx['tab'],idx['col']) c.execute( "drop index if exists %s_%s_idx" % (idx['tab'],idx['col']) ) #print "dropped pg index ", idx['tab'], idx['col'] except: if "does not exist" not in str(sys.exc_value): print "warning: drop index %s_%s_idx failed: %s, continuing ..." \ - % (idx['tab'],idx['col'], str(sys.exc_value).rstrip('\n')) + % (idx['tab'],idx['col'], str(sys.exc_value).rstrip('\n')) except: print "warning: index %s_%s_idx not dropped %s, continuing ..." \ % (idx['tab'],idx['col'], str(sys.exc_value).rstrip('\n')) @@ -927,7 +927,7 @@ class Database: def afterBulkImport(self): """Re-create any dropped indexes/foreign keys after bulk import""" stime = time() - + c = self.get_cursor() if self.backend == self.MYSQL_INNODB: c.execute("SET foreign_key_checks=1") @@ -943,7 +943,7 @@ class Database: "FROM information_schema.KEY_COLUMN_USAGE " + #"WHERE REFERENCED_TABLE_SCHEMA = 'fpdb' "WHERE 1=1 " + - "AND table_name = %s AND column_name = %s " + + "AND table_name = %s AND column_name = %s " + "AND referenced_table_name = %s " + "AND referenced_column_name = %s ", (fk['fktab'], fk['fkcol'], fk['rtab'], fk['rcol']) ) @@ -954,8 +954,8 @@ class Database: else: print "creating fk ", fk['fktab'], fk['fkcol'], "->", fk['rtab'], fk['rcol'] try: - c.execute("alter table " + fk['fktab'] + " add foreign key (" - + fk['fkcol'] + ") references " + fk['rtab'] + "(" + c.execute("alter table " + fk['fktab'] + " add foreign key (" + + fk['fkcol'] + ") references " + fk['rtab'] + "(" + fk['rcol'] + ")") except: print " create fk failed: " + str(sys.exc_info()) @@ -971,7 +971,7 @@ class Database: else: print "Only MySQL and Postgres supported so far" return -1 - + for idx in self.indexes[self.backend]: if idx['drop'] == 1: if self.backend == self.MYSQL_INNODB: @@ -1021,10 +1021,10 @@ class Database: c.execute("ALTER TABLE " + inner[j][0] + " DROP FOREIGN KEY " + key) self.commit() #end drop_referential_inegrity - + def recreate_tables(self): """(Re-)creates the tables of the current DB""" - + self.drop_tables() self.create_tables() self.createAllIndexes() @@ -1068,7 +1068,7 @@ class Database: self.rollback() raise #end def disconnect - + def drop_tables(self): """Drops the fpdb tables from the current db""" try: @@ -1202,7 +1202,7 @@ class Database: "FROM information_schema.KEY_COLUMN_USAGE " + #"WHERE REFERENCED_TABLE_SCHEMA = 'fpdb' "WHERE 1=1 " + - "AND table_name = %s AND column_name = %s " + + "AND table_name = %s AND column_name = %s " + "AND referenced_table_name = %s " + "AND referenced_column_name = %s ", (fk['fktab'], fk['fkcol'], fk['rtab'], fk['rcol']) ) @@ -1213,8 +1213,8 @@ class Database: else: print "creating fk ", fk['fktab'], fk['fkcol'], "->", fk['rtab'], fk['rcol'] try: - c.execute("alter table " + fk['fktab'] + " add foreign key (" - + fk['fkcol'] + ") references " + fk['rtab'] + "(" + c.execute("alter table " + fk['fktab'] + " add foreign key (" + + fk['fkcol'] + ") references " + fk['rtab'] + "(" + fk['rcol'] + ")") except: print " create fk failed: " + str(sys.exc_info()) @@ -1251,7 +1251,7 @@ class Database: "FROM information_schema.KEY_COLUMN_USAGE " + #"WHERE REFERENCED_TABLE_SCHEMA = 'fpdb' "WHERE 1=1 " + - "AND table_name = %s AND column_name = %s " + + "AND table_name = %s AND column_name = %s " + "AND referenced_table_name = %s " + "AND referenced_column_name = %s ", (fk['fktab'], fk['fkcol'], fk['rtab'], fk['rcol']) ) @@ -1268,7 +1268,7 @@ class Database: print "dropping pg fk", fk['fktab'], fk['fkcol'] try: # try to lock table to see if index drop will work: - # hmmm, tested by commenting out rollback in grapher. lock seems to work but + # hmmm, tested by commenting out rollback in grapher. lock seems to work but # then drop still hangs :-( does work in some tests though?? # will leave code here for now pending further tests/enhancement ... c.execute( "lock table %s in exclusive mode nowait" % (fk['fktab'],) ) @@ -1286,14 +1286,14 @@ class Database: % (fk['fktab'],fk['fkcol'], str(sys.exc_value).rstrip('\n')) else: print "Only MySQL and Postgres supported so far" - + if self.backend == self.PGSQL: self.connection.set_isolation_level(1) # go back to normal isolation level #end def dropAllForeignKeys - + def fillDefaultData(self): - c = self.get_cursor() + c = self.get_cursor() c.execute("INSERT INTO Settings (version) VALUES (118);") c.execute("INSERT INTO Sites (name,currency) VALUES ('Full Tilt Poker', 'USD')") c.execute("INSERT INTO Sites (name,currency) VALUES ('PokerStars', 'USD')") @@ -1343,7 +1343,7 @@ class Database: p_id = self.get_player_id(self.config, site, self.hero[site_id]) if p_id: self.hero_ids[site_id] = int(p_id) - + if start is None: start = self.hero_hudstart_def if self.hero_ids == {}: @@ -1381,7 +1381,7 @@ class Database: p_id = self.get_player_id(self.config, site, self.hero[site_id]) if p_id: self.hero_ids[site_id] = int(p_id) - + q = self.sql.query['get_hero_hudcache_start'].replace("", str(tuple(self.hero_ids.values()))) c = self.get_cursor() c.execute(q) @@ -1458,7 +1458,7 @@ class Database: if h.isTourney: ranks = map(lambda x: 0, h.names) # create an array of 0's equal to the length of names payin_amounts = fpdb_simple.calcPayin(len(h.names), h.buyin, h.fee) - + if h.base == "hold": result = self.tourney_holdem_omaha( h.config, h.settings, h.base, h.category, h.siteTourneyNo, h.buyin @@ -1520,19 +1520,19 @@ class Database: c = self.get_cursor() c.execute(q, ( - p['tableName'], - p['gameTypeId'], - p['siteHandNo'], - p['handStart'], + p['tableName'], + p['gameTypeId'], + p['siteHandNo'], + p['handStart'], datetime.today(), #importtime p['seats'], p['maxSeats'], p['texture'], p['playersVpi'], - p['boardcard1'], - p['boardcard2'], - p['boardcard3'], - p['boardcard4'], + p['boardcard1'], + p['boardcard2'], + p['boardcard3'], + p['boardcard4'], p['boardcard5'], p['playersAtStreet1'], p['playersAtStreet2'], @@ -1858,7 +1858,7 @@ class Database: def getGameTypeId(self, siteid, game): c = self.get_cursor() #FIXME: Fixed for NL at the moment - c.execute(self.sql.query['getGametypeNL'], (siteid, game['type'], game['category'], game['limitType'], + c.execute(self.sql.query['getGametypeNL'], (siteid, game['type'], game['category'], game['limitType'], int(Decimal(game['sb'])*100), int(Decimal(game['bb'])*100))) tmp = c.fetchone() if (tmp == None): @@ -1875,7 +1875,7 @@ class Database: result = {} if(self.pcache == None): self.pcache = LambdaDict(lambda key:self.insertPlayer(key, siteid)) - + for player in pnames: result[player] = self.pcache[player] # NOTE: Using the LambdaDict does the same thing as: @@ -1935,7 +1935,7 @@ class Database: #stores into table hands: try: c = self.get_cursor() - c.execute ("""INSERT INTO Hands + c.execute ("""INSERT INTO Hands (siteHandNo, gametypeId, handStart, seats, tableName, importTime, maxSeats ,boardcard1,boardcard2,boardcard3,boardcard4,boardcard5 ,playersVpi, playersAtStreet1, playersAtStreet2 @@ -1944,8 +1944,8 @@ class Database: ,street3Raises, street4Raises, street1Pot ,street2Pot, street3Pot, street4Pot ,showdownPot - ) - VALUES + ) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) """.replace('%s', self.sql.query['placeholder']) @@ -1965,7 +1965,7 @@ class Database: return ret #end def storeHands - + def store_hands_players_holdem_omaha(self, backend, category, hands_id, player_ids, start_cashes ,positions, card_values, card_suits, winnings, rakes, seatNos, hudCache): result=[] @@ -2002,27 +2002,27 @@ class Database: hands_id, player_ids[i], start_cashes[i], positions[i], 1, # tourneytypeid - needed for hudcache card1, card2, card3, card4, startCards, winnings[i], rakes[i], seatNos[i], hudCache['totalProfit'][i], - hudCache['street0VPI'][i], hudCache['street0Aggr'][i], + hudCache['street0VPI'][i], hudCache['street0Aggr'][i], hudCache['street0_3BChance'][i], hudCache['street0_3BDone'][i], - hudCache['street1Seen'][i], hudCache['street2Seen'][i], hudCache['street3Seen'][i], + hudCache['street1Seen'][i], hudCache['street2Seen'][i], hudCache['street3Seen'][i], hudCache['street4Seen'][i], hudCache['sawShowdown'][i], hudCache['street1Aggr'][i], hudCache['street2Aggr'][i], hudCache['street3Aggr'][i], hudCache['street4Aggr'][i], - hudCache['otherRaisedStreet1'][i], hudCache['otherRaisedStreet2'][i], + hudCache['otherRaisedStreet1'][i], hudCache['otherRaisedStreet2'][i], hudCache['otherRaisedStreet3'][i], hudCache['otherRaisedStreet4'][i], - hudCache['foldToOtherRaisedStreet1'][i], hudCache['foldToOtherRaisedStreet2'][i], + hudCache['foldToOtherRaisedStreet1'][i], hudCache['foldToOtherRaisedStreet2'][i], hudCache['foldToOtherRaisedStreet3'][i], hudCache['foldToOtherRaisedStreet4'][i], hudCache['wonWhenSeenStreet1'][i], hudCache['wonAtSD'][i], - hudCache['stealAttemptChance'][i], hudCache['stealAttempted'][i], hudCache['foldBbToStealChance'][i], + hudCache['stealAttemptChance'][i], hudCache['stealAttempted'][i], hudCache['foldBbToStealChance'][i], hudCache['foldedBbToSteal'][i], hudCache['foldSbToStealChance'][i], hudCache['foldedSbToSteal'][i], hudCache['street1CBChance'][i], hudCache['street1CBDone'][i], hudCache['street2CBChance'][i], hudCache['street2CBDone'][i], hudCache['street3CBChance'][i], hudCache['street3CBDone'][i], hudCache['street4CBChance'][i], hudCache['street4CBDone'][i], - hudCache['foldToStreet1CBChance'][i], hudCache['foldToStreet1CBDone'][i], + hudCache['foldToStreet1CBChance'][i], hudCache['foldToStreet1CBDone'][i], hudCache['foldToStreet2CBChance'][i], hudCache['foldToStreet2CBDone'][i], - hudCache['foldToStreet3CBChance'][i], hudCache['foldToStreet3CBDone'][i], + hudCache['foldToStreet3CBChance'][i], hudCache['foldToStreet3CBDone'][i], hudCache['foldToStreet4CBChance'][i], hudCache['foldToStreet4CBDone'][i], - hudCache['street1CheckCallRaiseChance'][i], hudCache['street1CheckCallRaiseDone'][i], + hudCache['street1CheckCallRaiseChance'][i], hudCache['street1CheckCallRaiseDone'][i], hudCache['street2CheckCallRaiseChance'][i], hudCache['street2CheckCallRaiseDone'][i], - hudCache['street3CheckCallRaiseChance'][i], hudCache['street3CheckCallRaiseDone'][i], + hudCache['street3CheckCallRaiseChance'][i], hudCache['street3CheckCallRaiseDone'][i], hudCache['street4CheckCallRaiseChance'][i], hudCache['street4CheckCallRaiseDone'][i], hudCache['street0Calls'][i], hudCache['street1Calls'][i], hudCache['street2Calls'][i], hudCache['street3Calls'][i], hudCache['street4Calls'][i], hudCache['street0Bets'][i], hudCache['street1Bets'][i], hudCache['street2Bets'][i], hudCache['street3Bets'][i], hudCache['street4Bets'][i] @@ -2045,12 +2045,12 @@ class Database: foldToStreet3CBChance, foldToStreet3CBDone, foldToStreet4CBChance, foldToStreet4CBDone, street1CheckCallRaiseChance, street1CheckCallRaiseDone, street2CheckCallRaiseChance, street2CheckCallRaiseDone, street3CheckCallRaiseChance, street3CheckCallRaiseDone, street4CheckCallRaiseChance, street4CheckCallRaiseDone, - street0Calls, street1Calls, street2Calls, street3Calls, street4Calls, + street0Calls, street1Calls, street2Calls, street3Calls, street4Calls, street0Bets, street1Bets, street2Bets, street3Bets, street4Bets ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, - %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, + %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""".replace('%s', self.sql.query['placeholder']) ,inserts ) result.append( self.get_last_insert_id(c) ) # wrong? not used currently @@ -2084,7 +2084,7 @@ class Database: card5, card6, card7, winnings, rake, seatNo) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""".replace('%s', self.sql.query['placeholder']), - (hands_id, player_ids[i], start_cashes[i], antes[i], 1, + (hands_id, player_ids[i], start_cashes[i], antes[i], 1, card1, card2, card3, card4, card5, card6, @@ -2097,7 +2097,7 @@ class Database: return result #end def store_hands_players_stud - + def store_hands_players_holdem_omaha_tourney(self, backend, category, hands_id, player_ids ,start_cashes, positions, card_values, card_suits ,winnings, rakes, seatNos, tourneys_players_ids @@ -2126,31 +2126,31 @@ class Database: inserts.append( (hands_id, player_ids[i], start_cashes[i], positions[i], tourneyTypeId, card1, card2, card3, card4, startCards, winnings[i], rakes[i], tourneys_players_ids[i], seatNos[i], hudCache['totalProfit'][i], - hudCache['street0VPI'][i], hudCache['street0Aggr'][i], + hudCache['street0VPI'][i], hudCache['street0Aggr'][i], hudCache['street0_3BChance'][i], hudCache['street0_3BDone'][i], - hudCache['street1Seen'][i], hudCache['street2Seen'][i], hudCache['street3Seen'][i], + hudCache['street1Seen'][i], hudCache['street2Seen'][i], hudCache['street3Seen'][i], hudCache['street4Seen'][i], hudCache['sawShowdown'][i], hudCache['street1Aggr'][i], hudCache['street2Aggr'][i], hudCache['street3Aggr'][i], hudCache['street4Aggr'][i], - hudCache['otherRaisedStreet1'][i], hudCache['otherRaisedStreet2'][i], + hudCache['otherRaisedStreet1'][i], hudCache['otherRaisedStreet2'][i], hudCache['otherRaisedStreet3'][i], hudCache['otherRaisedStreet4'][i], - hudCache['foldToOtherRaisedStreet1'][i], hudCache['foldToOtherRaisedStreet2'][i], + hudCache['foldToOtherRaisedStreet1'][i], hudCache['foldToOtherRaisedStreet2'][i], hudCache['foldToOtherRaisedStreet3'][i], hudCache['foldToOtherRaisedStreet4'][i], hudCache['wonWhenSeenStreet1'][i], hudCache['wonAtSD'][i], - hudCache['stealAttemptChance'][i], hudCache['stealAttempted'][i], hudCache['foldBbToStealChance'][i], + hudCache['stealAttemptChance'][i], hudCache['stealAttempted'][i], hudCache['foldBbToStealChance'][i], hudCache['foldedBbToSteal'][i], hudCache['foldSbToStealChance'][i], hudCache['foldedSbToSteal'][i], hudCache['street1CBChance'][i], hudCache['street1CBDone'][i], hudCache['street2CBChance'][i], hudCache['street2CBDone'][i], hudCache['street3CBChance'][i], hudCache['street3CBDone'][i], hudCache['street4CBChance'][i], hudCache['street4CBDone'][i], - hudCache['foldToStreet1CBChance'][i], hudCache['foldToStreet1CBDone'][i], + hudCache['foldToStreet1CBChance'][i], hudCache['foldToStreet1CBDone'][i], hudCache['foldToStreet2CBChance'][i], hudCache['foldToStreet2CBDone'][i], - hudCache['foldToStreet3CBChance'][i], hudCache['foldToStreet3CBDone'][i], + hudCache['foldToStreet3CBChance'][i], hudCache['foldToStreet3CBDone'][i], hudCache['foldToStreet4CBChance'][i], hudCache['foldToStreet4CBDone'][i], - hudCache['street1CheckCallRaiseChance'][i], hudCache['street1CheckCallRaiseDone'][i], + hudCache['street1CheckCallRaiseChance'][i], hudCache['street1CheckCallRaiseDone'][i], hudCache['street2CheckCallRaiseChance'][i], hudCache['street2CheckCallRaiseDone'][i], - hudCache['street3CheckCallRaiseChance'][i], hudCache['street3CheckCallRaiseDone'][i], + hudCache['street3CheckCallRaiseChance'][i], hudCache['street3CheckCallRaiseDone'][i], hudCache['street4CheckCallRaiseChance'][i], hudCache['street4CheckCallRaiseDone'][i], - hudCache['street0Calls'][i], hudCache['street1Calls'][i], hudCache['street2Calls'][i], + hudCache['street0Calls'][i], hudCache['street1Calls'][i], hudCache['street2Calls'][i], hudCache['street3Calls'][i], hudCache['street4Calls'][i], - hudCache['street0Bets'][i], hudCache['street1Bets'][i], hudCache['street2Bets'][i], + hudCache['street0Bets'][i], hudCache['street1Bets'][i], hudCache['street2Bets'][i], hudCache['street3Bets'][i], hudCache['street4Bets'][i] ) ) @@ -2172,13 +2172,13 @@ class Database: foldToStreet3CBChance, foldToStreet3CBDone, foldToStreet4CBChance, foldToStreet4CBDone, street1CheckCallRaiseChance, street1CheckCallRaiseDone, street2CheckCallRaiseChance, street2CheckCallRaiseDone, street3CheckCallRaiseChance, street3CheckCallRaiseDone, street4CheckCallRaiseChance, street4CheckCallRaiseDone, - street0Calls, street1Calls, street2Calls, street3Calls, street4Calls, + street0Calls, street1Calls, street2Calls, street3Calls, street4Calls, street0Bets, street1Bets, street2Bets, street3Bets, street4Bets ) - VALUES + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, - %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, + %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""".replace('%s', self.sql.query['placeholder']) ,inserts ) @@ -2189,10 +2189,10 @@ class Database: err = traceback.extract_tb(sys.exc_info()[2])[-1] print "***Error storing hand: "+err[2]+"("+str(err[1])+"): "+str(sys.exc_info()[1]) raise FpdbError( "store_hands_players_holdem_omaha_tourney error: " + str(sys.exc_value) ) - + return result #end def store_hands_players_holdem_omaha_tourney - + def store_hands_players_stud_tourney(self, backend, hands_id, player_ids, start_cashes, antes, card_values, card_suits, winnings, rakes, seatNos, tourneys_players_ids, tourneyTypeId): #stores hands_players for tourney stud/razz hands @@ -2219,10 +2219,10 @@ class Database: result.append( self.get_last_insert_id(c) ) except: raise FpdbError( "store_hands_players_stud_tourney error: " + str(sys.exc_value) ) - + return result #end def store_hands_players_stud_tourney - + def storeHudCache(self, backend, base, category, gametypeId, hand_start_time, playerIds, hudImportData): """Update cached statistics. If update fails because no record exists, do an insert. Can't use array updates here (not easily anyway) because we need to insert any rows @@ -2236,11 +2236,11 @@ class Database: else: # hard-code styleKey as 'A000000' (all-time cache, no key) for now styleKey = 'A000000' - + #print "storeHudCache, len(playerIds)=", len(playerIds), " len(vpip)=" \ #, len(hudImportData['street0VPI']), " len(totprof)=", len(hudImportData['totalProfit']) for player in xrange(len(playerIds)): - + # Set up a clean row row=[] row.append(0)#blank for id @@ -2249,7 +2249,7 @@ class Database: row.append(len(playerIds))#seats for i in xrange(len(hudImportData)+2): row.append(0) - + if base=="hold": row[4]=hudImportData['position'][player] else: @@ -2285,7 +2285,7 @@ class Database: if hudImportData['foldedBbToSteal'][player]: row[33]+=1 if hudImportData['foldSbToStealChance'][player]: row[34]+=1 if hudImportData['foldedSbToSteal'][player]: row[35]+=1 - + if hudImportData['street1CBChance'][player]: row[36]+=1 if hudImportData['street1CBDone'][player]: row[37]+=1 if hudImportData['street2CBChance'][player]: row[38]+=1 @@ -2294,7 +2294,7 @@ class Database: if hudImportData['street3CBDone'][player]: row[41]+=1 if hudImportData['street4CBChance'][player]: row[42]+=1 if hudImportData['street4CBDone'][player]: row[43]+=1 - + if hudImportData['foldToStreet1CBChance'][player]: row[44]+=1 if hudImportData['foldToStreet1CBDone'][player]: row[45]+=1 if hudImportData['foldToStreet2CBChance'][player]: row[46]+=1 @@ -2303,12 +2303,12 @@ class Database: if hudImportData['foldToStreet3CBDone'][player]: row[49]+=1 if hudImportData['foldToStreet4CBChance'][player]: row[50]+=1 if hudImportData['foldToStreet4CBDone'][player]: row[51]+=1 - + #print "player=", player #print "len(totalProfit)=", len(hudImportData['totalProfit']) if hudImportData['totalProfit'][player]: row[52]+=hudImportData['totalProfit'][player] - + if hudImportData['street1CheckCallRaiseChance'][player]: row[53]+=1 if hudImportData['street1CheckCallRaiseDone'][player]: row[54]+=1 if hudImportData['street2CheckCallRaiseChance'][player]: row[55]+=1 @@ -2317,7 +2317,7 @@ class Database: if hudImportData['street3CheckCallRaiseDone'][player]: row[58]+=1 if hudImportData['street4CheckCallRaiseChance'][player]: row[59]+=1 if hudImportData['street4CheckCallRaiseDone'][player]: row[60]+=1 - + # Try to do the update first: cursor = self.get_cursor() num = cursor.execute("""UPDATE HudCache @@ -2348,10 +2348,10 @@ class Database: street2CheckCallRaiseDone=street2CheckCallRaiseDone+%s, street3CheckCallRaiseChance=street3CheckCallRaiseChance+%s, street3CheckCallRaiseDone=street3CheckCallRaiseDone+%s, street4CheckCallRaiseChance=street4CheckCallRaiseChance+%s, street4CheckCallRaiseDone=street4CheckCallRaiseDone+%s - WHERE gametypeId+0=%s - AND playerId=%s - AND activeSeats=%s - AND position=%s + WHERE gametypeId+0=%s + AND playerId=%s + AND activeSeats=%s + AND position=%s AND tourneyTypeId+0=%s AND styleKey=%s """.replace('%s', self.sql.query['placeholder']) @@ -2371,8 +2371,8 @@ class Database: #print "storehud2, upd num =", num.rowcount # num is a cursor in sqlite if ( (backend == self.PGSQL and cursor.statusmessage != "UPDATE 1") - or (backend == self.MYSQL_INNODB and num == 0) - or (backend == self.SQLITE and num.rowcount == 0) + or (backend == self.MYSQL_INNODB and num == 0) + or (backend == self.SQLITE and num.rowcount == 0) ): #print "playerid before insert:",row[2]," num = ", num num = cursor.execute("""INSERT INTO HudCache @@ -2416,9 +2416,9 @@ class Database: except: raise FpdbError( "storeHudCache error: " + str(sys.exc_value) ) - + #end def storeHudCache - + def store_tourneys(self, tourneyTypeId, siteTourneyNo, entries, prizepool, startTime): ret = -1 try: @@ -2471,7 +2471,7 @@ class Database: cursor.execute("""INSERT INTO TourneysPlayers (tourneyId, playerId, payinAmount, rank, winnings) VALUES (%s, %s, %s, %s, %s)""".replace('%s', self.sql.query['placeholder']), (tourney_id, player_ids[i], payin_amounts[i], ranks[i], winnings[i])) - + tmp = self.get_last_insert_id(cursor) result.append(tmp) #print "created new tourneys_players.id:", tmp @@ -2527,7 +2527,7 @@ class Database: sendFinal = True else: self.store_the_hand(h) - # optional commit, could be every hand / every N hands / every time a + # optional commit, could be every hand / every N hands / every time a # commit message received?? mark flag to indicate if commits outstanding if commitEachHand: self.commit() @@ -2581,7 +2581,7 @@ class Database: ) result=cursor.fetchone() - expectedValues = { 1 : "buyin", 2 : "fee", 4 : "isKO", 5 : "isRebuy", 6 : "speed", + expectedValues = { 1 : "buyin", 2 : "fee", 4 : "isKO", 5 : "isRebuy", 6 : "speed", 7 : "isHU", 8 : "isShootout", 9 : "isMatrix" } typeIdMatch = True @@ -2597,17 +2597,17 @@ class Database: except: # Tourney not found : a TourneyTypeId has to be found or created for that specific tourney typeIdMatch = False - + if typeIdMatch == False : # Check for an existing TTypeId that matches tourney info (buyin/fee, knockout, rebuy, speed, matrix, shootout) # if not found create it logging.debug("Searching for a TourneyTypeId matching TourneyType data") - cursor.execute (self.sql.query['getTourneyTypeId'].replace('%s', self.sql.query['placeholder']), + cursor.execute (self.sql.query['getTourneyTypeId'].replace('%s', self.sql.query['placeholder']), (tourney.siteId, tourney.buyin, tourney.fee, tourney.isKO, tourney.isRebuy, tourney.speed, tourney.isHU, tourney.isShootout, tourney.isMatrix) ) result=cursor.fetchone() - + try: len(result) typeId = result[0] @@ -2623,7 +2623,7 @@ class Database: return typeId #end def tRecogniseTourneyType - + def tRecognizeTourney(self, tourney, dbTourneyTypeId): logging.debug("Database.tRecognizeTourney") tourneyID = 1 @@ -2635,8 +2635,8 @@ class Database: ) result=cursor.fetchone() - expectedValuesDecimal = { 2 : "entries", 3 : "prizepool", 6 : "buyInChips", 9 : "rebuyChips", - 10 : "addOnChips", 11 : "rebuyAmount", 12 : "addOnAmount", 13 : "totalRebuys", + expectedValuesDecimal = { 2 : "entries", 3 : "prizepool", 6 : "buyInChips", 9 : "rebuyChips", + 10 : "addOnChips", 11 : "rebuyAmount", 12 : "addOnAmount", 13 : "totalRebuys", 14 : "totalAddOns", 15 : "koBounty" } expectedValues = { 7 : "tourneyName", 16 : "tourneyComment" } @@ -2671,7 +2671,7 @@ class Database: #break # TO DO : Deal with matrix summary mutliple parsings - + except: # Tourney not found : create logging.debug("Tourney is not found : create") @@ -2710,10 +2710,10 @@ class Database: return tourneyID #end def tRecognizeTourney - + def tStoreTourneyPlayers(self, tourney, dbTourneyId): logging.debug("Database.tStoreTourneyPlayers") - # First, get playerids for the players and specifically the one for hero : + # First, get playerids for the players and specifically the one for hero : playersIds = self.recognisePlayerIDs(tourney.players, tourney.siteId) # hero may be None for matrix tourneys summaries # hero = [ tourney.hero ] @@ -2723,22 +2723,22 @@ class Database: tourneyPlayersIds=[] try: cursor = self.get_cursor() - + for i in xrange(len(playersIds)): cursor.execute(self.sql.query['getTourneysPlayers'].replace('%s', self.sql.query['placeholder']) ,(dbTourneyId, playersIds[i])) result=cursor.fetchone() #print "tried SELECTing tourneys_players.id:",tmp - + try: len(result) # checking data logging.debug("TourneysPlayers found : checking data") - expectedValuesDecimal = { 1 : "payinAmounts", 2 : "finishPositions", 3 : "winnings", 4 : "countRebuys", + expectedValuesDecimal = { 1 : "payinAmounts", 2 : "finishPositions", 3 : "winnings", 4 : "countRebuys", 5 : "countAddOns", 6 : "countKO" } - + tourneyPlayersIds.append(result[0]); - + tourneysPlayersDataMatch = True for evD in expectedValuesDecimal : if ( Decimal(getattr( tourney, expectedValuesDecimal.get(evD))[tourney.players[i]] ) <> result[evD] ): @@ -2765,10 +2765,10 @@ class Database: None, None) ) tourneyPlayersIds.append(self.get_last_insert_id(cursor)) - + except: raise fpdb_simple.FpdbError( "tStoreTourneyPlayers error: " + str(sys.exc_value) ) - + return tourneyPlayersIds #end def tStoreTourneyPlayers @@ -2803,7 +2803,7 @@ class Database: # Class used to hold all the data needed to write a hand to the db -# mainParser() in fpdb_parse_logic.py creates one of these and then passes it to +# mainParser() in fpdb_parse_logic.py creates one of these and then passes it to # self.insert_queue_hands() class HandToWrite: @@ -2860,7 +2860,7 @@ class HandToWrite: , positions, antes, cardValues, cardSuits, boardValues, boardSuits , winnings, rakes, actionTypes, allIns, actionAmounts , actionNos, hudImportData, maxSeats, tableName, seatNos): - + try: self.config = config self.settings = settings @@ -2906,7 +2906,7 @@ class HandToWrite: def get_finished(self): return( self.finished ) # end def get_finished - + def get_siteHandNo(self): return( self.siteHandNo ) # end def get_siteHandNo @@ -2923,18 +2923,18 @@ if __name__=="__main__": # db_connection.recreate_tables() db_connection.dropAllIndexes() db_connection.createAllIndexes() - + h = db_connection.get_last_hand() print "last hand = ", h - + hero = db_connection.get_player_id(c, 'PokerStars', 'nutOmatic') if hero: print "nutOmatic is id_player = %d" % hero - + stat_dict = db_connection.get_stats_from_hand(h, "ring") for p in stat_dict.keys(): print p, " ", stat_dict[p] - + print "cards =", db_connection.get_cards(u'1') db_connection.close_connection diff --git a/pyfpdb/fpdb.py b/pyfpdb/fpdb.py index b960da05..d363b10f 100755 --- a/pyfpdb/fpdb.py +++ b/pyfpdb/fpdb.py @@ -557,7 +557,7 @@ class fpdb: self.warning_box("MySQL Server reports: Access denied. Are your permissions set correctly?") exit() except Exceptions.FpdbMySQLNoDatabase: - msg = "MySQL client reports: 2002 error. Unable to connect - Please check that the MySQL service has been started" + msg = "MySQL client reports: 2002 or 2003 error. Unable to connect - Please check that the MySQL service has been started" self.warning_box(msg) exit diff --git a/pyfpdb/fpdb_db.py b/pyfpdb/fpdb_db.py index 8a0ec54e..405a142c 100644 --- a/pyfpdb/fpdb_db.py +++ b/pyfpdb/fpdb_db.py @@ -106,7 +106,7 @@ class fpdb_db: except MySQLdb.Error, ex: if ex.args[0] == 1045: raise FpdbMySQLAccessDenied(ex.args[0], ex.args[1]) - elif ex.args[0] == 2002: + elif ex.args[0] == 2002 or ex.args[0] == 2003: # 2002 is no unix socket, 2003 is no tcp socket raise FpdbMySQLNoDatabase(ex.args[0], ex.args[1]) else: print "*** WARNING UNKNOWN MYSQL ERROR", ex From 2120257aeed648cc588cd2cd76e12837dc50c032 Mon Sep 17 00:00:00 2001 From: Eric Blade Date: Thu, 3 Dec 2009 07:21:24 -0500 Subject: [PATCH 05/10] whitespace.. sorry guys. --- ...0.05-0.10-200909.All.in.river.splitpot.txt | 108 +++++++++--------- 1 file changed, 54 insertions(+), 54 deletions(-) diff --git a/pyfpdb/regression-test-files/cash/Betfair/Flop/PLO-6max-USD-0.05-0.10-200909.All.in.river.splitpot.txt b/pyfpdb/regression-test-files/cash/Betfair/Flop/PLO-6max-USD-0.05-0.10-200909.All.in.river.splitpot.txt index f1fc48c0..c4685742 100644 --- a/pyfpdb/regression-test-files/cash/Betfair/Flop/PLO-6max-USD-0.05-0.10-200909.All.in.river.splitpot.txt +++ b/pyfpdb/regression-test-files/cash/Betfair/Flop/PLO-6max-USD-0.05-0.10-200909.All.in.river.splitpot.txt @@ -1,55 +1,55 @@ -***** Betfair Poker Hand History for Game 100000000 ***** -PL $0.05/$0.10 Omaha - Sunday, October 18, 20:00:00 GMT 2009 -Table Death 1 6-max (Real Money) -Seat 2 is the button -Total number of active players : 6 -Seat 1: Player6 ( $1 ) -Seat 2: Player3 ( $9.38 ) -Seat 3: Player2 ( $2.82 ) -Seat 4: Player4 ( $4.13 ) -Seat 5: Player5 ( $28.77 ) -Seat 6: Player1 ( $6.46 ) -Player2 posts small blind [$0.05] -Player4 posts big blind [$0.10] -Player6 posts big blind [$0.10] -** Dealing down cards ** -Dealt to Player6 [ 7c, 6c, 5h, Jh ] -Player5 folds -Player1 calls [$0.10] -Player6 checks -Player3 calls [$0.10] -Player2 raises to [$0.30] -Player4 calls [$0.20] -Player1 calls [$0.20] -Player6 goes all-in -Player6 raises to [$1] -Player3 calls [$0.90] -Player2 calls [$0.70] -Player4 calls [$0.70] -Player1 calls [$0.70] -** Dealing Flop ** [ 4d, 5d, 6d ] -Player2 checks -Player4 checks -Player1 checks -Player3 checks -** Dealing Turn ** [ 3s ] -Player2 checks -Player4 bets [$0.10] -Player1 calls [$0.10] -Player3 folds -Player2 folds -** Dealing River ** [ 4c ] -Player4 goes all-in -Player4 bets [$3.03] -Player1 calls [$3.03] -** Showdown ** -Player6 shows [ 7c, 6c, 5h, Jh ] a straight, Seven to Three -Player4 shows [ 7d, 8c, 3d, 6h ] a straight flush, Seven to Three -Player1 shows [ 3h, 4h, Td, 4s ] four of a kind, Fours -** Hand Conclusion ** -Player4 wins $6.26 from side pot #1 with a straight flush, Seven to Three -Player4 wins $4.44 from main pot with a straight flush, Seven to Three -************ Game 100000000 ends ************ - - +***** Betfair Poker Hand History for Game 100000000 ***** +PL $0.05/$0.10 Omaha - Sunday, October 18, 20:00:00 GMT 2009 +Table Death 1 6-max (Real Money) +Seat 2 is the button +Total number of active players : 6 +Seat 1: Player6 ( $1 ) +Seat 2: Player3 ( $9.38 ) +Seat 3: Player2 ( $2.82 ) +Seat 4: Player4 ( $4.13 ) +Seat 5: Player5 ( $28.77 ) +Seat 6: Player1 ( $6.46 ) +Player2 posts small blind [$0.05] +Player4 posts big blind [$0.10] +Player6 posts big blind [$0.10] +** Dealing down cards ** +Dealt to Player6 [ 7c, 6c, 5h, Jh ] +Player5 folds +Player1 calls [$0.10] +Player6 checks +Player3 calls [$0.10] +Player2 raises to [$0.30] +Player4 calls [$0.20] +Player1 calls [$0.20] +Player6 goes all-in +Player6 raises to [$1] +Player3 calls [$0.90] +Player2 calls [$0.70] +Player4 calls [$0.70] +Player1 calls [$0.70] +** Dealing Flop ** [ 4d, 5d, 6d ] +Player2 checks +Player4 checks +Player1 checks +Player3 checks +** Dealing Turn ** [ 3s ] +Player2 checks +Player4 bets [$0.10] +Player1 calls [$0.10] +Player3 folds +Player2 folds +** Dealing River ** [ 4c ] +Player4 goes all-in +Player4 bets [$3.03] +Player1 calls [$3.03] +** Showdown ** +Player6 shows [ 7c, 6c, 5h, Jh ] a straight, Seven to Three +Player4 shows [ 7d, 8c, 3d, 6h ] a straight flush, Seven to Three +Player1 shows [ 3h, 4h, Td, 4s ] four of a kind, Fours +** Hand Conclusion ** +Player4 wins $6.26 from side pot #1 with a straight flush, Seven to Three +Player4 wins $4.44 from main pot with a straight flush, Seven to Three +************ Game 100000000 ends ************ + + From 81adfff93b6b9831dd0a9f0bd24725435f7d1580 Mon Sep 17 00:00:00 2001 From: Eric Blade Date: Thu, 3 Dec 2009 07:22:33 -0500 Subject: [PATCH 06/10] Add some basic error handling at the very beginning of startup, to deal with missing imports and such, update about box --- pyfpdb/fpdb.py | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/pyfpdb/fpdb.py b/pyfpdb/fpdb.py index 47d3bc55..f6ad7e3f 100755 --- a/pyfpdb/fpdb.py +++ b/pyfpdb/fpdb.py @@ -37,14 +37,20 @@ if os.name == 'nt' and sys.version[0:3] not in ('2.5', '2.6') and '-r' not in sy os.execvpe('python.exe', ('python.exe', 'fpdb.py', '-r'), os.environ) # first arg is ignored (name of program being run) else: print "\npython 2.5 not found, please install python 2.5 or 2.6 for fpdb\n" - exit + raw_input("Press ENTER to continue.") + exit() else: pass #print "debug - not changing path" if os.name == 'nt': - import win32api - import win32con + try: + import win32api + import win32con + except ImportError: + print "We appear to be running in Windows, but the Windows Python Extensions are not loading. Please install the PYWIN32 package from http://sourceforge.net/projects/pywin32/" + raw_input("Press ENTER to continue.") + exit() print "Python " + sys.version[0:3] + '...\n' @@ -62,9 +68,14 @@ if not options.errorsToConsole: import logging -import pygtk -pygtk.require('2.0') -import gtk +try: + import pygtk + pygtk.require('2.0') + import gtk +except: + print "Unable to load PYGTK modules required for GUI. Please install PyCairo, PyGObject, and PyGTK from www.pygtk.org." + raw_input("Press ENTER to continue.") + exit() import interlocks @@ -196,14 +207,14 @@ class fpdb: def dia_about(self, widget, data=None): #self.warning_box("About FPDB:\n\nFPDB was originally created by a guy named Steffen, sometime in 2008, \nand is mostly worked on these days by people named Eratosthenes, s0rrow, _mt, EricBlade, sqlcoder, and other strange people.\n\n", "ABOUT FPDB") dia = gtk.AboutDialog() - dia.set_name("FPDB") + dia.set_name("Free Poker Database (FPDB)") dia.set_version(VERSION) - dia.set_copyright("2008-2009, Steffen, Eratosthenes, s0rrow, EricBlade, _mt, sqlcoder, and others") + dia.set_copyright("2008-2010, Steffen, Eratosthenes, s0rrow, EricBlade, _mt, sqlcoder, Bostik, and others") dia.set_comments("GTK AboutDialog comments here") dia.set_license("GPL v3") dia.set_website("http://fpdb.sourceforge.net/") - dia.set_authors("Steffen, Eratosthenes, s0rrow, EricBlade, _mt, and others") - dia.set_program_name("FPDB") + dia.set_authors("Steffen, Eratosthenes, s0rrow, EricBlade, _mt, sqlcoder, Bostik, and others") + dia.set_program_name("Free Poker Database (FPDB)") dia.run() dia.destroy() From f05b521d6f8d5fb8803382f5a8fbdae9f94db79a Mon Sep 17 00:00:00 2001 From: Eric Blade Date: Thu, 3 Dec 2009 07:24:12 -0500 Subject: [PATCH 07/10] comment out some prints, apparently mysqlcoder and my editors do not agree well with each other on spacing. --- pyfpdb/Hud.py | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/pyfpdb/Hud.py b/pyfpdb/Hud.py index c9420a8a..b61c17aa 100644 --- a/pyfpdb/Hud.py +++ b/pyfpdb/Hud.py @@ -173,26 +173,26 @@ class Hud: item = gtk.CheckMenuItem(' All Levels') self.aggMenu.append(item) item.connect("activate", self.set_aggregation, ('P',10000)) - setattr(self, 'h_aggBBmultItem10000', item) - # + setattr(self, 'h_aggBBmultItem10000', item) + # item = gtk.MenuItem('For #Seats:') self.aggMenu.append(item) - # + # item = gtk.CheckMenuItem(' Any Number') self.aggMenu.append(item) item.connect("activate", self.set_seats_style, ('P','A')) setattr(self, 'h_seatsStyleOptionA', item) - # + # item = gtk.CheckMenuItem(' Custom') self.aggMenu.append(item) item.connect("activate", self.set_seats_style, ('P','C')) - setattr(self, 'h_seatsStyleOptionC', item) - # + setattr(self, 'h_seatsStyleOptionC', item) + # item = gtk.CheckMenuItem(' Exact') self.aggMenu.append(item) item.connect("activate", self.set_seats_style, ('P','E')) - setattr(self, 'h_seatsStyleOptionE', item) - # + setattr(self, 'h_seatsStyleOptionE', item) + # item = gtk.MenuItem('Since:') self.aggMenu.append(item) # @@ -242,26 +242,26 @@ class Hud: item = gtk.CheckMenuItem(' All Levels') self.aggMenu.append(item) item.connect("activate", self.set_aggregation, ('O',10000)) - setattr(self, 'aggBBmultItem10000', item) - # + setattr(self, 'aggBBmultItem10000', item) + # item = gtk.MenuItem('For #Seats:') self.aggMenu.append(item) - # + # item = gtk.CheckMenuItem(' Any Number') self.aggMenu.append(item) item.connect("activate", self.set_seats_style, ('O','A')) setattr(self, 'seatsStyleOptionA', item) - # + # item = gtk.CheckMenuItem(' Custom') self.aggMenu.append(item) item.connect("activate", self.set_seats_style, ('O','C')) - setattr(self, 'seatsStyleOptionC', item) - # + setattr(self, 'seatsStyleOptionC', item) + # item = gtk.CheckMenuItem(' Exact') self.aggMenu.append(item) item.connect("activate", self.set_seats_style, ('O','E')) - setattr(self, 'seatsStyleOptionE', item) - # + setattr(self, 'seatsStyleOptionE', item) + # item = gtk.MenuItem('Since:') self.aggMenu.append(item) # @@ -358,7 +358,7 @@ class Hud: def change_max_seats(self, widget): if self.max != widget.ms: - print 'change_max_seats', widget.ms + #print 'change_max_seats', widget.ms self.max = widget.ms try: self.kill() @@ -402,7 +402,7 @@ class Hud: else: param = 'seats_style' prefix = '' - + if style == 'A' and getattr(self, prefix+'seatsStyleOptionA').get_active(): self.hud_params[param] = 'A' getattr(self, prefix+'seatsStyleOptionC').set_active(False) @@ -678,7 +678,7 @@ class Stat_Window: return True def kill_popup(self, popup): - print "remove popup", popup + #print "remove popup", popup self.popups.remove(popup) popup.window.destroy() From 3248cb60f21a340ff35414bae9eee6129ae47501 Mon Sep 17 00:00:00 2001 From: Eric Blade Date: Thu, 3 Dec 2009 12:35:00 -0500 Subject: [PATCH 08/10] added checks to see if player has folded when processing wether they've seen streets/showdown (corrects problem of player calling someone's short all in and it not counting as having seen showdown) --- pyfpdb/fpdb_simple.py | 378 +++++++++++++++++++++--------------------- 1 file changed, 190 insertions(+), 188 deletions(-) diff --git a/pyfpdb/fpdb_simple.py b/pyfpdb/fpdb_simple.py index aaf74772..85e60eeb 100644 --- a/pyfpdb/fpdb_simple.py +++ b/pyfpdb/fpdb_simple.py @@ -1,5 +1,5 @@ #!/usr/bin/python - + #Copyright 2008 Steffen Jobbagy-Felso #This program is free software: you can redistribute it and/or modify #it under the terms of the GNU Affero General Public License as published by @@ -14,13 +14,13 @@ #along with this program. If not, see . #In the "official" distribution you can find the license in #agpl-3.0.txt in the docs folder of the package. - + #This file contains simple functions for fpdb #Aiming to eventually remove this module, functions will move to, eg: #fpdb_db db create/re-create/management/etc #Hands or related files for saving hands to db, etc - + import datetime import time import re @@ -29,7 +29,7 @@ from Exceptions import * import locale import Card - + PS = 1 FTP = 2 @@ -52,7 +52,7 @@ def checkPositions(positions): raise FpdbError("invalid position '"+p+"' found in checkPositions") ### RHH modified to allow for "position 9" here (pos==9 is when you're a dead hand before the BB ### eric - position 8 could be valid - if only one blind is posted, but there's still 10 people, ie a sitout is present, and the small is dead... - + def classifyLines(hand, category, lineTypes, lineStreets): """ makes a list of classifications for each line for further processing manipulates passed arrays """ @@ -69,7 +69,7 @@ def classifyLines(hand, category, lineTypes, lineStreets): elif i == 0: lineTypes.append("header") elif line.startswith("Table '"): - lineTypes.append("table") + lineTypes.append("table") elif line.startswith("Seat ") and ( ("in chips" in line) or "($" in line): lineTypes.append("name") elif isActionLine(line): @@ -84,7 +84,7 @@ def classifyLines(hand, category, lineTypes, lineStreets): elif line.startswith("*** TURN *** ["): lineTypes.append("cards") currentStreet="turn" - elif line.startswith("*** RIVER *** ["): + elif line.startswith("*** RIVER *** ["): lineTypes.append("cards") currentStreet="river" elif line.startswith("*** 3"): @@ -115,7 +115,7 @@ def classifyLines(hand, category, lineTypes, lineStreets): else: raise FpdbError("unrecognised linetype in:"+hand[i]) lineStreets.append(currentStreet) - + def convert3B4B(category, limit_type, actionTypes, actionAmounts): """calculates the actual bet amounts in the given amount array and changes it accordingly.""" for i in xrange(len(actionTypes)): @@ -130,7 +130,7 @@ def convert3B4B(category, limit_type, actionTypes, actionAmounts): amount2 = actionAmounts[bets[betNo][0]][bets[betNo][1]][bets[betNo][2]] amount1 = actionAmounts[bets[betNo-1][0]][bets[betNo-1][1]][bets[betNo-1][2]] actionAmounts[bets[betNo][0]][bets[betNo][1]][bets[betNo][2]] = amount2 - amount1 - + def convertBlindBet(actionTypes, actionAmounts): """ Corrects the bet amount if the player had to pay blinds """ i = 0#setting street to pre-flop @@ -140,14 +140,14 @@ def convertBlindBet(actionTypes, actionAmounts): for k in xrange(len(actionTypes[i][j])): if actionTypes[i][j][k] == "blind": blinds.append((i,j,k)) - + if blinds and actionTypes[i][j][k] == "bet": bets.append((i,j,k)) if len(bets) == 1: blind_amount=actionAmounts[blinds[0][0]][blinds[0][1]][blinds[0][2]] bet_amount=actionAmounts[bets[0][0]][bets[0][1]][bets[0][2]] actionAmounts[bets[0][0]][bets[0][1]][bets[0][2]] = bet_amount - blind_amount - + #converts the strings in the given array to ints (changes the passed array, no returning). see table design for conversion details #todo: make this use convertCardValuesBoard def convertCardValues(arr): @@ -156,14 +156,14 @@ def convertCardValues(arr): # a 0-card is one in a stud game that we did not see or was not shown card_map = { 0: 0, "2": 2, "3" : 3, "4" : 4, "5" : 5, "6" : 6, "7" : 7, "8" : 8, "9" : 9, "T" : 10, "J" : 11, "Q" : 12, "K" : 13, "A" : 14} - + def convertCardValuesBoard(arr): """ converts the strings in the given array to ints (changes the passed array, no returning). see table design for conversion details """ for i in xrange(len(arr)): arr[i] = card_map[arr[i]] - + def createArrays(category, seats, card_values, card_suits, antes, winnings, rakes, action_types, allIns, action_amounts, actionNos, actionTypeByNo): @@ -174,10 +174,10 @@ def createArrays(category, seats, card_values, card_suits, antes, winnings, antes.append(0) winnings.append(0) rakes.append(0) - + streetCount = 4 if (category == "holdem" or category == "omahahi" or category == "omahahilo") else 5 - + for i in xrange(streetCount): #build the first dimension array, for streets action_types.append([]) allIns.append([]) @@ -199,13 +199,13 @@ def createArrays(category, seats, card_values, card_suits, antes, winnings, # else: # raise FpdbError("invalid category") #end def createArrays - + def fill_board_cards(board_values, board_suits): """ fill up the two board card arrays """ while len(board_values) < 5: board_values.append(0) board_suits.append("x") - + def fillCardArrays(player_count, base, category, card_values, card_suits): """fills up the two card arrays""" if category == "holdem": @@ -216,13 +216,13 @@ def fillCardArrays(player_count, base, category, card_values, card_suits): cardCount = 7 else: raise FpdbError("invalid category:", category) - + for i in xrange(player_count): while len(card_values[i]) < cardCount: card_values[i].append(0) card_suits[i].append("x") #end def fillCardArrays - + #filters out a player that folded before paying ante or blinds. This should be called #before calling the actual hand parser. manipulates hand, no return. def filterAnteBlindFold(hand): @@ -233,7 +233,7 @@ def filterAnteBlindFold(hand): for i, line in enumerate(hand): if line.startswith("*** 3") or line.startswith("*** HOLE"): pre3rd = hand[0:i] - + foldeeName = None for line in pre3rd: if line.endswith("folds") or line.endswith("is sitting out") or line.endswith(" stands up"): #found ante fold or timeout @@ -249,24 +249,24 @@ def filterAnteBlindFold(hand): pos1 = line.find(": ") + 2 pos2 = line.find(" (") foldeeName = line[pos1:pos2] - + if foldeeName is not None: #print "filterAnteBlindFold, foldeeName:",foldeeName for i, line in enumerate(hand): if foldeeName in line: hand[i] = None - + return [line for line in hand if line] def stripEOLspaces(str): return str.rstrip() - + def filterCrap(hand, isTourney): """ removes useless lines as well as trailing spaces """ #remove trailing spaces at end of line hand = [line.rstrip() for line in hand] - + #general variable position word filter/string filter for i in xrange(len(hand)): if hand[i].startswith("Board ["): @@ -347,10 +347,10 @@ def filterCrap(hand, isTourney): hand[i] = False # python docs say this is identical to filter(None, list) # which removes all false items from the passed list (hand) - hand = [line for line in hand if line] - + hand = [line for line in hand if line] + return hand - + def float2int(string): """ takes a poker float (including , for thousand seperator) and converts it to an int """ @@ -358,11 +358,11 @@ def float2int(string): pos = string.find(",") if pos != -1: #remove , the thousand seperator string = "%s%s" % (string[0:pos], string[pos+1:]) - + pos = string.find(".") if pos != -1: #remove decimal point string = "%s%s" % (string[0:pos], string[pos+1:]) - + result = int(string) if pos == -1: #no decimal point - was in full dollars - need to multiply with 100 result *= 100 @@ -372,7 +372,7 @@ ActionLines = ( "calls $", ": calls ", "brings in for", "completes it to", "posts small blind", "posts the small blind", "posts big blind", "posts the big blind", "posts small & big blinds", "posts $", "posts a dead", "bets $", ": bets ", " raises") - + def isActionLine(line): if line.endswith("folds"): return True @@ -383,44 +383,44 @@ def isActionLine(line): # searches for each member of ActionLines being in line, returns true # on first match .. neat func - return any(x for x in ActionLines if x in line) - + return any(x for x in ActionLines if x in line) + def isAlreadyInDB(db, gametypeID, siteHandNo): c = db.get_cursor() c.execute(db.sql.query['isAlreadyInDB'], (gametypeID, siteHandNo)) result = c.fetchall() if len(result) >= 1: raise DuplicateError ("dupl") - + def isRebuyOrAddon(topline): """isRebuyOrAddon not implemented yet""" return False - + #returns whether the passed topline indicates a tournament or not def isTourney(topline): return "Tournament" in topline - + WinLines = ( "wins the pot", "ties for the ", "wins side pot", "wins the low main pot", "wins the high main pot", "wins the low", "wins the high pot", "wins the high side pot", "wins the main pot", "wins the side pot", "collected" ) def isWinLine(line): """ returns boolean whether the passed line is a win line """ - return any(x for x in WinLines if x in line) - + return any(x for x in WinLines if x in line) + #returns the amount of cash/chips put into the put in the given action line def parseActionAmount(line, atype, isTourney): #if (line.endswith(" and is all-in")): # line=line[:-14] #elif (line.endswith(", and is all in")): # line=line[:-15] - - #ideally we should recognise this as an all-in if category is capXl + + #ideally we should recognise this as an all-in if category is capXl if line.endswith(", and is capped"): line=line[:-15] if line.endswith(" and is capped"): line=line[:-14] - + if atype == "fold" or atype == "check": amount = 0 elif atype == "unbet": @@ -443,12 +443,12 @@ def parseActionAmount(line, atype, isTourney): #print "pos:",pos #print "pos of 20:", line.find("20") amount = int(line[pos:]) - + if atype == "unbet": amount *= -1 return amount #end def parseActionAmount - + #doesnt return anything, simply changes the passed arrays action_types and # action_amounts. For stud this expects numeric streets (3-7), for # holdem/omaha it expects predeal, preflop, flop, turn or river @@ -461,25 +461,25 @@ def parseActionLine(base, isTourney, line, street, playerIDs, names, action_type street = 2 elif street == "river": street = 3 - + nextActionNo = 0 for player in xrange(len(actionNos[street])): for count in xrange(len(actionNos[street][player])): if actionNos[street][player][count]>=nextActionNo: nextActionNo=actionNos[street][player][count]+1 - + (line, allIn) = goesAllInOnThisLine(line) atype = parseActionType(line) playerno = recognisePlayerNo(line, names, atype) amount = parseActionAmount(line, atype, isTourney) - + action_types[street][playerno].append(atype) allIns[street][playerno].append(allIn) action_amounts[street][playerno].append(amount) actionNos[street][playerno].append(nextActionNo) tmp=(playerIDs[playerno], atype) actionTypeByNo[street].append(tmp) - + def goesAllInOnThisLine(line): """returns whether the player went all-in on this line and removes the all-in text from the line.""" isAllIn = False @@ -490,20 +490,20 @@ def goesAllInOnThisLine(line): line = line[:-15] isAllIn = True return (line, isAllIn) - + #returns the action type code (see table design) of the given action line -ActionTypes = { 'brings in for' :"blind", +ActionTypes = { 'brings in for' :"blind", ' posts $' :"blind", - ' posts a dead ' :"blind", - ' posts the small blind of $' :"blind", + ' posts a dead ' :"blind", + ' posts the small blind of $' :"blind", ': posts big blind ' :"blind", - ': posts small blind ' :"blind", - ' posts the big blind of $' :"blind", + ': posts small blind ' :"blind", + ' posts the big blind of $' :"blind", ': posts small & big blinds $' :"blind", ': posts small blind $' :"blind", - 'calls' :"call", - 'completes it to' :"bet", - ' bets' :"bet", + 'calls' :"call", + 'completes it to' :"bet", + ' bets' :"bet", ' raises' :"bet" } def parseActionType(line): @@ -516,9 +516,9 @@ def parseActionType(line): else: for x in ActionTypes: if x in line: - return ActionTypes[x] + return ActionTypes[x] raise FpdbError ("failed to recognise actiontype in parseActionLine in: "+line) - + #parses the ante out of the given line and checks which player paid it, updates antes accordingly. def parseAnteLine(line, isTourney, names, antes): for i, name in enumerate(names): @@ -534,19 +534,19 @@ def parseAnteLine(line, isTourney, names, antes): pos1 = line.rfind("ante") + 5 pos2 = line.find(" ", pos1) antes[i] += int(line[pos1:pos2]) - + #returns the buyin of a tourney in cents def parseBuyin(topline): pos1 = topline.find("$")+1 pos2 = topline.find("+") return float2int(topline[pos1:pos2]) - + #parses a card line and changes the passed arrays accordingly #todo: reorganise this messy method def parseCardLine(category, street, line, names, cardValues, cardSuits, boardValues, boardSuits): if line.startswith("Dealt to") or " shows [" in line or "mucked [" in line: playerNo = recognisePlayerNo(line, names, "card") #anything but unbet will be ok for that string - + pos = line.rfind("[")+1 if category == "holdem": for i in (pos, pos+3): @@ -554,7 +554,7 @@ def parseCardLine(category, street, line, names, cardValues, cardSuits, boardVal cardSuits[playerNo].append(line[i+1:i+2]) if len(cardValues[playerNo]) != 2: if (cardValues[playerNo][0] == cardValues[playerNo][2] and - cardSuits[playerNo][1] == cardSuits[playerNo][3]): + cardSuits[playerNo][1] == cardSuits[playerNo][3]): cardValues[playerNo]=cardValues[playerNo][0:2] cardSuits[playerNo]=cardSuits[playerNo][0:2] else: @@ -617,7 +617,7 @@ def parseCardLine(category, street, line, names, cardValues, cardSuits, boardVal #print boardValues else: raise FpdbError ("unrecognised line:"+line) - + def parseCashesAndSeatNos(lines): """parses the startCashes and seatNos of each player out of the given lines and returns them as a dictionary of two arrays""" cashes = [] @@ -625,21 +625,21 @@ def parseCashesAndSeatNos(lines): for i in xrange (len(lines)): pos2=lines[i].find(":") seatNos.append(int(lines[i][5:pos2])) - + pos1=lines[i].rfind("($")+2 if pos1==1: #for tourneys - it's 1 instead of -1 due to adding 2 above pos1=lines[i].rfind("(")+1 pos2=lines[i].find(" in chips") cashes.append(float2int(lines[i][pos1:pos2])) return {'startCashes':cashes, 'seatNos':seatNos} - + #returns the buyin of a tourney in cents def parseFee(topline): pos1=topline.find("$")+1 pos1=topline.find("$",pos1)+1 pos2=topline.find(" ", pos1) return float2int(topline[pos1:pos2]) - + #returns a datetime object with the starttime indicated in the given topline def parseHandStartTime(topline): #convert x:13:35 to 0x:13:35 @@ -650,7 +650,7 @@ def parseHandStartTime(topline): topline = "%s0%s" % (topline[0:pos+1], topline[pos+1:]) break counter += 1 - + isUTC=False if topline.find("UTC")!=-1: pos1 = topline.find("-")+2 @@ -669,12 +669,12 @@ def parseHandStartTime(topline): rexx = '(?P[0-9]{4})\/(?P[0-9]{2})\/(?P[0-9]{2})[\- ]+(?P
[0-9]+):(?P[0-9]+):(?P[0-9]+)' m = re.search(rexx,tmp) result = datetime.datetime(int(m.group('YEAR')), int(m.group('MON')), int(m.group('DAY')), int(m.group('HR')), int(m.group('MIN')), int(m.group('SEC'))) - + if not isUTC: #these use US ET result += datetime.timedelta(hours=5) - + return result - + #parses the names out of the given lines and returns them as an array def findName(line): pos1 = line.find(":") + 2 @@ -683,11 +683,11 @@ def findName(line): def parseNames(lines): return [findName(line) for line in lines] - + def parsePositions(hand, names): positions = [-1 for i in names] sb, bb = -1, -1 - + for line in hand: if sb == -1 and "small blind" in line and "dead small blind" not in line: sb = line @@ -703,7 +703,7 @@ def parsePositions(hand, names): sbExists = False if bb != -1: bb = recognisePlayerNo(bb, names, "bet") - + # print "sb = ", sb, "bb = ", bb if bb == sb: # if big and small are same, then don't duplicate the small sbExists = False @@ -716,7 +716,7 @@ def parsePositions(hand, names): #fill up rest of array arraypos = sb - 1 if sbExists else bb - 1 - + distFromBtn=0 while arraypos >= 0 and arraypos != bb: #print "parsePositions first while, arraypos:",arraypos,"positions:",positions @@ -732,7 +732,7 @@ def parsePositions(hand, names): i -= 1 ### RHH - Changed to set the null seats before BB to "9" i = sb - 1 if sbExists else bb - 1 - + while positions[i] < 0: positions[i]=9 i-=1 @@ -750,19 +750,19 @@ def parsePositions(hand, names): raise FpdbError ("failed to read positions") # print str(positions), "\n" return positions - + #simply parses the rake amount and returns it as an int def parseRake(line): pos = line.find("Rake")+6 rake = float2int(line[pos:]) return rake - + def parseSiteHandNo(topline): """returns the hand no assigned by the poker site""" pos1 = topline.find("#")+1 pos2 = topline.find(":") return topline[pos1:pos2] - + def parseTableLine(base, line): """returns a dictionary with maxSeats and tableName""" pos1=line.find('\'')+1 @@ -773,14 +773,14 @@ def parseTableLine(base, line): #print "seats:",line[pos3:pos4] return {'maxSeats':int(line[pos3:pos4]), 'tableName':line[pos1:pos2]} #end def parseTableLine - + #returns the hand no assigned by the poker site def parseTourneyNo(topline): pos1 = topline.find("Tournament #")+12 pos2 = topline.find(",", pos1) #print "parseTourneyNo pos1:",pos1," pos2:",pos2, " result:",topline[pos1:pos2] return topline[pos1:pos2] - + #parses a win/collect line. manipulates the passed array winnings, no explicit return def parseWinLine(line, names, winnings, isTourney): #print "parseWinLine: line:",line @@ -795,7 +795,7 @@ def parseWinLine(line, names, winnings, isTourney): pos1 = line.rfind("$") + 1 pos2 = line.find(" ", pos1) winnings[i] += float2int(line[pos1:pos2]) - + #returns the category (as per database) string for the given line def recogniseCategory(line): if "Razz" in line: @@ -814,12 +814,12 @@ def recogniseCategory(line): return "studhilo" else: raise FpdbError("failed to recognise category, line:"+line) - + #returns the int for the gametype_id for the given line def recogniseGametypeID(backend, db, cursor, topline, smallBlindLine, site_id, category, isTourney):#todo: this method is messy #if (topline.find("HORSE")!=-1): # raise FpdbError("recogniseGametypeID: HORSE is not yet supported.") - + #note: the below variable names small_bet and big_bet are misleading, in NL/PL they mean small/big blind if isTourney: type = "tour" @@ -835,27 +835,27 @@ def recogniseGametypeID(backend, db, cursor, topline, smallBlindLine, site_id, c pos1 = topline.find("$")+1 pos2 = topline.find("/$") small_bet = float2int(topline[pos1:pos2]) - + pos1 = pos2+2 if isTourney: pos1 -= 1 pos2 = topline.find(")") - + if pos2 <= pos1: pos2 = topline.find(")", pos1) - + if isTourney: big_bet = int(topline[pos1:pos2]) else: big_bet = float2int(topline[pos1:pos2]) - + if 'No Limit' in topline: limit_type = "nl" if 'Cap No' not in topline else "cn" elif 'Pot Limit' in topline: limit_type = "pl" if 'Cap Pot' not in topline else "cp" else: limit_type = "fl" - + #print "recogniseGametypeID small_bet/blind:",small_bet,"big bet/blind:", big_bet,"limit type:",limit_type if limit_type == "fl": cursor.execute(db.sql.query['getGametypeFL'], (site_id, type, category, @@ -870,7 +870,7 @@ def recogniseGametypeID(backend, db, cursor, topline, smallBlindLine, site_id, c #ret=result[0] #print "recgt1 ret=",ret #print "tried SELECTing gametypes.id, result:",result - + try: len(result) except TypeError: @@ -878,14 +878,14 @@ def recogniseGametypeID(backend, db, cursor, topline, smallBlindLine, site_id, c base="hold" else: base="stud" - + if category=="holdem" or category=="omahahi" or category=="studhi": hiLo='h' elif category=="razz": hiLo='l' else: hiLo='s' - + if (limit_type=="fl"): big_blind=small_bet if base=="hold": @@ -901,17 +901,17 @@ def recogniseGametypeID(backend, db, cursor, topline, smallBlindLine, site_id, c small_blind=0 result = db.insertGameTypes( (site_id, type, base, category, limit_type, hiLo ,small_blind, big_blind, small_bet, big_bet) ) - #cursor.execute ("SELECT id FROM Gametypes WHERE siteId=%s AND type=%s AND category=%s + #cursor.execute ("SELECT id FROM Gametypes WHERE siteId=%s AND type=%s AND category=%s #AND limitType=%s AND smallBet=%s AND bigBet=%s", (site_id, type, category, limit_type, small_bet, big_bet)) else: result = db.insertGameTypes( (site_id, type, base, category, limit_type, hiLo ,small_bet, big_bet, 0, 0) )#remember, for these bet means blind #cursor.execute ("SELECT id FROM Gametypes WHERE siteId=%s AND type=%s AND category=%s #AND limitType=%s AND smallBlind=%s AND bigBlind=%s", (site_id, type, category, limit_type, small_bet, big_bet)) - + return result[0] #end def recogniseGametypeID - + def recogniseTourneyTypeId(db, siteId, tourneySiteId, buyin, fee, knockout, rebuyOrAddon): ret = -1 cursor = db.get_cursor() @@ -920,32 +920,32 @@ def recogniseTourneyTypeId(db, siteId, tourneySiteId, buyin, fee, knockout, rebu #TODO: When the summary file will be dumped to BD, if the tourney is already in, Buy-In/Fee may need an update (e.g. creation of a new type and link to the Tourney) cursor.execute (db.sql.query['getTourneyTypeIdByTourneyNo'].replace('%s', db.sql.query['placeholder']), (tourneySiteId, siteId)) result = cursor.fetchone() - + try: len(result) ret = result[0] except: - cursor.execute( """SELECT id FROM TourneyTypes - WHERE siteId=%s AND buyin=%s AND fee=%s + cursor.execute( """SELECT id FROM TourneyTypes + WHERE siteId=%s AND buyin=%s AND fee=%s AND knockout=%s AND rebuyOrAddon=%s""".replace('%s', db.sql.query['placeholder']) , (siteId, buyin, fee, knockout, rebuyOrAddon) ) result = cursor.fetchone() #print "tried selecting tourneytypes.id, result:", result - + try: len(result) ret = result[0] except TypeError:#this means we need to create a new entry #print "insert new tourneytype record ..." try: - cursor.execute( """INSERT INTO TourneyTypes (siteId, buyin, fee, knockout, rebuyOrAddon) + cursor.execute( """INSERT INTO TourneyTypes (siteId, buyin, fee, knockout, rebuyOrAddon) VALUES (%s, %s, %s, %s, %s)""".replace('%s', db.sql.query['placeholder']) , (siteId, buyin, fee, knockout, rebuyOrAddon) ) ret = db.get_last_insert_id(cursor) except: #print "maybe tourneytype was created since select, try selecting again ..." - cursor.execute( """SELECT id FROM TourneyTypes - WHERE siteId=%s AND buyin=%s AND fee=%s + cursor.execute( """SELECT id FROM TourneyTypes + WHERE siteId=%s AND buyin=%s AND fee=%s AND knockout=%s AND rebuyOrAddon=%s""".replace('%s', db.sql.query['placeholder']) , (siteId, buyin, fee, knockout, rebuyOrAddon) ) result = cursor.fetchone() @@ -956,12 +956,12 @@ def recogniseTourneyTypeId(db, siteId, tourneySiteId, buyin, fee, knockout, rebu print "Failed to find or insert TourneyTypes record" ret = -1 # failed to find or insert record #print "tried selecting tourneytypes.id again, result:", result - + #print "recogniseTourneyTypeId: returning", ret return ret #end def recogniseTourneyTypeId - - + + #recognises the name in the given line and returns its array position in the given array def recognisePlayerNo(line, names, atype): #print "recogniseplayerno, names:",names @@ -981,7 +981,7 @@ def recognisePlayerNo(line, names, atype): tmp=line[9:] else: tmp=line[8:] - + if (tmp.startswith(encodedName)): return (i) else: @@ -990,8 +990,8 @@ def recognisePlayerNo(line, names, atype): #if we're here we mustve failed raise FpdbError ("failed to recognise player in: "+line+" atype:"+atype) #end def recognisePlayerNo - - + + #removes trailing \n from the given array def removeTrailingEOL(arr): for i in xrange(len(arr)): @@ -1001,7 +1001,7 @@ def removeTrailingEOL(arr): #print "arr[i] after removetrailingEOL:", arr[i] return arr #end def removeTrailingEOL - + #splits the rake according to the proportion of pot won. manipulates the second passed array. def splitRake(winnings, rakes, totalRake): winnercnt=0 @@ -1020,7 +1020,7 @@ def splitRake(winnings, rakes, totalRake): winPortion=winnings[i]/totalWin rakes[i]=totalRake*winPortion #end def splitRake - + def generateHudCacheData(player_ids, base, category, action_types, allIns, actionTypeByNo ,winnings, totalWinnings, positions, actionTypes, actionAmounts, antes): """calculates data for the HUD during import. IMPORTANT: if you change this method make @@ -1050,12 +1050,12 @@ sure to also change the following storage method and table_viewer.prepare_data i foldToOtherRaisedStreet3=[] foldToOtherRaisedStreet4=[] wonWhenSeenStreet1=[] - + wonAtSD=[] stealAttemptChance=[] stealAttempted=[] hudDataPositions=[] - + street0Calls=[] street1Calls=[] street2Calls=[] @@ -1071,7 +1071,7 @@ sure to also change the following storage method and table_viewer.prepare_data i #street2Raises=[] #street3Raises=[] #street4Raises=[] - + # Summary figures for hand table: result={} result['playersVpi']=0 @@ -1090,13 +1090,13 @@ sure to also change the following storage method and table_viewer.prepare_data i result['street3Pot']=0 result['street4Pot']=0 result['showdownPot']=0 - + firstPfRaiseByNo=-1 firstPfRaiserId=-1 firstPfRaiserNo=-1 firstPfCallByNo=-1 firstPfCallerId=-1 - + for i, action in enumerate(actionTypeByNo[0]): if action[1] == "bet": firstPfRaiseByNo = i @@ -1116,7 +1116,7 @@ sure to also change the following storage method and table_viewer.prepare_data i if firstPfRaiseByNo < firstPfCallByNo or firstPfCallByNo == -1: firstPlayId = firstPfRaiserId - + cutoffId=-1 buttonId=-1 sbId=-1 @@ -1131,9 +1131,9 @@ sure to also change the following storage method and table_viewer.prepare_data i sbId = player_ids[player] if pos == 'B': bbId = player_ids[player] - + someoneStole=False - + #run a loop for each player preparing the actual values that will be commited to SQL for player in xrange(len(player_ids)): #set default values @@ -1177,7 +1177,7 @@ sure to also change the following storage method and table_viewer.prepare_data i #myStreet2Raises=0 #myStreet3Raises=0 #myStreet4Raises=0 - + #calculate VPIP and PFR street=0 heroPfRaiseCount=0 @@ -1186,14 +1186,14 @@ sure to also change the following storage method and table_viewer.prepare_data i myStreet0Aggr = True if currentAction == "bet" or currentAction == "call": myStreet0VPI = True - + if myStreet0VPI: result['playersVpi'] += 1 myStreet0Calls = action_types[street][player].count('call') myStreet0Bets = action_types[street][player].count('bet') # street0Raises = action_types[street][player].count('raise') bet count includes raises for now result['street0Raises'] += myStreet0Bets - + #PF3BChance and PF3B pfFold=-1 pfRaise=-1 @@ -1208,7 +1208,7 @@ sure to also change the following storage method and table_viewer.prepare_data i myStreet0_3BChance = True if pfRaise > firstPfRaiseByNo: myStreet0_3BDone = True - + #steal calculations if base=="hold": if len(player_ids)>=3: # no point otherwise # was 5, use 3 to match pokertracker definition @@ -1235,30 +1235,32 @@ sure to also change the following storage method and table_viewer.prepare_data i myStealAttemptChance=True if positions[player]=='B': pass - + if myStealAttempted: someoneStole=True - - + + #calculate saw* values isAllIn = False if any(i for i in allIns[0][player]): isAllIn = True - if (len(action_types[1][player])>0 or isAllIn): + if isAllIn or len(action_types[1][player]) > 0: myStreet1Seen = True - + if any(i for i in allIns[1][player]): isAllIn = True - if (len(action_types[2][player])>0 or isAllIn): - myStreet2Seen = True - + if isAllIn or len(action_types[2][player]) > 0: + if all(actiontype != "fold" for actiontype in action_types[1][player]): + myStreet2Seen = True + if any(i for i in allIns[2][player]): isAllIn = True - if (len(action_types[3][player])>0 or isAllIn): - myStreet3Seen = True - + if isAllIn or len(action_types[3][player]) > 0: + if all(actiontype != "fold" for actiontype in action_types[2][player]): + myStreet3Seen = True + #print "base:", base - if base=="hold": + if base == "hold": mySawShowdown = True if any(actiontype == "fold" for actiontype in action_types[3][player]): mySawShowdown = False @@ -1266,10 +1268,10 @@ sure to also change the following storage method and table_viewer.prepare_data i #print "in else" if any(i for i in allIns[3][player]): isAllIn = True - if (len(action_types[4][player])>0 or isAllIn): + if isAllIn or len(action_types[4][player]) > 0: #print "in if" myStreet4Seen = True - + mySawShowdown = True if any(actiontype == "fold" for actiontype in action_types[4][player]): mySawShowdown = False @@ -1284,18 +1286,18 @@ sure to also change the following storage method and table_viewer.prepare_data i result['playersAtStreet4'] += 1 if mySawShowdown: result['playersAtShowdown'] += 1 - + #flop stuff street=1 if myStreet1Seen: if any(actiontype == "bet" for actiontype in action_types[street][player]): myStreet1Aggr = True - + myStreet1Calls = action_types[street][player].count('call') myStreet1Bets = action_types[street][player].count('bet') # street1Raises = action_types[street][player].count('raise') bet count includes raises for now result['street1Raises'] += myStreet1Bets - + for otherPlayer in xrange(len(player_ids)): if player==otherPlayer: pass @@ -1306,18 +1308,18 @@ sure to also change the following storage method and table_viewer.prepare_data i for countOtherFold in xrange(len(action_types[street][player])): if action_types[street][player][countOtherFold]=="fold": myFoldToOtherRaisedStreet1=True - + #turn stuff - copy of flop with different vars street=2 if myStreet2Seen: if any(actiontype == "bet" for actiontype in action_types[street][player]): myStreet2Aggr = True - + myStreet2Calls = action_types[street][player].count('call') myStreet2Bets = action_types[street][player].count('bet') # street2Raises = action_types[street][player].count('raise') bet count includes raises for now result['street2Raises'] += myStreet2Bets - + for otherPlayer in xrange(len(player_ids)): if player==otherPlayer: pass @@ -1328,18 +1330,18 @@ sure to also change the following storage method and table_viewer.prepare_data i for countOtherFold in xrange(len(action_types[street][player])): if action_types[street][player][countOtherFold]=="fold": myFoldToOtherRaisedStreet2=True - + #river stuff - copy of flop with different vars street=3 if myStreet3Seen: if any(actiontype == "bet" for actiontype in action_types[street][player]): myStreet3Aggr = True - + myStreet3Calls = action_types[street][player].count('call') myStreet3Bets = action_types[street][player].count('bet') # street3Raises = action_types[street][player].count('raise') bet count includes raises for now result['street3Raises'] += myStreet3Bets - + for otherPlayer in xrange(len(player_ids)): if player==otherPlayer: pass @@ -1350,18 +1352,18 @@ sure to also change the following storage method and table_viewer.prepare_data i for countOtherFold in xrange(len(action_types[street][player])): if action_types[street][player][countOtherFold]=="fold": myFoldToOtherRaisedStreet3=True - + #stud river stuff - copy of flop with different vars street=4 if myStreet4Seen: if any(actiontype == "bet" for actiontype in action_types[street][player]): myStreet4Aggr=True - + myStreet4Calls = action_types[street][player].count('call') myStreet4Bets = action_types[street][player].count('bet') # street4Raises = action_types[street][player].count('raise') bet count includes raises for now result['street4Raises'] += myStreet4Bets - + for otherPlayer in xrange(len(player_ids)): if player==otherPlayer: pass @@ -1372,13 +1374,13 @@ sure to also change the following storage method and table_viewer.prepare_data i for countOtherFold in xrange(len(action_types[street][player])): if action_types[street][player][countOtherFold]=="fold": myFoldToOtherRaisedStreet4=True - + if winnings[player] != 0: if myStreet1Seen: myWonWhenSeenStreet1 = winnings[player] / float(totalWinnings) if mySawShowdown: myWonAtSD=myWonWhenSeenStreet1 - + #add each value to the appropriate array street0VPI.append(myStreet0VPI) street0Aggr.append(myStreet0Aggr) @@ -1443,7 +1445,7 @@ sure to also change the following storage method and table_viewer.prepare_data i #street2Raises.append(myStreet2Raises) #street3Raises.append(myStreet3Raises) #street4Raises.append(myStreet4Raises) - + #add each array to the to-be-returned dictionary result['street0VPI']=street0VPI result['street0Aggr']=street0Aggr @@ -1454,7 +1456,7 @@ sure to also change the following storage method and table_viewer.prepare_data i result['street3Seen']=street3Seen result['street4Seen']=street4Seen result['sawShowdown']=sawShowdown - + result['street1Aggr']=street1Aggr result['otherRaisedStreet1']=otherRaisedStreet1 result['foldToOtherRaisedStreet1']=foldToOtherRaisedStreet1 @@ -1486,7 +1488,7 @@ sure to also change the following storage method and table_viewer.prepare_data i #result['street2Raises']=street2Raises #result['street3Raises']=street3Raises #result['street4Raises']=street4Raises - + #now the various steal values foldBbToStealChance=[] foldedBbToSteal=[] @@ -1497,7 +1499,7 @@ sure to also change the following storage method and table_viewer.prepare_data i myFoldedBbToSteal=False myFoldSbToStealChance=False myFoldedSbToSteal=False - + if base=="hold": if someoneStole and (positions[player]=='B' or positions[player]=='S') and firstPfRaiserId!=player_ids[player]: street=0 @@ -1510,8 +1512,8 @@ sure to also change the following storage method and table_viewer.prepare_data i myFoldSbToStealChance=True if action_types[street][player][count]=="fold": myFoldedSbToSteal=True - - + + foldBbToStealChance.append(myFoldBbToStealChance) foldedBbToSteal.append(myFoldedBbToSteal) foldSbToStealChance.append(myFoldSbToStealChance) @@ -1520,7 +1522,7 @@ sure to also change the following storage method and table_viewer.prepare_data i result['foldedBbToSteal']=foldedBbToSteal result['foldSbToStealChance']=foldSbToStealChance result['foldedSbToSteal']=foldedSbToSteal - + #now CB street1CBChance=[] street1CBDone=[] @@ -1528,18 +1530,18 @@ sure to also change the following storage method and table_viewer.prepare_data i for player in xrange(len(player_ids)): myStreet1CBChance=False myStreet1CBDone=False - + if street0VPI[player]: myStreet1CBChance=True if street1Aggr[player]: myStreet1CBDone=True didStreet1CB.append(player_ids[player]) - + street1CBChance.append(myStreet1CBChance) street1CBDone.append(myStreet1CBDone) result['street1CBChance']=street1CBChance result['street1CBDone']=street1CBDone - + #now 2B street2CBChance=[] street2CBDone=[] @@ -1547,18 +1549,18 @@ sure to also change the following storage method and table_viewer.prepare_data i for player in xrange(len(player_ids)): myStreet2CBChance=False myStreet2CBDone=False - + if street1CBDone[player]: myStreet2CBChance=True if street2Aggr[player]: myStreet2CBDone=True didStreet2CB.append(player_ids[player]) - + street2CBChance.append(myStreet2CBChance) street2CBDone.append(myStreet2CBDone) result['street2CBChance']=street2CBChance result['street2CBDone']=street2CBDone - + #now 3B street3CBChance=[] street3CBDone=[] @@ -1566,18 +1568,18 @@ sure to also change the following storage method and table_viewer.prepare_data i for player in xrange(len(player_ids)): myStreet3CBChance=False myStreet3CBDone=False - + if street2CBDone[player]: myStreet3CBChance=True if street3Aggr[player]: myStreet3CBDone=True didStreet3CB.append(player_ids[player]) - + street3CBChance.append(myStreet3CBChance) street3CBDone.append(myStreet3CBDone) result['street3CBChance']=street3CBChance result['street3CBDone']=street3CBDone - + #and 4B street4CBChance=[] street4CBDone=[] @@ -1585,21 +1587,21 @@ sure to also change the following storage method and table_viewer.prepare_data i for player in xrange(len(player_ids)): myStreet4CBChance=False myStreet4CBDone=False - + if street3CBDone[player]: myStreet4CBChance=True if street4Aggr[player]: myStreet4CBDone=True didStreet4CB.append(player_ids[player]) - + street4CBChance.append(myStreet4CBChance) street4CBDone.append(myStreet4CBDone) result['street4CBChance']=street4CBChance result['street4CBDone']=street4CBDone - - + + result['position']=hudDataPositions - + foldToStreet1CBChance=[] foldToStreet1CBDone=[] foldToStreet2CBChance=[] @@ -1608,40 +1610,40 @@ sure to also change the following storage method and table_viewer.prepare_data i foldToStreet3CBDone=[] foldToStreet4CBChance=[] foldToStreet4CBDone=[] - + for player in xrange(len(player_ids)): myFoldToStreet1CBChance=False myFoldToStreet1CBDone=False foldToStreet1CBChance.append(myFoldToStreet1CBChance) foldToStreet1CBDone.append(myFoldToStreet1CBDone) - + myFoldToStreet2CBChance=False myFoldToStreet2CBDone=False foldToStreet2CBChance.append(myFoldToStreet2CBChance) foldToStreet2CBDone.append(myFoldToStreet2CBDone) - + myFoldToStreet3CBChance=False myFoldToStreet3CBDone=False foldToStreet3CBChance.append(myFoldToStreet3CBChance) foldToStreet3CBDone.append(myFoldToStreet3CBDone) - + myFoldToStreet4CBChance=False myFoldToStreet4CBDone=False foldToStreet4CBChance.append(myFoldToStreet4CBChance) foldToStreet4CBDone.append(myFoldToStreet4CBDone) - + if len(didStreet1CB)>=1: generateFoldToCB(1, player_ids, didStreet1CB, street1CBDone, foldToStreet1CBChance, foldToStreet1CBDone, actionTypeByNo) - + if len(didStreet2CB)>=1: generateFoldToCB(2, player_ids, didStreet2CB, street2CBDone, foldToStreet2CBChance, foldToStreet2CBDone, actionTypeByNo) - + if len(didStreet3CB)>=1: generateFoldToCB(3, player_ids, didStreet3CB, street3CBDone, foldToStreet3CBChance, foldToStreet3CBDone, actionTypeByNo) - + if len(didStreet4CB)>=1: generateFoldToCB(4, player_ids, didStreet4CB, street4CBDone, foldToStreet4CBChance, foldToStreet4CBDone, actionTypeByNo) - + result['foldToStreet1CBChance']=foldToStreet1CBChance result['foldToStreet1CBDone']=foldToStreet1CBDone result['foldToStreet2CBChance']=foldToStreet2CBChance @@ -1650,10 +1652,10 @@ sure to also change the following storage method and table_viewer.prepare_data i result['foldToStreet3CBDone']=foldToStreet3CBDone result['foldToStreet4CBChance']=foldToStreet4CBChance result['foldToStreet4CBDone']=foldToStreet4CBDone - - + + totalProfit=[] - + street1CheckCallRaiseChance=[] street1CheckCallRaiseDone=[] street2CheckCallRaiseChance=[] @@ -1672,7 +1674,7 @@ sure to also change the following storage method and table_viewer.prepare_data i #for j in xrange(len(actionTypes[i])): #iterate through names (using pl loop above) for k in xrange(len(actionTypes[i][pl])): #iterate through individual actions of that player on that street myTotalProfit -= actionAmounts[i][pl][k] - + myStreet1CheckCallRaiseChance=False myStreet1CheckCallRaiseDone=False myStreet2CheckCallRaiseChance=False @@ -1681,11 +1683,11 @@ sure to also change the following storage method and table_viewer.prepare_data i myStreet3CheckCallRaiseDone=False myStreet4CheckCallRaiseChance=False myStreet4CheckCallRaiseDone=False - + #print "myTotalProfit=", myTotalProfit totalProfit.append(myTotalProfit) #print "totalProfit[]=", totalProfit - + street1CheckCallRaiseChance.append(myStreet1CheckCallRaiseChance) street1CheckCallRaiseDone.append(myStreet1CheckCallRaiseDone) street2CheckCallRaiseChance.append(myStreet2CheckCallRaiseChance) @@ -1694,10 +1696,10 @@ sure to also change the following storage method and table_viewer.prepare_data i street3CheckCallRaiseDone.append(myStreet3CheckCallRaiseDone) street4CheckCallRaiseChance.append(myStreet4CheckCallRaiseChance) street4CheckCallRaiseDone.append(myStreet4CheckCallRaiseDone) - + result['totalProfit']=totalProfit #print "res[totalProfit]=", result['totalProfit'] - + result['street1CheckCallRaiseChance']=street1CheckCallRaiseChance result['street1CheckCallRaiseDone']=street1CheckCallRaiseDone result['street2CheckCallRaiseChance']=street2CheckCallRaiseChance @@ -1708,7 +1710,7 @@ sure to also change the following storage method and table_viewer.prepare_data i result['street4CheckCallRaiseDone']=street4CheckCallRaiseDone return result #end def generateHudCacheData - + def generateFoldToCB(street, playerIDs, didStreetCB, streetCBDone, foldToStreetCBChance, foldToStreetCBDone, actionTypeByNo): """fills the passed foldToStreetCB* arrays appropriately depending on the given street""" #print "beginning of generateFoldToCB, street:", street, "len(actionTypeByNo):", len(actionTypeByNo) @@ -1720,7 +1722,7 @@ def generateFoldToCB(street, playerIDs, didStreetCB, streetCBDone, foldToStreetC if player==actionTypeByNo[street][action][0] and firstCBReaction==0: firstCBReaction=action+1 break - + for action in actionTypeByNo[street][firstCBReaction:]: for player in xrange(len(playerIDs)): if playerIDs[player]==action[0]: From adadb7defad98d3c1bffe20063ceaa618c83992e Mon Sep 17 00:00:00 2001 From: Eric Blade Date: Thu, 3 Dec 2009 12:51:10 -0500 Subject: [PATCH 09/10] slight optimizations --- pyfpdb/fpdb_simple.py | 96 ++++++++++++++++++------------------------- 1 file changed, 41 insertions(+), 55 deletions(-) diff --git a/pyfpdb/fpdb_simple.py b/pyfpdb/fpdb_simple.py index 85e60eeb..a6071a83 100644 --- a/pyfpdb/fpdb_simple.py +++ b/pyfpdb/fpdb_simple.py @@ -1241,40 +1241,34 @@ sure to also change the following storage method and table_viewer.prepare_data i #calculate saw* values - isAllIn = False - if any(i for i in allIns[0][player]): - isAllIn = True + isAllIn = any(i for i in AllIns[0][player]) if isAllIn or len(action_types[1][player]) > 0: myStreet1Seen = True - if any(i for i in allIns[1][player]): - isAllIn = True - if isAllIn or len(action_types[2][player]) > 0: + if not isAllIn: + isAllIn = any(i for i in allins[1][player]) + elif len(action_types[2][player]) > 0: if all(actiontype != "fold" for actiontype in action_types[1][player]): myStreet2Seen = True - if any(i for i in allIns[2][player]): - isAllIn = True - if isAllIn or len(action_types[3][player]) > 0: + if not isAllIn: + isAllAin = any(i for i in allIns[2][player]) + elif len(action_types[3][player]) > 0: if all(actiontype != "fold" for actiontype in action_types[2][player]): myStreet3Seen = True #print "base:", base if base == "hold": - mySawShowdown = True - if any(actiontype == "fold" for actiontype in action_types[3][player]): - mySawShowdown = False + mySawShowdown = not any(actiontype == "fold" for actiontype in action_types[3][player]) else: #print "in else" - if any(i for i in allIns[3][player]): - isAllIn = True - if isAllIn or len(action_types[4][player]) > 0: + if not isAllIn: + isAllIn = any(i for i in allins[3][player]) + elif len(action_types[4][player]) > 0: #print "in if" myStreet4Seen = True - mySawShowdown = True - if any(actiontype == "fold" for actiontype in action_types[4][player]): - mySawShowdown = False + mySawShowdown = not any(actiontype == "fold" for actiontype in action_types[4][player]) if myStreet1Seen: result['playersAtStreet1'] += 1 @@ -1288,98 +1282,90 @@ sure to also change the following storage method and table_viewer.prepare_data i result['playersAtShowdown'] += 1 #flop stuff - street=1 + street = 1 if myStreet1Seen: - if any(actiontype == "bet" for actiontype in action_types[street][player]): - myStreet1Aggr = True - + myStreet1Aggr = any(actiontype == "bet" for actiontype in action_types[street][player]) myStreet1Calls = action_types[street][player].count('call') myStreet1Bets = action_types[street][player].count('bet') # street1Raises = action_types[street][player].count('raise') bet count includes raises for now result['street1Raises'] += myStreet1Bets for otherPlayer in xrange(len(player_ids)): - if player==otherPlayer: + if player == otherPlayer: pass else: for countOther in xrange(len(action_types[street][otherPlayer])): - if action_types[street][otherPlayer][countOther]=="bet": - myOtherRaisedStreet1=True + if action_types[street][otherPlayer][countOther] == "bet": + myOtherRaisedStreet1 = True for countOtherFold in xrange(len(action_types[street][player])): - if action_types[street][player][countOtherFold]=="fold": - myFoldToOtherRaisedStreet1=True + if action_types[street][player][countOtherFold] == "fold": + myFoldToOtherRaisedStreet1 = True #turn stuff - copy of flop with different vars - street=2 + street = 2 if myStreet2Seen: - if any(actiontype == "bet" for actiontype in action_types[street][player]): - myStreet2Aggr = True - + myStreet2Aggr = any(actiontype == "bet" for actiontype in action_types[street][player]) myStreet2Calls = action_types[street][player].count('call') myStreet2Bets = action_types[street][player].count('bet') # street2Raises = action_types[street][player].count('raise') bet count includes raises for now result['street2Raises'] += myStreet2Bets for otherPlayer in xrange(len(player_ids)): - if player==otherPlayer: + if player == otherPlayer: pass else: for countOther in xrange(len(action_types[street][otherPlayer])): - if action_types[street][otherPlayer][countOther]=="bet": - myOtherRaisedStreet2=True + if action_types[street][otherPlayer][countOther] == "bet": + myOtherRaisedStreet2 = True for countOtherFold in xrange(len(action_types[street][player])): - if action_types[street][player][countOtherFold]=="fold": - myFoldToOtherRaisedStreet2=True + if action_types[street][player][countOtherFold] == "fold": + myFoldToOtherRaisedStreet2 = True #river stuff - copy of flop with different vars - street=3 + street = 3 if myStreet3Seen: - if any(actiontype == "bet" for actiontype in action_types[street][player]): - myStreet3Aggr = True - + myStreet3Aggr = any(actiontype == "bet" for actiontype in action_types[street][player]) myStreet3Calls = action_types[street][player].count('call') myStreet3Bets = action_types[street][player].count('bet') # street3Raises = action_types[street][player].count('raise') bet count includes raises for now result['street3Raises'] += myStreet3Bets for otherPlayer in xrange(len(player_ids)): - if player==otherPlayer: + if player == otherPlayer: pass else: for countOther in xrange(len(action_types[street][otherPlayer])): - if action_types[street][otherPlayer][countOther]=="bet": - myOtherRaisedStreet3=True + if action_types[street][otherPlayer][countOther] == "bet": + myOtherRaisedStreet3 = True for countOtherFold in xrange(len(action_types[street][player])): - if action_types[street][player][countOtherFold]=="fold": - myFoldToOtherRaisedStreet3=True + if action_types[street][player][countOtherFold] == "fold": + myFoldToOtherRaisedStreet3 = True #stud river stuff - copy of flop with different vars - street=4 + street = 4 if myStreet4Seen: - if any(actiontype == "bet" for actiontype in action_types[street][player]): - myStreet4Aggr=True - + myStreet4Aggr = any(actiontype == "bet" for actiontype in action_types[street][player]) myStreet4Calls = action_types[street][player].count('call') myStreet4Bets = action_types[street][player].count('bet') # street4Raises = action_types[street][player].count('raise') bet count includes raises for now result['street4Raises'] += myStreet4Bets for otherPlayer in xrange(len(player_ids)): - if player==otherPlayer: + if player == otherPlayer: pass else: for countOther in xrange(len(action_types[street][otherPlayer])): - if action_types[street][otherPlayer][countOther]=="bet": - myOtherRaisedStreet4=True + if action_types[street][otherPlayer][countOther] == "bet": + myOtherRaisedStreet4 = True for countOtherFold in xrange(len(action_types[street][player])): - if action_types[street][player][countOtherFold]=="fold": - myFoldToOtherRaisedStreet4=True + if action_types[street][player][countOtherFold] == "fold": + myFoldToOtherRaisedStreet4 = True if winnings[player] != 0: if myStreet1Seen: myWonWhenSeenStreet1 = winnings[player] / float(totalWinnings) if mySawShowdown: - myWonAtSD=myWonWhenSeenStreet1 + myWonAtSD = myWonWhenSeenStreet1 #add each value to the appropriate array street0VPI.append(myStreet0VPI) From 6195397c88b397f40939746d2f392be4d4b34c85 Mon Sep 17 00:00:00 2001 From: Eric Blade Date: Thu, 3 Dec 2009 12:52:57 -0500 Subject: [PATCH 10/10] fix typos.. durrr --- pyfpdb/fpdb_simple.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pyfpdb/fpdb_simple.py b/pyfpdb/fpdb_simple.py index a6071a83..aa9421f6 100644 --- a/pyfpdb/fpdb_simple.py +++ b/pyfpdb/fpdb_simple.py @@ -1241,12 +1241,12 @@ sure to also change the following storage method and table_viewer.prepare_data i #calculate saw* values - isAllIn = any(i for i in AllIns[0][player]) + isAllIn = any(i for i in allIns[0][player]) if isAllIn or len(action_types[1][player]) > 0: myStreet1Seen = True if not isAllIn: - isAllIn = any(i for i in allins[1][player]) + isAllIn = any(i for i in allIns[1][player]) elif len(action_types[2][player]) > 0: if all(actiontype != "fold" for actiontype in action_types[1][player]): myStreet2Seen = True @@ -1263,7 +1263,7 @@ sure to also change the following storage method and table_viewer.prepare_data i else: #print "in else" if not isAllIn: - isAllIn = any(i for i in allins[3][player]) + isAllIn = any(i for i in allIns[3][player]) elif len(action_types[4][player]) > 0: #print "in if" myStreet4Seen = True