so many pep8 fixes

(cherry picked from commit bee125d)
This commit is contained in:
a-tal
2016-12-03 17:04:12 -08:00
committed by Ebag333
parent 510492e5e9
commit d3b6bc1c93
133 changed files with 3371 additions and 3319 deletions

View File

@@ -1,4 +1,4 @@
#===============================================================================
# =============================================================================
# Copyright (C) 2010 Diego Duclos
#
# This file is part of pyfa.
@@ -15,7 +15,7 @@
#
# You should have received a copy of the GNU General Public License
# along with pyfa. If not, see <http://www.gnu.org/licenses/>.
#===============================================================================
# =============================================================================
import eos.db

View File

@@ -1,4 +1,4 @@
#===============================================================================
# =============================================================================
# Copyright (C) 2010 Diego Duclos
#
# This file is part of pyfa.
@@ -15,7 +15,7 @@
#
# You should have received a copy of the GNU General Public License
# along with pyfa. If not, see <http://www.gnu.org/licenses/>.
#===============================================================================
# =============================================================================
import copy
import itertools
@@ -37,6 +37,7 @@ from eos.saveddata.implant import Implant as es_Implant
from eos.saveddata.character import Character as es_Character
from eos.saveddata.module import Slot as es_Slot, Module as es_Module
from eos.saveddata.fighter import Fighter as es_Fighter
from service.fit import Fit as es_Fit
logger = logging.getLogger(__name__)
@@ -54,7 +55,7 @@ class CharacterImportThread(threading.Thread):
# we try to parse api XML data first
with open(path, mode='r') as charFile:
sheet = ParseXML(charFile)
char = sCharacter.new(sheet.name+" (imported)")
char = sCharacter.new(sheet.name + " (imported)")
sCharacter.apiUpdateCharSheet(char.ID, sheet.skills)
except:
# if it's not api XML data, try this
@@ -72,7 +73,7 @@ class CharacterImportThread(threading.Thread):
"typeID": int(skill.getAttribute("typeID")),
"level": int(skill.getAttribute("level")),
})
char = sCharacter.new(name+" (EVEMon)")
char = sCharacter.new(name + " (EVEMon)")
sCharacter.apiUpdateCharSheet(char.ID, skills)
except Exception, e:
print e.message
@@ -91,6 +92,8 @@ class SkillBackupThread(threading.Thread):
def run(self):
path = self.path
sCharacter = Character.getInstance()
sFit = es_Fit.getInstance()
fit = sFit.getFit(self.activeFit)
backupData = ""
if self.saveFmt == "xml" or self.saveFmt == "emp":
backupData = sCharacter.exportXml()
@@ -123,7 +126,7 @@ class Character(object):
self.all5()
def exportText(self):
data = "Pyfa exported plan for \""+self.skillReqsDict['charname']+"\"\n"
data = "Pyfa exported plan for \"" + self.skillReqsDict['charname'] + "\"\n"
data += "=" * 79 + "\n"
data += "\n"
item = ""
@@ -139,7 +142,7 @@ class Character(object):
def exportXml(self):
root = ElementTree.Element("plan")
root.attrib["name"] = "Pyfa exported plan for "+self.skillReqsDict['charname']
root.attrib["name"] = "Pyfa exported plan for " + self.skillReqsDict['charname']
root.attrib["revision"] = config.evemonMinVersion
sorts = ElementTree.SubElement(root, "sorting")
@@ -150,7 +153,7 @@ class Character(object):
skillsSeen = set()
for s in self.skillReqsDict['skills']:
skillKey = str(s["skillID"])+"::"+s["skill"]+"::"+str(int(s["level"]))
skillKey = str(s["skillID"]) + "::" + s["skill"] + "::" + str(int(s["level"]))
if skillKey in skillsSeen:
pass # Duplicate skills confuse EVEMon
else:
@@ -164,7 +167,7 @@ class Character(object):
notes = ElementTree.SubElement(entry, "notes")
notes.text = entry.attrib["skill"]
tree = ElementTree.ElementTree(root)
# tree = ElementTree.ElementTree(root)
data = ElementTree.tostring(root, 'utf-8')
prettydata = minidom.parseString(data).toprettyxml(indent=" ")
@@ -362,7 +365,7 @@ class Character(object):
return char.implants
def checkRequirements(self, fit):
toCheck = []
# toCheck = []
reqs = {}
for thing in itertools.chain(fit.modules, fit.drones, fit.fighters, (fit.ship,)):
if isinstance(thing, es_Module) and thing.slot == es_Slot.RIG:

View File

@@ -42,4 +42,4 @@ CONVERSIONS = {
"Unit W-634's Modified Drone Control Unit": "Unit W-634's Modified Fighter Support Unit",
"Heavy Shadow Serpentis Stasis Grappler": "Shadow Serpentis Heavy Stasis Grappler",
"Heavy Domination Stasis Grappler": "Domination Heavy Stasis Grappler",
}
}

View File

@@ -96,4 +96,4 @@ CONVERSIONS = {
"Micro S95a Remote Shield Booster": "'Micro' Remote Shield Booster",
"Large 'Atonement' Remote Shield Booster": "Large Murky Compact Remote Shield Booster",
"E50 Prototype Energy Vampire": "Medium Knave Scoped Energy Nosferatu",
}
}

View File

@@ -7,4 +7,3 @@ CONVERSIONS = {
"Capital Coaxial Remote Armor Repairer Blueprint": "CONCORD Capital Remote Armor Repairer Blueprint",
"Capital Murky Remote Shield Booster Blueprint": "CONCORD Capital Remote Shield Booster Blueprint",
}

View File

@@ -10,4 +10,4 @@ CONVERSIONS = {
"'Distributor' Guidance Disruptor I Blueprint": "'Distributor' Guidance Disruptor Blueprint",
"Highstroke Scoped Guidance Disruptor I": "Highstroke Scoped Guidance Disruptor",
"A-211 Enduring Guidance Disruptor I": "A-211 Enduring Guidance Disruptor",
}
}

View File

@@ -358,4 +358,4 @@ CONVERSIONS = {
"Wavelength Signal Enhancer I": "F-89 Compact Signal Amplifier",
"Type-D Attenuation Signal Augmentation": "F-89 Compact Signal Amplifier",
"Indirect Scanning Dampening Unit I": "Phased Muon Scoped Sensor Dampener",
}
}

View File

@@ -1,4 +1,4 @@
#===============================================================================
# =============================================================================
# Copyright (C) 2010 Diego Duclos
#
# This file is part of pyfa.
@@ -15,7 +15,7 @@
#
# You should have received a copy of the GNU General Public License
# along with pyfa. If not, see <http://www.gnu.org/licenses/>.
#===============================================================================
# =============================================================================
import copy
@@ -24,6 +24,8 @@ from eos.saveddata.damagePattern import DamagePattern as es_DamagePattern
class ImportError(Exception):
pass
class DamagePattern():
instance = None
@classmethod
@@ -79,7 +81,7 @@ class DamagePattern():
if lenImports == 0:
raise ImportError("No patterns found for import")
if lenImports != num:
raise ImportError("%d patterns imported from clipboard; %d had errors"%(num, num-lenImports))
raise ImportError("%d patterns imported from clipboard; %d had errors" % (num, num - lenImports))
def exportPatterns(self):
patterns = self.getDamagePatternList()

View File

@@ -1,4 +1,4 @@
#-----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# eveapi - EVE Online API access
#
# Copyright (c)2007-2014 Jamie "Entity" van den Berge <jamie@hlekkir.com>
@@ -24,7 +24,7 @@
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE
#
#-----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
#
# Version: 1.3.0 - 27 May 2014
# - Added set_user_agent() module-level function to set the User-Agent header
@@ -145,10 +145,10 @@
# Requirements:
# Python 2.4+
#
#-----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# This eveapi has been modified for pyfa.
#
# Specifically, the entire network request/response has been substituted for
@@ -156,7 +156,7 @@
#
# Additionally, various other parts have been changed to support urllib2
# responses instead of httplib
#-----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
import urlparse
@@ -174,7 +174,8 @@ proxySSL = False
_default_useragent = "eveapi.py/1.3"
_useragent = None # use set_user_agent() to set this.
#-----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
def set_cast_func(func):
"""Sets an alternative value casting function for the XML parser.
@@ -185,25 +186,30 @@ def set_cast_func(func):
global _castfunc
_castfunc = _autocast if func is None else func
def set_user_agent(user_agent_string):
"""Sets a User-Agent for any requests sent by the library."""
global _useragent
_useragent = user_agent_string
class Error(StandardError):
class Error(Exception):
def __init__(self, code, message):
self.code = code
self.args = (message.rstrip("."),)
def __unicode__(self):
return u'%s [code=%s]' % (self.args[0], self.code)
class RequestError(Error):
pass
class AuthenticationError(Error):
pass
class ServerError(Error):
pass
@@ -303,19 +309,16 @@ def _ParseXML(response, fromContext, storeFunc):
return result
#-----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# API Classes
#-----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
_listtypes = (list, tuple, dict)
_unspecified = []
class _Context(object):
class _Context(object):
def __init__(self, root, path, parentDict, newKeywords=None):
self._root = root or self
self._path = path
@@ -356,20 +359,18 @@ class _Context(object):
class _AuthContext(_Context):
def character(self, characterID):
# returns a copy of this connection object but for every call made
# through it, it will add the folder "/char" to the url, and the
# characterID to the parameters passed.
return _Context(self._root, self._path + "/char", self.parameters, {"characterID":characterID})
return _Context(self._root, self._path + "/char", self.parameters, {"characterID": characterID})
def corporation(self, characterID):
# same as character except for the folder "/corp"
return _Context(self._root, self._path + "/corp", self.parameters, {"characterID":characterID})
return _Context(self._root, self._path + "/corp", self.parameters, {"characterID": characterID})
class _RootContext(_Context):
def auth(self, **kw):
if len(kw) == 2 and (("keyID" in kw and "vCode" in kw) or ("userID" in kw and "apiKey" in kw)):
return _AuthContext(self._root, self._path, self.parameters, kw)
@@ -397,7 +398,7 @@ class _RootContext(_Context):
if response is None:
network = Network.getInstance()
req = self._scheme+'://'+self._host+path
req = self._scheme + '://' + self._host + path
response = network.request(req, network.EVE, kw)
@@ -423,9 +424,11 @@ class _RootContext(_Context):
# implementor is not handling fallbacks...
return _ParseXML(response, True, store and (lambda obj: cache.store(self._host, path, kw, response, obj)))
#-----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# XML Parser
#-----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
def _autocast(key, value):
# attempts to cast an XML string to the most probable type.
@@ -452,11 +455,11 @@ def _autocast(key, value):
# couldn't cast. return string unchanged.
return value
_castfunc = _autocast
class _Parser(object):
def Parse(self, data, isStream=False):
self.container = self.root = None
self._cdata = False
@@ -475,7 +478,6 @@ class _Parser(object):
p.Parse(data, True)
return self.root
def tag_cdatasection_enter(self):
# encountered an explicit CDATA tag.
self._cdata = True
@@ -501,21 +503,20 @@ class _Parser(object):
if name == "rowset":
# for rowsets, use the given name
try:
columns = attributes[attributes.index('columns')+1].replace(" ", "").split(",")
columns = attributes[attributes.index('columns') + 1].replace(" ", "").split(",")
except ValueError:
# rowset did not have columns tag set (this is a bug in API)
# columns will be extracted from first row instead.
columns = []
try:
priKey = attributes[attributes.index('key')+1]
priKey = attributes[attributes.index('key') + 1]
this = IndexRowset(cols=columns, key=priKey)
except ValueError:
this = Rowset(cols=columns)
this._name = attributes[attributes.index('name')+1]
this.__catch = "row" # tag to auto-add to rowset.
this._name = attributes[attributes.index('name') + 1]
this.__catch = "row" # tag to auto-add to rowset.
else:
this = Element()
this._name = name
@@ -528,7 +529,7 @@ class _Parser(object):
if name != "eveapi":
raise RuntimeError("Invalid API response")
try:
this.version = attributes[attributes.index("version")+1]
this.version = attributes[attributes.index("version") + 1]
except KeyError:
raise RuntimeError("Invalid API response")
self.root = this
@@ -541,16 +542,18 @@ class _Parser(object):
# such as rawQuantity in the assets lists.
# In either case the tag is assumed to be correct and the rowset's
# columns are overwritten with the tag's version, if required.
numAttr = len(attributes)/2
numAttr = len(attributes) / 2
numCols = len(self.container._cols)
if numAttr < numCols and (attributes[-2] == self.container._cols[-1]):
# the row data is missing attributes that were defined in the rowset.
# missing attributes' values will be set to None.
fixed = []
row_idx = 0; hdr_idx = 0; numAttr*=2
row_idx = 0
hdr_idx = 0
numAttr *= 2
for col in self.container._cols:
if col == attributes[row_idx]:
fixed.append(_castfunc(col, attributes[row_idx+1]))
fixed.append(_castfunc(col, attributes[row_idx + 1]))
row_idx += 2
else:
fixed.append(None)
@@ -560,7 +563,7 @@ class _Parser(object):
if not self.container._cols or (numAttr > numCols):
# the row data contains more attributes than were defined.
self.container._cols = attributes[0::2]
self.container.append([_castfunc(attributes[i], attributes[i+1]) for i in xrange(0, len(attributes), 2)])
self.container.append([_castfunc(attributes[i], attributes[i + 1]) for i in xrange(0, len(attributes), 2)])
# </hack>
this._isrow = True
@@ -611,7 +614,7 @@ class _Parser(object):
if this is self.root:
del this._attributes
#this.__dict__.pop("_attributes", None)
# this.__dict__.pop("_attributes", None)
return
# we're done with current tag, so we can pop it off. This means that
@@ -651,7 +654,7 @@ class _Parser(object):
e._name = this._name
setattr(self.container, this._name, e)
for i in xrange(0, len(attributes), 2):
setattr(e, attributes[i], attributes[i+1])
setattr(e, attributes[i], attributes[i + 1])
else:
# tag of the form: <tag />, treat as empty string.
setattr(self.container, this._name, "")
@@ -663,7 +666,7 @@ class _Parser(object):
# multiples of some tag or attribute. Code below handles this case.
elif isinstance(sibling, Rowset):
# its doppelganger is a rowset, append this as a row to that.
row = [_castfunc(attributes[i], attributes[i+1]) for i in xrange(0, len(attributes), 2)]
row = [_castfunc(attributes[i], attributes[i + 1]) for i in xrange(0, len(attributes), 2)]
row.extend([getattr(this, col) for col in attributes2])
sibling.append(row)
elif isinstance(sibling, Element):
@@ -672,11 +675,11 @@ class _Parser(object):
# into a Rowset, adding the sibling element and this one.
rs = Rowset()
rs.__catch = rs._name = this._name
row = [_castfunc(attributes[i], attributes[i+1]) for i in xrange(0, len(attributes), 2)]+[getattr(this, col) for col in attributes2]
row = [_castfunc(attributes[i], attributes[i + 1]) for i in xrange(0, len(attributes), 2)] + [getattr(this, col) for col in attributes2]
rs.append(row)
row = [getattr(sibling, attributes[i]) for i in xrange(0, len(attributes), 2)]+[getattr(sibling, col) for col in attributes2]
row = [getattr(sibling, attributes[i]) for i in xrange(0, len(attributes), 2)] + [getattr(sibling, col) for col in attributes2]
rs.append(row)
rs._cols = [attributes[i] for i in xrange(0, len(attributes), 2)]+[col for col in attributes2]
rs._cols = [attributes[i] for i in xrange(0, len(attributes), 2)] + [col for col in attributes2]
setattr(self.container, this._name, rs)
else:
# something else must have set this attribute already.
@@ -685,29 +688,31 @@ class _Parser(object):
# Now fix up the attributes and be done with it.
for i in xrange(0, len(attributes), 2):
this.__dict__[attributes[i]] = _castfunc(attributes[i], attributes[i+1])
this.__dict__[attributes[i]] = _castfunc(attributes[i], attributes[i + 1])
return
#-----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# XML Data Containers
#-----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# The following classes are the various container types the XML data is
# unpacked into.
#
# Note that objects returned by API calls are to be treated as read-only. This
# is not enforced, but you have been warned.
#-----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
class Element(object):
# Element is a namespace for attributes and nested tags
def __str__(self):
return "<Element '%s'>" % self._name
_fmt = u"%s:%s".__mod__
class Row(object):
# A Row is a single database record associated with a Rowset.
# The fields in the record are accessed as attributes by their respective
@@ -750,7 +755,7 @@ class Row(object):
try:
return self._row[self._cols.index(this)]
except:
raise AttributeError, this
raise AttributeError(this)
def __getitem__(self, this):
return self._row[self._cols.index(this)]
@@ -823,7 +828,6 @@ class Rowset(object):
for line in self._rows:
yield [line[x] for x in i]
# -------------
def __init__(self, cols=None, rows=None):
@@ -871,7 +875,6 @@ class Rowset(object):
self._cols, self._rows = state
class IndexRowset(Rowset):
# An IndexRowset is a Rowset that keeps an index on a column.
#
@@ -888,7 +891,7 @@ class IndexRowset(Rowset):
if row is None:
if default:
return default[0]
raise KeyError, key
raise KeyError(key)
return Row(self._cols, row)
# -------------
@@ -960,7 +963,7 @@ class FilterRowset(object):
if id in items:
items[id][row[idfield2]] = row
else:
items[id] = {row[idfield2]:row}
items[id] = {row[idfield2]: row}
self._cols = cols
self.key = key

View File

@@ -17,10 +17,14 @@
# along with pyfa. If not, see <http://www.gnu.org/licenses/>.
# ===============================================================================
import locale
import copy
import threading
import logging
import wx
from codecs import open
import xml.parsers.expat
import eos.db
from eos.types import State, Slot, Module, Drone, Fighter, Fit as FitType
@@ -80,8 +84,8 @@ class Fit(object):
"showMarketShortcuts": False,
"enableGaugeAnimation": True,
"exportCharges": True,
"openFitInNew": False
}
"openFitInNew": False,
}
self.serviceFittingOptions = SettingsProvider.getInstance().getSettings(
"pyfaServiceFittingOptions", serviceFittingDefaultOptions)
@@ -532,7 +536,7 @@ class Fit(object):
# Gather modules and convert Cargo item to Module, silently return if not a module
try:
cargoP = Module(cargo.item)
cargoP = es_Module(cargo.item)
cargoP.owner = fit
if cargoP.isValidState(State.ACTIVE):
cargoP.state = State.ACTIVE
@@ -665,7 +669,7 @@ class Fit(object):
break
'''
if fighter is None:
fighter = Fighter(item)
fighter = es_Fighter(item)
used = fit.getSlotsUsed(fighter.slot)
total = fit.getNumSlots(fighter.slot)
standardAttackActive = False
@@ -756,7 +760,7 @@ class Fit(object):
d.amount = amount
d.amountActive = amount if active else 0
newD = Drone(d.item)
newD = es_Drone(d.item)
newD.amount = total - amount
newD.amountActive = newD.amount if active else 0
l.append(newD)

View File

@@ -1,4 +1,4 @@
#===============================================================================
# =============================================================================
# Copyright (C) 2010 Diego Duclos
#
# This file is part of pyfa.
@@ -15,7 +15,7 @@
#
# You should have received a copy of the GNU General Public License
# along with pyfa. If not, see <http://www.gnu.org/licenses/>.
#===============================================================================
# =============================================================================
import copy
import eos.db

View File

@@ -1,4 +1,4 @@
#===============================================================================
# =============================================================================
# Copyright (C) 2016 Ryan Holmes
#
# This file is part of pyfa.
@@ -15,7 +15,7 @@
#
# You should have received a copy of the GNU General Public License
# along with pyfa. If not, see <http://www.gnu.org/licenses/>.
#===============================================================================
# =============================================================================
import copy
@@ -27,8 +27,9 @@ from eos.saveddata.implantSet import ImplantSet as es_ImplantSet
class ImportError(Exception):
pass
class ImplantSets():
class ImplantSets(object):
instance = None
@classmethod
def getInstance(cls):
if cls.instance is None:
@@ -43,8 +44,7 @@ class ImplantSets():
return eos.db.getImplantSet(name)
def getImplants(self, setID):
set = eos.db.getImplantSet(setID)
return set.implants
return eos.db.getImplantSet(setID).implants
def addImplant(self, setID, itemID):
set = eos.db.getImplantSet(setID)
@@ -53,30 +53,29 @@ class ImplantSets():
eos.db.commit()
def removeImplant(self, setID, implant):
set = eos.db.getImplantSet(setID)
set.implants.remove(implant)
eos.db.getImplantSet(setID).implants.remove(implant)
eos.db.commit()
def newSet(self, name):
s = es_ImplantSet()
s.name = name
eos.db.save(s)
return s
implant_set = es_ImplantSet()
implant_set.name = name
eos.db.save(implant_set)
return implant_set
def renameSet(self, s, newName):
s.name = newName
eos.db.save(s)
def renameSet(self, implant_set, newName):
implant_set.name = newName
eos.db.save(implant_set)
def deleteSet(self, s):
eos.db.remove(s)
def deleteSet(self, implant_set):
eos.db.remove(implant_set)
def copySet(self, s):
newS = copy.deepcopy(s)
def copySet(self, implant_set):
newS = copy.deepcopy(implant_set)
eos.db.save(newS)
return newS
def saveChanges(self, s):
eos.db.save(s)
def saveChanges(self, implant_set):
eos.db.save(implant_set)
def importSets(self, text):
sMkt = Market.getInstance()
@@ -101,16 +100,16 @@ class ImplantSets():
errors += 1
continue
for set in self.getImplantSetList():
lookup[set.name] = set
for implant_set in self.getImplantSetList():
lookup[implant_set.name] = implant_set
for set in newSets:
if set.name in lookup:
match = lookup[set.name]
for implant in set.implants:
for implant_set in newSets:
if implant_set.name in lookup:
match = lookup[implant_set.name]
for implant in implant_set.implants:
match.implants.append(es_Implant(implant.item))
else:
eos.db.save(set)
eos.db.save(implant_set)
eos.db.commit()
@@ -118,7 +117,8 @@ class ImplantSets():
if lenImports == 0:
raise ImportError("No patterns found for import")
if errors > 0:
raise ImportError("%d sets imported from clipboard; %d errors"%(lenImports, errors))
raise ImportError("%d sets imported from clipboard; %d errors" %
(lenImports, errors))
def exportSets(self):
patterns = self.getImplantSetList()

View File

@@ -1,4 +1,4 @@
#===============================================================================
# =============================================================================
# Copyright (C) 2014 Ryan Holmes
#
# This file is part of pyfa.
@@ -15,7 +15,7 @@
#
# You should have received a copy of the GNU General Public License
# along with pyfa. If not, see <http://www.gnu.org/licenses/>.
#===============================================================================
# =============================================================================
import urllib2
@@ -54,6 +54,7 @@ class Network():
UPDATE = 8
_instance = None
@classmethod
def getInstance(cls):
if cls._instance is None:
@@ -63,7 +64,7 @@ class Network():
def request(self, url, type, data=None):
# URL is required to be https as of right now
#print "Starting request: %s\n\tType: %s\n\tPost Data: %s"%(url,type,data)
# print "Starting request: %s\n\tType: %s\n\tPost Data: %s"%(url,type,data)
# Make sure request is enabled
access = NetworkSettings.getInstance().getAccess()
@@ -73,7 +74,7 @@ class Network():
# Set up some things for the request
versionString = "{0} {1} - {2} {3}".format(config.version, config.tag, config.expansionName, config.expansionVersion)
headers = {"User-Agent" : "pyfa {0} (Python-urllib2)".format(versionString)}
headers = {"User-Agent": "pyfa {0} (Python-urllib2)".format(versionString)}
proxy = NetworkSettings.getInstance().getProxySettings()
if proxy is not None:

View File

@@ -1,4 +1,4 @@
#===============================================================================
# =============================================================================
# Copyright (C) 2014 Ryan Holmes
#
# This file is part of pyfa.
@@ -15,7 +15,7 @@
#
# You should have received a copy of the GNU General Public License
# along with pyfa. If not, see <http://www.gnu.org/licenses/>.
#===============================================================================
# =============================================================================
import re
import os
@@ -31,13 +31,13 @@ from codecs import open
import xml.parsers.expat
from eos import db
from service.fit import Fit
import wx
from eos.types import Fit, State, Slot, Module, Cargo, Ship, Drone, Implant, Booster, Citadel
from eos.types import State, Slot, Module, Cargo, Fit, Ship, Drone, Implant, Booster, Citadel
from service.crest import Crest
from service.market import Market
from service.fit import Fit
logger = logging.getLogger("pyfa.service.port")
@@ -48,15 +48,17 @@ except ImportError:
EFT_SLOT_ORDER = [Slot.LOW, Slot.MED, Slot.HIGH, Slot.RIG, Slot.SUBSYSTEM]
INV_FLAGS = {
Slot.LOW: 11,
Slot.MED: 19,
Slot.HIGH: 27,
Slot.RIG: 92,
Slot.SUBSYSTEM: 125}
Slot.LOW: 11,
Slot.MED: 19,
Slot.HIGH: 27,
Slot.RIG: 92,
Slot.SUBSYSTEM: 125
}
INV_FLAG_CARGOBAY = 5
INV_FLAG_DRONEBAY = 87
class Port(object):
def backupFits(self, path, callback):
thread = FitBackupThread(path, callback)
@@ -185,7 +187,7 @@ class Port(object):
# max length is 50 characters
name = ofit.name[:47] + '...' if len(ofit.name) > 50 else ofit.name
fit['name'] = name
fit['ship']['href'] = "%sinventory/types/%d/"%(eve._authed_endpoint, ofit.ship.item.ID)
fit['ship']['href'] = "%sinventory/types/%d/" % (eve._authed_endpoint, ofit.ship.item.ID)
fit['ship']['id'] = ofit.ship.item.ID
fit['ship']['name'] = ''
@@ -213,7 +215,7 @@ class Port(object):
slotNum[slot] += 1
item['quantity'] = 1
item['type']['href'] = "%sinventory/types/%d/"%(eve._authed_endpoint, module.item.ID)
item['type']['href'] = "%sinventory/types/%d/" % (eve._authed_endpoint, module.item.ID)
item['type']['id'] = module.item.ID
item['type']['name'] = ''
fit['items'].append(item)
@@ -228,7 +230,7 @@ class Port(object):
item = nested_dict()
item['flag'] = INV_FLAG_CARGOBAY
item['quantity'] = cargo.amount
item['type']['href'] = "%sinventory/types/%d/"%(eve._authed_endpoint, cargo.item.ID)
item['type']['href'] = "%sinventory/types/%d/" % (eve._authed_endpoint, cargo.item.ID)
item['type']['id'] = cargo.item.ID
item['type']['name'] = ''
fit['items'].append(item)
@@ -237,7 +239,7 @@ class Port(object):
item = nested_dict()
item['flag'] = INV_FLAG_CARGOBAY
item['quantity'] = amount
item['type']['href'] = "%sinventory/types/%d/"%(eve._authed_endpoint, chargeID)
item['type']['href'] = "%sinventory/types/%d/" % (eve._authed_endpoint, chargeID)
item['type']['id'] = chargeID
item['type']['name'] = ''
fit['items'].append(item)
@@ -246,7 +248,7 @@ class Port(object):
item = nested_dict()
item['flag'] = INV_FLAG_DRONEBAY
item['quantity'] = drone.amount
item['type']['href'] = "%sinventory/types/%d/"%(eve._authed_endpoint, drone.item.ID)
item['type']['href'] = "%sinventory/types/%d/" % (eve._authed_endpoint, drone.item.ID)
item['type']['id'] = drone.item.ID
item['type']['name'] = ''
fit['items'].append(item)
@@ -372,12 +374,12 @@ class Port(object):
except ValueError:
f.ship = Citadel(sMkt.getItem(int(info[0])))
f.name = "{0} - DNA Imported".format(f.ship.item.name)
except UnicodeEncodeError as e:
except UnicodeEncodeError:
def logtransform(s):
if len(s) > 10:
return s[:10] + "..."
return s
logger.exception("Couldn't import ship data %r", [ logtransform(s) for s in info ])
logger.exception("Couldn't import ship data %r", [logtransform(s) for s in info])
return None
moduleList = []

View File

@@ -1,4 +1,4 @@
#===============================================================================
# =============================================================================
# Copyright (C) 2010 Diego Duclos
#
# This file is part of pyfa.
@@ -15,7 +15,7 @@
#
# You should have received a copy of the GNU General Public License
# along with pyfa. If not, see <http://www.gnu.org/licenses/>.
#===============================================================================
# =============================================================================
import threading
import os
@@ -35,16 +35,15 @@ class PrefetchThread(threading.Thread):
except:
pass
prefetch = PrefetchThread()
prefetch.daemon = True
prefetch.start()
########
# The following code does not belong here, however until we rebuild skeletons
# to include modified pyfa.py, this is the best place to put it. See GH issue
# #176
# @ todo: move this to pyfa.py
########
# Make sure the saveddata db exists
if config.savePath and not os.path.exists(config.savePath):

View File

@@ -1,4 +1,4 @@
#===============================================================================
# =============================================================================
# Copyright (C) 2010 Diego Duclos
#
# This file is part of pyfa.
@@ -15,7 +15,7 @@
#
# You should have received a copy of the GNU General Public License
# along with pyfa. If not, see <http://www.gnu.org/licenses/>.
#===============================================================================
# =============================================================================
import time
@@ -24,12 +24,12 @@ from xml.dom import minidom
from eos import db
from service.network import Network, TimeoutError
VALIDITY = 24*60*60 # Price validity period, 24 hours
REREQUEST = 4*60*60 # Re-request delay for failed fetches, 4 hours
TIMEOUT = 15*60 # Network timeout delay for connection issues, 15 minutes
VALIDITY = 24 * 60 * 60 # Price validity period, 24 hours
REREQUEST = 4 * 60 * 60 # Re-request delay for failed fetches, 4 hours
TIMEOUT = 15 * 60 # Network timeout delay for connection issues, 15 minutes
class Price():
class Price(object):
@classmethod
def fetchPrices(cls, prices):
"""Fetch all prices passed to this method"""
@@ -65,7 +65,7 @@ class Price():
# Base request URL
baseurl = "https://eve-central.com/api/marketstat"
data.append(("usesystem", 30000142)) # Use Jita for market
data.append(("usesystem", 30000142)) # Use Jita for market
for typeID in toRequest: # Add all typeID arguments
data.append(("typeid", typeID))

View File

@@ -5,6 +5,7 @@ class NullHandler(logging.Handler):
def emit(self, record):
pass
logger = logging.getLogger('pycrest')
logger.addHandler(NullHandler())

View File

@@ -21,4 +21,4 @@ def text_(s, encoding='latin-1', errors='strict'): # pragma: no cover
def bytes_(s, encoding='latin-1', errors='strict'): # pragma: no cover
if isinstance(s, text_type):
return s.encode(encoding, errors)
return s
return s

View File

@@ -1,2 +1,2 @@
class APIException(Exception):
pass
pass

View File

@@ -243,19 +243,18 @@ class EVE(APIConnection):
def temptoken_authorize(self, access_token=None, expires_in=0, refresh_token=None):
self.set_auth_values({'access_token': access_token,
'refresh_token': refresh_token,
'expires_in': expires_in})
'refresh_token': refresh_token,
'expires_in': expires_in})
class AuthedConnection(EVE):
def __call__(self):
if not self._data:
self._data = APIObject(self.get(self._endpoint), self)
return self._data
def whoami(self):
#if 'whoami' not in self._cache:
# if 'whoami' not in self._cache:
# print "Setting this whoami cache"
# self._cache['whoami'] = self.get("%s/verify" % self._oauth_endpoint)
return self.get("%s/verify" % self._oauth_endpoint)
@@ -275,6 +274,7 @@ class AuthedConnection(EVE):
self.refr_authorize(self.refresh_token)
return self._session.delete(resource, params=params)
class APIObject(object):
def __init__(self, parent, connection):
self._dict = {}

View File

@@ -20,8 +20,7 @@ except:
from urllib3.packages.ssl_match_hostname import match_hostname
class WeakCiphersHTTPSConnection(
urllib3.connection.VerifiedHTTPSConnection): # pragma: no cover
class WeakCiphersHTTPSConnection(urllib3.connection.VerifiedHTTPSConnection): # pragma: no cover
# Python versions >=2.7.9 and >=3.4.1 do not (by default) allow ciphers
# with MD5. Unfortunately, the CREST public server _only_ supports
@@ -74,16 +73,20 @@ class WeakCiphersHTTPSConnection(
# Wrap socket using verification with the root certs in
# trusted_root_certs
self.sock = ssl_.ssl_wrap_socket(conn, self.key_file, self.cert_file,
cert_reqs=resolved_cert_reqs,
ca_certs=self.ca_certs,
server_hostname=hostname,
ssl_version=resolved_ssl_version,
ciphers=self.ciphers)
self.sock = ssl_.ssl_wrap_socket(
conn,
self.key_file,
self.cert_file,
cert_reqs=resolved_cert_reqs,
ca_certs=self.ca_certs,
server_hostname=hostname,
ssl_version=resolved_ssl_version,
ciphers=self.ciphers,
)
if self.assert_fingerprint:
ssl_.assert_fingerprint(self.sock.getpeercert(binary_form=True),
self.assert_fingerprint)
self.assert_fingerprint)
elif resolved_cert_reqs != ssl.CERT_NONE \
and self.assert_hostname is not False:
cert = self.sock.getpeercert()
@@ -96,8 +99,7 @@ class WeakCiphersHTTPSConnection(
)
match_hostname(cert, self.assert_hostname or hostname)
self.is_verified = (resolved_cert_reqs == ssl.CERT_REQUIRED
or self.assert_fingerprint is not None)
self.is_verified = (resolved_cert_reqs == ssl.CERT_REQUIRED or self.assert_fingerprint is not None)
class WeakCiphersHTTPSConnectionPool(
@@ -110,22 +112,24 @@ class WeakCiphersPoolManager(urllib3.poolmanager.PoolManager):
def _new_pool(self, scheme, host, port):
if scheme == 'https':
return WeakCiphersHTTPSConnectionPool(host, port,
**(self.connection_pool_kw))
return super(WeakCiphersPoolManager, self)._new_pool(scheme, host,
port)
return WeakCiphersHTTPSConnectionPool(host, port, **(self.connection_pool_kw))
return super(WeakCiphersPoolManager, self)._new_pool(scheme, host, port)
class WeakCiphersAdapter(HTTPAdapter):
""""Transport adapter" that allows us to use TLS_RSA_WITH_RC4_128_MD5."""
def init_poolmanager(self, connections, maxsize, block=False,
**pool_kwargs):
def init_poolmanager(self, connections, maxsize, block=False, **pool_kwargs):
# Rewrite of the requests.adapters.HTTPAdapter.init_poolmanager method
# to use WeakCiphersPoolManager instead of urllib3's PoolManager
self._pool_connections = connections
self._pool_maxsize = maxsize
self._pool_block = block
self.poolmanager = WeakCiphersPoolManager(num_pools=connections,
maxsize=maxsize, block=block, strict=True, **pool_kwargs)
self.poolmanager = WeakCiphersPoolManager(
num_pools=connections,
maxsize=maxsize,
block=block,
strict=True,
**pool_kwargs
)

View File

@@ -57,6 +57,7 @@ else {
</html>
'''
# https://github.com/fuzzysteve/CREST-Market-Downloader/
class AuthHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
@@ -73,6 +74,7 @@ class AuthHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def log_message(self, format, *args):
return
# http://code.activestate.com/recipes/425210-simple-stoppable-server-using-socket-timeout/
class StoppableHTTPServer(BaseHTTPServer.HTTPServer):
@@ -102,7 +104,7 @@ class StoppableHTTPServer(BaseHTTPServer.HTTPServer):
self.run = False
def handle_timeout(self):
#logger.debug("Number of tries: %d"%self.tries)
# logger.debug("Number of tries: %d"%self.tries)
self.tries += 1
if self.tries == self.max_tries:
logger.debug("Server timed out waiting for connection")
@@ -117,6 +119,7 @@ class StoppableHTTPServer(BaseHTTPServer.HTTPServer):
pass
self.server_close()
if __name__ == "__main__":
httpd = StoppableHTTPServer(('', 6461), AuthHandler)
thread.start_new_thread(httpd.serve, ())

View File

@@ -1,4 +1,4 @@
#===============================================================================
# =============================================================================
# Copyright (C) 2010 Diego Duclos
#
# This file is part of pyfa.
@@ -15,7 +15,7 @@
#
# You should have received a copy of the GNU General Public License
# along with pyfa. If not, see <http://www.gnu.org/licenses/>.
#===============================================================================
# =============================================================================
import cPickle
import os.path
@@ -23,13 +23,15 @@ import urllib2
import config
class SettingsProvider():
class SettingsProvider(object):
BASE_PATH = os.path.join(config.savePath or ".", "settings")
settings = {}
_instance = None
@classmethod
def getInstance(cls):
if cls._instance == None:
if cls._instance is None:
cls._instance = SettingsProvider()
return cls._instance
@@ -72,7 +74,8 @@ class SettingsProvider():
for settings in self.settings.itervalues():
settings.save()
class Settings():
class Settings(object):
def __init__(self, location, info):
self.location = location
self.info = info
@@ -112,7 +115,7 @@ class Settings():
return self.info.items()
class NetworkSettings():
class NetworkSettings(object):
_instance = None
# constants for serviceNetworkDefaultSettings["mode"] parameter
@@ -122,7 +125,7 @@ class NetworkSettings():
@classmethod
def getInstance(cls):
if cls._instance == None:
if cls._instance is None:
cls._instance = NetworkSettings()
return cls._instance
@@ -190,12 +193,11 @@ class NetworkSettings():
proxy = None
proxAddr = proxPort = ""
proxydict = urllib2.ProxyHandler().proxies
txt = "Auto-detected: "
validPrefixes = ("http", "https")
for prefix in validPrefixes:
if not prefix in proxydict:
if prefix not in proxydict:
continue
proxyline = proxydict[prefix]
proto = "{0}://".format(prefix)
@@ -238,22 +240,21 @@ class NetworkSettings():
self.serviceNetworkSettings["password"] = password
"""
Settings used by the HTML export feature.
"""
class HTMLExportSettings():
class HTMLExportSettings(object):
"""
Settings used by the HTML export feature.
"""
_instance = None
@classmethod
def getInstance(cls):
if cls._instance == None:
if cls._instance is None:
cls._instance = HTMLExportSettings()
return cls._instance
def __init__(self):
serviceHTMLExportDefaultSettings = {"enabled": False, "path": config.pyfaPath + os.sep + 'pyfaFits.html', "minimal": False }
serviceHTMLExportDefaultSettings = {"enabled": False, "path": config.pyfaPath + os.sep + 'pyfaFits.html', "minimal": False}
self.serviceHTMLExportSettings = SettingsProvider.getInstance().getSettings("pyfaServiceHTMLExportSettings", serviceHTMLExportDefaultSettings)
def getEnabled(self):
@@ -262,29 +263,28 @@ class HTMLExportSettings():
def setEnabled(self, enabled):
self.serviceHTMLExportSettings["enabled"] = enabled
def getMinimalEnabled(self):
return self.serviceHTMLExportSettings["minimal"]
def setMinimalEnabled(self, minimal):
self.serviceHTMLExportSettings["minimal"] = minimal
def getPath(self):
return self.serviceHTMLExportSettings["path"]
def setPath(self, path):
self.serviceHTMLExportSettings["path"] = path
"""
Settings used by update notification
"""
class UpdateSettings():
class UpdateSettings(object):
"""
Settings used by update notification
"""
_instance = None
@classmethod
def getInstance(cls):
if cls._instance == None:
if cls._instance is None:
cls._instance = UpdateSettings()
return cls._instance
@@ -294,7 +294,7 @@ class UpdateSettings():
# Updates are completely suppressed via network settings
# prerelease - If True, suppress prerelease notifications
# version - Set to release tag that user does not want notifications for
serviceUpdateDefaultSettings = {"prerelease": True, 'version': None }
serviceUpdateDefaultSettings = {"prerelease": True, 'version': None}
self.serviceUpdateSettings = SettingsProvider.getInstance().getSettings("pyfaServiceUpdateSettings", serviceUpdateDefaultSettings)
def get(self, type):
@@ -303,7 +303,8 @@ class UpdateSettings():
def set(self, type, value):
self.serviceUpdateSettings[type] = value
class CRESTSettings():
class CRESTSettings(object):
_instance = None
@classmethod

View File

@@ -1,4 +1,4 @@
#===============================================================================
# =============================================================================
# Copyright (C) 2014 Ryan Holmes
#
# This file is part of pyfa.
@@ -15,7 +15,7 @@
#
# You should have received a copy of the GNU General Public License
# along with pyfa. If not, see <http://www.gnu.org/licenses/>.
#===============================================================================
# =============================================================================
import copy
@@ -81,7 +81,7 @@ class TargetResists(object):
if lenImports == 0:
raise ImportError("No patterns found for import")
if lenImports != num:
raise ImportError("%d patterns imported from clipboard; %d had errors"%(num, num-lenImports))
raise ImportError("%d patterns imported from clipboard; %d had errors" % (num, num - lenImports))
def exportPatterns(self):
patterns = self.getTargetResistsList()

View File

@@ -1,4 +1,4 @@
#===============================================================================
# =============================================================================
# Copyright (C) 2014 Ryan Holmes
#
# This file is part of pyfa.
@@ -15,7 +15,7 @@
#
# You should have received a copy of the GNU General Public License
# along with pyfa. If not, see <http://www.gnu.org/licenses/>.
#===============================================================================
# =============================================================================
import threading
import json
@@ -28,6 +28,7 @@ import config
from service.network import Network
from service.settings import UpdateSettings
class CheckUpdateThread(threading.Thread):
def __init__(self, callback):
threading.Thread.__init__(self)
@@ -49,7 +50,7 @@ class CheckUpdateThread(threading.Thread):
continue
# Handle use-case of updating to suppressed version
if self.settings.get('version') == 'v'+config.version:
if self.settings.get('version') == 'v' + config.version:
self.settings.set('version', None)
# Suppress version
@@ -63,15 +64,15 @@ class CheckUpdateThread(threading.Thread):
rVersion = release['tag_name'].replace('v', '', 1)
if config.tag is 'git' and not release['prerelease'] and self.versiontuple(rVersion) >= self.versiontuple(config.version):
wx.CallAfter(self.callback, release) # git (dev/Singularity) -> Stable
wx.CallAfter(self.callback, release) # git (dev/Singularity) -> Stable
elif config.expansionName is not "Singularity":
if release['prerelease']:
wx.CallAfter(self.callback, release) # Stable -> Singularity
wx.CallAfter(self.callback, release) # Stable -> Singularity
elif self.versiontuple(rVersion) > self.versiontuple(config.version):
wx.CallAfter(self.callback, release) # Stable -> Stable
wx.CallAfter(self.callback, release) # Stable -> Stable
else:
if release['prerelease'] and rVersion > config.expansionVersion:
wx.CallAfter(self.callback, release) # Singularity -> Singularity
wx.CallAfter(self.callback, release) # Singularity -> Singularity
break
except:
pass
@@ -79,10 +80,9 @@ class CheckUpdateThread(threading.Thread):
def versiontuple(self, v):
return tuple(map(int, (v.split("."))))
class Update():
instance = None
def __init__(self):
pass
def CheckUpdate(self, callback):
thread = CheckUpdateThread(callback)
@@ -90,6 +90,6 @@ class Update():
@classmethod
def getInstance(cls):
if cls.instance == None:
if cls.instance is None:
cls.instance = Update()
return cls.instance