output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Split the stream into channels and start a parallel region. | Can you generate a brief explanation for the following Python 3 code
def parallel(self, width, routing=Routing.ROUND_ROBIN, func=None, name=None):
_name = name
if _name is None:
_name = self.name + '_parallel'
_name = self.topology.graph._requested_name(_name, action='pa... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def end_parallel(self):
"""
Ends a parallel region by merging the channels into a single stream.
Returns:
Stream: Stream for which subsequent transformations are no longer parallelized.
.. seealso:: :py:meth:`set_parallel`, :py:meth:`parallel`
"""
outport = ... | Create a Python 3 function for
ending a parallel region by merging the channels into a single stream. | You are a Python code analyst, evaluating scripts for potential improvements. |
def set_parallel(self, width, name=None):
"""
Set this source stream to be split into multiple channels
as the start of a parallel region.
Calling ``set_parallel`` on a stream created by
:py:meth:`~Topology.source` results in the stream
having `width` channels, each crea... | How would you implement a function in Python 3 that
sets this source stream to be split into multiple channels and start a parallel region. | As a Python code composer, you craft elegant and concise scripts. |
Sets the consistent state of the current stream. | Can you generate the documentation for the following Python 3 function
def set_consistent(self, consistent_config):
# add job control plane if needed
self.topology._add_job_control_plane()
self.oport.operator.consistent(consistent_config)
return self._make_placeable() | As a Python code composer, you craft elegant and concise scripts. |
Declares a slding window containing the most recent tuples on this stream. | Can you generate a brief explanation for the following Python 3 code
def last(self, size=1):
win = Window(self, 'SLIDING')
if isinstance(size, datetime.timedelta):
win._evict_time(size)
elif isinstance(size, int):
win._evict_count(size)
else:
raise Val... | As a python code expert, you are capable of creating scripts from specifications. |
Returns a new stream that is a union of this stream and other streams. | How would you explain what the following Python 3 function does
def union(self, streamSet):
if(not isinstance(streamSet,set)) :
raise TypeError("The union operator parameter must be a set object")
if(len(streamSet) == 0):
return self
op = self.topology.graph.addOp... | You are a Python code generator, capable of creating scripts from specifications. |
Prints each tuple to stdout flushing after each tuple. | Can you tell what is the following Python 3 function doing
def print(self, tag=None, name=None):
_name = name
if _name is None:
_name = 'print'
fn = streamsx.topology.functions.print_flush
if tag is not None:
tag = str(tag) + ': '
fn = lambda v : strea... | As a python code expert, you are capable of creating scripts from specifications. |
def publish(self, topic, schema=None, name=None):
"""
Publish this stream on a topic for other Streams applications to subscribe to.
A Streams application may publish a stream to allow other
Streams applications to subscribe to it. A subscriber
matches a publisher if the topic an... | Can you create a Python 3 function that
publishes this stream to a topic. | As a python code expert, you are capable of creating scripts from specifications. |
Starts an autonomous region for downstream processing. | Here you have a function in Python 3, explain what it does
def autonomous(self):
op = self.topology.graph.addOperator("$Autonomous$")
op.addInputPort(outputPort=self.oport)
oport = op.addOutputPort(schema=self.oport.schema)
return Stream(self.topology, oport) | As a Python code analyst, you investigate and solve complex coding mysteries |
def as_string(self, name=None):
"""
Declares a stream converting each tuple on this stream
into a string using `str(tuple)`.
The stream is typed as a :py:const:`string stream <streamsx.topology.schema.CommonSchema.String>`.
If this stream is already typed as a string stream the... | Write a Python 3 script to
return a new SAS stream containing the string representations of each tuple on this stream. | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a new stream that contains the JSON representation of the tuples on this stream. | Make a summary of the following Python 3 code
def as_json(self, force_object=True, name=None):
func = streamsx.topology.runtime._json_force_object if force_object else None
saj = self._change_schema(streamsx.topology.schema.CommonSchema.Json, 'as_json', name, func)._layout('AsJson')
saj.oport.op... | You are a Python code analyst, evaluating scripts for potential improvements. |
Used to initialize the View object on first use. | Here you have a function in Python 3, explain what it does
def _initialize_rest(self):
if self._submit_context is None:
raise ValueError("View has not been created.")
job = self._submit_context._job_access()
self._view_object = job.get_views(name=self.name)[0] | You are a Python code generator, capable of creating scripts from specifications. |
Display a view within a Jupyter or IPython notebook cell. | Given the following Python 3 function, write the documentation
def display(self, duration=None, period=2):
self._initialize_rest()
return self._view_object.display(duration, period) | You are a Python code architect, reviewing and designing scalable and efficient code |
def complete(self, stream):
"""Complete the pending stream.
Any connections made to :py:attr:`stream` are connected to `stream` once
this method returns.
Args:
stream(Stream): Stream that completes the connection.
"""
assert not s... | Can you create a Python 3 function that
completes the pending stream. | You are a Python code architect, reviewing and designing scalable and efficient code |
Declare a window with this window s size and a trigger policy. | Can you generate a brief explanation for the following Python 3 code
def trigger(self, when=1):
tw = Window(self.stream, self._config['type'])
tw._config['evictPolicy'] = self._config['evictPolicy']
tw._config['evictConfig'] = self._config['evictConfig']
if self._config['evictPolicy'] ==... | As a Python code composer, you craft elegant and concise scripts. |
Aggregates the contents of the window when the window is triggered. | How would you explain what the following Python 3 function does
def aggregate(self, function, name=None):
schema = streamsx.topology.schema.CommonSchema.Python
sl = _SourceLocation(_source_info(), "aggregate")
_name = self.topology.graph._requested_name(name, action="aggregate", func=fu... | You are a Python code generator, capable of creating scripts from specifications. |
Get the root URL for IBM Streams REST API. | Here you have a function in Python 3, explain what it does
def get_rest_api():
assert _has_local_install
url=[]
ok = _run_st(['geturl', '--api'], lines=url)
if not ok:
raise ChildProcessError('streamtool geturl')
return url[0] | You are a Python code generator, capable of creating scripts from specifications. |
Gets the package name given a module object | Given the following Python 3 function, write the documentation
def _get_package_name(module):
try:
# if __package__ is defined, use it
package_name = module.__package__
except AttributeError:
package_name = None
if package_name is None:
# if __path__ is defined, th... | As a Python code composer, you craft elegant and concise scripts. |
def _get_module_name(function):
"""
Gets the function's module name
Resolves the __main__ module to an actual module name
Returns:
str: the function's module name
"""
module_name = function.__module__
if module_name == '__main__':
# get the main module object of the function
... | How would you implement a function in Python 3 that
gets the function s module name | You are a Python code generator, capable of creating scripts from specifications. |
def _is_builtin_module(module):
"""Is builtin or part of standard library
"""
if (not hasattr(module, '__file__')) or module.__name__ in sys.builtin_module_names:
return True
if module.__name__ in _stdlib._STD_LIB_MODULES:
return True
amp = os.path.abspath(module.__file__)
if 's... | Write a Python 3 script to
am the given module a builtin module? | You are a Python code generator, capable of creating scripts from specifications. |
def _find_dependent_modules(self, module):
"""
Return the set of dependent modules for used modules,
classes and routines.
"""
dms = set()
for um in inspect.getmembers(module, inspect.ismodule):
dms.add(um[1])
for uc in inspect.getmembers(module, insp... | Can you implement a function in Python 3 that
finds the set of dependent modules for used modules classes and routines. | You are a Python code generator, capable of creating scripts from specifications. |
Adds a module and its dependencies to the list of dependencies. | Make a summary of the following Python 3 code
def add_dependencies(self, module):
if module in self._processed_modules:
return None
if hasattr(module, "__name__"):
mn = module.__name__
else:
mn = '<unknown>'
_debug.debug("add_dependencies:module=%s"... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _include_module(self, module, mn):
""" See if a module should be included or excluded based upon
included_packages and excluded_packages.
As some packages have the following format:
scipy.special.specfun
scipy.linalg
Where the top-level package name is just a prefi... | Write a Python 3 function for
returning True if a module should be included or excluded based upon included_packages and excluded_packages. | As a Python code composer, you craft elegant and concise scripts. |
def _add_dependency(self, module, mn):
"""
Adds a module to the list of dependencies
without handling the modules dependences.
Modules in site-packages are excluded from being added into
the toolkit. This mimics dill.
"""
_debug.debug("_add_dependency:module=%s",... | Implement a Python 3 function for
adding a module to the list of dependencies. | As a Python code composer, you craft elegant and concise scripts. |
Returns a dictionary of all settings set for this object including any values of its parents or hardcoded defaults. | Make a summary of the following Python 3 code
def freeze(self) -> dict:
settings = {}
for key, v in self._h.defaults.items():
settings[key] = self._unserialize(v.value, v.type)
if self._parent:
settings.update(getattr(self._parent, self._h.attribute_name).freeze())
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get(self, key: str, default=None, as_type: type = None, binary_file=False):
"""
Get a setting specified by key ``key``. Normally, settings are strings, but
if you put non-strings into the settings object, you can request unserialization
by specifying ``as_type``. If the key does not ... | Can you write a function in Python 3 where it
gets a value from the object s settings object. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def set(self, key: str, value: Any) -> None:
"""
Stores a setting to the database of its object.
The write to the database is performed immediately and the cache in the cache backend is flushed.
The cache within this object will be updated correctly.
"""
wc = se... | Write a Python 3 function for
storing a setting to the database of the object. | You are a Python code architect, reviewing and designing scalable and efficient code |
def delete(self, key: str) -> None:
"""
Deletes a setting from this object's storage.
The write to the database is performed immediately and the cache in the cache backend is flushed.
The cache within this object will be updated correctly.
"""
if key in self._wri... | Write a Python 3 script to
delete a setting from this object s storage. | As a python code expert, you are capable of creating scripts from specifications. |
Retrieves the VCAP Services information from the VCAP_SERVICES environment variable or from the config object. | How would you explain what the following Python 3 function does
def _get_vcap_services(vcap_services=None):
vcap_services = vcap_services or os.environ.get('VCAP_SERVICES')
if not vcap_services:
raise ValueError(
"VCAP_SERVICES information must be supplied as a parameter or as environment va... | You are a Python code generator, capable of creating scripts from specifications. |
def _get_credentials(vcap_services, service_name=None):
"""Retrieves the credentials of the VCAP Service of the specified `service_name`. If
`service_name` is not specified, it takes the information from STREAMING_ANALYTICS_SERVICE_NAME environment
variable.
Args:
vcap_services (dict): A dict ... | How would you implement a function in Python 3 that
retrieves the credentials of the specified service_name. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _get_rest_api_url_from_creds(session, credentials):
"""Retrieves the Streams REST API URL from the provided credentials.
Args:
session (:py:class:`requests.Session`): A Requests session object for making REST calls
credentials (dict): A dict representation of the credentials.
Returns:
... | Write a Python 3 function that can
retrieve the Streams REST API URL from the provided credentials. | You are a Python code generator, capable of creating scripts from specifications. |
Retrieves the remote Streams REST API URL from the provided credentials using IAM authentication. | Here you have a function in Python 3, explain what it does
def _get_iam_rest_api_url_from_creds(rest_client, credentials):
res = rest_client.make_request(credentials[_IAMConstants.V2_REST_URL])
base = res['streams_self']
end = base.find('/instances')
return base[:end] + '/resources' | You are a Python code architect, reviewing and designing scalable and efficient code |
str - Root URL for IBM Streams REST API | Can you generate a brief explanation for the following Python 3 code
def resource_url(self):
self._resource_url = self._resource_url or st.get_rest_api()
return self._resource_url | As a Python code analyst, you investigate and solve complex coding mysteries |
def _get_element_by_id(self, resource_name, eclass, id):
"""Get a single element matching an id"""
elements = self._get_elements(resource_name, eclass, id=id)
if not elements:
raise ValueError("No resource matching: {0}".format(id))
if len(elements) == 1:
return e... | Create a Python 3 function to
get a single element matching an id | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_domains(self):
"""Retrieves available domains.
Returns:
:py:obj:`list` of :py:class:`~.rest_primitives.Domain`: List of available domains
"""
# Domains are fixed and actually only one per REST api.
if self._domains is None:
self._domains = self._g... | Can you write a function in Python 3 where it
retrieves the available domains. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_resources(self):
"""Retrieves a list of all known Streams high-level REST resources.
Returns:
:py:obj:`list` of :py:class:`~.rest_primitives.RestResource`: List of all Streams high-level REST resources.
"""
json_resources = self.rest_client.make_request(self.resource... | Implement a Python 3 function for
retrieving a list of all known Streams high - level REST resources. | You are a Python code generator, capable of creating scripts from specifications. |
Create a Streaming Analytics connection to a single service. | Explain what the following Python 3 code does
def of_definition(service_def):
vcap_services = streamsx.topology.context._vcap_from_service_definition(service_def)
service_name = streamsx.topology.context._name_from_service_definition(service_def)
return StreamingAnalyticsConnection(vcap_services, s... | As a Python code translator, you convert algorithms and pseudocode into Python. |
str - Returns the root URL for the IBM Streams REST API. | Can you generate a brief explanation for the following Python 3 code
def resource_url(self):
if self._iam:
self._resource_url = self._resource_url or _get_iam_rest_api_url_from_creds(self.rest_client, self.credentials)
else:
self._resource_url = self._resource_url or _get_rest_ap... | As a Python code composer, you craft elegant and concise scripts. |
Verify 2 - legged OAuth request. | Can you generate the documentation for the following Python 3 function
def is_authenticated(self, request, **kwargs):
log.info("OAuth20Authentication")
try:
key = request.GET.get('oauth_consumer_key')
if not key:
for header in ['Authorization', 'HTTP_AUTHORIZATION... | You are a Python code architect, reviewing and designing scalable and efficient code |
Checks if the token is allowed for our access token. | How would you explain what the following Python 3 function does
def check_scope(self, token, request):
http_method = request.method
if not hasattr(self, http_method):
raise OAuthError("HTTP method is not recognized")
required_scopes = getattr(self, http_method)
# a None scope... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _is_args_eightbit(*args) -> bool:
"""
Check if input matches type: renderer.eightbit.
"""
if not args:
return False
elif args[0] is 0:
return True
elif isinstance(args[0], int):
return True
else:
return False | Write a Python 3 script for
checking if input matches type renderer. eightbit. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def as_dict(self) -> Dict[str, str]:
"""
Export color register as dict.
"""
items: Dict[str, str] = {}
for k, v in self.items():
if type(v) is str:
items.update({k: v})
return items | How would you code a function in Python 3 to
export color register as dict. | You are a Python code analyst, evaluating scripts for potential improvements. |
Export color register as namedtuple. | Given the following Python 3 function, write the documentation
def as_namedtuple(self):
d = self.as_dict()
return namedtuple('ColorRegister', d.keys())(*d.values()) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Extracts attributes from an image list x. | Explain what the following Python 3 code does
def _extract_attrs(x, n):
try:
return extract_attrs(x, n)
except (ValueError, IndexError):
if PANDOCVERSION < '1.16':
# Look for attributes attached to the image path, as occurs with
# image references for pandoc < 1.16 (pan... | As a python code expert, you are capable of creating scripts from specifications. |
def _process_figure(value, fmt):
"""Processes the figure. Returns a dict containing figure properties."""
# pylint: disable=global-statement
global Nreferences # Global references counter
global has_unnumbered_figures # Flags unnumbered figures were found
global cursec ... | How would you code a function in Python 3 to
process the figure. Returns a dict containing the figure properties. | As a python code expert, you are capable of creating scripts from specifications. |
Filters the document AST and returns the resulting tree. | Can you tell what is the following Python 3 function doing
def main():
# pylint: disable=global-statement
global PANDOCVERSION
global Image
# Get the output format and document
fmt = args.fmt
doc = json.loads(STDIN.read())
# Initialize pandocxnos
# pylint: disable=too-many-function-ar... | You are a Python code generator, capable of creating scripts from specifications. |
Displays the i18n JavaScript that the Django admin requires. | Here you have a function in Python 3, explain what it does
def i18n_javascript(self, request):
if settings.USE_I18N:
from django.views.i18n import javascript_catalog
else:
from django.views.i18n import null_javascript_catalog as javascript_catalog
return javascript_catalo... | You are a Python code analyst, evaluating scripts for potential improvements. |
Turns a list of FileNode objects into a list of
strings linking to the associated files. | Can you generate a brief explanation for the following Python 3 code
def file_links(items, opts=None):
result = []
kwargs = get_kwargs_for_file_link(opts)
for item in items:
if isinstance(item, FileNode):
result.append(get_file_link(item, **kwargs))
else:
result.append(file_links(item, kwargs))
return res... | You are a Python code architect, reviewing and designing scalable and efficient code |
Write your forwards methods here. | Can you generate the documentation for the following Python 3 function
def forwards(self, orm):
"Write your forwards methods here."
for node in orm.FileNode.objects.all():
node.save() | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the MediaBackend subclass that is configured for use with
media_tree. | Given the following Python 3 function, write the documentation
def get_media_backend(fail_silently=True, handles_media_types=None,
handles_file_extensions=None, supports_thumbnails=None):
"""
Returns the MediaBackend subclass that is configured for use with
media_tree.
"""
... | As a python code expert, you are capable of creating scripts from specifications. |
Returns a pre - configured thumbnail size or assigns it to a context variable. | Here you have a function in Python 3, explain what it does
def thumbnail_size(parser, token):
args = token.split_contents()
tag = args.pop(0)
if len(args) >= 2 and args[-2] == 'as':
context_name = args[-1]
args = args[:-2]
else:
context_name = None
if len(args) > 1:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
This function is used to make a request to the server. | Given the following Python 3 function, write the documentation
def request(method, path, params=None, data=None, auto_retry=True):
body = None
if data is not None:
body = json.dumps(data, cls=utils.DateTimeEncoder)
headers = {
'accept': 'application/json',
'content-type': 'applicati... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the length in bytes of a given file object. | Can you tell what is the following Python 3 function doing
def file_length(file_obj):
file_obj.seek(0, 2)
length = file_obj.tell()
file_obj.seek(0)
return length | As a Python code composer, you craft elegant and concise scripts. |
def parse_href(href):
"""Parses an Analyze Re href into collection name and ID"""
url = urlparse(href)
path = url.path.split('/')
collection_name = path[1]
id_ = path[2]
return collection_name, id_ | Can you create a Python 3 function that
parses an Analyze Re href into collection name and ID | You are a Python code analyst, evaluating scripts for potential improvements. |
def vectorize(values):
"""
Takes a value or list of values and returns a single result, joined by ","
if necessary.
"""
if isinstance(values, list):
return ','.join(str(v) for v in values)
return values | Implement a function in Python 3 to
take a value or list of values and returns a single result joined by ",". | As a python code expert, you are capable of creating scripts from specifications. |
def upload_data(self, file_or_str, chunk_size=analyzere.upload_chunk_size,
poll_interval=analyzere.upload_poll_interval,
upload_callback=lambda x: None,
commit_callback=lambda x: None):
"""
Accepts a file-like object or string and uploads it. F... | Can you implement a function in Python 3 that
uploads data to the tus server. | As a Python code composer, you craft elegant and concise scripts. |
def delete_orphaned_files(modeladmin, request, queryset=None):
"""
Deletes orphaned files, i.e. media files existing in storage that are not in the database.
"""
execute = request.POST.get('execute')
storage = get_media_storage()
broken_node_links = []
orphaned_files_choices = []
... | Can you write a function in Python 3 where it
deletes orphaned files from storage. | As a Python code analyst, you investigate and solve complex coding mysteries |
def rebuild_tree(modeladmin, request, queryset=None):
"""
Rebuilds whole tree in database using `parent` link.
"""
tree = FileNode.tree.rebuild()
messages.success(request, message=_('The node tree was rebuilt.'))
return HttpResponseRedirect('') | Can you write a function in Python 3 where it
rebuilds whole tree in database using parent link. | You are a Python code analyst, evaluating scripts for potential improvements. |
Clear media cache files. | Here you have a function in Python 3, explain what it does
def clear_cache(modeladmin, request, queryset=None):
execute = request.POST.get('execute')
files_in_storage = []
storage = get_media_storage()
cache_files_choices = []
for storage_name in get_cache_files():
link = mark_safe... | As a Python code composer, you craft elegant and concise scripts. |
Returns a suitable description of this field for South. | Can you generate the documentation for the following Python 3 function
def south_field_triple(self):
"Returns a suitable description of this field for South."
from south.modelsinspector import introspector
field_class = "django.db.models.fields.CharField"
args, kwargs = introspector(self... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a list of three elements that are the same size and the third being the full extension. | Given the following Python 3 function, write the documentation
def multi_splitext(basename):
groups = list(RE_SPLITEXT.match(basename).groups())
if not groups[2]:
groups[2] = groups[1]
return groups | You are a Python code generator, capable of creating scripts from specifications. |
Join two strings optionally escaping the second and using one of the two string formats for glueing them together. | Can you generate a brief explanation for the following Python 3 code
def join_formatted(text, new_text, glue_format_if_true = u'%s%s', glue_format_if_false = u'%s%s', condition=None, format = u'%s', escape=False):
if condition is None:
condition = text and new_text
add_text = new_text
if escape:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the width ratio of a single value. | Can you tell what is the following Python 3 function doing
def widthratio(value, max_value, max_width):
ratio = float(value) / float(max_value)
return int(round(ratio * max_width)) | You are a Python code analyst, evaluating scripts for potential improvements. |
def _initialize(self, path):
""" Find metadata tree root, detect format version """
# Find the tree root
root = os.path.abspath(path)
try:
while ".fmf" not in next(os.walk(root))[1]:
if root == "/":
raise utils.RootError(
... | Can you implement a function in Python 3 that
initializes the internal state of the object. | You are a Python code analyst, evaluating scripts for potential improvements. |
Merge the current object with the parent object. | Can you generate the documentation for the following Python 3 function
def merge(self, parent=None):
# Check parent, append source files
if parent is None:
parent = self.parent
if parent is None:
return
self.sources = parent.sources + self.sources
# Merge ... | As a Python code composer, you craft elegant and concise scripts. |
def inherit(self):
""" Apply inheritance """
# Preserve original data and merge parent
# (original data needed for custom inheritance extensions)
self.original_data = self.data
self.merge()
log.debug("Data for '{0}' inherited.".format(self))
log.data(pretty(self.d... | Implement a function in Python 3 to
apply inheritance to this object and all its children. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Update metadata for this object by parsing the data dictionary. | Can you tell what is the following Python 3 function doing
def update(self, data):
# Nothing to do if no data
if data is None:
return
for key, value in sorted(data.items()):
# Handle child attributes
if key.startswith('/'):
name = key.lstrip('/... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get(self, name=None, default=None):
"""
Get attribute value or return default
Whole data dictionary is returned when no attribute provided.
Supports direct values retrieval from deep dictionaries as well.
Dictionary path should be provided as list. The following two
... | How would you code a function in Python 3 to
get attribute value or return default if no attribute specified. | As a python code expert, you are capable of creating scripts from specifications. |
Create or update a child with given data. | Can you generate the documentation for the following Python 3 function
def child(self, name, data, source=None):
try:
if isinstance(data, dict):
self.children[name].update(data)
else:
self.children[name].grow(data)
except KeyError:
self... | You are a Python code architect, reviewing and designing scalable and efficient code |
Grow the tree for the given path. | Here you have a function in Python 3, explain what it does
def grow(self, path):
if path is None:
return
path = path.rstrip("/")
log.info("Walking through directory {0}".format(
os.path.abspath(path)))
dirpath, dirnames, filenames = next(os.walk(path))
# I... | As a python code expert, you are capable of creating scripts from specifications. |
Iterate through the tree and yield all the nodes that are leaf. | Here you have a function in Python 3, explain what it does
def climb(self, whole=False):
if whole or not self.children:
yield self
for name, child in self.children.items():
for node in child.climb(whole):
yield node | You are a Python code generator, capable of creating scripts from specifications. |
Find a node with given name | How would you explain what the following Python 3 function does
def find(self, name):
for node in self.climb(whole=True):
if node.name == name:
return node
return None | As a Python code translator, you convert algorithms and pseudocode into Python. |
def prune(self, whole=False, keys=[], names=[], filters=[]):
""" Filter tree nodes based on given criteria """
for node in self.climb(whole):
# Select only nodes with key content
if not all([key in node.data for key in keys]):
continue
# Select nodes w... | Write a Python 3 script for
pruning the tree nodes based on given criteria | As a Python code translator, you convert algorithms and pseudocode into Python. |
def show(self, brief=False, formatting=None, values=[]):
""" Show metadata """
# Show nothing if there's nothing
if not self.data:
return None
# Custom formatting
if formatting is not None:
formatting = re.sub("\\\\n", "\n", formatting)
name =... | Create a Python 3 function to
show the current state of the object. | You are a Python code analyst, evaluating scripts for potential improvements. |
def label_from_instance(self, obj):
"""
Creates labels which represent the tree level of each node when
generating option labels.
"""
level = getattr(obj, obj._mptt_meta.level_attr)
level_indicator = mark_safe(conditional_escape(self.level_indicator) * level)
retu... | Can you implement a function in Python 3 that
returns a label for the given object. | As a Python code analyst, you investigate and solve complex coding mysteries |
Saves the current state of the node to the specified target and position. | Explain what the following Python 3 code does
def save(self):
try:
self.node.move_to(self.cleaned_data['target'],
self.cleaned_data['position'])
return self.node
except InvalidMove, e:
self.errors[NON_FIELD_ERRORS] = ErrorList(e)
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def find(names, dirs, file_ext):
"""
Iterating a set of dirs under the static root, this method tries to find
a file named like one of the names and file ext passed, and returns the
storage path to the first file it encounters.
Usage this method makes it possible to over... | Create a Python 3 function for
iterating a set of dirs under the static root, this method tries to find a file named like one of the names and file ext passed, and returns the storage path to the first file it encounters. Usage this method makes it possible to override static files (such as icon sets) in a similar way ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Find a file in the given directory and return a StaticIconFile object. | Can you tell what is the following Python 3 function doing
def find(file_node, dirs=ICON_DIRS, default_name=None, file_ext='.png'):
names = []
for attr_name in ('extension', 'mimetype', 'mime_supertype'):
attr = getattr(file_node, attr_name)
if attr:
names.append(... | As a python code expert, you are capable of creating scripts from specifications. |
def result_tree_flat(context, cl, request):
"""
Added 'filtered' param, so the template's js knows whether the results have
been affected by a GET param or not. Only when the results are not filtered
you can drag and sort the tree
"""
return {
#'filtered': is_filtered_cl(cl, request),
... | Implement a Python 3 function for
returning a flat tree of results | As a Python code composer, you craft elegant and concise scripts. |
Returns the object that the view is displaying. | How would you explain what the following Python 3 function does
def get_object(self, queryset=None):
# Use a custom queryset if provided; this is required for subclasses
# like DateDetailView
if queryset is None:
queryset = self.get_queryset()
path = self.kwargs.get('path', ... | You are a Python code generator, capable of creating scripts from specifications. |
Instantiates and returns the view class that will generate the actual
context for this plugin. | Explain what the following Python 3 code does
def get_detail_view(self, request, object, opts=None):
view = self.get_view(request, self.view_class, opts)
view.object = object
return view | You are a Python code generator, capable of creating scripts from specifications. |
Instantiates and returns the view class that will generate the
actual context for this plugin. | Here you have a function in Python 3, explain what it does
def get_listing_view(self, request, queryset, opts=None):
view = self.get_view(request, self.view_class, opts)
view.queryset = queryset
return view | You are a Python code generator, capable of creating scripts from specifications. |
def options_formatting(self):
""" Formating options """
group = self.parser.add_argument_group("Format")
group.add_argument(
"--format", dest="formatting", default=None,
help="Custom output format using the {} expansion")
group.add_argument(
"--value",... | Write a Python 3 script to
add the formatting options to the parser | You are a Python code architect, reviewing and designing scalable and efficient code |
Options for the utils command | Can you generate a brief explanation for the following Python 3 code
def options_utils(self):
group = self.parser.add_argument_group("Utils")
group.add_argument(
"--path", action="append", dest="paths",
help="Path to the metadata tree (default: current directory)")
group.... | As a Python code composer, you craft elegant and concise scripts. |
def command_ls(self):
""" List names """
self.parser = argparse.ArgumentParser(
description="List names of available objects")
self.options_select()
self.options_utils()
self.options = self.parser.parse_args(self.arguments[2:])
self.show(brief=True) | Create a Python 3 function to
list names of available objects | As a python code expert, you are capable of creating scripts from specifications. |
Show metadata of available objects | How would you explain what the following Python 3 function does
def command_show(self):
self.parser = argparse.ArgumentParser(
description="Show metadata of available objects")
self.options_select()
self.options_formatting()
self.options_utils()
self.options = self.pa... | You are a Python code architect, reviewing and designing scalable and efficient code |
Initialize a new metadata tree | How would you explain what the following Python 3 function does
def command_init(self):
self.parser = argparse.ArgumentParser(
description="Initialize a new metadata tree")
self.options_utils()
self.options = self.parser.parse_args(self.arguments[2:])
# For each path create a... | You are a Python code analyst, evaluating scripts for potential improvements. |
def show(self, brief=False):
""" Show metadata for each path given """
output = []
for path in self.options.paths or ["."]:
if self.options.verbose:
utils.info("Checking {0} for metadata.".format(path))
tree = fmf.Tree(path)
for node in tree.pr... | Write a Python 3 function that can
show metadata for each path given | As a Python code composer, you craft elegant and concise scripts. |
def filter(filter, data, sensitive=True, regexp=False):
"""
Return true if provided filter matches given dictionary of values
Filter supports disjunctive normal form with '|' used for OR, '&'
for AND and '-' for negation. Individual values are prefixed with
'value:', leading/trailing white-space is... | How would you code a function in Python 3 to
filter the data dictionary for a single item in the list of items in the list of items in the list of items in the list of items in the list of items in the list of items in the list of items in the list. | As a Python code analyst, you investigate and solve complex coding mysteries |
Color a text in the specified color if coloring is enabled. | Make a summary of the following Python 3 code
def color(text, color=None, background=None, light=False, enabled="auto"):
colors = {"black": 30, "red": 31, "green": 32, "yellow": 33,
"blue": 34, "magenta": 35, "cyan": 36, "white": 37}
# Nothing do do if coloring disabled
if enabled == "auto":
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _create_logger(name='fmf', level=None):
""" Create fmf logger """
# Create logger, handler and formatter
logger = logging.getLogger(name)
handler = logging.StreamHandler()
handler.setFormatter(Logging.ColoredFormatter())
logger.addHandler(handler)
# Save log l... | Create a Python 3 function for
creating a logger with the given name and level. | You are a Python code analyst, evaluating scripts for potential improvements. |
def filter(self, *args, **kwargs):
"""
Works just like the default Manager's :func:`filter` method, but
you can pass an additional keyword argument named ``path`` specifying
the full **path of the folder whose immediate child objects** you
want to retrieve, e.g. ``"path/to/folder... | Write a Python 3 script for
working just like the default Manager's :func:`filter` method, but you can pass an additional keyword argument named ``path`` specifying the full **path of the folder whose immediate child objects** you want to retrieve, e.g. ``"path/to/folder"``. | As a python code expert, you are capable of creating scripts from specifications. |
def exclude(self, *args, **kwargs):
"""
Works just like the default Manager's :func:`exclude` method, but
you can pass an additional keyword argument named ``path`` specifying
the full **path of the folder whose immediate child objects** you
want to exclude, e.g. ``"path/to/folde... | Implement a function in Python 3 to
exclude objects from the cache. | You are a Python code analyst, evaluating scripts for potential improvements. |
This method is a wrapper for the base class get method. | Given the following Python 3 function, write the documentation
def get(self, *args, **kwargs):
if 'path' in kwargs:
kwargs = self.get_filter_args_with_path(True, **kwargs)
return super(FileNodeManager, self).get(
*args, **kwargs) | You are a Python code analyst, evaluating scripts for potential improvements. |
Validate value and throws ValidationError. | Given the following Python 3 function, write the documentation
def validate(self, value, model_instance):
if not self.editable:
# Skip validation for non-editable fields.
return
if self._choices and value:
print(value)
l = value
if type(value) ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a fully qualified URL for the file field including the protocol domain and port. | Can you generate a brief explanation for the following Python 3 code
def get_qualified_file_url(self, field_name='file'):
url = getattr(self, field_name).url
if '://' in url:
# `MEDIA_URL` already contains domain
return url
protocol = getattr(settings, 'PROTOCOL', 'http')... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the URL for viewing a FileNode in the admin. | Given the following Python 3 function, write the documentation
def get_admin_url(self, query_params=None, use_path=False):
if not query_params:
query_params = {}
url = ''
if self.is_top_node():
url = reverse('admin:media_tree_filenode_changelist');
elif use_path... | You are a Python code generator, capable of creating scripts from specifications. |
def get_metadata_display(self, field_formats = {}, escape=True):
"""Returns object metadata that has been selected to be displayed to
users, compiled as a string.
"""
def field_format(field):
if field in field_formats:
return field_formats[field]
r... | Can you write a function in Python 3 where it
returns the object metadata that has been selected to be displayed users compiled as a string. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_caption_formatted(self, field_formats = app_settings.MEDIA_TREE_METADATA_FORMATS, escape=True):
"""Returns object metadata that has been selected to be displayed to
users, compiled as a string including default formatting, for example
bold titles.
You can use this method in temp... | Create a Python 3 function to
return object metadata that has been selected to be displayed as a string including default formatting for example. | As a Python code composer, you craft elegant and concise scripts. |
Returns object metadata suitable for use as the HTML alt attribute. | Can you tell what is the following Python 3 function doing
def alt(self):
if self.override_alt != '' and self.override_alt is not None:
return self.override_alt
elif self.override_caption != '' and self.override_caption is not None:
return self.override_caption
else:
... | You are a Python code generator, capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.