code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
'''Attempts to extract a module name for the given addon's addon.xml file. Looks for the 'xbmc.python.pluginsource' extension node and returns the addon's filename without the .py suffix. ''' try: xml = ET.parse(addonxml_filename).getroot() except IOError: sys.exit('Cannot find a...
def get_addon_module_name(addonxml_filename)
Attempts to extract a module name for the given addon's addon.xml file. Looks for the 'xbmc.python.pluginsource' extension node and returns the addon's filename without the .py suffix.
4.744654
2.749318
1.725756
'''Patches a few attributes of a plugin instance to enable a new call to plugin.run() ''' if handle is None: handle = plugin.request.handle patch_sysargv(path, handle) plugin._end_of_directory = False
def patch_plugin(plugin, path, handle=None)
Patches a few attributes of a plugin instance to enable a new call to plugin.run()
13.890393
6.439269
2.157138
'''A run mode for the CLI that runs the plugin once and exits.''' plugin.clear_added_items() items = plugin.run() # if update_listing=True, we need to remove the last url from the parent # stack if parent_stack and plugin._update_listing: del parent_stack[-1] # if we have parent it...
def once(plugin, parent_stack=None)
A run mode for the CLI that runs the plugin once and exits.
8.654636
6.668912
1.297758
'''A run mode for the CLI that runs the plugin in a loop based on user input. ''' items = [item for item in once(plugin) if not item.get_played()] parent_stack = [] # Keep track of parents so we can have a '..' option selected_item = get_user_choice(items) while selected_item is not None: ...
def interactive(plugin)
A run mode for the CLI that runs the plugin in a loop based on user input.
5.836482
4.76454
1.224983
'''Performs a breadth-first crawl of all possible routes from the starting path. Will only visit a URL once, even if it is referenced multiple times in a plugin. Requires user interaction in between each fetch. ''' # TODO: use OrderedSet? paths_visited = set() paths_to_visit = set(item.g...
def crawl(plugin)
Performs a breadth-first crawl of all possible routes from the starting path. Will only visit a URL once, even if it is referenced multiple times in a plugin. Requires user interaction in between each fetch.
6.727301
3.735661
1.800833
'''The run method for the 'run' command. Executes a plugin from the command line. ''' setup_options(opts) mode = Modes.ONCE if len(args) > 0 and hasattr(Modes, args[0].upper()): _mode = args.pop(0).upper() mode = getattr(Modes, _mode) url...
def run(opts, args)
The run method for the 'run' command. Executes a plugin from the command line.
5.329247
4.002407
1.331511
'''Attempts to import a plugin's source code and find an instance of :class:`~xbmcswif2.Plugin`. Returns an instance of PluginManager if succesful. ''' cwd = os.getcwd() sys.path.insert(0, cwd) module_name = get_addon_module_name(os.path.join(cwd, 'addon.xml')) ...
def load_plugin_from_addonxml(cls, mode, url)
Attempts to import a plugin's source code and find an instance of :class:`~xbmcswif2.Plugin`. Returns an instance of PluginManager if succesful.
5.260783
2.857386
1.841118
'''This method runs the the plugin in the appropriate mode parsed from the command line options. ''' handle = 0 handlers = { Modes.ONCE: once, Modes.CRAWL: crawl, Modes.INTERACTIVE: interactive, } handler = handlers[self.mode] ...
def run(self)
This method runs the the plugin in the appropriate mode parsed from the command line options.
10.208924
5.991771
1.703824
modules = [line.strip() for line in dist.get_metadata_lines('top_level.txt') if line.strip() and not line.strip().startswith('#')] if not modules: print('No modules are listed in top_level.txt') print('Try running python setup.py egg_info to regenera...
def _setup_config(self, dist, filename, section, vars, verbosity)
Called to setup an application, given its configuration file/directory. The default implementation calls ``package.websetup.setup_config(command, filename, section, vars)`` or ``package.websetup.setup_app(command, config, vars)`` With ``setup_app`` the ``config`` object...
2.604211
2.550554
1.021037
mod = __import__(s) parts = s.split('.') for part in parts[1:]: mod = getattr(mod, part) return mod
def _import_module(self, s)
Import a module.
2.113903
2.089947
1.011463
params = self._get_params(input, kwargs) try: reply = yield from self.session.get( self.url, params=params, timeout=self.timeout) except asyncio.TimeoutError: raise Timeout(self.timeout) else: try: data = yield ...
def say(self, input=None, **kwargs)
Talk to Cleverbot. Arguments: input: The input argument is what you want to say to Cleverbot, such as "hello". tweak1-3: Changes Cleverbot's mood. **kwargs: Keyword arguments to update the request parameters with. Returns: Cleverbot's rep...
2.817594
2.618546
1.076015
convo = Conversation(self, **kwargs) super().conversation(name, convo) return convo
def conversation(self, name=None, **kwargs)
Make a new conversation. Arguments: name: The key for the dictionary the conversation will be stored as in conversations. If None the conversation will be stored as a list instead. Mixing both types results in an error. **kwargs: Keyword arguments to pass...
4.473271
13.643942
0.327858
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__), ...
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`: Pat...
3.836136
3.930333
0.976033
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] ...
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".
4.661848
4.286456
1.087576
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 ret...
def drop_message(self, message)
Drop the given message object from the appropriate message list. Returns True if the message was found, otherwise False.
5.226742
4.337921
1.204896
'Updates the tier and ending tier' self.tier = tier if tier > self.ending_tier: self.ending_tier = tier
def set_tier(self, tier)
Updates the tier and ending tier
7.503585
4.334888
1.730976
'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 ...
def _save_message(self, stack, type_, message, context=None, from_merge=False)
Stores a message in the appropriate message stack.
4.039838
3.961154
1.019864
return bool(self.errors) or (fail_on_warnings and bool(self.warnings))
def failed(self, fail_on_warnings=True)
Returns a boolean value describing whether the validation succeeded or not.
5.384885
4.767745
1.129441
'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
def get_resource(self, name)
Retrieves an object that has been stored by another test.
5.547109
3.607015
1.537867
'Saves an object such that it can be used by other tests.' if pushable: self.pushable_resources[name] = resource else: self.resources[name] = resource
def save_resource(self, name, resource, pushable=False)
Saves an object such that it can be used by other tests.
5.910693
2.884729
2.048959
'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...
def push_state(self, new_file='')
Saves the current error state to parse subpackages
7.625072
5.519205
1.381553
'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 ...
def pop_state(self)
Retrieves the last saved state and restores it.
9.575491
8.853648
1.081531
'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': typ...
def render_json(self)
Returns a JSON summary of the validation operation.
3.412158
3.155785
1.081239
'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', ...
def print_summary(self, verbose=False, no_color=False)
Prints a summary of the validation process so far.
3.923033
3.807054
1.030464
'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)
def _flatten_list(self, data)
Flattens nested lists into strings.
3.159049
2.802757
1.127122
'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. ...
def _print_message(self, prefix, message, verbose=True)
Prints a message and takes care of all sorts of nasty code
4.233884
4.016956
1.054003
# 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, ...
def supports_version(self, guid_set)
Returns whether a GUID set in for_appversions format is compatbile with the current supported applications list.
10.381842
10.676829
0.972371
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_versi...
def _compare_version(self, requirements, support)
Return whether there is an intersection between a support applications GUID set and a set of supported applications.
8.528639
6.84468
1.246025
stacks = [self.errors, self.warnings, self.notices] for stack in stacks: for message in stack: if message['tier'] > ending_tier: stack.remove(message)
def discard_unused_messages(self, ending_tier)
Delete messages from errors, warnings, and notices whose tier is greater than the ending tier.
3.923726
2.618124
1.498679
for tweak in ('tweak1', 'tweak2', 'tweak3'): del state[0][tweak] for convo in state[1]: if tweak in convo: del convo[tweak] return state
def migrator(state)
Tweaks will be lost for Cleverbot and its conversations.
5.897147
4.630193
1.273629
cleverbot_kwargs, convos_kwargs = state cb = Cleverbot(**cleverbot_kwargs) for convo_kwargs in convos_kwargs: cb.conversation(**convo_kwargs) return cb
def migrator(state)
Nameless conversations will be lost.
5.033643
4.946023
1.017715
self._uid = uid self._brain = None self._catalog = None self._instance = None
def init_with_uid(self, uid)
Initialize with an UID
8.364645
8.199104
1.02019
self._uid = api.get_uid(brain) self._brain = brain self._catalog = self.get_catalog_for(brain) self._instance = None
def init_with_brain(self, brain)
Initialize with a catalog brain
6.929822
5.847543
1.185083
self._uid = api.get_uid(instance) self._brain = None self._catalog = self.get_catalog_for(instance) self._instance = instance
def init_with_instance(self, instance)
Initialize with an instance object
7.983477
8.413658
0.948871
# 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 saf...
def process_value(self, value)
Process publication value
3.469774
3.41885
1.014895
if self._instance is None: logger.debug("SuperModel::instance: *Wakup object*") self._instance = api.get_object(self.brain) return self._instance
def instance(self)
Content instance of the wrapped object
14.848033
14.988792
0.990609
if self._brain is None: logger.debug("SuperModel::brain: *Fetch catalog brain*") self._brain = self.get_brain_by_uid(self.uid) return self._brain
def brain(self)
Catalog brain of the wrapped object
10.814771
7.567196
1.429165
if self._catalog is None: logger.debug("SuperModel::catalog: *Fetch catalog*") self._catalog = self.get_catalog_for(self.brain) return self._catalog
def catalog(self)
Primary registered catalog for the wrapped portal type
9.607112
9.175048
1.047091
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]
def get_catalog_for(self, brain_or_object)
Return the primary catalog for the given brain or object
4.470785
4.137592
1.080528
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...
def get_brain_by_uid(self, uid)
Lookup brain from the right catalog
3.889234
3.720964
1.045222
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
def to_super_model(self, thing)
Wraps an object into a Super Model
6.131414
5.781046
1.060606
# 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"): ret...
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.)
3.468447
3.531318
0.982196
if converter is None: converter = self.stringify out = dict() for k, v in self.iteritems(): out[k] = converter(v) return out
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`.
3.372566
2.507774
1.344845
'''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, ...
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.
4.617729
2.768291
1.668079
'''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 ar...
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 names...
10.84547
3.605396
3.008122
'''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' % ...
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.
5.549826
2.959327
1.875368
parser = argparse.ArgumentParser(description=self.get_description(), prog=prog_name, add_help=False) return parser
def get_parser(self, prog_name)
Override to add command options.
3.069165
2.461837
1.246697
'''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)
def validate_pluginid(value)
Returns True if the provided value is a valid pluglin id
6.617564
3.445101
1.920862
'''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 err...
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_mess...
5.384754
1.806213
2.98124
'''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) ...
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.
3.53182
2.398779
1.472341
'''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 repla...
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.
6.501399
3.92379
1.656918
'''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.' ...
def create_new_project()
Creates a new XBMC Addon directory based on user input
4.047184
3.790722
1.067655
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 ...
def get_applications(self)
Return the list of supported applications.
3.190546
3.006815
1.061105
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 ...
def get_value(self, subject=None, predicate=None, object_=None)
Returns the first triple value matching the given subject, predicate, and/or object
3.230341
3.293161
0.980924
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']
def get_objects(self, subject=None, predicate=None)
Returns a generator of objects that correspond to the specified subjects and predicates.
3.808081
3.748167
1.015985
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 tri...
def get_triples(self, subject=None, predicate=None, object_=None)
Returns triples that correspond to the specified subject, predicates, and objects.
2.095525
2.119704
0.988593
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 = '/'...
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.
4.745754
4.738216
1.001591
# 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.ge...
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.
4.036162
3.507462
1.150736
# 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('/'): ...
def _url_chunk_join(self, *args)
Join the arguments together to form a predictable URL chunk.
3.642572
3.681415
0.989449
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) ...
def run(self, argv)
Application entry point
3.574106
3.498293
1.021671
'Returns a URIRef object for use with the RDF document.' if namespace is None: namespace = self.namespace return URIRef('%s#%s' % (namespace, element))
def uri(self, element, namespace=None)
Returns a URIRef object for use with the RDF document.
7.372789
3.286269
2.243514
'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()
def get_root_subject(self)
Returns the BNode which describes the topmost subject of the graph.
7.676083
4.687478
1.637572
# 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]
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.
7.594203
7.034161
1.079618
# Get the result of the search results = self.rdf.objects(subject, predicate) return list(results)
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.
7.342117
7.333695
1.001148
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....
def get_applications(self)
Return the list of supported applications.
3.998115
3.896483
1.026083
'''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_men...
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.
3.532891
2.91223
1.213122
'''Sets the listitem's icon image''' self._icon = icon return self._listitem.setIconImage(icon)
def set_icon(self, icon)
Sets the listitem's icon image
10.72325
7.327347
1.463456
'''Sets the listitem's thumbnail image''' self._thumbnail = thumbnail return self._listitem.setThumbnailImage(thumbnail)
def set_thumbnail(self, thumbnail)
Sets the listitem's thumbnail image
8.264878
6.054132
1.365163
'''Sets the listitem's path''' self._path = path return self._listitem.setPath(path)
def set_path(self, path)
Sets the listitem's path
8.243668
6.357688
1.296645
'''Sets the listitem's playable flag''' value = 'false' if is_playable: value = 'true' self.set_property('isPlayable', value) self.is_folder = not is_playable
def set_is_playable(self, is_playable)
Sets the listitem's playable flag
5.229671
4.255093
1.229038
'''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...
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.
3.587532
2.080031
1.724749
'''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 :me...
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:`xbmcswi...
4.04949
2.650937
1.527569
'''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.startswit...
def list_storages(self)
Returns a list of existing stores. The returned names can then be used to call get_storage().
11.109426
6.224219
1.784871
'''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. ...
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. .....
4.385993
1.778269
2.46644
'''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(str...
def get_string(self, stringid)
Returns the localized string from strings.xml for the given stringid.
2.78004
2.132137
1.303875
'''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:: I...
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 sugges...
5.056269
2.003961
2.523138
'''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) ...
def add_to_playlist(self, items, playlist='video')
Adds the provided list of items to the specified playlist. Available playlists include *video* and *music*.
4.406037
3.961854
1.112115
'''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 vi...
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.
5.566422
2.111754
2.635923
'''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 ...
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 ...
4.138551
1.469125
2.817018
'''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 notif...
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.
4.383053
2.212689
1.980872
'''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 ...
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.
4.835734
2.854983
1.693788
'''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. ...
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.
6.523524
3.547236
1.839044
'''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 ...
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_r...
7.33631
2.646332
2.772256
'''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 i...
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 eith...
5.793044
2.759068
2.099638
'''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 sel...
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.
5.706364
2.660056
2.145204
'''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 ...
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 ...
3.593864
1.513616
2.374357
'''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 s...
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...
4.037362
1.729414
2.334527
if not callable(cleanup): # Allow decorating a class with a `cleanup` classm ethod. cleanup = cleanup.cleanup CLEANUP_FUNCTIONS.append(cleanup.cleanup) return cleanup
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.
11.563492
7.415338
1.559402
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_ve...
def version_range(guid, version, before=None, app_versions=None)
Returns all values after (and including) `version` for the app `guid`
3.072273
3.127026
0.98249
'''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 r...
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 ...
6.234364
3.118952
1.998865
'''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): ...
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.
4.116347
2.37791
1.731078
'''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. A...
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 wh...
5.396435
1.867378
2.889846
'''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....
def sync(self)
Write the dict to disk
3.642548
3.416384
1.0662
'''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 == 'pick...
def dump(self, fileobj)
Handles the writing of the dict to the file object
2.778902
2.47367
1.123392
'''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: ...
def load(self, fileobj)
Load the dict from the file object
5.74968
5.81861
0.988154
'''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.__...
def initial_update(self, mapping)
Initially fills the underlying dictionary with keys, values and timestamps.
7.62337
4.259358
1.789793
'''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_LEVE...
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.
4.023236
1.990185
2.021538
'''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 ...
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.
7.805517
4.290976
1.819054
'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.', ...
def validate_name(err, value, source)
Tests a manifest name value for trademarks.
12.894266
8.83562
1.45935
'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-\._]+' ')', ...
def validate_id(err, value, source)
Tests a manifest UUID value
5.382164
5.064794
1.062662