output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Returns a matcher to match the subscribe connection status. | Can you generate the documentation for the following Python 3 function
def subscribe_state_matcher(self, container, connected = True):
'''
Return a matcher to match the subscribe connection status.
:param container: a routine container. NOTICE: this method is not a routine.
... | As a python code expert, you are capable of creating scripts from specifications. |
def _escape_path(key):
'''
Replace '/', '\\' in key
'''
return _tobytes(key).replace(b'$', b'$_').replace(b'/', b'$+').replace(b'\\', b'$$') | Write a Python 3 function for
escaping a path in a bytestring. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Reassemble partial options to options returns a list of dhcp_option objects | How would you explain what the following Python 3 function does
def reassemble_options(payload):
'''
Reassemble partial options to options, returns a list of dhcp_option
DHCP options are basically `|tag|length|value|` structure. When an
option is longer than 255 bytes, it can be splitted into multi... | You are a Python code analyst, evaluating scripts for potential improvements. |
Builds the dhcp options for a given message. | Can you tell what is the following Python 3 function doing
def build_options(payload, options, maxsize = 576, overload = OVERLOAD_FILE | OVERLOAD_SNAME, allowpartial = True):
'''
Split a list of options
This is the reverse operation of `reassemble_options`, it splits `dhcp_option` into
`dhcp_option... | You are a Python code analyst, evaluating scripts for potential improvements. |
def create_option_from_value(tag, value):
"""
Set DHCP option with human friendly value
"""
dhcp_option.parser()
fake_opt = dhcp_option(tag = tag)
for c in dhcp_option.subclasses:
if c.criteria(fake_opt):
if hasattr(c, '_parse_from_value'):
return c(tag = tag,... | Can you write a function in Python 3 where it
creates DHCP option from value. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Try to create dhcp_options from human friendly values ignoring invalid values ignoring invalid values generateNone = True | How would you explain what the following Python 3 function does
def create_dhcp_options(input_dict, ignoreError = False, generateNone = False):
retdict = {}
for k,v in dict(input_dict).items():
try:
if generateNone and v is None:
retdict[k] = None
else:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Decorator to create indices for an event class. Every event class must be decorated with this decorator. | Here you have a function in Python 3, explain what it does
def with_indices(*args):
'''
Create indices for an event class. Every event class must be decorated with this decorator.
'''
def decorator(cls):
for c in cls.__bases__:
if hasattr(c, '_indicesNames'):
cls._cla... | You are a Python code architect, reviewing and designing scalable and efficient code |
def two_way_difference(self, b, extra_add = (), extra_remove = ()):
"""
Return (self - b, b - self)
"""
if self is b:
return ((), ())
if isinstance(b, DiffRef_):
extra_remove = extra_remove + b.add
b = b.origin
if extra_add == extra_rem... | Write a Python 3 script to
return two way difference between two sets of keys. | As a python code expert, you are capable of creating scripts from specifications. |
returns the proper name to match
| How would you explain what the following Python 3 function does
def getTypename(cls):
'''
:returns: return the proper name to match
'''
if cls is Event:
return None
else:
for c in cls.__bases__:
if issubclass(c, Event):
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Create a new EventMatcher object for the given class. | Make a summary of the following Python 3 code
def createMatcher(cls, *args, **kwargs):
'''
:param _ismatch: user-defined function ismatch(event) for matching test
:param \*args: indices
:param \*\*kwargs: index_name=index_value for matching criteria
'''
if kwargs and not ... | As a python code expert, you are capable of creating scripts from specifications. |
async def limit(self, use = 1):
"""
Acquire "resources", wait until enough "resources" are acquired. For each loop,
`limit` number of "resources" are permitted.
:param use: number of "resouces" to be used.
:return: True if is limited
"""
c = self... | Create a Python 3 function for
limiting the number of resources acquired by the current task. | As a python code expert, you are capable of creating scripts from specifications. |
async def run_task(self, container, task, newthread = False):
"Run task() in task pool. Raise an exception or return the return value"
e = TaskEvent(self, task=task, newthread = newthread)
await container.wait_for_send(e)
ev = await TaskDoneEvent.createMatcher(e)
if hasattr(ev, '... | Implement a Python 3 function for
running task in task pool. Raise an exception or return the return value | You are a Python code analyst, evaluating scripts for potential improvements. |
Run generator gentask() in task pool yield customized events | Explain what the following Python 3 code does
async def run_gen_task(self, container, gentask, newthread = True):
"Run generator gentask() in task pool, yield customized events"
e = TaskEvent(self, gen_task = gentask, newthread = newthread)
await container.wait_for_send(e)
ev = await Tas... | You are a Python code analyst, evaluating scripts for potential improvements. |
async def run_async_task(self, container, asynctask, newthread = True):
"Run asynctask(sender) in task pool, call sender(events) to send customized events, return result"
e = TaskEvent(self, async_task = asynctask, newthread = newthread)
await container.wait_for_send(e)
ev = await TaskDo... | Implement a Python 3 function for
running asynctask in task pool call sender ( events to send customized events return result | You are a Python code architect, reviewing and designing scalable and efficient code |
Wait for lock acquire | Given the following Python 3 function, write the documentation
async def lock(self, container = None):
"Wait for lock acquire"
if container is None:
container = RoutineContainer.get_container(self.scheduler)
if self.locked:
pass
elif self.lockroutine:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Try to acquire lock and return True ; if cannot acquire the lock at this moment return False. | Can you generate the documentation for the following Python 3 function
def trylock(self):
"Try to acquire lock and return True; if cannot acquire the lock at this moment, return False."
if self.locked:
return True
if self.lockroutine:
return False
waiter = self.sc... | As a Python code composer, you craft elegant and concise scripts. |
def beginlock(self, container):
"Start to acquire lock in another routine. Call trylock or lock later to acquire the lock. Call unlock to cancel the lock routine"
if self.locked:
return True
if self.lockroutine:
return False
self.lockroutine = container.subroutine... | Implement a function in Python 3 to
start to acquire lock in another routine. Call trylock or lock later to acquire the lock. Call unlock to cancel the lock routine | As a Python code composer, you craft elegant and concise scripts. |
Create the subqueue for this lock. | Can you generate a brief explanation for the following Python 3 code
def create(self):
self.queue = self.scheduler.queue.addSubQueue(self.priority, LockEvent.createMatcher(self.context, self.key),
maxdefault = self.size, defaultQueueClass = CBQueue.AutoClassQueue.initHel... | As a python code expert, you are capable of creating scripts from specifications. |
Destroy the created subqueue | How would you explain what the following Python 3 function does
async def destroy(self, container = None):
if container is None:
container = RoutineContainer(self.scheduler)
if self.queue is not None:
await container.syscall_noreturn(syscall_removequeue(self.scheduler.queue, self... | As a Python code composer, you craft elegant and concise scripts. |
Send a shutdown event to the scheduler. | Here you have a function in Python 3, explain what it does
async def shutdown(self, force = False, connmark = -1):
'''
Can call without delegate
'''
if connmark is None:
connmark = self.connmark
self.scheduler.emergesend(ConnectionControlEvent(self, ConnectionControlE... | You are a Python code generator, capable of creating scripts from specifications. |
async def reconnect(self, force = True, connmark = None):
'''
Can call without delegate
'''
if connmark is None:
connmark = self.connmark
self.scheduler.emergesend(ConnectionControlEvent(self, ConnectionControlEvent.RECONNECT, force, connmark)) | Create a Python 3 function for
reconnecting to the next available session. | You are a Python code generator, capable of creating scripts from specifications. |
async def reset(self, force = True, connmark = None):
'''
Can call without delegate
'''
if connmark is None:
connmark = self.connmark
self.scheduler.emergesend(ConnectionControlEvent(self, ConnectionControlEvent.RESET, force, connmark)) | Write a Python 3 script for
resetting the internal state of the object. | You are a Python code generator, capable of creating scripts from specifications. |
async def write(self, event, ignoreException = True):
'''
Can call without delegate
'''
connmark = self.connmark
if self.connected:
def _until():
if not self.connected or self.connmark != connmark:
return True
r = await ... | Can you implement a function in Python 3 that
writes an event to the broker. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Send a shutdown event to the scheduler. | Here you have a function in Python 3, explain what it does
async def shutdown(self, connmark = -1):
'''
Can call without delegate
'''
if connmark is None:
connmark = self.connmark
self.scheduler.emergesend(ConnectionControlEvent(self, ConnectionControlEvent.SHUTDOWN, ... | As a Python code composer, you craft elegant and concise scripts. |
async def stoplisten(self, connmark = -1):
'''
Can call without delegate
'''
if connmark is None:
connmark = self.connmark
self.scheduler.emergesend(ConnectionControlEvent(self, ConnectionControlEvent.STOPLISTEN, True, connmark)) | Can you create a Python 3 function that
stops listens for a specific object. | As a Python code composer, you craft elegant and concise scripts. |
Start listening for a specific object. | Make a summary of the following Python 3 code
async def startlisten(self, connmark = -1):
'''
Can call without delegate
'''
if connmark is None:
connmark = self.connmark
self.scheduler.emergesend(ConnectionControlEvent(self, ConnectionControlEvent.STARTLISTEN, True, c... | You are a Python code architect, reviewing and designing scalable and efficient code |
Use `sys.argv` for starting parameters. This is the entry-point of `vlcp-start` | Can you generate the documentation for the following Python 3 function
def default_start():
(config, daemon, pidfile, startup, fork) = parsearg()
if config is None:
if os.path.isfile('/etc/vlcp.conf'):
config = '/etc/vlcp.conf'
else:
print('/etc/vlcp.conf is not found; st... | As a Python code analyst, you investigate and solve complex coding mysteries |
def close(self):
"Stop the output stream, but further download will still perform"
if self.stream:
self.stream.close(self.scheduler)
self.stream = None | Write a Python 3 function for
stopping the output stream but further download will still perform | You are a Python code generator, capable of creating scripts from specifications. |
async def shutdown(self):
"Force stop the output stream, if there are more data to download, shutdown the connection"
if self.stream:
if not self.stream.dataeof and not self.stream.dataerror:
self.stream.close(self.scheduler)
await self.connection.shutdown()
... | Write a Python 3 script to
force stop the output stream if there are more data to download shutdown the connection | As a Python code translator, you convert algorithms and pseudocode into Python. |
Create a new physical network of the specified type. | Can you tell what is the following Python 3 function doing
def createphysicalnetwork(type, create_processor = partial(default_processor, excluding=('id', 'type')),
reorder_dict = default_iterate_dict):
"""
:param type: physical network type
:param create_processor:... | You are a Python code generator, capable of creating scripts from specifications. |
Returns a walker that deletes all physical network in the virtual network. | Can you generate the documentation for the following Python 3 function
def deletephysicalnetwork(check_processor = default_physicalnetwork_delete_check,
reorder_dict = default_iterate_dict):
"""
:param check_processor: check_processor(physicalnetwork, physicalnetworkmap, walk, wr... | As a python code expert, you are capable of creating scripts from specifications. |
def createphysicalport(create_processor = partial(default_processor, excluding=('vhost', 'systemid',
'bridge', 'name',
'physicalnetwork')),
... | Create a Python 3 function to
create a new PhysicalPort object. | As a Python code analyst, you investigate and solve complex coding mysteries |
This function deletes a physicalport from the database. | Here you have a function in Python 3, explain what it does
def deletephysicalport(check_processor=_false_processor,
reorder_dict = default_iterate_dict):
"""
:param check_processor: check_processor(physicalport, physicalnetwork, physicalnetworkmap,
walk, write ... | As a Python code analyst, you investigate and solve complex coding mysteries |
def createlogicalnetwork(create_processor = partial(default_processor, excluding=('id', 'physicalnetwork')),
reorder_dict = default_iterate_dict):
"""
:param create_processor: create_processor(logicalnetwork, logicalnetworkmap, physicalnetwork,
physicalnetwo... | Write a Python 3 function for
creating a new LogicalNetwork object and return it. | As a python code expert, you are capable of creating scripts from specifications. |
def deletelogicalnetwork(check_processor=default_logicalnetwork_delete_check,
reorder_dict = default_iterate_dict):
"""
:param check_processor: check_processor(logicalnetwork, logicalnetworkmap,
physicalnetwork, physicalnetworkmap,
... | How would you implement a function in Python 3 that
returns a walker that deletes the logicalnetwork from the logmap and physicalnetworkmap. | You are a Python code architect, reviewing and designing scalable and efficient code |
def updateobjects(self, updatedvalues):
"""
Force a update notification on specified objects, even if they are not actually updated
in ObjectDB
"""
if not self._updatedset:
self.scheduler.emergesend(FlowUpdaterNotification(self, FlowUpdaterNotification.DATAUPDATED))
... | Can you create a Python 3 function that
forces an update notification on specified objects even if they are not actually updated in the DB. | As a Python code composer, you craft elegant and concise scripts. |
Coroutine calling updateflow for all flow updates. | Here you have a function in Python 3, explain what it does
async def _flowupdater(self):
lastresult = set(v for v in self._savedresult if v is not None and not v.isdeleted())
flowupdate = FlowUpdaterNotification.createMatcher(self, FlowUpdaterNotification.FLOWUPDATE)
while True:
curr... | You are a Python code generator, capable of creating scripts from specifications. |
def syscall_clearqueue(queue):
'''
Clear a queue
'''
def _syscall(scheduler, processor):
qes, qees = queue.clear()
events = scheduler.queue.unblockqueue(queue)
for e in events:
scheduler.eventtree.remove(e)
for e in qes:
processor(e)
for e ... | Create a Python 3 function for
clearing a queue and call processor on all events in it | As a Python code composer, you craft elegant and concise scripts. |
def syscall_removequeue(queue, index):
'''
Remove subqueue `queue[index]` from queue.
'''
def _syscall(scheduler, processor):
events = scheduler.queue.unblockqueue(queue[index])
for e in events:
scheduler.eventtree.remove(e)
qes, qees = queue.removeSubQueue(index)
... | Implement a function in Python 3 to
remove subqueue from queue. | As a Python code analyst, you investigate and solve complex coding mysteries |
Clear the subqueue queue [ index and remove it from queue.
| Explain what the following Python 3 code does
def syscall_clearremovequeue(queue, index):
'''
Clear the subqueue `queue[index]` and remove it from queue.
'''
def _syscall(scheduler, processor):
qes, qees = queue[index].clear()
events = scheduler.queue.unblockqueue(queue[index])
f... | As a Python code composer, you craft elegant and concise scripts. |
Register an iterator that accepts send method
| Here you have a function in Python 3, explain what it does
def register(self, matchers, runnable):
'''
Register an iterator(runnable) to scheduler and wait for events
:param matchers: sequence of EventMatchers
:param runnable: an iterator that accept send method
... | As a python code expert, you are capable of creating scripts from specifications. |
Unregisters an iterator that accepts send method
yizi | How would you explain what the following Python 3 function does
def unregister(self, matchers, runnable):
'''
Unregister an iterator(runnable) and stop waiting for events
:param matchers: sequence of EventMatchers
:param runnable: an iterator that accept send method
... | As a python code expert, you are capable of creating scripts from specifications. |
Unregisters all matches and detach the runnable. Automatically called when runnable returns StopIteration. | Make a summary of the following Python 3 code
def unregisterall(self, runnable):
'''
Unregister all matches and detach the runnable. Automatically called when runnable returns StopIteration.
'''
if runnable in self.registerIndex:
for m in self.registerIndex[runnable]:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def ignore(self, matcher):
'''
Unblock and ignore the matched events, if any.
'''
events = self.eventtree.findAndRemove(matcher)
for e in events:
self.queue.unblock(e)
e.canignore = True | Write a Python 3 script to
unblock and ignore the matched events | As a Python code composer, you craft elegant and concise scripts. |
Send quit event to quit the main loop | Can you generate the documentation for the following Python 3 function
def quit(self, daemononly = False):
'''
Send quit event to quit the main loop
'''
if not self.quitting:
self.quitting = True
self.queue.append(SystemControlEvent(SystemControlEvent.QUIT, daemon... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def setTimer(self, start, interval = None):
'''
Generate a TimerEvent on specified time
:param start: offset for time from now (seconds), or datetime for a fixed time
:param interval: if not None, the timer is regenerated by interval seconds.
:returns: ... | Implement a function in Python 3 to
generate a TimerEvent on the specified time. | You are a Python code generator, capable of creating scripts from specifications. |
register a polling file descriptor fd | Make a summary of the following Python 3 code
def registerPolling(self, fd, options = POLLING_IN|POLLING_OUT, daemon = False):
'''
register a polling file descriptor
:param fd: file descriptor or socket object
:param options: bit mask flags. Polling object should ignore... | You are a Python code generator, capable of creating scripts from specifications. |
Sets the runnable to be a daemon. | How would you explain what the following Python 3 function does
def setDaemon(self, runnable, isdaemon, noregister = False):
'''
If a runnable is a daemon, it will not keep the main loop running. The main loop will end when all alived runnables are daemons.
'''
if not noregister and runn... | As a Python code analyst, you investigate and solve complex coding mysteries |
Call the function in core context. | Here you have a function in Python 3, explain what it does
def syscall(self, func):
'''
Call the func in core context (main loop).
func should like::
def syscall_sample(scheduler, processor):
something...
where processor is a function which ... | You are a Python code analyst, evaluating scripts for potential improvements. |
def getservers(self, vhost = None):
'''
Return current servers
:param vhost: return only servers of vhost if specified. '' to return only default servers.
None for all servers.
'''
if vhost is not None:
return [s for s in self.connection... | Write a Python 3 function that can
return current servers of vhost if vhost is None return all servers. | As a Python code composer, you craft elegant and concise scripts. |
Stop listen on current servers
COOKIE | Given the following Python 3 function, write the documentation
async def stoplisten(self, vhost = None):
'''
Stop listen on current servers
:param vhost: return only servers of vhost if specified. '' to return only default servers.
None for all servers.
'''... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Start listening on all servers in vhost. | Can you generate the documentation for the following Python 3 function
async def startlisten(self, vhost = None):
'''
Start listen on current servers
:param vhost: return only servers of vhost if specified. '' to return only default servers.
None for all servers.
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Reload configurations remove non - exist servers add new servers and leave others unchanged | Can you generate the documentation for the following Python 3 function
async def updateconfig(self):
"Reload configurations, remove non-exist servers, add new servers, and leave others unchanged"
exists = {}
for s in self.connections:
exists[(s.protocol.vhost, s.rawurl)] = s
... | You are a Python code generator, capable of creating scripts from specifications. |
Return accepted connections optionally filtered by vhost | Can you tell what is the following Python 3 function doing
def getconnections(self, vhost = None):
"Return accepted connections, optionally filtered by vhost"
if vhost is None:
return list(self.managed_connections)
else:
return [c for c in self.managed_connections if c.pr... | As a Python code analyst, you investigate and solve complex coding mysteries |
async def _dhcp_handler(self):
"""
Mini DHCP server, respond DHCP packets from OpenFlow
"""
conn = self._connection
ofdef = self._connection.openflowdef
l3 = self._parent._gettableindex('l3input', self._connection.protocol.vhost)
dhcp_packet_matcher = OpenflowAsyn... | Implement a function in Python 3 to
handle DHCP packets from OpenFlow. | You are a Python code analyst, evaluating scripts for potential improvements. |
Decorator for returning self updater. | Can you generate the documentation for the following Python 3 function
def return_self_updater(func):
'''
Run func, but still return v. Useful for using knowledge.update with operates like append, extend, etc.
e.g. return_self(lambda k,v: v.append('newobj'))
'''
@functools.wraps(func)
def decora... | As a python code expert, you are capable of creating scripts from specifications. |
Return the current date and time formatted for a message header. | Here you have a function in Python 3, explain what it does
def date_time_string(timestamp=None):
global _last_date_time_string
_last_timestamp, _last_str = _last_date_time_string
if timestamp is None:
timestamp = time.time()
_curr_timestamp = int(timestamp)
if _curr_timestamp == _last_timest... | You are a Python code architect, reviewing and designing scalable and efficient code |
Replace special characters < and > to HTML - safe sequences. | Can you tell what is the following Python 3 function doing
def escape_b(s, quote=True):
'''Replace special characters "&", "<" and ">" to HTML-safe sequences.
If the optional flag quote is true, the quotation mark character (")
is also translated.'''
s = s.replace(b"&", b"&") # Must be done first!
... | As a Python code composer, you craft elegant and concise scripts. |
def watch_context(keys, result, reqid, container, module = 'objectdb'):
"""
DEPRECATED - use request_context for most use cases
"""
try:
keys = [k for k,r in zip(keys, result) if r is not None]
yield result
finally:
if keys:
async def clearup():
tr... | Can you write a function in Python 3 where it
deprecates - use request_context for most use cases | You are a Python code analyst, evaluating scripts for potential improvements. |
Decorate a function with named arguments into updater for transact | Given the following Python 3 function, write the documentation
def updater(f):
"Decorate a function with named arguments into updater for transact"
@functools.wraps(f)
def wrapped_updater(keys, values):
result = f(*values)
return (keys[:len(result)], result)
return wrapped_updater | As a Python code composer, you craft elegant and concise scripts. |
def list_updater(*args):
"""
Decorate a function with named lists into updater for transact.
:params \*args: parameter list sizes. -1 means all other items. None means a single item instead of a list.
only one -1 is allowed.
"""
neg_index = [i for v,i in izip(args, itertools... | Create a Python 3 function to
decorate a function with named lists into updater for transact. :params \*args: parameter list sizes. -1 means all other items. None means a single item instead of a list. only one -1 is allowed. | You are a Python code architect, reviewing and designing scalable and efficient code |
Raise if the old value already exists | Make a summary of the following Python 3 code
def create_new(cls, oldvalue, *args):
"Raise if the old value already exists"
if oldvalue is not None:
raise AlreadyExistsException('%r already exists' % (oldvalue,))
return cls.create_instance(*args) | You are a Python code analyst, evaluating scripts for potential improvements. |
Raise if the old value already exists | Make a summary of the following Python 3 code
def create_from_key(cls, oldvalue, key):
"Raise if the old value already exists"
if oldvalue is not None:
raise AlreadyExistsException('%r already exists' % (oldvalue,))
return cls.create_from_key(key) | You are a Python code analyst, evaluating scripts for potential improvements. |
def dump(obj, attributes = True, _refset = None):
"Show full value of a data object"
if _refset is None:
_refset = set()
if obj is None:
return None
elif isinstance(obj, DataObject):
if id(obj) in _refset:
attributes = False
else:
_refset.a... | Implement a Python 3 function for
showing full value of a data object | As a Python code translator, you convert algorithms and pseudocode into Python. |
async def action_handler(self):
"""
Call vtep controller in sequence, merge mutiple calls if possible
When a bind relationship is updated, we always send all logical ports to a logicalswitch,
to make sure it recovers from some failed updates (so called idempotency). When multipl... | Implement a function in Python 3 to
call vtep controller in sequence, merge mutiple calls if possible When a bind relationship is updated, we always send all logical ports to a logicalswitch, to make sure it recovers from some failed updates (so called idempotency). When multiple calls are pending, we only need to send... | You are a Python code analyst, evaluating scripts for potential improvements. |
Update the internal port information. | Here you have a function in Python 3, explain what it does
async def update_ports(self, ports, ovsdb_ports):
new_port_names = dict((p['name'], _to32bitport(p['ofport'])) for p in ovsdb_ports)
new_port_ids = dict((p['id'], _to32bitport(p['ofport'])) for p in ovsdb_ports if p['id'])
if new_port_na... | As a Python code translator, you convert algorithms and pseudocode into Python. |
List all the proxy modules in the specified root_package. | Can you generate a brief explanation for the following Python 3 code
def list_proxy(root_package = 'vlcp'):
'''
Walk through all the sub modules, find subclasses of vlcp.server.module._ProxyModule,
list their default values
'''
proxy_dict = OrderedDict()
pkg = __import__(root_package, fromlist=[... | As a python code expert, you are capable of creating scripts from specifications. |
List all the modules in the specified root_package. | Here you have a function in Python 3, explain what it does
def list_modules(root_package = 'vlcp'):
'''
Walk through all the sub modules, find subclasses of vlcp.server.module.Module,
list their apis through apidefs
'''
pkg = __import__(root_package, fromlist=['_'])
module_dict = OrderedDict()
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def append(self, event, force = False):
'''
Append an event to queue. The events are classified and appended to sub-queues
:param event: input event
:param force: if True, the event is appended even if the queue is full
:returns: None if appended succes... | Can you implement a function in Python 3 that
appends an event to the queue. | You are a Python code generator, capable of creating scripts from specifications. |
def block(self, event, emptyEvents = ()):
'''
Return a recently popped event to queue, and block all later events until unblock.
Only the sub-queue directly containing the event is blocked, so events in other queues may still be processed.
It is illegal to call block and unblock... | Can you write a function in Python 3 where it
blocks the specified event and all subsequent events until unblock. | You are a Python code architect, reviewing and designing scalable and efficient code |
Remove a block
from the event list. | Here you have a function in Python 3, explain what it does
def unblock(self, event):
'''
Remove a block
'''
if event not in self.blockEvents:
return
self.blockEvents[event].unblock(event)
del self.blockEvents[event] | As a Python code translator, you convert algorithms and pseudocode into Python. |
def unblockqueue(self, queue):
'''
Remove blocked events from the queue and all subqueues. Usually used after queue clear/unblockall to prevent leak.
:returns: the cleared events
'''
subqueues = set()
def allSubqueues(q):
subqueues.add(q)
... | Create a Python 3 function for
removing blocked events from the queue and all subqueues. Usually used after queue clear or unblockall. | As a python code expert, you are capable of creating scripts from specifications. |
Remove all blocks from the queue and all sub - queues. | Can you tell what is the following Python 3 function doing
def unblockall(self):
'''
Remove all blocks from the queue and all sub-queues
'''
for q in self.queues.values():
q.unblockall()
self.blockEvents.clear() | As a python code expert, you are capable of creating scripts from specifications. |
Internal notify for sub - queues been popped
. | How would you explain what the following Python 3 function does
def notifyPop(self, queue, length = 1):
'''
Internal notify for sub-queues been poped
:returns: List of any events generated by this pop
'''
self.totalSize = self.totalSize - length
ret1 = []
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def pop(self):
'''
Pop an event from the queue. The event in the queue with higher priority is popped before ones in lower priority.
If there are multiple queues with the same priority, events are taken in turn from each queue.
May return some queueEvents indicating that some of the queu... | Implement a Python 3 function for
popping an event from the queue. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Actual pop
from the queue. | Can you generate a brief explanation for the following Python 3 code
def _pop(self):
'''
Actual pop
'''
if not self.canPop():
raise IndexError('pop from an empty or blocked queue')
priority = self.prioritySet[-1]
ret = self.queues[priority]._pop()
self... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def clear(self):
'''
Clear all the events in this queue, including any sub-queues.
:returns: ((queueEvents,...), (queueEmptyEvents,...)) where queueEvents are QueueCanWriteEvents generated by clearing.
'''
l = len(self)
ret = self._clear()
if self.parent ... | How would you implement a function in Python 3 that
clears all the events in this queue including any sub - queues. | As a Python code composer, you craft elegant and concise scripts. |
Internal method to clear the internal state of the internal state. | Can you tell what is the following Python 3 function doing
def _clear(self):
'''
Actual clear
'''
ret = ([],[])
for q in self.queues.values():
pr = q._clear()
ret[0].extend(pr[0])
ret[1].extend(pr[1])
self.totalSize = 0
del self... | You are a Python code analyst, evaluating scripts for potential improvements. |
Set priority of a sub - queue. | How would you explain what the following Python 3 function does
def setPriority(self, queue, priority):
'''
Set priority of a sub-queue
'''
q = self.queueindex[queue]
self.queues[q[0]].removeSubQueue(q[1])
newPriority = self.queues.setdefault(priority, CBQueue.MultiQueue(... | As a python code expert, you are capable of creating scripts from specifications. |
def addSubQueue(self, priority, matcher, name = None, maxdefault = None, maxtotal = None, defaultQueueClass = FifoQueue):
'''
add a sub queue to current queue, with a priority and a matcher
:param priority: priority of this queue. Larger is higher, 0 is lowest.
:param m... | Can you create a Python 3 function that
adds a sub - queue to current queue with a priority and a matcher | As a Python code composer, you craft elegant and concise scripts. |
def removeSubQueue(self, queue):
'''
remove a sub queue from current queue.
This unblock the sub-queue, retrieve all events from the queue and put them back to the parent.
Call clear on the sub-queue first if the events are not needed any more.
:param q... | Implement a Python 3 function for
removing a sub - queue from current queue. | You are a Python code architect, reviewing and designing scalable and efficient code |
Check if all keys are available in a tree. | Here you have a function in Python 3, explain what it does
def ensure_keys(walk, *keys):
all_retrieved = True
for k in keys:
try:
walk(k)
except WalkKeyNotRetrieved:
all_retrieved = False
return all_retrieved | You are a Python code analyst, evaluating scripts for potential improvements. |
List all available configurations in a VLCP package. | Explain what the following Python 3 code does
def list_config(root_package = 'vlcp'):
'''
Walk through all the sub modules, find subclasses of vlcp.config.Configurable,
list their available configurations through _default_ prefix
'''
pkg = __import__(root_package, fromlist=['_'])
return_dict = O... | You are a Python code architect, reviewing and designing scalable and efficient code |
def http(container = None):
"wrap a WSGI-style class method to a HTTPRequest event handler"
def decorator(func):
@functools.wraps(func)
def handler(self, event):
return _handler(self if container is None else container, event, lambda env: func(self, env))
return handler
r... | Create a Python 3 function for
wrapping a WSGI - style class method to a HTTPRequest event handler | You are a Python code architect, reviewing and designing scalable and efficient code |
def statichttp(container = None):
"wrap a WSGI-style function to a HTTPRequest event handler"
def decorator(func):
@functools.wraps(func)
def handler(event):
return _handler(container, event, func)
if hasattr(func, '__self__'):
handler.__self__ = func.__self__
... | Create a Python 3 function for
wrapping a WSGI - style function to a HTTPRequest event handler | As a Python code analyst, you investigate and solve complex coding mysteries |
def start_response(self, status = 200, headers = [], clearheaders = True, disabletransferencoding = False):
"Start to send response"
if self._sendHeaders:
raise HttpProtocolException('Cannot modify response, headers already sent')
self.status = status
self.disabledeflate = di... | Implement a Python 3 function for
starting to send response | You are a Python code analyst, evaluating scripts for potential improvements. |
def header(self, key, value, replace = True):
"Send a new header"
if hasattr(key, 'encode'):
key = key.encode('ascii')
if hasattr(value, 'encode'):
value = value.encode(self.encoding)
if replace:
self.sent_headers = [(k,v) for k,v in self.sent_headers ... | Can you write a function in Python 3 where it
sends a new header | You are a Python code generator, capable of creating scripts from specifications. |
Add a header with "<Header>: Value | Can you tell what is the following Python 3 function doing
def rawheader(self, kv, replace = True):
if hasattr(kv, 'encode'):
kv = kv.encode(self.encoding)
k,v = kv.split(b':', 1)
self.header(k, v.strip(), replace) | As a python code expert, you are capable of creating scripts from specifications. |
Add a new cookie to the list of sent cookies. | Here you have a function in Python 3, explain what it does
def setcookie(self, key, value, max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False):
newcookie = Morsel()
newcookie.key = key
newcookie.value = value
newcookie.coded_value = value
if max_age is... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def bufferoutput(self):
"""
Buffer the whole output until write EOF or flushed.
"""
new_stream = Stream(writebufferlimit=None)
if self._sendHeaders:
# An extra copy
self.container.subroutine(new_stream.copy_to(self.outputstream, self.container, buffering=F... | Can you create a Python 3 function that
buffers the whole output until EOF or flushed. | You are a Python code architect, reviewing and designing scalable and efficient code |
Rewrite this request to another processor. Must be called before header sent | Here you have a function in Python 3, explain what it does
async def rewrite(self, path, method = None, keepresponse = True):
"Rewrite this request to another processor. Must be called before header sent"
if self._sendHeaders:
raise HttpProtocolException('Cannot modify response, headers alre... | You are a Python code analyst, evaluating scripts for potential improvements. |
async def redirect(self, path, status = 302):
"""
Redirect this request with 3xx status
"""
location = urljoin(urlunsplit((b'https' if self.https else b'http',
self.host,
... | Write a Python 3 function that can
redirect this request with 3xx status | As a python code expert, you are capable of creating scripts from specifications. |
Escape special characters in HTML. | Here you have a function in Python 3, explain what it does
def escape(self, text, quote = True):
if isinstance(text, bytes):
return escape_b(text, quote)
else:
return escape(text, quote) | You are a Python code architect, reviewing and designing scalable and efficient code |
async def error(self, status=500, allowredirect = True, close = True, showerror = None, headers = []):
"""
Show default error response
"""
if showerror is None:
showerror = self.showerrorinfo
if self._sendHeaders:
if showerror:
typ, exc, tb... | Create a Python 3 function for
writing an error response. | As a Python code translator, you convert algorithms and pseudocode into Python. |
async def write(self, data, eof = False, buffering = True):
"""
Write output to current output stream
"""
if not self.outputstream:
self.outputstream = Stream()
self._startResponse()
elif (not buffering or eof) and not self._sendHeaders:
self._... | Implement a Python 3 function for
writing data to the current output stream. | As a python code expert, you are capable of creating scripts from specifications. |
Write a list of lines to the current output stream. | Explain what the following Python 3 code does
async def writelines(self, lines, eof = False, buffering = True):
for l in lines:
await self.write(l, False, buffering)
if eof:
await self.write(b'', eof, buffering) | You are a Python code generator, capable of creating scripts from specifications. |
Send a response to the client. | Given the following Python 3 function, write the documentation
def output(self, stream, disabletransferencoding = None):
if self._sendHeaders:
raise HttpProtocolException('Cannot modify response, headers already sent')
self.outputstream = stream
try:
content_length = len(... | You are a Python code architect, reviewing and designing scalable and efficient code |
def outputdata(self, data):
"""
Send output with fixed length data
"""
if not isinstance(data, bytes):
data = str(data).encode(self.encoding)
self.output(MemoryStream(data)) | How would you implement a function in Python 3 that
sends data to the client. | You are a Python code analyst, evaluating scripts for potential improvements. |
Close this request send all data and close the connection. | Can you generate a brief explanation for the following Python 3 code
async def close(self):
if not self._sendHeaders:
self._startResponse()
if self.inputstream is not None:
self.inputstream.close(self.connection.scheduler)
if self.outputstream is not None:
awa... | You are a Python code generator, capable of creating scripts from specifications. |
Parse the form - data and return the form data as a dict. | Can you generate a brief explanation for the following Python 3 code
async def parseform(self, limit = 67108864, tostr = True, safename = True):
'''
Parse form-data with multipart/form-data or application/x-www-form-urlencoded
In Python3, the keys of form and files are unicode, but values are by... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.