desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Calls CloudFormation to execute changeset
:param changeset_id: ID of the changeset
:param stack_name: Name or ID of the stack
:return: Response from execute-change-set call'
| def execute_changeset(self, changeset_id, stack_name):
| return self._client.execute_change_set(ChangeSetName=changeset_id, StackName=stack_name)
|
'Default export action is to upload artifacts and set the property to
S3 URL of the uploaded object'
| def do_export(self, resource_id, resource_dict, parent_dir):
| resource_dict[self.PROPERTY_NAME] = upload_local_artifacts(resource_id, resource_dict, self.PROPERTY_NAME, parent_dir, self.uploader)
|
'Upload to S3 and set property to an dict representing the S3 url
of the uploaded object'
| def do_export(self, resource_id, resource_dict, parent_dir):
| artifact_s3_url = upload_local_artifacts(resource_id, resource_dict, self.PROPERTY_NAME, parent_dir, self.uploader)
resource_dict[self.PROPERTY_NAME] = parse_s3_url(artifact_s3_url, bucket_name_property=self.BUCKET_NAME_PROPERTY, object_key_property=self.OBJECT_KEY_PROPERTY, version_property=self.VERSION_PROPER... |
'If the nested stack template is valid, this method will
export on the nested template, upload the exported template to S3
and set property to URL of the uploaded S3 template'
| def do_export(self, resource_id, resource_dict, parent_dir):
| template_path = resource_dict.get(self.PROPERTY_NAME, None)
if ((template_path is None) or is_s3_url(template_path) or template_path.startswith('https://s3.amazonaws.com/')):
return
abs_template_path = make_abs_path(parent_dir, template_path)
if (not is_local_file(abs_template_path)):
ra... |
'Reads the template and makes it ready for export'
| def __init__(self, template_path, parent_dir, uploader, resources_to_export=EXPORT_DICT):
| if (not (is_local_folder(parent_dir) and os.path.isabs(parent_dir))):
raise ValueError('parent_dir parameter must be an absolute path to a folder {0}'.format(parent_dir))
abs_template_path = make_abs_path(parent_dir, template_path)
template_dir = os.path.dirname(abs_tem... |
'Exports the local artifacts referenced by the given template to an
s3 bucket.
:return: The template with references to artifacts that have been
exported to s3.'
| def export(self):
| if ('Resources' not in self.template_dict):
return self.template_dict
for (resource_id, resource) in self.template_dict['Resources'].items():
resource_type = resource.get('Type', None)
resource_dict = resource.get('Properties', None)
if (resource_type in self.resources_to_export)... |
'CloudFormation CreateChangeset requires a value for every parameter
from the template, either specifying a new value or use previous value.
For convenience, this method will accept new parameter values and
generates a dict of all parameters in a format that ChangeSet API
will accept
:param parameter_overrides:
:return... | def merge_parameters(self, template_dict, parameter_overrides):
| parameter_values = []
if (not isinstance(template_dict.get('Parameters', None), dict)):
return parameter_values
for (key, value) in template_dict['Parameters'].items():
obj = {'ParameterKey': key}
if (key in parameter_overrides):
obj['ParameterValue'] = parameter_override... |
'Uploads given file to S3
:param file_name: Path to the file that will be uploaded
:param remote_path: be uploaded
:return: VersionId of the latest upload'
| def upload(self, file_name, remote_path):
| if (self.prefix and (len(self.prefix) > 0)):
remote_path = '{0}/{1}'.format(self.prefix, remote_path)
if ((not self.force_upload) and self.file_exists(remote_path)):
LOG.debug('File with same data is already exists at {0}. Skipping upload'.format(remote_path))
... |
'Makes and returns name of the S3 object based on the file\'s MD5 sum
:param file_name: file to upload
:param extension: String of file extension to append to the object
:return: S3 URL of the uploaded object'
| def upload_with_dedup(self, file_name, extension=None):
| filemd5 = self.file_checksum(file_name)
remote_path = filemd5
if extension:
remote_path = ((remote_path + '.') + extension)
return self.upload(file_name, remote_path)
|
'Check if the file we are trying to upload already exists in S3
:param remote_path:
:return: True, if file exists. False, otherwise'
| def file_exists(self, remote_path):
| try:
self.s3.head_object(Bucket=self.bucket_name, Key=remote_path)
return True
except botocore.exceptions.ClientError:
return False
|
'This link describes the format of Path Style URLs
http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html#access-bucket-intro'
| def to_path_style_s3_url(self, key, version=None):
| base = 'https://s3.amazonaws.com'
if (self.region and (self.region != 'us-east-1')):
base = 'https://s3-{0}.amazonaws.com'.format(self.region)
result = '{0}/{1}/{2}'.format(base, self.bucket_name, key)
if version:
result = '{0}?versionId={1}'.format(result, version)
return result
|
'Call to run the commands'
| def _run_main(self, parsed_args, parsed_globals, **kwargs):
| self._region = get_region(self._session, parsed_globals)
self._endpoint_url = parsed_globals.endpoint_url
self._iam_client = self._session.create_client('iam', region_name=self._region, endpoint_url=self._endpoint_url, verify=parsed_globals.verify_ssl)
return self._create_default_roles(parsed_args, pars... |
'Method to create a role for a given role name and arn
if it does not exist'
| def _create_role(self, role_name, role_arn, role_policy):
| role_result = None
role_policy_result = None
if self._check_if_role_exists(role_name):
LOG.debug((('Role ' + role_name) + ' exists.'))
else:
LOG.debug(((('Role ' + role_name) + ' does not exist. Creating default role for EC2: ') + role_name))
r... |
'Method to create a resultant list of responses for create roles
for service and resource role'
| def _construct_result(self, dpl_default_result, dpl_default_policy, dpl_default_res_result, dpl_default_res_policy):
| result = []
self._construct_role_and_role_policy_structure(result, dpl_default_result, dpl_default_policy)
self._construct_role_and_role_policy_structure(result, dpl_default_res_result, dpl_default_res_policy)
return result
|
'Method to get the Policy for a particular ARN
This is used to display the policy contents to the user'
| def _get_role_policy(self, arn):
| pol_det = self._iam_client.get_policy(PolicyArn=arn)
policy_version_details = self._iam_client.get_policy_version(PolicyArn=arn, VersionId=pol_det['Policy']['DefaultVersionId'])
return policy_version_details['PolicyVersion']['Document']
|
'Method to create role with a given rolename, assume_role_policy
and role_arn'
| def _create_role_with_role_policy(self, role_name, assume_role_policy, role_arn):
| create_role_response = self._iam_client.create_role(RoleName=role_name, AssumeRolePolicyDocument=dict_to_string(assume_role_policy))
self._iam_client.attach_role_policy(PolicyArn=role_arn, RoleName=role_name)
return create_role_response
|
'Method to construct the message to be displayed to the user'
| def _construct_role_and_role_policy_structure(self, list_val, response, policy):
| if ((response is not None) and (response['Role'] is not None)):
list_val.append({'Role': response['Role'], 'RolePolicy': policy})
return list_val
|
'Method to verify if a particular role exists'
| def _check_if_instance_profile_exists(self, instance_profile_name):
| try:
self._iam_client.get_instance_profile(InstanceProfileName=instance_profile_name)
except ClientError as e:
if (e.response['Error']['Code'] == 'NoSuchEntity'):
return False
else:
raise e
return True
|
'Method to verify if a particular role exists'
| def _check_if_role_exists(self, role_name):
| try:
self._iam_client.get_role(RoleName=role_name)
except ClientError as e:
if (e.response['Error']['Code'] == 'NoSuchEntity'):
return False
else:
raise e
return True
|
'Method to create the instance profile with the role'
| def _create_instance_profile_with_role(self, instance_profile_name, role_name):
| self._iam_client.create_instance_profile(InstanceProfileName=instance_profile_name)
self._iam_client.add_role_to_instance_profile(InstanceProfileName=instance_profile_name, RoleName=role_name)
|
'``**kwargs`` can contain a ``root_module`` argument
that contains the root module where the file contents
should be searched. This is an optional argument, and if
no value is provided, will default to ``awscli``. This means
that by default we look for examples in the ``awscli`` module.'
| def __init__(self, *paths, **kwargs):
| self.filename = None
if paths:
self.filename = os.path.join(*paths)
if ('root_module' in kwargs):
self.root_module = kwargs['root_module']
else:
self.root_module = awscli
|
'Create the command table into a form that can be handled by the
BasicDocHandler.'
| def create_help_command_table(self):
| commands = {}
for command in self.SUBCOMMANDS:
commands[command['name']] = command['command_class'](self._session)
self._add_lineage(commands)
return commands
|
'Repack the input structure into a revisionLocation.'
| def build_revision_location(self, value_dict):
| raise NotImplementedError('build_revision_location')
|
'This adds waiter state commands to the subcommand table passed in.
This is the method that adds waiter state commands like
``instance-running`` to ``ec2 wait``.'
| def build_all_waiter_state_cmds(self, subcommand_table):
| waiter_names = self._model.waiter_names
for waiter_name in waiter_names:
waiter_cli_name = xform_name(waiter_name, '-')
subcommand_table[waiter_cli_name] = self._build_waiter_state_cmd(waiter_name)
|
'Update config file with new values.
This method will update a section in a config file with
new key value pairs.
This method provides a few conveniences:
* If the ``config_filename`` does not exist, it will
be created. Any parent directories will also be created
if necessary.
* If the section to update does not exist... | def update_config(self, new_values, config_filename):
| section_name = new_values.pop('__section__', 'default')
if (not os.path.isfile(config_filename)):
self._create_file(config_filename)
self._write_new_section(section_name, new_values, config_filename)
return
with open(config_filename, 'r') as f:
contents = f.readlines()
tr... |
'Invoke CLI operation.
:type args: str
:param args: The remaining command line args.
:type parsed_globals: ``argparse.Namespace``
:param parsed_globals: The parsed arguments so far.
:rtype: int
:return: The return code of the operation. This will be used
as the RC code for the ``aws`` process.'
| def __call__(self, args, parsed_globals):
| pass
|
'Create the main parser to handle the global arguments.
:rtype: ``argparser.ArgumentParser``
:return: The parser object'
| def _build_command_table(self):
| command_table = self._build_builtin_commands(self.session)
self.session.emit('building-command-table.main', command_table=command_table, session=self.session, command_object=self)
return command_table
|
':param args: List of arguments, with the \'aws\' removed. For example,
the command "aws s3 list-objects --bucket foo" will have an
args list of ``[\'s3\', \'list-objects\', \'--bucket\', \'foo\']``.'
| def main(self, args=None):
| if (args is None):
args = sys.argv[1:]
command_table = self._get_command_table()
parser = self._create_parser(command_table)
self._add_aliases(command_table, parser)
(parsed_args, remaining) = parser.parse_known_args(args)
try:
self._handle_top_level_args(parsed_args)
sel... |
':type name: str
:param name: The name of the operation/subcommand.
:type parent_name: str
:param parent_name: The name of the parent command.
:type operation_model: ``botocore.model.OperationModel``
:param operation_object: The operation model
associated with this subcommand.
:type operation_caller: ``CLIOperationCall... | def __init__(self, name, parent_name, operation_caller, operation_model, session):
| self._arg_table = None
self._name = name
self._parent_name = parent_name
self._operation_caller = operation_caller
self._lineage = [self]
self._operation_model = operation_model
self._session = session
|
'Invoke an operation and format the response.
:type service_name: str
:param service_name: The name of the service. Note this is the service name,
not the endpoint prefix (e.g. ``ses`` not ``email``).
:type operation_name: str
:param operation_name: The operation name of the service. The casing
of the operation name ... | def invoke(self, service_name, operation_name, parameters, parsed_globals):
| client = self._session.create_client(service_name, region_name=parsed_globals.region, endpoint_url=parsed_globals.endpoint_url, verify=parsed_globals.verify_ssl)
response = self._make_client_call(client, operation_name, parameters, parsed_globals)
self._display_response(operation_name, response, parsed_glob... |
'Convert JSON schema to the format used internally by the AWS CLI.
:type schema: dict
:param schema: The JSON schema describing the argument model.
:rtype: dict
:return: The transformed model in a form that can be consumed
internally by the AWS CLI. The dictionary returned will
have a list of shapes, where the shape r... | def transform(self, schema):
| shapes = {}
self._transform(schema, shapes, 'InputShape')
return shapes
|
'It\'s probably not a great idea to override a "hidden" method
but the default behavior is pretty ugly and there doesn\'t
seem to be any other way to change it.'
| def _check_value(self, action, value):
| if ((action.choices is not None) and (value not in action.choices)):
msg = ['Invalid choice, valid choices are:\n']
for i in range(len(action.choices))[::self.ChoicesPerLine]:
current = []
for choice in action.choices[i:(i + self.ChoicesPerLine)]:
... |
'Install a handler in the current DB.'
| def setupDB(self, db):
| self.lastDbProgress = 0
self.inDB = False
try:
db.set_progress_handler(self._dbProgress, 10000)
except:
print 'Your pysqlite2 is too old. Anki will appear frozen during long operations.'
|
'Called from SQLite.'
| def _dbProgress(self):
| if (not self._win):
return
if ((time.time() - self.lastDbProgress) < 0.01):
return
self.lastDbProgress = time.time()
if (not self.mw.inMainThread()):
return
self.inDB = True
if (not self.blockUpdates):
self._maybeShow()
self.app.processEvents(QEventLoop.Ex... |
'Restore the interface after an error.'
| def clear(self):
| if self._levels:
self._levels = 1
self.finish()
|
'True if processing.'
| def busy(self):
| return self._levels
|
'Show answer on RET or register answer.'
| def keyPressEvent(self, evt):
| if ((evt.key() in (Qt.Key_Enter, Qt.Key_Return)) and self.editor.tags.hasFocus()):
evt.accept()
return
return QDialog.keyPressEvent(self, evt)
|
'Set the current col, updating list of available tags.'
| def setCol(self, col):
| self.col = col
if (self.type == 0):
l = sorted(self.col.tags.all())
else:
l = sorted(self.col.decks.allNames())
self.model.setStringList(l)
|
'True if all closed successfully.'
| def closeAll(self):
| for (n, (creator, instance)) in list(self._dialogs.items()):
if instance:
if (not instance.canClose()):
return False
instance.forceClose = True
instance.close()
self.close(n)
return True
|
'Create a new profile if none exists.'
| def ensureProfile(self):
| if self.firstRun:
self.create(_('User 1'))
p = os.path.join(self.base, 'README.txt')
open(p, 'w').write((_('This folder stores all of your Anki data in a single location,\nto make backups easy. To tell Anki to use a different ... |
'Unload the collection.
This unloads a collection if there is one and returns True if
there is no collection after the call. (Because the unload
worked or because there was no collection to start with.)'
| def unloadCollection(self):
| if self.col:
if (not self.closeAllCollectionWindows()):
return
self.progress.start(immediate=True)
corrupt = False
try:
self.maybeOptimize()
except:
corrupt = True
if (not corrupt):
if devMode:
corrupt = ... |
'Run once, when col is loaded.'
| def _colLoadingState(self, oldState):
| self.enableColMenuItems()
self.col.media.dir()
runHook('colLoading', self.col)
self.moveToState('overview')
|
'Called when a card or note is edited (but not deleted).'
| def noteChanged(self, nid):
| runHook('noteChanged', nid)
|
'Called for non-trivial edits. Rebuilds queue and updates UI.'
| def reset(self, guiOnly=False):
| if self.col:
if (not guiOnly):
self.col.reset()
runHook('reset')
self.maybeEnableUndo()
self.moveToState(self.state)
|
'Signal queue needs to be rebuilt when edits are finished or by user.'
| def requireReset(self, modal=False):
| self.autosave()
self.resetModal = modal
if self.interactiveState():
self.moveToState('resetRequired')
|
'True if not in profile manager, syncing, etc.'
| def interactiveState(self):
| return (self.state in ('overview', 'review', 'deckBrowser'))
|
'User hit the X button, etc.'
| def closeEvent(self, event):
| event.accept()
self.onClose(force=True)
|
'Called from a shortcut key. Close current active window.'
| def onClose(self, force=False):
| aw = self.app.activeWindow()
if ((not aw) or (aw == self) or force):
self.unloadProfile(browser=False)
else:
aw.close()
|
'True if no problems'
| def onCheckDB(self):
| self.progress.start(immediate=True)
(ret, ok) = self.col.fixIntegrity()
self.progress.finish()
if (not ok):
showText(ret)
else:
tooltip(ret)
self.reset()
return ret
|
'Clear .pyc files which may cause crashes if Python version updated.'
| def clearAddonCache(self):
| dir = self.addonsFolder()
for (curdir, dirs, files) in os.walk(dir):
for f in files:
if (not f.endswith('.pyc')):
continue
os.unlink(os.path.join(curdir, f))
|
'Convert a file (specified by a path) into a data URI.'
| def resourceToData(self, path):
| if (not os.path.exists(path)):
raise FileNotFoundError
(mime, _) = mimetypes.guess_type(path)
with open(path, 'rb') as fp:
data = fp.read()
data64 = ''.join(base64.encodestring(data).splitlines())
return ('data:%s;base64,%s' % (mime, data64.decode('ascii')))
|
'Make NOTE the current note.'
| def setNote(self, note, hide=True, focusTo=None):
| self.note = note
self.currentField = None
if self.note:
self.loadNote(focusTo=focusTo)
else:
self.hideCompleters()
if hide:
self.widget.hide()
|
'Save unsaved edits then call callback().'
| def saveNow(self, callback):
| if (not self.note):
callback()
return
self.saveTags()
self.web.evalWithCallback('saveNow()', (lambda res: callback()))
|
'Add to media folder and return local img or sound tag.'
| def _addMedia(self, path, canDelete=False):
| fname = self.mw.col.media.addFile(path)
if (canDelete and self.mw.pm.profile['deleteMedia']):
if (os.path.abspath(fname) != os.path.abspath(path)):
try:
os.unlink(path)
except:
pass
return self.fnameToLink(fname)
|
'Download file into media folder and return local filename or None.'
| def _retrieveURL(self, url):
| url = urllib.parse.unquote(url)
if url.lower().startswith('file://'):
url = url.replace('%', '%25')
url = url.replace('#', '%23')
self.mw.progress.start(immediate=True, parent=self.parentWindow)
try:
req = urllib.request.Request(url, None, {'User-Agent': 'Mozilla/5.0 (compatib... |
'Prepare index of schema hashes.'
| def _prepareModels(self):
| self._modelMap = {}
|
'Return local id for remote MID.'
| def _mid(self, srcMid):
| if (srcMid in self._modelMap):
return self._modelMap[srcMid]
mid = srcMid
srcModel = self.src.models.get(srcMid)
srcScm = self.src.models.scmhash(srcModel)
while True:
if (not self.dst.models.have(mid)):
model = srcModel.copy()
model['id'] = mid
mo... |
'Given did in src col, return local id.'
| def _did(self, did):
| if (did in self._decks):
return self._decks[did]
g = self.src.decks.get(did)
name = g['name']
if self.deckPrefix:
tmpname = '::'.join(name.split('::')[1:])
name = self.deckPrefix
if tmpname:
name += ('::' + tmpname)
head = ''
for parent in name.split('... |
'Data for FNAME in src collection.'
| def _srcMediaData(self, fname):
| return self._mediaData(fname, self.src.media.dir())
|
'Data for FNAME in dst collection.'
| def _dstMediaData(self, fname):
| return self._mediaData(fname, self.dst.media.dir())
|
'Import.'
| def run(self):
| assert self.mapping
c = self.foreignNotes()
self.importNotes(c)
|
'The number of fields.'
| def fields(self):
| return 0
|
'Return a list of foreign notes for importing.'
| def foreignNotes(self):
| assert 0
|
'Open file and ensure it\'s in the right format.'
| def open(self):
| return
|
'Convert each card into a note, apply attributes and add to col.'
| def importNotes(self, notes):
| assert self.mappingOk()
self._tagsMapped = False
for f in self.mapping:
if (f == '_tags'):
self._tagsMapped = True
csums = {}
for (csum, id) in self.col.db.execute('select csum, id from notes where mid = ?', self.model['id']):
if (csum in csums):
... |
'Initialize internal varables.
Pameters to be exposed to GUI are stored in self.META'
| def __init__(self, *args):
| NoteImporter.__init__(self, *args)
m = addBasicModel(self.col)
m['name'] = 'Supermemo'
self.col.models.save(m)
self.initMapping()
self.lines = None
self.numFields = int(2)
self.xmldoc = None
self.pieces = []
self.cntBuf = []
self.cntElm = []
self.cntCol = []
self.cntM... |
'Replace sm syntax to Anki syntax'
| def _fudgeText(self, text):
| text = text.replace('\n\r', '<br>')
text = text.replace('\n', '<br>')
return text
|
'Remove diacritic punctuation from strings (titles)'
| def _unicode2ascii(self, str):
| return ''.join([c for c in unicodedata.normalize('NFKD', str) if (not unicodedata.combining(c))])
|
'Unescape HTML code.'
| def _decode_htmlescapes(self, s):
| from bs4 import BeautifulSoup as btflsoup
s = re.sub('&', '&', s)
return str(btflsoup(s, 'html.parser'))
|
'This method actually do conversion'
| def addItemToCards(self, item):
| note = ForeignNote()
note.fields.append(self._fudgeText(self._decode_htmlescapes(item.Question)))
note.fields.append(self._fudgeText(self._decode_htmlescapes(item.Answer)))
note.tags = []
if ((not self.META.resetLearningData) and (int(item.Interval) >= 1) and getattr(item, 'LastRepetition', None)):
... |
'Wrapper for Anki logger'
| def logger(self, text, level=1):
| dLevels = {0: '', 1: 'Info', 2: 'Verbose', 3: 'Debug'}
if (level <= self.META.loggerLevel):
if self.META.logToStdOutput:
print ((((self.__class__.__name__ + ' - ') + dLevels[level].ljust(9)) + ' - DCTB ') + _(text))
|
'Open any source / actually only openig of files is used'
| def openAnything(self, source):
| if (source == '-'):
return sys.stdin
import urllib.request, urllib.parse, urllib.error
try:
return urllib.request.urlopen(source)
except (IOError, OSError):
pass
try:
return open(source)
except (IOError, OSError):
pass
import io
return io.StringIO(... |
'Load source file and parse with xml.dom.minidom'
| def loadSource(self, source):
| self.source = source
self.logger('Load started...')
sock = open(self.source)
self.xmldoc = minidom.parse(sock).documentElement
sock.close()
self.logger('Load done.')
|
'Parse method - parses document elements'
| def parse(self, node=None):
| if ((node == None) and (self.xmldoc != None)):
node = self.xmldoc
_method = ('parse_%s' % node.__class__.__name__)
if hasattr(self, _method):
parseMethod = getattr(self, _method)
parseMethod(node)
else:
self.logger(('No handler for method %s' % _method), level... |
'Parse XML document'
| def parse_Document(self, node):
| self.parse(node.documentElement)
|
'Parse XML element'
| def parse_Element(self, node):
| _method = ('do_%s' % node.tagName)
if hasattr(self, _method):
handlerMethod = getattr(self, _method)
handlerMethod(node)
else:
self.logger(('No handler for method %s' % _method), level=3)
|
'Parse text inside elements. Text is stored into local buffer.'
| def parse_Text(self, node):
| text = node.data
self.cntBuf.append(text)
|
'Process SM Collection'
| def do_SuperMemoCollection(self, node):
| for child in node.childNodes:
self.parse(child)
|
'Process SM Element (Type - Title,Topics)'
| def do_SuperMemoElement(self, node):
| self.logger(('=' * 45), level=3)
self.cntElm.append(SuperMemoElement())
self.cntElm[(-1)]['lTitle'] = self.cntMeta['title']
for child in node.childNodes:
self.parse(child)
for key in list(self.cntElm[(-1)].keys()):
if hasattr(self.cntElm[(-1)][key], 'strip'):
self.cntElm[... |
'Process SM element Content'
| def do_Content(self, node):
| for child in node.childNodes:
if (hasattr(child, 'tagName') and (child.firstChild != None)):
self.cntElm[(-1)][child.tagName] = child.firstChild.data
|
'Process SM element LearningData'
| def do_LearningData(self, node):
| for child in node.childNodes:
if (hasattr(child, 'tagName') and (child.firstChild != None)):
self.cntElm[(-1)][child.tagName] = child.firstChild.data
|
'Process SM element Title'
| def do_Title(self, node):
| t = self._decode_htmlescapes(node.firstChild.data)
self.cntElm[(-1)][node.tagName] = t
self.cntMeta['title'].append(t)
self.cntElm[(-1)]['lTitle'] = self.cntMeta['title']
self.logger(('Start of topic DCTB - ' + ' / '.join(self.cntMeta['title'])), level=2)
|
'Process SM element Type'
| def do_Type(self, node):
| if (len(self.cntBuf) >= 1):
self.cntElm[(-1)][node.tagName] = self.cntBuf.pop()
|
'Parse the top line and determine the pattern and number of fields.'
| def open(self):
| self.cacheFile()
|
'Read file into self.lines if not already there.'
| def cacheFile(self):
| if (not self.fileobj):
self.openFile()
|
'Number of fields.'
| def fields(self):
| self.open()
return self.numFields
|
'Pauker is Front/Back'
| def fields(self):
| return 2
|
'Build and return a list of notes.'
| def foreignNotes(self):
| notes = []
try:
f = gzip.open(self.file)
tree = ET.parse(f)
lesson = tree.getroot()
assert (lesson.tag == 'Lesson')
finally:
f.close()
index = (-4)
for batch in lesson.findall('./Batch'):
index += 1
for card in batch.findall('./Card'):
... |
'Escape newlines, tabs, CSS and quotechar.'
| def escapeText(self, text):
| text = text.replace('\n', ' ')
text = text.replace(' DCTB ', (' ' * 8))
text = re.sub('(?i)<style>.*?</style>', '', text)
if ('"' in text):
text = (('"' + text.replace('"', '""')) + '"')
return text
|
'Return a list of card ids for QUERY.'
| def findCards(self, query, order=False):
| tokens = self._tokenize(query)
(preds, args) = self._where(tokens)
if (preds is None):
raise Exception('invalidSearch')
(order, rev) = self._order(order)
sql = self._query(preds, order)
try:
res = self.col.db.list(sql, *args)
except:
return []
if rev:
res.... |
'If fields or tags have changed, write changes to disk.'
| def flush(self, mod=None):
| assert (self.scm == self.col.scm)
self._preFlush()
sfld = stripHTMLMedia(self.fields[self.col.models.sortIdx(self._model)])
tags = self.stringTags()
fields = self.joinedFields()
if ((not mod) and self.col.db.scalar('select 1 from notes where id = ? and tags = ? ... |
'1 if first is empty; 2 if first is a duplicate, False otherwise.'
| def dupeOrEmpty(self):
| val = self.fields[0]
if (not val.strip()):
return 1
csum = fieldChecksum(val)
for flds in self.col.db.list('select flds from notes where csum = ? and id != ? and mid = ?', csum, (self.id or 0), self.mid):
if (stripHTMLMedia(splitFields(flds)[0... |
'Return (missingFiles, unusedFiles).'
| def check(self, local=None):
| mdir = self.dir()
allRefs = set()
for (nid, mid, flds) in self.col.db.execute('select id, mid, flds from notes'):
noteRefs = self.filesInStr(mid, flds)
for f in noteRefs:
if (f != unicodedata.normalize('NFC', f)):
self._normalizeNoteRefs(nid)
... |
'Scan the media folder if it\'s changed, and note any changes.'
| def findChanges(self):
| if self._changed():
self._logChanges()
|
'Return dir mtime if it has changed since the last findChanges()'
| def _changed(self):
| mod = self.db.scalar('select dirMod from meta')
mtime = self._mtime(self.dir())
if ((not self._isFAT32()) and mod and (mod == mtime)):
return False
return mtime
|
'Extract zip data; true if finished.'
| def addFilesFromZip(self, zipData):
| f = io.BytesIO(zipData)
z = zipfile.ZipFile(f, 'r')
media = []
meta = json.loads(z.read('_meta').decode('utf8'))
cnt = 0
for i in z.infolist():
if (i.filename == '_meta'):
continue
else:
data = z.read(i)
csum = checksum(data)
name =... |
'Mark DB modified.
DB operations and the deck/tag/model managers do this automatically, so this
is only necessary if you modify properties of this object or the conf dict.'
| def setMod(self):
| self.db.mod = True
|
'Flush state to DB, updating mod time.'
| def flush(self, mod=None):
| self.mod = (intTime(1000) if (mod is None) else mod)
self.db.execute('update col set\ncrt=?, mod=?, scm=?, dty=?, usn=?, ls=?, conf=?', self.crt, self.mod, self.scm, self.dty, self._usn, self.ls, json.dumps(self.conf))
|
'Flush, commit DB, and take out another write lock.'
| def save(self, name=None, mod=None):
| self.models.flush()
self.decks.flush()
self.tags.flush()
if self.db.mod:
self.flush(mod=mod)
self.db.commit()
self.lock()
self.db.mod = False
self._markOp(name)
self._lastSave = time.time()
|
'Save if 5 minutes has passed since last save. True if saved.'
| def autosave(self):
| if ((time.time() - self._lastSave) > 300):
self.save()
return True
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.