text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set(self, instance, value, **kw):
""" Set Analyses to an AR :param instance: Analysis Request :param value: Single AS UID or a list of dictionaries containin... |
if not isinstance(value, (list, tuple)):
value = [value]
uids = []
for item in value:
uid = None
if isinstance(item, dict):
uid = item.get("uid")
if api.is_uid(value):
uid = item
if uid is None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set(self, instance, value, **kw):
# noqa """Set the value of the uid reference field """ |
ref = []
# The value is an UID
if api.is_uid(value):
ref.append(value)
# The value is a dictionary, get the UIDs.
if u.is_dict(value):
ref = ref.append(value.get("uid"))
# The value is already an object
if api.is_at_content(value):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_dict(self):
""" extract the data of the content and return it as a dictionary """ |
# 1. extract the schema fields
data = self.extract_fields()
# 2. include custom key-value pairs listed in the mapping dictionary
for key, attr in self.attributes.iteritems():
if key in self.ignore:
continue # skip ignores
# fetch the mapped att... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_fields(self):
"""Extract the given fieldnames from the object :returns: Schema name/value mapping :rtype: dict """ |
# get the proper data manager for the object
dm = IDataManager(self.context)
# filter out ignored fields
fieldnames = filter(lambda name: name not in self.ignore, self.keys)
# schema mapping
out = dict()
for fieldname in fieldnames:
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _x_get_physical_path(self):
"""Generate the physical path """ |
path = self.context.getPath()
portal_path = api.get_path(api.get_portal())
if portal_path not in path:
return "{}/{}".format(portal_path, path)
return path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def snake2ucamel(value):
"""Casts a snake_case string to an UpperCamelCase string.""" |
UNDER, LETTER, OTHER = object(), object(), object()
def group_key_function(char):
if char == "_":
return UNDER
if char in string.ascii_letters:
return LETTER
return OTHER
def process_group(idx, key, chars):
if key is LETTER:
return "".join... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ucamel_method(func):
""" Decorator to ensure the given snake_case method is also written in UpperCamelCase in the given namespace. That was mainly written to... |
frame_locals = inspect.currentframe().f_back.f_locals
frame_locals[snake2ucamel(func.__name__)] = func
return func |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_plain_text(fname, encoding="utf-8"):
"""Reads a file as a list of strings.""" |
with io.open(fname, encoding=encoding) as f:
result = list(f)
if result:
if result[-1][-1:] == "\n":
result.append("\n")
else:
result[-1] += "\n"
return [line[:-1] for line in result]
return [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maxcardsearch(A, ve = None):
""" Maximum cardinality search ordering of a sparse chordal matrix. Returns the maximum cardinality search ordering of a symmetr... |
n = A.size[0]
assert A.size[1] == n, "A must be a square matrix"
assert type(A) is spmatrix, "A must be a sparse matrix"
if ve is None:
ve = n-1
else:
assert type(ve) is int and 0<=ve<n,\
"ve must be an integer between 0 and A.size[0]-1"
As = symmetrize(A)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _setup_logging():
"""Setup logging to log to nowhere by default. For details, see: http://docs.python.org/3/howto/logging.html#library-config Internal functi... |
import logging
logger = logging.getLogger('spotify-connect')
handler = logging.NullHandler()
logger.addHandler(handler) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serialized(f):
"""Decorator that serializes access to all decorated functions. The decorator acquires pyspotify's single global lock while calling any wrappe... |
import functools
@functools.wraps(f)
def wrapper(*args, **kwargs):
with _lock:
return f(*args, **kwargs)
if not hasattr(wrapper, '__wrapped__'):
# Workaround for Python < 3.2
wrapper.__wrapped__ = f
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_pocketmod_pages(elements, page_edge_bottom=True, first_page_vertical=True):
""" Creates one or more managers that wraps the given elements into one or mo... |
pages = {
(False, False):[2,3,4,5,1,8,7,6],
(False, True):[4,5,6,7,3,2,1,8],
(True, False):[5,4,3,2,6,7,8,1],
(True, True):[7,6,5,4,8,1,2,3]
}[page_edge_bottom, first_page_vertical]
output = []
num_pages = len(elements)
for index in range(0, num_pages, 8):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close(self):
""" Close the internal epoll file descriptor if it isn't closed :raises OSError: If the underlying ``close(2)`` fails. The error message matches... |
with self._close_lock:
epfd = self._epfd
if epfd >= 0:
self._epfd = -1
close(epfd) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fromfd(cls, fd):
""" Create a new epoll object from a given file descriptor :param fd: A pre-made file descriptor obtained from ``epoll_create(2)`` or ``epol... |
if fd < 0:
_err_closed()
self = cls.__new__()
object.__init__(self)
self._epfd = fd
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(self, fd, eventmask=None):
""" Register a new descriptor :param fd: The descriptor to register. :param eventmask: Bit-mask of events that will be mo... |
if self._epfd < 0:
_err_closed()
if eventmask is None:
eventmask = EPOLLIN | EPOLLOUT | EPOLLPRI
ev = epoll_event()
ev.events = eventmask
ev.data.fd = fd
epoll_ctl(self._epfd, EPOLL_CTL_ADD, fd, byref(ev)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unregister(self, fd):
""" Unregister a previously registered descriptor :param fd: The descriptor to unregister :raises ValueError: If :meth:`closed()` is Tr... |
if self._epfd < 0:
_err_closed()
ev = epoll_event()
try:
epoll_ctl(self._epfd, EPOLL_CTL_DEL, fd, byref(ev))
except OSError as exc:
# Allow fd to be closed, matching Python 3.4
if exc.errno != EBADF:
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modify(self, fd, eventmask):
""" Change the bit-mask of events associated with a previously-registered descriptor. :param fd: The descriptor to modify. :para... |
if self._epfd < 0:
_err_closed()
ev = epoll_event()
ev.events = eventmask
ev.data.fd = fd
epoll_ctl(self._epfd, EPOLL_CTL_MOD, fd, byref(ev)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def poll(self, timeout=-1, maxevents=-1):
""" Poll for events :param timeout: The amount of seconds to wait for events before giving up. The default value, -1, r... |
if self._epfd < 0:
_err_closed()
if timeout != -1:
# 1000 because epoll_wait(2) uses milliseconds
timeout = int(timeout * 1000)
if maxevents == -1:
maxevents = FD_SETSIZE - 1
events = (epoll_event * maxevents)()
num_events = epoll_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate(self, schema_str, xml_valid):
"""Compare the valid information on an xml from given schema. :param str schema_str: content string from schema file. ... |
# TODO: be able to get doc for error given an xsd.
# Changed path to allow have xsd that are imported by others xsd in the
# same library, and not call to SAT page each time that is generated
# a new XML.
with change_path():
path = os.path.join(
os.pa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_xml(self):
"""Set document xml just rendered already validated against xsd to be signed. :params boolean debug_mode: Either if you want the rendered temp... |
cached = StringIO()
document = u''
try:
document = self.template.render(inv=self)
except UndefinedError as ups:
self.ups = ups
# TODO: Here should be called the cleanup 'Just before the validation'.
valid = self.validate(self.schema, document)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_record(uid=None):
"""Get a single record """ |
obj = None
if uid is not None:
obj = get_object_by_uid(uid)
else:
obj = get_object_by_request()
if obj is None:
fail(404, "No object found")
complete = req.get_complete(default=_marker)
if complete is _marker:
complete = True
items = make_items_for([obj], com... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_batched(portal_type=None, uid=None, endpoint=None, **kw):
"""Get batched results """ |
# fetch the catalog results
results = get_search_results(portal_type=portal_type, uid=uid, **kw)
# fetch the batch params from the request
size = req.get_batch_size()
start = req.get_batch_start()
# check for existing complete flag
complete = req.get_complete(default=_marker)
if comp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_info(brain_or_object, endpoint=None, complete=False):
"""Extract the data from the catalog brain or object :param brain_or_object: A single catalog brain... |
# also extract the brain data for objects
if not is_brain(brain_or_object):
brain_or_object = get_brain(brain_or_object)
if brain_or_object is None:
logger.warn("Couldn't find/fetch brain of {}".format(brain_or_object))
return {}
complete = True
# When quer... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_parent_info(brain_or_object, endpoint=None):
"""Generate url information for the parent object :param brain_or_object: A single catalog brain or content ... |
# special case for the portal object
if is_root(brain_or_object):
return {}
# get the parent object
parent = get_parent(brain_or_object)
portal_type = get_portal_type(parent)
resource = portal_type_to_resource(portal_type)
# fall back if no endpoint specified
if endpoint is N... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_children_info(brain_or_object, complete=False):
"""Generate data items of the contained contents :param brain_or_object: A single catalog brain or conten... |
# fetch the contents (if folderish)
children = get_contents(brain_or_object)
def extract_data(brain_or_object):
return get_info(brain_or_object, complete=complete)
items = map(extract_data, children)
return {
"children_count": len(items),
"children": items
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_file_info(obj, fieldname, default=None):
"""Extract file data from a file field :param obj: Content object :type obj: ATContentType/DexterityContentType ... |
# extract the file field from the object if omitted
field = get_field(obj, fieldname)
# get the value with the fieldmanager
fm = IFieldManager(field)
# return None if we have no file data
if fm.get_size(obj) == 0:
return None
out = {
"content_type": fm.get_content_type(o... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_workflow_info(brain_or_object, endpoint=None):
"""Generate workflow information of the assigned workflows :param brain_or_object: A single catalog brain ... |
# ensure we have a full content object
obj = get_object(brain_or_object)
# get the portal workflow tool
wf_tool = get_tool("portal_workflow")
# the assigned workflows of this object
workflows = wf_tool.getWorkflowsFor(obj)
# no worfkflows assigned -> return
if not workflows:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search(**kw):
"""Search the catalog adapter :returns: Catalog search results :rtype: iterable """ |
portal = get_portal()
catalog = ICatalog(portal)
catalog_query = ICatalogQuery(catalog)
query = catalog_query.make_query(**kw)
return catalog(query) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_search_results(portal_type=None, uid=None, **kw):
"""Search the catalog and return the results :returns: Catalog search results :rtype: iterable """ |
# If we have an UID, return the object immediately
if uid is not None:
logger.info("UID '%s' found, returning the object immediately" % uid)
return u.to_list(get_object_by_uid(uid))
# allow to search search for the Plone Site with portal_type
include_portal = False
if u.to_string(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_brain(brain_or_object):
"""Return a ZCatalog brain for the object :param brain_or_object: A single catalog brain or content object :type brain_or_object:... |
if is_brain(brain_or_object):
return brain_or_object
if is_root(brain_or_object):
return brain_or_object
# fetch the brain by UID
uid = get_uid(brain_or_object)
uc = get_tool("uid_catalog")
results = uc({"UID": uid}) or search(query={'UID': uid})
if len(results) == 0:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_field(brain_or_object, name, default=None):
"""Return the named field """ |
fields = get_fields(brain_or_object)
return fields.get(name, default) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_behaviors(brain_or_object):
"""Iterate over all behaviors that are assigned to the object :param brain_or_object: A single catalog brain or content objec... |
obj = get_object(brain_or_object)
if not is_dexterity_content(obj):
fail(400, "Only Dexterity contents can have assigned behaviors")
assignable = IBehaviorAssignable(obj, None)
if not assignable:
return {}
out = {}
for behavior in assignable.enumerateBehaviors():
for nam... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_path(path):
"""Checks if the passed in path is a valid Path within the portal :param path: The path to check :type uid: string :return: True if the path i... |
if not isinstance(path, basestring):
return False
portal_path = get_path(get_portal())
if not path.startswith(portal_path):
return False
obj = get_object_by_path(path)
if obj is None:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_json_value(obj, fieldname, value=_marker, default=None):
"""JSON save value encoding :param obj: Content object :type obj: ATContentType/DexterityContentT... |
# This function bridges the value of the field to a probably more complex
# JSON structure to return to the client.
# extract the value from the object if omitted
if value is _marker:
value = IDataManager(obj).json_data(fieldname)
# convert objects
if isinstance(value, ImplicitAcquis... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_date(thing):
"""Checks if the given thing represents a date :param thing: The object to check if it is a date :type thing: arbitrary object :returns: True... |
# known date types
date_types = (datetime.datetime,
datetime.date,
DateTime)
return isinstance(thing, date_types) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_iso_date(date, default=None):
"""ISO representation for the date object :param date: A date object :type field: datetime/DateTime :returns: The ISO format... |
# not a date
if not is_date(date):
return default
# handle Zope DateTime objects
if isinstance(date, (DateTime)):
return date.ISO8601()
# handle python datetime objects
return date.isoformat() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_contents(brain_or_object):
"""Lookup folder contents for this object. :param brain_or_object: A single catalog brain or content object :type brain_or_obj... |
# Nothing to do if the object is contentish
if not is_folderish(brain_or_object):
return []
# Returning objects (not brains) to make sure we do not miss any child.
# It may happen when children belong to different catalogs and not
# found on 'portal_catalog'.
ret = filter(lambda obj: ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_resource_mapping():
"""Map resources used in the routes to portal types :returns: Mapping of resource->portal_type :rtype: dict """ |
portal_types = get_portal_types()
resources = map(portal_type_to_resource, portal_types)
return dict(zip(resources, portal_types)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resource_to_portal_type(resource):
"""Converts a resource to a portal type :param resource: Resource name as it is used in the content route :type name: stri... |
if resource is None:
return None
resource_mapping = get_resource_mapping()
portal_type = resource_mapping.get(resource.lower())
if portal_type is None:
logger.warn("Could not map the resource '{}' "
"to any known portal type".format(resource))
return portal_ty... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_container_for(portal_type):
"""Returns the single holding container object of this content type :param portal_type: The portal type requested :type porta... |
container_paths = config.CONTAINER_PATHS_FOR_PORTAL_TYPES
container_path = container_paths.get(portal_type)
if container_path is None:
return None
portal_path = get_path(get_portal())
return get_object_by_path("/".join([portal_path, container_path])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_endpoint(brain_or_object, default=DEFAULT_ENDPOINT):
"""Calculate the endpoint for this object :param brain_or_object: A single catalog brain or content ... |
portal_type = get_portal_type(brain_or_object)
resource = portal_type_to_resource(portal_type)
# Try to get the right namespaced endpoint
endpoints = router.DefaultRouter.view_functions.keys()
if resource in endpoints:
return resource # exact match
endpoint_candidates = filter(lambda ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_object_by_record(record):
"""Find an object by a given record Inspects request the record to locate an object :param record: A dictionary representation ... |
# nothing to do here
if not record:
return None
if record.get("uid"):
return get_object_by_uid(record["uid"])
if record.get("path"):
return get_object_by_path(record["path"])
if record.get("parent_path") and record.get("id"):
path = "/".join([record["parent_path"],... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_object_by_path(path):
"""Find an object by a given physical path :param path: The physical path of the object to find :type path: string :returns: Found ... |
# nothing to do here
if not isinstance(path, basestring):
return None
# path must be a string
path = str(path)
portal = get_portal()
portal_path = get_path(portal)
if path == portal_path:
return portal
if path.startswith(portal_path):
segments = path.split("... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_member_ids():
"""Return all member ids of the portal. """ |
pm = get_tool("portal_membership")
member_ids = pm.listMemberIds()
# How can it be possible to get member ids with None?
return filter(lambda x: x, member_ids) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_objects(uid=None):
"""Find the object by its UID 1. get the object from the given uid 2. fetch objects specified in the request parameters 3. fetch obje... |
# The objects to cut
objects = []
# get the object by the given uid or try to find it by the request
# parameters
obj = get_object_by_uid(uid) or get_object_by_request()
if obj:
objects.append(obj)
else:
# no uid -> go through the record items
records = req.get_req... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_target_container(portal_type, record):
"""Locates a target container for the given portal_type and record :param record: The dictionary representation o... |
portal_type = portal_type or record.get("portal_type")
container = get_container_for(portal_type)
if container:
return container
parent_uid = record.pop("parent_uid", None)
parent_path = record.pop("parent_path", None)
target = None
# Try to find the target object
if parent_u... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_object(container, portal_type, **data):
"""Creates an object slug :returns: The new created content object :rtype: object """ |
if "id" in data:
# always omit the id as senaite LIMS generates a proper one
id = data.pop("id")
logger.warn("Passed in ID '{}' omitted! Senaite LIMS "
"generates a proper ID for you" .format(id))
try:
# Special case for ARs
# => return immediately ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_analysisrequest(container, **data):
"""Create a minimun viable AnalysisRequest :param container: A single folderish catalog brain or content object :t... |
container = get_object(container)
request = req.get_request()
# we need to resolve the SampleType to a full object
sample_type = data.get("SampleType", None)
if sample_type is None:
fail(400, "Please provide a SampleType")
# TODO We should handle the same values as in the DataManager f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_object_with_data(content, record):
"""Update the content with the record data :param content: A single folderish catalog brain or content object :type... |
# ensure we have a full content object
content = get_object(content)
# get the proper data manager
dm = IDataManager(content)
if dm is None:
fail(400, "Update for this object is not allowed")
# Iterate through record items
for k, v in record.items():
try:
suc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_object(brain_or_object, data):
"""Validate the entire object :param brain_or_object: A single catalog brain or content object :type brain_or_object:... |
obj = get_object(brain_or_object)
# Call the validator of AT Content Types
if is_at_content(obj):
return obj.validate(data=data)
return {} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deactivate_object(brain_or_object):
"""Deactivate the given object :param brain_or_object: A single catalog brain or content object :type brain_or_object: AT... |
obj = get_object(brain_or_object)
# we do not want to delete the site root!
if is_root(obj):
fail(401, "Deactivating the Portal is not allowed")
try:
do_transition_for(brain_or_object, "deactivate")
except Unauthorized:
fail(401, "Not allowed to deactivate object '%s'" % obj... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_settings_by_keyword(keyword=None):
"""Get the settings associated to the specified keyword or, if keyword is None, get all the settings. :param keyword: ... |
settings = []
if keyword is None:
# iterate over all the schemas to return all settings
for key, ischemas in CONTROLPANEL_INTERFACE_MAPPING.items():
settings_from_ifaces = map(get_settings_from_interface, ischemas)
settings_from_key = {k: v for d in settings_from_ifaces ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_settings_from_interface(iface):
"""Get the configuration settings associated to a list of schema interfaces :param iface: The schema interface from which... |
settings = {}
schema_id = iface.getName()
settings[schema_id] = {}
schema = getAdapter(api.get_portal(), iface)
for setting in getFieldNames(iface):
value = getattr(schema, setting, None)
if is_json_serializable(value):
settings[schema_id][setting] = value
return set... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calculate_columns(self):
"""Assuming the number of rows is constant, work out the best number of columns to use.""" |
self.cols = int(math.ceil(len(self.elements) / float(self.rows))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_rule(self, start_col, start_row, end_col, end_row, width=0.5, color=(0,0,0)):
"""Adds a rule to the grid. The row and column numbers are those on the top... |
self.rules.append(
(start_col, start_row, end_col, end_row, width, color)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _compile_dimension_size(self, base_index, array, property, sized_elements):
"""Build one set of col widths or row heights.""" |
sort_index = base_index + 2
sized_elements.sort(key=lambda x: x[sort_index])
for element_data in sized_elements:
start, end = element_data[base_index], element_data[sort_index]
end += start
element, size = element_data[4:6]
# Find the total curre... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_minimum_size(self, data):
"""Finds the minimum size of the grid.""" |
# Gat a list of elements with their sizes, so we don't have to
# recalculate that each time.
sized_elements = [
(col, row, cols, rows, element, element.get_minimum_size(data))
for col, row, cols, rows, element in self.elements
]
# Create the heights... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render(self, rect, data):
"""Draws the cells in grid.""" |
size = self.get_minimum_size(data)
# Find how much extra space we have.
extra_width = rect.w - size.x
extra_height = rect.h - size.y
# Distribute the extra space into the correct rows and columns.
if self.scaling_col is None or not 0 <= self.scaling_col < self.cols:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_block(name, data, newline="\n"):
""" First block in a list of one line strings containing reStructuredText data. The result is as a joined string with th... |
lines = itertools.dropwhile(not_eq(BLOCK_START % name), data)
gen = itertools.takewhile(not_eq(BLOCK_END % name), tail(lines))
return gen if newline is None else newline.join(gen) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all_but_blocks(names, data, newline="\n", remove_empty_next=True, remove_comments=True):
""" Multiline string from a list of strings data, removing every blo... |
@allow_implicit_stop
def remove_blocks(name, iterable):
start, end = BLOCK_START % name, BLOCK_END % name
it = iter(iterable)
while True:
line = next(it)
while line != start:
yield line
line = next(it)
it = tail(itertoo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def commentless(data):
""" Generator that removes from a list of strings the double dot reStructuredText comments and its contents based on indentation, removing... |
it = iter(data)
while True:
line = next(it)
while ":" in line or not line.lstrip().startswith(".."):
yield line
line = next(it)
indent = indent_size(line)
it = itertools.dropwhile(lambda el: indent_size(el) > indent
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __tdfs(j, k, head, next, post, stack):
""" Depth-first search and postorder of a tree rooted at node j. """ |
top = 0
stack[0] = j
while (top >= 0):
p = stack[top]
i = head[p]
if i == -1:
top -= 1
post[k] = p
k += 1
else:
head[p] = next[i]
top += 1
stack[top] = i
return k |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post_order(parent):
""" Post order a forest. """ |
n = len(parent)
k = 0
p = matrix(0,(n,1))
head = matrix(-1,(n,1))
next = matrix(0,(n,1))
stack = matrix(0,(n,1))
for j in range(n-1,-1,-1):
if (parent[j] == j): continue
next[j] = head[parent[j]]
head[parent[j]] = j
for j in range(n):
if (parent[j] != ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def etree(A):
""" Compute elimination tree from upper triangle of A. """ |
assert isinstance(A,spmatrix), "A must be a sparse matrix"
assert A.size[0] == A.size[1], "A must be a square matrix"
n = A.size[0]
cp,ri,_ = A.CCS
parent = matrix(0,(n,1))
w = matrix(0,(n,1))
for k in range(n):
parent[k] = k
w[k] = -1
for p in range(cp[k],cp[k+1])... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __leaf(i, j, first, maxfirst, prevleaf, ancestor):
""" Determine if j is leaf of i'th row subtree. """ |
jleaf = 0
if i<=j or first[j] <= maxfirst[i]: return -1, jleaf
maxfirst[i] = first[j]
jprev = prevleaf[i]
prevleaf[i] = j
if jprev == -1: jleaf = 1
else: jleaf = 2
if jleaf == 1: return i, jleaf
q = jprev
while q != ancestor[q]: q = ancestor[q]
s = jprev
while s != q:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def counts(A, parent, post):
""" Compute column counts. """ |
n = A.size[0]
colcount = matrix(0,(n,1))
ancestor = matrix(range(n),(n,1))
maxfirst = matrix(-1,(n,1))
prevleaf = matrix(-1,(n,1))
first = matrix(-1,(n,1))
for k in range(n):
j = post[k]
if first[j] == -1:
colcount[j] = 1
else:
colcount[j... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pothen_sun(par, post, colcount):
""" Find supernodes and supernodal etree. ARGUMENTS par parent array post array with post ordering colcount array with colum... |
n = len(par)
flag = matrix(-1, (n, 1))
snpar = matrix(-1, (n, 1))
snodes = n
ch = {}
for j in post:
if par[j] in ch: ch[par[j]].append(j)
else: ch[par[j]] = [j]
mdeg = colcount[j] - 1
if par[j] != j:
if mdeg == colcount[par[j]] and flag[p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def supernodes(par, post, colcount):
""" Find supernodes. ARGUMENTS par parent array post array with post ordering colcount array with column counts RETURNS snod... |
snpar, flag = pothen_sun(par, post, colcount)
n = len(par)
N = len(snpar)
snode = matrix(0, (n,1))
snptr = matrix(0, (N+1,1))
slist = [[] for i in range(n)]
for i in range(n):
f = flag[i]
if f < 0:
slist[i].append(i)
else:
slist[f].append(i)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def amalgamate(colcount, snode, snptr, snpar, snpost, merge_function):
""" Supernodal amalgamation. amalgamate(colcount, snode, snptr, snpar, snpost, merge_funct... |
N = len(snpost)
ch = {}
for j in snpost:
if snpar[j] in ch: ch[snpar[j]].append(j)
else: ch[snpar[j]] = [j]
snlist = [snode[snptr[k]:snptr[k+1]] for k in range(N)]
snpar_ = +snpar
colcount_ = +colcount
Ns = N
for k in snpost:
if snpar_[k] != k:
colk... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def embed(A, colcount, snode, snptr, snpar, snpost):
""" Compute filled pattern. colptr, rowidx = embed(A, colcount, snode, snptr, snpar, snpost) PURPOSE Compute... |
Alo = tril(A)
cp,ri,_ = Alo.CCS
N = len(snpar)
# colptr for compressed cholesky factor
colptr = matrix(0,(N+1,1))
for k in range(N):
colptr[k+1] = colptr[k] + colcount[snode[snptr[k]]]
rowidx = matrix(-1,(colptr[-1],1))
cnnz = matrix(0,(N,1))
# compute compressed sparse r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def relative_idx(colptr, rowidx, snptr, snpar):
""" Compute relative indices of update matrices in frontal matrix of parent. """ |
relptr = matrix(0, (len(snptr),1))
relidx = matrix(-1, (colptr[-1],1))
def lfind(a,b):
i = 0
ret = +a
for k in range(len(a)):
while a[k] != b[i]: i += 1
ret[k] = i
i += 1
return ret
for k in range(len(snpar)):
p = sn... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def peo(A, p):
""" Checks whether an ordering is a perfect elmimination order. Returns `True` if the permutation :math:`p` is a perfect elimination order for a C... |
n = A.size[0]
assert type(A) == spmatrix, "A must be a sparse matrix"
assert A.size[1] == n, "A must be a square matrix"
assert len(p) == n, "length of p must be equal to the order of A"
if isinstance(p, list): p = matrix(p)
As = symmetrize(A)
cp,ri,_ = As.CCS
# compute inverse ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nnz(self):
""" Returns the number of lower-triangular nonzeros. """ |
nnz = 0
for k in range(len(self.snpost)):
nn = self.snptr[k+1]-self.snptr[k]
na = self.relptr[k+1]-self.relptr[k]
nnz += nn*(nn+1)/2 + nn*na
return nnz |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cliques(self, reordered = True):
""" Returns a list of cliques """ |
if reordered:
return [list(self.snrowidx[self.sncolptr[k]:self.sncolptr[k+1]]) for k in range(self.Nsn)]
else:
return [list(self.__p[self.snrowidx[self.sncolptr[k]:self.sncolptr[k+1]]]) for k in range(self.Nsn)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def separators(self, reordered = True):
""" Returns a list of separator sets """ |
if reordered:
return [list(self.snrowidx[self.sncolptr[k]+self.snptr[k+1]-self.snptr[k]:self.sncolptr[k+1]]) for k in range(self.Nsn)]
else:
return [list(self.__p[self.snrowidx[self.sncolptr[k]+self.snptr[k+1]-self.snptr[k]:self.sncolptr[k+1]]]) for k in range(self.Nsn)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def supernodes(self, reordered = True):
""" Returns a list of supernode sets """ |
if reordered:
return [list(self.snode[self.snptr[k]:self.snptr[k+1]]) for k in range(self.Nsn)]
else:
return [list(self.__p[self.snode[self.snptr[k]:self.snptr[k+1]]]) for k in range(self.Nsn)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def diag(self, reordered = True):
""" Returns a vector with the diagonal elements of the matrix. """ |
sncolptr = self.symb.sncolptr
snptr = self.symb.snptr
snode = self.symb.snode
blkptr = self.symb.blkptr
D = matrix(0.0,(self.symb.n,1))
for k in range(self.symb.Nsn):
nn = snptr[k+1]-snptr[k]
w = sncolptr[k+1]-sncolptr[k]
for ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_deep_link_url(self, data=None, alias=None, type=0, duration=None, identity=None, tags=None, campaign=None, feature=None, channel=None, stage=None, skip... |
url = "/v1/url"
method = "POST"
params = {}
# Check Params
self._check_param("data", data, params, type=dict)
self._check_param("alias", alias, params, type=(binary_type, text_type))
self._check_param("type", type, params, type=int, lte=2, gte=0)
self._c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_deep_linking_urls(self, url_params):
""" Bulk Creates Deep Linking URLs See the URL https://dev.branch.io/references/http_api/#bulk-creating-deep-link... |
url = "/v1/url/bulk/%s" % self.branch_key
method = "POST"
# Checks params
self._check_param(value=url_params, type=list, sub_type=dict, optional=False)
return self.make_api_call(method, url, json_params=url_params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_enum(lib_prefix, enum_prefix=''):
"""Class decorator for automatically adding enum values. The values are read directly from the :attr:`spotify.lib` CFF... |
def wrapper(cls):
for attr in dir(lib):
if attr.startswith(lib_prefix):
name = attr.replace(lib_prefix, enum_prefix)
cls.add(name, getattr(lib, attr))
return cls
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_bytes(value):
"""Converts bytes, unicode, and C char arrays to bytes. Unicode strings are encoded to UTF-8. """ |
if isinstance(value, text_type):
return value.encode('utf-8')
elif isinstance(value, ffi.CData):
return ffi.string(value)
elif isinstance(value, binary_type):
return value
else:
raise ValueError('Value must be text, bytes, or char[]') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_bytes_or_none(value):
"""Converts C char arrays to bytes and C NULL values to None.""" |
if value == ffi.NULL:
return None
elif isinstance(value, ffi.CData):
return ffi.string(value)
else:
raise ValueError('Value must be char[] or NULL') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_unicode(value):
"""Converts bytes, unicode, and C char arrays to unicode strings. Bytes and C char arrays are decoded from UTF-8. """ |
if isinstance(value, ffi.CData):
return ffi.string(value).decode('utf-8')
elif isinstance(value, binary_type):
return value.decode('utf-8')
elif isinstance(value, text_type):
return value
else:
raise ValueError('Value must be text, bytes, or char[]') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_unicode_or_none(value):
"""Converts C char arrays to unicode and C NULL values to None. C char arrays are decoded from UTF-8. """ |
if value == ffi.NULL:
return None
elif isinstance(value, ffi.CData):
return ffi.string(value).decode('utf-8')
else:
raise ValueError('Value must be char[] or NULL') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on(self, event, listener, *user_args):
"""Register a ``listener`` to be called on ``event``. The listener will be called with any extra arguments passed to :... |
self._listeners[event].append(
_Listener(callback=listener, user_args=user_args)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def off(self, event=None, listener=None):
"""Remove a ``listener`` that was to be called on ``event``. If ``listener`` is :class:`None`, all listeners for the gi... |
if event is None:
events = self._listeners.keys()
else:
events = [event]
for event in events:
if listener is None:
self._listeners[event] = []
else:
self._listeners[event] = [
l for l in self._li... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def emit(self, event, *event_args):
"""Call the registered listeners for ``event``. The listeners will be called with any extra arguments passed to :meth:`emit` ... |
listeners = self._listeners[event][:]
for listener in listeners:
args = list(event_args) + list(listener.user_args)
result = listener.callback(*args)
if result is False:
self.off(event, listener.callback) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def num_listeners(self, event=None):
"""Return the number of listeners for ``event``. Return the total number of listeners for all events on this object if ``eve... |
if event is not None:
return len(self._listeners[event])
else:
return sum(len(l) for l in self._listeners.values()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call(self, event, *event_args):
"""Call the single registered listener for ``event``. The listener will be called with any extra arguments passed to :meth:`c... |
# XXX It would be a lot better for debugging if this error was raised
# when registering the second listener instead of when the event is
# emitted.
assert self.num_listeners(event) == 1, (
'Expected exactly 1 event listener, found %d listeners' %
self.num_listen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(cls, name, value):
"""Add a name-value pair to the enumeration.""" |
attr = cls(value)
attr._name = name
setattr(cls, name, attr) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_minimum_size(self, data):
""" Minimum height is the total height + margins, minimum width is the largest width. """ |
min_width = 0
height = 0
for element in self.elements:
size = element.get_minimum_size(data)
min_width = max(min_width, size.x)
height += size.y
height += (len(self.elements)-1)*self.margin
return datatypes.Point(min_width, height) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_minimum_size(self, data):
"""Minimum width is the total width + margins, minimum height is the largest height.""" |
width = 0
min_height = 0
for element in self.elements:
size = element.get_minimum_size(data)
min_height = max(min_height, size.y)
width += size.x
width += (len(self.elements)-1)*self.margin
return datatypes.Point(width, min_height) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render(self, rect, data):
"""Draws the columns.""" |
num_elements = len(self.elements)
col_width = (rect.w-self.margin*(num_elements-1)) / float(num_elements)
x = rect.x
for element in self.elements:
if element is not None:
element.render(datatypes.Rectangle(
x, rect.y, col_width, rect.h... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_minimum_size(self, data):
"""The minimum height is the number of rows multiplied by the tallest row.""" |
min_width = 0
min_height = 0
for element in self.elements:
size = (
datatypes.Point(0, 0) if element is None
else element.get_minimum_size(data)
)
min_height = max(min_height, size.y)
min_width = max(min_width, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_import(self, name, compilation, rule):
""" Re-implementation of the core Sass import mechanism, which looks for files using the staticfiles storage an... |
original_path = PurePath(name)
search_exts = list(compilation.compiler.dynamic_extensions)
if original_path.suffix and original_path.suffix in search_exts:
basename = original_path.stem
else:
basename = original_path.name
if original_path.is_absolute():... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parser_help_text(help_text):
"""Takes the help text supplied as a doc string and extraxts the description and any param arguments.""" |
if help_text is None:
return None, {}
main_text = ''
params_help = {}
for line in help_text.splitlines():
line = line.strip()
match = re.search(r':\s*param\s*(?P<param>\w+)\s*:(?P<help>.*)$', line)
if match:
params_help[match.group('param')] = match.group('... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calculate_default_type(arg, has_default, default_value, params_help):
"""This function looks at the default value and returns the type that should be supplie... |
positional = True
arg_params = {}
arg_name = arg
# Check to see if we have help text for this argument
try:
arg_params['help'] = params_help[arg_name]
except KeyError:
pass
# If we have a default value, then this is not positional
if has_default:
positional = F... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def function_parser(function, parser):
"""This function parses a function and adds its arguments to the supplied parser""" |
# Store the function pointer on the parser for later use
parser.set_defaults(func=function)
# Get the help text and parse it for params
help_text = inspect.getdoc(function)
main_text, params_help = parser_help_text(help_text)
# Get the function information
args, varargs, keywords, defaul... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def urijoin(base, ref, strict=False):
"""Convert a URI reference relative to a base URI to its target URI string. """ |
if isinstance(base, type(ref)):
return urisplit(base).transform(ref, strict).geturi()
elif isinstance(base, bytes):
return urisplit(base.decode()).transform(ref, strict).geturi()
else:
return urisplit(base).transform(ref.decode(), strict).geturi() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_response(self, response):
"""Send a unicode object as reply to the most recently-issued command """ |
response_bytes = response.encode(config.CODEC)
log.debug("About to send reponse: %r", response_bytes)
self.socket.send(response_bytes) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.