sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1 value |
|---|---|---|
def validate(path, format='json',
approved_applications=None,
determined=True,
listed=True,
expectation=PACKAGE_ANY,
for_appversions=None,
overrides=None,
timeout=-1,
compat_test=False,
**kw):
"""
Perform validation in one easy step!
`path`:
*Required*
A file system path to the package to be validated.
`format`:
The format to return the results in. Defaults to "json". Currently, any
other format will simply return the error bundle.
`approved_applications`:
Path to the list of approved application versions
`determined`:
If set to `False`, validation will halt at the end of the first tier
that raises errors.
`listed`:
Whether the app is headed for the app marketplace or AMO. Defaults to
`True`.
`expectation`:
The type of package that should be expected. Must be a symbolic
constant from validator.constants (i.e.:
validator.constants.PACKAGE_*). Defaults to PACKAGE_ANY.
`for_appversions`:
A dict of app GUIDs referencing lists of versions. Determines which
version-dependant tests should be run.
`timeout`:
Number of seconds before aborting addon validation, or -1 to
run with no timeout.
`compat_tests`:
A flag to signal the validator to skip tests which should not be run
during compatibility bumps. Defaults to `False`.
"""
bundle = ErrorBundle(listed=listed, determined=determined,
overrides=overrides, for_appversions=for_appversions)
bundle.save_resource('is_compat_test', compat_test)
if approved_applications is None:
approved_applications = os.path.join(os.path.dirname(__file__),
'app_versions.json')
if isinstance(approved_applications, types.StringTypes):
# Load up the target applications if the approved applications is a
# path (string).
with open(approved_applications) as approved_apps:
apps = json.load(approved_apps)
elif isinstance(approved_applications, dict):
# If the lists of approved applications are already in a dict, just use
# that instead of trying to pull from a file.
apps = approved_applications
else:
raise ValueError('Unknown format for `approved_applications`.')
constants.APPROVED_APPLICATIONS.clear()
constants.APPROVED_APPLICATIONS.update(apps)
submain.prepare_package(bundle, path, expectation,
for_appversions=for_appversions,
timeout=timeout)
return format_result(bundle, format) | Perform validation in one easy step!
`path`:
*Required*
A file system path to the package to be validated.
`format`:
The format to return the results in. Defaults to "json". Currently, any
other format will simply return the error bundle.
`approved_applications`:
Path to the list of approved application versions
`determined`:
If set to `False`, validation will halt at the end of the first tier
that raises errors.
`listed`:
Whether the app is headed for the app marketplace or AMO. Defaults to
`True`.
`expectation`:
The type of package that should be expected. Must be a symbolic
constant from validator.constants (i.e.:
validator.constants.PACKAGE_*). Defaults to PACKAGE_ANY.
`for_appversions`:
A dict of app GUIDs referencing lists of versions. Determines which
version-dependant tests should be run.
`timeout`:
Number of seconds before aborting addon validation, or -1 to
run with no timeout.
`compat_tests`:
A flag to signal the validator to skip tests which should not be run
during compatibility bumps. Defaults to `False`. | entailment |
def system_error(self, msg_id=None, message=None, description=None,
validation_timeout=False, exc_info=None, **kw):
"""Add an error message for an unexpected exception in validator
code, and move it to the front of the error message list. If
`exc_info` is supplied, the error will be logged.
If the error is a validation timeout, it is re-raised unless
`msg_id` is "validation_timeout"."""
if exc_info:
if (isinstance(exc_info[1], validator.ValidationTimeout) and
msg_id != 'validation_timeout'):
# These should always propagate to the top-level exception
# handler, and be reported only once.
raise exc_info[1]
log.error('Unexpected error during validation: %s: %s'
% (exc_info[0].__name__, exc_info[1]),
exc_info=exc_info)
full_id = ('validator', 'unexpected_exception')
if msg_id:
full_id += (msg_id,)
self.error(full_id,
message or 'An unexpected error has occurred.',
description or
('Validation was unable to complete successfully due '
'to an unexpected error.',
'The error has been logged, but please consider '
'filing an issue report here: '
'https://bit.ly/1POrYYU'),
tier=1, **kw)
# Move the error message to the beginning of the list.
self.errors.insert(0, self.errors.pop()) | Add an error message for an unexpected exception in validator
code, and move it to the front of the error message list. If
`exc_info` is supplied, the error will be logged.
If the error is a validation timeout, it is re-raised unless
`msg_id` is "validation_timeout". | entailment |
def drop_message(self, message):
"""Drop the given message object from the appropriate message list.
Returns True if the message was found, otherwise False."""
for type_ in 'errors', 'warnings', 'notices':
list_ = getattr(self, type_)
if message in list_:
list_.remove(message)
if 'signing_severity' in message:
self.signing_summary[message['signing_severity']] -= 1
return True
return False | Drop the given message object from the appropriate message list.
Returns True if the message was found, otherwise False. | entailment |
def set_tier(self, tier):
'Updates the tier and ending tier'
self.tier = tier
if tier > self.ending_tier:
self.ending_tier = tier | Updates the tier and ending tier | entailment |
def _save_message(self, stack, type_, message, context=None,
from_merge=False):
'Stores a message in the appropriate message stack.'
uid = uuid.uuid4().hex
message['uid'] = uid
# Get the context for the message (if there's a context available)
if context is not None:
if isinstance(context, tuple):
message['context'] = context
else:
message['context'] = (
context.get_context(line=message['line'],
column=message['column']))
else:
message['context'] = None
if self.package_stack:
if not isinstance(message['file'], list):
message['file'] = [message['file']]
message['file'] = self.package_stack + message['file']
# Test that if for_appversions is set that we're only applying to
# supported add-ons. THIS IS THE LAST FILTER BEFORE THE MESSAGE IS
# ADDED TO THE STACK!
if message['for_appversions']:
if not self.supports_version(message['for_appversions']):
if self.instant:
print '(Instant error discarded)'
self._print_message(type_, message, verbose=True)
return
elif self.version_requirements:
# If there was no for_appversions but there were version
# requirements detailed in the decorator, use the ones from the
# decorator.
message['for_appversions'] = self.version_requirements
# Save the message to the stack.
stack.append(message)
# Mark the tier that the error occurred at.
if message['tier'] is None:
message['tier'] = self.tier
# Build out the compatibility summary if possible.
if message['compatibility_type'] and not from_merge:
self.compat_summary['%ss' % message['compatibility_type']] += 1
# Build out the message tree entry.
if message['id']:
tree = self.message_tree
last_id = None
for eid in message['id']:
if last_id is not None:
tree = tree[last_id]
if eid not in tree:
tree[eid] = {'__errors': 0,
'__warnings': 0,
'__notices': 0,
'__messages': []}
tree[eid]['__%s' % type_] += 1
last_id = eid
tree[last_id]['__messages'].append(uid)
# If instant mode is turned on, output the message immediately.
if self.instant:
self._print_message(type_, message, verbose=True) | Stores a message in the appropriate message stack. | entailment |
def failed(self, fail_on_warnings=True):
"""Returns a boolean value describing whether the validation
succeeded or not."""
return bool(self.errors) or (fail_on_warnings and bool(self.warnings)) | Returns a boolean value describing whether the validation
succeeded or not. | entailment |
def get_resource(self, name):
'Retrieves an object that has been stored by another test.'
if name in self.resources:
return self.resources[name]
elif name in self.pushable_resources:
return self.pushable_resources[name]
else:
return False | Retrieves an object that has been stored by another test. | entailment |
def save_resource(self, name, resource, pushable=False):
'Saves an object such that it can be used by other tests.'
if pushable:
self.pushable_resources[name] = resource
else:
self.resources[name] = resource | Saves an object such that it can be used by other tests. | entailment |
def push_state(self, new_file=''):
'Saves the current error state to parse subpackages'
self.subpackages.append({'detected_type': self.detected_type,
'message_tree': self.message_tree,
'resources': self.pushable_resources,
'metadata': self.metadata})
self.message_tree = {}
self.pushable_resources = {}
self.metadata = {'requires_chrome': False,
'listed': self.metadata.get('listed'),
'validator_version': validator.__version__}
self.package_stack.append(new_file) | Saves the current error state to parse subpackages | entailment |
def pop_state(self):
'Retrieves the last saved state and restores it.'
# Save a copy of the current state.
state = self.subpackages.pop()
metadata = self.metadata
# We only rebuild message_tree anyway. No need to restore.
# Copy the existing state back into place
self.detected_type = state['detected_type']
self.message_tree = state['message_tree']
self.pushable_resources = state['resources']
self.metadata = state['metadata']
name = self.package_stack.pop()
self.metadata.setdefault('sub_packages', {})[name] = metadata | Retrieves the last saved state and restores it. | entailment |
def render_json(self):
'Returns a JSON summary of the validation operation.'
types = {0: 'unknown',
1: 'extension',
2: 'theme',
3: 'dictionary',
4: 'langpack',
5: 'search',
8: 'webapp'}
output = {'detected_type': types[self.detected_type],
'ending_tier': self.ending_tier,
'success': not self.failed(),
'messages': [],
'errors': len(self.errors),
'warnings': len(self.warnings),
'notices': len(self.notices),
'message_tree': self.message_tree,
'compatibility_summary': self.compat_summary,
'signing_summary': self.signing_summary,
'metadata': self.metadata}
messages = output['messages']
# Copy messages to the JSON output
for error in self.errors:
error['type'] = 'error'
messages.append(error)
for warning in self.warnings:
warning['type'] = 'warning'
messages.append(warning)
for notice in self.notices:
notice['type'] = 'notice'
messages.append(notice)
# Output the JSON.
return json.dumps(output) | Returns a JSON summary of the validation operation. | entailment |
def print_summary(self, verbose=False, no_color=False):
'Prints a summary of the validation process so far.'
types = {0: 'Unknown',
1: 'Extension/Multi-Extension',
2: 'Full Theme',
3: 'Dictionary',
4: 'Language Pack',
5: 'Search Provider',
7: 'Subpackage',
8: 'App'}
detected_type = types[self.detected_type]
buffer = StringIO()
self.handler = OutputHandler(buffer, no_color)
# Make a neat little printout.
self.handler.write('\n<<GREEN>>Summary:') \
.write('-' * 30) \
.write('Detected type: <<BLUE>>%s' % detected_type) \
.write('-' * 30)
if self.failed():
self.handler.write('<<BLUE>>Test failed! Errors:')
# Print out all the errors/warnings:
for error in self.errors:
self._print_message('<<RED>>Error:<<NORMAL>>\t',
error, verbose)
for warning in self.warnings:
self._print_message('<<YELLOW>>Warning:<<NORMAL>> ',
warning, verbose)
else:
self.handler.write('<<GREEN>>All tests succeeded!')
if self.notices:
for notice in self.notices:
self._print_message(prefix='<<WHITE>>Notice:<<NORMAL>>\t',
message=notice,
verbose=verbose)
if 'is_jetpack' in self.metadata and verbose:
self.handler.write('\n')
self.handler.write('<<GREEN>>Jetpack add-on detected.<<NORMAL>>\n'
'Identified files:')
if 'jetpack_identified_files' in self.metadata:
for filename, data in \
self.metadata['jetpack_identified_files'].items():
self.handler.write((' %s\n' % filename) +
(' %s : %s' % data))
if 'jetpack_unknown_files' in self.metadata:
self.handler.write('Unknown files:')
for filename in self.metadata['jetpack_unknown_files']:
self.handler.write(' %s' % filename)
self.handler.write('\n')
if self.unfinished:
self.handler.write('<<RED>>Validation terminated early')
self.handler.write('Errors during validation are preventing '
'the validation process from completing.')
self.handler.write('Use the <<YELLOW>>--determined<<NORMAL>> '
'flag to ignore these errors.')
self.handler.write('\n')
return buffer.getvalue() | Prints a summary of the validation process so far. | entailment |
def _flatten_list(self, data):
'Flattens nested lists into strings.'
if data is None:
return ''
if isinstance(data, types.StringTypes):
return data
elif isinstance(data, (list, tuple)):
return '\n'.join(self._flatten_list(x) for x in data) | Flattens nested lists into strings. | entailment |
def _print_message(self, prefix, message, verbose=True):
'Prints a message and takes care of all sorts of nasty code'
# Load up the standard output.
output = ['\n', prefix, message['message']]
# We have some extra stuff for verbose mode.
if verbose:
verbose_output = []
# Detailed problem description.
if message['description']:
verbose_output.append(
self._flatten_list(message['description']))
if message.get('signing_severity'):
verbose_output.append(
('\tAutomated signing severity: %s' %
message['signing_severity']))
if message.get('signing_help'):
verbose_output.append(
'\tSuggestions for passing automated signing:')
verbose_output.append(
self._flatten_list(message['signing_help']))
# Show the user what tier we're on
verbose_output.append('\tTier:\t%d' % message['tier'])
# If file information is available, output that as well.
files = message['file']
if files is not None and files != '':
fmsg = '\tFile:\t%s'
# Nested files (subpackes) are stored in a list.
if type(files) is list:
if files[-1] == '':
files[-1] = '(none)'
verbose_output.append(fmsg % ' > '.join(files))
else:
verbose_output.append(fmsg % files)
# If there is a line number, that gets put on the end.
if message['line']:
verbose_output.append('\tLine:\t%s' % message['line'])
if message['column'] and message['column'] != 0:
verbose_output.append('\tColumn:\t%d' % message['column'])
if message.get('context'):
verbose_output.append('\tContext:')
verbose_output.extend([('\t> %s' % x
if x is not None
else '\t>' + ('-' * 20))
for x
in message['context']])
# Stick it in with the standard items.
output.append('\n')
output.append('\n'.join(verbose_output))
# Send the final output to the handler to be rendered.
self.handler.write(u''.join(map(unicodehelper.decode, output))) | Prints a message and takes care of all sorts of nasty code | entailment |
def supports_version(self, guid_set):
"""
Returns whether a GUID set in for_appversions format is compatbile with
the current supported applications list.
"""
# Don't let the test run if we haven't parsed install.rdf yet.
if self.supported_versions is None:
raise Exception('Early compatibility test run before install.rdf '
'was parsed.')
return self._compare_version(requirements=guid_set,
support=self.supported_versions) | Returns whether a GUID set in for_appversions format is compatbile with
the current supported applications list. | entailment |
def _compare_version(self, requirements, support):
"""
Return whether there is an intersection between a support applications
GUID set and a set of supported applications.
"""
for guid in requirements:
# If we support any of the GUIDs in the guid_set, test if any of
# the provided versions for the GUID are supported.
if (guid in support and
any((detected_version in requirements[guid]) for
detected_version in support[guid])):
return True | Return whether there is an intersection between a support applications
GUID set and a set of supported applications. | entailment |
def discard_unused_messages(self, ending_tier):
"""
Delete messages from errors, warnings, and notices whose tier is
greater than the ending tier.
"""
stacks = [self.errors, self.warnings, self.notices]
for stack in stacks:
for message in stack:
if message['tier'] > ending_tier:
stack.remove(message) | Delete messages from errors, warnings, and notices whose tier is
greater than the ending tier. | entailment |
def migrator(state):
"""Tweaks will be lost for Cleverbot and its conversations."""
for tweak in ('tweak1', 'tweak2', 'tweak3'):
del state[0][tweak]
for convo in state[1]:
if tweak in convo:
del convo[tweak]
return state | Tweaks will be lost for Cleverbot and its conversations. | entailment |
def migrator(state):
"""Nameless conversations will be lost."""
cleverbot_kwargs, convos_kwargs = state
cb = Cleverbot(**cleverbot_kwargs)
for convo_kwargs in convos_kwargs:
cb.conversation(**convo_kwargs)
return cb | Nameless conversations will be lost. | entailment |
def init_with_uid(self, uid):
"""Initialize with an UID
"""
self._uid = uid
self._brain = None
self._catalog = None
self._instance = None | Initialize with an UID | entailment |
def init_with_brain(self, brain):
"""Initialize with a catalog brain
"""
self._uid = api.get_uid(brain)
self._brain = brain
self._catalog = self.get_catalog_for(brain)
self._instance = None | Initialize with a catalog brain | entailment |
def init_with_instance(self, instance):
"""Initialize with an instance object
"""
self._uid = api.get_uid(instance)
self._brain = None
self._catalog = self.get_catalog_for(instance)
self._instance = instance | Initialize with an instance object | entailment |
def process_value(self, value):
"""Process publication value
"""
# UID -> SuperModel
if api.is_uid(value):
return self.to_super_model(value)
# Content -> SuperModel
elif api.is_object(value):
return self.to_super_model(value)
# String -> Unicode
elif isinstance(value, basestring):
return safe_unicode(value).encode("utf-8")
# DateTime -> DateTime
elif isinstance(value, DateTime):
return value
# Process list values
elif isinstance(value, (LazyMap, list, tuple)):
return map(self.process_value, value)
# Process dict values
elif isinstance(value, (dict)):
return {k: self.process_value(v) for k, v in value.iteritems()}
# Process function
elif safe_callable(value):
return self.process_value(value())
# Always return the unprocessed value last
return value | Process publication value | entailment |
def instance(self):
"""Content instance of the wrapped object
"""
if self._instance is None:
logger.debug("SuperModel::instance: *Wakup object*")
self._instance = api.get_object(self.brain)
return self._instance | Content instance of the wrapped object | entailment |
def brain(self):
"""Catalog brain of the wrapped object
"""
if self._brain is None:
logger.debug("SuperModel::brain: *Fetch catalog brain*")
self._brain = self.get_brain_by_uid(self.uid)
return self._brain | Catalog brain of the wrapped object | entailment |
def catalog(self):
"""Primary registered catalog for the wrapped portal type
"""
if self._catalog is None:
logger.debug("SuperModel::catalog: *Fetch catalog*")
self._catalog = self.get_catalog_for(self.brain)
return self._catalog | Primary registered catalog for the wrapped portal type | entailment |
def get_catalog_for(self, brain_or_object):
"""Return the primary catalog for the given brain or object
"""
if not api.is_object(brain_or_object):
raise TypeError("Invalid object type %r" % brain_or_object)
catalogs = api.get_catalogs_for(brain_or_object, default="uid_catalog")
return catalogs[0] | Return the primary catalog for the given brain or object | entailment |
def get_brain_by_uid(self, uid):
"""Lookup brain from the right catalog
"""
if uid == "0":
return api.get_portal()
# ensure we have the primary catalog
if self._catalog is None:
uid_catalog = api.get_tool("uid_catalog")
results = uid_catalog({"UID": uid})
if len(results) != 1:
raise ValueError("No object found for UID '{}'".format(uid))
brain = results[0]
self._catalog = self.get_catalog_for(brain)
# Fetch the brain with the primary catalog
results = self.catalog({"UID": uid})
if not results:
raise ValueError("No results found for UID '{}'".format(uid))
if len(results) != 1:
raise ValueError("Found more than one object for UID '{}'"
.format(uid))
return results[0] | Lookup brain from the right catalog | entailment |
def to_super_model(self, thing):
"""Wraps an object into a Super Model
"""
if api.is_uid(thing):
return SuperModel(thing)
if not api.is_object(thing):
raise TypeError("Expected a portal object, got '{}'"
.format(type(thing)))
return thing | Wraps an object into a Super Model | entailment |
def stringify(self, value):
"""Convert value to string
This method is used to generate a simple JSON representation of the
object (without dereferencing objects etc.)
"""
# SuperModel -> UID
if ISuperModel.providedBy(value):
return str(value)
# DateTime -> ISO8601 format
elif isinstance(value, (DateTime)):
return value.ISO8601()
# Image/Files -> filename
elif safe_hasattr(value, "filename"):
return value.filename
# Dict -> convert_value_to_string
elif isinstance(value, dict):
return {k: self.stringify(v) for k, v in value.iteritems()}
# List -> convert_value_to_string
if isinstance(value, (list, tuple, LazyMap)):
return map(self.stringify, value)
# Callables
elif safe_callable(value):
return self.stringify(value())
elif isinstance(value, unicode):
value = value.encode("utf8")
try:
return str(value)
except (AttributeError, TypeError, ValueError):
logger.warn("Could not convert {} to string".format(repr(value)))
return None | Convert value to string
This method is used to generate a simple JSON representation of the
object (without dereferencing objects etc.) | entailment |
def to_dict(self, converter=None):
"""Returns a copy dict of the current object
If a converter function is given, pass each value to it.
Per default the values are converted by `self.stringify`.
"""
if converter is None:
converter = self.stringify
out = dict()
for k, v in self.iteritems():
out[k] = converter(v)
return out | Returns a copy dict of the current object
If a converter function is given, pass each value to it.
Per default the values are converted by `self.stringify`. | entailment |
def route(self, url_rule, name=None, options=None):
'''A decorator to add a route to a view. name is used to
differentiate when there are multiple routes for a given view.'''
def decorator(func):
'''Adds a url rule for the provided function'''
view_name = name or func.__name__
self.add_url_rule(url_rule, func, name=view_name, options=options)
return func
return decorator | A decorator to add a route to a view. name is used to
differentiate when there are multiple routes for a given view. | entailment |
def url_for(self, endpoint, explicit=False, **items):
'''Returns a valid XBMC plugin URL for the given endpoint name.
endpoint can be the literal name of a function, or it can
correspond to the name keyword arguments passed to the route
decorator.
Currently, view names must be unique across all plugins and
modules. There are not namespace prefixes for modules.
'''
# TODO: Enable items to be passed with keywords of other var names
# such as endpoing and explicit
# TODO: Figure out how to handle the case where a module wants to
# call a parent plugin view.
if not explicit and not endpoint.startswith(self._namespace):
endpoint = '%s.%s' % (self._namespace, endpoint)
return self._plugin.url_for(endpoint, **items) | Returns a valid XBMC plugin URL for the given endpoint name.
endpoint can be the literal name of a function, or it can
correspond to the name keyword arguments passed to the route
decorator.
Currently, view names must be unique across all plugins and
modules. There are not namespace prefixes for modules. | entailment |
def add_url_rule(self, url_rule, view_func, name, options=None):
'''This method adds a URL rule for routing purposes. The
provided name can be different from the view function name if
desired. The provided name is what is used in url_for to build
a URL.
The route decorator provides the same functionality.
'''
name = '%s.%s' % (self._namespace, name)
def register_rule(plugin, url_prefix):
'''Registers a url rule for the provided plugin and
url_prefix.
'''
full_url_rule = url_prefix + url_rule
plugin.add_url_rule(full_url_rule, view_func, name, options)
# Delay actual registration of the url rule until this module is
# registered with a plugin
self._register_funcs.append(register_rule) | This method adds a URL rule for routing purposes. The
provided name can be different from the view function name if
desired. The provided name is what is used in url_for to build
a URL.
The route decorator provides the same functionality. | entailment |
def get_parser(self, prog_name):
"""Override to add command options."""
parser = argparse.ArgumentParser(description=self.get_description(),
prog=prog_name, add_help=False)
return parser | Override to add command options. | entailment |
def validate_pluginid(value):
'''Returns True if the provided value is a valid pluglin id'''
valid = string.ascii_letters + string.digits + '.'
return all(c in valid for c in value) | Returns True if the provided value is a valid pluglin id | entailment |
def get_valid_value(prompt, validator, default=None):
'''Displays the provided prompt and gets input from the user. This behavior
loops indefinitely until the provided validator returns True for the user
input. If a default value is provided, it will be used only if the user
hits Enter and does not provide a value.
If the validator callable has an error_message attribute, it will be
displayed for an invalid value, otherwise a generic message is used.
'''
ans = get_value(prompt, default)
while not validator(ans):
try:
print validator.error_message
except AttributeError:
print 'Invalid value.'
ans = get_value(prompt, default)
return ans | Displays the provided prompt and gets input from the user. This behavior
loops indefinitely until the provided validator returns True for the user
input. If a default value is provided, it will be used only if the user
hits Enter and does not provide a value.
If the validator callable has an error_message attribute, it will be
displayed for an invalid value, otherwise a generic message is used. | entailment |
def get_value(prompt, default=None, hidden=False):
'''Displays the provided prompt and returns the input from the user. If the
user hits Enter and there is a default value provided, the default is
returned.
'''
_prompt = '%s : ' % prompt
if default:
_prompt = '%s [%s]: ' % (prompt, default)
if hidden:
ans = getpass(_prompt)
else:
ans = raw_input(_prompt)
# If user hit Enter and there is a default value
if not ans and default:
ans = default
return ans | Displays the provided prompt and returns the input from the user. If the
user hits Enter and there is a default value provided, the default is
returned. | entailment |
def update_file(filename, items):
'''Edits the given file in place, replacing any instances of {key} with the
appropriate value from the provided items dict. If the given filename ends
with ".xml" values will be quoted and escaped for XML.
'''
# TODO: Implement something in the templates to denote whether the value
# being replaced is an XML attribute or a value. Perhaps move to dyanmic
# XML tree building rather than string replacement.
should_escape = filename.endswith('addon.xml')
with open(filename, 'r') as inp:
text = inp.read()
for key, val in items.items():
if should_escape:
val = saxutils.quoteattr(val)
text = text.replace('{%s}' % key, val)
output = text
with open(filename, 'w') as out:
out.write(output) | Edits the given file in place, replacing any instances of {key} with the
appropriate value from the provided items dict. If the given filename ends
with ".xml" values will be quoted and escaped for XML. | entailment |
def create_new_project():
'''Creates a new XBMC Addon directory based on user input'''
readline.parse_and_bind('tab: complete')
print \
'''
xbmcswift2 - A micro-framework for creating XBMC plugins.
xbmc@jonathanbeluch.com
--
'''
print 'I\'m going to ask you a few questions to get this project' \
' started.'
opts = {}
# Plugin Name
opts['plugin_name'] = get_valid_value(
'What is your plugin name?',
validate_nonblank
)
# Plugin ID
opts['plugin_id'] = get_valid_value(
'Enter your plugin id.',
validate_pluginid,
'plugin.video.%s' % (opts['plugin_name'].lower().replace(' ', ''))
)
# Parent Directory
opts['parent_dir'] = get_valid_value(
'Enter parent folder (where to create project)',
validate_isfolder,
getcwd()
)
opts['plugin_dir'] = os.path.join(opts['parent_dir'], opts['plugin_id'])
assert not os.path.isdir(opts['plugin_dir']), \
'A folder named %s already exists in %s.' % (opts['plugin_id'],
opts['parent_dir'])
# Provider
opts['provider_name'] = get_valid_value(
'Enter provider name',
validate_nonblank,
)
# Create the project folder by copying over skel
copytree(SKEL, opts['plugin_dir'], ignore=ignore_patterns('*.pyc'))
# Walk through all the new files and fill in with out options
for root, dirs, files in os.walk(opts['plugin_dir']):
for filename in files:
update_file(os.path.join(root, filename), opts)
print 'Projects successfully created in %s.' % opts['plugin_dir']
print 'Done.' | Creates a new XBMC Addon directory based on user input | entailment |
def get_applications(self):
"""Return the list of supported applications."""
if ('applications' not in self.data or
'gecko' not in self.data['applications']):
return []
app = self.data['applications']['gecko']
min_version = app.get('strict_min_version', u'42.0')
max_version = app.get('strict_max_version', u'*')
return [{u'guid': FIREFOX_GUID,
u'min_version': min_version,
u'max_version': max_version}] | Return the list of supported applications. | entailment |
def get_value(self, subject=None, predicate=None, object_=None):
"""Returns the first triple value matching the given subject,
predicate, and/or object"""
for triple in self.triples:
# Filter out non-matches
if (subject and triple['subject'] != subject) or \
(predicate and triple['predicate'] != predicate) or \
(object_ and triple['object'] != object_): # pragma: no cover
continue
# Return the first found.
return triple
return None | Returns the first triple value matching the given subject,
predicate, and/or object | entailment |
def get_objects(self, subject=None, predicate=None):
"""Returns a generator of objects that correspond to the
specified subjects and predicates."""
for triple in self.triples:
# Filter out non-matches
if ((subject and triple['subject'] != subject) or
(predicate and triple['predicate'] != predicate)):
continue
yield triple['object'] | Returns a generator of objects that correspond to the
specified subjects and predicates. | entailment |
def get_triples(self, subject=None, predicate=None, object_=None):
"""Returns triples that correspond to the specified subject,
predicates, and objects."""
for triple in self.triples:
# Filter out non-matches
if subject is not None and triple['subject'] != subject:
continue
if predicate is not None and triple['predicate'] != predicate:
continue
if object_ is not None and triple['object'] != object_:
continue
yield triple | Returns triples that correspond to the specified subject,
predicates, and objects. | entailment |
def get_applicable_overlays(self, error_bundle):
"""
Given an error bundle, a list of overlays that are present in the
current package or subpackage are returned.
"""
content_paths = self.get_triples(subject='content')
if not content_paths:
return set()
# Create some variables that will store where the applicable content
# instruction path references and where it links to.
chrome_path = ''
content_root_path = '/'
# Look through each of the listed packages and paths.
for path in content_paths:
chrome_name = path['predicate']
if not path['object']:
continue
path_location = path['object'].strip().split()[0]
# Handle jarred paths differently.
if path_location.startswith('jar:'):
if not error_bundle.is_nested_package:
continue
# Parse out the JAR and it's location within the chrome.
split_jar_url = path_location[4:].split('!', 2)
# Ignore invalid/unsupported JAR URLs.
if len(split_jar_url) != 2:
continue
# Unpack the JAR URL.
jar_path, package_path = split_jar_url
# Ignore the instruction if the JAR it points to doesn't match
# up with the current subpackage tree.
if jar_path != error_bundle.package_stack[0]:
continue
chrome_path = self._url_chunk_join(chrome_name, package_path)
# content_root_path stays at the default: /
break
else:
# If we're in a subpackage, a content instruction referring to
# the root of the package obviously doesn't apply.
if error_bundle.is_nested_package:
continue
chrome_path = self._url_chunk_join(chrome_name, 'content')
content_root_path = '/%s/' % path_location.strip('/')
break
if not chrome_path:
return set()
applicable_overlays = set()
chrome_path = 'chrome://%s' % self._url_chunk_join(chrome_path + '/')
for overlay in self.get_triples(subject='overlay'):
if not overlay['object']:
error_bundle.error(
err_id=('chromemanifest', 'get_applicable_overalys',
'object'),
error='Overlay instruction missing a property.',
description='When overlays are registered in a chrome '
'manifest file, they require a namespace and '
'a chrome URL at minimum.',
filename=overlay['filename'],
line=overlay['line'],
context=self.context) #TODO(basta): Update this!
continue
overlay_url = overlay['object'].split()[0]
if overlay_url.startswith(chrome_path):
overlay_relative_path = overlay_url[len(chrome_path):]
applicable_overlays.add('/%s' %
self._url_chunk_join(content_root_path,
overlay_relative_path))
return applicable_overlays | Given an error bundle, a list of overlays that are present in the
current package or subpackage are returned. | entailment |
def reverse_lookup(self, state, path):
"""
Returns a chrome URL for a given path, given the current package depth
in an error bundle.
State may either be an error bundle or the actual package stack.
"""
# Make sure the path starts with a forward slash.
if not path.startswith('/'):
path = '/%s' % path
# If the state is an error bundle, extract the package stack.
if not isinstance(state, list):
state = state.package_stack
content_paths = self.get_triples(subject='content')
for content_path in content_paths:
chrome_name = content_path['predicate']
if not content_path['object']:
continue
path_location = content_path['object'].split()[0]
if path_location.startswith('jar:'):
if not state:
continue
# Parse out the JAR and it's location within the chrome.
split_jar_url = path_location[4:].split('!', 2)
# Ignore invalid/unsupported JAR URLs.
if len(split_jar_url) != 2:
continue
# Unpack the JAR URL.
jar_path, package_path = split_jar_url
if jar_path != state[0]:
continue
return 'chrome://%s' % self._url_chunk_join(chrome_name,
package_path,
path)
else:
if state:
continue
path_location = '/%s/' % path_location.strip('/')
rel_path = os.path.relpath(path, path_location)
if rel_path.startswith('../') or rel_path == '..':
continue
return 'chrome://%s' % self._url_chunk_join(chrome_name,
rel_path)
return None | Returns a chrome URL for a given path, given the current package depth
in an error bundle.
State may either be an error bundle or the actual package stack. | entailment |
def _url_chunk_join(self, *args):
"""Join the arguments together to form a predictable URL chunk."""
# Strip slashes from either side of each path piece.
pathlets = map(lambda s: s.strip('/'), args)
# Remove empty pieces.
pathlets = filter(None, pathlets)
url = '/'.join(pathlets)
# If this is a directory, add a trailing slash.
if args[-1].endswith('/'):
url = '%s/' % url
return url | Join the arguments together to form a predictable URL chunk. | entailment |
def run(self, argv):
"""Application entry point"""
try:
self.options, remainder = self.parser.parse_known_args(argv)
self._configure_logging()
if self.options.relative_plugins:
curdir = os.getcwd()
sys.path.insert(0, curdir)
pkg_resources.working_set.add_entry(curdir)
try:
self._load_commands_for_current_dir()
except pkg_resources.DistributionNotFound as e:
try:
error_msg = repr(e)
except:
error_msg = 'Unknown Error'
log.error('Failed to load project commands with error '
'``%s``, have you installed your project?' % error_msg)
except Exception as err:
if hasattr(self, 'options'):
debug = self.options.debug
else:
debug = True
if debug:
log.exception(err)
else:
log.error(err)
return 1
return self._run_subcommand(remainder) | Application entry point | entailment |
def uri(self, element, namespace=None):
'Returns a URIRef object for use with the RDF document.'
if namespace is None:
namespace = self.namespace
return URIRef('%s#%s' % (namespace, element)) | Returns a URIRef object for use with the RDF document. | entailment |
def get_root_subject(self):
'Returns the BNode which describes the topmost subject of the graph.'
manifest = URIRef(self.manifest)
if list(self.rdf.triples((manifest, None, None))):
return manifest
else:
return self.rdf.subjects(None, self.manifest).next() | Returns the BNode which describes the topmost subject of the graph. | entailment |
def get_object(self, subject=None, predicate=None):
"""Eliminates some of the glue code for searching RDF. Pass
in a URIRef object (generated by the `uri` function above or
a BNode object (returned by this function) for either of the
parameters."""
# Get the result of the search
results = self.rdf.objects(subject, predicate)
as_list = list(results)
# Don't raise exceptions, value test!
if not as_list:
return None
return as_list[0] | Eliminates some of the glue code for searching RDF. Pass
in a URIRef object (generated by the `uri` function above or
a BNode object (returned by this function) for either of the
parameters. | entailment |
def get_objects(self, subject=None, predicate=None):
"""Same as get_object, except returns a list of objects which
satisfy the query rather than a single result."""
# Get the result of the search
results = self.rdf.objects(subject, predicate)
return list(results) | Same as get_object, except returns a list of objects which
satisfy the query rather than a single result. | entailment |
def get_applications(self):
"""Return the list of supported applications."""
applications = []
# Isolate all of the bnodes referring to target applications
for target_app in self.get_objects(None,
self.uri('targetApplication')):
applications.append({
'guid': self.get_object(target_app, self.uri('id')),
'min_version': self.get_object(target_app,
self.uri('minVersion')),
'max_version': self.get_object(target_app,
self.uri('maxVersion'))})
return applications | Return the list of supported applications. | entailment |
def add_context_menu_items(self, items, replace_items=False):
'''Adds context menu items. If replace_items is True all
previous context menu items will be removed.
'''
for label, action in items:
assert isinstance(label, basestring)
assert isinstance(action, basestring)
if replace_items:
self._context_menu_items = []
self._context_menu_items.extend(items)
self._listitem.addContextMenuItems(items, replace_items) | Adds context menu items. If replace_items is True all
previous context menu items will be removed. | entailment |
def set_icon(self, icon):
'''Sets the listitem's icon image'''
self._icon = icon
return self._listitem.setIconImage(icon) | Sets the listitem's icon image | entailment |
def set_thumbnail(self, thumbnail):
'''Sets the listitem's thumbnail image'''
self._thumbnail = thumbnail
return self._listitem.setThumbnailImage(thumbnail) | Sets the listitem's thumbnail image | entailment |
def set_path(self, path):
'''Sets the listitem's path'''
self._path = path
return self._listitem.setPath(path) | Sets the listitem's path | entailment |
def set_is_playable(self, is_playable):
'''Sets the listitem's playable flag'''
value = 'false'
if is_playable:
value = 'true'
self.set_property('isPlayable', value)
self.is_folder = not is_playable | Sets the listitem's playable flag | entailment |
def from_dict(cls, label=None, label2=None, icon=None, thumbnail=None,
path=None, selected=None, info=None, properties=None,
context_menu=None, replace_context_menu=False,
is_playable=None, info_type='video', stream_info=None):
'''A ListItem constructor for setting a lot of properties not
available in the regular __init__ method. Useful to collect all
the properties in a dict and then use the **dct to call this
method.
'''
listitem = cls(label, label2, icon, thumbnail, path)
if selected is not None:
listitem.select(selected)
if info:
listitem.set_info(info_type, info)
if is_playable:
listitem.set_is_playable(True)
if properties:
# Need to support existing tuples, but prefer to have a dict for
# properties.
if hasattr(properties, 'items'):
properties = properties.items()
for key, val in properties:
listitem.set_property(key, val)
if stream_info:
for stream_type, stream_values in stream_info.items():
listitem.add_stream_info(stream_type, stream_values)
if context_menu:
listitem.add_context_menu_items(context_menu, replace_context_menu)
return listitem | A ListItem constructor for setting a lot of properties not
available in the regular __init__ method. Useful to collect all
the properties in a dict and then use the **dct to call this
method. | entailment |
def cached(self, TTL=60 * 24):
'''A decorator that will cache the output of the wrapped function. The
key used for the cache is the function name as well as the `*args` and
`**kwargs` passed to the function.
:param TTL: time to live in minutes
.. note:: For route caching, you should use
:meth:`xbmcswift2.Plugin.cached_route`.
'''
def decorating_function(function):
# TODO test this method
storage = self.get_storage(self._function_cache_name, file_format='pickle',
TTL=TTL)
kwd_mark = 'f35c2d973e1bbbc61ca60fc6d7ae4eb3'
@wraps(function)
def wrapper(*args, **kwargs):
key = (function.__name__, kwd_mark,) + args
if kwargs:
key += (kwd_mark,) + tuple(sorted(kwargs.items()))
try:
result = storage[key]
log.debug('Storage hit for function "%s" with args "%s" '
'and kwargs "%s"', function.__name__, args,
kwargs)
except KeyError:
log.debug('Storage miss for function "%s" with args "%s" '
'and kwargs "%s"', function.__name__, args,
kwargs)
result = function(*args, **kwargs)
storage[key] = result
storage.sync()
return result
return wrapper
return decorating_function | A decorator that will cache the output of the wrapped function. The
key used for the cache is the function name as well as the `*args` and
`**kwargs` passed to the function.
:param TTL: time to live in minutes
.. note:: For route caching, you should use
:meth:`xbmcswift2.Plugin.cached_route`. | entailment |
def list_storages(self):
'''Returns a list of existing stores. The returned names can then be
used to call get_storage().
'''
# Filter out any storages used by xbmcswift2 so caller doesn't corrupt
# them.
return [name for name in os.listdir(self.storage_path)
if not name.startswith('.')] | Returns a list of existing stores. The returned names can then be
used to call get_storage(). | entailment |
def get_storage(self, name='main', file_format='pickle', TTL=None):
'''Returns a storage for the given name. The returned storage is a
fully functioning python dictionary and is designed to be used that
way. It is usually not necessary for the caller to load or save the
storage manually. If the storage does not already exist, it will be
created.
.. seealso:: :class:`xbmcswift2.TimedStorage` for more details.
:param name: The name of the storage to retrieve.
:param file_format: Choices are 'pickle', 'csv', and 'json'. Pickle is
recommended as it supports python objects.
.. note:: If a storage already exists for the given
name, the file_format parameter is
ignored. The format will be determined by
the existing storage file.
:param TTL: The time to live for storage items specified in minutes or None
for no expiration. Since storage items aren't expired until a
storage is loaded form disk, it is possible to call
get_storage() with a different TTL than when the storage was
created. The currently specified TTL is always honored.
'''
if not hasattr(self, '_unsynced_storages'):
self._unsynced_storages = {}
filename = os.path.join(self.storage_path, name)
try:
storage = self._unsynced_storages[filename]
log.debug('Loaded storage "%s" from memory', name)
except KeyError:
if TTL:
TTL = timedelta(minutes=TTL)
try:
storage = TimedStorage(filename, file_format, TTL)
except ValueError:
# Thrown when the storage file is corrupted and can't be read.
# Prompt user to delete storage.
choices = ['Clear storage', 'Cancel']
ret = xbmcgui.Dialog().select('A storage file is corrupted. It'
' is recommended to clear it.',
choices)
if ret == 0:
os.remove(filename)
storage = TimedStorage(filename, file_format, TTL)
else:
raise Exception('Corrupted storage file at %s' % filename)
self._unsynced_storages[filename] = storage
log.debug('Loaded storage "%s" from disk', name)
return storage | Returns a storage for the given name. The returned storage is a
fully functioning python dictionary and is designed to be used that
way. It is usually not necessary for the caller to load or save the
storage manually. If the storage does not already exist, it will be
created.
.. seealso:: :class:`xbmcswift2.TimedStorage` for more details.
:param name: The name of the storage to retrieve.
:param file_format: Choices are 'pickle', 'csv', and 'json'. Pickle is
recommended as it supports python objects.
.. note:: If a storage already exists for the given
name, the file_format parameter is
ignored. The format will be determined by
the existing storage file.
:param TTL: The time to live for storage items specified in minutes or None
for no expiration. Since storage items aren't expired until a
storage is loaded form disk, it is possible to call
get_storage() with a different TTL than when the storage was
created. The currently specified TTL is always honored. | entailment |
def get_string(self, stringid):
'''Returns the localized string from strings.xml for the given
stringid.
'''
stringid = int(stringid)
if not hasattr(self, '_strings'):
self._strings = {}
if not stringid in self._strings:
self._strings[stringid] = self.addon.getLocalizedString(stringid)
return self._strings[stringid] | Returns the localized string from strings.xml for the given
stringid. | entailment |
def get_setting(self, key, converter=None, choices=None):
'''Returns the settings value for the provided key.
If converter is str, unicode, bool or int the settings value will be
returned converted to the provided type.
If choices is an instance of list or tuple its item at position of the
settings value be returned.
.. note:: It is suggested to always use unicode for text-settings
because else xbmc returns utf-8 encoded strings.
:param key: The id of the setting defined in settings.xml.
:param converter: (Optional) Choices are str, unicode, bool and int.
:param converter: (Optional) Choices are instances of list or tuple.
Examples:
* ``plugin.get_setting('per_page', int)``
* ``plugin.get_setting('password', unicode)``
* ``plugin.get_setting('force_viewmode', bool)``
* ``plugin.get_setting('content', choices=('videos', 'movies'))``
'''
#TODO: allow pickling of settings items?
# TODO: STUB THIS OUT ON CLI
value = self.addon.getSetting(id=key)
if converter is str:
return value
elif converter is unicode:
return value.decode('utf-8')
elif converter is bool:
return value == 'true'
elif converter is int:
return int(value)
elif isinstance(choices, (list, tuple)):
return choices[int(value)]
elif converter is None:
log.warning('No converter provided, unicode should be used, '
'but returning str value')
return value
else:
raise TypeError('Acceptable converters are str, unicode, bool and '
'int. Acceptable choices are instances of list '
' or tuple.') | Returns the settings value for the provided key.
If converter is str, unicode, bool or int the settings value will be
returned converted to the provided type.
If choices is an instance of list or tuple its item at position of the
settings value be returned.
.. note:: It is suggested to always use unicode for text-settings
because else xbmc returns utf-8 encoded strings.
:param key: The id of the setting defined in settings.xml.
:param converter: (Optional) Choices are str, unicode, bool and int.
:param converter: (Optional) Choices are instances of list or tuple.
Examples:
* ``plugin.get_setting('per_page', int)``
* ``plugin.get_setting('password', unicode)``
* ``plugin.get_setting('force_viewmode', bool)``
* ``plugin.get_setting('content', choices=('videos', 'movies'))`` | entailment |
def add_to_playlist(self, items, playlist='video'):
'''Adds the provided list of items to the specified playlist.
Available playlists include *video* and *music*.
'''
playlists = {'music': 0, 'video': 1}
assert playlist in playlists.keys(), ('Playlist "%s" is invalid.' %
playlist)
selected_playlist = xbmc.PlayList(playlists[playlist])
_items = []
for item in items:
if not hasattr(item, 'as_xbmc_listitem'):
if 'info_type' in item.keys():
log.warning('info_type key has no affect for playlist '
'items as the info_type is inferred from the '
'playlist type.')
# info_type has to be same as the playlist type
item['info_type'] = playlist
item = xbmcswift2.ListItem.from_dict(**item)
_items.append(item)
selected_playlist.add(item.get_path(), item.as_xbmc_listitem())
return _items | Adds the provided list of items to the specified playlist.
Available playlists include *video* and *music*. | entailment |
def get_view_mode_id(self, view_mode):
'''Attempts to return a view_mode_id for a given view_mode
taking into account the current skin. If not view_mode_id can
be found, None is returned. 'thumbnail' is currently the only
suppported view_mode.
'''
view_mode_ids = VIEW_MODES.get(view_mode.lower())
if view_mode_ids:
return view_mode_ids.get(xbmc.getSkinDir())
return None | Attempts to return a view_mode_id for a given view_mode
taking into account the current skin. If not view_mode_id can
be found, None is returned. 'thumbnail' is currently the only
suppported view_mode. | entailment |
def keyboard(self, default=None, heading=None, hidden=False):
'''Displays the keyboard input window to the user. If the user does not
cancel the modal, the value entered by the user will be returned.
:param default: The placeholder text used to prepopulate the input field.
:param heading: The heading for the window. Defaults to the current
addon's name. If you require a blank heading, pass an
empty string.
:param hidden: Whether or not the input field should be masked with
stars, e.g. a password field.
'''
if heading is None:
heading = self.addon.getAddonInfo('name')
if default is None:
default = ''
keyboard = xbmc.Keyboard(default, heading, hidden)
keyboard.doModal()
if keyboard.isConfirmed():
return keyboard.getText() | Displays the keyboard input window to the user. If the user does not
cancel the modal, the value entered by the user will be returned.
:param default: The placeholder text used to prepopulate the input field.
:param heading: The heading for the window. Defaults to the current
addon's name. If you require a blank heading, pass an
empty string.
:param hidden: Whether or not the input field should be masked with
stars, e.g. a password field. | entailment |
def notify(self, msg='', title=None, delay=5000, image=''):
'''Displays a temporary notification message to the user. If
title is not provided, the plugin name will be used. To have a
blank title, pass '' for the title argument. The delay argument
is in milliseconds.
'''
if not msg:
log.warning('Empty message for notification dialog')
if title is None:
title = self.addon.getAddonInfo('name')
xbmc.executebuiltin('XBMC.Notification("%s", "%s", "%s", "%s")' %
(msg, title, delay, image)) | Displays a temporary notification message to the user. If
title is not provided, the plugin name will be used. To have a
blank title, pass '' for the title argument. The delay argument
is in milliseconds. | entailment |
def _listitemify(self, item):
'''Creates an xbmcswift2.ListItem if the provided value for item is a
dict. If item is already a valid xbmcswift2.ListItem, the item is
returned unmodified.
'''
info_type = self.info_type if hasattr(self, 'info_type') else 'video'
# Create ListItems for anything that is not already an instance of
# ListItem
if not hasattr(item, 'as_tuple'):
if 'info_type' not in item.keys():
item['info_type'] = info_type
item = xbmcswift2.ListItem.from_dict(**item)
return item | Creates an xbmcswift2.ListItem if the provided value for item is a
dict. If item is already a valid xbmcswift2.ListItem, the item is
returned unmodified. | entailment |
def _add_subtitles(self, subtitles):
'''Adds subtitles to playing video.
:param subtitles: A URL to a remote subtitles file or a local filename
for a subtitles file.
.. warning:: You must start playing a video before calling this method
or it will loop for an indefinite length.
'''
# This method is named with an underscore to suggest that callers pass
# the subtitles argument to set_resolved_url instead of calling this
# method directly. This is to ensure a video is played before calling
# this method.
player = xbmc.Player()
for _ in xrange(30):
if player.isPlaying():
break
time.sleep(1)
else:
raise Exception('No video playing. Aborted after 30 seconds.')
player.setSubtitles(subtitles) | Adds subtitles to playing video.
:param subtitles: A URL to a remote subtitles file or a local filename
for a subtitles file.
.. warning:: You must start playing a video before calling this method
or it will loop for an indefinite length. | entailment |
def set_resolved_url(self, item=None, subtitles=None):
'''Takes a url or a listitem to be played. Used in conjunction with a
playable list item with a path that calls back into your addon.
:param item: A playable list item or url. Pass None to alert XBMC of a
failure to resolve the item.
.. warning:: When using set_resolved_url you should ensure
the initial playable item (which calls back
into your addon) doesn't have a trailing
slash in the URL. Otherwise it won't work
reliably with XBMC's PlayMedia().
:param subtitles: A URL to a remote subtitles file or a local filename
for a subtitles file to be played along with the
item.
'''
if self._end_of_directory:
raise Exception('Current XBMC handle has been removed. Either '
'set_resolved_url(), end_of_directory(), or '
'finish() has already been called.')
self._end_of_directory = True
succeeded = True
if item is None:
# None item indicates the resolve url failed.
item = {}
succeeded = False
if isinstance(item, basestring):
# caller is passing a url instead of an item dict
item = {'path': item}
item = self._listitemify(item)
item.set_played(True)
xbmcplugin.setResolvedUrl(self.handle, succeeded,
item.as_xbmc_listitem())
# call to _add_subtitles must be after setResolvedUrl
if subtitles:
self._add_subtitles(subtitles)
return [item] | Takes a url or a listitem to be played. Used in conjunction with a
playable list item with a path that calls back into your addon.
:param item: A playable list item or url. Pass None to alert XBMC of a
failure to resolve the item.
.. warning:: When using set_resolved_url you should ensure
the initial playable item (which calls back
into your addon) doesn't have a trailing
slash in the URL. Otherwise it won't work
reliably with XBMC's PlayMedia().
:param subtitles: A URL to a remote subtitles file or a local filename
for a subtitles file to be played along with the
item. | entailment |
def add_items(self, items):
'''Adds ListItems to the XBMC interface. Each item in the
provided list should either be instances of xbmcswift2.ListItem,
or regular dictionaries that will be passed to
xbmcswift2.ListItem.from_dict. Returns the list of ListItems.
:param items: An iterable of items where each item is either a
dictionary with keys/values suitable for passing to
:meth:`xbmcswift2.ListItem.from_dict` or an instance of
:class:`xbmcswift2.ListItem`.
'''
_items = [self._listitemify(item) for item in items]
tuples = [item.as_tuple() for item in _items]
xbmcplugin.addDirectoryItems(self.handle, tuples, len(tuples))
# We need to keep track internally of added items so we can return them
# all at the end for testing purposes
self.added_items.extend(_items)
# Possibly need an if statement if only for debug mode
return _items | Adds ListItems to the XBMC interface. Each item in the
provided list should either be instances of xbmcswift2.ListItem,
or regular dictionaries that will be passed to
xbmcswift2.ListItem.from_dict. Returns the list of ListItems.
:param items: An iterable of items where each item is either a
dictionary with keys/values suitable for passing to
:meth:`xbmcswift2.ListItem.from_dict` or an instance of
:class:`xbmcswift2.ListItem`. | entailment |
def end_of_directory(self, succeeded=True, update_listing=False,
cache_to_disc=True):
'''Wrapper for xbmcplugin.endOfDirectory. Records state in
self._end_of_directory.
Typically it is not necessary to call this method directly, as
calling :meth:`~xbmcswift2.Plugin.finish` will call this method.
'''
self._update_listing = update_listing
if not self._end_of_directory:
self._end_of_directory = True
# Finalize the directory items
return xbmcplugin.endOfDirectory(self.handle, succeeded,
update_listing, cache_to_disc)
assert False, 'Already called endOfDirectory.' | Wrapper for xbmcplugin.endOfDirectory. Records state in
self._end_of_directory.
Typically it is not necessary to call this method directly, as
calling :meth:`~xbmcswift2.Plugin.finish` will call this method. | entailment |
def add_sort_method(self, sort_method, label2_mask=None):
'''A wrapper for `xbmcplugin.addSortMethod()
<http://mirrors.xbmc.org/docs/python-docs/xbmcplugin.html#-addSortMethod>`_.
You can use ``dir(xbmcswift2.SortMethod)`` to list all available sort
methods.
:param sort_method: A valid sort method. You can provided the constant
from xbmcplugin, an attribute of SortMethod, or a
string name. For instance, the following method
calls are all equivalent:
* ``plugin.add_sort_method(xbmcplugin.SORT_METHOD_TITLE)``
* ``plugin.add_sort_metohd(SortMethod.TITLE)``
* ``plugin.add_sort_method('title')``
:param label2_mask: A mask pattern for label2. See the `XBMC
documentation
<http://mirrors.xbmc.org/docs/python-docs/xbmcplugin.html#-addSortMethod>`_
for more information.
'''
try:
# Assume it's a string and we need to get the actual int value
sort_method = SortMethod.from_string(sort_method)
except AttributeError:
# sort_method was already an int (or a bad value)
pass
if label2_mask:
xbmcplugin.addSortMethod(self.handle, sort_method, label2_mask)
else:
xbmcplugin.addSortMethod(self.handle, sort_method) | A wrapper for `xbmcplugin.addSortMethod()
<http://mirrors.xbmc.org/docs/python-docs/xbmcplugin.html#-addSortMethod>`_.
You can use ``dir(xbmcswift2.SortMethod)`` to list all available sort
methods.
:param sort_method: A valid sort method. You can provided the constant
from xbmcplugin, an attribute of SortMethod, or a
string name. For instance, the following method
calls are all equivalent:
* ``plugin.add_sort_method(xbmcplugin.SORT_METHOD_TITLE)``
* ``plugin.add_sort_metohd(SortMethod.TITLE)``
* ``plugin.add_sort_method('title')``
:param label2_mask: A mask pattern for label2. See the `XBMC
documentation
<http://mirrors.xbmc.org/docs/python-docs/xbmcplugin.html#-addSortMethod>`_
for more information. | entailment |
def finish(self, items=None, sort_methods=None, succeeded=True,
update_listing=False, cache_to_disc=True, view_mode=None):
'''Adds the provided items to the XBMC interface.
:param items: an iterable of items where each item is either a
dictionary with keys/values suitable for passing to
:meth:`xbmcswift2.ListItem.from_dict` or an instance of
:class:`xbmcswift2.ListItem`.
:param sort_methods: a list of valid XBMC sort_methods. Each item in
the list can either be a sort method or a tuple of
``sort_method, label2_mask``. See
:meth:`add_sort_method` for
more detail concerning valid sort_methods.
Example call with sort_methods::
sort_methods = ['label', 'title', ('date', '%D')]
plugin.finish(items, sort_methods=sort_methods)
:param view_mode: can either be an integer (or parseable integer
string) corresponding to a view_mode or the name of a type of view.
Currrently the only view type supported is 'thumbnail'.
:returns: a list of all ListItems added to the XBMC interface.
'''
# If we have any items, add them. Items are optional here.
if items:
self.add_items(items)
if sort_methods:
for sort_method in sort_methods:
if not isinstance(sort_method, basestring) and hasattr(sort_method, '__len__'):
self.add_sort_method(*sort_method)
else:
self.add_sort_method(sort_method)
# Attempt to set a view_mode if given
if view_mode is not None:
# First check if we were given an integer or parseable integer
try:
view_mode_id = int(view_mode)
except ValueError:
# Attempt to lookup a view mode
view_mode_id = self.get_view_mode_id(view_mode)
if view_mode_id is not None:
self.set_view_mode(view_mode_id)
# Finalize the directory items
self.end_of_directory(succeeded, update_listing, cache_to_disc)
# Return the cached list of all the list items that were added
return self.added_items | Adds the provided items to the XBMC interface.
:param items: an iterable of items where each item is either a
dictionary with keys/values suitable for passing to
:meth:`xbmcswift2.ListItem.from_dict` or an instance of
:class:`xbmcswift2.ListItem`.
:param sort_methods: a list of valid XBMC sort_methods. Each item in
the list can either be a sort method or a tuple of
``sort_method, label2_mask``. See
:meth:`add_sort_method` for
more detail concerning valid sort_methods.
Example call with sort_methods::
sort_methods = ['label', 'title', ('date', '%D')]
plugin.finish(items, sort_methods=sort_methods)
:param view_mode: can either be an integer (or parseable integer
string) corresponding to a view_mode or the name of a type of view.
Currrently the only view type supported is 'thumbnail'.
:returns: a list of all ListItems added to the XBMC interface. | entailment |
def register_cleanup(cleanup):
"""Register a cleanup function to be called at the end of every validation
task. Takes either a callable (including a class with a __call_ method),
or a class with a `cleanup` class method."""
if not callable(cleanup):
# Allow decorating a class with a `cleanup` classm ethod.
cleanup = cleanup.cleanup
CLEANUP_FUNCTIONS.append(cleanup.cleanup)
return cleanup | Register a cleanup function to be called at the end of every validation
task. Takes either a callable (including a class with a __call_ method),
or a class with a `cleanup` class method. | entailment |
def version_range(guid, version, before=None, app_versions=None):
"""Returns all values after (and including) `version` for the app `guid`"""
if app_versions is None:
app_versions = validator.constants.APPROVED_APPLICATIONS
app_key = None
# Support for shorthand instead of full GUIDs.
for app_guid, app_name in APPLICATIONS.items():
if app_name == guid:
guid = app_guid
break
for key in app_versions.keys():
if app_versions[key]['guid'] == guid:
app_key = key
break
if not app_key or version not in app_versions[app_key]['versions']:
raise Exception('Bad GUID or version provided for version range: %s'
% version)
all_versions = app_versions[app_key]['versions']
version_pos = all_versions.index(version)
before_pos = None
if before is not None and before in all_versions:
before_pos = all_versions.index(before)
return all_versions[version_pos:before_pos] | Returns all values after (and including) `version` for the app `guid` | entailment |
def match(self, path):
'''Attempts to match a url to the given path. If successful, a tuple is
returned. The first item is the matchd function and the second item is
a dictionary containing items to be passed to the function parsed from
the provided path.
If the provided path does not match this url rule then a
NotFoundException is raised.
'''
m = self._regex.search(path)
if not m:
raise NotFoundException
# urlunencode the values
items = dict((key, unquote_plus(val))
for key, val in m.groupdict().items())
# unpickle any items if present
items = unpickle_dict(items)
# We need to update our dictionary with default values provided in
# options if the keys don't already exist.
[items.setdefault(key, val) for key, val in self._options.items()]
return self._view_func, items | Attempts to match a url to the given path. If successful, a tuple is
returned. The first item is the matchd function and the second item is
a dictionary containing items to be passed to the function parsed from
the provided path.
If the provided path does not match this url rule then a
NotFoundException is raised. | entailment |
def _make_path(self, items):
'''Returns a relative path for the given dictionary of items.
Uses this url rule's url pattern and replaces instances of <var_name>
with the appropriate value from the items dict.
'''
for key, val in items.items():
if not isinstance(val, basestring):
raise TypeError, ('Value "%s" for key "%s" must be an instance'
' of basestring' % (val, key))
items[key] = quote_plus(val)
try:
path = self._url_format.format(**items)
except AttributeError:
# Old version of python
path = self._url_format
for key, val in items.items():
path = path.replace('{%s}' % key, val)
return path | Returns a relative path for the given dictionary of items.
Uses this url rule's url pattern and replaces instances of <var_name>
with the appropriate value from the items dict. | entailment |
def make_path_qs(self, items):
'''Returns a relative path complete with query string for the given
dictionary of items.
Any items with keys matching this rule's url pattern will be inserted
into the path. Any remaining items will be appended as query string
parameters.
All items will be urlencoded. Any items which are not instances of
basestring, or int/long will be pickled before being urlencoded.
.. warning:: The pickling of items only works for key/value pairs which
will be in the query string. This behavior should only be
used for the simplest of python objects. It causes the
URL to get very lengthy (and unreadable) and XBMC has a
hard limit on URL length. See the caching section if you
need to persist a large amount of data between requests.
'''
# Convert any ints and longs to strings
for key, val in items.items():
if isinstance(val, (int, long)):
items[key] = str(val)
# First use our defaults passed when registering the rule
url_items = dict((key, val) for key, val in self._options.items()
if key in self._keywords)
# Now update with any items explicitly passed to url_for
url_items.update((key, val) for key, val in items.items()
if key in self._keywords)
# Create the path
path = self._make_path(url_items)
# Extra arguments get tacked on to the query string
qs_items = dict((key, val) for key, val in items.items()
if key not in self._keywords)
qs = self._make_qs(qs_items)
if qs:
return '?'.join([path, qs])
return path | Returns a relative path complete with query string for the given
dictionary of items.
Any items with keys matching this rule's url pattern will be inserted
into the path. Any remaining items will be appended as query string
parameters.
All items will be urlencoded. Any items which are not instances of
basestring, or int/long will be pickled before being urlencoded.
.. warning:: The pickling of items only works for key/value pairs which
will be in the query string. This behavior should only be
used for the simplest of python objects. It causes the
URL to get very lengthy (and unreadable) and XBMC has a
hard limit on URL length. See the caching section if you
need to persist a large amount of data between requests. | entailment |
def sync(self):
'''Write the dict to disk'''
if self.flag == 'r':
return
filename = self.filename
tempname = filename + '.tmp'
fileobj = open(tempname, 'wb' if self.file_format == 'pickle' else 'w')
try:
self.dump(fileobj)
except Exception:
os.remove(tempname)
raise
finally:
fileobj.close()
shutil.move(tempname, self.filename) # atomic commit
if self.mode is not None:
os.chmod(self.filename, self.mode) | Write the dict to disk | entailment |
def dump(self, fileobj):
'''Handles the writing of the dict to the file object'''
if self.file_format == 'csv':
csv.writer(fileobj).writerows(self.raw_dict().items())
elif self.file_format == 'json':
json.dump(self.raw_dict(), fileobj, separators=(',', ':'))
elif self.file_format == 'pickle':
pickle.dump(dict(self.raw_dict()), fileobj, 2)
else:
raise NotImplementedError('Unknown format: ' +
repr(self.file_format)) | Handles the writing of the dict to the file object | entailment |
def load(self, fileobj):
'''Load the dict from the file object'''
# try formats from most restrictive to least restrictive
for loader in (pickle.load, json.load, csv.reader):
fileobj.seek(0)
try:
return self.initial_update(loader(fileobj))
except Exception as e:
pass
raise ValueError('File not in a supported format') | Load the dict from the file object | entailment |
def initial_update(self, mapping):
'''Initially fills the underlying dictionary with keys, values and
timestamps.
'''
for key, val in mapping.items():
_, timestamp = val
if not self.TTL or (datetime.utcnow() -
datetime.utcfromtimestamp(timestamp) < self.TTL):
self.__setitem__(key, val, raw=True) | Initially fills the underlying dictionary with keys, values and
timestamps. | entailment |
def setup_log(name):
'''Returns a logging instance for the provided name. The returned
object is an instance of logging.Logger. Logged messages will be
printed to stderr when running in the CLI, or forwarded to XBMC's
log when running in XBMC mode.
'''
_log = logging.getLogger(name)
_log.setLevel(GLOBAL_LOG_LEVEL)
handler = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s - %(levelname)s - [%(name)s] %(message)s')
handler.setFormatter(formatter)
_log.addHandler(handler)
_log.addFilter(XBMCFilter('[%s] ' % name))
return _log | Returns a logging instance for the provided name. The returned
object is an instance of logging.Logger. Logged messages will be
printed to stderr when running in the CLI, or forwarded to XBMC's
log when running in XBMC mode. | entailment |
def filter(self, record):
'''Returns True for all records if running in the CLI, else returns
True.
When running inside XBMC it calls the xbmc.log() method and prevents
the message from being double printed to STDOUT.
'''
# When running in XBMC, any logged statements will be double printed
# since we are calling xbmc.log() explicitly. Therefore we return False
# so every log message is filtered out and not printed again.
if CLI_MODE:
return True
else:
# Must not be imported until here because of import order issues
# when running in CLI
from xbmcswift2 import xbmc
xbmc_level = XBMCFilter.xbmc_levels.get(
XBMCFilter.python_to_xbmc.get(record.levelname))
xbmc.log('%s%s' % (self.prefix, record.getMessage()), xbmc_level)
return False | Returns True for all records if running in the CLI, else returns
True.
When running inside XBMC it calls the xbmc.log() method and prevents
the message from being double printed to STDOUT. | entailment |
def validate_name(err, value, source):
'Tests a manifest name value for trademarks.'
ff_pattern = re.compile('(mozilla|firefox)', re.I)
err.metadata['name'] = value
if ff_pattern.search(value):
err.warning(
('metadata_helpers', '_test_name', 'trademark'),
'Add-on has potentially illegal name.',
'Add-on names cannot contain the Mozilla or Firefox '
'trademarks. These names should not be contained in add-on '
'names if at all possible.',
source) | Tests a manifest name value for trademarks. | entailment |
def validate_id(err, value, source):
'Tests a manifest UUID value'
field_name = '<em:id>' if source == 'install.rdf' else 'id'
id_pattern = re.compile(
'('
# UUID format.
'\{[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}\}'
'|'
# "email" format.
'[a-z0-9-\.\+_]*\@[a-z0-9-\._]+'
')',
re.I)
err.metadata['id'] = value
# Must be a valid UUID string.
if not id_pattern.match(value):
err.error(
('metadata_helpers', '_test_id', 'invalid'),
'The value of {name} is invalid'.format(name=field_name),
['The values supplied for {name} in the {source} file is not a '
'valid UUID string or email address.'.format(
name=field_name, source=source),
'For help, please consult: '
'https://developer.mozilla.org/en/install_manifests#id'],
source) | Tests a manifest UUID value | entailment |
def validate_version(err, value, source):
'Tests a manifest version number'
field_name = '<em:version>' if source == 'install.rdf' else 'version'
err.metadata['version'] = value
# May not be longer than 32 characters
if len(value) > 32:
err.error(
('metadata_helpers', '_test_version', 'too_long'),
'The value of {name} is too long'.format(name=field_name),
'Values supplied for {name} in the {source} file must be 32 '
'characters or less.'.format(name=field_name, source=source),
source)
# Must be a valid version number.
if not VERSION_PATTERN.match(value):
err.error(
('metadata_helpers', '_test_version', 'invalid_format'),
'The value of {name} is invalid'.format(name=field_name),
'The values supplied for version in the {source} file is not a '
'valid version string. It can only contain letters, numbers, and '
'the symbols +*.-_.'.format(name=field_name, source=source),
source) | Tests a manifest version number | entailment |
def get_device(self, pin=None):
""" Query the status of a specific pin (or all configured pins if pin is ommitted) """
url = self.base_url + '/device'
try:
r = requests.get(url, params={'pin': pin}, timeout=10)
return r.json()
except RequestException as err:
raise Client.ClientError(err) | Query the status of a specific pin (or all configured pins if pin is ommitted) | entailment |
def get_status(self):
""" Query the device status. Returns JSON of the device internal state """
url = self.base_url + '/status'
try:
r = requests.get(url, timeout=10)
return r.json()
except RequestException as err:
raise Client.ClientError(err) | Query the device status. Returns JSON of the device internal state | entailment |
def put_device(self, pin, state, momentary=None, times=None, pause=None):
""" Actuate a device pin """
url = self.base_url + '/device'
payload = {
"pin": pin,
"state": state
}
if momentary is not None:
payload["momentary"] = momentary
if times is not None:
payload["times"] = times
if pause is not None:
payload["pause"] = pause
try:
r = requests.put(url, json=payload, timeout=10)
return r.json()
except RequestException as err:
raise Client.ClientError(err) | Actuate a device pin | entailment |
def put_settings(self, sensors=[], actuators=[], auth_token=None,
endpoint=None, blink=None, discovery=None,
dht_sensors=[], ds18b20_sensors=[]):
""" Sync settings to the Konnected device """
url = self.base_url + '/settings'
payload = {
"sensors": sensors,
"actuators": actuators,
"dht_sensors": dht_sensors,
"ds18b20_sensors": ds18b20_sensors,
"token": auth_token,
"apiUrl": endpoint
}
if blink is not None:
payload['blink'] = blink
if discovery is not None:
payload['discovery'] = discovery
try:
r = requests.put(url, json=payload, timeout=10)
return r.ok
except RequestException as err:
raise Client.ClientError(err) | Sync settings to the Konnected device | entailment |
def parse_mime_type(mime_type):
"""Parses a mime-type into its component parts.
Carves up a mime-type and returns a tuple of the (type, subtype, params)
where 'params' is a dictionary of all the parameters for the media range.
For example, the media range 'application/xhtml;q=0.5' would get parsed
into:
('application', 'xhtml', {'q', '0.5'})
:rtype: (str,str,dict)
"""
full_type, params = cgi.parse_header(mime_type)
# Java URLConnection class sends an Accept header that includes a
# single '*'. Turn it into a legal wildcard.
if full_type == '*':
full_type = '*/*'
type_parts = full_type.split('/') if '/' in full_type else None
if not type_parts or len(type_parts) > 2:
raise MimeTypeParseException(
"Can't parse type \"{}\"".format(full_type))
(type, subtype) = type_parts
return (type.strip(), subtype.strip(), params) | Parses a mime-type into its component parts.
Carves up a mime-type and returns a tuple of the (type, subtype, params)
where 'params' is a dictionary of all the parameters for the media range.
For example, the media range 'application/xhtml;q=0.5' would get parsed
into:
('application', 'xhtml', {'q', '0.5'})
:rtype: (str,str,dict) | entailment |
def parse_media_range(range):
"""Parse a media-range into its component parts.
Carves up a media range and returns a tuple of the (type, subtype,
params) where 'params' is a dictionary of all the parameters for the media
range. For example, the media range 'application/*;q=0.5' would get parsed
into:
('application', '*', {'q', '0.5'})
In addition this function also guarantees that there is a value for 'q'
in the params dictionary, filling it in with a proper default if
necessary.
:rtype: (str,str,dict)
"""
(type, subtype, params) = parse_mime_type(range)
params.setdefault('q', params.pop('Q', None)) # q is case insensitive
try:
if not params['q'] or not 0 <= float(params['q']) <= 1:
params['q'] = '1'
except ValueError: # from float()
params['q'] = '1'
return (type, subtype, params) | Parse a media-range into its component parts.
Carves up a media range and returns a tuple of the (type, subtype,
params) where 'params' is a dictionary of all the parameters for the media
range. For example, the media range 'application/*;q=0.5' would get parsed
into:
('application', '*', {'q', '0.5'})
In addition this function also guarantees that there is a value for 'q'
in the params dictionary, filling it in with a proper default if
necessary.
:rtype: (str,str,dict) | entailment |
def quality_and_fitness_parsed(mime_type, parsed_ranges):
"""Find the best match for a mime-type amongst parsed media-ranges.
Find the best match for a given mime-type against a list of media_ranges
that have already been parsed by parse_media_range(). Returns a tuple of
the fitness value and the value of the 'q' quality parameter of the best
match, or (-1, 0) if no match was found. Just as for quality_parsed(),
'parsed_ranges' must be a list of parsed media ranges.
:rtype: (float,int)
"""
best_fitness = -1
best_fit_q = 0
(target_type, target_subtype, target_params) = \
parse_media_range(mime_type)
for (type, subtype, params) in parsed_ranges:
# check if the type and the subtype match
type_match = (
type in (target_type, '*') or
target_type == '*'
)
subtype_match = (
subtype in (target_subtype, '*') or
target_subtype == '*'
)
# if they do, assess the "fitness" of this mime_type
if type_match and subtype_match:
# 100 points if the type matches w/o a wildcard
fitness = type == target_type and 100 or 0
# 10 points if the subtype matches w/o a wildcard
fitness += subtype == target_subtype and 10 or 0
# 1 bonus point for each matching param besides "q"
param_matches = sum([
1 for (key, value) in target_params.items()
if key != 'q' and key in params and value == params[key]
])
fitness += param_matches
# finally, add the target's "q" param (between 0 and 1)
fitness += float(target_params.get('q', 1))
if fitness > best_fitness:
best_fitness = fitness
best_fit_q = params['q']
return float(best_fit_q), best_fitness | Find the best match for a mime-type amongst parsed media-ranges.
Find the best match for a given mime-type against a list of media_ranges
that have already been parsed by parse_media_range(). Returns a tuple of
the fitness value and the value of the 'q' quality parameter of the best
match, or (-1, 0) if no match was found. Just as for quality_parsed(),
'parsed_ranges' must be a list of parsed media ranges.
:rtype: (float,int) | entailment |
def quality(mime_type, ranges):
"""Return the quality ('q') of a mime-type against a list of media-ranges.
Returns the quality 'q' of a mime-type when compared against the
media-ranges in ranges. For example:
>>> quality('text/html','text/*;q=0.3, text/html;q=0.7,
text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5')
0.7
:rtype: float
"""
parsed_ranges = [parse_media_range(r) for r in ranges.split(',')]
return quality_parsed(mime_type, parsed_ranges) | Return the quality ('q') of a mime-type against a list of media-ranges.
Returns the quality 'q' of a mime-type when compared against the
media-ranges in ranges. For example:
>>> quality('text/html','text/*;q=0.3, text/html;q=0.7,
text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5')
0.7
:rtype: float | entailment |
def best_match(supported, header):
"""Return mime-type with the highest quality ('q') from list of candidates.
Takes a list of supported mime-types and finds the best match for all the
media-ranges listed in header. The value of header must be a string that
conforms to the format of the HTTP Accept: header. The value of 'supported'
is a list of mime-types. The list of supported mime-types should be sorted
in order of increasing desirability, in case of a situation where there is
a tie.
>>> best_match(['application/xbel+xml', 'text/xml'],
'text/*;q=0.5,*/*; q=0.1')
'text/xml'
:rtype: str
"""
split_header = _filter_blank(header.split(','))
parsed_header = [parse_media_range(r) for r in split_header]
weighted_matches = []
pos = 0
for mime_type in supported:
weighted_matches.append((
quality_and_fitness_parsed(mime_type, parsed_header),
pos,
mime_type
))
pos += 1
weighted_matches.sort()
return weighted_matches[-1][0][0] and weighted_matches[-1][2] or '' | Return mime-type with the highest quality ('q') from list of candidates.
Takes a list of supported mime-types and finds the best match for all the
media-ranges listed in header. The value of header must be a string that
conforms to the format of the HTTP Accept: header. The value of 'supported'
is a list of mime-types. The list of supported mime-types should be sorted
in order of increasing desirability, in case of a situation where there is
a tie.
>>> best_match(['application/xbel+xml', 'text/xml'],
'text/*;q=0.5,*/*; q=0.1')
'text/xml'
:rtype: str | entailment |
def makeXsl(filename):
""" Helper that creates a XSLT stylesheet """
pkg = 'cnxml2html'
package = ''.join(['.' + x for x in __name__.split('.')[:-1]])[1:]
if package != '':
pkg = package + '.' + pkg
path = pkg_resources.resource_filename(pkg, filename)
xml = etree.parse(path)
return etree.XSLT(xml) | Helper that creates a XSLT stylesheet | entailment |
def transform_collxml(collxml_file):
""" Given a collxml file (collection.xml) this returns an HTML version of it
(including "include" anchor links to the modules) """
xml = etree.parse(collxml_file)
xslt = makeXsl('collxml2xhtml.xsl')
xml = xslt(xml)
return xml | Given a collxml file (collection.xml) this returns an HTML version of it
(including "include" anchor links to the modules) | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.