diff --git a/anki/decks.py b/anki/decks.py index b0e8234ba..d3d193081 100644 --- a/anki/decks.py +++ b/anki/decks.py @@ -295,9 +295,9 @@ class DeckManager: def _canDragAndDrop(self, draggedDeckName, ontoDeckName): if draggedDeckName == ontoDeckName \ - or self._isParent(ontoDeckName, draggedDeckName) \ - or self._isAncestor(draggedDeckName, ontoDeckName): - return False + or self._isParent(ontoDeckName, draggedDeckName) \ + or self._isAncestor(draggedDeckName, ontoDeckName): + return False else: return True diff --git a/anki/importing/supermemo_xml.py b/anki/importing/supermemo_xml.py index 4eb66ee78..0f2129811 100644 --- a/anki/importing/supermemo_xml.py +++ b/anki/importing/supermemo_xml.py @@ -37,24 +37,24 @@ class SmartDict(dict): self.__dict__ = self class SuperMemoElement(SmartDict): - "SmartDict wrapper to store SM Element data" + "SmartDict wrapper to store SM Element data" - def __init__(self, *a, **kw): - SmartDict.__init__(self, *a, **kw) - #default content - self.__dict__['lTitle'] = None - self.__dict__['Title'] = None - self.__dict__['Question'] = None - self.__dict__['Answer'] = None - self.__dict__['Count'] = None - self.__dict__['Type'] = None - self.__dict__['ID'] = None - self.__dict__['Interval'] = None - self.__dict__['Lapses'] = None - self.__dict__['Repetitions'] = None - self.__dict__['LastRepetiton'] = None - self.__dict__['AFactor'] = None - self.__dict__['UFactor'] = None + def __init__(self, *a, **kw): + SmartDict.__init__(self, *a, **kw) + #default content + self.__dict__['lTitle'] = None + self.__dict__['Title'] = None + self.__dict__['Question'] = None + self.__dict__['Answer'] = None + self.__dict__['Count'] = None + self.__dict__['Type'] = None + self.__dict__['ID'] = None + self.__dict__['Interval'] = None + self.__dict__['Lapses'] = None + self.__dict__['Repetitions'] = None + self.__dict__['LastRepetiton'] = None + self.__dict__['AFactor'] = None + self.__dict__['UFactor'] = None @@ -116,7 +116,7 @@ class SupermemoXmlImporter(NoteImporter): self.notes = [] -## TOOLS + ## TOOLS def _fudgeText(self, text): "Replace sm syntax to Anki syntax" @@ -163,7 +163,7 @@ class SupermemoXmlImporter(NoteImporter): return ef -## DEFAULT IMPORTER METHODS + ## DEFAULT IMPORTER METHODS def foreignNotes(self): @@ -184,7 +184,7 @@ class SupermemoXmlImporter(NoteImporter): def fields(self): return 2 -## PARSER METHODS + ## PARSER METHODS def addItemToCards(self,item): "This method actually do conversion" @@ -200,8 +200,8 @@ class SupermemoXmlImporter(NoteImporter): # pre-process scheduling data # convert learning data if (not self.META.resetLearningData - and int(item.Interval) >= 1 - and getattr(item, "LastRepetition", None)): + and int(item.Interval) >= 1 + and getattr(item, "LastRepetition", None)): # migration of LearningData algorithm tLastrep = time.mktime(time.strptime(item.LastRepetition, '%d.%m.%Y')) tToday = time.time() @@ -221,28 +221,28 @@ class SupermemoXmlImporter(NoteImporter): tTaggTitle = False for pattern in self.META.pathsToBeTagged: if item.lTitle is not None and pattern.lower() in " ".join(item.lTitle).lower(): - tTaggTitle = True - break + tTaggTitle = True + break if tTaggTitle or self.META.tagAllTopics: - # normalize - remove diacritic punctuation from unicode chars to ascii - item.lTitle = [ self._unicode2ascii(topic) for topic in item.lTitle] + # normalize - remove diacritic punctuation from unicode chars to ascii + item.lTitle = [ self._unicode2ascii(topic) for topic in item.lTitle] - # Transfrom xyz / aaa / bbb / ccc on Title path to Tag xyzAaaBbbCcc - # clean things like [999] or [111-2222] from title path, example: xyz / [1000-1200] zyx / xyz - # clean whitespaces - # set Capital letters for first char of the word - tmp = list(set([ re.sub('(\[[0-9]+\])' , ' ' , i ).replace('_',' ') for i in item.lTitle ])) - tmp = list(set([ re.sub('(\W)',' ', i ) for i in tmp ])) - tmp = list(set([ re.sub( '^[0-9 ]+$','',i) for i in tmp ])) - tmp = list(set([ capwords(i).replace(' ','') for i in tmp ])) - tags = [ j[0].lower() + j[1:] for j in tmp if j.strip() != ''] + # Transfrom xyz / aaa / bbb / ccc on Title path to Tag xyzAaaBbbCcc + # clean things like [999] or [111-2222] from title path, example: xyz / [1000-1200] zyx / xyz + # clean whitespaces + # set Capital letters for first char of the word + tmp = list(set([ re.sub('(\[[0-9]+\])' , ' ' , i ).replace('_',' ') for i in item.lTitle ])) + tmp = list(set([ re.sub('(\W)',' ', i ) for i in tmp ])) + tmp = list(set([ re.sub( '^[0-9 ]+$','',i) for i in tmp ])) + tmp = list(set([ capwords(i).replace(' ','') for i in tmp ])) + tags = [ j[0].lower() + j[1:] for j in tmp if j.strip() != ''] - note.tags += tags + note.tags += tags - if self.META.tagMemorizedItems and int(item.Interval) >0: - note.tags.append("Memorized") + if self.META.tagMemorizedItems and int(item.Interval) >0: + note.tags.append("Memorized") - self.logger('Element tags\t- ' + repr(note.tags), level=3) + self.logger('Element tags\t- ' + repr(note.tags), level=3) self.notes.append(note) @@ -251,10 +251,10 @@ class SupermemoXmlImporter(NoteImporter): dLevels={0:'',1:'Info',2:'Verbose',3:'Debug'} if level<=self.META.loggerLevel: - #self.deck.updateProgress(_(text)) + #self.deck.updateProgress(_(text)) - if self.META.logToStdOutput: - print(self.__class__.__name__+ " - " + dLevels[level].ljust(9) +' -\t'+ _(text)) + if self.META.logToStdOutput: + print(self.__class__.__name__+ " - " + dLevels[level].ljust(9) +' -\t'+ _(text)) # OPEN AND LOAD @@ -296,14 +296,14 @@ class SupermemoXmlImporter(NoteImporter): "Parse method - parses document elements" if node is None and self.xmldoc is not None: - node = self.xmldoc + node = self.xmldoc _method = "parse_%s" % node.__class__.__name__ if hasattr(self,_method): - parseMethod = getattr(self, _method) - parseMethod(node) + parseMethod = getattr(self, _method) + parseMethod(node) else: - self.logger('No handler for method %s' % _method, level=3) + self.logger('No handler for method %s' % _method, level=3) def parse_Document(self, node): "Parse XML document" @@ -315,11 +315,11 @@ class SupermemoXmlImporter(NoteImporter): _method = "do_%s" % node.tagName if hasattr(self,_method): - handlerMethod = getattr(self, _method) - handlerMethod(node) + handlerMethod = getattr(self, _method) + handlerMethod(node) else: - self.logger('No handler for method %s' % _method, level=3) - #print traceback.print_exc() + self.logger('No handler for method %s' % _method, level=3) + #print traceback.print_exc() def parse_Text(self, node): "Parse text inside elements. Text is stored into local buffer." @@ -353,8 +353,8 @@ class SupermemoXmlImporter(NoteImporter): #strip all saved strings, just for sure for key in list(self.cntElm[-1].keys()): - if hasattr(self.cntElm[-1][key], 'strip'): - self.cntElm[-1][key]=self.cntElm[-1][key].strip() + if hasattr(self.cntElm[-1][key], 'strip'): + self.cntElm[-1][key]=self.cntElm[-1][key].strip() #pop current element smel = self.cntElm.pop() @@ -362,47 +362,47 @@ class SupermemoXmlImporter(NoteImporter): # Process cntElm if is valid Item (and not an Topic etc..) # if smel.Lapses != None and smel.Interval != None and smel.Question != None and smel.Answer != None: if smel.Title is None and smel.Question is not None and smel.Answer is not None: - if smel.Answer.strip() !='' and smel.Question.strip() !='': + if smel.Answer.strip() !='' and smel.Question.strip() !='': - # migrate only memorized otherway skip/continue - if self.META.onlyMemorizedItems and not(int(smel.Interval) > 0): - self.logger('Element skiped \t- not memorized ...', level=3) + # migrate only memorized otherway skip/continue + if self.META.onlyMemorizedItems and not(int(smel.Interval) > 0): + self.logger('Element skiped \t- not memorized ...', level=3) + else: + #import sm element data to Anki + self.addItemToCards(smel) + self.logger("Import element \t- " + smel['Question'], level=3) + + #print element + self.logger('-'*45, level=3) + for key in list(smel.keys()): + self.logger('\t%s %s' % ((key+':').ljust(15),smel[key]), level=3 ) else: - #import sm element data to Anki - self.addItemToCards(smel) - self.logger("Import element \t- " + smel['Question'], level=3) - - #print element - self.logger('-'*45, level=3) - for key in list(smel.keys()): - self.logger('\t%s %s' % ((key+':').ljust(15),smel[key]), level=3 ) - else: - self.logger('Element skiped \t- no valid Q and A ...', level=3) + self.logger('Element skiped \t- no valid Q and A ...', level=3) else: - # now we know that item was topic - # parseing of whole node is now finished + # now we know that item was topic + # parseing of whole node is now finished - # test if it's really topic - if smel.Title is not None: - # remove topic from title list - t = self.cntMeta['title'].pop() - self.logger('End of topic \t- %s' % (t), level=2) + # test if it's really topic + if smel.Title is not None: + # remove topic from title list + t = self.cntMeta['title'].pop() + self.logger('End of topic \t- %s' % (t), level=2) def do_Content(self, node): "Process SM element Content" for child in node.childNodes: - if hasattr(child,'tagName') and child.firstChild is not None: - self.cntElm[-1][child.tagName]=child.firstChild.data + if hasattr(child,'tagName') and child.firstChild is not None: + self.cntElm[-1][child.tagName]=child.firstChild.data def do_LearningData(self, node): "Process SM element LearningData" for child in node.childNodes: - if hasattr(child,'tagName') and child.firstChild is not None: - self.cntElm[-1][child.tagName]=child.firstChild.data + if hasattr(child,'tagName') and child.firstChild is not None: + self.cntElm[-1][child.tagName]=child.firstChild.data # It's being processed in do_Content now #def do_Question(self, node): @@ -428,20 +428,20 @@ class SupermemoXmlImporter(NoteImporter): "Process SM element Type" if len(self.cntBuf) >=1 : - self.cntElm[-1][node.tagName]=self.cntBuf.pop() + self.cntElm[-1][node.tagName]=self.cntBuf.pop() #if __name__ == '__main__': - # for testing you can start it standalone +# for testing you can start it standalone - #file = u'/home/epcim/hg2g/dev/python/sm2anki/ADVENG2EXP.xxe.esc.zaloha_FINAL.xml' - #file = u'/home/epcim/hg2g/dev/python/anki/libanki/tests/importing/supermemo/original_ENGLISHFORBEGGINERS_noOEM.xml' - #file = u'/home/epcim/hg2g/dev/python/anki/libanki/tests/importing/supermemo/original_ENGLISHFORBEGGINERS_oem_1250.xml' - #file = str(sys.argv[1]) - #impo = SupermemoXmlImporter(Deck(),file) - #impo.foreignCards() +#file = u'/home/epcim/hg2g/dev/python/sm2anki/ADVENG2EXP.xxe.esc.zaloha_FINAL.xml' +#file = u'/home/epcim/hg2g/dev/python/anki/libanki/tests/importing/supermemo/original_ENGLISHFORBEGGINERS_noOEM.xml' +#file = u'/home/epcim/hg2g/dev/python/anki/libanki/tests/importing/supermemo/original_ENGLISHFORBEGGINERS_oem_1250.xml' +#file = str(sys.argv[1]) +#impo = SupermemoXmlImporter(Deck(),file) +#impo.foreignCards() - #sys.exit(1) +#sys.exit(1) # vim: ts=4 sts=2 ft=python diff --git a/anki/media.py b/anki/media.py index a2c33026a..a0398c486 100644 --- a/anki/media.py +++ b/anki/media.py @@ -129,12 +129,12 @@ create table meta (dirMod int, lastUsn int); insert into meta values (0, 0); # pylint: disable=import-error import win32api, win32file try: - name = win32file.GetVolumeNameForVolumeMountPoint(self._dir[:3]) + name = win32file.GetVolumeNameForVolumeMountPoint(self._dir[:3]) except: # mapped & unmapped network drive; pray that it's not vfat return if win32api.GetVolumeInformation(name)[4].lower().startswith("fat"): - return True + return True # Adding media ########################################################################## diff --git a/anki/models.py b/anki/models.py index b8a003a5c..95690f111 100644 --- a/anki/models.py +++ b/anki/models.py @@ -168,10 +168,9 @@ select id from cards where nid in (select id from notes where mid = ?)""", def ensureNameUnique(self, m): for mcur in self.all(): - if (mcur['name'] == m['name'] and - mcur['id'] != m['id']): - m['name'] += "-" + checksum(str(time.time()))[:5] - break + if (mcur['name'] == m['name'] and mcur['id'] != m['id']): + m['name'] += "-" + checksum(str(time.time()))[:5] + break def update(self, m): "Add or update an existing model. Used for syncing and merging." diff --git a/aqt/browser.py b/aqt/browser.py index 0ed9aa462..fd1eafa7c 100644 --- a/aqt/browser.py +++ b/aqt/browser.py @@ -953,7 +953,7 @@ by clicking on one on the left.""")) if self.mw.app.keyboardModifiers() & Qt.ControlModifier: cur = str(self.form.searchEdit.lineEdit().text()) if cur and cur != self._searchPrompt: - txt = cur + " " + txt + txt = cur + " " + txt elif self.mw.app.keyboardModifiers() & Qt.ShiftModifier: cur = str(self.form.searchEdit.lineEdit().text()) if cur: diff --git a/aqt/clayout.py b/aqt/clayout.py index e9ea807cf..e88b24581 100644 --- a/aqt/clayout.py +++ b/aqt/clayout.py @@ -63,7 +63,7 @@ class CardLayout(QDialog): def redraw(self): did = None if hasattr(self.parent,"deckChooser"): - did = self.parent.deckChooser.selectedId() + did = self.parent.deckChooser.selectedId() self.cards = self.col.previewCards(self.note, 2, did=did) idx = self.ord if idx >= len(self.cards): diff --git a/aqt/mediasrv.py b/aqt/mediasrv.py index 7ae437ca7..963f7857a 100644 --- a/aqt/mediasrv.py +++ b/aqt/mediasrv.py @@ -21,7 +21,7 @@ def _getExportFolder(): dir = os.path.dirname(os.path.abspath(__file__)) return os.path.abspath(dir + "/../../Resources/web") else: - raise Exception("couldn't find web folder") + raise Exception("couldn't find web folder") _exportFolder = _getExportFolder() diff --git a/aqt/progress.py b/aqt/progress.py index a053c48aa..3e3bf823d 100644 --- a/aqt/progress.py +++ b/aqt/progress.py @@ -49,8 +49,8 @@ class ProgressManager: self.inDB = True # handle GUI events if not self.blockUpdates: - self._maybeShow() - self.app.processEvents(QEventLoop.ExcludeUserInputEvents) + self._maybeShow() + self.app.processEvents(QEventLoop.ExcludeUserInputEvents) self.inDB = False # Safer timers diff --git a/aqt/qt.py b/aqt/qt.py index 1b993dec0..6eb2db004 100644 --- a/aqt/qt.py +++ b/aqt/qt.py @@ -22,9 +22,9 @@ except ImportError: from PyQt5.QtCore import pyqtRemoveInputHook # pylint: disable=no-name-in-module def debug(): - from pdb import set_trace - pyqtRemoveInputHook() - set_trace() + from pdb import set_trace + pyqtRemoveInputHook() + set_trace() import sys, traceback @@ -42,7 +42,7 @@ qtminor = (QT_VERSION & 0x00ff00) >> 8 qtpoint = QT_VERSION & 0xff if qtmajor != 5 or qtminor < 9 or qtminor == 10: - raise Exception("Anki does not support your Qt version.") + raise Exception("Anki does not support your Qt version.") # GUI code assumes python 3.6+ if sys.version_info[0] < 3 or sys.version_info[1] < 6: diff --git a/aqt/toolbar.py b/aqt/toolbar.py index f935fc8ca..bdc6828ca 100644 --- a/aqt/toolbar.py +++ b/aqt/toolbar.py @@ -65,7 +65,7 @@ class Toolbar: self.mw.col.startTimebox() self.mw.moveToState("review") else: - self.mw.onOverview() + self.mw.onOverview() def _addLinkHandler(self): self.mw.onAddCard()