desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Disconnect from DB.'
def close(self, save=True):
if self.db: if save: self.save() else: self.db.rollback() if (not self.server): self.db.setAutocommit(True) self.db.execute('pragma journal_mode = delete') self.db.setAutocommit(False) self.db.close() self.d...
'Reconnect to DB (after changing threads, etc).'
def reopen(self):
import anki.db if (not self.db): self.db = anki.db.DB(self.path) self.media.connect() self._openLog()
'Mark schema modified. Call this first so user can abort if necessary.'
def modSchema(self, check):
if (not self.schemaChanged()): if (check and (not runFilter('modSchema', True))): raise AnkiError('abortSchemaMod') self.scm = intTime(1000) self.setMod()
'True if schema changed since last sync.'
def schemaChanged(self):
return (self.scm > self.ls)
'Called before a full upload.'
def beforeUpload(self):
tbls = ('notes', 'cards', 'revlog') for t in tbls: self.db.execute(('update %s set usn=0 where usn=-1' % t)) self.db.execute('delete from graves') self._usn += 1 self.models.beforeUpload() self.tags.beforeUpload() self.decks.beforeUpload() self.modSchema(chec...
'Rebuild the queue and reload data after DB modified.'
def reset(self):
self.sched.reset()
'Return a new note with the current model.'
def newNote(self, forDeck=True):
return anki.notes.Note(self, self.models.current(forDeck))
'Add a note to the collection. Return number of new cards.'
def addNote(self, note):
cms = self.findTemplates(note) if (not cms): return 0 note.flush() due = self.nextID('pos') ncards = 0 for template in cms: self._newCard(note, template, due) ncards += 1 return ncards
'Bulk delete notes by ID. Don\'t call this directly.'
def _remNotes(self, ids):
if (not ids): return strids = ids2str(ids) runHook('remNotes', self, ids) self._logRem(ids, REM_NOTE) self.db.execute(('delete from notes where id in %s' % strids))
'Return (active), non-empty templates.'
def findTemplates(self, note):
model = note.model() avail = self.models.availOrds(model, joinFields(note.fields)) return self._tmplsFromOrds(model, avail)
'Generate cards for non-empty templates, return ids to remove.'
def genCards(self, nids):
snids = ids2str(nids) have = {} dids = {} for (id, nid, ord, did, odid) in self.db.execute(('select id, nid, ord, did, odid from cards where nid in ' + snids)): if (nid not in have): have[nid] = {} have[nid][ord] = id if (odid != 0): ...
'Create a new card.'
def _newCard(self, note, template, due, flush=True):
card = anki.cards.Card(self) card.nid = note.id card.ord = template['ord'] if (template['did'] and (str(template['did']) in self.decks.decks)): card.did = template['did'] else: card.did = note.model()['did'] deck = self.decks.get(card.did) if deck['dyn']: card.did = 1...
'Bulk delete cards by ID.'
def remCards(self, ids, notes=True):
if (not ids): return sids = ids2str(ids) nids = self.db.list(('select nid from cards where id in ' + sids)) self._logRem(ids, REM_CARD) self.db.execute(('delete from cards where id in ' + sids)) if (not notes): return nids = self.db.list...
'Update field checksums and sort cache, after find&replace, etc.'
def updateFieldCache(self, nids):
snids = ids2str(nids) r = [] for (nid, mid, flds) in self._fieldData(snids): fields = splitFields(flds) model = self.models.get(mid) if (not model): continue r.append((stripHTML(fields[self.models.sortIdx(model)]), fieldChecksum(fields[0]), nid)) self.db.execu...
'Returns hash of id, question, answer.'
def _renderQA(self, data, qfmt=None, afmt=None):
flist = splitFields(data[6]) fields = {} model = self.models.get(data[2]) for (name, (idx, conf)) in list(self.models.fieldMap(model).items()): fields[name] = flist[idx] fields['Tags'] = data[5].strip() fields['Type'] = model['name'] fields['Deck'] = self.decks.name(data[3]) fiel...
'Return [cid, nid, mid, did, ord, tags, flds] db query'
def _qaData(self, where=''):
return self.db.execute(('\nselect c.id, f.id, f.mid, c.did, c.ord, f.tags, f.flds\nfrom cards c, notes f\nwhere c.nid == f.id\n%s' % where))
'Return (elapsedTime, reps) if timebox reached, or False.'
def timeboxReached(self):
if (not self.conf['timeLim']): return False elapsed = (time.time() - self._startTime) if (elapsed > self.conf['timeLim']): return (self.conf['timeLim'], (self.sched.reps - self._startReps))
'Undo menu item name, or None if undo unavailable.'
def undoName(self):
if (not self._undo): return None return self._undo[1]
'Call via .save()'
def _markOp(self, name):
if name: self._undo = [2, name] elif (self._undo and (self._undo[0] == 2)): self.clearUndo()
'Basic integrity check for syncing. True if ok.'
def basicCheck(self):
if self.db.scalar('\nselect 1 from cards where nid not in (select id from notes) limit 1'): return if self.db.scalar(('\nselect 1 from notes where id not in (select distinct nid from cards)\nor mid not in %s limit ...
'Fix possible problems and rebuild caches.'
def fixIntegrity(self):
problems = [] self.save() oldSize = os.stat(self.path)[stat.ST_SIZE] if (self.db.scalar('pragma integrity_check') != 'ok'): return (_('Collection is corrupt. Please see the manual.'), False) ids = self.db.list(('\nselect id from notes where mid not i...
'Load registry from JSON.'
def load(self, json_):
self.changed = False self.models = json.loads(json_)
'Mark M modified if provided, and schedule registry flush.'
def save(self, m=None, templates=False):
if (m and m['id']): m['mod'] = intTime() m['usn'] = self.col.usn() self._updateRequired(m) if templates: self._syncTemplates(m) self.changed = True runHook('newModel')
'Flush the registry if any models were changed.'
def flush(self):
if self.changed: self.col.db.execute('update col set models = ?', json.dumps(self.models)) self.changed = False
'Get current model.'
def current(self, forDeck=True):
m = self.get(self.col.decks.current().get('mid')) if ((not forDeck) or (not m)): m = self.get(self.col.conf['curModel']) return (m or list(self.models.values())[0])
'Get model with ID, or None.'
def get(self, id):
id = str(id) if (id in self.models): return self.models[id]
'Get all models.'
def all(self):
return list(self.models.values())
'Get model with NAME.'
def byName(self, name):
for m in list(self.models.values()): if (m['name'] == name): return m
'Create a new model, save it in the registry, and return it.'
def new(self, name):
m = defaultModel.copy() m['name'] = name m['mod'] = intTime() m['flds'] = [] m['tmpls'] = [] m['tags'] = [] m['id'] = None return m
'Delete model, and all its cards/notes.'
def rem(self, m):
self.col.modSchema(check=True) current = (self.current()['id'] == m['id']) self.col.remCards(self.col.db.list('\nselect id from cards where nid in (select id from notes where mid = ?)', m['id'])) del self.models[str(m['id'])] self.save() if current: ...
'Add or update an existing model. Used for syncing and merging.'
def update(self, m):
self.ensureNameUnique(m) self.models[str(m['id'])] = m self.save()
'Note ids for M.'
def nids(self, m):
return self.col.db.list('select id from notes where mid = ?', m['id'])
'Number of note using M.'
def useCount(self, m):
return self.col.db.scalar('select count() from notes where mid = ?', m['id'])
'Copy, save and return.'
def copy(self, m):
m2 = copy.deepcopy(m) m2['name'] = (_('%s copy') % m2['name']) self.add(m2) return m2
'Mapping of field name -> (ord, field).'
def fieldMap(self, m):
return dict(((f['name'], (f['ord'], f)) for f in m['flds']))
'Note: should col.genCards() afterwards.'
def addTemplate(self, m, template):
if m['id']: self.col.modSchema(check=True) m['tmpls'].append(template) self._updateTemplOrds(m) self.save(m)
'False if removing template would leave orphan notes.'
def remTemplate(self, m, template):
assert (len(m['tmpls']) > 1) ord = m['tmpls'].index(template) cids = self.col.db.list('\nselect c.id from cards c, notes f where c.nid=f.id and mid = ? and ord = ?', m['id'], ord) if self.col.db.scalar(('\nselect nid, count() from cards wher...
'Return a hash of the schema, to see if models are compatible.'
def scmhash(self, m):
s = '' for f in m['flds']: s += f['name'] for t in m['tmpls']: s += t['name'] return checksum(s)
'Given a joined field string, return available template ordinals.'
def availOrds(self, m, flds):
if (m['type'] == MODEL_CLOZE): return self._availClozeOrds(m, flds) fields = {} for (c, f) in enumerate(splitFields(flds)): fields[c] = f.strip() avail = [] for (ord, type, req) in m['req']: if (type == 'none'): continue elif (type == 'all'): o...
'Returns \'noChanges\', \'fullSync\', \'success\', etc'
def sync(self):
self.syncMsg = '' self.uname = '' self.col.save() runHook('sync', 'login') meta = self.server.meta() self.col.log('rmeta', meta) if (not meta): return 'badAuth' self.syncMsg = meta['msg'] if (not meta['cont']): return 'serverAbort' else: pass rscm = me...
'Bundle up small objects.'
def changes(self):
d = dict(models=self.getModels(), decks=self.getDecks(), tags=self.getTags()) if self.lnewer: d['conf'] = self.getConf() d['crt'] = self.col.crt return d
'Returns hkey or none if user/pw incorrect.'
def hostKey(self, user, pw):
self.postVars = dict() ret = self.req('hostKey', io.BytesIO(json.dumps(dict(u=user, p=pw)).encode('utf8')), badAuthRaises=False) if (not ret): return self.hkey = json.loads(ret.decode('utf8'))['key'] return self.hkey
'True if upload successful.'
def upload(self):
runHook('sync', 'upload') if (self.col.db.scalar('pragma integrity_check') != 'ok'): return False if (not self.col.basicCheck()): return False self.col.beforeUpload() if (self.req('upload', open(self.col.path, 'rb')) != 'OK'): return False return True
'Can be called with either a deck or a deck configuration.'
def save(self, g=None):
if g: g['mod'] = intTime() g['usn'] = self.col.usn() self.changed = True
'Add a deck with NAME. Reuse deck if already exists. Return id as int.'
def id(self, name, create=True, type=defaultDeck):
name = name.replace('"', '') for (id, g) in list(self.decks.items()): if (g['name'].lower() == name.lower()): return int(id) if (not create): return None g = copy.deepcopy(type) if ('::' in name): name = self._ensureParents(name) g['name'] = name while 1: ...
'Remove the deck. If cardsToo, delete any cards inside.'
def rem(self, did, cardsToo=False, childrenToo=True):
if (str(did) == '1'): deck = self.get(did) if ('::' in deck['name']): deck['name'] = _('Default') self.save(deck) return self.col._logRem([did], REM_DECK) if (not (str(did) in self.decks)): return deck = self.get(did) if deck['dyn']: se...
'An unsorted list of all deck names.'
def allNames(self, dyn=True):
if dyn: return [x['name'] for x in list(self.decks.values())] else: return [x['name'] for x in list(self.decks.values()) if (not x['dyn'])]
'A list of all decks.'
def all(self):
return list(self.decks.values())
'Get deck with NAME.'
def byName(self, name):
for m in list(self.decks.values()): if (m['name'] == name): return m
'Add or update an existing deck. Used for syncing and merging.'
def update(self, g):
self.decks[str(g['id'])] = g self.maybeAddToActive() self.save()
'Rename deck prefix to NAME if not exists. Updates children.'
def rename(self, g, newName):
if (newName in self.allNames()): raise DeckRenameError(_('That deck already exists.')) newName = self._ensureParents(newName) if ('::' in newName): newParent = '::'.join(newName.split('::')[:(-1)]) if self.byName(newParent)['dyn']: raise DeckRenameError(_('A f...
'Ensure parents exist, and return name with case matching parents.'
def _ensureParents(self, name):
s = '' path = self._path(name) if (len(path) < 2): return name for p in path[:(-1)]: if (not s): s += p else: s += ('::' + p) did = self.id(s) s = self.name(did) name = ((s + '::') + path[(-1)]) return name
'A list of all deck config.'
def allConf(self):
return list(self.dconf.values())
'Create a new configuration and return id.'
def confId(self, name, cloneFrom=defaultConf):
c = copy.deepcopy(cloneFrom) while 1: id = intTime(1000) if (str(id) not in self.dconf): break c['id'] = id c['name'] = name self.dconf[str(id)] = c self.save(c) return id
'Remove a configuration and update all decks using it.'
def remConf(self, id):
assert (int(id) != 1) self.col.modSchema(check=True) del self.dconf[str(id)] for g in self.all(): if ('conf' not in g): continue if (str(g['conf']) == str(id)): g['conf'] = 1 self.save(g)
'The currrently active dids. Make sure to copy before modifying.'
def active(self):
return self.col.conf['activeDecks']
'The currently selected did.'
def selected(self):
return self.col.conf['curDeck']
'Select a new branch.'
def select(self, did):
did = int(did) self.col.conf['curDeck'] = did actv = self.children(did) actv.sort() self.col.conf['activeDecks'] = ([did] + [a[1] for a in actv]) self.changed = True
'All children of did, as (name, id).'
def children(self, did):
name = self.get(did)['name'] actv = [] for g in self.all(): if g['name'].startswith((name + '::')): actv.append((g['name'], g['id'])) return actv
'All parents of did.'
def parents(self, did):
parents = [] for part in self.get(did)['name'].split('::')[:(-1)]: if (not parents): parents.append(part) else: parents.append(((parents[(-1)] + '::') + part)) for (c, p) in enumerate(parents): parents[c] = self.get(self.id(p)) return parents
'Return a new dynamic deck and set it as the current deck.'
def newDyn(self, name):
did = self.id(name, type=defaultDynamicDeck) self.select(did) return did
'Time limit for answering in milliseconds.'
def timeLimit(self):
conf = self.col.decks.confForDid((self.odid or self.did)) return (conf['maxTaken'] * 1000)
'Time taken to answer card, in integer MS.'
def timeTaken(self):
total = int(((time.time() - self.timerStarted) * 1000)) return min(total, self.timeLimit())
'Given a list of tags, add any missing ones to tag registry.'
def register(self, tags, usn=None):
found = False for t in tags: if (t not in self.tags): found = True self.tags[t] = (self.col.usn() if (usn is None) else usn) self.changed = True if found: runHook('newTag')
'Add any missing tags from notes to the tags list.'
def registerNotes(self, nids=None):
if nids: lim = (' where id in ' + ids2str(nids)) else: lim = '' self.tags = {} self.changed = True self.register(set(self.split(' '.join(self.col.db.list(('select distinct tags from notes' + lim))))))
'Add tags in bulk. TAGS is space-separated.'
def bulkAdd(self, ids, tags, add=True):
newTags = self.split(tags) if (not newTags): return if add: self.register(newTags) if add: l = 'tags not ' fn = self.addToStr else: l = 'tags ' fn = self.remFromStr lim = ' or '.join([(l + ('like :_%d' % c)) for (c, t) in enumerat...
'Parse a string and return a list of tags.'
def split(self, tags):
return [t for t in tags.replace('\\u3000', ' ').split(' ') if t]
'Join tags into a single string, with leading and trailing spaces.'
def join(self, tags):
if (not tags): return '' return (' %s ' % ' '.join(tags))
'Add tags if they don\'t exist, and canonify.'
def addToStr(self, addtags, tags):
currentTags = self.split(tags) for tag in self.split(addtags): if (not self.inList(tag, currentTags)): currentTags.append(tag) return self.join(self.canonify(currentTags))
'Delete tags if they exist.'
def remFromStr(self, deltags, tags):
def wildcard(pat, str): pat = re.escape(pat).replace('\\*', '.*') return re.search(pat, str, re.IGNORECASE) currentTags = self.split(tags) for tag in self.split(deltags): remove = [] for tx in currentTags: if ((tag.lower() == tx.lower()) or wildcard(tag, tx)): ...
'Strip duplicates, adjust case to match existing tags, and sort.'
def canonify(self, tagList):
strippedTags = [] for t in tagList: s = re.sub('["\']', '', t) for existingTag in self.tags: if (s.lower() == existingTag.lower()): s = existingTag strippedTags.append(s) return sorted(set(strippedTags))
'True if TAG is in TAGS. Ignore case.'
def inList(self, tag, tags):
return (tag.lower() in [t.lower() for t in tags])
'Given another View, copies its settings.'
def inherit_settings(self, view):
if view.template_path: self.template_path = view.template_path if view.template_name: self.template_name = view.template_name
'TemplatePartial => template_partial Takes a string but defaults to using the current class\' name or the `template_name` attribute'
def get_template_name(self, name=None):
if self.template_name: return self.template_name if (not name): name = self.__class__.__name__ def repl(match): return ('_' + match.group(0).lower()) return re.sub('[A-Z]', repl, name)[1:]
'Turns a Mustache template into something wonderful.'
def render(self, template=None, context=None, encoding=None):
template = (template or self.template) context = (context or self.context) template = self.render_sections(template, context) result = self.render_tags(template, context) if (encoding is not None): result = result.encode(encoding) return result
'Compiles our section and tag regular expressions.'
def compile_regexps(self):
tags = {'otag': re.escape(self.otag), 'ctag': re.escape(self.ctag)} section = '%(otag)s[\\#|^]([^\\}]*)%(ctag)s(.+?)%(otag)s/\\1%(ctag)s' self.section_re = re.compile((section % tags), (re.M | re.S)) tag = '%(otag)s(#|=|&|!|>|\\{)?(.+?)\\1?%(ctag)s+' self.tag_re = re.compile((tag % tags))
'Expands sections.'
def render_sections(self, template, context):
while 1: match = self.section_re.search(template) if (match is None): break (section, section_name, inner) = match.group(0, 1, 2) section_name = section_name.strip() val = None m = re.match('c[qa]:(\\d+):(.+)', section_name) if m: txt =...
'Renders all the tags in a template for a context.'
def render_tags(self, template, context):
while 1: match = self.tag_re.search(template) if (match is None): break (tag, tag_type, tag_name) = match.group(0, 1, 2) tag_name = tag_name.strip() try: func = modifiers[tag_type] replacement = func(self, tag_name, context) tem...
'Rendering a comment always returns nothing.'
@modifier('!') def render_comment(self, tag_name=None, context=None):
return ''
'Render a tag without escaping it.'
@modifier(None) def render_unescaped(self, tag_name=None, context=None):
txt = get_or_attr(context, tag_name) if (txt is not None): return txt parts = tag_name.split(':') extra = None if ((len(parts) == 1) or (parts[0] == '')): return ('{unknown field %s}' % tag_name) else: (mods, tag) = (parts[:(-1)], parts[(-1)]) txt = get_or_attr(...
'Changes the Mustache delimiter.'
@modifier('=') def render_delimiter(self, tag_name=None, context=None):
try: (self.otag, self.ctag) = tag_name.split(' ') except ValueError: return self.compile_regexps() return ''
'Pop the next card from the queue. None if finished.'
def getCard(self):
self._checkDay() if (not self._haveQueues): self.reset() card = self._getCard() if card: self.col.log(card) if (not self._burySiblingsOnAnswer): self._burySiblings(card) self.reps += 1 card.startTimer() return card
'Return counts over next DAYS. Includes today.'
def dueForecast(self, days=7):
daysd = dict(self.col.db.all(('\nselect due, count() from cards\nwhere did in %s and queue = 2\nand due between ? and ?\ngroup by due\norder by due' % self._deckLimit()), self.today, ((self.today + days) - 1))) for d in range(days): d = (self.t...
'Unbury cards.'
def unburyCards(self):
self.col.conf['lastUnburied'] = self.today self.col.log(self.col.db.list('select id from cards where queue = -2')) self.col.db.execute('update cards set queue=type where queue = -2')
'Returns [deckname, did, rev, lrn, new]'
def deckDueList(self):
self._checkDay() self.col.decks.recoverOrphans() decks = self.col.decks.all() decks.sort(key=itemgetter('name')) lims = {} data = [] def parent(name): parts = name.split('::') if (len(parts) < 2): return None parts = parts[:(-1)] return '::'.join(p...
'Return the next due card id, or None.'
def _getCard(self):
c = self._getLrnCard() if c: return c if self._timeForNewCard(): c = self._getNewCard() if c: return c c = self._getRevCard() if c: return c c = self._getLrnDayCard() if c: return c c = self._getNewCard() if c: return c ...
'True if it\'s time to display a new card when distributing.'
def _timeForNewCard(self):
if (not self.newCount): return False if (self.col.conf['newSpread'] == NEW_CARDS_LAST): return False elif (self.col.conf['newSpread'] == NEW_CARDS_FIRST): return True elif self.newCardModulus: return (self.reps and ((self.reps % self.newCardModulus) == 0))
'New count for a single deck.'
def _newForDeck(self, did, lim):
if (not lim): return 0 lim = min(lim, self.reportLimit) return self.col.db.scalar('\nselect count() from\n(select 1 from cards where did = ? and queue = 0 limit ?)', did, lim)
'Limit for deck without parent limits.'
def _deckNewLimitSingle(self, g):
if g['dyn']: return self.reportLimit c = self.col.decks.confForDid(g['id']) return max(0, (c['new']['perDay'] - g['newToday'][1]))
'The number of steps that can be completed by the day cutoff.'
def _leftToday(self, delays, left, now=None):
if (not now): now = intTime() delays = delays[(- left):] ok = 0 for i in range(len(delays)): now += (delays[i] * 60) if (now > self.dayCutoff): break ok = i return (ok + 1)
'Reschedule a new card that\'s graduated for the first time.'
def _rescheduleNew(self, card, conf, early):
card.ivl = self._graduatingIvl(card, conf, early) card.due = (self.today + card.ivl) card.factor = conf['initialFactor']
'Remove cards from the learning queues.'
def removeLrn(self, ids=None):
if ids: extra = (' and id in ' + ids2str(ids)) else: extra = (' and did in ' + ids2str(self.col.decks.allIds())) self.col.db.execute(('\nupdate cards set\ndue = odue, queue = 2, mod = %d, usn = %d, odue = 0\nwhere que...
'Ideal next interval for CARD, given EASE.'
def _nextRevIvl(self, card, ease):
delay = self._daysLate(card) conf = self._revConf(card) fct = (card.factor / 1000) ivl2 = self._constrainedIvl(((card.ivl + (delay // 4)) * 1.2), conf, card.ivl) ivl3 = self._constrainedIvl(((card.ivl + (delay // 2)) * fct), conf, ivl2) ivl4 = self._constrainedIvl((((card.ivl + delay) * fct) * c...
'Integer interval after interval factor and prev+1 constraints applied.'
def _constrainedIvl(self, ivl, conf, prev):
new = (ivl * conf.get('ivlFct', 1)) return int(max(new, (prev + 1)))
'Number of days later than scheduled.'
def _daysLate(self, card):
due = (card.odue if card.odid else card.due) return max(0, (self.today - due))
'Rebuild a dynamic deck.'
def rebuildDyn(self, did=None):
did = (did or self.col.decks.selected()) deck = self.col.decks.get(did) assert deck['dyn'] self.emptyDyn(did) ids = self._fillDyn(deck) if (not ids): return self.col.decks.select(did) return ids
'Leech handler. True if card was a leech.'
def _checkLeech(self, card, conf):
lf = conf['leechFails'] if (not lf): return if ((card.lapses >= lf) and (((card.lapses - lf) % max((lf // 2), 1)) == 0)): f = card.note() f.addTag('leech') f.flush() a = conf['leechAction'] if (a == 0): if card.odue: card.due = card...
'True if there are any rev cards due.'
def revDue(self):
return self.col.db.scalar(('select 1 from cards where did in %s and queue = 2 and due <= ? limit 1' % self._deckLimit()), self.today)
'True if there are any new cards due.'
def newDue(self):
return self.col.db.scalar(('select 1 from cards where did in %s and queue = 0 limit 1' % self._deckLimit()))
'Return the next interval for CARD as a string.'
def nextIvlStr(self, card, ease, short=False):
ivl = self.nextIvl(card, ease) if (not ivl): return _('(end)') s = fmtTimeSpan(ivl, short=short) if (ivl < self.col.conf['collapseTime']): s = ('<' + s) return s