diff --git a/elite/db.py b/elite/db.py index db24294..a3f6850 100644 --- a/elite/db.py +++ b/elite/db.py @@ -14,7 +14,7 @@ import elite.loader.maddavo import elite.loader.bpc import elite.loader.EDMarakedConnector -import elite.loader.eddb +import elite.loader.eddb import elite.loader.raresimport import elite.loader.eddn @@ -23,9 +23,10 @@ import sqlite3_functions -__DBPATH__ = os.path.join("db","my.db") +__DBPATH__ = os.path.join("db", "my.db") DBVERSION = 2 + class db(object): path = None @@ -35,7 +36,7 @@ class db(object): __itemIDCache = {} __streamUpdater = [] loaderCount = __loaderCount__ - sendProcessMsg=None + sendProcessMsg = None def __init__(self, guiMode=None, DBPATH=__DBPATH__): @@ -49,37 +50,37 @@ def __init__(self, guiMode=None, DBPATH=__DBPATH__): print("new db") new_db = True - self.con = sqlite3.connect(DBPATH, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES, check_same_thread = False) - self.con.row_factory = sqlite3.Row + self.con = sqlite3.connect(DBPATH, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES, check_same_thread=False) + self.con.row_factory = sqlite3.Row sqlite3_functions.registerSQLiteFunktions(self.con) if new_db: self.initDB() self.importData() - self.getSystemPaths() + self.getSystemPaths() else: pass - #self.initDB() + # self.initDB() - #self.fillCache() + # self.fillCache() self.con.execute("PRAGMA journal_mode = MEMORY") self.con.execute("PRAGMA recursive_triggers=True") - if self.getConfig( 'dbVersion' ) != DBVERSION: + if self.getConfig('dbVersion') != DBVERSION: ''' run on database update''' self.initDB() - self.getSystemPaths() + self.getSystemPaths() self.setConfig('dbVersion', DBVERSION) - elif self.getConfig( 'initRun' ) == "1" or os.path.isfile( __forceupdateFile__ ): + elif self.getConfig('initRun') == "1" or os.path.isfile(__forceupdateFile__): ''' run on first start (install with build db or on update)''' print("init run") self.initDB() - self.getSystemPaths() + self.getSystemPaths() self.setConfig('initRun', 0) ''' remove trigger file ''' - if os.path.isfile( __forceupdateFile__ ): - os.remove( __forceupdateFile__ ) + if os.path.isfile(__forceupdateFile__): + os.remove(__forceupdateFile__) if not self.guiMode: self.initDB() @@ -100,13 +101,13 @@ def fillCache(self): ''' cur = self.cursor() - cur.execute( "select id, SystemID, Station from stations" ) + cur.execute("select id, SystemID, Station from stations") result = cur.fetchall() for station in result: - key = "%d_%s" % (station["SystemID"],station["Station"]) + key = "%d_%s" % (station["SystemID"], station["Station"]) self.__stationIDCache[key] = station["id"] - cur.execute( "select id, System from systems" ) + cur.execute("select id, System from systems") result = cur.fetchall() for system in result: self.__systemIDCache[system["System"] ] = system["id"] @@ -117,10 +118,11 @@ def importData(self): print("import data") elite.loader.raresimport.loader(self).importData('db/rares.csv') + def startStreamUpdater(self): ''' Start this only from a gui or other running instances and not in single run scripts''' - self.__streamUpdater.append( elite.loader.eddn.newClient(self) ) + self.__streamUpdater.append(elite.loader.eddn.newClient(self)) def stopStreamUpdater(self): if self.__streamUpdater: @@ -132,39 +134,49 @@ def updateData(self): update price date from all sources ''' myPos = 0 - if self._active != True: return + if self._active is not True: + return myPos += 1 - if self.sendProcessMsg: self.sendProcessMsg("Update: EDDB", myPos, self.loaderCount) + if self.sendProcessMsg: + self.sendProcessMsg("Update: EDDB", myPos, self.loaderCount) elite.loader.eddb.updateAll(self) - if self._active != True: return + if self._active is not True: + return myPos += 1 - if self.sendProcessMsg: self.sendProcessMsg("Update: EDMC", myPos, self.loaderCount) + if self.sendProcessMsg: + self.sendProcessMsg("Update: EDMC", myPos, self.loaderCount) elite.loader.EDMarakedConnector.loader(self).update() - if self._active != True: return + if self._active is not True: + return myPos += 1 - if self.sendProcessMsg: self.sendProcessMsg("Update: Maddavo", myPos, self.loaderCount) + if self.sendProcessMsg: + self.sendProcessMsg("Update: Maddavo", myPos, self.loaderCount) elite.loader.maddavo.updateAll(self) - if self._active != True: return + if self._active is not True: + return myPos += 1 - if self.sendProcessMsg: self.sendProcessMsg("Update: BPC", myPos, self.loaderCount) + if self.sendProcessMsg: + self.sendProcessMsg("Update: BPC", myPos, self.loaderCount) elite.loader.bpc.prices.loader(self).importData() - if self._active != True: return + if self._active is not True: + return myPos += 1 - if self.sendProcessMsg: self.sendProcessMsg("Update: EDDN", myPos, self.loaderCount) + if self.sendProcessMsg: + self.sendProcessMsg("Update: EDDN", myPos, self.loaderCount) if self.__streamUpdater: for client in self.__streamUpdater: client.update() - lastOptimize = self.getConfig( 'lastOptimizeDatabase' ) + lastOptimize = self.getConfig('lastOptimizeDatabase') optimize = None if lastOptimize: - lastOptimize = datetime.strptime(lastOptimize , "%Y-%m-%d %H:%M:%S") + lastOptimize = datetime.strptime(lastOptimize, "%Y-%m-%d %H:%M:%S") if lastOptimize + timedelta(days=7) < datetime.now(): optimize = True else: @@ -172,105 +184,107 @@ def updateData(self): if optimize: myPos += 1 - if self.sendProcessMsg: self.sendProcessMsg("Optimize DB", myPos, self.loaderCount) + if self.sendProcessMsg: + self.sendProcessMsg("Optimize DB", myPos, self.loaderCount) self.optimizeDatabase() - if myPos > self.loaderCount: self.loaderCount = myPos + if myPos > self.loaderCount: + self.loaderCount = myPos def initDB(self): print("create/update db") ''' create tables ''' - self.con.execute( "CREATE TABLE IF NOT EXISTS config(var TEXT,val)" ) - self.con.execute( "create UNIQUE index IF NOT EXISTS config_unique_var on config (var)" ) + self.con.execute("CREATE TABLE IF NOT EXISTS config(var TEXT,val)") + self.con.execute("create UNIQUE index IF NOT EXISTS config_unique_var on config (var)") - #systems - self.con.execute( "CREATE TABLE IF NOT EXISTS systems (id INTEGER PRIMARY KEY AUTOINCREMENT, System TEXT COLLATE NOCASE UNIQUE , posX FLOAT, posY FLOAT, posZ FLOAT, permit BOOLEAN DEFAULT 0, power_control INT, government INT, allegiance INT, modified timestamp)" ) + # systems + self.con.execute("CREATE TABLE IF NOT EXISTS systems (id INTEGER PRIMARY KEY AUTOINCREMENT, System TEXT COLLATE NOCASE UNIQUE , posX FLOAT, posY FLOAT, posZ FLOAT, permit BOOLEAN DEFAULT 0, power_control INT, government INT, allegiance INT, modified timestamp)") - #stations - self.con.execute( "CREATE TABLE IF NOT EXISTS stations (id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, SystemID INT NOT NULL, Station TEXT COLLATE NOCASE, StarDist INT, government INT, allegiance INT, blackmarket BOOLEAN, max_pad_size CHARACTER, market BOOLEAN, shipyard BOOLEAN,outfitting BOOLEAN,rearm BOOLEAN,refuel BOOLEAN,repair BOOLEAN, modified timestamp)" ) - self.con.execute( "create UNIQUE index IF NOT EXISTS station_unique_system_Station on stations (SystemID, Station)" ) + # stations + self.con.execute("CREATE TABLE IF NOT EXISTS stations (id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, SystemID INT NOT NULL, Station TEXT COLLATE NOCASE, StarDist INT, government INT, allegiance INT, blackmarket BOOLEAN, max_pad_size CHARACTER, market BOOLEAN, shipyard BOOLEAN,outfitting BOOLEAN,rearm BOOLEAN,refuel BOOLEAN,repair BOOLEAN, modified timestamp)") + self.con.execute("create UNIQUE index IF NOT EXISTS station_unique_system_Station on stations (SystemID, Station)") - self.con.execute( "CREATE TABLE IF NOT EXISTS allegiances (id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT UNIQUE)" ) - self.con.execute( "CREATE TABLE IF NOT EXISTS governments (id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT UNIQUE)" ) + self.con.execute("CREATE TABLE IF NOT EXISTS allegiances (id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT UNIQUE)") + self.con.execute("CREATE TABLE IF NOT EXISTS governments (id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT UNIQUE)") - #items - self.con.execute( "CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT COLLATE NOCASE UNIQUE, category TEXT COLLATE NOCASE, ui_sort TINYINT )" ) + # items + self.con.execute("CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT COLLATE NOCASE UNIQUE, category TEXT COLLATE NOCASE, ui_sort TINYINT )") - #price - self.con.execute( "CREATE TABLE IF NOT EXISTS price (id INTEGER PRIMARY KEY AUTOINCREMENT, SystemID INT NOT NULL, StationID INT NOT NULL, ItemID INT NOT NULL, StationSell INT NOT NULL DEFAULT 0, StationBuy INT NOT NULL DEFAULT 0, Dammand INT NOT NULL DEFAULT 0, Stock INT NOT NULL DEFAULT 0, modified timestamp, source INT NOT NULL)" ) - self.con.execute( "create UNIQUE index IF NOT EXISTS price_unique_System_Station_Item on price (SystemID,StationID,ItemID)" ) - self.con.execute( "CREATE UNIQUE INDEX IF NOT EXISTS `price_index_StationID_ItemID` ON `price` (`StationID` ,`ItemID` )") - self.con.execute( "create index IF NOT EXISTS price_modified on price (modified)" ) + # price + self.con.execute("CREATE TABLE IF NOT EXISTS price (id INTEGER PRIMARY KEY AUTOINCREMENT, SystemID INT NOT NULL, StationID INT NOT NULL, ItemID INT NOT NULL, StationSell INT NOT NULL DEFAULT 0, StationBuy INT NOT NULL DEFAULT 0, Dammand INT NOT NULL DEFAULT 0, Stock INT NOT NULL DEFAULT 0, modified timestamp, source INT NOT NULL)") + self.con.execute("create UNIQUE index IF NOT EXISTS price_unique_System_Station_Item on price (SystemID,StationID,ItemID)") + self.con.execute("CREATE UNIQUE INDEX IF NOT EXISTS `price_index_StationID_ItemID` ON `price` (`StationID` ,`ItemID` )") + self.con.execute("create index IF NOT EXISTS price_modified on price (modified)") - #fakePrice - self.con.execute( "CREATE TABLE IF NOT EXISTS fakePrice (priceID INTEGER PRIMARY KEY )" ) + # fakePrice + self.con.execute("CREATE TABLE IF NOT EXISTS fakePrice (priceID INTEGER PRIMARY KEY )") - #blackmarketPrice - self.con.execute( "CREATE TABLE IF NOT EXISTS blackmarketPrice (priceID INTEGER PRIMARY KEY )" ) + # blackmarketPrice + self.con.execute("CREATE TABLE IF NOT EXISTS blackmarketPrice (priceID INTEGER PRIMARY KEY )") - #default config - self.con.execute( "insert or ignore into config(var,val) values (?,?)", ( "dbVersion", DBVERSION ) ) - self.con.execute( "insert or ignore into config(var,val) values (?,?)", ( "EDMarkedConnector_cvsDir", r'c:\Users\mEDI\Documents\ED' ) ) - self.con.execute( "insert or ignore into config(var,val) values (?,?)", ( "EliteLogDir", r'C:\Program Files (x86)\Steam\SteamApps\common\Elite Dangerous\Products\FORC-FDEV-D-1010\Logs' ) ) - self.con.execute( "insert or ignore into config(var,val) values (?,?)", ( "BPC_db_path", r'c:\Program Files (x86)\Slopeys ED BPC\ED4.db' ) ) + # default config + self.con.execute("insert or ignore into config(var,val) values (?,?)", ("dbVersion", DBVERSION)) + self.con.execute("insert or ignore into config(var,val) values (?,?)", ("EDMarkedConnector_cvsDir", r'c:\Users\mEDI\Documents\ED')) + self.con.execute("insert or ignore into config(var,val) values (?,?)", ("EliteLogDir", r'C:\Program Files (x86)\Steam\SteamApps\common\Elite Dangerous\Products\FORC-FDEV-D-1010\Logs')) + self.con.execute("insert or ignore into config(var,val) values (?,?)", ("BPC_db_path", r'c:\Program Files (x86)\Slopeys ED BPC\ED4.db')) - #rares - self.con.execute( "CREATE TABLE IF NOT EXISTS rares (id INTEGER PRIMARY KEY AUTOINCREMENT, SystemID INT NOT NULL, StationID INT NOT NULL, Name TEXT, Price INT, MaxAvail INT, illegal BOOLEAN DEFAULT NULL, offline BOOLEAN DEFAULT NULL, modifydate timestamp, comment TEXT )" ) + # rares + self.con.execute("CREATE TABLE IF NOT EXISTS rares (id INTEGER PRIMARY KEY AUTOINCREMENT, SystemID INT NOT NULL, StationID INT NOT NULL, Name TEXT, Price INT, MaxAvail INT, illegal BOOLEAN DEFAULT NULL, offline BOOLEAN DEFAULT NULL, modifydate timestamp, comment TEXT )") - #dealCache dynamic cache - self.con.execute( "CREATE TABLE IF NOT EXISTS dealsInDistances(dist FLOAT, priceAID INT, priceBID INT)" ) - self.con.execute( "create UNIQUE index IF NOT EXISTS dealsInDistances_unique_priceA_priceB on dealsInDistances (priceAID, priceBID)" ) + # dealCache dynamic cache + self.con.execute("CREATE TABLE IF NOT EXISTS dealsInDistances(dist FLOAT, priceAID INT, priceBID INT)") + self.con.execute("create UNIQUE index IF NOT EXISTS dealsInDistances_unique_priceA_priceB on dealsInDistances (priceAID, priceBID)") - self.con.execute( "CREATE TABLE IF NOT EXISTS dealsInDistancesSystems(systemID INT, dist FLOAT)" ) - self.con.execute( "create UNIQUE index IF NOT EXISTS dealsInDistancesSystems_unique_systemID on dealsInDistancesSystems (systemID)" ) - self.con.execute( "CREATE TABLE IF NOT EXISTS dealsInDistancesSystems_queue (systemID INTEGER PRIMARY KEY)" ) + self.con.execute("CREATE TABLE IF NOT EXISTS dealsInDistancesSystems(systemID INT, dist FLOAT)") + self.con.execute("create UNIQUE index IF NOT EXISTS dealsInDistancesSystems_unique_systemID on dealsInDistancesSystems (systemID)") + self.con.execute("CREATE TABLE IF NOT EXISTS dealsInDistancesSystems_queue (systemID INTEGER PRIMARY KEY)") - #ships and shipyard - self.con.execute( "CREATE TABLE IF NOT EXISTS ships (id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT UNIQUE)" ) - self.con.execute( "CREATE TABLE IF NOT EXISTS shipyard (SystemID INT,StationID INT ,ShipID INT, Price INT, modifydate timestamp)" ) - self.con.execute( "create UNIQUE index IF NOT EXISTS shipyard_unique_systemID_StationID_ShipID on shipyard (systemID, StationID, ShipID)" ) + # ships and shipyard + self.con.execute("CREATE TABLE IF NOT EXISTS ships (id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT UNIQUE)") + self.con.execute("CREATE TABLE IF NOT EXISTS shipyard (SystemID INT,StationID INT ,ShipID INT, Price INT, modifydate timestamp)") + self.con.execute("create UNIQUE index IF NOT EXISTS shipyard_unique_systemID_StationID_ShipID on shipyard (systemID, StationID, ShipID)") - #powers - self.con.execute( "CREATE TABLE IF NOT EXISTS powers (id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT UNIQUE)" ) + # powers + self.con.execute("CREATE TABLE IF NOT EXISTS powers (id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT UNIQUE)") - #fly log - self.con.execute( "CREATE TABLE IF NOT EXISTS flylog (id INTEGER PRIMARY KEY AUTOINCREMENT, SystemID INT, optionalSystemName TEXT, Comment TEXT, DateTime timestamp)" ) + # fly log + self.con.execute("CREATE TABLE IF NOT EXISTS flylog (id INTEGER PRIMARY KEY AUTOINCREMENT, SystemID INT, optionalSystemName TEXT, Comment TEXT, DateTime timestamp)") # trigger to controll the dynamic cache - self.con.execute( """CREATE TRIGGER IF NOT EXISTS trigger_update_price AFTER UPDATE OF StationBuy, StationSell ON price + self.con.execute("""CREATE TRIGGER IF NOT EXISTS trigger_update_price AFTER UPDATE OF StationBuy, StationSell ON price WHEN NEW.StationBuy != OLD.StationBuy OR NEW.StationSell != OLD.StationSell BEGIN DELETE FROM dealsInDistances WHERE priceAID=OLD.id; DELETE FROM dealsInDistancesSystems WHERE systemID=OLD.SystemID; - END; """ ) + END; """) - self.con.execute( """CREATE TRIGGER IF NOT EXISTS trigger_delete_price AFTER DELETE ON price + self.con.execute("""CREATE TRIGGER IF NOT EXISTS trigger_delete_price AFTER DELETE ON price BEGIN DELETE FROM dealsInDistances WHERE priceAID=OLD.id; DELETE FROM dealsInDistances WHERE priceBID=OLD.id; DELETE FROM dealsInDistancesSystems WHERE systemID=OLD.SystemID; - END; """ ) + END; """) - self.con.execute( """CREATE TRIGGER IF NOT EXISTS trigger_insert_price AFTER INSERT ON price + self.con.execute("""CREATE TRIGGER IF NOT EXISTS trigger_insert_price AFTER INSERT ON price BEGIN DELETE FROM dealsInDistancesSystems WHERE systemID=NEW.SystemID; - END; """ ) + END; """) - self.con.execute( """CREATE TRIGGER IF NOT EXISTS trigger_delete_dealsInDistancesSystems AFTER DELETE ON dealsInDistancesSystems + self.con.execute("""CREATE TRIGGER IF NOT EXISTS trigger_delete_dealsInDistancesSystems AFTER DELETE ON dealsInDistancesSystems BEGIN insert or ignore into dealsInDistancesSystems_queue (systemID) values(OLD.systemID); - END; """ ) + END; """) ''' update db version''' - dbVersion = self.getConfig( 'dbVersion' ) + dbVersion = self.getConfig('dbVersion') if dbVersion: dbVersion = int(dbVersion) else: @@ -278,14 +292,14 @@ def initDB(self): ''' 01 to 02 ''' if dbVersion < 2: print("update database from %s to 2" % dbVersion) - self.con.execute( "ALTER TABLE systems ADD COLUMN government INT;" ) - self.con.execute( "ALTER TABLE systems ADD COLUMN allegiance INT;" ) + self.con.execute("ALTER TABLE systems ADD COLUMN government INT;") + self.con.execute("ALTER TABLE systems ADD COLUMN allegiance INT;") - self.con.execute( "ALTER TABLE stations ADD COLUMN government INT;" ) - self.con.execute( "ALTER TABLE stations ADD COLUMN allegiance INT;" ) + self.con.execute("ALTER TABLE stations ADD COLUMN government INT;") + self.con.execute("ALTER TABLE stations ADD COLUMN allegiance INT;") - self.con.execute( "vacuum systems;" ) - self.con.execute( "vacuum stations;" ) + self.con.execute("vacuum systems;") + self.con.execute("vacuum stations;") self.con.commit() @@ -295,48 +309,48 @@ def optimizeDatabase(self): ''' cur = self.cursor() - cur.execute( "select * from sqlite_master where type = 'table' or type = 'index' order by type" ) + cur.execute("select * from sqlite_master where type = 'table' or type = 'index' order by type") result = cur.fetchall() for table in result: print("vacuum %s" % table["name"]) - self.con.execute( "vacuum '%s'" % table["name"] ) + self.con.execute("vacuum '%s'" % table["name"]) - cur.execute( "select * from sqlite_master where type = 'table' order by rootpage" ) + cur.execute("select * from sqlite_master where type = 'table' order by rootpage") result = cur.fetchall() for table in result: print("analyze %s" % table["name"]) - cur.execute( "analyze '%s'" % table["name"] ) + cur.execute("analyze '%s'" % table["name"]) self.con.commit() cur.close() - self.setConfig( 'lastOptimizeDatabase', datetime.now().strftime("%Y-%m-%d %H:%M:%S") ) + self.setConfig('lastOptimizeDatabase', datetime.now().strftime("%Y-%m-%d %H:%M:%S")) - def cursor( self ): + def cursor(self): cur = self.con.cursor() - #cur.execute("PRAGMA synchronous = OFF") - #cur.execute("PRAGMA journal_mode = MEMORY") - #cur.execute("PRAGMA journal_mode = OFF") + # cur.execute("PRAGMA synchronous = OFF") + # cur.execute("PRAGMA journal_mode = MEMORY") + # cur.execute("PRAGMA journal_mode = OFF") return cur - def setConfig( self, var, val ): + def setConfig(self, var, val): cur = self.cursor() - cur.execute( "insert or replace into config(var,val) values (?,?)", ( var, val ) ) + cur.execute("insert or replace into config(var,val) values (?,?)", (var, val)) self.con.commit() cur.close() def setFakePrice(self, id): - if isinstance( id, int): - self.con.execute( "insert or ignore into fakePrice (priceID) values(?);", ( id, ) ) + if isinstance(id, int): + self.con.execute("insert or ignore into fakePrice (priceID) values(?);", (id,)) self.con.commit() - def getConfig( self, var ): + def getConfig(self, var): cur = self.cursor() - cur.execute( "select val from config where var = ? limit 1", ( var, ) ) + cur.execute("select val from config where var = ? limit 1", (var,)) result = cur.fetchone() cur.close() if result: @@ -344,7 +358,7 @@ def getConfig( self, var ): else: return False - def getSystemIDbyName(self,system): + def getSystemIDbyName(self, system): system = system.lower() @@ -353,7 +367,7 @@ def getSystemIDbyName(self,system): return result cur = self.cursor() - cur.execute( "select id from systems where LOWER(System) = ? limit 1", ( system, ) ) + cur.execute("select id from systems where LOWER(System) = ? limit 1", (system,)) result = cur.fetchone() cur.close() @@ -365,15 +379,15 @@ def getShiptID(self, name): name = name.lower() cur = self.cursor() - cur.execute( "select id from ships where LOWER(Name)=? limit 1", ( name, ) ) + cur.execute("select id from ships where LOWER(Name)=? limit 1", (name,)) result = cur.fetchone() cur.close() if result: return result[0] - def getSystemname(self,SystemID): + def getSystemname(self, SystemID): cur = self.cursor() - cur.execute( "select System from systems where id = ? limit 1", ( SystemID, ) ) + cur.execute("select System from systems where id = ? limit 1", (SystemID,)) result = cur.fetchone() cur.close() @@ -384,14 +398,14 @@ def getStationID(self, systemID, station): if not systemID or not station: return station = station.lower() - key = "%d_%s" % (systemID,station) + key = "%d_%s" % (systemID, station) - result = self.__stationIDCache.get( key ) + result = self.__stationIDCache.get(key) if result: return result cur = self.cursor() - cur.execute( "select id from stations where systemID = ? and LOWER(Station) = ? limit 1", (systemID, station, ) ) + cur.execute("select id from stations where systemID = ? and LOWER(Station) = ? limit 1", (systemID, station,)) result = cur.fetchone() cur.close() @@ -399,10 +413,10 @@ def getStationID(self, systemID, station): self.__stationIDCache[key] = result[0] return result[0] - def getStationname(self,stationID): + def getStationname(self, stationID): cur = self.cursor() - cur.execute( "select Station from stations where id = ? limit 1", (stationID, ) ) + cur.execute("select Station from stations where id = ? limit 1", (stationID,)) result = cur.fetchone() cur.close() if result: @@ -422,22 +436,23 @@ def getStarDistFromStation(self, station, system=None): else: stationID = station - if not stationID: return + if not stationID: + return cur = self.cursor() - cur.execute( "select StarDist from stations where id = ? limit 1", ( stationID, ) ) + cur.execute("select StarDist from stations where id = ? limit 1", (stationID,)) result = cur.fetchone() cur.close() return result[0] - def getItemID(self,itemname): + def getItemID(self, itemname): result = self.__itemIDCache.get(itemname.lower()) if result: return result cur = self.cursor() - cur.execute( "select id from items where LOWER(name) = ? limit 1", (itemname.lower(), ) ) + cur.execute("select id from items where LOWER(name) = ? limit 1", (itemname.lower(),)) result = cur.fetchone() cur.close() @@ -449,7 +464,7 @@ def getAllItemNames(self): cur = self.cursor() - cur.execute( "select id ,name from items order by name" ) + cur.execute("select id ,name from items order by name") result = cur.fetchall() @@ -457,14 +472,14 @@ def getAllItemNames(self): if result: return result - def getSystemData(self,systemID): + def getSystemData(self, systemID): cur = self.cursor() - cur.execute( "select * from systems where id = ? limit 1", ( systemID, ) ) + cur.execute("select * from systems where id = ? limit 1", (systemID,)) result = cur.fetchone() cur.close() return result - def getStationsFromSystem(self,system): + def getStationsFromSystem(self, system): if isinstance(system, int): systemID = system @@ -472,52 +487,53 @@ def getStationsFromSystem(self,system): systemID = self.getSystemIDbyName(system) cur = self.con.cursor() - cur.execute('SELECT id, Station FROM stations where SystemID=? order by Station' , (systemID,)) + cur.execute('SELECT id, Station FROM stations where SystemID=? order by Station', (systemID,)) rows = cur.fetchall() cur.close() stations = [] for row in rows: - stations.append( [ row["id"], row["Station"] ] ) + stations.append([ row["id"], row["Station"] ]) return stations - def getStationData(self,stationID): + def getStationData(self, stationID): cur = self.cursor() - cur.execute( "select * from stations where id = ? limit 1", ( stationID, ) ) + cur.execute("select * from stations where id = ? limit 1", (stationID,)) result = cur.fetchone() cur.close() return result - def getItemPriceDataByID(self,systemID,stationID,itemID): + def getItemPriceDataByID(self, systemID, stationID, itemID): cur = self.cursor() - cur.execute( "select * from price where SystemID = ? and StationID = ? AND ItemID = ? limit 1", ( systemID,stationID,itemID, ) ) + cur.execute("select * from price where SystemID = ? and StationID = ? AND ItemID = ? limit 1", (systemID, stationID, itemID,)) result = cur.fetchone() cur.close() return result - def getItemPriceModifiedDate(self,systemID,stationID,itemID): + def getItemPriceModifiedDate(self, systemID, stationID, itemID): cur = self.cursor() - cur.execute( "select modified from price where SystemID = ? and StationID = ? AND ItemID = ? limit 1", ( systemID,stationID,itemID, ) ) + cur.execute("select modified from price where SystemID = ? and StationID = ? AND ItemID = ? limit 1", (systemID, stationID, itemID,)) result = cur.fetchone() cur.close() - if result: return result[0] + if result: + return result[0] return None def getSystemsInDistance(self, system, distance): # system is systemid or name - if isinstance(system,int): + if isinstance(system, int): systemID = system else: systemID = self.getSystemIDbyName(system) cur = self.cursor() - #get pos data from systemA - cur.execute( "select * from systems where id = ? limit 1", ( systemID, ) ) + # get pos data from systemA + cur.execute("select * from systems where id = ? limit 1", (systemID,)) systemA = cur.fetchone() - cur.execute( "select id, calcDistance(?, ?, ?, posX, posY, posZ ) AS dist, System from systems where dist <= ? order by dist", ( systemA["posX"],systemA["posY"],systemA["posZ"],distance, ) ) + cur.execute("select id, calcDistance(?, ?, ?, posX, posY, posZ ) AS dist, System from systems where dist <= ? order by dist", (systemA["posX"], systemA["posY"], systemA["posZ"], distance,)) result = cur.fetchall() cur.close() @@ -526,10 +542,10 @@ def getSystemsInDistance(self, system, distance): def getDistanceFromTo(self, systemA, systemB): # system is systemid or name - if not isinstance(systemA,int): + if not isinstance(systemA, int): systemA = self.getSystemIDbyName(systemA) - if not isinstance(systemB,int): + if not isinstance(systemB, int): systemB = self.getSystemIDbyName(systemB) cur = self.cursor() @@ -537,7 +553,7 @@ def getDistanceFromTo(self, systemA, systemB): cur.execute("""select calcDistance(a.posX, a.posY, a.posZ, b.posX, b.posY, b.posZ ) As dist FROM systems AS a left JOIN systems AS b on b.id = ? - where a.id = ? """ , ( systemA, systemB, ) ) + where a.id = ? """, (systemA, systemB,)) result = cur.fetchone() cur.close() @@ -549,19 +565,19 @@ def getDistanceFromTo(self, systemA, systemB): def getPricesInDistance(self, system, distance, maxStarDist, maxAgeDate, ItemID=None, onlyLpads=None, buyOrSell=None, allegiance=None, government=None): # system is systemid or name - if isinstance(system,int): + if isinstance(system, int): systemID = system else: systemID = self.getSystemIDbyName(system) cur = self.cursor() - if distance == 0: + if distance == 0: distanceFromQuery = "FROM ( select * from systems where systems.id = '%s' ) as systems" % systemID else: - #get pos data from systemA - cur.execute( "select * from systems where id = ? limit 1", ( systemID, ) ) + # get pos data from systemA + cur.execute("select * from systems where id = ? limit 1", (systemID,)) systemA = cur.fetchone() - distanceFromQuery = "FROM ( select calcDistance(%s, %s, %s, systems.posX, systems.posY, systems.posZ ) as dist, * from systems where dist <= %s ) as systems" % (systemA["posX"],systemA["posY"],systemA["posZ"], distance) + distanceFromQuery = "FROM ( select calcDistance(%s, %s, %s, systems.posX, systems.posY, systems.posZ ) as dist, * from systems where dist <= %s ) as systems" % (systemA["posX"], systemA["posY"], systemA["posZ"], distance) itemFilter = "" if ItemID: @@ -584,9 +600,9 @@ def getPricesInDistance(self, system, distance, maxStarDist, maxAgeDate, ItemID= governmentFilter = "" if government: - governmentFilter = "AND ( systems.government=%s OR stations.government=%s)" % (government, government) + governmentFilter = "AND ( systems.government=%s OR stations.government=%s)" % (government, government) - cur.execute("""select *, price.modified AS age + cur.execute("""select *, price.modified AS age %s inner join price ON systems.id=price.SystemID @@ -602,21 +618,21 @@ def getPricesInDistance(self, system, distance, maxStarDist, maxAgeDate, ItemID= %s %s AND price.modified >= ? AND stations.StarDist <= ? - """ % (distanceFromQuery, itemFilter, padsizeFilter, buyOrSellFilter, allegianceFilter, governmentFilter) , ( maxAgeDate, maxStarDist, ) ) + """ % (distanceFromQuery, itemFilter, padsizeFilter, buyOrSellFilter, allegianceFilter, governmentFilter), (maxAgeDate, maxStarDist, )) result = cur.fetchall() cur.close() return result - def getDealsFromTo(self, fromStation, toStation, maxAgeDate=datetime.utcnow()-timedelta(days=14), minStock=0 ): + def getDealsFromTo(self, fromStation, toStation, maxAgeDate=datetime.utcnow() - timedelta(days=14), minStock=0): - if isinstance(fromStation,int): + if isinstance(fromStation, int): fromStationID = fromStation else: return - if isinstance(toStation,int): + if isinstance(toStation, int): toStationID = toStation else: return @@ -641,9 +657,9 @@ def getDealsFromTo(self, fromStation, toStation, maxAgeDate=datetime.utcnow()-t left JOIN fakePrice AS fakePriceA ON priceA.id=fakePriceA.priceID left JOIN fakePrice AS fakePriceB ON priceB.id=fakePriceB.priceID - WHERE + WHERE - priceA.StationID=? + priceA.StationID=? AND priceA.StationSell > 0 AND priceA.Stock > ? AND priceA.modified >= ? @@ -659,7 +675,7 @@ def getDealsFromTo(self, fromStation, toStation, maxAgeDate=datetime.utcnow()-t return result - def getDealsFromToSystem(self, fromStationID, toSystemID, maxStarDist=999999999, maxAgeDate=datetime.utcnow()-timedelta(days=14), minStock=0 ): + def getDealsFromToSystem(self, fromStationID, toSystemID, maxStarDist=999999999, maxAgeDate=datetime.utcnow() - timedelta(days=14), minStock=0): cur = self.cursor() @@ -682,9 +698,9 @@ def getDealsFromToSystem(self, fromStationID, toSystemID, maxStarDist=999999999 left JOIN fakePrice AS fakePriceA ON priceA.id=fakePriceA.priceID left JOIN fakePrice AS fakePriceB ON priceB.id=fakePriceB.priceID - WHERE + WHERE - priceA.StationID=? + priceA.StationID=? AND priceA.StationSell > 0 AND stationB.StarDist <= ? AND priceA.Stock > ? @@ -700,43 +716,45 @@ def getDealsFromToSystem(self, fromStationID, toSystemID, maxStarDist=999999999 return result - def calcDealsInDistancesCache(self, systemIDlist, maxAgeDate , minTradeProfit=1000,dist=51): + def calcDealsInDistancesCache(self, systemIDlist, maxAgeDate, minTradeProfit=1000, dist=51): print("calcDealsInDistancesCache", len(systemIDlist)) cur = self.cursor() for myPos, system in enumerate(systemIDlist): - if self._active != True: return + if self._active is not True: + return - if self.sendProcessMsg: self.sendProcessMsg("rebuild cache", myPos+1, len(systemIDlist)) + if self.sendProcessMsg: + self.sendProcessMsg("rebuild cache", myPos + 1, len(systemIDlist)) systemID = system["id"] - cur.execute("INSERT or IGNORE INTO dealsInDistancesSystems ( systemID, dist ) values (?, ? )", (systemID, dist )) + cur.execute("INSERT or IGNORE INTO dealsInDistancesSystems ( systemID, dist ) values (?, ? )", (systemID, dist)) - cur.execute( "select * from systems where id = ? limit 1", ( systemID, ) ) + cur.execute("select * from systems where id = ? limit 1", (systemID,)) systemA = cur.fetchone() - cur.execute("""INSERT or IGNORE INTO dealsInDistances (dist, priceAID, priceBID ) + cur.execute("""INSERT or IGNORE INTO dealsInDistances (dist, priceAID, priceBID ) - select dist, priceA.id AS priceAID, priceB.id AS priceBID -/* + select dist, priceA.id AS priceAID, priceB.id AS priceBID +/* FROM price AS priceA inner JOIN (select priceB.id AS id , priceB.StationBuy, priceB.ItemID, calcDistance(?, ?, ?, systemB.posX, systemB.posY, systemB.posZ ) AS dist - from systems AS systemB - inner join price AS priceB ON priceB.SystemID=systemB.id - where priceB.StationBuy > 0 AND priceB.modified >= ? AND dist <= ?) - AS priceB ON priceA.ItemID=priceB.ItemID + from systems AS systemB + inner join price AS priceB ON priceB.SystemID=systemB.id + where priceB.StationBuy > 0 AND priceB.modified >= ? AND dist <= ?) + AS priceB ON priceA.ItemID=priceB.ItemID */ FROM (select priceB.id AS id , priceB.StationBuy, priceB.ItemID, calcDistance(?, ?, ?, systemB.posX, systemB.posY, systemB.posZ ) AS dist - from systems AS systemB - inner join price AS priceB ON priceB.SystemID=systemB.id - where priceB.StationBuy > 0 AND priceB.modified >= ? AND dist <= ?) - AS priceB + from systems AS systemB + inner join price AS priceB ON priceB.SystemID=systemB.id + where priceB.StationBuy > 0 AND priceB.modified >= ? AND dist <= ?) + AS priceB - inner JOIN price AS priceA ON priceA.ItemID=priceB.ItemID + inner JOIN price AS priceA ON priceA.ItemID=priceB.ItemID left JOIN fakePrice AS fakePriceA ON priceA.id=fakePriceA.priceID left JOIN fakePrice AS fakePriceB ON priceB.id=fakePriceB.priceID @@ -744,14 +762,14 @@ def calcDealsInDistancesCache(self, systemIDlist, maxAgeDate , minTradeProfit=10 where priceA.SystemID = ? AND priceA.modified >= ? - AND priceA.StationSell > 0 + AND priceA.StationSell > 0 - AND priceB.StationBuy > priceA.StationSell + AND priceB.StationBuy > priceA.StationSell AND priceB.StationBuy - priceA.StationSell >= ? AND fakePriceA.priceID IS NULL and fakePriceB.priceID IS NULL - """ , (systemA["posX"], systemA["posY"], systemA["posZ"], maxAgeDate, dist, systemID, maxAgeDate, minTradeProfit ) ) + """, (systemA["posX"], systemA["posY"], systemA["posZ"], maxAgeDate, dist, systemID, maxAgeDate, minTradeProfit)) # delete system from queue cur.execute("DELETE FROM dealsInDistancesSystems_queue WHERE systemID=?", [systemID]) @@ -761,21 +779,21 @@ def calcDealsInDistancesCache(self, systemIDlist, maxAgeDate , minTradeProfit=10 def calcDealsInDistancesCacheQueue(self): cur = self.cursor() - cur.execute( "select systemID AS id from dealsInDistancesSystems_queue") + cur.execute("select systemID AS id from dealsInDistancesSystems_queue") systemList = cur.fetchall() if systemList: - maxAgeDate = datetime.utcnow() - timedelta(days=14) #TODO: save max age and use the max? - self.calcDealsInDistancesCache(systemList, maxAgeDate ) + maxAgeDate = datetime.utcnow() - timedelta(days=14) # TODO: save max age and use the max? + self.calcDealsInDistancesCache(systemList, maxAgeDate) def checkDealsInDistancesCache(self): cur = self.cursor() - cur.execute( """select * from dealsInDistances + cur.execute("""select * from dealsInDistances left join price AS priceA ON priceA.id=dealsInDistances.priceAID left join price AS priceB ON priceB.id=dealsInDistances.priceBID where - priceB.StationBuy < priceA.StationSell + priceB.StationBuy < priceA.StationSell OR priceB.StationBuy IS NULL OR priceA.StationSell IS NULL """) @@ -786,26 +804,26 @@ def checkDealsInDistancesCache(self): def rebuildFullDistancesCache(self): cur = self.cursor() - cur.execute( """ DELETE FROM dealsInDistances""") - cur.execute( """ DELETE FROM dealsInDistancesSystems""") + cur.execute(""" DELETE FROM dealsInDistances""") + cur.execute(""" DELETE FROM dealsInDistancesSystems""") self.con.commit() def deleteDealsInDistancesSystems_queue(self): cur = self.cursor() - cur.execute( """ DELETE FROM dealsInDistancesSystems_queue""") + cur.execute(""" DELETE FROM dealsInDistancesSystems_queue""") self.con.commit() - def getBestDealsinDistance(self, system, distance,maxSearchRange, maxAgeDate, maxStarDist, minProfit, minStock, resultLimit=50, onlyLpads=None): - if isinstance(system,int): + def getBestDealsinDistance(self, system, distance, maxSearchRange, maxAgeDate, maxStarDist, minProfit, minStock, resultLimit=50, onlyLpads=None): + if isinstance(system, int): systemID = system else: systemID = self.getSystemIDbyName(system) cur = self.cursor() - #get pos data from systemA - cur.execute( "select * from systems where id = ? limit 1", ( systemID, ) ) + # get pos data from systemA + cur.execute("select * from systems where id = ? limit 1", (systemID,)) systemA = cur.fetchone() padsizePart = "" @@ -824,24 +842,24 @@ def getBestDealsinDistance(self, system, distance,maxSearchRange, maxAgeDate, ma where priceA.modified >= ? - AND priceA.StationSell>0 + AND priceA.StationSell>0 AND priceA.Stock>=? AND systemA.permit != 1 AND stationA.StarDist <= ? %s group by systemA.id - """ % (padsizePart) , - ( systemA["posX"], systemA["posY"], systemA["posZ"], maxSearchRange, maxAgeDate, minStock, maxStarDist) ) + """ % (padsizePart), + (systemA["posX"], systemA["posY"], systemA["posZ"], maxSearchRange, maxAgeDate, minStock, maxStarDist)) # check the dealsIndistance cache - cur.execute( """select id, calcDistance(?, ?, ?, posX, posY, posZ ) AS distn, dealsInDistancesSystems.dist - from TEAMP_selectSystemA AS systems + cur.execute("""select id, calcDistance(?, ?, ?, posX, posY, posZ ) AS distn, dealsInDistancesSystems.dist + from TEAMP_selectSystemA AS systems LEFT join dealsInDistancesSystems ON systems.id=dealsInDistancesSystems.SystemID where distn<=? AND dealsInDistancesSystems.dist is NULL group by id - """, ( systemA["posX"], systemA["posY"], systemA["posZ"], distance, ) ) + """, (systemA["posX"], systemA["posY"], systemA["posZ"], distance,)) systemList = cur.fetchall() if systemList: self.calcDealsInDistancesCache(systemList, maxAgeDate) @@ -855,7 +873,7 @@ def getBestDealsinDistance(self, system, distance,maxSearchRange, maxAgeDate, ma priceA.ItemID , priceB.StationBuy AS StationBuy, priceA.StationSell AS StationSell, systemA.System AS SystemA, priceA.id AS priceAid, priceA.SystemID AS SystemAID, priceA.StationID AS StationAID, stationA.Station AS StationA, stationA.StarDist, stationA.refuel, systemB.System AS SystemB, priceB.id AS priceBid, priceB.SystemID AS SystemBID, priceB.StationID AS StationBID, stationB.Station AS StationB, stationB.StarDist AS StarDist, stationB.refuel AS refuel, - dist, systemA.startDist AS startDist, items.name AS itemName + dist, systemA.startDist AS startDist, items.name AS itemName from TEAMP_selectSystemA AS systemA @@ -876,16 +894,16 @@ def getBestDealsinDistance(self, system, distance,maxSearchRange, maxAgeDate, ma where priceA.modified >= ? - AND priceA.StationSell>0 + AND priceA.StationSell>0 AND priceA.Stock>=? AND stationA.StarDist <= ? AND priceB.modified >= ? - AND priceB.StationBuy>0 + AND priceB.StationBuy>0 AND systemB.permit != 1 AND stationB.StarDist <= ? - AND priceB.StationBuy > priceA.StationSell + AND priceB.StationBuy > priceA.StationSell AND priceB.StationBuy-priceA.StationSell >= ? AND fakePriceA.priceID IS NULL and fakePriceB.priceID IS NULL %s @@ -894,7 +912,7 @@ def getBestDealsinDistance(self, system, distance,maxSearchRange, maxAgeDate, ma limit ? - """ % (padsizePart) , ( distance, maxAgeDate, minStock, maxStarDist, maxAgeDate, maxStarDist, minProfit, resultLimit) ) # + """ % (padsizePart), (distance, maxAgeDate, minStock, maxStarDist, maxAgeDate, maxStarDist, minProfit, resultLimit)) result = cur.fetchall() @@ -902,23 +920,23 @@ def getBestDealsinDistance(self, system, distance,maxSearchRange, maxAgeDate, ma return result - def getBestDealsFromStationInDistance(self,stationID, distance, maxAgeDate, maxStarDist, minProfit, minStock, reslultLimit=20, onlyLpads=None): + def getBestDealsFromStationInDistance(self, stationID, distance, maxAgeDate, maxStarDist, minProfit, minStock, reslultLimit=20, onlyLpads=None): cur = self.cursor() - #get pos data from systemA - cur.execute( "select * from stations left join systems on systems.id=stations.SystemID where stations.id = ? limit 1", ( stationID, ) ) + # get pos data from systemA + cur.execute("select * from stations left join systems on systems.id=stations.SystemID where stations.id = ? limit 1", (stationID,)) stationA = cur.fetchone() # check the dealsIndistance cache - cur.execute( """select id, calcDistance(?, ?, ?, posX, posY, posZ ) AS distn, dealsInDistancesSystems.dist - from TEAMP_selectSystemA AS systems + cur.execute("""select id, calcDistance(?, ?, ?, posX, posY, posZ ) AS distn, dealsInDistancesSystems.dist + from TEAMP_selectSystemA AS systems LEFT join dealsInDistancesSystems ON systems.id=dealsInDistancesSystems.SystemID where distn<=? AND dealsInDistancesSystems.dist is NULL group by id - """, ( stationA["posX"], stationA["posY"], stationA["posZ"], distance, ) ) + """, (stationA["posX"], stationA["posY"], stationA["posZ"], distance,)) systemList = cur.fetchall() if systemList: self.calcDealsInDistancesCache(systemList, maxAgeDate) @@ -955,40 +973,40 @@ def getBestDealsFromStationInDistance(self,stationID, distance, maxAgeDate, maxS AND priceB.modified >= ? AND systemB.permit != 1 - AND priceA.StationSell>0 + AND priceA.StationSell>0 AND stationB.StarDist <= ? AND priceB.StationBuy > priceA.StationSell - AND profit >= ? + AND profit >= ? AND fakePriceA.priceID IS NULL and fakePriceB.priceID IS NULL %s order by profit DESC limit ? - """ % (padsizePart) , - ( stationID, minStock, distance, maxAgeDate, maxAgeDate, maxStarDist,minProfit, reslultLimit ) ) + """ % (padsizePart), + (stationID, minStock, distance, maxAgeDate, maxAgeDate, maxStarDist, minProfit, reslultLimit)) result = cur.fetchall() cur.close() return result - def getPricesFrom(self,system, maxStarDist, maxAgeDate): + def getPricesFrom(self, system, maxStarDist, maxAgeDate): # system is name, systemID or systemID list (maximal 999 systems) - if isinstance(system,int): + if isinstance(system, int): systemIDs = [system] systemBseq = "?" - elif isinstance(system,list): - #print(len(system)) + elif isinstance(system, list): + # print(len(system)) systemIDs = system - systemBseq=','.join(['?']*len(systemIDs)) + systemBseq = ','.join(['?'] * len(systemIDs)) else: systemIDs = [self.getSystemIDbyName(system)] systemBseq = "?" - #print(systemBseq) + # print(systemBseq) - #print(systemAID, systemBID) + # print(systemAID, systemBID) cur = self.cursor() # add maxAgeDate to list end @@ -1003,7 +1021,7 @@ def getPricesFrom(self,system, maxStarDist, maxAgeDate): where price.systemID in (%s) AND price.modified >= ? AND stations.StarDist <= ? - """ % (systemBseq) , systemIDs ) + """ % (systemBseq), systemIDs) result = cur.fetchall() @@ -1049,15 +1067,15 @@ def getAllShipnames(self): cur.close() return result - def getShipyardWithShip(self,shipID,systemID=None): + def getShipyardWithShip(self, shipID, systemID=None): cur = self.cursor() if systemID: - cur.execute( "select * from systems where id = ? limit 1", ( systemID, ) ) + cur.execute("select * from systems where id = ? limit 1", (systemID,)) systemA = cur.fetchone() else: - systemA = {"posX":0.0, "posY":0.0, "posZ":0.0} + systemA = {"posX": 0.0, "posY": 0.0, "posZ": 0.0} cur.execute("""select *, calcDistance(?, ?, ?, posX, posY, posZ ) AS dist @@ -1066,9 +1084,9 @@ def getShipyardWithShip(self,shipID,systemID=None): left JOIN systems on systems.id = shipyard.SystemID left JOIN stations on stations.id = shipyard.StationID /* left JOIN ships on ships.id = shipyard.ShipID */ - where - ShipID=? - """ , (systemA["posX"],systemA["posY"],systemA["posZ"],shipID,)) + where + ShipID=? + """, (systemA["posX"], systemA["posY"], systemA["posZ"], shipID, )) result = cur.fetchall() cur.close() @@ -1077,18 +1095,18 @@ def getShipyardWithShip(self,shipID,systemID=None): def getSystemPaths(self): print("getSystemPaths") logPath = None - if sys.platform=='win32': + if sys.platform == 'win32': from PySide import QtCore InstallLocation = None ''' Elite Dangerous (steam install) path ''' - #HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Steam App 359320\InstallLocation - settings = QtCore.QSettings(r"HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Steam App 359320",QtCore.QSettings.NativeFormat) + # HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Steam App 359320\InstallLocation + settings = QtCore.QSettings(r"HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Steam App 359320", QtCore.QSettings.NativeFormat) if settings: InstallLocation = settings.value("InstallLocation") ''' Elite Dangerous (default install) path ''' - #https://support.frontier.co.uk/kb/faq.php?id=108 + # https://support.frontier.co.uk/kb/faq.php?id=108 if not InstallLocation: path = r'C:\Program Files (x86)\Frontier' if os.path.isdir(path): @@ -1096,30 +1114,30 @@ def getSystemPaths(self): if InstallLocation: - productsList = ['FORC-FDEV-D-1010','FORC-FDEV-D-1008','FORC-FDEV-D-1003','FORC-FDEV-D-1002','FORC-FDEV-D-1001','FORC-FDEV-D-1000'] + productsList = ['FORC-FDEV-D-1010', 'FORC-FDEV-D-1008', 'FORC-FDEV-D-1003', 'FORC-FDEV-D-1002', 'FORC-FDEV-D-1001', 'FORC-FDEV-D-1000'] for path in productsList: - mypath = os.path.join(InstallLocation,'Products', path, 'Logs') - if os.path.isdir( mypath ): + mypath = os.path.join(InstallLocation, 'Products', path, 'Logs') + if os.path.isdir(mypath): logPath = mypath break if os.path.isdir(logPath): self.setConfig('EliteLogDir', logPath) - #print("set %s" % logPath) + # print("set %s" % logPath) ''' EDMarketConnector settings import ''' - #HKEY_CURRENT_USER\Software\Marginal\EDMarketConnector\outdir + # HKEY_CURRENT_USER\Software\Marginal\EDMarketConnector\outdir settings = QtCore.QSettings("Marginal", "EDMarketConnector") outdir = settings.value("outdir") if outdir and os.path.isdir(outdir): self.setConfig('EDMarkedConnector_cvsDir', outdir) - #print("set %s" % outdir) + # print("set %s" % outdir) ''' Slopeys ED BPC path import ''' - #HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Slopeys ED BPC\UninstallString - settings = QtCore.QSettings(r"HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Slopeys ED BPC",QtCore.QSettings.NativeFormat) + # HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Slopeys ED BPC\UninstallString + settings = QtCore.QSettings(r"HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Slopeys ED BPC", QtCore.QSettings.NativeFormat) uninstallerPath = settings.value(r"UninstallString") if uninstallerPath: path = uninstallerPath.split("\\") @@ -1128,7 +1146,7 @@ def getSystemPaths(self): path = "\\".join(path) if os.path.isfile(path): self.setConfig('BPC_db_path', path) - #print("set %s" % path) + # print("set %s" % path) def close(self): self.con.close() @@ -1137,7 +1155,7 @@ def getPowerID(self, power): power = power.lower() cur = self.cursor() - cur.execute( "select id from powers where LOWER(Name)=? limit 1", ( power, ) ) + cur.execute("select id from powers where LOWER(Name)=? limit 1", (power,)) result = cur.fetchone() cur.close() if result: @@ -1157,16 +1175,16 @@ def getSystemsWithPower(self, powerID, systemID=None): cur = self.cursor() if systemID: - cur.execute( "select * from systems where id = ? limit 1", ( systemID, ) ) + cur.execute("select * from systems where id = ? limit 1", (systemID,)) systemA = cur.fetchone() else: - systemA = {"posX":0.0, "posY":0.0, "posZ":0.0} + systemA = {"posX": 0.0, "posY": 0.0, "posZ": 0.0} cur.execute("""select *, calcDistance(?, ?, ?, posX, posY, posZ ) AS dist FROM systems - where - power_control=? - """ , (systemA["posX"], systemA["posY"], systemA["posZ"], powerID,)) + where + power_control=? + """, (systemA["posX"], systemA["posY"], systemA["posZ"], powerID,)) result = cur.fetchall() cur.close() @@ -1177,13 +1195,13 @@ def getAllegianceID(self, allegiance, addUnknown=None): return cur = self.cursor() - cur.execute( "select id from allegiances where LOWER(Name)=? limit 1", ( allegiance.lower(), ) ) + cur.execute("select id from allegiances where LOWER(Name)=? limit 1", (allegiance.lower(),)) result = cur.fetchone() if not result and addUnknown: - cur.execute( "insert or IGNORE into allegiances (Name) values (?) ", ( allegiance, )) - cur.execute( "select id from allegiances where Name=? limit 1", ( allegiance, ) ) + cur.execute("insert or IGNORE into allegiances (Name) values (?) ", (allegiance,)) + cur.execute("select id from allegiances where Name=? limit 1", (allegiance,)) result = cur.fetchone() @@ -1194,7 +1212,7 @@ def getAllegianceID(self, allegiance, addUnknown=None): def getAllegiances(self): cur = self.cursor() - cur.execute( "select id, Name from allegiances " ) + cur.execute("select id, Name from allegiances ") result = cur.fetchall() @@ -1208,13 +1226,13 @@ def getGovernmentID(self, government, addUnknown=None): return cur = self.cursor() - cur.execute( "select id from governments where LOWER(Name)=? limit 1", ( government.lower(), ) ) + cur.execute("select id from governments where LOWER(Name)=? limit 1", (government.lower(),)) result = cur.fetchone() if not result and addUnknown: - cur.execute( "insert or IGNORE into governments (Name) values (?) ", ( government, )) - cur.execute( "select id from governments where Name=? limit 1", ( government, ) ) + cur.execute("insert or IGNORE into governments (Name) values (?) ", (government,)) + cur.execute("select id from governments where Name=? limit 1", (government,)) result = cur.fetchone() @@ -1226,7 +1244,7 @@ def getGovernmentID(self, government, addUnknown=None): def getGovernments(self): cur = self.cursor() - cur.execute( "select id, Name from governments " ) + cur.execute("select id, Name from governments ") result = cur.fetchall() @@ -1236,5 +1254,5 @@ def getGovernments(self): if __name__ == '__main__': - #mydb = db() + # mydb = db() pass diff --git a/elite/dealsroute.py b/elite/dealsroute.py index bf35878..7ac1d85 100644 --- a/elite/dealsroute.py +++ b/elite/dealsroute.py @@ -5,16 +5,17 @@ @author: mEDI ''' -from datetime import datetime, date, time, timedelta +from datetime import datetime, timedelta import elite + class route(object): ''' calculate a A-B-A or A-B(x) route, set speed control and result details over limitCalc() ''' - mydb=None + mydb = None deals = [] forceHops = None locked = None @@ -23,16 +24,16 @@ class route(object): options["startSystem"] = None options["tradingHops"] = 2 # +1 for the back hop options["maxJumpDistance"] = 16.3 - options["maxDist"] = options["maxJumpDistance"]*3 # max distace for B system - options["maxSearchRange"] = options["maxJumpDistance"]*5 # on start search used + options["maxDist"] = options["maxJumpDistance"] * 3 # max distace for B system + options["maxSearchRange"] = options["maxJumpDistance"] * 5 # on start search used options["maxStarDist"] = 1300 options["maxAge"] = 14 # max data age in days options["minTradeProfit"] = 1000 # only to minimize results (speedup) options["minStock"] = 50000 # > 10000 = stable route > 50000 = extrem stable route and faster results - options["resultLimit"] = None # calculated by self.limitCalc() - options["padsize"] = None # None = Any, allow a list + options["resultLimit"] = None # calculated by self.limitCalc() + options["padsize"] = None # None = Any, allow a list - maxAgeDate = None # calculated by setMaxAgeDate() + maxAgeDate = None # calculated by setMaxAgeDate() elitetime = None def __init__(self, mydb): @@ -58,24 +59,24 @@ def getStationA(self, route, hopID): if hopID == 0: return route["path"][hopID]["StationA"] - return route["path"][hopID-1]["StationB"] + return route["path"][hopID - 1]["StationB"] def getStationB(self, route, hopID): if hopID < len(route["path"]): return route["path"][hopID]["StationB"] - else: # back to start + else: # back to start return route["path"][0]["StationA"] def getSystemA(self, route, hopID): if hopID == 0: return route["path"][hopID]["SystemA"] - return route["path"][hopID-1]["SystemB"] + return route["path"][hopID - 1]["SystemB"] - def getSystemB(self,route,hopID): + def getSystemB(self, route, hopID): if hopID < len(route["path"]): return route["path"][hopID]["SystemB"] - else: # back to start + else: # back to start return route["path"][0]["SystemA"] def getRouteIDbyPointer(self, deal): @@ -90,7 +91,7 @@ def getPriceID(self, route, hopID): def limitCalc(self, accuracy=0): ''' ["normal","fast","nice","slow","all"] ''' - maxResults = 100000 # normal + maxResults = 100000 # normal if accuracy == 1: maxResults = 5000 @@ -100,15 +101,15 @@ def limitCalc(self, accuracy=0): maxResults = 4000000 if self.forceHops: - maxResults = maxResults*2 - self.options["resultLimit"] = round( maxResults**(1.0 / self.options["tradingHops"] )) #max results = 1000000 = resultLimit^tradingHops + maxResults = maxResults * 2 + self.options["resultLimit"] = round(maxResults ** (1.0 / self.options["tradingHops"])) # max results = 1000000 = resultLimit^tradingHops if accuracy == 4: self.options["resultLimit"] = 999999 def setMaxAgeDate(self): - self.maxAgeDate = datetime.utcnow() - timedelta(days = self.options["maxAge"] ) + self.maxAgeDate = datetime.utcnow() - timedelta(days=self.options["maxAge"]) def calcRoute(self): self.deals = [] @@ -121,18 +122,18 @@ def calcRoute(self): self.calcRating() def findStartDeal(self): - startdeals = self.mydb.getBestDealsinDistance( self.options["startSystem"], self.options["maxDist"], self.options["maxSearchRange"], self.maxAgeDate, self.options["maxStarDist"], self.options["minTradeProfit"], self.options["minStock"], self.options["resultLimit"], self.options["padsize"]) + startdeals = self.mydb.getBestDealsinDistance(self.options["startSystem"], self.options["maxDist"], self.options["maxSearchRange"], self.maxAgeDate, self.options["maxStarDist"], self.options["minTradeProfit"], self.options["minStock"], self.options["resultLimit"], self.options["padsize"]) for deal in startdeals: - self.deals.append({ "profit":0, "time":0 , "path":[deal], "backToStartDeal":None, "activeRoute":None, "lastHop":None}) + self.deals.append({ "profit": 0, "time": 0, "path": [deal], "backToStartDeal": None, "activeRoute": None, "lastHop": None}) def findHops(self): - for deep in range( 1, self.options["tradingHops"] ): - print("deep", deep+1) + for deep in range(1, self.options["tradingHops"]): + print("deep", deep + 1) for deal in self.deals[:]: if deep == len(deal["path"]): - delsX = self.mydb.getBestDealsFromStationInDistance(deal["path"][ len(deal["path"])-1 ]["StationBID"], self.options["maxDist"], self.maxAgeDate, self.options["maxStarDist"], self.options["minTradeProfit"], self.options["minStock"], self.options["resultLimit"], self.options["padsize"]) + delsX = self.mydb.getBestDealsFromStationInDistance(deal["path"][ len(deal["path"]) - 1 ]["StationBID"], self.options["maxDist"], self.maxAgeDate, self.options["maxStarDist"], self.options["minTradeProfit"], self.options["minStock"], self.options["resultLimit"], self.options["padsize"]) for dealX in delsX: ''' if same item in route already exist?''' ifExists = None @@ -143,16 +144,17 @@ def findHops(self): if not ifExists: dealnew = deal.copy() - dealnew["path"] = list(deal["path"]) #deepcopy do not work + dealnew["path"] = list(deal["path"]) # deepcopy do not work dealnew["path"].append(dealX) self.deals.append(dealnew) - elif self.forceHops : + elif self.forceHops: self.deals.remove(deal) def delToShortRoutes(self): - if not self.forceHops: return + if not self.forceHops: + return for deal in self.deals[:]: if len(deal["path"]) < self.forceHops: @@ -160,7 +162,7 @@ def delToShortRoutes(self): def findBackToStartDeals(self): for deal in self.deals: - backdeals = self.mydb.getDealsFromTo( deal["path"][ len(deal["path"])-1 ]["StationBID"], deal["path"][0]["StationAID"], self.maxAgeDate, 1000) + backdeals = self.mydb.getDealsFromTo(deal["path"][ len(deal["path"]) - 1 ]["StationBID"], deal["path"][0]["StationAID"], self.maxAgeDate, 1000) if backdeals: deal["backToStartDeal"] = backdeals[0] @@ -175,84 +177,83 @@ def calcRating(self): deal["time"] += self.elitetime.calcTimeFromTo(step["SystemAID"], step["StationBID"], step["SystemBID"]) Systembefore = step["SystemBID"] else: - deal["time"] += self.elitetime.calcTimeFromTo(Systembefore , step["StationBID"], step["SystemBID"]) + deal["time"] += self.elitetime.calcTimeFromTo(Systembefore, step["StationBID"], step["SystemBID"]) Systembefore = step["SystemBID"] # add back to start time - deal["time"] += self.elitetime.calcTimeFromTo(Systembefore , deal["path"][0]["StationAID"], deal["path"][0]["SystemAID"]) + deal["time"] += self.elitetime.calcTimeFromTo(Systembefore, deal["path"][0]["StationAID"], deal["path"][0]["SystemAID"]) if deal["backToStartDeal"]: deal["profit"] += deal["backToStartDeal"]["profit"] lapsInHour = int(3600 / deal["time"]) # round down - profitHour = int(3600.0 / deal["time"] * deal["profit"]) #hmm mit lapsInHour oder mit hochrechnung rechnen? - deal["profitAverage"] = round(deal["profit"] / (len(deal["path"]) + 1),0) + profitHour = int(3600.0 / deal["time"] * deal["profit"]) # hmm mit lapsInHour oder mit hochrechnung rechnen? + deal["profitAverage"] = round(deal["profit"] / (len(deal["path"]) + 1), 0) deal["profitHour"] = profitHour deal["lapsInHour"] = lapsInHour self.sortDealsByProfitH() - def sortDealsByProfitH(self, order=True): - self.locked = True - self.deals = sorted(self.deals , key=lambda deal: deal["profitHour"], reverse=order) - self.locked = None + def sortDealsByProfitH(self, order=True): + self.locked = True + self.deals = sorted(self.deals, key=lambda deal: deal["profitHour"], reverse=order) + self.locked = None - def sortDealsByProfit(self, order=True): - self.locked = True - self.deals = sorted(self.deals , key=lambda deal: deal["profit"], reverse=order) - self.locked = None + def sortDealsByProfit(self, order=True): + self.locked = True + self.deals = sorted(self.deals, key=lambda deal: deal["profit"], reverse=order) + self.locked = None - def sortDealsByProfitAverage(self, order=True): - self.locked = True - self.deals = sorted(self.deals , key=lambda deal: deal["profitAverage"], reverse=order) - self.locked = None + def sortDealsByProfitAverage(self, order=True): + self.locked = True + self.deals = sorted(self.deals, key=lambda deal: deal["profitAverage"], reverse=order) + self.locked = None - def sortDealsByLapTime(self, order=True): - self.locked = True - self.deals = sorted(self.deals , key=lambda deal: deal["time"], reverse=order) - self.locked = None + def sortDealsByLapTime(self, order=True): + self.locked = True + self.deals = sorted(self.deals, key=lambda deal: deal["time"], reverse=order) + self.locked = None - def sortDealsByStartDist(self, order=True): - self.locked = True - self.deals = sorted(self.deals , key=lambda deal: deal["path"][0]["startDist"], reverse=order) - self.locked = None + def sortDealsByStartDist(self, order=True): + self.locked = True + self.deals = sorted(self.deals, key=lambda deal: deal["path"][0]["startDist"], reverse=order) + self.locked = None def printList(self): print("routes found", len(self.deals)) for i, deal in enumerate(self.deals): - if i >= 40: break + if i >= 40: + break timeT = "%s:%s" % (divmod(deal["time"] * deal["lapsInHour"], 60)) timeL = "%s:%s" % (divmod(deal["time"], 60)) - print("\n%d. profit: %d profit/h:%d Laps/h: %d/%s LapTime: %s (Start dist: %s ly)" % (i + 1, deal["profit"], deal["profitHour"], deal["lapsInHour"], timeT, timeL, deal["path"][0]["startDist"])) + print("\n%d. profit: %d profit/h:%d Laps/h: %d/%s LapTime: %s (Start dist: %s ly)" % (i + 1, deal["profit"], deal["profitHour"], deal["lapsInHour"], timeT, timeL, deal["path"][0]["startDist"])) - before = { "StationB":deal["path"][0]["StationA"], "SystemB":deal["path"][0]["SystemA"], "StarDist":deal["path"][0]["stationA.StarDist"], "refuel":deal["path"][0]["stationA.refuel"] } + before = { "StationB": deal["path"][0]["StationA"], "SystemB": deal["path"][0]["SystemA"], "StarDist": deal["path"][0]["stationA.StarDist"], "refuel": deal["path"][0]["stationA.refuel"] } for d in deal["path"]: - #print(d.keys()) - print("\t%s : %s (%d ls) (%s buy:%d sell:%d profit:%d) (%s ly)-> %s:%s" % (before["SystemB"], before["StationB"], before["StarDist"] , d["itemName"],d["StationSell"], d["StationBuy"], d["profit"], d["dist"],d["SystemB"],d["StationB"] ) ) + # print(d.keys()) + print("\t%s : %s (%d ls) (%s buy:%d sell:%d profit:%d) (%s ly)-> %s:%s" % (before["SystemB"], before["StationB"], before["StarDist"], d["itemName"], d["StationSell"], d["StationBuy"], d["profit"], d["dist"], d["SystemB"], d["StationB"])) if before["refuel"] != 1: print("\t\tWarning: %s have no refuel!?" % before["StationB"]) before = d - backdist = self.mydb.getDistanceFromTo(deal["path"][0]["SystemAID"] , deal["path"][ len(deal["path"])-1 ]["SystemBID"]) + backdist = self.mydb.getDistanceFromTo(deal["path"][0]["SystemAID"], deal["path"][ len(deal["path"]) - 1 ]["SystemBID"]) if deal["backToStartDeal"]: - #print(deal["backToStartDeal"].keys()) - print("\t%s : %s (%d ls) (%s buy:%d sell:%d profit:%d) (%s ly)-> %s:%s" % (before["SystemB"], deal["backToStartDeal"]["fromStation"] , before["StarDist"], deal["backToStartDeal"]["itemName"], deal["backToStartDeal"]["StationSell"],deal["backToStartDeal"]["StationBuy"], deal["backToStartDeal"]["profit"], backdist, deal["path"][0]["SystemA"], deal["path"][0]["StationA"] ) ) + # print(deal["backToStartDeal"].keys()) + print("\t%s : %s (%d ls) (%s buy:%d sell:%d profit:%d) (%s ly)-> %s:%s" % (before["SystemB"], deal["backToStartDeal"]["fromStation"], before["StarDist"], deal["backToStartDeal"]["itemName"], deal["backToStartDeal"]["StationSell"], deal["backToStartDeal"]["StationBuy"], deal["backToStartDeal"]["profit"], backdist, deal["path"][0]["SystemA"], deal["path"][0]["StationA"])) else: - print("\tno back deal (%s ly) ->%s : %s" % (backdist, deal["path"][0]["SystemA"], deal["path"][0]["StationA"] )) + print("\tno back deal (%s ly) ->%s : %s" % (backdist, deal["path"][0]["SystemA"], deal["path"][0]["StationA"])) if before["refuel"] != 1: print("\t\tWarning: %s have no refuel!?" % before["StationB"]) - print("\noptions: startSystem:%s, tradingHops:%d, maxDist:%d, maxJumpDistance:%d, maxSearchRange:%d, maxStarDist:%d, maxAge:%d, minTradeProfit:%d, minStock:%d, resultLimit:%d" - % (self.options["startSystem"], self.options["tradingHops"], self.options["maxDist"], self.options["maxJumpDistance"], self.options["maxSearchRange"], self.options["maxStarDist"], self.options["maxAge"], self.options["minTradeProfit"], self.options["minStock"], self.options["resultLimit"]) ) - - \ No newline at end of file + print("\noptions: startSystem:%s, tradingHops:%d, maxDist:%d, maxJumpDistance:%d, maxSearchRange:%d, maxStarDist:%d, maxAge:%d, minTradeProfit:%d, minStock:%d, resultLimit:%d" + % (self.options["startSystem"], self.options["tradingHops"], self.options["maxDist"], self.options["maxJumpDistance"], self.options["maxSearchRange"], self.options["maxStarDist"], self.options["maxAge"], self.options["minTradeProfit"], self.options["minStock"], self.options["resultLimit"])) diff --git a/elite/loader/edsc.py b/elite/loader/edsc.py index a9ef61e..174d1b9 100644 --- a/elite/loader/edsc.py +++ b/elite/loader/edsc.py @@ -7,9 +7,7 @@ @author: mEDI ''' -import os -from datetime import datetime, date, time, timedelta import json import gzip @@ -17,13 +15,13 @@ import sys try: - from _version import __buildid__ , __version__, __builddate__, __toolname__, __useragent__ + from _version import __buildid__, __version__, __builddate__, __toolname__, __useragent__ except ImportError: __buildid__ = "UNKNOWN" __version__ = "UNKNOWN" __builddate__ = "NONE" __toolname__ = "mEDI s Elite Tools" - __useragent__ = '%s/%s (%s) %s(%s)' % (__toolname__.replace(" ", ""), __version__, sys.platform, __buildid__, __builddate__.replace(" ", "").replace("-", "").replace(":", "")) + __useragent__ = '%s/%s (%s) %s(%s)' % (__toolname__.replace(" ", ""), __version__, sys.platform, __buildid__, __builddate__.replace(" ", "").replace("-", "").replace(":", "")) try: import urllib2 @@ -33,6 +31,7 @@ __edscAPIurl__ = 'http://edstarcoordinator.com/api.asmx' __test__ = 'false' + class edsc(object): @@ -43,18 +42,17 @@ def __init__(self): def getSystemCoords(self, systemname): apiPath = "GetSystems" apiurl = "%s/%s" % (__edscAPIurl__, apiPath) - postrequest = { - "data": { + postrequest = {"data": { "ver": 2, 'test': __test__, "outputmode": 2, - "filter":{ - "knownstatus":1, + "filter": { + "knownstatus": 1, "cr": 1, # 1 or 5? "systemname": systemname, "date": '1990-01-01' } - } + } } josnData = self.sendAPIRequest(apiurl, postrequest) @@ -78,13 +76,13 @@ def submitDistances(self, targetSystemname, commander, refsystems ): apiurl = "%s/%s" % (__edscAPIurl__, apiPath) postrequest = { "data": { - "ver": 2, - 'test': __test__, - "commander": commander, - "p0":{ "name": targetSystemname }, + "ver": 2, + 'test': __test__, + "commander": commander, + "p0": { "name": targetSystemname }, "refs": refsystems, } - } + } # print(postrequest) josnData = self.sendAPIRequest(apiurl, postrequest) @@ -114,8 +112,8 @@ def sendAPIRequest(self, apiurl, postrequest): response = urllib2.urlopen(request) except: e = sys.exc_info() - print("sendAPIRequest except",e) - return {"error":e} + print("sendAPIRequest except", e) + return {"error": e} if response.info().get('Content-Encoding') == 'gzip': # print("gzip ok") @@ -128,5 +126,4 @@ def sendAPIRequest(self, apiurl, postrequest): result = f.read() josnData = json.loads(result.decode('utf-8')) - return josnData - + return josnData diff --git a/elite/location.py b/elite/location.py index 55fe837..035af60 100644 --- a/elite/location.py +++ b/elite/location.py @@ -10,6 +10,7 @@ import re from datetime import datetime + class location(object): ''' location.getLocation() return the current system @@ -26,7 +27,7 @@ def __init__(self, mydb): Constructor ''' self.mydb = mydb - self.eliteLogDir = self.mydb.getConfig( 'EliteLogDir' ) + self.eliteLogDir = self.mydb.getConfig('EliteLogDir') def getLocation(self): @@ -38,40 +39,40 @@ def getLocation(self): self.readLog(logfile) if not self.location: - self.location = "" + self.location = "" return self.location def getLastLog(self): - if not os.path.isdir( self.eliteLogDir ): + if not os.path.isdir(self.eliteLogDir): print("Warning: EliteLogDir:'%s' does not exist" % self.eliteLogDir) - return (None,None) + return (None, None) logfiles = [] for f in os.listdir(self.eliteLogDir): - if os.path.isfile( os.path.join(self.eliteLogDir, f) ) and len(f) > 4 and re.match(r"^netLog.*\.log$" ,f): + if os.path.isfile(os.path.join(self.eliteLogDir, f)) and len(f) > 4 and re.match(r"^netLog.*\.log$", f): path = os.path.join(self.eliteLogDir, f) - cDate = datetime.fromtimestamp( os.path.getmtime(path) ) + cDate = datetime.fromtimestamp(os.path.getmtime(path)) - logfiles.append( [cDate, path] ) + logfiles.append([cDate, path]) - logfiles = sorted(logfiles , key=lambda f: f[0], reverse=True) + logfiles = sorted(logfiles, key=lambda f: f[0], reverse=True) - return (logfiles[0][0],logfiles[0][1] ) + return (logfiles[0][0], logfiles[0][1]) - def readLog(self, logfile ): + def readLog(self, logfile): fh = open(logfile, 'rb') if self._lastFile == logfile and self._lastPos: - fh.seek(self._lastPos,0) + fh.seek(self._lastPos, 0) else: self._lastFile = logfile for line in fh: - locationma = re.search("^\{\d{2}:\d{2}:\d{2}\} System\:\d+\((.*?)\) .*", line.decode(encoding='ascii',errors='replace') ) + locationma = re.search("^\{\d{2}:\d{2}:\d{2}\} System\:\d+\((.*?)\) .*", line.decode(encoding='ascii', errors='replace')) if locationma: diff --git a/elite/time.py b/elite/time.py index dada334..a134e45 100644 --- a/elite/time.py +++ b/elite/time.py @@ -3,10 +3,9 @@ @author: mEDI ''' -from elite import db +from elite import db import math -# import elite class elitetime(object): ''' @@ -67,7 +66,7 @@ def calcTimeFromTo(self, systemAID, stationBID=None, SystemBID=None): else: print("warning: %d %s have no StarDist" % (stationBID, stationB["Station"])) - #docking time + # docking time if stationB["max_pad_size"] == "L": time += self.landingTime_station else: @@ -76,7 +75,7 @@ def calcTimeFromTo(self, systemAID, stationBID=None, SystemBID=None): else: print("warning: no station data!?", systemAID, stationBID, SystemBID) - return int(round(time, 0)) + return int(round(time, 0)) def calcTimeForDistance(self, dist): t = None diff --git a/gui/commodities_finder.py b/gui/commodities_finder.py index 60739da..0c4eec7 100644 --- a/gui/commodities_finder.py +++ b/gui/commodities_finder.py @@ -15,6 +15,7 @@ __internalName__ = "CoFi" __statusTip__ = "Open A %s Window" % __toolname__ + class tool(QtGui.QWidget): main = None mydb = None @@ -44,7 +45,7 @@ def getWideget(self): self.onlyLocation.setChecked(True) else: self.onlyLocation.setChecked(False) - self.onlyLocation.stateChanged.connect( self.searchItem ) + self.onlyLocation.stateChanged.connect(self.searchItem) gridLayout.addWidget(self.onlyLocation, 1, 0) @@ -52,7 +53,7 @@ def getWideget(self): if self.mydb.getConfig("option_cf_onlyLpadsize"): self.onlyLpadsize.setChecked(True) self.onlyLpadsize.setToolTip("Find only stations with a large landingpad") - self.onlyLpadsize.stateChanged.connect( self.searchItem ) + self.onlyLpadsize.stateChanged.connect(self.searchItem) gridLayout.addWidget(self.onlyLpadsize, 2, 0) @@ -72,11 +73,11 @@ def getWideget(self): allegiances = self.mydb.getAllegiances() self.allegiancesList = [] - self.allegiancesComboBox.addItem( "Any" ) + self.allegiancesComboBox.addItem("Any") self.allegiancesList.append(None) for allegiance in allegiances: - self.allegiancesComboBox.addItem( allegiance["Name"] ) + self.allegiancesComboBox.addItem(allegiance["Name"]) self.allegiancesList.append(allegiance["id"]) if self.mydb.getConfig("option_cf_allegiances"): self.allegiancesComboBox.setCurrentIndex(self.mydb.getConfig("option_cf_allegiances")) @@ -103,7 +104,7 @@ def getWideget(self): self.buySellComboBox = QtGui.QComboBox() buySellList = ["Any", "Buy", "Sell"] for item in buySellList: - self.buySellComboBox.addItem( item ) + self.buySellComboBox.addItem(item) if self.mydb.getConfig("option_cf_buySell"): self.buySellComboBox.setCurrentIndex(self.mydb.getConfig("option_cf_buySell")) self.buySellComboBox.currentIndexChanged.connect(self.searchItem) @@ -117,11 +118,11 @@ def getWideget(self): governments = self.mydb.getGovernments() self.governmentsList = [] - self.governmentsComboBox.addItem( "Any" ) + self.governmentsComboBox.addItem("Any") self.governmentsList.append(None) for government in governments: - self.governmentsComboBox.addItem( government["Name"] ) + self.governmentsComboBox.addItem(government["Name"]) self.governmentsList.append(government["id"]) if self.mydb.getConfig("option_cf_governments"): self.governmentsComboBox.setCurrentIndex(self.mydb.getConfig("option_cf_governments")) @@ -136,11 +137,11 @@ def getWideget(self): self.maxStartDistSpinBox.setSuffix("ls") self.maxStartDistSpinBox.setSingleStep(10) self.maxStartDistSpinBox.setAlignment(QtCore.Qt.AlignRight) - maxStarDist = self.mydb.getConfig( 'option_cf_maxStarDist' ) + maxStarDist = self.mydb.getConfig('option_cf_maxStarDist') if maxStarDist: - self.maxStartDistSpinBox.setValue( maxStarDist ) + self.maxStartDistSpinBox.setValue(maxStarDist) else: - self.maxStartDistSpinBox.setValue( 1500 ) + self.maxStartDistSpinBox.setValue(1500) gridLayout.addWidget(label, 2, 8) gridLayout.addWidget(self.maxStartDistSpinBox, 2, 9) @@ -159,7 +160,7 @@ def getWideget(self): locationLabel = QtGui.QLabel("Location:") self.locationlineEdit = guitools.LineEdit() - self.locationlineEdit.setText( self.main.location.getLocation() ) + self.locationlineEdit.setText(self.main.location.getLocation()) self.locationlineEdit.textChanged.connect(self.searchItem) @@ -168,11 +169,11 @@ def getWideget(self): items = self.mydb.getAllItemNames() self.itemList = [] - self.itemComboBox.addItem( "Any" ) + self.itemComboBox.addItem("Any") self.itemList.append(None) for item in items: - self.itemComboBox.addItem( item["name"] ) + self.itemComboBox.addItem(item["name"]) self.itemList.append(item["id"]) if self.mydb.getConfig("option_cf_item"): self.itemComboBox.setCurrentIndex(self.mydb.getConfig("option_cf_item")) @@ -181,7 +182,7 @@ def getWideget(self): self.showOptions = QtGui.QCheckBox("Show Options") if self.mydb.getConfig("option_cf_showOptions") != 0: self.showOptions.setChecked(True) - self.showOptions.stateChanged.connect( self.optionsGroupBoxToggleViewAction ) + self.showOptions.stateChanged.connect(self.optionsGroupBoxToggleViewAction) self.searchbutton = QtGui.QPushButton("Search") @@ -190,7 +191,7 @@ def getWideget(self): layout = QtGui.QHBoxLayout() - layout.setContentsMargins(0,0,0,0) + layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(locationLabel) layout.addWidget(locationButton) @@ -206,7 +207,7 @@ def getWideget(self): locationGroupBox.setFlat(True) locationGroupBox.setStyleSheet("""QGroupBox {border:0;margin:0;padding:0;} margin:0;padding:0;""") - #locationGroupBox.setFlat(True) + # locationGroupBox.setFlat(True) locationGroupBox.setLayout(layout) @@ -231,7 +232,7 @@ def getWideget(self): vGroupBox.setFlat(True) layout = QtGui.QVBoxLayout() - layout.setContentsMargins(6,2,6,6) + layout.setContentsMargins(6, 2, 6, 6) layout.addWidget(self.optionsGroupBox) layout.addWidget(locationGroupBox) @@ -267,27 +268,27 @@ def createActions(self): def setCurentLocation(self): - self.locationlineEdit.setText( self.main.location.getLocation() ) + self.locationlineEdit.setText(self.main.location.getLocation()) def saveOptions(self): - self.mydb.setConfig( 'option_cf_onlyLpadsize', self.onlyLpadsize.isChecked() ) - self.mydb.setConfig( 'option_cf_onlyLocation', self.onlyLocation.isChecked() ) - self.mydb.setConfig( 'option_cf_maxSearchRange', self.searchRangeSpinBox.value() ) - self.mydb.setConfig( 'option_cf_maxAge', self.maxAgeSpinBox.value() ) - self.mydb.setConfig( 'option_cf_maxStarDist', self.maxStartDistSpinBox.value() ) - self.mydb.setConfig( 'option_cf_showOptions', self.showOptions.isChecked() ) - self.mydb.setConfig( 'option_cf_item', self.itemComboBox.currentIndex() ) - self.mydb.setConfig( 'option_cf_buySell', self.buySellComboBox.currentIndex() ) - self.mydb.setConfig( 'option_cf_allegiances', self.allegiancesComboBox.currentIndex() ) - self.mydb.setConfig( 'option_cf_governments', self.governmentsComboBox.currentIndex() ) + self.mydb.setConfig('option_cf_onlyLpadsize', self.onlyLpadsize.isChecked()) + self.mydb.setConfig('option_cf_onlyLocation', self.onlyLocation.isChecked()) + self.mydb.setConfig('option_cf_maxSearchRange', self.searchRangeSpinBox.value()) + self.mydb.setConfig('option_cf_maxAge', self.maxAgeSpinBox.value()) + self.mydb.setConfig('option_cf_maxStarDist', self.maxStartDistSpinBox.value()) + self.mydb.setConfig('option_cf_showOptions', self.showOptions.isChecked()) + self.mydb.setConfig('option_cf_item', self.itemComboBox.currentIndex()) + self.mydb.setConfig('option_cf_buySell', self.buySellComboBox.currentIndex()) + self.mydb.setConfig('option_cf_allegiances', self.allegiancesComboBox.currentIndex()) + self.mydb.setConfig('option_cf_governments', self.governmentsComboBox.currentIndex()) sectionPosList = [] - for i in range( self.listView.header().count() ): - sectionPosList.append( self.listView.header().logicalIndex( i ) ) + for i in range(self.listView.header().count()): + sectionPosList.append(self.listView.header().logicalIndex(i)) - sectionPos = ",".join( map( str, sectionPosList ) ) - self.mydb.setConfig( 'option_cf.header.sectionPos', sectionPos ) + sectionPos = ",".join(map(str, sectionPosList)) + self.mydb.setConfig('option_cf.header.sectionPos', sectionPos) def searchItem(self): @@ -296,10 +297,10 @@ def searchItem(self): if not self.listView.header().count(): firstrun = True - self.headerList = ["System", "Permit","StarDist", "Station", "Distance", "Item", "Stock", "Buy", "Demand", "Sell", "Age", ""] + self.headerList = ["System", "Permit", "StarDist", "Station", "Distance", "Item", "Stock", "Buy", "Demand", "Sell", "Age", ""] model = QtGui.QStandardItemModel(0, len(self.headerList), self) - for x,column in enumerate(self.headerList): + for x, column in enumerate(self.headerList): model.setHeaderData(x, QtCore.Qt.Horizontal, column) location = self.locationlineEdit.text() @@ -313,58 +314,58 @@ def searchItem(self): else: distance = self.searchRangeSpinBox.value() - maxAgeDate = datetime.utcnow() - timedelta(days = self.maxAgeSpinBox.value() ) + maxAgeDate = datetime.utcnow() - timedelta(days=self.maxAgeSpinBox.value()) itemID = self.itemList[ self.itemComboBox.currentIndex() ] - items = self.mydb.getPricesInDistance( systemID, distance, self.maxStartDistSpinBox.value(), maxAgeDate, itemID, self.onlyLpadsize.isChecked(), self.buySellComboBox.currentIndex(), self.allegiancesComboBox.currentIndex(), self.governmentsComboBox.currentIndex()) + items = self.mydb.getPricesInDistance(systemID, distance, self.maxStartDistSpinBox.value(), maxAgeDate, itemID, self.onlyLpadsize.isChecked(), self.buySellComboBox.currentIndex(), self.allegiancesComboBox.currentIndex(), self.governmentsComboBox.currentIndex()) for item in items: model.insertRow(0) - model.setData(model.index(0, self.headerList.index("System") ), item["System"]) + model.setData(model.index(0, self.headerList.index("System")), item["System"]) - model.setData(model.index(0, self.headerList.index("Permit") ), "No" if not item["permit"] else "Yes" ) + model.setData(model.index(0, self.headerList.index("Permit")), "No" if not item["permit"] else "Yes") model.item(0, self.headerList.index("Permit")).setTextAlignment(QtCore.Qt.AlignCenter) - model.setData(model.index(0, self.headerList.index("StarDist") ), item["StarDist"]) + model.setData(model.index(0, self.headerList.index("StarDist")), item["StarDist"]) model.item(0, self.headerList.index("StarDist")).setTextAlignment(QtCore.Qt.AlignRight) - model.setData(model.index(0, self.headerList.index("Station") ), item["Station"]) + model.setData(model.index(0, self.headerList.index("Station")), item["Station"]) - if "dist" in item.keys() : - model.setData(model.index(0, self.headerList.index("Distance") ), item["dist"]) + if "dist" in item.keys(): + model.setData(model.index(0, self.headerList.index("Distance")), item["dist"]) else: - model.setData(model.index(0, self.headerList.index("Distance") ), 0) + model.setData(model.index(0, self.headerList.index("Distance")), 0) model.item(0, self.headerList.index("Distance")).setTextAlignment(QtCore.Qt.AlignRight) - model.setData(model.index(0, self.headerList.index("Item") ), item["name"]) + model.setData(model.index(0, self.headerList.index("Item")), item["name"]) - model.setData(model.index(0, self.headerList.index("Stock") ), item["Stock"]) + model.setData(model.index(0, self.headerList.index("Stock")), item["Stock"]) model.item(0, self.headerList.index("Stock")).setTextAlignment(QtCore.Qt.AlignRight) - model.setData(model.index(0, self.headerList.index("Buy") ), item["StationSell"]) + model.setData(model.index(0, self.headerList.index("Buy")), item["StationSell"]) model.item(0, self.headerList.index("Buy")).setTextAlignment(QtCore.Qt.AlignRight) - model.setData(model.index(0, self.headerList.index("Demand") ), item["Dammand"]) + model.setData(model.index(0, self.headerList.index("Demand")), item["Dammand"]) model.item(0, self.headerList.index("Demand")).setTextAlignment(QtCore.Qt.AlignRight) - model.setData(model.index(0, self.headerList.index("Sell") ), item["StationBuy"]) + model.setData(model.index(0, self.headerList.index("Sell")), item["StationBuy"]) model.item(0, self.headerList.index("Sell")).setTextAlignment(QtCore.Qt.AlignRight) - model.setData(model.index(0, self.headerList.index("Age") ), guitools.convertDateimeToAgeStr(item["age"]) ) + model.setData(model.index(0, self.headerList.index("Age")), guitools.convertDateimeToAgeStr(item["age"])) model.item(0, self.headerList.index("Age")).setTextAlignment(QtCore.Qt.AlignCenter) self.listView.setModel(model) if firstrun: - sectionPos = self.mydb.getConfig( 'option_cf.header.sectionPos' ) + sectionPos = self.mydb.getConfig('option_cf.header.sectionPos') if sectionPos: - sectionPosList = sectionPos.strip().split( ',' ) - for i,pos in enumerate(sectionPosList): - self.listView.header().moveSection( self.listView.header().visualIndex( int(pos) ) , i ) + sectionPosList = sectionPos.strip().split(',') + for i, pos in enumerate(sectionPosList): + self.listView.header().moveSection(self.listView.header().visualIndex(int(pos)), i) - self.listView.sortByColumn( self.headerList.index("Distance"), PySide.QtCore.Qt.SortOrder.AscendingOrder ) + self.listView.sortByColumn(self.headerList.index("Distance"), PySide.QtCore.Qt.SortOrder.AscendingOrder) - for i in range(0, len(self.headerList) ): + for i in range(0, len(self.headerList)): self.listView.resizeColumnToContents(i) diff --git a/gui/dbworker.py b/gui/dbworker.py index 664d196..65828da 100644 --- a/gui/dbworker.py +++ b/gui/dbworker.py @@ -8,7 +8,7 @@ import timeit from datetime import datetime import sys -from PySide import QtCore, QtGui +from PySide import QtCore import threading databaseAccessWait = QtCore.QWaitCondition() @@ -19,21 +19,25 @@ processPos = 0 processMsg = None + class statusMsg(object): processCount = 0 processPos = 0 msg = None processMsg = None + + def __init__(self, msg=None, processPos=None, processCount=None): self.processCount = processCount self.processPos = processPos self.msg = msg - + + class _updateDBchild(threading.Thread): ''' updatedb child job ''' - name = "updateDBchild" + name = "updateDBchild" def sendMsg(self, newmsg): global statusbarMsg @@ -46,8 +50,10 @@ def sendProcessMsg(self, newmsg, pos=None, count=None): mutex.lock() processMsg = newmsg - if pos: processPos = pos - if count: processCount = count + if pos: + processPos = pos + if count: + processCount = count mutex.unlock() @@ -63,36 +69,36 @@ def run(self): databaseLock = True mutex.unlock() - self.sendProcessMsg( "open db" ,0 ,0) + self.sendProcessMsg("open db", 0, 0) starttime = timeit.default_timer() self.mydb = elite.db(guiMode=True) - self.sendProcessMsg( "Start Update", 0, self.mydb.loaderCount ) + self.sendProcessMsg("Start Update", 0, self.mydb.loaderCount) self.mydb.sendProcessMsg = self.sendProcessMsg try: - self.mydb.updateData( ) + self.mydb.updateData() except: e = sys.exc_info() - print("except",e) + print("except", e) self.close() return - if self._active != True: + if self._active is not True: self.close() return self.mydb.calcDealsInDistancesCacheQueue() - if self._active != True: + if self._active is not True: self.close() return self.mydb.sendProcessMsg = None - self.sendProcessMsg( "%s finished %ss" % ( datetime.now().strftime("%H:%M:%S"), round(timeit.default_timer() - starttime, 2) ) ) + self.sendProcessMsg("%s finished %ss" % (datetime.now().strftime("%H:%M:%S"), round(timeit.default_timer() - starttime, 2))) self.close() @@ -108,7 +114,8 @@ def close(self): def stop(self): self._active = False self.mydb._active = False - + + class new(object): ''' class to do long woking jobs in background @@ -125,7 +132,7 @@ def start(self): self.waitQuit() self._updatedb = _updateDBchild() - self._updatedb.daemon=True + self._updatedb.daemon = True self._updatedb.setName("updateDBchildThread") self._updatedb.start() @@ -181,4 +188,3 @@ def getStatusbarMsg(self): mutex.unlock() return msg - \ No newline at end of file diff --git a/gui/deals_from_to.py b/gui/deals_from_to.py index de218fb..73adafc 100644 --- a/gui/deals_from_to.py +++ b/gui/deals_from_to.py @@ -8,7 +8,6 @@ from PySide import QtCore, QtGui import PySide import elite -import timeit from datetime import datetime, timedelta import gui.guitools as guitools @@ -17,6 +16,7 @@ __internalName__ = "DeFrToFi" __statusTip__ = "Open A %s Window" % __toolname__ + class tool(QtGui.QWidget): main = None mydb = elite.db @@ -44,7 +44,7 @@ def getWideget(self): self.autoUpdateLocation = QtGui.QCheckBox("Auto Switch/Location") self.autoUpdateLocation.setChecked(False) - self.autoUpdateLocation.stateChanged.connect( self.updateLocation ) + self.autoUpdateLocation.stateChanged.connect(self.updateLocation) gridLayout.addWidget(self.autoUpdateLocation, 1, 0) @@ -54,9 +54,9 @@ def getWideget(self): self.minProfitSpinBox.setSuffix("cr") self.minProfitSpinBox.setSingleStep(100) self.minProfitSpinBox.setAlignment(QtCore.Qt.AlignRight) - minTradeProfit = self.mydb.getConfig( 'option_dft_minProfit' ) + minTradeProfit = self.mydb.getConfig('option_dft_minProfit') if minTradeProfit: - self.minProfitSpinBox.setValue( minTradeProfit ) + self.minProfitSpinBox.setValue(minTradeProfit) gridLayout.addWidget(label, 1, 2) gridLayout.addWidget(self.minProfitSpinBox, 1, 3) @@ -66,11 +66,11 @@ def getWideget(self): self.maxAgeSpinBox.setRange(1, 1000) self.maxAgeSpinBox.setSuffix("Day") self.maxAgeSpinBox.setAlignment(QtCore.Qt.AlignRight) - configval = self.mydb.getConfig( 'option_dft_maxAgeDate' ) + configval = self.mydb.getConfig('option_dft_maxAgeDate') if configval: - self.maxAgeSpinBox.setValue( configval ) + self.maxAgeSpinBox.setValue(configval) else: - self.maxAgeSpinBox.setValue( 14 ) + self.maxAgeSpinBox.setValue(14) gridLayout.addWidget(label, 1, 5) gridLayout.addWidget(self.maxAgeSpinBox, 1, 6) @@ -81,11 +81,11 @@ def getWideget(self): self.minStockSpinBox.setRange(0, 1000000) self.minStockSpinBox.setSingleStep(100) self.minStockSpinBox.setAlignment(QtCore.Qt.AlignRight) - configval = self.mydb.getConfig( 'option_dft_minStock' ) + configval = self.mydb.getConfig('option_dft_minStock') if configval: - self.minStockSpinBox.setValue( configval ) + self.minStockSpinBox.setValue(configval) else: - self.minStockSpinBox.setValue( 100 ) + self.minStockSpinBox.setValue(100) gridLayout.addWidget(label, 2, 2) gridLayout.addWidget(self.minStockSpinBox, 2, 3) @@ -97,50 +97,50 @@ def getWideget(self): self.maxStartDistSpinBox.setSuffix("ls") self.maxStartDistSpinBox.setSingleStep(10) self.maxStartDistSpinBox.setAlignment(QtCore.Qt.AlignRight) - maxStarDist = self.mydb.getConfig( 'option_maxStarDist' ) + maxStarDist = self.mydb.getConfig('option_maxStarDist') if maxStarDist: - self.maxStartDistSpinBox.setValue( maxStarDist ) + self.maxStartDistSpinBox.setValue(maxStarDist) gridLayout.addWidget(label, 2, 5) gridLayout.addWidget(self.maxStartDistSpinBox, 2, 6) fromsystemlabel = QtGui.QLabel("From System:") self.fromSystem = guitools.LineEdit() - configval = self.mydb.getConfig( 'option_dft_fromSystem' ) + configval = self.mydb.getConfig('option_dft_fromSystem') if configval: - self.fromSystem.setText( configval ) + self.fromSystem.setText(configval) self.fromSystem.textChanged.connect(self.triggerFromSystemChanged) fromstationlabel = QtGui.QLabel("Station:") self.fromStation = guitools.LineEdit() - configval = self.mydb.getConfig( 'option_dft_fromStation' ) + configval = self.mydb.getConfig('option_dft_fromStation') if configval: - self.fromStation.setText( configval ) + self.fromStation.setText(configval) self.fromStation.textChanged.connect(self.triggerFromStationChanged) tosystemlabel = QtGui.QLabel("To System:") self.toSystem = guitools.LineEdit() - configval = self.mydb.getConfig( 'option_dft_toSystem' ) + configval = self.mydb.getConfig('option_dft_toSystem') if configval: - self.toSystem.setText( configval ) + self.toSystem.setText(configval) self.toSystem.textChanged.connect(self.triggerToSystemChanged) tostationlabel = QtGui.QLabel("Station:") self.toStation = guitools.LineEdit() - configval = self.mydb.getConfig( 'option_dft_toStation' ) + configval = self.mydb.getConfig('option_dft_toStation') if configval: - self.toStation.setText( configval ) + self.toStation.setText(configval) self.toStation.textChanged.connect(self.triggerToStationChanged) self.showOptions = QtGui.QCheckBox("Show Options") if self.mydb.getConfig("option_dft_showOptions") != 0: self.showOptions.setChecked(True) - self.showOptions.stateChanged.connect( self.optionsGroupBoxToggleViewAction ) + self.showOptions.stateChanged.connect(self.optionsGroupBoxToggleViewAction) self.searchbutton = QtGui.QPushButton("Search") self.searchbutton.clicked.connect(self.searchDeals) @@ -235,14 +235,12 @@ def triggerFromSystemChanged(self): self.searchDeals() def triggerFromStationChanged(self): - system = self.fromSystem.text() station = self.fromStation.text() self.guitools.setSystemComplete(station, self.fromSystem) self.searchDeals() def triggerToStationChanged(self): - system = self.toSystem.text() station = self.toStation.text() self.guitools.setSystemComplete(station, self.toSystem) @@ -260,7 +258,6 @@ def dealslistContextMenuEvent(self, event): menu = QtGui.QMenu(self) menu.addAction(self.copyAct) - indexes = self.listView.selectionModel().selectedIndexes() menu.addAction(self.markFakeItemAct) menu.exec_(self.listView.viewport().mapToGlobal(event)) @@ -273,11 +270,11 @@ def optionsGroupBoxToggleViewAction(self): def createTimer(self): self.autoUpdateLocationTimer = QtCore.QTimer() - self.autoUpdateLocationTimer.start(1000*60) + self.autoUpdateLocationTimer.start(1000 * 60) self.autoUpdateLocationTimer.timeout.connect(self.updateLocation) def setCurentLocation(self): - self.fromSystem.setText( self.main.location.getLocation() ) + self.fromSystem.setText(self.main.location.getLocation()) self.fromStation.setText("") def updateLocation(self): @@ -319,7 +316,7 @@ def markFakeItem(self): if id: msg = "Warning: fake items are ignored everywhere and no longer displayed\n" - msg += "\nSet\n From Station: %s\n Item: %s\nas Facke" % (indexes[self.headerList.index("From")].data(), indexes[self.headerList.index("Item")].data() ) + msg += "\nSet\n From Station: %s\n Item: %s\nas Facke" % (indexes[self.headerList.index("From")].data(), indexes[self.headerList.index("Item")].data()) msgBox = QtGui.QMessageBox(QtGui.QMessageBox.Warning, "Warning", msg, QtGui.QMessageBox.NoButton, self) @@ -345,34 +342,34 @@ def switchLocations(self): self.searchDeals() def saveOptions(self): - self.mydb.setConfig( 'option_dft_fromSystem', self.fromSystem.text() ) - self.mydb.setConfig( 'option_dft_fromStation', self.fromStation.text() ) - self.mydb.setConfig( 'option_dft_toSystem', self.toSystem.text() ) - self.mydb.setConfig( 'option_dft_toStation', self.toStation.text() ) - self.mydb.setConfig( 'option_dft_maxAgeDate', self.maxAgeSpinBox.value() ) - self.mydb.setConfig( 'option_dft_minStock', self.minStockSpinBox.value() ) - self.mydb.setConfig( 'option_dft_minProfit', self.minProfitSpinBox.value() ) + self.mydb.setConfig('option_dft_fromSystem', self.fromSystem.text()) + self.mydb.setConfig('option_dft_fromStation', self.fromStation.text()) + self.mydb.setConfig('option_dft_toSystem', self.toSystem.text()) + self.mydb.setConfig('option_dft_toStation', self.toStation.text()) + self.mydb.setConfig('option_dft_maxAgeDate', self.maxAgeSpinBox.value()) + self.mydb.setConfig('option_dft_minStock', self.minStockSpinBox.value()) + self.mydb.setConfig('option_dft_minProfit', self.minProfitSpinBox.value()) - self.mydb.setConfig( 'option_dft_showOptions', self.showOptions.isChecked() ) + self.mydb.setConfig('option_dft_showOptions', self.showOptions.isChecked()) sectionPosList = [] - for i in range( self.listView.header().count() ): - sectionPosList.append( self.listView.header().logicalIndex( i ) ) + for i in range(self.listView.header().count()): + sectionPosList.append(self.listView.header().logicalIndex(i)) - sectionPos = ",".join( map( str, sectionPosList ) ) - self.mydb.setConfig( 'option_dft.header.sectionPos', sectionPos ) + sectionPos = ",".join(map(str, sectionPosList)) + self.mydb.setConfig('option_dft.header.sectionPos', sectionPos) def searchDeals(self): - #self.saveOptions() + # self.saveOptions() firstrun = False if not self.listView.header().count(): firstrun = True - self.headerList = ["PriceID","Item","From","Buy", "Stock","To","Sell","Profit","FromAge","ToAge",""] + self.headerList = ["PriceID", "Item", "From", "Buy", "Stock", "To", "Sell", "Profit", "FromAge", "ToAge", ""] model = QtGui.QStandardItemModel(0, len(self.headerList), self) - for x,column in enumerate(self.headerList): + for x, column in enumerate(self.headerList): model.setHeaderData(x, QtCore.Qt.Horizontal, column) @@ -388,7 +385,7 @@ def searchDeals(self): toStation = self.toStation.text() toStationID = self.mydb.getStationID(toSystemID, toStation) - maxAgeDate = datetime.utcnow() - timedelta(days = self.maxAgeSpinBox.value() ) + maxAgeDate = datetime.utcnow() - timedelta(days=self.maxAgeSpinBox.value()) minStock = self.minStockSpinBox.value() startDist = self.maxStartDistSpinBox.value() @@ -398,9 +395,9 @@ def searchDeals(self): # self.main.lockDB() if fromStationID and toStationID: - deals = self.mydb.getDealsFromTo( fromStationID, toStationID, maxAgeDate , minStock ) + deals = self.mydb.getDealsFromTo(fromStationID, toStationID, maxAgeDate, minStock) elif fromStationID and toSystemID: - deals = self.mydb.getDealsFromToSystem( fromStationID, toSystemID, startDist, maxAgeDate , minStock ) + deals = self.mydb.getDealsFromToSystem(fromStationID, toSystemID, startDist, maxAgeDate, minStock) else: deals = [] @@ -410,41 +407,38 @@ def searchDeals(self): if self.minProfitSpinBox.value() <= deal["Profit"]: model.insertRow(0) - model.setData(model.index(0, self.headerList.index("PriceID") ), deal["priceAid"]) - model.setData(model.index(0, self.headerList.index("From") ), deal["fromStation"]) - model.setData(model.index(0, self.headerList.index("To") ), deal["toStation"]) - model.setData(model.index(0, self.headerList.index("Item") ), deal["itemName"]) - model.setData(model.index(0, self.headerList.index("Buy") ), deal["StationSell"]) + model.setData(model.index(0, self.headerList.index("PriceID")), deal["priceAid"]) + model.setData(model.index(0, self.headerList.index("From")), deal["fromStation"]) + model.setData(model.index(0, self.headerList.index("To")), deal["toStation"]) + model.setData(model.index(0, self.headerList.index("Item")), deal["itemName"]) + model.setData(model.index(0, self.headerList.index("Buy")), deal["StationSell"]) model.item(0, self.headerList.index("Buy")).setTextAlignment(QtCore.Qt.AlignRight) - model.setData(model.index(0, self.headerList.index("Sell") ), deal["StationBuy"]) + model.setData(model.index(0, self.headerList.index("Sell")), deal["StationBuy"]) model.item(0, self.headerList.index("Sell")).setTextAlignment(QtCore.Qt.AlignRight) - model.setData(model.index(0, self.headerList.index("Profit") ), deal["Profit"]) + model.setData(model.index(0, self.headerList.index("Profit")), deal["Profit"]) model.item(0, self.headerList.index("Profit")).setTextAlignment(QtCore.Qt.AlignRight) - model.setData(model.index(0, self.headerList.index("Stock") ), deal["Stock"]) + model.setData(model.index(0, self.headerList.index("Stock")), deal["Stock"]) model.item(0, self.headerList.index("Stock")).setTextAlignment(QtCore.Qt.AlignRight) - model.setData(model.index(0, self.headerList.index("FromAge") ), guitools.convertDateimeToAgeStr(deal["fromAge"]) ) + model.setData(model.index(0, self.headerList.index("FromAge")), guitools.convertDateimeToAgeStr(deal["fromAge"])) model.item(0, self.headerList.index("FromAge")).setTextAlignment(QtCore.Qt.AlignCenter) - model.setData(model.index(0, self.headerList.index("ToAge") ), guitools.convertDateimeToAgeStr(deal["toAge"]) ) + model.setData(model.index(0, self.headerList.index("ToAge")), guitools.convertDateimeToAgeStr(deal["toAge"])) model.item(0, self.headerList.index("ToAge")).setTextAlignment(QtCore.Qt.AlignCenter) self.listView.setModel(model) if firstrun: - sectionPos = self.mydb.getConfig( 'option_dft.header.sectionPos' ) + sectionPos = self.mydb.getConfig('option_dft.header.sectionPos') if sectionPos: - sectionPosList = sectionPos.strip().split( ',' ) - for i,pos in enumerate(sectionPosList): - self.listView.header().moveSection( self.listView.header().visualIndex( int(pos) ) , i ) + sectionPosList = sectionPos.strip().split(',') + for i, pos in enumerate(sectionPosList): + self.listView.header().moveSection(self.listView.header().visualIndex(int(pos)), i) - self.listView.sortByColumn( self.headerList.index("Profit"), PySide.QtCore.Qt.SortOrder.DescendingOrder ) + self.listView.sortByColumn(self.headerList.index("Profit"), PySide.QtCore.Qt.SortOrder.DescendingOrder) self.listView.hideColumn(self.headerList.index("PriceID")) - # self.main.unlockDB() +# self.main.unlockDB() - for i in range(0, len(self.headerList) ): + for i in range(0, len(self.headerList)): self.listView.resizeColumnToContents(i) - - - diff --git a/gui/flylog.py b/gui/flylog.py index 42a6cd2..155ea08 100644 --- a/gui/flylog.py +++ b/gui/flylog.py @@ -32,7 +32,7 @@ def __init__(self, main): self.edsm = elite.loader.edsm.edsm() self.lastPos = self.getLastPos() - print("lastpos",self.lastPos) + print("lastpos", self.lastPos) def getLastPos(self): cur = self.mydb.cursor() @@ -83,11 +83,11 @@ def insertSystemCoords(self, system, coords): print("update coord data from %s" % system) cur.execute("insert or IGNORE into systems (System, posX, posY, posZ) values (?,?,?,?) ", - (system , float(coords['x']) , float(coords['y']), float(coords['z']) )) + (system, float(coords['x']), float(coords['y']), float(coords['z']))) systemID = self.mydb.getSystemIDbyName(system) if systemID: - cur.execute( "UPDATE flylog SET SystemID=?, optionalSystemName='' where optionalSystemName=? and SystemID is Null", (systemID, system)) + cur.execute("UPDATE flylog SET SystemID=?, optionalSystemName='' where optionalSystemName=? and SystemID is Null", (systemID, system)) self.mydb.con.commit() cur.close() @@ -112,7 +112,7 @@ def logCurrentPos(self): if edsmCoords: print("update coord data from edsm for %s" % location) cur.execute("insert or IGNORE into systems (System, posX, posY, posZ) values (?,?,?,?) ", - (location , float(edsmCoords['x']) , float(edsmCoords['y']), float(edsmCoords['z']) ) ) + (location, float(edsmCoords['x']), float(edsmCoords['y']), float(edsmCoords['z']))) systemID = self.mydb.getSystemIDbyName(location) else: @@ -122,11 +122,11 @@ def logCurrentPos(self): print("update coord data from edsc for %s" % location) cur.execute("insert or IGNORE into systems (System, posX, posY, posZ) values (?,?,?,?) ", - (location , float(edscSystem['coord'][0]) , float(edscSystem['coord'][1]), float(edscSystem['coord'][2]))) + (location, float(edscSystem['coord'][0]), float(edscSystem['coord'][1]), float(edscSystem['coord'][2]))) systemID = self.mydb.getSystemIDbyName(location) - self.lastPos = location + self.lastPos = location print(location) # return if systemID: @@ -146,6 +146,7 @@ def reloadLogViews(self): for flylog in range(1, len(self.main.flyLogWidget)): self.main.flyLogWidget[flylog].showLog() + def initRun(self): self.flyLogger = flyLogger(self) @@ -154,6 +155,7 @@ def initRun(self): self.flyLogTimer.start(__defaultUpdateTime__) self.flyLogTimer.timeout.connect(self.flyLogger.logCurrentPos) + class tool(QtGui.QWidget): main = None mydb = None @@ -190,7 +192,7 @@ def getWideget(self): layout = QtGui.QHBoxLayout() - layout.setContentsMargins(0,0,0,0) + layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(locationFilterLabel) layout.addWidget(locationButton) @@ -235,7 +237,7 @@ def getWideget(self): spacer = QtGui.QSpacerItem(1, 1, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) layout = QtGui.QHBoxLayout() - layout.setContentsMargins(0,0,0,0) + layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(distanceLabel) layout.addWidget(self.distanceLineEdit) layout.addWidget(timeLabel) @@ -245,7 +247,7 @@ def getWideget(self): infosGroupBox = QtGui.QGroupBox() infosGroupBox.setFlat(True) - #infosGroupBox.setStyleSheet("""border:0; margin:0;padding:0;""") + # infosGroupBox.setStyleSheet("""border:0; margin:0;padding:0;""") infosGroupBox.setLayout(layout) @@ -254,7 +256,7 @@ def getWideget(self): vGroupBox.setStyleSheet("""QGroupBox {border:0;margin:0;padding:0;} margin:0;padding:0;""") layout = QtGui.QVBoxLayout() - layout.setContentsMargins(6,2,6,6) + layout.setContentsMargins(6, 2, 6, 6) layout.addWidget(locationGroupBox) layout.addWidget(self.listView) layout.addWidget(infosGroupBox) @@ -271,14 +273,14 @@ def calcSelected(self): indexes = self.listView.selectionModel().selectedIndexes() ''' calc Distances ''' if indexes[0].column() == self.headerList.index("Distance"): - distSum = 0 + distSum = 0 for index in indexes: item = self.proxyModel.sourceModel().item(index.row(), self.headerList.index("Distance")) if item: dist = item.data(0) if dist: distSum += dist - self.distanceLineEdit.setText( str( round(distSum,2) ) ) + self.distanceLineEdit.setText(str(round(distSum, 2))) ''' calc Time ''' if indexes[0].column() == self.headerList.index("Date"): minDate = None @@ -288,17 +290,17 @@ def calcSelected(self): if item: date = item.data(0) if not minDate and not maxDate: - minDate=date - maxDate=date + minDate = date + maxDate = date elif minDate > date: minDate = date elif maxDate < date: maxDate = date - timeDiff = int(maxDate.toMSecsSinceEpoch()/1000 - minDate.toMSecsSinceEpoch()/1000) + timeDiff = int(maxDate.toMSecsSinceEpoch() / 1000 - minDate.toMSecsSinceEpoch() / 1000) - minutes,sekunds = divmod( timeDiff, 60) - h,minutes = divmod( minutes, 60) - time = "%02d:%02d:%02d" % (h,minutes,sekunds) + minutes, sekunds = divmod(timeDiff, 60) + h, minutes = divmod(minutes, 60) + time = "%02d:%02d:%02d" % (h, minutes, sekunds) self.timeLineEdit.setText(time) def myContextMenuEvent(self, event): @@ -386,16 +388,16 @@ def createIntroPage(): def createReferencPage(): beforeSystem = self.main.flyLogger.getLastPosWithKnowCords() - refSystems = self.mydb.getSystemsInDistance( beforeSystem['SystemID'], 50) + refSystems = self.mydb.getSystemsInDistance(beforeSystem['SystemID'], 50) excludeList = ['Sector'] refsyslist = [] - #refsyslist.append(beforeSystem['System']) + # refsyslist.append(beforeSystem['System']) for i in range(1, 5): - idx = random.randint(0, len(refSystems)-1) + idx = random.randint(0, len(refSystems) - 1) - while refSystems[idx]['System'] in refsyslist or [s for s in excludeList if refSystems[idx]['System'].find(s) > -1 ] : - idx = random.randint(0, len(refSystems)-1) + while refSystems[idx]['System'] in refsyslist or [s for s in excludeList if refSystems[idx]['System'].find(s) > -1 ]: + idx = random.randint(0, len(refSystems) - 1) refsyslist.append(refSystems[idx]['System']) @@ -412,10 +414,10 @@ def createReferencPage(): self.refSyslist = [] - for i,system in enumerate(refsyslist): + for i, system in enumerate(refsyslist): print(system) - nameLabel = QtGui.QLabel("Ref. System %d:" % (i+1) ) + nameLabel = QtGui.QLabel("Ref. System %d:" % (i + 1)) LineEdit = QtGui.QLineEdit() LineEdit.setText(system) @@ -425,13 +427,13 @@ def createReferencPage(): DistSpinBox.setSingleStep(1) DistSpinBox.setAlignment(QtCore.Qt.AlignRight) - statusLabel = QtGui.QLabel("N/A" ) + statusLabel = QtGui.QLabel("N/A") statusLabel.setAlignment(QtCore.Qt.AlignCenter) - gridLayout.addWidget(nameLabel, i+1, 0) - gridLayout.addWidget(LineEdit, i+1, 1,1,2) - gridLayout.addWidget(DistSpinBox, i+1, 3) - gridLayout.addWidget(statusLabel, i+1, 4) + gridLayout.addWidget(nameLabel, i + 1, 0) + gridLayout.addWidget(LineEdit, i + 1, 1, 1, 2) + gridLayout.addWidget(DistSpinBox, i + 1, 3) + gridLayout.addWidget(statusLabel, i + 1, 4) self.refSyslist.append([LineEdit, DistSpinBox, statusLabel]) @@ -483,7 +485,7 @@ def createSubmitPage(): self.submitDistancesWizard.addPage(createSubmitPage()) self.submitDistancesWizard.setWindowTitle("EDSC Submit Distances") - self.submitDistancesWizard.setWindowFlags(QtCore.Qt.Tool| QtCore.Qt.MSWindowsFixedSizeDialogHint| QtCore.Qt.WindowStaysOnTopHint) + self.submitDistancesWizard.setWindowFlags(QtCore.Qt.Tool | QtCore.Qt.MSWindowsFixedSizeDialogHint | QtCore.Qt.WindowStaysOnTopHint) # submitDistancesWizard.setOptions(QtGui.QWizard.NoBackButtonOnStartPage) self.submitDistancesWizard.show() @@ -507,7 +509,7 @@ def submitDistancesEDSM(self): fail = "System name emty" break - refList.append({'name':system[0].text(), 'dist': system[1].value() }) + refList.append({'name': system[0].text(), 'dist': system[1].value() }) print(system[0].text(), system[1].value()) else: fail = "No Target System Name" @@ -520,7 +522,7 @@ def submitDistancesEDSM(self): msgBox.exec_() return - status = self.main.flyLogger.edsm.submitDistances( self.systemNameLineEdit.text(), self.commanderNameLineEdit.text(), refList ) + status = self.main.flyLogger.edsm.submitDistances(self.systemNameLineEdit.text(), self.commanderNameLineEdit.text(), refList) errorMsg = None if status and 'distances' in status: @@ -554,7 +556,7 @@ def submitDistancesEDSM(self): msgBox.exec_() if 'coords' in status['basesystem']: - self.main.flyLogger.insertSystemCoords( self.systemNameLineEdit.text(), status['basesystem']['coords'] ) + self.main.flyLogger.insertSystemCoords(self.systemNameLineEdit.text(), status['basesystem']['coords']) return elif status and "error" in status: errorMsg = str(status["error"][1]) @@ -568,7 +570,7 @@ def submitDistancesEDSM(self): msgBox.setWindowFlags(msgBox.windowFlags() | QtCore.Qt.WindowStaysOnTopHint) msgBox.exec_() - #{'input': [{'status': {'statusnum': 0, 'msg': 'Success'}}]} + # {'input': [{'status': {'statusnum': 0, 'msg': 'Success'}}]} def submitDistancesEDSC(self): @@ -576,7 +578,7 @@ def submitDistancesEDSC(self): refList = [] fail = "" if self.systemNameLineEdit.text(): - for system in self.refSyslist: #.append([LineEdit, DistSpinBox]) + for system in self.refSyslist: # .append([LineEdit, DistSpinBox]) if system[1].value() <= 0.0: fail = "distance from 0 is not allowed" break @@ -584,7 +586,7 @@ def submitDistancesEDSC(self): fail = "System name emty" break - refList.append({'name':system[0].text(), 'dist': system[1].value() }) + refList.append({'name': system[0].text(), 'dist': system[1].value() }) print(system[0].text(), system[1].value()) else: fail = "No Target System Name" @@ -597,7 +599,7 @@ def submitDistancesEDSC(self): msgBox.exec_() return - status = self.main.flyLogger.edsc.submitDistances( self.systemNameLineEdit.text(), self.commanderNameLineEdit.text(), refList ) + status = self.main.flyLogger.edsc.submitDistances(self.systemNameLineEdit.text(), self.commanderNameLineEdit.text(), refList) errorMsg = None if status and 'status' in status: print(status) @@ -628,9 +630,9 @@ def submitDistancesEDSC(self): msgBox.exec_() if 'trilat' in status['status'] and len(status['status']['trilat']) and status['status']['trilat'][0]['system'] == self.systemNameLineEdit.text() and status['status']['trilat'][0]['coord']: - self.main.flyLogger.insertSystemCoords(self.systemNameLineEdit.text(), status['status']['trilat'][0]['coord']) + self.main.flyLogger.insertSystemCoords(self.systemNameLineEdit.text(), status['status']['trilat'][0]['coord']) else: - self.main.flyLogger.insertSystemCoords(self.systemNameLineEdit.text(), self.main.flyLogger.edsc.getSystemCoords( self.systemNameLineEdit.text() ) ) + self.main.flyLogger.insertSystemCoords(self.systemNameLineEdit.text(), self.main.flyLogger.edsc.getSystemCoords(self.systemNameLineEdit.text())) return elif status and "error" in status: errorMsg = str(status["error"][1]) @@ -686,7 +688,7 @@ def showLog(self): model. setData(model.index(0, self.headerList.index("Date")), QtCore.QDateTime(entry["DateTime"])) model. setData(model.index(0, self.headerList.index("Comment")), entry["Comment"]) - #self.listView.setModel(model) + # self.listView.setModel(model) self.proxyModel.setSourceModel(model) self.proxyModel.setFilterKeyColumn(self.headerList.index("System")) diff --git a/gui/guitools.py b/gui/guitools.py index afd6a41..60a2632 100644 --- a/gui/guitools.py +++ b/gui/guitools.py @@ -3,8 +3,8 @@ @author: mEDI ''' -from PySide import QtCore, QtGui,QtSvg -from datetime import datetime, timedelta +from PySide import QtCore, QtGui, QtSvg +from datetime import datetime class guitools(object): @@ -61,7 +61,7 @@ def copyToClipboard(self): clip = [] lastRowCount = None for item in indexes: - if lastRowCount == None: + if lastRowCount is None: lastRowCount = item.row() elif lastRowCount != item.row(): lastRowCount = item.row() @@ -80,6 +80,7 @@ def copyToClipboard(self): string = ", ".join(clip) self.parent.main.clipboard.setText( string.replace(", \n, ", "\n") ) + class LineEdit(QtGui.QLineEdit): def __init__(self, parent=None): QtGui.QLineEdit.__init__(self, parent) @@ -94,8 +95,7 @@ def convertDateimeToAgeStr(dt=datetime.utcnow() ): if age.days >= 1: return "%dd" % age.days - elif age.seconds/60/60 >= 1: - return "%dh" % (age.seconds/60/60) + elif age.seconds / 60 / 60 >= 1: + return "%dh" % (age.seconds / 60 / 60) else: - return "%dm" % (age.seconds/60) - + return "%dm" % (age.seconds / 60) diff --git a/gui/multihoproute.py b/gui/multihoproute.py index d21acc3..765008b 100644 --- a/gui/multihoproute.py +++ b/gui/multihoproute.py @@ -8,7 +8,6 @@ from PySide import QtCore, QtGui import elite import timeit -import time import gui.guitools as guitools @@ -17,8 +16,10 @@ __statusTip__ = "Open A %s Window" % __toolname__ _debug = None + class RouteTreeInfoItem(object): parentItem = None + def __init__(self, data, parent=None): self.parentItem = parent self.itemData = data @@ -54,6 +55,7 @@ def row(self): class RouteTreeHopItem(object): parentItem = None + def __init__(self, data, parent=None): self.parentItem = parent self.itemData = data @@ -99,6 +101,7 @@ def row(self): class RouteTreeItem(object): parentItem = None childItems = [] + def __init__(self, data, parent=None): self.childItems = [] self.parentItem = parent @@ -175,7 +178,8 @@ def __init__(self, route, parent=None, forceHops=None): self.setupModelData() def cleanModel(self): - if _debug: print("cleanModel") + if _debug: + print("cleanModel") self.rootItem = RouteTreeItem(("Nr.", "routeidx", "Profit/h", "Profit", "Ø Profit", "StartDist", "Laps/h", "LapTime", "Status")) @@ -255,7 +259,7 @@ def parent(self, index): else: return QtCore.QModelIndex() - if parentItem == None: + if parentItem is None: return QtCore.QModelIndex() elif parentItem == self.rootItem: return QtCore.QModelIndex() @@ -264,10 +268,10 @@ def parent(self, index): def rowCount(self, parent=None): - if parent != None and parent.column() > 0: + if parent is not None and parent.column() > 0: return 0 - if parent == None or not parent.isValid(): + if parent is None or not parent.isValid(): parentItem = self.rootItem else: parentItem = parent.internalPointer() @@ -275,9 +279,11 @@ def rowCount(self, parent=None): return parentItem.childCount() def sort(self, col, order): - if _debug: print("sort") + if _debug: + print("sort") # print(col, order) - if self.route.locked: return + if self.route.locked: + return if order == QtCore.Qt.SortOrder.DescendingOrder: order = True else: @@ -308,12 +314,14 @@ def sort(self, col, order): self.layoutChanged.emit() def setupModelData(self): - if _debug: print("setupModelData") + if _debug: + print("setupModelData") parents = [self.rootItem] for routeId, deal in enumerate(self.route.deals): - if routeId >= 100: break + if routeId >= 100: + break timeT = "%s:%s" % (divmod(deal["time"] * deal["lapsInHour"], 60)) timeL = "%s:%s" % (divmod(deal["time"], 60)) @@ -323,7 +331,7 @@ def setupModelData(self): parents[-1].appendChild(RouteTreeItem(columnData, parents[-1])) - before = { "StationB":deal["path"][0]["StationA"], "SystemB":deal["path"][0]["SystemA"], "StarDist":deal["path"][0]["stationA.StarDist"], "refuel":deal["path"][0]["stationA.refuel"] } + before = { "StationB": deal["path"][0]["StationA"], "SystemB": deal["path"][0]["SystemA"], "StarDist": deal["path"][0]["stationA.StarDist"], "refuel": deal["path"][0]["stationA.refuel"] } # follow is a child parents.append(parents[-1].child(parents[-1].childCount() - 1)) @@ -331,13 +339,13 @@ def setupModelData(self): # print(d.keys()) columnData = "%s : %s (%d ls) (%s buy:%d sell:%d profit:%d) (%s ly)-> %s:%s" % (self.route.getSystemA(deal, hopID), self.route.getStationA(deal, hopID), - before["StarDist"] , d["itemName"], d["StationSell"], + before["StarDist"], d["itemName"], d["StationSell"], d["StationBuy"], d["profit"], d["dist"], self.route.getSystemB(deal, hopID), self.route.getStationB(deal, hopID)) - parents[-1].appendChild(RouteTreeHopItem(columnData , parents[-1])) + parents[-1].appendChild(RouteTreeHopItem(columnData, parents[-1])) @@ -348,7 +356,7 @@ def setupModelData(self): before = d - backdist = self.route.mydb.getDistanceFromTo(deal["path"][0]["SystemAID"] , deal["path"][ len(deal["path"]) - 1 ]["SystemBID"]) + backdist = self.route.mydb.getDistanceFromTo(deal["path"][0]["SystemAID"], deal["path"][ len(deal["path"]) - 1 ]["SystemBID"]) hopID += 1 @@ -362,7 +370,7 @@ def setupModelData(self): deal["backToStartDeal"]["profit"], backdist, self.route.getSystemB(deal, hopID), - self.route.getStationB(deal, hopID)) + self.route.getStationB(deal, hopID)) parents[-1].appendChild(RouteTreeHopItem(columnData, parents[-1])) else: columnData = "%s : %s (%d ls) (no back deal) (%s ly) ->%s : %s" % (self.route.getSystemA(deal, hopID), @@ -720,10 +728,10 @@ def startRouteSearch(self): self.routeModel = RouteTreeModel(self.route, self, forceHops) - QtCore.QObject.connect(self.routeModel, QtCore.SIGNAL ('layoutAboutToBeChanged()'), self.routeModellayoutAboutToBeChanged) - QtCore.QObject.connect(self.routeModel, QtCore.SIGNAL ('layoutChanged()'), self.routeModellayoutChanged) - QtCore.QObject.connect(self.routeModel, QtCore.SIGNAL ('modelAboutToBeReset()'), self.routeModelmodelAboutToBeReset) - QtCore.QObject.connect(self.routeModel, QtCore.SIGNAL ('modelReset()'), self.routeModemodelReset) + QtCore.QObject.connect(self.routeModel, QtCore.SIGNAL('layoutAboutToBeChanged()'), self.routeModellayoutAboutToBeChanged) + QtCore.QObject.connect(self.routeModel, QtCore.SIGNAL('layoutChanged()'), self.routeModellayoutChanged) + QtCore.QObject.connect(self.routeModel, QtCore.SIGNAL('modelAboutToBeReset()'), self.routeModelmodelAboutToBeReset) + QtCore.QObject.connect(self.routeModel, QtCore.SIGNAL('modelReset()'), self.routeModemodelReset) self.listView.setModel(self.routeModel) # routeModel.layoutChanged.emit() @@ -739,11 +747,13 @@ def startRouteSearch(self): self.triggerLocationChanged() def routeModelmodelAboutToBeReset(self): - if _debug: print("routeModelmodelAboutToBeReset") + if _debug: + print("routeModelmodelAboutToBeReset") def routeModemodelReset(self): - if _debug: print("routeModelmodelAboutToBeReset") + if _debug: + print("routeModelmodelAboutToBeReset") def enabelSorting(self): @@ -751,18 +761,20 @@ def enabelSorting(self): self.enabelSortingTimer = None def routeModellayoutAboutToBeChanged(self): - if _debug: print("routeModellayoutAboutToBeChanged") + if _debug: + print("routeModellayoutAboutToBeChanged") self.autoUpdateLocationTimer.stop() self.layoutLock = True def routeModellayoutChanged(self): - if _debug: print("routeModellayoutChanged") + if _debug: + print("routeModellayoutChanged") for rid in range(0, self.listView.model().rowCount(QtCore.QModelIndex())): # rid item count for cid in range(0, self.listView.model().rowCount(self.listView.model().index(rid, 0))): # cid child item count - self.listView.setFirstColumnSpanned(cid, self.listView.model().index(rid, 0) , True) + self.listView.setFirstColumnSpanned(cid, self.listView.model().index(rid, 0), True) self.listView.expandToDepth(1) @@ -800,7 +812,8 @@ def updateLocation(self): def triggerLocationChanged(self): - if _debug: print("triggerLocationChanged") + if _debug: + print("triggerLocationChanged") if self.route.locked or self.layoutLock: return @@ -809,18 +822,21 @@ def triggerLocationChanged(self): self.setLocationColors() def setLocationColors(self): - if _debug: print("setLocationColors") + if _debug: + print("setLocationColors") location = self.locationlineEdit.text() if self.route.locked or self.layoutLock: return - if not self.listView.model() or not self.listView.model().rowCount(): return - hopID = self.getCurrentHopFromActiveRoute() # only to fill deal["lastHop"] + if not self.listView.model() or not self.listView.model().rowCount(): + return + hopID = self.getCurrentHopFromActiveRoute() # only to fill deal["lastHop"] if location and self.listView.model(): for rid in range(0, self.listView.model().rowCount(QtCore.QModelIndex())): - if self.layoutLock: return + if self.layoutLock: + return guiRroute = self.listView.model().index(rid, 0).internalPointer() hopID = -1 for cid in range(0, guiRroute.childCount()): @@ -839,7 +855,7 @@ def setLocationColors(self): else: child.setBGColor(None) - self.listView.dataChanged(self.listView.model().index(0, 0), self.listView.model().index(self.listView.model().rowCount(QtCore.QModelIndex()) , 0)) + self.listView.dataChanged(self.listView.model().index(0, 0), self.listView.model().index(self.listView.model().rowCount(QtCore.QModelIndex()), 0)) def createActions(self): self.markFakeItemAct = QtGui.QAction("Set Item as Fake", self, @@ -891,7 +907,8 @@ def clipbordRouteHelper(self): def setNextRouteHopToClipbord(self, init=None): ''' helper to set next route hop to clipboard ''' - if _debug: print("setNextRouteHopToClipbord") + if _debug: + print("setNextRouteHopToClipbord") if not self.activeRoutePointer: return @@ -909,7 +926,7 @@ def setNextRouteHopToClipbord(self, init=None): hopID = self.getCurrentHopFromActiveRoute() - if hopID != None: + if hopID is not None: systemA = self.route.getSystemB(self.activeRoutePointer, hopID) if systemA != clipbordText: @@ -932,7 +949,7 @@ def setNextRouteHopToClipbord(self, init=None): def markFakeItem(self): route, hopID = self.getSelectedRouteHopID() - priceID = self.route.getPriceID(route, hopID) + priceID = self.route.getPriceID(route, hopID) if priceID: msgBox = QtGui.QMessageBox(QtGui.QMessageBox.Warning, @@ -949,7 +966,8 @@ def markFakeItem(self): self.main.unlockDB() def getSelectedRouteHopID(self): - if _debug: print("getSelectedRouteHopID") + if _debug: + print("getSelectedRouteHopID") indexes = self.listView.selectionModel().selectedIndexes() @@ -964,10 +982,11 @@ def getSelectedRouteHopID(self): return (None, None) def addRouteHopAsTargetSystemInDealsFromToFinder(self): - if _debug: print("addRouteHopAsTargetSystemInDealsFromToFinder") + if _debug: + print("addRouteHopAsTargetSystemInDealsFromToFinder") route, hopID = self.getSelectedRouteHopID() - if route == None or hopID == None: + if route is None or hopID is None: return toStation = self.route.getStationA(route, hopID) @@ -980,7 +999,8 @@ def addRouteHopAsTargetSystemInDealsFromToFinder(self): def addRouteHopAsFromSystemInDealsFromToFinder(self): route, hopID = self.getSelectedRouteHopID() - if route == None or hopID == None: return + if route is None or hopID is None: + return station = self.route.getStationA(route, hopID) system = self.route.getSystemA(route, hopID) @@ -990,7 +1010,8 @@ def addRouteHopAsFromSystemInDealsFromToFinder(self): self.main.dealsFromToWidget[1].fromStation.setText(station) def connectToDealsFromToWindows(self): - if _debug: print("connectToDealsFromToWindows") + if _debug: + print("connectToDealsFromToWindows") if self.connectedDealsFromToWindows: indexes = self.listView.selectionModel().selectedIndexes() if self.activeRoutePointer == indexes[0].internalPointer().getInternalRoutePointer(): @@ -1010,7 +1031,8 @@ def disconnectFromDealsFromToWindow(self): self.connectedDealsFromToWindows = None def getCurrentHopFromActiveRoute(self): - if _debug: print("getCurrentHopFromActiveRoute") + if _debug: + print("getCurrentHopFromActiveRoute") if not self.activeRoutePointer: return @@ -1021,7 +1043,7 @@ def getCurrentHopFromActiveRoute(self): for i in range(0, hopCount + 1): if not self.activeRoutePointer["lastHop"]: cid = i - else: + else: cid = self.activeRoutePointer["lastHop"] + i if cid > hopCount: @@ -1038,13 +1060,14 @@ def getCurrentHopFromActiveRoute(self): return hopID def updateConnectedDealsFromToWindow(self, init=None): - if _debug: print("updateConnectedDealsFromToWindow") - if not self.connectedDealsFromToWindows or not self.activeRoutePointer: + if _debug: + print("updateConnectedDealsFromToWindow") + if not self.connectedDealsFromToWindows or not self.activeRoutePointer: return hopID = self.getCurrentHopFromActiveRoute() - if hopID == None and init: + if hopID is None and init: ''' is init and im not inside the route set only the To part from first hop ''' systemA = self.route.getSystemA(self.activeRoutePointer, 0) stationA = self.route.getStationA(self.activeRoutePointer, 0) @@ -1054,7 +1077,7 @@ def updateConnectedDealsFromToWindow(self, init=None): return - if hopID == None: + if hopID is None: return systemA = self.route.getSystemA(self.activeRoutePointer, hopID) @@ -1068,4 +1091,3 @@ def updateConnectedDealsFromToWindow(self, init=None): self.connectedDealsFromToWindows.toSystem.setText(systemB) self.connectedDealsFromToWindows.toStation.setText(stationB) - diff --git a/gui/power_control_finder.py b/gui/power_control_finder.py index 477e812..7e46f9f 100644 --- a/gui/power_control_finder.py +++ b/gui/power_control_finder.py @@ -14,6 +14,7 @@ __internalName__ = "PoCoFi" __statusTip__ = "Find controlled systems by Power" + class tool(QtGui.QWidget): main = None mydb = None @@ -40,11 +41,11 @@ def getWideget(self): locationLabel = QtGui.QLabel("Location:") self.locationlineEdit = guitools.LineEdit() - configval = self.mydb.getConfig( 'option_pcf_location' ) + configval = self.mydb.getConfig('option_pcf_location') if configval: - self.locationlineEdit.setText( configval ) + self.locationlineEdit.setText(configval) else: - self.locationlineEdit.setText( self.main.location.getLocation() ) + self.locationlineEdit.setText(self.main.location.getLocation()) self.locationlineEdit.textChanged.connect(self.searchPower) @@ -54,7 +55,7 @@ def getWideget(self): powers = self.mydb.getAllPowers() self.powerList = [] for power in powers: - self.powerComboBox.addItem( power["Name"] ) + self.powerComboBox.addItem(power["Name"]) self.powerList.append(power["id"]) if self.mydb.getConfig("option_pcf_power"): @@ -129,13 +130,13 @@ def createActions(self): def setCurentLocation(self): - self.locationlineEdit.setText( self.main.location.getLocation() ) + self.locationlineEdit.setText(self.main.location.getLocation()) def saveOptions(self): # save last options self.mydb.setConfig('option_pcf_power', self.powerComboBox.currentIndex()) - self.mydb.setConfig( 'option_pcf_location', self.locationlineEdit.text() ) + self.mydb.setConfig('option_pcf_location', self.locationlineEdit.text()) def searchPower(self): @@ -147,7 +148,7 @@ def searchPower(self): self.headerList = ["System", "Distance", "Permit", ""] model = QtGui.QStandardItemModel(0, len(self.headerList), self) - for x,column in enumerate(self.headerList): + for x, column in enumerate(self.headerList): model.setHeaderData(x, QtCore.Qt.Horizontal, column) location = self.locationlineEdit.text() @@ -160,18 +161,18 @@ def searchPower(self): for system in systems: model.insertRow(0) - model.setData(model.index(0, self.headerList.index("System") ), system["System"]) + model.setData(model.index(0, self.headerList.index("System")), system["System"]) - model.setData(model.index(0, self.headerList.index("Distance") ), system["dist"]) + model.setData(model.index(0, self.headerList.index("Distance")), system["dist"]) model.item(0, self.headerList.index("Distance")).setTextAlignment(QtCore.Qt.AlignRight) - model.setData(model.index(0, self.headerList.index("Permit") ), "No" if not system["permit"] else "Yes" ) + model.setData(model.index(0, self.headerList.index("Permit")), "No" if not system["permit"] else "Yes") model.item(0, self.headerList.index("Permit")).setTextAlignment(QtCore.Qt.AlignCenter) self.listView.setModel(model) if firstrun: - self.listView.sortByColumn( self.headerList.index("Distance"), PySide.QtCore.Qt.SortOrder.AscendingOrder ) + self.listView.sortByColumn(self.headerList.index("Distance"), PySide.QtCore.Qt.SortOrder.AscendingOrder) - for i in range(0, len(self.headerList) ): + for i in range(0, len(self.headerList)): self.listView.resizeColumnToContents(i) diff --git a/gui/shipyard_finder.py b/gui/shipyard_finder.py index e1b9c1e..b703eb4 100644 --- a/gui/shipyard_finder.py +++ b/gui/shipyard_finder.py @@ -14,6 +14,7 @@ __internalName__ = "ShFi" __statusTip__ = "Open A %s Window" % __toolname__ + class tool(QtGui.QWidget): main = None mydb = None @@ -40,7 +41,7 @@ def getWideget(self): locationLabel = QtGui.QLabel("Location:") self.locationlineEdit = guitools.LineEdit() - self.locationlineEdit.setText( self.main.location.getLocation() ) + self.locationlineEdit.setText(self.main.location.getLocation()) self.locationlineEdit.textChanged.connect(self.searchShip) @@ -50,7 +51,7 @@ def getWideget(self): ships = self.mydb.getAllShipnames() self.shipList = [] for ship in ships: - self.shipComboBox.addItem( ship["Name"] ) + self.shipComboBox.addItem(ship["Name"]) self.shipList.append(ship["id"]) self.shipComboBox.currentIndexChanged.connect(self.searchShip) @@ -74,7 +75,7 @@ def getWideget(self): locationGroupBox.setFlat(True) locationGroupBox.setStyleSheet("""QGroupBox {border:0;margin:0;padding:0;} margin:0;padding:0;""") - #locationGroupBox.setFlat(True) + # locationGroupBox.setFlat(True) locationGroupBox.setLayout(layout) @@ -125,7 +126,7 @@ def createActions(self): def setCurentLocation(self): - self.locationlineEdit.setText( self.main.location.getLocation() ) + self.locationlineEdit.setText(self.main.location.getLocation()) def searchShip(self): @@ -134,10 +135,10 @@ def searchShip(self): if not self.listView.header().count(): firstrun = True - self.headerList = ["System", "Permit","StarDist", "Station", "Distance", "Age", ""] + self.headerList = ["System", "Permit", "StarDist", "Station", "Distance", "Age", ""] model = QtGui.QStandardItemModel(0, len(self.headerList), self) - for x,column in enumerate(self.headerList): + for x, column in enumerate(self.headerList): model.setHeaderData(x, QtCore.Qt.Horizontal, column) location = self.locationlineEdit.text() @@ -150,25 +151,25 @@ def searchShip(self): for shipyard in shipyards: model.insertRow(0) - model.setData(model.index(0, self.headerList.index("System") ), shipyard["System"]) + model.setData(model.index(0, self.headerList.index("System")), shipyard["System"]) - model.setData(model.index(0, self.headerList.index("Permit") ), "No" if not shipyard["permit"] else "Yes" ) + model.setData(model.index(0, self.headerList.index("Permit")), "No" if not shipyard["permit"] else "Yes") model.item(0, self.headerList.index("Permit")).setTextAlignment(QtCore.Qt.AlignCenter) - model.setData(model.index(0, self.headerList.index("StarDist") ), shipyard["StarDist"]) + model.setData(model.index(0, self.headerList.index("StarDist")), shipyard["StarDist"]) model.item(0, self.headerList.index("StarDist")).setTextAlignment(QtCore.Qt.AlignRight) - model.setData(model.index(0, self.headerList.index("Station") ), shipyard["Station"]) - model.setData(model.index(0, self.headerList.index("Distance") ), shipyard["dist"]) + model.setData(model.index(0, self.headerList.index("Station")), shipyard["Station"]) + model.setData(model.index(0, self.headerList.index("Distance")), shipyard["dist"]) model.item(0, self.headerList.index("Distance")).setTextAlignment(QtCore.Qt.AlignRight) - model.setData(model.index(0, self.headerList.index("Age") ), guitools.convertDateimeToAgeStr(shipyard["age"]) ) + model.setData(model.index(0, self.headerList.index("Age")), guitools.convertDateimeToAgeStr(shipyard["age"])) model.item(0, self.headerList.index("Age")).setTextAlignment(QtCore.Qt.AlignCenter) self.listView.setModel(model) if firstrun: - self.listView.sortByColumn( self.headerList.index("Distance"), PySide.QtCore.Qt.SortOrder.AscendingOrder ) + self.listView.sortByColumn(self.headerList.index("Distance"), PySide.QtCore.Qt.SortOrder.AscendingOrder) - for i in range(0, len(self.headerList) ): + for i in range(0, len(self.headerList)): self.listView.resizeColumnToContents(i) diff --git a/main.py b/main.py index 3da3faf..6ad4c64 100644 --- a/main.py +++ b/main.py @@ -6,19 +6,19 @@ @author: mEDI ''' -__defaultUpdateTime__ = 1000*30 +__defaultUpdateTime__ = 1000 * 30 import logging import sys try: - from _version import __buildid__ , __version__, __builddate__, __toolname__, __useragent__ + from _version import __buildid__, __version__, __builddate__, __toolname__, __useragent__ except ImportError: __buildid__ = "UNKNOWN" __version__ = "UNKNOWN" __builddate__ = "NONE" __toolname__ = "mEDI s Elite Tools" - __useragent__ = '%s/%s (%s) %s(%s)' % (__toolname__.replace(" ", ""), __version__, sys.platform, __buildid__, __builddate__.replace(" ", "").replace("-", "").replace(":", "") ) + __useragent__ = '%s/%s (%s) %s(%s)' % (__toolname__.replace(" ", ""), __version__, sys.platform, __buildid__, __builddate__.replace(" ", "").replace("-", "").replace(":", "") ) @@ -28,7 +28,7 @@ def __init__(self, logger, log_level=logging.INFO): self.logger = logger self.log_level = log_level self.linebuf = '' - self.logger.log(logging.INFO,"version: %s (%s)" % (__version__, __buildid__) ) + self.logger.log(logging.INFO, "version: %s (%s)" % (__version__, __buildid__) ) def write(self, buf): for line in buf.rstrip().splitlines(): @@ -52,6 +52,7 @@ def write(self, buf): from PySide import QtCore, QtGui import base64 + class MainWindow(QtGui.QMainWindow): mydb = None @@ -75,7 +76,7 @@ def __init__(self): self.setDockOptions(QtGui.QMainWindow.AnimatedDocks | QtGui.QMainWindow.AllowNestedDocks | QtGui.QMainWindow.AllowTabbedDocks) self.setStatusBar("Welcomme to mEDI's Elite Tools") - self.setMinimumSize(600,400) + self.setMinimumSize(600, 400) self.setWindowIcon(QtGui.QIcon(QtGui.QPixmap("img/logo.png"))) @@ -86,7 +87,7 @@ def __init__(self): self.mydb = elite.db(guiMode=True) self.mydb.startStreamUpdater() - self.dbworker = gui.dbworker.new(self) + self.dbworker = gui.dbworker.new(self) self.location = elite.location(self.mydb) @@ -96,7 +97,7 @@ def __init__(self): self.createTimer() - self.myPlugins = [gui.multihoproute, gui.deals_from_to, gui.commodities_finder, gui.shipyard_finder, gui.power_control_finder, gui.flylog] + self.myPlugins = [gui.multihoproute, gui.deals_from_to, gui.commodities_finder, gui.shipyard_finder, gui.power_control_finder, gui.flylog] self.addTool( gui.multihoproute, self.multiHopRouteWidget) self.addTool( gui.deals_from_to, self.dealsFromToWidget) @@ -148,14 +149,14 @@ def createDockWidget(): widget = myWidget.getWideget() - pos = len(toolsList)-1 + pos = len(toolsList) - 1 title = "%s %d" % (tool.__toolname__, pos) self.addMyDockWidget( widget, title) tool._openDockWidget = createDockWidget toolsList.append(createDockWidget) - ''' tool to tools menu ''' + ''' tool to tools menu ''' myAct = QtGui.QAction(tool.__toolname__, self, statusTip=tool.__statusTip__, triggered=createDockWidget) @@ -191,9 +192,9 @@ def addProgressBarStatusBar(self): self.statusBarProgressBarLabel = QtGui.QLabel(" ") gridLayout = QtGui.QGridLayout() - gridLayout.setContentsMargins(0,0,0,0) + gridLayout.setContentsMargins(0, 0, 0, 0) gridLayout.addWidget(self.statusBarProgressBarLabel, 0, 0) - gridLayout.addWidget(self.statusBarProgressBar, 0, 1, 0,2 ) + gridLayout.addWidget(self.statusBarProgressBar, 0, 1, 0, 2) GroupBox = QtGui.QGroupBox() GroupBox.setStyleSheet("border:0;margin:0;padding:0") @@ -211,7 +212,7 @@ def addMyDockWidget(self, widget, title): dock.setWidget(widget) - self.addDockWidget(QtCore.Qt.RightDockWidgetArea , dock) + self.addDockWidget(QtCore.Qt.RightDockWidgetArea, dock) self.viewMenu.addAction(dock.toggleViewAction()) @@ -301,8 +302,10 @@ def childMsgPull(self): if msg: if isinstance(msg, gui.dbworker.statusMsg): self.statusBarProgressBarLabel.setText(msg.msg) - if msg.processCount: self.statusBarProgressBar.setRange(0, msg.processCount) - if msg.processPos: self.statusBarProgressBar.setValue(msg.processPos) + if msg.processCount: + self.statusBarProgressBar.setRange(0, msg.processCount) + if msg.processPos: + self.statusBarProgressBar.setValue(msg.processPos) else: self.setStatusBar( msg ) @@ -316,7 +319,7 @@ def updateDB(self): if status: self.updateDBtimer.start(__defaultUpdateTime__) else: - self.updateDBtimer.start(__defaultUpdateTime__*4) + self.updateDBtimer.start(__defaultUpdateTime__ * 4) def lockDB(self): self.dbworker.lockDB() @@ -363,16 +366,16 @@ def saveOptions( self ): self.mydb.setConfig( 'mainwindow.openWidgets', ",".join(openWidgetsList) ) - if len(self.dealsFromToWidget) > 1: # save only from first windows + if len(self.dealsFromToWidget) > 1: # save only from first windows self.dealsFromToWidget[1].saveOptions() - if len(self.multiHopRouteWidget) > 1: # save only from first windows + if len(self.multiHopRouteWidget) > 1: # save only from first windows self.multiHopRouteWidget[1].saveOptions() - if len(self.powerControlFinderWidget) > 1: # save only from first windows + if len(self.powerControlFinderWidget) > 1: # save only from first windows self.powerControlFinderWidget[1].saveOptions() - if len(self.commoditiesFinderWidget) > 1: # save only from first windows + if len(self.commoditiesFinderWidget) > 1: # save only from first windows self.commoditiesFinderWidget[1].saveOptions() @@ -438,7 +441,7 @@ def checkUpdate(self): if msgBox.exec_() == QtGui.QMessageBox.AcceptRole: self.openUrl(url_update) else: - reply = QtGui.QMessageBox.information(self, + QtGui.QMessageBox.information(self, "No new version available", "Congratulation, you are already using the latest version") diff --git a/setup.py b/setup.py index 170ab0f..4b4cb1a 100644 --- a/setup.py +++ b/setup.py @@ -41,16 +41,16 @@ import sys -__useragent__ = '%%s/%%s (%%s) %%s(%%s)' %% (__toolname__.replace(' ', ''), __version__, sys.platform, __buildid__, __builddate__.replace(' ', '').replace('-', '').replace(':', '') ) +__useragent__ = '%%s/%%s (%%s) %%s(%%s)' %% (__toolname__.replace(' ', ''), __version__, sys.platform, __buildid__, __builddate__.replace(' ', '').replace('-', '').replace(':', '') ) """ VERSION_HOMEPAGE = """buildid=%s;version=%s;file=%s;builddate=%s""" -if sys.platform=='win32': +if sys.platform == 'win32': # platform.architecture()[0] - base = 'Win32GUI' + base = 'Win32GUI' mybuild_dir = 'build\exe.win32-3.4' else: base = None @@ -62,6 +62,7 @@ shutil.rmtree(mybuild_dir) pass + def isInt(s): try: int(s) @@ -69,6 +70,7 @@ def isInt(s): except ValueError: return False + def update_version_py(): global __buildid__, __version__ if not os.path.isdir(".git"): @@ -90,9 +92,9 @@ def update_version_py(): ver = __buildid__.split("-") if isInt(ver[1]): - __version__ = "%s.%s" % (ver[0], ver[1]) + __version__ = "%s.%s" % (ver[0], ver[1]) else: - __version__ = "%s.%s" % (ver[0], 0) + __version__ = "%s.%s" % (ver[0], 0) f = open("_version.py", "w") f.write(VERSION_PY % (__buildid__, __version__, __builddate__, __toolnameSave__)) @@ -108,7 +110,7 @@ def update_version_py(): __msiFile__ = "%s-%s-%s.msi" % (__toolnameSave__, __version__, sys.platform) ''' create versions file ''' -f = open(os.path.join(__destDisr__,"mediselitetools.version.txt"), "w") +f = open(os.path.join(__destDisr__, "mediselitetools.version.txt"), "w") f.write(VERSION_HOMEPAGE % (__buildid__, __version__, __msiFile__, __builddate__)) f.close() @@ -119,70 +121,69 @@ def update_version_py(): imgPath = "img" -#includeFilesList = [["db/my.db","db/my.db"],["db/rares.csv","db/rares.csv"]] -includeFilesList = [["db/rares.csv","db/rares.csv"], [zmq.libzmq.__file__, "libzmq.pyd" ], [__forceupdateFile__,__forceupdateFile__]] +# includeFilesList = [["db/my.db","db/my.db"],["db/rares.csv","db/rares.csv"]] +includeFilesList = [["db/rares.csv", "db/rares.csv"], [zmq.libzmq.__file__, "libzmq.pyd" ], [__forceupdateFile__, __forceupdateFile__]] -#add img +# add img for f in os.listdir(imgPath): - includeFilesList.append( [os.path.join(imgPath,f), os.path.join(imgPath,f) ] ) + includeFilesList.append([os.path.join(imgPath, f), os.path.join(imgPath, f) ]) shortcut_table = [ - ( - "DesktopShortcut", # Shortcut - "DesktopFolder", # Directory_ - __toolname__, # Name - "TARGETDIR", # Component_ - "[TARGETDIR]%s" % __exeName__,# Target - None, # Arguments - None, # Description - None, # Hotkey - None, # Icon - None, # IconIndex - None, # ShowCmd - "TARGETDIR", # WkDir - ), - ( - "Shortcut", # Shortcut - "ProgramMenuFolder", # Directory_ - __toolname__, # Name - "TARGETDIR", # Component_ - "[TARGETDIR]%s" % __exeName__,# Target - None, # Arguments - None, # Description - None, # Hotkey - None, # Icon - None, # IconIndex - None, # ShowCmd - "TARGETDIR", # WkDir - ), - - ] + ( + "DesktopShortcut", # Shortcut + "DesktopFolder", # Directory_ + __toolname__, # Name + "TARGETDIR", # Component_ + "[TARGETDIR]%s" % __exeName__, # Target + None, # Arguments + None, # Description + None, # Hotkey + None, # Icon + None, # IconIndex + None, # ShowCmd + "TARGETDIR", # WkDir + ), + ( + "Shortcut", # Shortcut + "ProgramMenuFolder", # Directory_ + __toolname__, # Name + "TARGETDIR", # Component_ + "[TARGETDIR]%s" % __exeName__, # Target + None, # Arguments + None, # Description + None, # Hotkey + None, # Icon + None, # IconIndex + None, # ShowCmd + "TARGETDIR", # WkDir + ), + ] msi_data = {"Shortcut": shortcut_table} msiOptions = dict( - upgrade_code = __GUID__, - data = msi_data, + upgrade_code=__GUID__, + data=msi_data, ) buildOptions = dict( - #build_exe = mybuild_dir, - packages = [], - excludes = [], - - includes = ['zmq.backend.cython'], - optimize = 2, - compressed = True, - icon = "img/logo.ico", - replace_paths = "*=", - include_files = includeFilesList, - silent = True, + # build_exe = mybuild_dir, + packages=[], + excludes=[], + + includes=['zmq.backend.cython'], + optimize=2, + compressed=True, + icon="img/logo.ico", + replace_paths="*=", + include_files=includeFilesList, + silent=True, ) installOptions = dict( - force = True, - skip_build = False, + force=True, + skip_build=False, ) @@ -191,36 +192,37 @@ def update_version_py(): Executable( 'main.py', base=base, - targetName = __exeName__, + targetName=__exeName__, compress=True, - shortcutName = __toolname__, - shortcutDir = None, - ) + shortcutName=__toolname__, + shortcutDir=None, + ) ] setup(name=__toolnameSave__, - version = __version__ , + version=__version__, author="René Wunderlich", - description = 'Elite Tools', - options = dict(build_exe = buildOptions, + description='Elite Tools', + options=dict( + build_exe=buildOptions, # install_exe = installOptions, - bdist_msi = msiOptions, - ), - executables = executables) + bdist_msi=msiOptions, + ), + executables=executables) ''' remove trigger file ''' -if os.path.isfile( __forceupdateFile__ ): - os.remove( __forceupdateFile__ ) +if os.path.isfile(__forceupdateFile__): + os.remove(__forceupdateFile__) ''' only for the zip fallback''' if _buildZip: ''' manipulate db clone ''' - clonedDBpath = os.path.join(mybuild_dir, __sourceDB__ ) + clonedDBpath = os.path.join(mybuild_dir, __sourceDB__) - shutil.copyfile(__sourceDB__ , clonedDBpath) + shutil.copyfile(__sourceDB__, clonedDBpath) if os.path.isfile(clonedDBpath): @@ -249,9 +251,9 @@ def update_version_py(): db.con.commit() cur.close() - lastOptimize = db.getConfig( 'lastOptimizeDatabase' ) + lastOptimize = db.getConfig('lastOptimizeDatabase') if __OptimizeDB__ and lastOptimize: - lastOptimize = datetime.strptime(lastOptimize , "%Y-%m-%d %H:%M:%S") + lastOptimize = datetime.strptime(lastOptimize, "%Y-%m-%d %H:%M:%S") if lastOptimize + timedelta(days=1) < datetime.now(): db.optimizeDatabase() @@ -266,7 +268,6 @@ def update_version_py(): if os.path.isfile(outputfile): os.remove(outputfile) - #compress + # compress options = "-y -t7z -mx9" - os.spawnl(os.P_WAIT, zipexepath,"7z","a",outputfile , "./%s/*" % mybuild_dir, options) - + os.spawnl(os.P_WAIT, zipexepath, "7z", "a", outputfile, "./%s/*" % mybuild_dir, options) diff --git a/sqlite3_functions.py b/sqlite3_functions.py index df4a3c0..b7206ef 100644 --- a/sqlite3_functions.py +++ b/sqlite3_functions.py @@ -2,10 +2,11 @@ import math + def calcDistance(AposX, AposY, AposZ, BposX, BposY, BposZ ): # #sqrt( (xA-xB)2 + (yA-yB)2 + (zA-zB)2 ) return round(math.sqrt((AposX - BposX) ** 2 + (AposY - BposY) ** 2 + (AposZ - BposZ) ** 2), 2) def registerSQLiteFunktions(con): - con.create_function("calcDistance", 6, calcDistance) \ No newline at end of file + con.create_function("calcDistance", 6, calcDistance) diff --git a/test_db.py b/test_db.py index 38ea6d1..1909e68 100644 --- a/test_db.py +++ b/test_db.py @@ -4,10 +4,16 @@ import timeit import sys +import elite.loader.eddb +import elite.loader.edsc +import elite.loader.edsm + + start = timeit.default_timer() -db = db() +db = db(guiMode=True) +db.initDB() etime = elitetime(db,23) @@ -16,6 +22,19 @@ print( wA, wB, wA+wB ) +#elite.loader.eddb.systems.loader(db).importData("db/systems.json") +#elite.loader.eddb.stations.loader(db).importData("db/stations.json") + +edsc = elite.loader.edsc.edsc() +#edsc.getSystemCoords("LP 761-93") +print(edsc.getSystemCoords("34 Pegasi")) +#edsc.getSystemCoords("Eravate") + +edsm = elite.loader.edsm.edsm() +#print(edsm.getSystemCoords("LP 761-93")) +print(edsm.getSystemCoords("34 Pegasi")) + + stop = timeit.default_timer() print(round(stop - start, 3)) print(sys.version)