output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def get_fixed_argv(self): # pragma: no cover
"""Get proper arguments for re-running the command.
This is primarily for fixing some issues under Windows.
First, there was a bug in Windows when running an executable
located at a path with a space in it. This has become a
non-iss... | Create a Python 3 function to
get proper arguments for re - running the command. | As a python code expert, you are capable of creating scripts from specifications. |
Returns a dictionary of file information | Can you generate the documentation for the following Python 3 function
def package_contents(self):
'Returns a dictionary of file information'
if self.contents_cache:
return self.contents_cache
# Get a list of ZipInfo objects.
files = self.zf.infolist()
out_files = {... | You are a Python code analyst, evaluating scripts for potential improvements. |
def write(self, name, data):
"""Write a blob of data to the XPI manager."""
if isinstance(data, StringIO):
self.zf.writestr(name, data.getvalue())
else:
self.zf.writestr(name, to_utf8(data)) | Write a Python 3 function that can
write a blob of data to the XPI manager. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Write the contents of a file from the disk to the XPI. | Can you generate the documentation for the following Python 3 function
def write_file(self, name, path=None):
if path is None:
path = name
self.zf.write(path, name) | As a Python code analyst, you investigate and solve complex coding mysteries |
def xbmc_url(url, **options):
'''Appends key/val pairs to the end of a URL. Useful for passing arbitrary
HTTP headers to XBMC to be used when fetching a media resource, e.g.
cookies.
'''
optionstring = urllib.urlencode(options)
if optionstring:
return url + '|' + optionstring
return ... | Write a Python 3 function that can
append key - val pairs to the end of a URL. Useful for passing arbitrary HTTP headers to XBMC. | You are a Python code architect, reviewing and designing scalable and efficient code |
def clean_dict(dct):
'''Returns a dict where items with a None value are removed'''
return dict((key, val) for key, val in dct.items() if val is not None) | Create a Python 3 function to
return a dict where items with a None value are removed | You are a Python code analyst, evaluating scripts for potential improvements. |
def pickle_dict(items):
'''Returns a new dictionary where values which aren't instances of
basestring are pickled. Also, a new key '_pickled' contains a comma
separated list of keys corresponding to the pickled values.
'''
ret = {}
pickled_keys = []
for key, val in items.items():
if ... | Write a Python 3 script for
returning a new dictionary where values which aren t instances of basestring are pickled. Also a new key _pickled contains a comma separated list of keys corresponding to the pickled values. Also a new key _pickled contains a comma separated list of keys corresponding to the pickled values. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Takes a dict and unpickles values whose keys are found in
_pickled key. | Explain what the following Python 3 code does
def unpickle_args(items):
'''Takes a dict and unpickles values whose keys are found in
'_pickled' key.
>>> unpickle_args({'_pickled': ['foo']. 'foo': ['I3%0A.']})
{'foo': 3}
'''
# Technically there can be more than one _pickled value. At this point
... | As a python code expert, you are capable of creating scripts from specifications. |
def unpickle_dict(items):
'''Returns a dict pickled with pickle_dict'''
pickled_keys = items.pop('_pickled', '').split(',')
ret = {}
for key, val in items.items():
if key in pickled_keys:
ret[key] = pickle.loads(val)
else:
ret[key] = val
return ret | How would you code a function in Python 3 to
return a dict pickled with pickle_dict | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns the response for the given url. The optional data argument is
passed directly to urlopen. | Here you have a function in Python 3, explain what it does
def download_page(url, data=None):
'''Returns the response for the given url. The optional data argument is
passed directly to urlopen.'''
conn = urllib2.urlopen(url, data)
resp = conn.read()
conn.close()
return resp | You are a Python code architect, reviewing and designing scalable and efficient code |
unquote ( r \ x20def ) -> abc def. | Explain what the following Python 3 code does
def unhex(inp):
'''unquote(r'abc\x20def') -> 'abc def'.'''
res = inp.split(r'\x')
for i in xrange(1, len(res)):
item = res[i]
try:
res[i] = _hextochr[item[:2]] + item[2:]
except KeyError:
res[i] = '%' + item
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Load all the commands from an entrypoint | Given the following Python 3 function, write the documentation
def load_commands(self, namespace):
for ep in pkg_resources.iter_entry_points(namespace):
LOG.debug('found command %r', ep.name)
cmd_name = (ep.name.replace('_', ' ')
if self.convert_underscores
... | As a Python code composer, you craft elegant and concise scripts. |
Given an argument list find a command and
return the processor and any remaining arguments. | Here you have a function in Python 3, explain what it does
def find_command(self, argv):
search_args = argv[:]
name = ''
while search_args:
if search_args[0].startswith('-'):
name = '%s %s' % (name, search_args[0])
raise ValueError('Invalid command %r'... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Setup logging via the logging module s fileConfig function with the specified config_uri. | Here you have a function in Python 3, explain what it does
def setup_logging(config_uri, fileConfig=fileConfig,
configparser=configparser):
"""
Set up logging via the logging module's fileConfig function with the
filename specified via ``config_uri`` (a string in the form
``filename#se... | You are a Python code generator, capable of creating scripts from specifications. |
def prepare_package(err, path, expectation=0, for_appversions=None,
timeout=-1):
"""Prepares a file-based package for validation.
timeout is the number of seconds before validation is aborted.
If timeout is -1 then no timeout checking code will run.
"""
package = None
try:
... | Write a Python 3 script for
preparing a file - based package for validation. | As a Python code analyst, you investigate and solve complex coding mysteries |
Loads the chrome. manifest if it s present | How would you explain what the following Python 3 function does
def populate_chrome_manifest(err, xpi_package):
"Loads the chrome.manifest if it's present"
if 'chrome.manifest' in xpi_package:
chrome_data = xpi_package.read('chrome.manifest')
chrome = ChromeManifest(chrome_data, 'chrome.manifes... | You are a Python code analyst, evaluating scripts for potential improvements. |
Detects the type of add - on being validated based on the install. rdf file extension and other properties. | How would you explain what the following Python 3 function does
def detect_type(err, install_rdf=None, xpi_package=None):
# The types in the install.rdf don't pair up 1:1 with the type
# system that we're using for expectations and the like. This is
# to help translate between the two.
translated_types... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def detect_opensearch(err, package, listed=False):
'Detect, parse, and validate an OpenSearch provider'
# Parse the file.
try:
# Check if it is a file object.
if hasattr(package, 'read'):
srch_prov = parse(package)
else:
# It's not a file object; open it (the... | Implement a Python 3 function for
detecting parse and validate an OpenSearch provider | You are a Python code architect, reviewing and designing scalable and efficient code |
Copy a directory from source to dest. | Can you tell what is the following Python 3 function doing
def copy_dir(source, dest, vars, verbosity=1, simulate=False, indent=0,
sub_vars=True, interactive=False, overwrite=True,
template_renderer=None, out_=sys.stdout):
"""
Copies the ``source`` directory to the ``dest`` directory.
... | As a Python code composer, you craft elegant and concise scripts. |
def should_skip_file(name):
"""
Checks if a file should be skipped based on its name.
If it should be skipped, returns the reason, otherwise returns
None.
"""
if name.startswith('.'):
return 'Skipping hidden file %(filename)s'
if name.endswith('~') or name.endswith('.bak'):
... | How would you code a function in Python 3 to
check if a file should be skipped based on its name. Returns the reason if it should be skipped. | As a python code expert, you are capable of creating scripts from specifications. |
def setup_options(opts):
'''Takes any actions necessary based on command line options'''
if opts.quiet:
logger.log.setLevel(logging.WARNING)
logger.GLOBAL_LOG_LEVEL = logging.WARNING
if opts.verbose:
logger.log.setLevel(logging.DEBUG)
logger.GLOBAL_LOG_LEVEL = logging.DEBUG | Create a Python 3 function for
taking any actions necessary based on command line options | You are a Python code analyst, evaluating scripts for potential improvements. |
Attempts to extract a module name for the given addon s addon. xml file and returns the addon s filename without the. py suffix. | Here you have a function in Python 3, explain what it does
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.
'''
try... | As a Python code composer, you craft elegant and concise scripts. |
Patches a few attributes of a plugin instance to enable a new call to
plugin. run | Here you have a function in Python 3, explain what it does
def patch_plugin(plugin, path, handle=None):
'''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_d... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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.
'''
# TODO: use OrderedSet?
paths_visited = set()
paths_to... | How would you implement a function in Python 3 that
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. | You are a Python code generator, capable of creating scripts from specifications. |
The run method for the run command. Executes a plugin from the
command line. | Make a summary of the following Python 3 code
def run(opts, args):
'''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.p... | You are a Python code analyst, evaluating scripts for potential improvements. |
Attempts to import a plugin s source code and find an instance of
:class ~xbmcswif2. Plugin. | Given the following Python 3 function, write the documentation
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.
'''
cwd = os.getcwd()
... | As a Python code analyst, you investigate and solve complex coding mysteries |
This method runs the plugin in the appropriate mode parsed from
the command line options. | Can you generate the documentation for the following Python 3 function
def run(self):
'''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,
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
This function is called by the application setup. py to generate a new configuration file. | Can you tell what is the following Python 3 function doing
def _setup_config(self, dist, filename, section, vars, verbosity):
modules = [line.strip() for line in dist.get_metadata_lines('top_level.txt')
if line.strip() and not line.strip().startswith('#')]
if not modules:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
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... | Make a summary of the following Python 3 code
def say(self, input=None, **kwargs):
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(... | As a python code expert, you are capable of creating scripts from specifications. |
Make a new conversation. | Make a summary of the following Python 3 code
def conversation(self, name=None, **kwargs):
convo = Conversation(self, **kwargs)
super().conversation(name, convo)
return convo | You are a Python code generator, capable of creating scripts from specifications. |
Validate a file system path. | Can you generate a brief explanation for the following Python 3 code
def validate(path, format='json',
approved_applications=None,
determined=True,
listed=True,
expectation=PACKAGE_ANY,
for_appversions=None,
overrides=None,
timeo... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Add an error message for an unexpected exception in validator
code and move it to the front of the error message list. | Make a summary of the following Python 3 code
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... | You are a Python code analyst, evaluating scripts for potential improvements. |
Drop the given message object from the appropriate message list. Returns True if the message was found otherwise False. | Can you tell what is the following Python 3 function doing
def drop_message(self, message):
for type_ in 'errors', 'warnings', 'notices':
list_ = getattr(self, type_)
if message in list_:
list_.remove(message)
if 'signing_severity' in message:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Updates the tier and ending tier | Can you generate the documentation for the following Python 3 function
def set_tier(self, tier):
'Updates the tier and ending tier'
self.tier = tier
if tier > self.ending_tier:
self.ending_tier = tier | You are a Python code generator, capable of creating scripts from specifications. |
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 i... | How would you code a function in Python 3 to
store a message in the appropriate message stack. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a boolean value describing whether the validation
succeeded or not. | Here you have a function in Python 3, explain what it does
def failed(self, fail_on_warnings=True):
return bool(self.errors) or (fail_on_warnings and bool(self.warnings)) | As a Python code composer, you craft elegant and concise scripts. |
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 | Write a Python 3 function for
retrieving an object that has been stored by another test. | As a Python code composer, you craft elegant and concise scripts. |
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 | Can you create a Python 3 function that
saves an object such that it can be used by other tests. | As a python code expert, you are capable of creating scripts from specifications. |
Saves the current error state to parse subpackages | Can you tell what is the following Python 3 function doing
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,
... | As a Python code composer, you craft elegant and concise scripts. |
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
... | Implement a Python 3 function for
retrieving the last saved state and restores it. | As a Python code composer, you craft elegant and concise scripts. |
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 ... | Can you write a function in Python 3 where it
returns a JSON summary of the validation operation. | You are a Python code generator, capable of creating scripts from specifications. |
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',
... | Write a Python 3 script for
printing a summary of the validation process so far. | As a Python code analyst, you investigate and solve complex coding mysteries |
Flattens nested lists into strings. | How would you explain what the following Python 3 function does
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)):
r... | As a Python code analyst, you investigate and solve complex coding mysteries |
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 =... | Write a Python 3 script for
printing a message and takes care of all sorts of nasty code | You are a Python code analyst, evaluating scripts for potential improvements. |
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:
r... | Can you implement a function in Python 3 that
returns whether a GUID set in for_appversions format is compatbile with the current supported applications list. | As a python code expert, you are capable of creating scripts from specifications. |
Compare the version of the application and the set of supported applications. | Here you have a function in Python 3, explain what it does
def _compare_version(self, requirements, support):
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 an... | You are a Python code generator, capable of creating scripts from specifications. |
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:
... | Write a Python 3 function for
deleting unused messages from errors warnings and notices. | As a Python code translator, you convert algorithms and pseudocode into Python. |
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 | Can you implement a function in Python 3 that
tweaks will be lost for Cleverbot and its conversations. | As a Python code composer, you craft elegant and concise scripts. |
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 | Implement a function in Python 3 to
migrate the state of the state machine into a Cleverbot object. | You are a Python code architect, reviewing and designing scalable and efficient code |
def init_with_uid(self, uid):
"""Initialize with an UID
"""
self._uid = uid
self._brain = None
self._catalog = None
self._instance = None | Implement a function in Python 3 to
initialize with an UID | As a python code expert, you are capable of creating scripts from specifications. |
Initialize with a catalog brain | Can you tell what is the following Python 3 function doing
def init_with_brain(self, brain):
self._uid = api.get_uid(brain)
self._brain = brain
self._catalog = self.get_catalog_for(brain)
self._instance = None | As a python code expert, you are capable of creating scripts from specifications. |
Initialize with an instance object | Given the following Python 3 function, write the documentation
def init_with_instance(self, instance):
self._uid = api.get_uid(instance)
self._brain = None
self._catalog = self.get_catalog_for(instance)
self._instance = instance | As a Python code analyst, you investigate and solve complex coding mysteries |
Process the value of the key - value pair. | Can you generate the documentation for the following Python 3 function
def process_value(self, 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)
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return the content instance of the wrapped object | Make a summary of the following Python 3 code
def instance(self):
if self._instance is None:
logger.debug("SuperModel::instance: *Wakup object*")
self._instance = api.get_object(self.brain)
return self._instance | You are a Python code analyst, evaluating scripts for potential improvements. |
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 | Write a Python 3 function that can
return the catalog brain of the wrapped object | As a Python code analyst, you investigate and solve complex coding mysteries |
Primary registered catalog for the wrapped portal type | Here you have a function in Python 3, explain what it does
def catalog(self):
if self._catalog is None:
logger.debug("SuperModel::catalog: *Fetch catalog*")
self._catalog = self.get_catalog_for(self.brain)
return self._catalog | As a Python code composer, you craft elegant and concise scripts. |
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... | Implement a Python 3 function for
returning the primary catalog for the given brain or object | As a python code expert, you are capable of creating scripts from specifications. |
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)))
re... | Write a Python 3 script to
wrap an object into a Super Model | As a Python code composer, you craft elegant and concise scripts. |
Convert value to string | How would you explain what the following Python 3 function does
def stringify(self, value):
# SuperModel -> UID
if ISuperModel.providedBy(value):
return str(value)
# DateTime -> ISO8601 format
elif isinstance(value, (DateTime)):
return value.ISO8601()
# Im... | As a python code expert, you are capable of creating scripts from specifications. |
Returns a copy dict of the current object. | Here you have a function in Python 3, explain what it does
def to_dict(self, converter=None):
if converter is None:
converter = self.stringify
out = dict()
for k, v in self.iteritems():
out[k] = converter(v)
return out | You are a Python code analyst, evaluating scripts for potential improvements. |
A decorator to add a route to a view. name is used to
differentiate when there are multiple routes for a given view. options is used to
differentiate when there are multiple routes for a given view. | Can you generate a brief explanation for the following Python 3 code
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 ... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a valid XBMC plugin URL for the given endpoint name. | Given the following Python 3 function, write the documentation
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 ro... | As a Python code translator, you convert algorithms and pseudocode into Python. |
This method adds a url rule for routing purposes. | Here you have a function in Python 3, explain what it does
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... | You are a Python code generator, capable of creating scripts from specifications. |
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 | Implement a Python 3 function for
overriding to add command options. | As a python code expert, you are capable of creating scripts from specifications. |
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) | Implement a Python 3 function for
returning True if the provided value is a valid pluglin id | As a Python code translator, you convert algorithms and pseudocode into Python. |
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 prov... | Implement a function in Python 3 to
display the provided prompt and gets input from the user. | As a python code expert, you are capable of creating scripts from specifications. |
Displays the provided prompt and returns the input from the user. | Can you generate a brief explanation for the following Python 3 code
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 : ' % ... | You are a Python code generator, capable of creating scripts from specifications. |
Edits the given file in place replacing any instances of key with the the
CTYPE appropriate value from the provided items dict. | Can you tell what is the following Python 3 function doing
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.
'''
... | As a Python code composer, you craft elegant and concise scripts. |
Create a new project in the current directory. | Can you generate the documentation for the following Python 3 function
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
--... | As a python code expert, you are capable of creating scripts from specifications. |
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... | Can you implement a function in Python 3 that
returns the list of supported applications. | As a Python code analyst, you investigate and solve complex coding mysteries |
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 \
... | Implement a Python 3 function for
returning the first triple value matching the given subject predicate and object. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a generator of objects that correspond to the
specified subjects and predicates. | How would you explain what the following Python 3 function does
def get_objects(self, subject=None, predicate=None):
for triple in self.triples:
# Filter out non-matches
if ((subject and triple['subject'] != subject) or
(predicate and triple['predicate'] != predicate)):... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a generator of triples that correspond to the specified subject predicate and object. | Explain what the following Python 3 code does
def get_triples(self, subject=None, predicate=None, object_=None):
for triple in self.triples:
# Filter out non-matches
if subject is not None and triple['subject'] != subject:
continue
if predicate is not None a... | You are a Python code architect, reviewing and designing scalable and efficient code |
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()
... | How would you implement a function in Python 3 that
returns a set of overlays that are applicable to the current package or subpackage. | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a chrome URL for a given path given the current package depth
in an error bundle. | Make a summary of the following Python 3 code
def reverse_lookup(self, state, path):
# 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, lis... | As a Python code composer, you craft elegant and concise scripts. |
Join the arguments together to form a predictable URL chunk. | Make a summary of the following Python 3 code
def _url_chunk_join(self, *args):
# 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... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Main entry point for the application. | Can you tell what is the following Python 3 function doing
def run(self, argv):
try:
self.options, remainder = self.parser.parse_known_args(argv)
self._configure_logging()
if self.options.relative_plugins:
curdir = os.getcwd()
sys.path.insert(... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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)) | Can you implement a function in Python 3 that
returns a URIRef object for use with the RDF document. | As a Python code composer, you craft elegant and concise scripts. |
Returns the BNode which describes the topmost subject of the graph. | Can you tell what is the following Python 3 function doing
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:
... | As a Python code composer, you craft elegant and concise scripts. |
Eliminates some of the glue code for searching RDF. Pass
in a URIRef object for either of the the
parameters. | Explain what the following Python 3 code does
def get_object(self, subject=None, predicate=None):
# 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
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return the list of supported applications. | Can you generate a brief explanation for the following Python 3 code
def get_applications(self):
applications = []
# Isolate all of the bnodes referring to target applications
for target_app in self.get_objects(None,
self.uri('targetApplication')):
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Adds context menu items. | How would you explain what the following Python 3 function does
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 isinstanc... | As a Python code analyst, you investigate and solve complex coding mysteries |
Sets the listitem s icon image | Can you generate the documentation for the following Python 3 function
def set_icon(self, icon):
'''Sets the listitem's icon image'''
self._icon = icon
return self._listitem.setIconImage(icon) | You are a Python code generator, capable of creating scripts from specifications. |
def set_thumbnail(self, thumbnail):
'''Sets the listitem's thumbnail image'''
self._thumbnail = thumbnail
return self._listitem.setThumbnailImage(thumbnail) | How would you code a function in Python 3 to
set the listitem s thumbnail image | You are a Python code analyst, evaluating scripts for potential improvements. |
Sets the listitem s path | Explain what the following Python 3 code does
def set_path(self, path):
'''Sets the listitem's path'''
self._path = path
return self._listitem.setPath(path) | As a Python code translator, you convert algorithms and pseudocode into Python. |
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 | Write a Python 3 script for
setting the listitem s playable flag | You are a Python code generator, capable of creating scripts from specifications. |
A decorator that caches the output of a function. | Here you have a function in Python 3, explain what it does
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 ... | You are a Python code generator, capable of creating scripts from specifications. |
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)
... | Write a Python 3 function that can
return a list of existing stores. The returned names can then be used to call get_storage. | You are a Python code architect, reviewing and designing scalable and efficient code |
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.... | How would you implement a function in Python 3 that
returns a storage for the given name. | You are a Python code analyst, evaluating scripts for potential improvements. |
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] = s... | Write a Python 3 function that can
return the localized string from strings. xml for the given stringid. | You are a Python code architect, reviewing and designing scalable and efficient code |
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 t... | Implement a function in Python 3 to
return the value of the setting with the provided id. | You are a Python code generator, capable of creating scripts from specifications. |
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.' %
... | Can you write a function in Python 3 where it
adds the provided list of items to the specified playlist. | You are a Python code analyst, evaluating scripts for potential improvements. |
Attempts to return a view_mode_id for a given view_mode. | Can you generate the documentation for the following Python 3 function
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
... | As a python code expert, you are capable of creating scripts from specifications. |
Displays the keyboard input window to the user. | Can you generate a brief explanation for the following Python 3 code
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 placeh... | As a Python code analyst, you investigate and solve complex coding mysteries |
Displays a temporary notification message to the user. | Given the following Python 3 function, write the documentation
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 ... | As a python code expert, you are capable of creating scripts from specifications. |
Creates an xbmcswift2. ListItem if the provided value for item is a
dict. | Can you generate the documentation for the following Python 3 function
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.i... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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... | Create a Python 3 function for
adding subtitles to playing video. | You are a Python code analyst, evaluating scripts for potential improvements. |
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 res... | How would you code a function in Python 3 to
set the resolved url of a playable list item. | As a Python code translator, you convert algorithms and pseudocode into Python. |
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 it... | Write a Python 3 function for
adding ListItems to the XBMC interface. | As a Python code analyst, you investigate and solve complex coding mysteries |
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.Plu... | Write a Python 3 function that can
wrap for xbmcplugin. endOfDirectory. Records state in self. _end_of_directory. | You are a Python code architect, reviewing and designing scalable and efficient code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.