fix inconsistent indentation

This commit is contained in:
Damien Elmes 2019-03-04 16:54:22 +10:00
parent 5185e817fc
commit 4037a034aa
10 changed files with 104 additions and 105 deletions

View file

@ -295,9 +295,9 @@ class DeckManager:
def _canDragAndDrop(self, draggedDeckName, ontoDeckName): def _canDragAndDrop(self, draggedDeckName, ontoDeckName):
if draggedDeckName == ontoDeckName \ if draggedDeckName == ontoDeckName \
or self._isParent(ontoDeckName, draggedDeckName) \ or self._isParent(ontoDeckName, draggedDeckName) \
or self._isAncestor(draggedDeckName, ontoDeckName): or self._isAncestor(draggedDeckName, ontoDeckName):
return False return False
else: else:
return True return True

View file

@ -37,24 +37,24 @@ class SmartDict(dict):
self.__dict__ = self self.__dict__ = self
class SuperMemoElement(SmartDict): class SuperMemoElement(SmartDict):
"SmartDict wrapper to store SM Element data" "SmartDict wrapper to store SM Element data"
def __init__(self, *a, **kw): def __init__(self, *a, **kw):
SmartDict.__init__(self, *a, **kw) SmartDict.__init__(self, *a, **kw)
#default content #default content
self.__dict__['lTitle'] = None self.__dict__['lTitle'] = None
self.__dict__['Title'] = None self.__dict__['Title'] = None
self.__dict__['Question'] = None self.__dict__['Question'] = None
self.__dict__['Answer'] = None self.__dict__['Answer'] = None
self.__dict__['Count'] = None self.__dict__['Count'] = None
self.__dict__['Type'] = None self.__dict__['Type'] = None
self.__dict__['ID'] = None self.__dict__['ID'] = None
self.__dict__['Interval'] = None self.__dict__['Interval'] = None
self.__dict__['Lapses'] = None self.__dict__['Lapses'] = None
self.__dict__['Repetitions'] = None self.__dict__['Repetitions'] = None
self.__dict__['LastRepetiton'] = None self.__dict__['LastRepetiton'] = None
self.__dict__['AFactor'] = None self.__dict__['AFactor'] = None
self.__dict__['UFactor'] = None self.__dict__['UFactor'] = None
@ -116,7 +116,7 @@ class SupermemoXmlImporter(NoteImporter):
self.notes = [] self.notes = []
## TOOLS ## TOOLS
def _fudgeText(self, text): def _fudgeText(self, text):
"Replace sm syntax to Anki syntax" "Replace sm syntax to Anki syntax"
@ -163,7 +163,7 @@ class SupermemoXmlImporter(NoteImporter):
return ef return ef
## DEFAULT IMPORTER METHODS ## DEFAULT IMPORTER METHODS
def foreignNotes(self): def foreignNotes(self):
@ -184,7 +184,7 @@ class SupermemoXmlImporter(NoteImporter):
def fields(self): def fields(self):
return 2 return 2
## PARSER METHODS ## PARSER METHODS
def addItemToCards(self,item): def addItemToCards(self,item):
"This method actually do conversion" "This method actually do conversion"
@ -200,8 +200,8 @@ class SupermemoXmlImporter(NoteImporter):
# pre-process scheduling data # pre-process scheduling data
# convert learning data # convert learning data
if (not self.META.resetLearningData if (not self.META.resetLearningData
and int(item.Interval) >= 1 and int(item.Interval) >= 1
and getattr(item, "LastRepetition", None)): and getattr(item, "LastRepetition", None)):
# migration of LearningData algorithm # migration of LearningData algorithm
tLastrep = time.mktime(time.strptime(item.LastRepetition, '%d.%m.%Y')) tLastrep = time.mktime(time.strptime(item.LastRepetition, '%d.%m.%Y'))
tToday = time.time() tToday = time.time()
@ -221,28 +221,28 @@ class SupermemoXmlImporter(NoteImporter):
tTaggTitle = False tTaggTitle = False
for pattern in self.META.pathsToBeTagged: for pattern in self.META.pathsToBeTagged:
if item.lTitle is not None and pattern.lower() in " ".join(item.lTitle).lower(): if item.lTitle is not None and pattern.lower() in " ".join(item.lTitle).lower():
tTaggTitle = True tTaggTitle = True
break break
if tTaggTitle or self.META.tagAllTopics: if tTaggTitle or self.META.tagAllTopics:
# normalize - remove diacritic punctuation from unicode chars to ascii # normalize - remove diacritic punctuation from unicode chars to ascii
item.lTitle = [ self._unicode2ascii(topic) for topic in item.lTitle] item.lTitle = [ self._unicode2ascii(topic) for topic in item.lTitle]
# Transfrom xyz / aaa / bbb / ccc on Title path to Tag xyzAaaBbbCcc # 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 things like [999] or [111-2222] from title path, example: xyz / [1000-1200] zyx / xyz
# clean whitespaces # clean whitespaces
# set Capital letters for first char of the word # 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('(\[[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('(\W)',' ', i ) for i in tmp ]))
tmp = list(set([ re.sub( '^[0-9 ]+$','',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 ])) tmp = list(set([ capwords(i).replace(' ','') for i in tmp ]))
tags = [ j[0].lower() + j[1:] for j in tmp if j.strip() != ''] 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: if self.META.tagMemorizedItems and int(item.Interval) >0:
note.tags.append("Memorized") 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) self.notes.append(note)
@ -251,10 +251,10 @@ class SupermemoXmlImporter(NoteImporter):
dLevels={0:'',1:'Info',2:'Verbose',3:'Debug'} dLevels={0:'',1:'Info',2:'Verbose',3:'Debug'}
if level<=self.META.loggerLevel: if level<=self.META.loggerLevel:
#self.deck.updateProgress(_(text)) #self.deck.updateProgress(_(text))
if self.META.logToStdOutput: if self.META.logToStdOutput:
print(self.__class__.__name__+ " - " + dLevels[level].ljust(9) +' -\t'+ _(text)) print(self.__class__.__name__+ " - " + dLevels[level].ljust(9) +' -\t'+ _(text))
# OPEN AND LOAD # OPEN AND LOAD
@ -296,14 +296,14 @@ class SupermemoXmlImporter(NoteImporter):
"Parse method - parses document elements" "Parse method - parses document elements"
if node is None and self.xmldoc is not None: if node is None and self.xmldoc is not None:
node = self.xmldoc node = self.xmldoc
_method = "parse_%s" % node.__class__.__name__ _method = "parse_%s" % node.__class__.__name__
if hasattr(self,_method): if hasattr(self,_method):
parseMethod = getattr(self, _method) parseMethod = getattr(self, _method)
parseMethod(node) parseMethod(node)
else: 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): def parse_Document(self, node):
"Parse XML document" "Parse XML document"
@ -315,11 +315,11 @@ class SupermemoXmlImporter(NoteImporter):
_method = "do_%s" % node.tagName _method = "do_%s" % node.tagName
if hasattr(self,_method): if hasattr(self,_method):
handlerMethod = getattr(self, _method) handlerMethod = getattr(self, _method)
handlerMethod(node) handlerMethod(node)
else: else:
self.logger('No handler for method %s' % _method, level=3) self.logger('No handler for method %s' % _method, level=3)
#print traceback.print_exc() #print traceback.print_exc()
def parse_Text(self, node): def parse_Text(self, node):
"Parse text inside elements. Text is stored into local buffer." "Parse text inside elements. Text is stored into local buffer."
@ -353,8 +353,8 @@ class SupermemoXmlImporter(NoteImporter):
#strip all saved strings, just for sure #strip all saved strings, just for sure
for key in list(self.cntElm[-1].keys()): for key in list(self.cntElm[-1].keys()):
if hasattr(self.cntElm[-1][key], 'strip'): if hasattr(self.cntElm[-1][key], 'strip'):
self.cntElm[-1][key]=self.cntElm[-1][key].strip() self.cntElm[-1][key]=self.cntElm[-1][key].strip()
#pop current element #pop current element
smel = self.cntElm.pop() smel = self.cntElm.pop()
@ -362,47 +362,47 @@ class SupermemoXmlImporter(NoteImporter):
# Process cntElm if is valid Item (and not an Topic etc..) # 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.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.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 # migrate only memorized otherway skip/continue
if self.META.onlyMemorizedItems and not(int(smel.Interval) > 0): if self.META.onlyMemorizedItems and not(int(smel.Interval) > 0):
self.logger('Element skiped \t- not memorized ...', level=3) 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: else:
#import sm element data to Anki self.logger('Element skiped \t- no valid Q and A ...', level=3)
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)
else: else:
# now we know that item was topic # now we know that item was topic
# parseing of whole node is now finished # parseing of whole node is now finished
# test if it's really topic # test if it's really topic
if smel.Title is not None: if smel.Title is not None:
# remove topic from title list # remove topic from title list
t = self.cntMeta['title'].pop() t = self.cntMeta['title'].pop()
self.logger('End of topic \t- %s' % (t), level=2) self.logger('End of topic \t- %s' % (t), level=2)
def do_Content(self, node): def do_Content(self, node):
"Process SM element Content" "Process SM element Content"
for child in node.childNodes: for child in node.childNodes:
if hasattr(child,'tagName') and child.firstChild is not None: if hasattr(child,'tagName') and child.firstChild is not None:
self.cntElm[-1][child.tagName]=child.firstChild.data self.cntElm[-1][child.tagName]=child.firstChild.data
def do_LearningData(self, node): def do_LearningData(self, node):
"Process SM element LearningData" "Process SM element LearningData"
for child in node.childNodes: for child in node.childNodes:
if hasattr(child,'tagName') and child.firstChild is not None: if hasattr(child,'tagName') and child.firstChild is not None:
self.cntElm[-1][child.tagName]=child.firstChild.data self.cntElm[-1][child.tagName]=child.firstChild.data
# It's being processed in do_Content now # It's being processed in do_Content now
#def do_Question(self, node): #def do_Question(self, node):
@ -428,20 +428,20 @@ class SupermemoXmlImporter(NoteImporter):
"Process SM element Type" "Process SM element Type"
if len(self.cntBuf) >=1 : if len(self.cntBuf) >=1 :
self.cntElm[-1][node.tagName]=self.cntBuf.pop() self.cntElm[-1][node.tagName]=self.cntBuf.pop()
#if __name__ == '__main__': #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/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_noOEM.xml'
#file = u'/home/epcim/hg2g/dev/python/anki/libanki/tests/importing/supermemo/original_ENGLISHFORBEGGINERS_oem_1250.xml' #file = u'/home/epcim/hg2g/dev/python/anki/libanki/tests/importing/supermemo/original_ENGLISHFORBEGGINERS_oem_1250.xml'
#file = str(sys.argv[1]) #file = str(sys.argv[1])
#impo = SupermemoXmlImporter(Deck(),file) #impo = SupermemoXmlImporter(Deck(),file)
#impo.foreignCards() #impo.foreignCards()
#sys.exit(1) #sys.exit(1)
# vim: ts=4 sts=2 ft=python # vim: ts=4 sts=2 ft=python

View file

@ -129,12 +129,12 @@ create table meta (dirMod int, lastUsn int); insert into meta values (0, 0);
# pylint: disable=import-error # pylint: disable=import-error
import win32api, win32file import win32api, win32file
try: try:
name = win32file.GetVolumeNameForVolumeMountPoint(self._dir[:3]) name = win32file.GetVolumeNameForVolumeMountPoint(self._dir[:3])
except: except:
# mapped & unmapped network drive; pray that it's not vfat # mapped & unmapped network drive; pray that it's not vfat
return return
if win32api.GetVolumeInformation(name)[4].lower().startswith("fat"): if win32api.GetVolumeInformation(name)[4].lower().startswith("fat"):
return True return True
# Adding media # Adding media
########################################################################## ##########################################################################

View file

@ -168,10 +168,9 @@ select id from cards where nid in (select id from notes where mid = ?)""",
def ensureNameUnique(self, m): def ensureNameUnique(self, m):
for mcur in self.all(): for mcur in self.all():
if (mcur['name'] == m['name'] and if (mcur['name'] == m['name'] and mcur['id'] != m['id']):
mcur['id'] != m['id']): m['name'] += "-" + checksum(str(time.time()))[:5]
m['name'] += "-" + checksum(str(time.time()))[:5] break
break
def update(self, m): def update(self, m):
"Add or update an existing model. Used for syncing and merging." "Add or update an existing model. Used for syncing and merging."

View file

@ -953,7 +953,7 @@ by clicking on one on the left."""))
if self.mw.app.keyboardModifiers() & Qt.ControlModifier: if self.mw.app.keyboardModifiers() & Qt.ControlModifier:
cur = str(self.form.searchEdit.lineEdit().text()) cur = str(self.form.searchEdit.lineEdit().text())
if cur and cur != self._searchPrompt: if cur and cur != self._searchPrompt:
txt = cur + " " + txt txt = cur + " " + txt
elif self.mw.app.keyboardModifiers() & Qt.ShiftModifier: elif self.mw.app.keyboardModifiers() & Qt.ShiftModifier:
cur = str(self.form.searchEdit.lineEdit().text()) cur = str(self.form.searchEdit.lineEdit().text())
if cur: if cur:

View file

@ -63,7 +63,7 @@ class CardLayout(QDialog):
def redraw(self): def redraw(self):
did = None did = None
if hasattr(self.parent,"deckChooser"): 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) self.cards = self.col.previewCards(self.note, 2, did=did)
idx = self.ord idx = self.ord
if idx >= len(self.cards): if idx >= len(self.cards):

View file

@ -21,7 +21,7 @@ def _getExportFolder():
dir = os.path.dirname(os.path.abspath(__file__)) dir = os.path.dirname(os.path.abspath(__file__))
return os.path.abspath(dir + "/../../Resources/web") return os.path.abspath(dir + "/../../Resources/web")
else: else:
raise Exception("couldn't find web folder") raise Exception("couldn't find web folder")
_exportFolder = _getExportFolder() _exportFolder = _getExportFolder()

View file

@ -49,8 +49,8 @@ class ProgressManager:
self.inDB = True self.inDB = True
# handle GUI events # handle GUI events
if not self.blockUpdates: if not self.blockUpdates:
self._maybeShow() self._maybeShow()
self.app.processEvents(QEventLoop.ExcludeUserInputEvents) self.app.processEvents(QEventLoop.ExcludeUserInputEvents)
self.inDB = False self.inDB = False
# Safer timers # Safer timers

View file

@ -22,9 +22,9 @@ except ImportError:
from PyQt5.QtCore import pyqtRemoveInputHook # pylint: disable=no-name-in-module from PyQt5.QtCore import pyqtRemoveInputHook # pylint: disable=no-name-in-module
def debug(): def debug():
from pdb import set_trace from pdb import set_trace
pyqtRemoveInputHook() pyqtRemoveInputHook()
set_trace() set_trace()
import sys, traceback import sys, traceback
@ -42,7 +42,7 @@ qtminor = (QT_VERSION & 0x00ff00) >> 8
qtpoint = QT_VERSION & 0xff qtpoint = QT_VERSION & 0xff
if qtmajor != 5 or qtminor < 9 or qtminor == 10: 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+ # GUI code assumes python 3.6+
if sys.version_info[0] < 3 or sys.version_info[1] < 6: if sys.version_info[0] < 3 or sys.version_info[1] < 6:

View file

@ -65,7 +65,7 @@ class Toolbar:
self.mw.col.startTimebox() self.mw.col.startTimebox()
self.mw.moveToState("review") self.mw.moveToState("review")
else: else:
self.mw.onOverview() self.mw.onOverview()
def _addLinkHandler(self): def _addLinkHandler(self):
self.mw.onAddCard() self.mw.onAddCard()