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 disable_directory_service(self, check_peer=False):
"""Disable the directory service. :param check_peer: If True, disables server authenticity enforcement. If False, disables directory service integration. :type check_peer: bool, optional :returns: A dictionary describing the status of the directory service. :rtype: ResponseDict """ |
if check_peer:
return self.set_directory_service(check_peer=False)
return self.set_directory_service(enabled=False) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enable_directory_service(self, check_peer=False):
"""Enable the directory service. :param check_peer: If True, enables server authenticity enforcement. If False, enables directory service integration. :type check_peer: bool, optional :returns: A dictionary describing the status of the directory service. :rtype: ResponseDict """ |
if check_peer:
return self.set_directory_service(check_peer=True)
return self.set_directory_service(enabled=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 create_snmp_manager(self, manager, host, **kwargs):
"""Create an SNMP manager. :param manager: Name of manager to be created. :type manager: str :param host: IP address or DNS name of SNMP server to be used. :type host: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST snmp/:manager** :type \*\*kwargs: optional :returns: A dictionary describing the created SNMP manager. :rtype: ResponseDict """ |
data = {"host": host}
data.update(kwargs)
return self._request("POST", "snmp/{0}".format(manager), data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect_array(self, address, connection_key, connection_type, **kwargs):
"""Connect this array with another one. :param address: IP address or DNS name of other array. :type address: str :param connection_key: Connection key of other array. :type connection_key: str :param connection_type: Type(s) of connection desired. :type connection_type: list :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST array/connection** :type \*\*kwargs: optional :returns: A dictionary describing the connection to the other array. :rtype: ResponseDict .. note:: Currently, the only type of connection is "replication". .. note:: Requires use of REST API 1.2 or later. """ |
data = {"management_address": address,
"connection_key": connection_key,
"type": connection_type}
data.update(kwargs)
return self._request("POST", "array/connection", data) |
<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_pgroup_snapshot(self, source, **kwargs):
"""Create snapshot of pgroup from specified source. :param source: Name of pgroup of which to take snapshot. :type source: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST pgroup** :type \*\*kwargs: optional :returns: A dictionary describing the created snapshot. :rtype: ResponseDict .. note:: Requires use of REST API 1.2 or later. """ |
# In REST 1.4, support was added for snapshotting multiple pgroups. As a
# result, the endpoint response changed from an object to an array of
# objects. To keep the response type consistent between REST versions,
# we unbox the response when creating a single snapshot.
result = self.create_pgroup_snapshots([source], **kwargs)
if self._rest_version >= LooseVersion("1.4"):
headers = result.headers
result = ResponseDict(result[0])
result.headers = headers
return result |
<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_pgroup_snapshots(self, sources, **kwargs):
"""Create snapshots of pgroups from specified sources. :param sources: Names of pgroups of which to take snapshots. :type sources: list of str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST pgroup** :type \*\*kwargs: optional :returns: A list of dictionaries describing the created snapshots. :rtype: ResponseList .. note:: Requires use of REST API 1.2 or later. """ |
data = {"source": sources, "snap": True}
data.update(kwargs)
return self._request("POST", "pgroup", data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def eradicate_pgroup(self, pgroup, **kwargs):
"""Eradicate a destroyed pgroup. :param pgroup: Name of pgroup to be eradicated. :type pgroup: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **DELETE pgroup/:pgroup** :type \*\*kwargs: optional :returns: A dictionary mapping "name" to pgroup. :rtype: ResponseDict .. note:: Requires use of REST API 1.2 or later. """ |
eradicate = {"eradicate": True}
eradicate.update(kwargs)
return self._request("DELETE", "pgroup/{0}".format(pgroup), eradicate) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clone_pod(self, source, dest, **kwargs):
"""Clone an existing pod to a new one. :param source: Name of the pod the be cloned. :type source: str :param dest: Name of the target pod to clone into :type dest: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST pod/:pod** :type \*\*kwargs: optional :returns: A dictionary describing the created pod :rtype: ResponseDict .. note:: Requires use of REST API 1.13 or later. """ |
data = {"source": source}
data.update(kwargs)
return self._request("POST", "pod/{0}".format(dest), data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_pod(self, pod, array, **kwargs):
"""Remove arrays from a pod. :param pod: Name of the pod. :type pod: str :param array: Array to remove from pod. :type array: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **DELETE pod/:pod**/array/:array** :type \*\*kwargs: optional :returns: A dictionary mapping "name" to pod and "array" to the pod's new array list. :rtype: ResponseDict .. note:: Requires use of REST API 1.13 or later. """ |
return self._request("DELETE", "pod/{0}/array/{1}".format(pod, array), kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def page_through(page_size, function, *args, **kwargs):
"""Return an iterator over all pages of a REST operation. :param page_size: Number of elements to retrieve per call. :param function: FlashArray function that accepts limit as an argument. :param \*args: Positional arguments to be passed to function. :param \*\*kwargs: Keyword arguments to be passed to function. :returns: An iterator of tuples containing a page of results for the function(\*args, \*\*kwargs) and None, or None and a PureError if a call to retrieve a page fails. :rtype: iterator .. note:: Requires use of REST API 1.7 or later. Only works with functions that accept limit as an argument. Iterator will retrieve page_size elements per call Iterator will yield None and an error if a call fails. The next call will repeat the same call, unless the caller sends in an alternate page token. """ |
kwargs["limit"] = page_size
def get_page(token):
page_kwargs = kwargs.copy()
if token:
page_kwargs["token"] = token
return function(*args, **page_kwargs)
def page_generator():
token = None
while True:
try:
response = get_page(token)
token = response.headers.get("x-next-token")
except PureError as err:
yield None, err
else:
if response:
sent_token = yield response, None
if sent_token is not None:
token = sent_token
else:
return
return page_generator() |
<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_all(self, n, check_rekey=False):
""" Read as close to N bytes as possible, blocking as long as necessary. @param n: number of bytes to read @type n: int @return: the data read @rtype: str @raise EOFError: if the socket was closed before all the bytes could be read """ |
out = ''
# handle over-reading from reading the banner line
if len(self.__remainder) > 0:
out = self.__remainder[:n]
self.__remainder = self.__remainder[n:]
n -= len(out)
if PY22:
return self._py22_read_all(n, out)
while n > 0:
got_timeout = False
try:
x = self.__socket.recv(n)
if len(x) == 0:
raise EOFError()
out += x
n -= len(x)
except socket.timeout:
got_timeout = True
except socket.error, e:
# on Linux, sometimes instead of socket.timeout, we get
# EAGAIN. this is a bug in recent (> 2.6.9) kernels but
# we need to work around it.
if (type(e.args) is tuple) and (len(e.args) > 0) and (e.args[0] == errno.EAGAIN):
got_timeout = True
elif (type(e.args) is tuple) and (len(e.args) > 0) and (e.args[0] == errno.EINTR):
# syscall interrupted; try again
pass
elif self.__closed:
raise EOFError()
else:
raise
if got_timeout:
if self.__closed:
raise EOFError()
if check_rekey and (len(out) == 0) and self.__need_rekey:
raise NeedRekeyException()
self._check_keepalive()
return out |
<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_message(self, data):
""" Write a block of data using the current cipher, as an SSH block. """ |
# encrypt this sucka
data = str(data)
cmd = ord(data[0])
if cmd in MSG_NAMES:
cmd_name = MSG_NAMES[cmd]
else:
cmd_name = '$%x' % cmd
orig_len = len(data)
self.__write_lock.acquire()
try:
if self.__compress_engine_out is not None:
data = self.__compress_engine_out(data)
packet = self._build_packet(data)
if self.__dump_packets:
self._log(DEBUG, 'Write packet <%s>, length %d' % (cmd_name, orig_len))
self._log(DEBUG, util.format_binary(packet, 'OUT: '))
if self.__block_engine_out != None:
out = self.__block_engine_out.encrypt(packet)
else:
out = packet
# + mac
if self.__block_engine_out != None:
payload = struct.pack('>I', self.__sequence_number_out) + packet
out += compute_hmac(self.__mac_key_out, payload, self.__mac_engine_out)[:self.__mac_size_out]
self.__sequence_number_out = (self.__sequence_number_out + 1) & 0xffffffffL
self.write_all(out)
self.__sent_bytes += len(out)
self.__sent_packets += 1
if ((self.__sent_packets >= self.REKEY_PACKETS) or (self.__sent_bytes >= self.REKEY_BYTES)) \
and not self.__need_rekey:
# only ask once for rekeying
self._log(DEBUG, 'Rekeying (hit %d packets, %d bytes sent)' %
(self.__sent_packets, self.__sent_bytes))
self.__received_bytes_overflow = 0
self.__received_packets_overflow = 0
self._trigger_rekey()
finally:
self.__write_lock.release() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_line(cls, line):
""" Parses the given line of text to find the names for the host, the type of key, and the key data. The line is expected to be in the format used by the openssh known_hosts file. Lines are expected to not have leading or trailing whitespace. We don't bother to check for comments or empty lines. All of that should be taken care of before sending the line to us. @param line: a line from an OpenSSH known_hosts file @type line: str """ |
fields = line.split(' ')
if len(fields) < 3:
# Bad number of fields
return None
fields = fields[:3]
names, keytype, key = fields
names = names.split(',')
# Decide what kind of key we're looking at and create an object
# to hold it accordingly.
try:
if keytype == 'ssh-rsa':
key = RSAKey(data=base64.decodestring(key))
elif keytype == 'ssh-dss':
key = DSSKey(data=base64.decodestring(key))
else:
return None
except binascii.Error, e:
raise InvalidHostKey(line, e)
return cls(names, key) |
<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_line(self):
""" Returns a string in OpenSSH known_hosts file format, or None if the object is not in a valid state. A trailing newline is included. """ |
if self.valid:
return '%s %s %s\n' % (','.join(self.hostnames), self.key.get_name(),
self.key.get_base64())
return 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 check(self, hostname, key):
""" Return True if the given key is associated with the given hostname in this dictionary. @param hostname: hostname (or IP) of the SSH server @type hostname: str @param key: the key to check @type key: L{PKey} @return: C{True} if the key is associated with the hostname; C{False} if not @rtype: bool """ |
k = self.lookup(hostname)
if k is None:
return False
host_key = k.get(key.get_name(), None)
if host_key is None:
return False
return str(host_key) == str(key) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hash_host(hostname, salt=None):
""" Return a "hashed" form of the hostname, as used by openssh when storing hashed hostnames in the known_hosts file. @param hostname: the hostname to hash @type hostname: str @param salt: optional salt to use when hashing (must be 20 bytes long) @type salt: str @return: the hashed hostname @rtype: str """ |
if salt is None:
salt = rng.read(SHA.digest_size)
else:
if salt.startswith('|1|'):
salt = salt.split('|')[2]
salt = base64.decodestring(salt)
assert len(salt) == SHA.digest_size
hmac = HMAC.HMAC(salt, hostname, SHA).digest()
hostkey = '|1|%s|%s' % (base64.encodestring(salt), base64.encodestring(hmac))
return hostkey.replace('\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 retry_on_signal(function):
"""Retries function until it doesn't raise an EINTR error""" |
while True:
try:
return function()
except EnvironmentError, e:
if e.errno != errno.EINTR:
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 lookup(self, hostname):
""" Return a dict of config options for a given hostname. The host-matching rules of OpenSSH's C{ssh_config} man page are used, which means that all configuration options from matching host specifications are merged, with more specific hostmasks taking precedence. In other words, if C{"Port"} is set under C{"Host *"} and also C{"Host *.example.com"}, and the lookup is for C{"ssh.example.com"}, then the port entry for C{"Host *.example.com"} will win out. The keys in the returned dict are all normalized to lowercase (look for C{"port"}, not C{"Port"}. No other processing is done to the keys or values. @param hostname: the hostname to lookup @type hostname: str """ |
matches = [x for x in self._config if fnmatch.fnmatch(hostname, x['host'])]
# Move * to the end
_star = matches.pop(0)
matches.append(_star)
ret = {}
for m in matches:
for k,v in m.iteritems():
if not k in ret:
ret[k] = v
ret = self._expand_variables(ret, hostname)
del ret['host']
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def url(proto, server, port=None, uri=None):
"""Construct a URL from the given components.""" |
url_parts = [proto, '://', server]
if port:
port = int(port)
if port < 1 or port > 65535:
raise ValueError('invalid port value')
if not ((proto == 'http' and port == 80) or
(proto == 'https' and port == 443)):
url_parts.append(':')
url_parts.append(str(port))
if uri:
url_parts.append('/')
url_parts.append(requests.utils.quote(uri.strip('/')))
url_parts.append('/')
return ''.join(url_parts) |
<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_url(self, container=None, resource=None, query_items=None):
"""Create a URL from the specified parts.""" |
pth = [self._base_url]
if container:
pth.append(container.strip('/'))
if resource:
pth.append(resource)
else:
pth.append('')
url = '/'.join(pth)
if isinstance(query_items, (list, tuple, set)):
url += RestHttp._list_query_str(query_items)
query_items = None
p = requests.PreparedRequest()
p.prepare_url(url, query_items)
return p.url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def head_request(self, container, resource=None):
"""Send a HEAD request.""" |
url = self.make_url(container, resource)
headers = self._make_headers(None)
try:
rsp = requests.head(url, headers=self._base_headers,
verify=self._verify, timeout=self._timeout)
except requests.exceptions.ConnectionError as e:
RestHttp._raise_conn_error(e)
if self._dbg_print:
self.__print_req('HEAD', rsp.url, headers, None)
return rsp.status_code |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload_file(self, container, src_file_path, dst_name=None, put=True, content_type=None):
"""Upload a single file.""" |
if not os.path.exists(src_file_path):
raise RuntimeError('file not found: ' + src_file_path)
if not dst_name:
dst_name = os.path.basename(src_file_path)
if not content_type:
content_type = "application/octet.stream"
headers = dict(self._base_headers)
if content_type:
headers["content-length"] = content_type
else:
headers["content-length"] = "application/octet.stream"
headers["content-length"] = str(os.path.getsize(src_file_path))
headers['content-disposition'] = 'attachment; filename=' + dst_name
if put:
method = 'PUT'
url = self.make_url(container, dst_name, None)
else:
method = 'POST'
url = self.make_url(container, None, None)
with open(src_file_path, 'rb') as up_file:
try:
rsp = requests.request(method, url, headers=headers,
data=up_file, timeout=self._timeout)
except requests.exceptions.ConnectionError as e:
RestHttp._raise_conn_error(e)
return self._handle_response(rsp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload_file_mp(self, container, src_file_path, dst_name=None, content_type=None):
"""Upload a file using multi-part encoding.""" |
if not os.path.exists(src_file_path):
raise RuntimeError('file not found: ' + src_file_path)
if not dst_name:
dst_name = os.path.basename(src_file_path)
if not content_type:
content_type = "application/octet.stream"
url = self.make_url(container, None, None)
headers = self._base_headers
with open(src_file_path, 'rb') as up_file:
files = {'file': (dst_name, up_file, content_type)}
try:
rsp = requests.post(url, headers=headers, files=files,
timeout=self._timeout)
except requests.exceptions.ConnectionError as e:
RestHttp._raise_conn_error(e)
return self._handle_response(rsp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload_files(self, container, src_dst_map, content_type=None):
"""Upload multiple files.""" |
if not content_type:
content_type = "application/octet.stream"
url = self.make_url(container, None, None)
headers = self._base_headers
multi_files = []
try:
for src_path in src_dst_map:
dst_name = src_dst_map[src_path]
if not dst_name:
dst_name = os.path.basename(src_path)
multi_files.append(
('files', (dst_name, open(src_path, 'rb'), content_type)))
rsp = requests.post(url, headers=headers, files=multi_files,
timeout=self._timeout)
except requests.exceptions.ConnectionError as e:
RestHttp._raise_conn_error(e)
finally:
for n, info in multi_files:
dst, f, ctype = info
f.close()
return self._handle_response(rsp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new_session(self, server=None, session_name=None, user_name=None, existing_session=None):
"""Create a new session or attach to existing. Normally, this function is called automatically, and gets its parameter values from the environment. It is provided as a public function for cases when extra control over session creation is required in an automation script that is adapted to use ReST. WARNING: This function is not part of the original StcPython.py and if called directly by an automation script, then that script will not be able to revert to using the non-ReST API until the call to this function is removed. Arguments: server -- STC server (Lab Server) address. If not set get value from STC_SERVER_ADDRESS environment variable. session_name -- Name part of session ID. If not set get value from STC_SESSION_NAME environment variable. user_name -- User portion of session ID. If not set get name of user this script is running as. existing_session -- Behavior when session already exists. Recognized values are 'kill' and 'join'. If not set get value from EXISTING_SESSION environment variable. If not set to recognized value, raise exception if session already exists. See also: stchttp.StcHttp(), stchttp.new_session() Return: The internal StcHttp object that is used for this session. This allows the caller to perform additional interactions with the STC ReST API beyond what the adapter provides. """ |
if not server:
server = os.environ.get('STC_SERVER_ADDRESS')
if not server:
raise EnvironmentError('STC_SERVER_ADDRESS not set')
self._stc = stchttp.StcHttp(server)
if not session_name:
session_name = os.environ.get('STC_SESSION_NAME')
if not session_name or session_name == '__NEW_TEST_SESSION__':
session_name = None
if not user_name:
try:
# Try to get the name of the current user.
user_name = getpass.getuser()
except:
pass
if not existing_session:
# Try to get existing_session from environ if not passed in.
existing_session = os.environ.get('EXISTING_SESSION')
if existing_session:
existing_session = existing_session.lower()
if existing_session == 'kill':
# Kill any existing session and create a new one.
self._stc.new_session(user_name, session_name, True)
return self._stc
if existing_session == 'join':
# Create a new session, or join if already exists.
try:
self._stc.new_session(user_name, session_name, False)
except RuntimeError as e:
if str(e).find('already exists') >= 0:
sid = ' - '.join((session_name, user_name))
self._stc.join_session(sid)
else:
raise
return self._stc
# Create a new session, raise exception if session already exists.
self._stc.new_session(user_name, session_name, False)
return self._stc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _end_session(self, kill=None):
"""End the client session.""" |
if self._stc:
if kill is None:
kill = os.environ.get('STC_SESSION_TERMINATE_ON_DISCONNECT')
kill = _is_true(kill)
self._stc.end_session(kill)
self._stc = 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 setup(app):
""" This isn't used in Production, but allows this module to be used as a standalone extension. """ |
app.add_directive('readthedocs-embed', EmbedDirective)
app.add_config_value('readthedocs_embed_project', '', 'html')
app.add_config_value('readthedocs_embed_version', '', 'html')
app.add_config_value('readthedocs_embed_doc', '', 'html')
return app |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def finalize_media(app):
"""Point media files at our media server.""" |
if (app.builder.name == 'readthedocssinglehtmllocalmedia' or
app.builder.format != 'html' or
not hasattr(app.builder, 'script_files')):
return # Use local media for downloadable files
# Pull project data from conf.py if it exists
context = app.builder.config.html_context
STATIC_URL = context.get('STATIC_URL', DEFAULT_STATIC_URL)
js_file = '{}javascript/readthedocs-doc-embed.js'.format(STATIC_URL)
if sphinx.version_info < (1, 8):
app.builder.script_files.append(js_file)
else:
app.add_js_file(js_file) |
<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_body(app, pagename, templatename, context, doctree):
""" Add Read the Docs content to Sphinx body content. This is the most reliable way to inject our content into the page. """ |
STATIC_URL = context.get('STATIC_URL', DEFAULT_STATIC_URL)
online_builders = [
'readthedocs', 'readthedocsdirhtml', 'readthedocssinglehtml'
]
if app.builder.name == 'readthedocssinglehtmllocalmedia':
if 'html_theme' in context and context['html_theme'] == 'sphinx_rtd_theme':
theme_css = '_static/css/theme.css'
else:
theme_css = '_static/css/badge_only.css'
elif app.builder.name in online_builders:
if 'html_theme' in context and context['html_theme'] == 'sphinx_rtd_theme':
theme_css = '%scss/sphinx_rtd_theme.css' % STATIC_URL
else:
theme_css = '%scss/badge_only.css' % STATIC_URL
else:
# Only insert on our HTML builds
return
inject_css = True
# Starting at v0.4.0 of the sphinx theme, the theme CSS should not be injected
# This decouples the theme CSS (which is versioned independently) from readthedocs.org
if theme_css.endswith('sphinx_rtd_theme.css'):
try:
import sphinx_rtd_theme
inject_css = LooseVersion(sphinx_rtd_theme.__version__) < LooseVersion('0.4.0')
except ImportError:
pass
if inject_css and theme_css not in app.builder.css_files:
if sphinx.version_info < (1, 8):
app.builder.css_files.insert(0, theme_css)
else:
app.add_css_file(theme_css)
# This is monkey patched on the signal because we can't know what the user
# has done with their `app.builder.templates` before now.
if not hasattr(app.builder.templates.render, '_patched'):
# Janky monkey patch of template rendering to add our content
old_render = app.builder.templates.render
def rtd_render(self, template, render_context):
"""
A decorator that renders the content with the users template renderer,
then adds the Read the Docs HTML content at the end of body.
"""
# Render Read the Docs content
template_context = render_context.copy()
template_context['rtd_css_url'] = '{}css/readthedocs-doc-embed.css'.format(STATIC_URL)
template_context['rtd_analytics_url'] = '{}javascript/readthedocs-analytics.js'.format(
STATIC_URL,
)
source = os.path.join(
os.path.abspath(os.path.dirname(__file__)),
'_templates',
'readthedocs-insert.html.tmpl'
)
templ = open(source).read()
rtd_content = app.builder.templates.render_string(templ, template_context)
# Handle original render function
content = old_render(template, render_context)
end_body = content.lower().find('</head>')
# Insert our content at the end of the body.
if end_body != -1:
content = content[:end_body] + rtd_content + "\n" + content[end_body:]
else:
log.debug("File doesn't look like HTML. Skipping RTD content addition")
return content
rtd_render._patched = True
app.builder.templates.render = types.MethodType(rtd_render,
app.builder.templates) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_json_artifacts(app, pagename, templatename, context, doctree):
""" Generate JSON artifacts for each page. This way we can skip generating this in other build step. """ |
try:
# We need to get the output directory where the docs are built
# _build/json.
build_json = os.path.abspath(
os.path.join(app.outdir, '..', 'json')
)
outjson = os.path.join(build_json, pagename + '.fjson')
outdir = os.path.dirname(outjson)
if not os.path.exists(outdir):
os.makedirs(outdir)
with open(outjson, 'w+') as json_file:
to_context = {
key: context.get(key, '')
for key in KEYS
}
json.dump(to_context, json_file, indent=4)
except TypeError:
log.exception(
'Fail to encode JSON for page {page}'.format(page=outjson)
)
except IOError:
log.exception(
'Fail to save JSON output for page {page}'.format(page=outjson)
)
except Exception as e:
log.exception(
'Failure in JSON search dump for page {page}'.format(page=outjson)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _copy_searchtools(self, renderer=None):
"""Copy and patch searchtools This uses the included Sphinx version's searchtools, but patches it to remove automatic initialization. This is a fork of ``sphinx.util.fileutil.copy_asset`` """ |
log.info(bold('copying searchtools... '), nonl=True)
if sphinx.version_info < (1, 8):
search_js_file = 'searchtools.js_t'
else:
search_js_file = 'searchtools.js'
path_src = os.path.join(
package_dir, 'themes', 'basic', 'static', search_js_file
)
if os.path.exists(path_src):
path_dest = os.path.join(self.outdir, '_static', 'searchtools.js')
if renderer is None:
# Sphinx 1.4 used the renderer from the existing builder, but
# the pattern for Sphinx 1.5 is to pass in a renderer separate
# from the builder. This supports both patterns for future
# compatibility
if sphinx.version_info < (1, 5):
renderer = self.templates
else:
from sphinx.util.template import SphinxRenderer
renderer = SphinxRenderer()
with codecs.open(path_src, 'r', encoding='utf-8') as h_src:
with codecs.open(path_dest, 'w', encoding='utf-8') as h_dest:
data = h_src.read()
data = self.REPLACEMENT_PATTERN.sub(self.REPLACEMENT_TEXT, data)
h_dest.write(renderer.render_string(
data,
self.get_static_readthedocs_context()
))
else:
log.warning('Missing {}'.format(search_js_file))
log.info('done') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stc_system_info(stc_addr):
"""Return dictionary of STC and API information. If a session already exists, then use it to get STC information and avoid taking the time to start a new session. A session is necessary to get STC information. """ |
stc = stchttp.StcHttp(stc_addr)
sessions = stc.sessions()
if sessions:
# If a session already exists, use it to get STC information.
stc.join_session(sessions[0])
sys_info = stc.system_info()
else:
# Create a new session to get STC information.
stc.new_session('anonymous')
try:
sys_info = stc.system_info()
finally:
# Make sure the temporary session in terminated.
stc.end_session()
return sys_info |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new_session(self, user_name=None, session_name=None, kill_existing=False, analytics=None):
"""Create a new test session. The test session is identified by the specified user_name and optional session_name parameters. If a session name is not specified, then the server will create one. Arguments: user_name -- User name part of session ID. session_name -- Session name part of session ID. kill_existing -- If there is an existing session, with the same session name and user name, then terminate it before creating a new session analytics -- Optional boolean value to disable or enable analytics for new session. None will use setting configured on server. Return: True is session started, False if session was already started. """ |
if self.started():
return False
if not session_name or not session_name.strip():
session_name = ''
if not user_name or not user_name.strip():
user_name = ''
params = {'userid': user_name, 'sessionname': session_name}
if analytics not in (None, ''):
params['analytics'] = str(analytics).lower()
try:
status, data = self._rest.post_request('sessions', None, params)
except resthttp.RestHttpError as e:
if kill_existing and str(e).find('already exists') >= 0:
self.end_session('kill', ' - '.join((session_name, user_name)))
else:
raise RuntimeError('failed to create session: ' + str(e))
# Starting session
if self._dbg_print:
print('===> starting session')
status, data = self._rest.post_request('sessions', None, params)
if self._dbg_print:
print('===> OK, started')
sid = data['session_id']
if self._dbg_print:
print('===> session ID:', sid)
print('===> URL:', self._rest.make_url('sessions', sid))
self._rest.add_header('X-STC-API-Session', sid)
self._sid = sid
return sid |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def join_session(self, sid):
"""Attach to an existing session.""" |
self._rest.add_header('X-STC-API-Session', sid)
self._sid = sid
try:
status, data = self._rest.get_request('objects', 'system1',
['version', 'name'])
except resthttp.RestHttpError as e:
self._rest.del_header('X-STC-API-Session')
self._sid = None
raise RuntimeError('failed to join session "%s": %s' % (sid, e))
return data['version'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def end_session(self, end_tcsession=True, sid=None):
"""End this test session. A session can be ended in three ways, depending on the value of the end_tcsession parameter: - end_tcsession=None: Stop using session locally, do not contact server. - end_tcsession=False: End client controller, but leave test session on server. - end_tcsession=True: End client controller and terminate test session (default). - end_tcsession='kill': Forcefully terminate test session. Specifying end_tcsession=False is useful to do before attaching an STC GUI or legacy automation script, so that there are not multiple controllers to interfere with each other. When the session is ended, it is no longer available. Clients should export any result or log files, that they want to preserve, before the session is ended. Arguments end_tcsession -- How to end the session (see above) sid -- ID of session to end. None to use current session. Return: True if session ended, false if session was not started. """ |
if not sid or sid == self._sid:
if not self.started():
return False
sid = self._sid
self._sid = None
self._rest.del_header('X-STC-API-Session')
if end_tcsession is None:
if self._dbg_print:
print('===> detached from session')
return True
try:
if end_tcsession:
if self._dbg_print:
print('===> deleting session:', sid)
if end_tcsession == 'kill':
status, data = self._rest.delete_request(
'sessions', sid, 'kill')
else:
status, data = self._rest.delete_request('sessions', sid)
count = 0
while 1:
time.sleep(5)
if self._dbg_print:
print('===> checking if session ended')
ses_list = self.sessions()
if not ses_list or sid not in ses_list:
break
count += 1
if count == 3:
raise RuntimeError("test session has not stopped")
if self._dbg_print:
print('===> ok - deleted test session')
else:
# Ending client session is supported on version >= 2.1.5
if self._get_api_version() < (2, 1, 5):
raise RuntimeError('option no available on server')
status, data = self._rest.delete_request(
'sessions', sid, 'false')
if self._dbg_print:
print('===> OK - detached REST API from test session')
except resthttp.RestHttpError as e:
raise RuntimeError('failed to end session: ' + str(e))
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 session_info(self, session_id=None):
"""Get information on session. If session_id is None, the default, then return information about this session. If a session ID is given, then get information about that session. Arguments: session_id -- Id of session to get info for, if not this session. Return: Dictionary of session information. """ |
if not session_id:
if not self.started():
return []
session_id = self._sid
status, data = self._rest.get_request('sessions', session_id)
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def files(self):
"""Get list of files, for this session, on server.""" |
self._check_session()
status, data = self._rest.get_request('files')
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bll_version(self):
"""Get the BLL version this session is connected to. Return: Version string if session started. None if session not started. """ |
if not self.started():
return None
status, data = self._rest.get_request('objects', 'system1',
['version', 'name'])
return data['version'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, handle):
"""Delete the specified object. Arguments: handle -- Handle of object to delete. """ |
self._check_session()
self._rest.delete_request('objects', str(handle)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def config(self, handle, attributes=None, **kwattrs):
"""Sets or modifies one or more object attributes or relations. Arguments can be supplied either as a dictionary or as keyword arguments. Examples: stc.config('port1', location='//10.1.2.3/1/1') stc.config('port2', {'location': '//10.1.2.3/1/2'}) Arguments: handle -- Handle of object to modify. attributes -- Dictionary of attributes (name-value pairs). kwattrs -- Optional keyword attributes (name=value pairs). """ |
self._check_session()
if kwattrs:
if attributes:
attributes.update(kwattrs)
else:
attributes = kwattrs
self._rest.put_request('objects', str(handle), attributes) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chassis(self):
"""Get list of chassis known to test session.""" |
self._check_session()
status, data = self._rest.get_request('chassis')
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chassis_info(self, chassis):
"""Get information about the specified chassis.""" |
if not chassis or not isinstance(chassis, str):
raise RuntimeError('missing chassis address')
self._check_session()
status, data = self._rest.get_request('chassis', chassis)
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connections(self):
"""Get list of connections.""" |
self._check_session()
status, data = self._rest.get_request('connections')
return data |
<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_connected(self, chassis):
"""Get Boolean connected status of the specified chassis.""" |
self._check_session()
try:
status, data = self._rest.get_request('connections', chassis)
except resthttp.RestHttpError as e:
if int(e) == 404:
# 404 NOT FOUND means the chassis in unknown, so return false.
return False
return bool(data and data.get('IsConnected')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self, chassis_list):
"""Establish connection to one or more chassis. Arguments: chassis_list -- List of chassis (IP addresses or DNS names) Return: List of chassis addresses. """ |
self._check_session()
if not isinstance(chassis_list, (list, tuple, set, dict, frozenset)):
chassis_list = (chassis_list,)
if len(chassis_list) == 1:
status, data = self._rest.put_request(
'connections', chassis_list[0])
data = [data]
else:
params = {chassis: True for chassis in chassis_list}
params['action'] = 'connect'
status, data = self._rest.post_request('connections', None, params)
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disconnect(self, chassis_list):
"""Remove connection with one or more chassis. Arguments: chassis_list -- List of chassis (IP addresses or DNS names) """ |
self._check_session()
if not isinstance(chassis_list, (list, tuple, set, dict, frozenset)):
chassis_list = (chassis_list,)
if len(chassis_list) == 1:
self._rest.delete_request('connections', chassis_list[0])
else:
params = {chassis: True for chassis in chassis_list}
params['action'] = 'disconnect'
self._rest.post_request('connections', None, 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 help(self, subject=None, args=None):
"""Get help information about Automation API. The following values can be specified for the subject: None -- gets an overview of help. 'commands' -- gets a list of API functions command name -- get info about the specified command. object type -- get info about the specified object type handle value -- get info about the object type referred to Arguments: subject -- Optional. Subject to get help on. args -- Optional. Additional arguments for searching help. These are used when the subject is 'list'. Return: String of help information. """ |
if subject:
if subject not in (
'commands', 'create', 'config', 'get', 'delete', 'perform',
'connect', 'connectall', 'disconnect', 'disconnectall',
'apply', 'log', 'help'):
self._check_session()
status, data = self._rest.get_request('help', subject, args)
else:
status, data = self._rest.get_request('help')
if isinstance(data, (list, tuple, set)):
return ' '.join((str(i) for i in data))
return data['message'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log(self, level, msg):
"""Write a diagnostic message to a log file or to standard output. Arguments: level -- Severity level of entry. One of: INFO, WARN, ERROR, FATAL. msg -- Message to write to log. """ |
self._check_session()
level = level.upper()
allowed_levels = ('INFO', 'WARN', 'ERROR', 'FATAL')
if level not in allowed_levels:
raise ValueError('level must be one of: ' +
', '.join(allowed_levels))
self._rest.post_request(
'log', None, {'log_level': level.upper(), 'message': msg}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(self, file_name, save_as=None):
"""Download the specified file from the server. Arguments: file_name -- Name of file resource to save. save_as -- Optional path name to write file to. If not specified, then file named by the last part of the resource path is downloaded to current directory. Return: (save_path, bytes) save_path -- Path where downloaded file was saved. bytes -- Bytes downloaded. """ |
self._check_session()
try:
if save_as:
save_as = os.path.normpath(save_as)
save_dir = os.path.dirname(save_as)
if save_dir:
if not os.path.exists(save_dir):
os.makedirs(save_dir)
elif not os.path.isdir(save_dir):
raise RuntimeError(save_dir + " is not a directory")
status, save_path, bytes = self._rest.download_file(
'files', file_name, save_as, 'application/octet-stream')
except resthttp.RestHttpError as e:
raise RuntimeError('failed to download "%s": %s' % (file_name, e))
return save_path, bytes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_all(self, dst_dir=None):
"""Download all available files. Arguments: dst_dir -- Optional destination directory to write files to. If not specified, then files are downloaded current directory. Return: Dictionary of {file_name: file_size, ..} """ |
saved = {}
save_as = None
for f in self.files():
if dst_dir:
save_as = os.path.join(dst_dir, f.split('/')[-1])
name, bytes = self.download(f, save_as)
saved[name] = bytes
return saved |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload(self, src_file_path, dst_file_name=None):
"""Upload the specified file to the server.""" |
self._check_session()
status, data = self._rest.upload_file(
'files', src_file_path, dst_file_name)
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wait_until_complete(self, timeout=None):
"""Wait until sequencer is finished. This method blocks your application until the sequencer has completed its operation. It returns once the sequencer has finished. Arguments: timeout -- Optional. Seconds to wait for sequencer to finish. If this time is exceeded, then an exception is raised. Return: Sequencer testState value. """ |
timeout_at = None
if timeout:
timeout_at = time.time() + int(timeout)
sequencer = self.get('system1', 'children-sequencer')
while True:
cur_test_state = self.get(sequencer, 'state')
if 'PAUSE' in cur_test_state or 'IDLE' in cur_test_state:
break
time.sleep(2)
if timeout_at and time.time() >= timeout_at:
raise RuntimeError('wait_until_complete timed out after %s sec'
% timeout)
return self.get(sequencer, 'testState') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mock_signal_receiver(signal, wraps=None, **kwargs):
""" Temporarily attaches a receiver to the provided ``signal`` within the scope of the context manager. The mocked receiver is returned as the ``as`` target of the ``with`` statement. To have the mocked receiver wrap a callable, pass the callable as the ``wraps`` keyword argument. All other keyword arguments provided are passed through to the signal's ``connect`` method. """ |
if wraps is None:
def wraps(*args, **kwrags):
return None
receiver = mock.Mock(wraps=wraps)
signal.connect(receiver, **kwargs)
yield receiver
signal.disconnect(receiver) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def QuerySetMock(model, *return_value):
""" Get a SharedMock that returns self for most attributes and a new copy of itself for any method that ordinarily generates QuerySets. Set the results to two items: Force an exception: Chain calls: """ |
def make_get(self, model):
def _get(*a, **k):
results = list(self)
if len(results) > 1:
raise model.MultipleObjectsReturned
try:
return results[0]
except IndexError:
raise model.DoesNotExist
return _get
def make_qs_returning_method(self):
def _qs_returning_method(*a, **k):
return copy.deepcopy(self)
return _qs_returning_method
def make_getitem(self):
def _getitem(k):
if isinstance(k, slice):
self.__start = k.start
self.__stop = k.stop
else:
return list(self)[k]
return self
return _getitem
def make_iterator(self):
def _iterator(*a, **k):
if len(return_value) == 1 and isinstance(return_value[0], Exception):
raise return_value[0]
start = getattr(self, '__start', None)
stop = getattr(self, '__stop', None)
for x in return_value[start:stop]:
yield x
return _iterator
actual_model = model
if actual_model:
model = mock.MagicMock(spec=actual_model())
else:
model = mock.MagicMock()
m = SharedMock(reserved=['count', 'exists'] + QUERYSET_RETURNING_METHODS)
m.__start = None
m.__stop = None
m.__iter__.side_effect = lambda: iter(m.iterator())
m.__getitem__.side_effect = make_getitem(m)
if hasattr(m, "__nonzero__"):
# Python 2
m.__nonzero__.side_effect = lambda: bool(return_value)
m.exists.side_effect = m.__nonzero__
else:
# Python 3
m.__bool__.side_effect = lambda: bool(return_value)
m.exists.side_effect = m.__bool__
m.__len__.side_effect = lambda: len(return_value)
m.count.side_effect = m.__len__
m.model = model
m.get = make_get(m, actual_model)
for method_name in QUERYSET_RETURNING_METHODS:
setattr(m, method_name, make_qs_returning_method(m))
# Note since this is a SharedMock, *all* auto-generated child
# attributes will have the same side_effect ... might not make
# sense for some like count().
m.iterator.side_effect = make_iterator(m)
return m |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def csrf_token():
""" Generate a token string from bytes arrays. The token in the session is user specific. """ |
if "_csrf_token" not in session:
session["_csrf_token"] = os.urandom(128)
return hmac.new(app.secret_key, session["_csrf_token"],
digestmod=sha1).hexdigest() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_csrf_token():
"""Checks that token is correct, aborting if not""" |
if request.method in ("GET",): # not exhaustive list
return
token = request.form.get("csrf_token")
if token is None:
app.logger.warning("Expected CSRF Token: not present")
abort(400)
if not safe_str_cmp(token, csrf_token()):
app.logger.warning("CSRF Token incorrect")
abort(400) |
<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_request(cls):
""" Get the HTTPRequest object from thread storage or from a callee by searching each frame in the call stack. """ |
request = cls.get_global('request')
if request:
return request
try:
stack = inspect.stack()
except IndexError:
# in some cases this may return an index error
# (pyc files dont match py files for example)
return
for frame, _, _, _, _, _ in stack:
if 'request' in frame.f_locals:
if isinstance(frame.f_locals['request'], HttpRequest):
request = frame.f_locals['request']
cls.set_global('request', request)
return request |
<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_response(sijax_response):
"""Takes a Sijax response object and returns a valid Flask response object.""" |
from types import GeneratorType
if isinstance(sijax_response, GeneratorType):
# Streaming response using a generator (non-JSON response).
# Upon returning a response, Flask would automatically destroy
# the request data and uploaded files - done by `flask.ctx.RequestContext.auto_pop()`
# We can't allow that, since the user-provided callback we're executing
# from within the generator may want to access request data/files.
# That's why we'll tell Flask to preserve the context and we'll clean up ourselves.
request.environ['flask._preserve_context'] = True
# Clean-up code taken from `flask.testing.TestingClient`
def clean_up_context():
top = _request_ctx_stack.top
if top is not None and top.preserved:
top.pop()
# As per the WSGI specification, `close()` would be called on iterator responses.
# Let's wrap the iterator in another one, which will forward that `close()` call to our clean-up callback.
response = Response(ClosingIterator(sijax_response, clean_up_context), direct_passthrough=True)
else:
# Non-streaming response - a single JSON string
response = Response(sijax_response)
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute_callback(self, *args, **kwargs):
"""Executes a callback and returns the proper response. Refer to :meth:`sijax.Sijax.execute_callback` for more details. """ |
response = self._sijax.execute_callback(*args, **kwargs)
return _make_response(response) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def logout(self, request):
"Logs out user and redirects them to Nexus home"
from django.contrib.auth import logout
logout(request)
return HttpResponseRedirect(reverse('nexus:index', current_app=self.name)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def dashboard(self, request):
"Basic dashboard panel"
# TODO: these should be ajax
module_set = []
for namespace, module in self.get_modules():
home_url = module.get_home_url(request)
if hasattr(module, 'render_on_dashboard'):
# Show by default, unless a permission is required
if not module.permission or request.user.has_perm(module.permission):
module_set.append((module.get_dashboard_title(), module.render_on_dashboard(request), home_url))
return self.render_to_response('nexus/dashboard.html', {
'module_set': module_set,
}, request) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def submit_row(context):
""" Displays the row of buttons for delete and save. """ |
opts = context['opts']
change = context['change']
is_popup = context['is_popup']
save_as = context['save_as']
return {
'onclick_attrib': (opts.get_ordered_objects() and change
and 'onclick="submitOrderForm();"' or ''),
'show_delete_link': (not is_popup and context['has_delete_permission']
and (change or context['show_delete'])),
'show_save_as_new': not is_popup and change and save_as,
'show_save_and_add_another': context['has_add_permission'] and
not is_popup and (not save_as or context['add']),
'show_save_and_continue': not is_popup and context['has_change_permission'],
'is_popup': is_popup,
'show_save': 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 autodiscover(site=None):
""" Auto-discover INSTALLED_APPS nexus.py modules and fail silently when not present. This forces an import on them to register any api bits they may want. Specifying ``site`` will register all auto discovered modules with the new site. """ |
# Bail out if autodiscover didn't finish loading from a previous call so
# that we avoid running autodiscover again when the URLconf is loaded by
# the exception handler to resolve the handler500 view. This prevents an
# admin.py module with errors from re-registering models and raising a
# spurious AlreadyRegistered exception (see #8245).
global LOADING
if LOADING:
return
LOADING = True
if site:
orig_site = globals()['site']
globals()['site'] = locals()['site']
import imp
from django.utils.importlib import import_module
from django.conf import settings
for app in settings.INSTALLED_APPS:
# For each app, we need to look for an api.py inside that app's
# package. We can't use os.path here -- recall that modules may be
# imported different ways (think zip files) -- so we need to get
# the app's __path__ and look for admin.py on that path.
# Step 1: find out the app's __path__ Import errors here will (and
# should) bubble up, but a missing __path__ (which is legal, but weird)
# fails silently -- apps that do weird things with __path__ might
# need to roll their own admin registration.
try:
app_path = import_module(app).__path__
except (AttributeError, ImportError):
continue
# Step 2: use imp.find_module to find the app's admin.py. For some
# reason imp.find_module raises ImportError if the app can't be found
# but doesn't actually try to import the module. So skip this app if
# its admin.py doesn't exist
try:
imp.find_module('nexus_modules', app_path)
except ImportError:
continue
# Step 3: import the app's admin file. If this has errors we want them
# to bubble up.
import_module("%s.nexus_modules" % app)
# # load builtins
# from gargoyle.builtins import *
if site:
globals()['site'] = orig_site
# autodiscover was successful, reset loading flag.
LOADING = False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getAllNodes(self):
'''
getAllNodes - Get every element
@return TagCollection<AdvancedTag>
'''
ret = TagCollection()
for rootNode in self.getRootNodes():
ret.append(rootNode)
ret += rootNode.getAllChildNodes()
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getElementsByAttr(self, attrName, attrValue, root='root'):
'''
getElementsByAttr - Searches the full tree for elements with a given attribute name and value combination. This is always a full scan.
@param attrName <lowercase str> - A lowercase attribute name
@param attrValue <str> - Expected value of attribute
@param root <AdvancedTag/'root'> - Search starting at a specific node, if provided. if string 'root', the root of the parsed tree will be used.
'''
(root, isFromRoot) = self._handleRootArg(root)
elements = []
if isFromRoot is True and root.getAttribute(attrName) == attrValue:
elements.append(root)
getElementsByAttr = self.getElementsByAttr
for child in root.children:
if child.getAttribute(attrName) == attrValue:
elements.append(child)
elements += getElementsByAttr(attrName, attrValue, child)
return TagCollection(elements) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getElementsCustomFilter(self, filterFunc, root='root'):
'''
getElementsCustomFilter - Scan elements using a provided function
@param filterFunc <function>(node) - A function that takes an AdvancedTag as an argument, and returns True if some arbitrary criteria is met
@return - TagCollection of all matching elements
'''
(root, isFromRoot) = self._handleRootArg(root)
elements = []
if isFromRoot is True and filterFunc(root) is True:
elements.append(root)
getElementsCustomFilter = self.getElementsCustomFilter
for child in root.children:
if filterFunc(child) is True:
elements.append(child)
elements += getElementsCustomFilter(filterFunc, child)
return TagCollection(elements) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getFirstElementCustomFilter(self, filterFunc, root='root'):
'''
getFirstElementCustomFilter - Scan elements using a provided function, stop and return the first match.
@see getElementsCustomFilter to match multiple elements
@param filterFunc <function>(node) - A function that takes an AdvancedTag as an argument, and returns True if some arbitrary criteria is met
@return - An AdvancedTag of the node that matched, or None if no match.
'''
(root, isFromRoot) = self._handleRootArg(root)
elements = []
if isFromRoot is True and filterFunc(root) is True:
return root
getFirstElementCustomFilter = self.getFirstElementCustomFilter
for child in root.children:
if filterFunc(child) is True:
return child
subRet = getFirstElementCustomFilter(filterFunc, child)
if subRet:
return subRet
return 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 getHTML(self):
'''
getHTML - Get the full HTML as contained within this tree.
If parsed from a document, this will contain the original whitespacing.
@returns - <str> of html
@see getFormattedHTML
@see getMiniHTML
'''
root = self.getRoot()
if root is None:
raise ValueError('Did not parse anything. Use parseFile or parseStr')
if self.doctype:
doctypeStr = '<!%s>\n' %(self.doctype)
else:
doctypeStr = ''
# 6.6.0: If we have a real root tag, print the outerHTML. If we have a fake root tag (for multiple root condition),
# then print the innerHTML (skipping the outer root tag). Otherwise, we will miss
# untagged text (between the multiple root nodes).
rootNode = self.getRoot()
if rootNode.tagName == INVISIBLE_ROOT_TAG:
return doctypeStr + rootNode.innerHTML
else:
return doctypeStr + rootNode.outerHTML |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getFormattedHTML(self, indent=' '):
'''
getFormattedHTML - Get formatted and xhtml of this document, replacing the original whitespace
with a pretty-printed version
@param indent - space/tab/newline of each level of indent, or integer for how many spaces per level
@return - <str> Formatted html
@see getHTML - Get HTML with original whitespace
@see getMiniHTML - Get HTML with only functional whitespace remaining
'''
from .Formatter import AdvancedHTMLFormatter
html = self.getHTML()
formatter = AdvancedHTMLFormatter(indent, None) # Do not double-encode
formatter.feed(html)
return formatter.getHTML() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getMiniHTML(self):
'''
getMiniHTML - Gets the HTML representation of this document without any pretty formatting
and disregarding original whitespace beyond the functional.
@return <str> - HTML with only functional whitespace present
'''
from .Formatter import AdvancedHTMLMiniFormatter
html = self.getHTML()
formatter = AdvancedHTMLMiniFormatter(None) # Do not double-encode
formatter.feed(html)
return formatter.getHTML() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def feed(self, contents):
'''
feed - Feed contents. Use parseStr or parseFile instead.
@param contents - Contents
'''
contents = stripIEConditionals(contents)
try:
HTMLParser.feed(self, contents)
except MultipleRootNodeException:
self.reset()
HTMLParser.feed(self, "%s%s" %(addStartTag(contents, INVISIBLE_ROOT_TAG_START), INVISIBLE_ROOT_TAG_END)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def parseFile(self, filename):
'''
parseFile - Parses a file and creates the DOM tree and indexes
@param filename <str/file> - A string to a filename or a file object. If file object, it will not be closed, you must close.
'''
self.reset()
if isinstance(filename, file):
contents = filename.read()
else:
with codecs.open(filename, 'r', encoding=self.encoding) as f:
contents = f.read()
self.feed(contents) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def parseStr(self, html):
'''
parseStr - Parses a string and creates the DOM tree and indexes.
@param html <str> - valid HTML
'''
self.reset()
if isinstance(html, bytes):
self.feed(html.decode(self.encoding))
else:
self.feed(html) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def createElementFromHTML(cls, html, encoding='utf-8'):
'''
createElementFromHTML - Creates an element from a string of HTML.
If this could create multiple root-level elements (children are okay),
you must use #createElementsFromHTML which returns a list of elements created.
@param html <str> - Some html data
@param encoding <str> - Encoding to use for document
@raises MultipleRootNodeException - If given html would produce multiple root-level elements (use #createElementsFromHTML instead)
@return AdvancedTag - A single AdvancedTag
NOTE: If there is text outside the tag, they will be lost in this.
Use createBlocksFromHTML instead if you need to retain both text and tags.
Also, if you are just appending to an existing tag, use AdvancedTag.appendInnerHTML
'''
parser = cls(encoding=encoding)
html = stripIEConditionals(html)
try:
HTMLParser.feed(parser, html)
except MultipleRootNodeException:
raise MultipleRootNodeException('Multiple nodes passed to createElementFromHTML method. Use #createElementsFromHTML instead to get a list of AdvancedTag elements.')
rootNode = parser.getRoot()
rootNode.remove()
return rootNode |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def createElementsFromHTML(cls, html, encoding='utf-8'):
'''
createElementsFromHTML - Creates elements from provided html, and returns a list of the root-level elements
children of these root-level nodes are accessable via the usual means.
@param html <str> - Some html data
@param encoding <str> - Encoding to use for document
@return list<AdvancedTag> - The root (top-level) tags from parsed html.
NOTE: If there is text outside the tags, they will be lost in this.
Use createBlocksFromHTML instead if you need to retain both text and tags.
Also, if you are just appending to an existing tag, use AdvancedTag.appendInnerHTML
'''
# TODO: If text is present outside a tag, it will be lost.
parser = cls(encoding=encoding)
parser.parseStr(html)
rootNode = parser.getRoot()
rootNode.remove() # Detatch from temp document
if isInvisibleRootTag(rootNode):
return rootNode.children
return [rootNode] |
<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_starttag(self, tagName, attributeList, isSelfClosing=False):
'''
internal for parsing
'''
newTag = AdvancedHTMLParser.handle_starttag(self, tagName, attributeList, isSelfClosing)
self._indexTag(newTag)
return newTag |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def reindex(self, newIndexIDs=None, newIndexNames=None, newIndexClassNames=None, newIndexTagNames=None):
'''
reindex - reindex the tree. Optionally, change what fields are indexed.
@param newIndexIDs <bool/None> - None to leave same, otherwise new value to index IDs
@parma newIndexNames <bool/None> - None to leave same, otherwise new value to index names
@param newIndexClassNames <bool/None> - None to leave same, otherwise new value to index class names
@param newIndexTagNames <bool/None> - None to leave same, otherwise new value to index tag names
'''
if newIndexIDs is not None:
self.indexIDs = newIndexIDs
if newIndexNames is not None:
self.indexNames = newIndexNames
if newIndexClassNames is not None:
self.newIndexClassNames = newIndexClassNames
if newIndexTagNames is not None:
self.newIndexTagNames = newIndexTagNames
self._resetIndexInternal()
self._indexTagRecursive(self.root) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def disableIndexing(self):
'''
disableIndexing - Disables indexing. Consider using plain AdvancedHTMLParser class.
Maybe useful in some scenarios where you want to parse, add a ton of elements, then index
and do a bunch of searching.
'''
self.indexIDs = self.indexNames = self.indexClassNames = self.indexTagNames = False
self._resetIndexInternal() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def addIndexOnAttribute(self, attributeName):
'''
addIndexOnAttribute - Add an index for an arbitrary attribute. This will be used by the getElementsByAttr function.
You should do this prior to parsing, or call reindex. Otherwise it will be blank. "name" and "id" will have no effect.
@param attributeName <lowercase str> - An attribute name. Will be lowercased.
'''
attributeName = attributeName.lower()
self._otherAttributeIndexes[attributeName] = {}
def _otherIndexFunction(self, tag):
thisAttribute = tag.getAttribute(attributeName)
if thisAttribute is not None:
if thisAttribute not in self._otherAttributeIndexes[attributeName]:
self._otherAttributeIndexes[attributeName][thisAttribute] = []
self._otherAttributeIndexes[attributeName][thisAttribute].append(tag)
self.otherAttributeIndexFunctions[attributeName] = _otherIndexFunction |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getElementsByAttr(self, attrName, attrValue, root='root', useIndex=True):
'''
getElementsByAttr - Searches the full tree for elements with a given attribute name and value combination. If you want multiple potential values, see getElementsWithAttrValues
If you want an index on a random attribute, use the addIndexOnAttribute function.
@param attrName <lowercase str> - A lowercase attribute name
@param attrValue <str> - Expected value of attribute
@param root <AdvancedTag/'root'> - Search starting at a specific node, if provided. if string 'root', the root of the parsed tree will be used.
@param useIndex <bool> If useIndex is True and this specific attribute is indexed [see addIndexOnAttribute] only the index will be used. Otherwise a full search is performed.
'''
(root, isFromRoot) = self._handleRootArg(root)
if useIndex is True and attrName in self._otherAttributeIndexes:
elements = self._otherAttributeIndexes[attrName].get(attrValue, [])
if isFromRoot is False:
_hasTagInParentLine = self._hasTagInParentLine
elements = [x for x in elements if _hasTagInParentLine(x, root)]
return TagCollection(elements)
return AdvancedHTMLParser.getElementsByAttr(self, attrName, attrValue, root) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def uniqueTags(tagList):
'''
uniqueTags - Returns the unique tags in tagList.
@param tagList list<AdvancedTag> : A list of tag objects.
'''
ret = []
alreadyAdded = set()
for tag in tagList:
myUid = tag.getUid()
if myUid in alreadyAdded:
continue
ret.append(tag)
return TagCollection(ret) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def toggleAttributesDOM(isEnabled):
'''
toggleAttributesDOM - Toggle if the old DOM tag.attributes NamedNodeMap model should be used for the .attributes method, versus
a more sane direct dict implementation.
The DOM version is always accessable as AdvancedTag.attributesDOM
The dict version is always accessable as AdvancedTag.attributesDict
Default for AdvancedTag.attributes is to be attributesDict implementation.
@param isEnabled <bool> - If True, .attributes will be changed to use the DOM-provider. Otherwise, it will use the dict provider.
'''
if isEnabled:
AdvancedTag.attributes = AdvancedTag.attributesDOM
else:
AdvancedTag.attributes = AdvancedTag.attributesDict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def appendText(self, text):
'''
appendText - append some inner text
'''
# self.text is just raw string of the text
self.text += text
self.isSelfClosing = False # inner text means it can't self close anymo
# self.blocks is either text or tags, in order of appearance
self.blocks.append(text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def appendChild(self, child):
'''
appendChild - Append a child to this element.
@param child <AdvancedTag> - Append a child element to this element
'''
# Associate parentNode of #child to this tag
child.parentNode = self
# Associate owner document to child and all children recursive
ownerDocument = self.ownerDocument
child.ownerDocument = ownerDocument
for subChild in child.getAllChildNodes():
subChild.ownerDocument = ownerDocument
# Our tag cannot be self-closing if we have a child tag
self.isSelfClosing = False
# Append to both "children" and "blocks"
self.children.append(child)
self.blocks.append(child)
return child |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def appendInnerHTML(self, html):
'''
appendInnerHTML - Appends nodes from arbitrary HTML as if doing element.innerHTML += 'someHTML' in javascript.
@param html <str> - Some HTML
NOTE: If associated with a document ( AdvancedHTMLParser ), the html will use the encoding associated with
that document.
@return - None. A browser would return innerHTML, but that's somewhat expensive on a high-level node.
So just call .innerHTML explicitly if you need that
'''
# Late-binding to prevent circular import
from .Parser import AdvancedHTMLParser
# Inherit encoding from the associated document, if any.
encoding = None
if self.ownerDocument:
encoding = self.ownerDocument.encoding
# Generate blocks (text nodes and AdvancedTag's) from HTML
blocks = AdvancedHTMLParser.createBlocksFromHTML(html, encoding)
# Throw them onto this node
self.appendBlocks(blocks) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def removeChild(self, child):
'''
removeChild - Remove a child tag, if present.
@param child <AdvancedTag> - The child to remove
@return - The child [with parentNode cleared] if removed, otherwise None.
NOTE: This removes a tag. If removing a text block, use #removeText function.
If you need to remove an arbitrary block (text or AdvancedTag), @see removeBlock
Removing multiple children? @see removeChildren
'''
try:
# Remove from children and blocks
self.children.remove(child)
self.blocks.remove(child)
# Clear parent node association on child
child.parentNode = None
# Clear document reference on removed child and all children thereof
child.ownerDocument = None
for subChild in child.getAllChildNodes():
subChild.ownerDocument = None
return child
except ValueError:
# TODO: What circumstances cause this to be raised? Is it okay to have a partial remove?
#
# Is it only when "child" is not found? Should that just be explicitly tested?
return 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 removeChildren(self, children):
'''
removeChildren - Remove multiple child AdvancedTags.
@see removeChild
@return list<AdvancedTag/None> - A list of all tags removed in same order as passed.
Item is "None" if it was not attached to this node, and thus was not removed.
'''
ret = []
for child in children:
ret.append( self.removeChild(child) )
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def firstChild(self):
'''
firstChild - property, Get the first child block, text or tag.
@return <str/AdvancedTag/None> - The first child block, or None if no child blocks
'''
blocks = object.__getattribute__(self, 'blocks')
# First block is empty string for indent, but don't hardcode incase that changes
if blocks[0] == '':
firstIdx = 1
else:
firstIdx = 0
if len(blocks) == firstIdx:
# No first child
return None
return blocks[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 lastChild(self):
'''
lastChild - property, Get the last child block, text or tag
@return <str/AdvancedTag/None> - The last child block, or None if no child blocks
'''
blocks = object.__getattribute__(self, 'blocks')
# First block is empty string for indent, but don't hardcode incase that changes
if blocks[0] == '':
firstIdx = 1
else:
firstIdx = 0
if len(blocks) <= firstIdx:
return None
return blocks[-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 nextSibling(self):
'''
nextSibling - Returns the next sibling. This is the child following this node in the parent's list of children.
This could be text or an element. use nextSiblingElement to ensure element
@return <None/str/AdvancedTag> - None if there are no nodes (text or tag) in the parent after this node,
Otherwise the following node (text or tag)
'''
parentNode = self.parentNode
# If no parent, no siblings.
if not parentNode:
return None
# Determine index in blocks
myBlockIdx = parentNode.blocks.index(self)
# If we are the last, no next sibling
if myBlockIdx == len(parentNode.blocks) - 1:
return None
# Else, return the next block in parent
return parentNode.blocks[ myBlockIdx + 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 nextElementSibling(self):
'''
nextElementSibling - Returns the next sibling that is an element.
This is the tag node following this node in the parent's list of children
@return <None/AdvancedTag> - None if there are no children (tag) in the parent after this node,
Otherwise the following element (tag)
'''
parentNode = self.parentNode
# If no parent, no siblings
if not parentNode:
return None
# Determine the index in children
myElementIdx = parentNode.children.index(self)
# If we are last child, no next sibling
if myElementIdx == len(parentNode.children) - 1:
return None
# Else, return the next child in parent
return parentNode.children[myElementIdx+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 previousElementSibling(self):
'''
previousElementSibling - Returns the previous sibling that is an element.
This is the previous tag node in the parent's list of children
@return <None/AdvancedTag> - None if there are no children (tag) in the parent before this node,
Otherwise the previous element (tag)
'''
parentNode = self.parentNode
# If no parent, no siblings
if not parentNode:
return None
# Determine this node's index in the children of parent
myElementIdx = parentNode.children.index(self)
# If we are the first child, no previous element
if myElementIdx == 0:
return None
# Else, return previous element tag
return parentNode.children[myElementIdx-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 getBlocksTags(self):
'''
getBlocksTags - Returns a list of tuples referencing the blocks which are direct children of this node, and the block is an AdvancedTag.
The tuples are ( block, blockIdx ) where "blockIdx" is the index of self.blocks wherein the tag resides.
@return list< tuple(block, blockIdx) > - A list of tuples of child blocks which are tags and their index in the self.blocks list
'''
myBlocks = self.blocks
return [ (myBlocks[i], i) for i in range( len(myBlocks) ) if issubclass(myBlocks[i].__class__, AdvancedTag) ] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def textContent(self):
'''
textContent - property, gets the text of this node and all inner nodes.
Use .innerText for just this node's text
@return <str> - The text of all nodes at this level or lower
'''
def _collateText(curNode):
'''
_collateText - Recursive function to gather the "text" of all blocks
in the order that they appear
@param curNode <AdvancedTag> - The current AdvancedTag to process
@return list<str> - A list of strings in order. Join using '' to obtain text
as it would appear
'''
curStrLst = []
blocks = object.__getattribute__(curNode, 'blocks')
for block in blocks:
if isTagNode(block):
curStrLst += _collateText(block)
else:
curStrLst.append(block)
return curStrLst
return ''.join(_collateText(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 getAllChildNodes(self):
'''
getAllChildNodes - Gets all the children, and their children,
and their children, and so on, all the way to the end as a TagCollection.
Use .childNodes for a regular list
@return TagCollection<AdvancedTag> - A TagCollection of all children (and their children recursive)
'''
ret = TagCollection()
# Scan all the children of this node
for child in self.children:
# Append each child
ret.append(child)
# Append children's children recursive
ret += child.getAllChildNodes()
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getAllChildNodeUids(self):
'''
getAllChildNodeUids - Returns all the unique internal IDs for all children, and there children,
so on and so forth until the end.
For performing "contains node" kind of logic, this is more efficent than copying the entire nodeset
@return set<uuid.UUID> A set of uuid objects
'''
ret = set()
# Iterate through all children
for child in self.children:
# Add child's uid
ret.add(child.uid)
# Add child's children's uid and their children, recursive
ret.update(child.getAllChildNodeUids())
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getAllNodeUids(self):
'''
getAllNodeUids - Returns all the unique internal IDs from getAllChildNodeUids, but also includes this tag's uid
@return set<uuid.UUID> A set of uuid objects
'''
# Start with a set including this tag's uuid
ret = { self.uid }
ret.update(self.getAllChildNodeUids())
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getPeers(self):
'''
getPeers - Get elements who share a parent with this element
@return - TagCollection of elements
'''
parentNode = self.parentNode
# If no parent, no peers
if not parentNode:
return None
peers = parentNode.children
# Otherwise, get all children of parent excluding this node
return TagCollection([peer for peer in peers if peer is not 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 getStartTag(self):
'''
getStartTag - Returns the start tag represented as HTML
@return - String of start tag with attributes
'''
attributeStrings = []
# Get all attributes as a tuple (name<str>, value<str>)
for name, val in self._attributes.items():
# Get all attributes
if val:
val = tostr(val)
# Only binary attributes have a "present/not present"
if val or name not in TAG_ITEM_BINARY_ATTRIBUTES:
# Escape any quotes found in the value
val = escapeQuotes(val)
# Add a name="value" to the resulting string
attributeStrings.append('%s="%s"' %(name, val) )
else:
# This is a binary attribute, and thus only includes the name ( e.x. checked )
attributeStrings.append(name)
# Join together all the attributes in @attributeStrings list into a string
if attributeStrings:
attributeString = ' ' + ' '.join(attributeStrings)
else:
attributeString = ''
# If this is a self-closing tag, generate like <tag attr1="val" attr2="val2" /> with the close "/>"
# Include the indent prior to tag opening
if self.isSelfClosing is False:
return "%s<%s%s >" %(self._indent, self.tagName, attributeString)
else:
return "%s<%s%s />" %(self._indent, self.tagName, attributeString) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getEndTag(self):
'''
getEndTag - returns the end tag representation as HTML string
@return - String of end tag
'''
# If this is a self-closing tag, we have no end tag (opens and closes in the start)
if self.isSelfClosing is True:
return ''
tagName = self.tagName
# Do not add any indentation to the end of preformatted tags.
if self._indent and tagName in PREFORMATTED_TAGS:
return "</%s>" %(tagName, )
# Otherwise, indent the end of this tag
return "%s</%s>" %(self._indent, tagName) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.