text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Set textContent both on this node and related browser node.
<END_TASK>
<USER_TASK:>
Description:
def textContent(self, text: str) -> None: # type: ignore
"""Set textContent both on this node and related browser node.""" |
self._set_text_content(text)
if self.connected:
self._set_text_content_web(text) |
<SYSTEM_TASK:>
Set innerHTML both on this node and related browser node.
<END_TASK>
<USER_TASK:>
Description:
def innerHTML(self, html: str) -> None: # type: ignore
"""Set innerHTML both on this node and related browser node.""" |
df = self._parse_html(html)
if self.connected:
self._set_inner_html_web(df.html)
self._empty()
self._append_child(df) |
<SYSTEM_TASK:>
Cleanup temporary directory.
<END_TASK>
<USER_TASK:>
Description:
def _cleanup(path: str) -> None:
"""Cleanup temporary directory.""" |
if os.path.isdir(path):
shutil.rmtree(path) |
<SYSTEM_TASK:>
Create element with a tag of ``name``.
<END_TASK>
<USER_TASK:>
Description:
def create_element(tag: str, name: str = None, base: type = None,
attr: dict = None) -> Node:
"""Create element with a tag of ``name``.
:arg str name: html tag.
:arg type base: Base class of the created element
(defatlt: ``WdomElement``)
:arg dict attr: Attributes (key-value pairs dict) of the new element.
""" |
from wdom.web_node import WdomElement
from wdom.tag import Tag
from wdom.window import customElements
if attr is None:
attr = {}
if name:
base_class = customElements.get((name, tag))
else:
base_class = customElements.get((tag, None))
if base_class is None:
attr['_registered'] = False
base_class = base or WdomElement
if issubclass(base_class, Tag):
return base_class(**attr)
return base_class(tag, **attr) |
<SYSTEM_TASK:>
Get elements in this document which matches condition.
<END_TASK>
<USER_TASK:>
Description:
def getElementsBy(self, cond: Callable[[Element], bool]) -> NodeList:
"""Get elements in this document which matches condition.""" |
return getElementsBy(self, cond) |
<SYSTEM_TASK:>
Get element by ``id``.
<END_TASK>
<USER_TASK:>
Description:
def getElementById(self, id: str) -> Optional[Node]:
"""Get element by ``id``.
If this document does not have the element with the id, return None.
""" |
elm = getElementById(id)
if elm and elm.ownerDocument is self:
return elm
return None |
<SYSTEM_TASK:>
Create new element whose tag name is ``tag``.
<END_TASK>
<USER_TASK:>
Description:
def createElement(self, tag: str) -> Node:
"""Create new element whose tag name is ``tag``.""" |
return create_element(tag, base=self._default_class) |
<SYSTEM_TASK:>
Get an element node with ``wdom_id``.
<END_TASK>
<USER_TASK:>
Description:
def getElementByWdomId(self, id: Union[str]) -> Optional[WebEventTarget]:
"""Get an element node with ``wdom_id``.
If this document does not have the element with the id, return None.
""" |
elm = getElementByWdomId(id)
if elm and elm.ownerDocument is self:
return elm
return None |
<SYSTEM_TASK:>
Add JS file to load at this document's bottom of the body.
<END_TASK>
<USER_TASK:>
Description:
def add_jsfile(self, src: str) -> None:
"""Add JS file to load at this document's bottom of the body.""" |
self.body.appendChild(Script(src=src)) |
<SYSTEM_TASK:>
Add JS file to load at this document's header.
<END_TASK>
<USER_TASK:>
Description:
def add_jsfile_head(self, src: str) -> None:
"""Add JS file to load at this document's header.""" |
self.head.appendChild(Script(src=src)) |
<SYSTEM_TASK:>
Add CSS file to load at this document's header.
<END_TASK>
<USER_TASK:>
Description:
def add_cssfile(self, src: str) -> None:
"""Add CSS file to load at this document's header.""" |
self.head.appendChild(Link(rel='stylesheet', href=src)) |
<SYSTEM_TASK:>
Set theme for this docuemnt.
<END_TASK>
<USER_TASK:>
Description:
def register_theme(self, theme: ModuleType) -> None:
"""Set theme for this docuemnt.
This method sets theme's js/css files and headers on this document.
:arg ModuleType theme: a module which has ``js_files``, ``css_files``,
``headers``, and ``extended_classes``. see ``wdom.themes``
directory actual theme module structures.
""" |
if not hasattr(theme, 'css_files'):
raise ValueError('theme module must include `css_files`.')
for css in getattr(theme, 'css_files', []):
self.add_cssfile(css)
for js in getattr(theme, 'js_files', []):
self.add_jsfile(js)
for header in getattr(theme, 'headers', []):
self.add_header(header)
for cls in getattr(theme, 'extended_classes', []):
self.defaultView.customElements.define(cls) |
<SYSTEM_TASK:>
Send message via WS to all client connections.
<END_TASK>
<USER_TASK:>
Description:
def send_message() -> None:
"""Send message via WS to all client connections.""" |
if not _msg_queue:
return
msg = json.dumps(_msg_queue)
_msg_queue.clear()
for conn in module.connections:
conn.write_message(msg) |
<SYSTEM_TASK:>
Add directory to serve static files.
<END_TASK>
<USER_TASK:>
Description:
def add_static_path(prefix: str, path: str, no_watch: bool = False) -> None:
"""Add directory to serve static files.
First argument ``prefix`` is a URL prefix for the ``path``. ``path`` must
be a directory. If ``no_watch`` is True, any change of the files in the
path do not trigger restart if ``--autoreload`` is enabled.
""" |
app = get_app()
app.add_static_path(prefix, path)
if not no_watch:
watch_dir(path) |
<SYSTEM_TASK:>
Start web server.
<END_TASK>
<USER_TASK:>
Description:
def start(**kwargs: Any) -> None:
"""Start web server.
Run until ``Ctrl-c`` pressed, or if auto-shutdown is enabled, until when
all browser windows are closed.
This function accepts keyword areguments same as :func:`start_server` and
all arguments passed to it.
""" |
start_server(**kwargs)
try:
asyncio.get_event_loop().run_forever()
except KeyboardInterrupt:
stop_server() |
<SYSTEM_TASK:>
Handle response sent by browser.
<END_TASK>
<USER_TASK:>
Description:
def response_handler(msg: Dict[str, str]) -> None:
"""Handle response sent by browser.""" |
from wdom.document import getElementByWdomId
id = msg['id']
elm = getElementByWdomId(id)
if elm:
elm.on_response(msg)
else:
logger.warning('No such element: wdom_id={}'.format(id)) |
<SYSTEM_TASK:>
Handle messages from browser.
<END_TASK>
<USER_TASK:>
Description:
def on_websocket_message(message: str) -> None:
"""Handle messages from browser.""" |
msgs = json.loads(message)
for msg in msgs:
if not isinstance(msg, dict):
logger.error('Invalid WS message format: {}'.format(message))
continue
_type = msg.get('type')
if _type == 'log':
log_handler(msg['level'], msg['message'])
elif _type == 'event':
event_handler(msg['event'])
elif _type == 'response':
response_handler(msg)
else:
raise ValueError('Unkown message type: {}'.format(message)) |
<SYSTEM_TASK:>
Return list of child elements of start_node which matches ``cond``.
<END_TASK>
<USER_TASK:>
Description:
def getElementsBy(start_node: ParentNode,
cond: Callable[['Element'], bool]) -> NodeList:
"""Return list of child elements of start_node which matches ``cond``.
``cond`` must be a function which gets a single argument ``Element``,
and returns boolean. If the node matches requested condition, ``cond``
should return True.
This searches all child elements recursively.
:arg ParentNode start_node:
:arg cond: Callable[[Element], bool]
:rtype: NodeList[Element]
""" |
elements = []
for child in start_node.children:
if cond(child):
elements.append(child)
elements.extend(child.getElementsBy(cond))
return NodeList(elements) |
<SYSTEM_TASK:>
Get child nodes which tag name is ``tag``.
<END_TASK>
<USER_TASK:>
Description:
def getElementsByTagName(start_node: ParentNode, tag: str) -> NodeList:
"""Get child nodes which tag name is ``tag``.""" |
_tag = tag.upper()
return getElementsBy(start_node, lambda node: node.tagName == _tag) |
<SYSTEM_TASK:>
Get child nodes which has ``class_name`` class attribute.
<END_TASK>
<USER_TASK:>
Description:
def getElementsByClassName(start_node: ParentNode, class_name: str
) -> NodeList:
"""Get child nodes which has ``class_name`` class attribute.""" |
classes = set(class_name.split(' '))
return getElementsBy(
start_node,
lambda node: classes.issubset(set(node.classList))
) |
<SYSTEM_TASK:>
Remove tokens from list.
<END_TASK>
<USER_TASK:>
Description:
def remove(self, *tokens: str) -> None:
"""Remove tokens from list.""" |
from wdom.web_node import WdomElement
_removed_tokens = []
for token in tokens:
self._validate_token(token)
if token in self:
self._list.remove(token)
_removed_tokens.append(token)
if isinstance(self._owner, WdomElement) and _removed_tokens:
self._owner.js_exec('removeClass', _removed_tokens) |
<SYSTEM_TASK:>
Return if the token is in the list or not.
<END_TASK>
<USER_TASK:>
Description:
def contains(self, token: str) -> bool:
"""Return if the token is in the list or not.""" |
self._validate_token(token)
return token in self |
<SYSTEM_TASK:>
Return string representation of this.
<END_TASK>
<USER_TASK:>
Description:
def html(self) -> str:
"""Return string representation of this.
Used in start tag of HTML representation of the Element node.
""" |
if self._owner and self.name in self._owner._special_attr_boolean:
return self.name
else:
value = self.value
if isinstance(value, str):
value = html_.escape(value)
return '{name}="{value}"'.format(name=self.name, value=value) |
<SYSTEM_TASK:>
Get ``Attr`` object which has ``name``.
<END_TASK>
<USER_TASK:>
Description:
def getNamedItem(self, name: str) -> Optional[Attr]:
"""Get ``Attr`` object which has ``name``.
If does not have ``name`` attr, return None.
""" |
return self._dict.get(name, None) |
<SYSTEM_TASK:>
Parse ``html`` to DOM and insert to ``position``.
<END_TASK>
<USER_TASK:>
Description:
def insertAdjacentHTML(self, position: str, html: str) -> None:
"""Parse ``html`` to DOM and insert to ``position``.
``position`` is a case-insensive string, and must be one of
"beforeBegin", "afterBegin", "beforeEnd", or "afterEnd".
""" |
df = self._parse_html(html)
pos = position.lower()
if pos == 'beforebegin':
self.before(df)
elif pos == 'afterbegin':
self.prepend(df)
elif pos == 'beforeend':
self.append(df)
elif pos == 'afterend':
self.after(df)
else:
raise ValueError(
'The value provided ({}) is not one of "beforeBegin", '
'"afterBegin", "beforeEnd", or "afterEnd".'.format(position)
) |
<SYSTEM_TASK:>
Get attribute of this node as string format.
<END_TASK>
<USER_TASK:>
Description:
def getAttribute(self, attr: str) -> _AttrValueType:
"""Get attribute of this node as string format.
If this node does not have ``attr``, return None.
""" |
if attr == 'class':
if self.classList:
return self.classList.toString()
return None
attr_node = self.getAttributeNode(attr)
if attr_node is None:
return None
return attr_node.value |
<SYSTEM_TASK:>
Get attribute of this node as Attr format.
<END_TASK>
<USER_TASK:>
Description:
def getAttributeNode(self, attr: str) -> Optional[Attr]:
"""Get attribute of this node as Attr format.
If this node does not have ``attr``, return None.
""" |
return self.attributes.getNamedItem(attr) |
<SYSTEM_TASK:>
Return True if this node has ``attr``.
<END_TASK>
<USER_TASK:>
Description:
def hasAttribute(self, attr: str) -> bool:
"""Return True if this node has ``attr``.""" |
if attr == 'class':
return bool(self.classList)
return attr in self.attributes |
<SYSTEM_TASK:>
Set ``attr`` and ``value`` in this node.
<END_TASK>
<USER_TASK:>
Description:
def setAttribute(self, attr: str, value: _AttrValueType) -> None:
"""Set ``attr`` and ``value`` in this node.""" |
self._set_attribute(attr, value) |
<SYSTEM_TASK:>
Remove ``Attr`` node from this node.
<END_TASK>
<USER_TASK:>
Description:
def removeAttributeNode(self, attr: Attr) -> Optional[Attr]:
"""Remove ``Attr`` node from this node.""" |
return self.attributes.removeNamedItem(attr) |
<SYSTEM_TASK:>
Set style attribute of this node.
<END_TASK>
<USER_TASK:>
Description:
def style(self, style: _AttrValueType) -> None:
"""Set style attribute of this node.
If argument ``style`` is string, it will be parsed to
``CSSStyleDeclaration``.
""" |
if isinstance(style, str):
self.__style._parse_str(style)
elif style is None:
self.__style._parse_str('')
elif isinstance(style, CSSStyleDeclaration):
self.__style._owner = None
if style._owner is not None:
new_style = CSSStyleDeclaration(owner=self)
new_style.update(style)
self.__style = new_style
else:
# always making new decl may be better
style._owner = self
self.__style = style
else:
raise TypeError('Invalid type for style: {}'.format(type(style))) |
<SYSTEM_TASK:>
Set ``draggable`` property.
<END_TASK>
<USER_TASK:>
Description:
def draggable(self, value: Union[bool, str]) -> None:
"""Set ``draggable`` property.
``value`` is boolean or string.
""" |
if value is False:
self.removeAttribute('draggable')
else:
self.setAttribute('draggable', value) |
<SYSTEM_TASK:>
Generate and return new ``Tag`` class.
<END_TASK>
<USER_TASK:>
Description:
def NewTagClass(class_name: str, tag: str = None,
bases: Union[type, Iterable] = (Tag, ),
**kwargs: Any) -> type:
"""Generate and return new ``Tag`` class.
If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of
the new class. ``bases`` should be a tuple of base classes. If it is empty,
use ``Tag`` class for a base class. Other keyword arguments are used for
class variables of the new class.
Example::
MyButton = NewTagClass('MyButton', 'button', (Button,),
class_='btn', is_='my-button')
my_button = MyButton('Click!')
print(my_button.html)
>>> <button class="btn" id="111111111" is="my-button">Click!</button>
""" |
if tag is None:
tag = class_name.lower()
if not isinstance(type, tuple):
if isinstance(bases, Iterable):
bases = tuple(bases)
elif isinstance(bases, type):
bases = (bases, )
else:
TypeError('Invalid base class: {}'.format(str(bases)))
kwargs['tag'] = tag
# Here not use type() function, since it does not support
# metaclasss (__prepare__) properly.
cls = new_class( # type: ignore
class_name, bases, {}, lambda ns: ns.update(kwargs))
return cls |
<SYSTEM_TASK:>
Need to copy class, not tag.
<END_TASK>
<USER_TASK:>
Description:
def _clone_node(self) -> 'Tag':
"""Need to copy class, not tag.
So need to re-implement copy.
""" |
clone = type(self)()
for attr in self.attributes:
clone.setAttribute(attr, self.getAttribute(attr))
for c in self.classList:
clone.addClass(c)
clone.style.update(self.style)
# TODO: should clone event listeners???
return clone |
<SYSTEM_TASK:>
Terminate server if no more connection exists.
<END_TASK>
<USER_TASK:>
Description:
async def terminate(self) -> None:
"""Terminate server if no more connection exists.""" |
await asyncio.sleep(config.shutdown_wait)
# stop server and close loop if no more connection exists
if not is_connected():
stop_server(self.application.server)
self.application.loop.stop() |
<SYSTEM_TASK:>
Execute when connection closed.
<END_TASK>
<USER_TASK:>
Description:
def on_close(self) -> None:
"""Execute when connection closed.""" |
logger.info('WebSocket CLOSED')
if self in connections:
# Remove this connection from connection-list
connections.remove(self)
# close if auto_shutdown is enabled and there is no more connection
if config.auto_shutdown and not is_connected():
asyncio.ensure_future(self.terminate()) |
<SYSTEM_TASK:>
Add path to serve static files.
<END_TASK>
<USER_TASK:>
Description:
def add_static_path(self, prefix: str, path: str) -> None:
"""Add path to serve static files.
``prefix`` is used for url prefix to serve static files and ``path`` is
a path to the static file directory. ``prefix = '/_static'`` is
reserved for the server, so do not use it for your app.
""" |
pattern = prefix
if not pattern.startswith('/'):
pattern = '/' + pattern
if not pattern.endswith('/(.*)'):
pattern = pattern + '/(.*)'
self.add_handlers(
r'.*', # add static path for all virtual host
[(pattern, StaticFileHandler, dict(path=path))]
) |
<SYSTEM_TASK:>
Add path to serve favicon file.
<END_TASK>
<USER_TASK:>
Description:
def add_favicon_path(self, path: str) -> None:
"""Add path to serve favicon file.
``path`` should be a directory, which contains favicon file
(``favicon.ico``) for your app.
""" |
spec = web.URLSpec(
'/(favicon.ico)',
StaticFileHandler,
dict(path=path)
)
# Need some check
handlers = self.handlers[0][1]
handlers.append(spec) |
<SYSTEM_TASK:>
Private method to implement the deploy, invoke and query actions
<END_TASK>
<USER_TASK:>
Description:
def _exec_action(self,
method,
type,
chaincodeID,
function,
args,
id,
secure_context=None,
confidentiality_level=CHAINCODE_CONFIDENTIAL_PUB,
metadata=None):
""" Private method to implement the deploy, invoke and query actions
Following http://www.jsonrpc.org/specification.
:param method: Chaincode action to exec. MUST within
DEFAULT_CHAINCODE_METHODS.
:param type: chaincode language type: 1 for golang, 2 for node.
:param chaincodeID: May include name or path.
:param function: chaincode function name.
:param args: chaincode function args.
:param id: JSON-RPC requires this value for a response.
:param secure_context: secure context if enable authentication.
:param confidentiality_level: level of confidentiality.
:param metadata: Metadata by client.
""" |
if method not in DEFAULT_CHAINCODE_METHODS:
self.logger.error('Non-supported chaincode method: '+method)
data = {
"jsonrpc": "2.0", # JSON-RPC protocol version. MUST be "2.0".
"method": method,
"params": {
"type": type,
"chaincodeID": chaincodeID,
"ctorMsg": {
"function": function,
"args": args
}
},
"id": id
}
if secure_context:
data["params"]["secureContext"] = secure_context
u = self._url("/chaincode")
response = self._post(u, data=json.dumps(data))
return self._result(response, True) |
<SYSTEM_TASK:>
Set property as the value.
<END_TASK>
<USER_TASK:>
Description:
def setProperty(self, prop: str, value: str, priority: str = None
) -> None:
"""Set property as the value.
The third argument ``priority`` is not implemented yet.
""" |
self[prop] = value |
<SYSTEM_TASK:>
Return string representation of this rule.
<END_TASK>
<USER_TASK:>
Description:
def cssText(self) -> str:
"""Return string representation of this rule.""" |
_style = self.style.cssText
if _style:
return '{0} {{{1}}}'.format(self.selectorText, _style)
return '' |
<SYSTEM_TASK:>
Set proper log-level.
<END_TASK>
<USER_TASK:>
Description:
def set_loglevel(level: Union[int, str, None] = None) -> None:
"""Set proper log-level.
:arg Optional[int, str] level: Level to be set. If None, use proper log
level from command line option. Default value is ``logging.INFO``.
""" |
if level is not None:
lv = level_to_int(level)
elif config.logging:
lv = level_to_int(config.logging)
elif config.debug:
lv = logging.DEBUG
else:
lv = logging.INFO
root_logger.setLevel(lv)
_log_handler.setLevel(lv) |
<SYSTEM_TASK:>
Parse command line options and set them to ``config``.
<END_TASK>
<USER_TASK:>
Description:
def parse_command_line() -> Namespace:
"""Parse command line options and set them to ``config``.
This function skips unknown command line options. After parsing options,
set log level and set options in ``tornado.options``.
""" |
import tornado.options
parser.parse_known_args(namespace=config)
set_loglevel() # set new log level based on commanline option
for k, v in vars(config).items():
if k.startswith('log'):
tornado.options.options.__setattr__(k, v)
return config |
<SYSTEM_TASK:>
Suppress log output to stdout.
<END_TASK>
<USER_TASK:>
Description:
def suppress_logging() -> None:
"""Suppress log output to stdout.
This function is intended to be used in test's setup. This function removes
log handler of ``wdom`` logger and set NullHandler to suppress log.
""" |
from wdom import options
options.root_logger.removeHandler(options._log_handler)
options.root_logger.addHandler(logging.NullHandler()) |
<SYSTEM_TASK:>
Reset all wdom objects.
<END_TASK>
<USER_TASK:>
Description:
def reset() -> None:
"""Reset all wdom objects.
This function clear all connections, elements, and resistered custom
elements. This function also makes new document/application and set them.
""" |
from wdom.document import get_new_document, set_document
from wdom.element import Element
from wdom.server import _tornado
from wdom.window import customElements
set_document(get_new_document())
_tornado.connections.clear()
_tornado.set_application(_tornado.Application())
Element._elements_with_id.clear()
Element._element_buffer.clear()
customElements.reset() |
<SYSTEM_TASK:>
Ensure to be node.
<END_TASK>
<USER_TASK:>
Description:
def _ensure_node(node: Union[str, AbstractNode]) -> AbstractNode:
"""Ensure to be node.
If ``node`` is string, convert it to ``Text`` node.
""" |
if isinstance(node, str):
return Text(node)
elif isinstance(node, Node):
return node
else:
raise TypeError('Invalid type to append: {}'.format(node)) |
<SYSTEM_TASK:>
Return the previous sibling of this node.
<END_TASK>
<USER_TASK:>
Description:
def previousSibling(self) -> Optional[AbstractNode]:
"""Return the previous sibling of this node.
If there is no previous sibling, return ``None``.
""" |
parent = self.parentNode
if parent is None:
return None
return parent.childNodes.item(parent.childNodes.index(self) - 1) |
<SYSTEM_TASK:>
Return the owner document of this node.
<END_TASK>
<USER_TASK:>
Description:
def ownerDocument(self) -> Optional[AbstractNode]:
"""Return the owner document of this node.
Owner document is an ancestor document node of this node. If this node
(or node tree including this node) is not appended to any document
node, this property returns ``None``.
:rtype: Document or None
""" |
if self.nodeType == Node.DOCUMENT_NODE:
return self
elif self.parentNode:
return self.parentNode.ownerDocument
return None |
<SYSTEM_TASK:>
Return index of the node.
<END_TASK>
<USER_TASK:>
Description:
def index(self, node: AbstractNode) -> int:
"""Return index of the node.
If the node is not a child of this node, raise ``ValueError``.
""" |
if node in self.childNodes:
return self.childNodes.index(node)
elif isinstance(node, Text):
for i, n in enumerate(self.childNodes):
# should consider multiple match?
if isinstance(n, Text) and n.data == node:
return i
raise ValueError('node is not in this node') |
<SYSTEM_TASK:>
Insert a node just before the reference node.
<END_TASK>
<USER_TASK:>
Description:
def insertBefore(self, node: AbstractNode,
ref_node: AbstractNode) -> AbstractNode:
"""Insert a node just before the reference node.""" |
return self._insert_before(node, ref_node) |
<SYSTEM_TASK:>
Replace an old child with new child.
<END_TASK>
<USER_TASK:>
Description:
def replaceChild(self, new_child: AbstractNode,
old_child: AbstractNode) -> AbstractNode:
"""Replace an old child with new child.""" |
return self._replace_child(new_child, old_child) |
<SYSTEM_TASK:>
Return new copy of this node.
<END_TASK>
<USER_TASK:>
Description:
def cloneNode(self, deep: bool=False) -> AbstractNode:
"""Return new copy of this node.
If optional argument ``deep`` is specified and is True, new node has
clones of child nodes of this node (if presents).
""" |
if deep:
return self._clone_node_deep()
return self._clone_node() |
<SYSTEM_TASK:>
Return item with the index.
<END_TASK>
<USER_TASK:>
Description:
def item(self, index: int) -> Optional[Node]:
"""Return item with the index.
If the index is negative number or out of the list, return None.
""" |
if not isinstance(index, int):
raise TypeError(
'Indeces must be integer, not {}'.format(type(index)))
return self.__nodes[index] if 0 <= index < self.length else None |
<SYSTEM_TASK:>
Return list of child nodes.
<END_TASK>
<USER_TASK:>
Description:
def children(self) -> NodeList:
"""Return list of child nodes.
Currently this is not a live object.
""" |
return NodeList([e for e in self.childNodes
if e.nodeType == Node.ELEMENT_NODE]) |
<SYSTEM_TASK:>
Insert new nodes before first child node.
<END_TASK>
<USER_TASK:>
Description:
def prepend(self, *nodes: Union[str, AbstractNode]) -> None:
"""Insert new nodes before first child node.""" |
node = _to_node_list(nodes)
if self.firstChild:
self.insertBefore(node, self.firstChild)
else:
self.appendChild(node) |
<SYSTEM_TASK:>
Append new nodes after last child node.
<END_TASK>
<USER_TASK:>
Description:
def append(self, *nodes: Union[AbstractNode, str]) -> None:
"""Append new nodes after last child node.""" |
node = _to_node_list(nodes)
self.appendChild(node) |
<SYSTEM_TASK:>
Insert nodes before this node.
<END_TASK>
<USER_TASK:>
Description:
def before(self, *nodes: Union[AbstractNode, str]) -> None:
"""Insert nodes before this node.
If nodes contains ``str``, it will be converted to Text node.
""" |
if self.parentNode:
node = _to_node_list(nodes)
self.parentNode.insertBefore(node, self) |
<SYSTEM_TASK:>
Append nodes after this node.
<END_TASK>
<USER_TASK:>
Description:
def after(self, *nodes: Union[AbstractNode, str]) -> None:
"""Append nodes after this node.
If nodes contains ``str``, it will be converted to Text node.
""" |
if self.parentNode:
node = _to_node_list(nodes)
_next_node = self.nextSibling
if _next_node is None:
self.parentNode.appendChild(node)
else:
self.parentNode.insertBefore(node, _next_node) |
<SYSTEM_TASK:>
Replace this node with nodes.
<END_TASK>
<USER_TASK:>
Description:
def replaceWith(self, *nodes: Union[AbstractNode, str]) -> None:
"""Replace this node with nodes.
If nodes contains ``str``, it will be converted to Text node.
""" |
if self.parentNode:
node = _to_node_list(nodes)
self.parentNode.replaceChild(node, self) |
<SYSTEM_TASK:>
Insert ``string`` at offset on this node.
<END_TASK>
<USER_TASK:>
Description:
def insertData(self, offset: int, string: str) -> None:
"""Insert ``string`` at offset on this node.""" |
self._insert_data(offset, string) |
<SYSTEM_TASK:>
Delete data by offset to count letters.
<END_TASK>
<USER_TASK:>
Description:
def deleteData(self, offset: int, count: int) -> None:
"""Delete data by offset to count letters.""" |
self._delete_data(offset, count) |
<SYSTEM_TASK:>
Replace data from offset to count by string.
<END_TASK>
<USER_TASK:>
Description:
def replaceData(self, offset: int, count: int, string: str) -> None:
"""Replace data from offset to count by string.""" |
self._replace_data(offset, count, string) |
<SYSTEM_TASK:>
Create Event from JSOM msg and set target nodes.
<END_TASK>
<USER_TASK:>
Description:
def create_event(msg: EventMsgDict) -> Event:
"""Create Event from JSOM msg and set target nodes.
:arg EventTarget currentTarget: Current event target node.
:arg EventTarget target: Node which emitted this event first.
:arg dict init: Event options.
""" |
proto = msg.get('proto', '')
cls = proto_dict.get(proto, Event)
e = cls(msg['type'], msg)
return e |
<SYSTEM_TASK:>
Get data of type format.
<END_TASK>
<USER_TASK:>
Description:
def getData(self, type: str) -> str:
"""Get data of type format.
If this DataTransfer object does not have `type` data, return empty
string.
:arg str type: Data format of the data, like 'text/plain'.
""" |
return self.__data.get(normalize_type(type), '') |
<SYSTEM_TASK:>
Remove data of type foramt.
<END_TASK>
<USER_TASK:>
Description:
def clearData(self, type: str = '') -> None:
"""Remove data of type foramt.
If type argument is omitted, remove all data.
""" |
type = normalize_type(type)
if not type:
self.__data.clear()
elif type in self.__data:
del self.__data[type] |
<SYSTEM_TASK:>
Add event listener to this node.
<END_TASK>
<USER_TASK:>
Description:
def addEventListener(self, event: str, listener: _EventListenerType
) -> None:
"""Add event listener to this node.
``event`` is a string which determines the event type when the new
listener called. Acceptable events are same as JavaScript, without
``on``. For example, to add a listener which is called when this node
is clicked, event is ``'click``.
""" |
self._add_event_listener(event, listener) |
<SYSTEM_TASK:>
Remove an event listener of this node.
<END_TASK>
<USER_TASK:>
Description:
def removeEventListener(self, event: str, listener: _EventListenerType
) -> None:
"""Remove an event listener of this node.
The listener is removed only when both event type and listener is
matched.
""" |
self._remove_event_listener(event, listener) |
<SYSTEM_TASK:>
Run when get response from browser.
<END_TASK>
<USER_TASK:>
Description:
def on_response(self, msg: Dict[str, str]) -> None:
"""Run when get response from browser.""" |
response = msg.get('data', False)
if response:
task = self.__tasks.pop(msg.get('reqid'), False)
if task and not task.cancelled() and not task.done():
task.set_result(msg.get('data')) |
<SYSTEM_TASK:>
Execute ``method`` in the related node on browser.
<END_TASK>
<USER_TASK:>
Description:
def js_exec(self, method: str, *args: Union[int, str, bool]) -> None:
"""Execute ``method`` in the related node on browser.
Other keyword arguments are passed to ``params`` attribute.
If this node is not in any document tree (namely, this node does not
have parent node), the ``method`` is not executed.
""" |
if self.connected:
self.ws_send(dict(method=method, params=args)) |
<SYSTEM_TASK:>
Send query to related DOM on browser.
<END_TASK>
<USER_TASK:>
Description:
def js_query(self, query: str) -> Awaitable:
"""Send query to related DOM on browser.
:param str query: single string which indicates query type.
""" |
if self.connected:
self.js_exec(query, self.__reqid)
fut = Future() # type: Future[str]
self.__tasks[self.__reqid] = fut
self.__reqid += 1
return fut
f = Future() # type: Future[None]
f.set_result(None)
return f |
<SYSTEM_TASK:>
Send ``obj`` as message to the related nodes on browser.
<END_TASK>
<USER_TASK:>
Description:
def ws_send(self, obj: Dict[str, Union[Iterable[_T_MsgItem], _T_MsgItem]]
) -> None:
"""Send ``obj`` as message to the related nodes on browser.
:arg dict obj: Message is serialized by JSON object and send via
WebSocket connection.
""" |
from wdom import server
if self.ownerDocument is not None:
obj['target'] = 'node'
obj['id'] = self.wdom_id
server.push_message(obj) |
<SYSTEM_TASK:>
Generate a time series with a given mu and sigma. This serves as the
<END_TASK>
<USER_TASK:>
Description:
def generate_null_timeseries(self, ts, mu, sigma):
""" Generate a time series with a given mu and sigma. This serves as the
NULL distribution. """ |
l = len(ts)
return np.random.normal(mu, sigma, l) |
<SYSTEM_TASK:>
Compute the balance. The right end - the left end.
<END_TASK>
<USER_TASK:>
Description:
def compute_balance_mean(self, ts, t):
""" Compute the balance. The right end - the left end.""" |
""" For changed words we expect an increase in the mean, and so only 1 """
return np.mean(ts[t + 1:]) - np.mean(ts[:t + 1]) |
<SYSTEM_TASK:>
Compute the balance at either end.
<END_TASK>
<USER_TASK:>
Description:
def compute_balance_median(self, ts, t):
""" Compute the balance at either end.""" |
return np.median(ts[t + 1:]) - np.median(ts[:t + 1]) |
<SYSTEM_TASK:>
Compute the Cumulative Sum at each point 't' of the time series.
<END_TASK>
<USER_TASK:>
Description:
def compute_cusum_ts(self, ts):
""" Compute the Cumulative Sum at each point 't' of the time series. """ |
mean = np.mean(ts)
cusums = np.zeros(len(ts))
cusum[0] = (ts[0] - mean)
for i in np.arange(1, len(ts)):
cusums[i] = cusums[i - 1] + (ts[i] - mean)
assert(np.isclose(cumsum[-1], 0.0))
return cusums |
<SYSTEM_TASK:>
Detect mean shift in a time series. B is number of bootstrapped
<END_TASK>
<USER_TASK:>
Description:
def detect_mean_shift(self, ts, B=1000):
""" Detect mean shift in a time series. B is number of bootstrapped
samples to draw.
""" |
x = np.arange(0, len(ts))
stat_ts_func = self.compute_balance_mean_ts
null_ts_func = self.shuffle_timeseries
stats_ts, pvals, nums = self.get_ts_stats_significance(x, ts, stat_ts_func, null_ts_func, B=B, permute_fast=True)
return stats_ts, pvals, nums |
<SYSTEM_TASK:>
Parallelize a function over each element of an iterable.
<END_TASK>
<USER_TASK:>
Description:
def parallelize_func(iterable, func, chunksz=1, n_jobs=16, *args, **kwargs):
""" Parallelize a function over each element of an iterable. """ |
chunker = func
chunks = more_itertools.chunked(iterable, chunksz)
chunks_results = Parallel(n_jobs=n_jobs, verbose=50)(
delayed(chunker)(chunk, *args, **kwargs) for chunk in chunks)
results = more_itertools.flatten(chunks_results)
return list(results) |
<SYSTEM_TASK:>
Compute the statistical significance of a test statistic at each point
<END_TASK>
<USER_TASK:>
Description:
def ts_stats_significance(ts, ts_stat_func, null_ts_func, B=1000, permute_fast=False):
""" Compute the statistical significance of a test statistic at each point
of the time series.
""" |
stats_ts = ts_stat_func(ts)
if permute_fast:
# Permute it in 1 shot
null_ts = map(np.random.permutation, np.array([ts, ] * B))
else:
null_ts = np.vstack([null_ts_func(ts) for i in np.arange(0, B)])
stats_null_ts = np.vstack([ts_stat_func(nts) for nts in null_ts])
pvals = []
nums = []
for i in np.arange(0, len(stats_ts)):
num_samples = np.sum((stats_null_ts[:, i] >= stats_ts[i]))
nums.append(num_samples)
pval = num_samples / float(B)
pvals.append(pval)
return stats_ts, pvals, nums |
<SYSTEM_TASK:>
Get the p-value from the confidence interval.
<END_TASK>
<USER_TASK:>
Description:
def get_pvalue(value, ci):
""" Get the p-value from the confidence interval.""" |
from scipy.stats import norm
se = (ci[1] - ci[0]) / (2.0 * 1.96)
z = value / se
pvalue = -2 * norm.cdf(-np.abs(z))
return pvalue |
<SYSTEM_TASK:>
Compute the statistical significance of a test statistic at each point
<END_TASK>
<USER_TASK:>
Description:
def ts_stats_significance_bootstrap(ts, stats_ts, stats_func, B=1000, b=3):
""" Compute the statistical significance of a test statistic at each point
of the time series by using timeseries boootstrap.
""" |
pvals = []
for tp in np.arange(0, len(stats_ts)):
pf = partial(stats_func, t=tp)
bs = bootstrap_ts(ts, pf, B=B, b=b)
ci = get_ci(bs, blockratio=b / len(stats_ts))
pval = abs(get_pvalue(stats_ts[tp], ci))
pvals.append(pval)
return pvals |
<SYSTEM_TASK:>
Return an iterable of formatted Unicode traceback frames.
<END_TASK>
<USER_TASK:>
Description:
def format_traceback(extracted_tb,
exc_type,
exc_value,
cwd='',
term=None,
function_color=12,
dim_color=8,
editor='vi',
template=DEFAULT_EDITOR_SHORTCUT_TEMPLATE):
"""Return an iterable of formatted Unicode traceback frames.
Also include a pseudo-frame at the end representing the exception itself.
Format things more compactly than the stock formatter, and make every
frame an editor shortcut.
""" |
def format_shortcut(editor,
path,
line_number,
function=None):
"""Return a pretty-printed editor shortcut."""
return template.format(editor=editor,
line_number=line_number or 0,
path=path,
function=function or u'',
hash_if_function=u' # ' if function else u'',
function_format=term.color(function_color),
# Underline is also nice and doesn't make us
# worry about appearance on different background
# colors.
normal=term.normal,
dim_format=term.color(dim_color) + term.bold,
line_number_max_width=line_number_max_width,
term=term)
template += '\n' # Newlines are awkward to express on the command line.
extracted_tb = _unicode_decode_extracted_tb(extracted_tb)
if not term:
term = Terminal()
if extracted_tb:
# Shorten file paths:
for i, (file, line_number, function, text) in enumerate(extracted_tb):
extracted_tb[i] = human_path(src(file), cwd), line_number, function, text
line_number_max_width = len(unicode(max(the_line for _, the_line, _, _ in extracted_tb)))
# Stack frames:
for i, (path, line_number, function, text) in enumerate(extracted_tb):
text = (text and text.strip()) or u''
yield (format_shortcut(editor, path, line_number, function) +
(u' %s\n' % text))
# Exception:
if exc_type is SyntaxError:
# Format a SyntaxError to look like our other traceback lines.
# SyntaxErrors have a format different from other errors and include a
# file path which looks out of place in our newly highlit, editor-
# shortcutted world.
if hasattr(exc_value, 'filename') and hasattr(exc_value, 'lineno'):
exc_lines = [format_shortcut(editor, exc_value.filename, exc_value.lineno)]
formatted_exception = format_exception_only(SyntaxError, exc_value)[1:]
else:
# The logcapture plugin may format exceptions as strings,
# stripping them of the full filename and lineno
exc_lines = []
formatted_exception = format_exception_only(SyntaxError, exc_value)
formatted_exception.append(u'(Try --nologcapture for a more detailed traceback)\n')
else:
exc_lines = []
formatted_exception = format_exception_only(exc_type, exc_value)
exc_lines.extend([_decode(f) for f in formatted_exception])
yield u''.join(exc_lines) |
<SYSTEM_TASK:>
Return extracted traceback frame 4-tuples that aren't unittest ones.
<END_TASK>
<USER_TASK:>
Description:
def extract_relevant_tb(tb, exctype, is_test_failure):
"""Return extracted traceback frame 4-tuples that aren't unittest ones.
This used to be _exc_info_to_string().
""" |
# Skip test runner traceback levels:
while tb and _is_unittest_frame(tb):
tb = tb.tb_next
if is_test_failure:
# Skip assert*() traceback levels:
length = _count_relevant_tb_levels(tb)
return extract_tb(tb, length)
return extract_tb(tb) |
<SYSTEM_TASK:>
Return a traceback with the string elements translated into Unicode.
<END_TASK>
<USER_TASK:>
Description:
def _unicode_decode_extracted_tb(extracted_tb):
"""Return a traceback with the string elements translated into Unicode.""" |
return [(_decode(file), line_number, _decode(function), _decode(text))
for file, line_number, function, text in extracted_tb] |
<SYSTEM_TASK:>
Return the number of frames in ``tb`` before all that's left is unittest frames.
<END_TASK>
<USER_TASK:>
Description:
def _count_relevant_tb_levels(tb):
"""Return the number of frames in ``tb`` before all that's left is unittest frames.
Unlike its namesake in unittest, this doesn't bail out as soon as it hits a
unittest frame, which means we don't bail out as soon as somebody uses the
mock library, which defines ``__unittest``.
""" |
length = contiguous_unittest_frames = 0
while tb:
length += 1
if _is_unittest_frame(tb):
contiguous_unittest_frames += 1
else:
contiguous_unittest_frames = 0
tb = tb.tb_next
return length - contiguous_unittest_frames |
<SYSTEM_TASK:>
Call pdb's cmdloop, making readline work.
<END_TASK>
<USER_TASK:>
Description:
def cmdloop(self, *args, **kwargs):
"""Call pdb's cmdloop, making readline work.
Patch raw_input so it sees the original stdin and stdout, lest
readline refuse to work.
The C implementation of raw_input uses readline functionality only if
both stdin and stdout are from a terminal AND are FILE*s (not
PyObject*s): http://bugs.python.org/issue5727 and
https://bugzilla.redhat.com/show_bug.cgi?id=448864
""" |
def unwrapping_raw_input(*args, **kwargs):
"""Call raw_input(), making sure it finds an unwrapped stdout."""
wrapped_stdout = sys.stdout
sys.stdout = wrapped_stdout.stream
ret = orig_raw_input(*args, **kwargs)
sys.stdout = wrapped_stdout
return ret
try:
orig_raw_input = raw_input
except NameError:
orig_raw_input = input
if hasattr(sys.stdout, 'stream'):
__builtin__.raw_input = unwrapping_raw_input
# else if capture plugin has replaced it with a StringIO, don't bother.
try:
# Interesting things happen when you try to not reference the
# superclass explicitly.
ret = cmd.Cmd.cmdloop(self, *args, **kwargs)
finally:
__builtin__.raw_input = orig_raw_input
return ret |
<SYSTEM_TASK:>
Call pdb.set_trace, making sure it receives the unwrapped stdout.
<END_TASK>
<USER_TASK:>
Description:
def set_trace(*args, **kwargs):
"""Call pdb.set_trace, making sure it receives the unwrapped stdout.
This is so we don't keep drawing progress bars over debugger output.
""" |
# There's no stream attr if capture plugin is enabled:
out = sys.stdout.stream if hasattr(sys.stdout, 'stream') else None
# Python 2.5 can't put an explicit kwarg and **kwargs in the same function
# call.
kwargs['stdout'] = out
debugger = pdb.Pdb(*args, **kwargs)
# Ordinarily (and in a silly fashion), pdb refuses to use raw_input() if
# you pass it a stream on instantiation. Fix that:
debugger.use_rawinput = True
debugger.set_trace(sys._getframe().f_back) |
<SYSTEM_TASK:>
Make some monkeypatches to dodge progress bar.
<END_TASK>
<USER_TASK:>
Description:
def begin(self):
"""Make some monkeypatches to dodge progress bar.
Wrap stderr and stdout to keep other users of them from smearing the
progress bar. Wrap some pdb routines to stop showing the bar while in
the debugger.
""" |
# The calls to begin/finalize end up like this: a call to begin() on
# instance A of the plugin, then a paired begin/finalize for each test
# on instance B, then a final call to finalize() on instance A.
# TODO: Do only if isatty.
self._stderr.append(sys.stderr)
sys.stderr = StreamWrapper(sys.stderr, self) # TODO: Any point?
self._stdout.append(sys.stdout)
sys.stdout = StreamWrapper(sys.stdout, self)
self._set_trace.append(pdb.set_trace)
pdb.set_trace = set_trace
self._cmdloop.append(pdb.Pdb.cmdloop)
pdb.Pdb.cmdloop = cmdloop
# nosetests changes directories to the tests dir when run from a
# distribution dir, so save the original cwd for relativizing paths.
self._cwd = '' if self.conf.options.absolute_paths else getcwd() |
<SYSTEM_TASK:>
Put monkeypatches back as we found them.
<END_TASK>
<USER_TASK:>
Description:
def finalize(self, result):
"""Put monkeypatches back as we found them.""" |
sys.stderr = self._stderr.pop()
sys.stdout = self._stdout.pop()
pdb.set_trace = self._set_trace.pop()
pdb.Pdb.cmdloop = self._cmdloop.pop() |
<SYSTEM_TASK:>
Turn style-forcing on if bar-forcing is on.
<END_TASK>
<USER_TASK:>
Description:
def configure(self, options, conf):
"""Turn style-forcing on if bar-forcing is on.
It'd be messy to position the bar but still have the rest of the
terminal capabilities emit ''.
""" |
super(ProgressivePlugin, self).configure(options, conf)
if (getattr(options, 'verbosity', 0) > 1 and
getattr(options, 'enable_plugin_id', False)):
# TODO: Can we forcibly disable the ID plugin?
print ('Using --with-id and --verbosity=2 or higher with '
'nose-progressive causes visualization errors. Remove one '
'or the other to avoid a mess.')
if options.with_bar:
options.with_styling = True |
<SYSTEM_TASK:>
Draw an updated progress bar.
<END_TASK>
<USER_TASK:>
Description:
def update(self, test_path, number):
"""Draw an updated progress bar.
At the moment, the graph takes a fixed width, and the test identifier
takes the rest of the row, truncated from the left to fit.
test_path -- the selector of the test being run
number -- how many tests have been run so far, including this one
""" |
# TODO: Play nicely with absurdly narrow terminals. (OS X's won't even
# go small enough to hurt us.)
# Figure out graph:
GRAPH_WIDTH = 14
# min() is in case we somehow get the total test count wrong. It's tricky.
num_filled = int(round(min(1.0, float(number) / self.max) * GRAPH_WIDTH))
graph = ''.join([self._fill_cap(' ' * num_filled),
self._empty_cap(self._empty_char * (GRAPH_WIDTH - num_filled))])
# Figure out the test identifier portion:
cols_for_path = self.cols - GRAPH_WIDTH - 2 # 2 spaces between path & graph
if len(test_path) > cols_for_path:
test_path = test_path[len(test_path) - cols_for_path:]
else:
test_path += ' ' * (cols_for_path - len(test_path))
# Put them together, and let simmer:
self.last = self._term.bold(test_path) + ' ' + graph
with self._at_last_line():
self.stream.write(self.last)
self.stream.flush() |
<SYSTEM_TASK:>
Return a context manager which erases the bar, lets you output things, and then redraws the bar.
<END_TASK>
<USER_TASK:>
Description:
def dodging(bar):
"""Return a context manager which erases the bar, lets you output things, and then redraws the bar.
It's reentrant.
""" |
class ShyProgressBar(object):
"""Context manager that implements a progress bar that gets out of the way"""
def __enter__(self):
"""Erase the progress bar so bits of disembodied progress bar don't get scrolled up the terminal."""
# My terminal has no status line, so we make one manually.
bar._is_dodging += 1 # Increment before calling erase(), which
# calls dodging() again.
if bar._is_dodging <= 1: # It *was* 0.
bar.erase()
def __exit__(self, type, value, tb):
"""Redraw the last saved state of the progress bar."""
if bar._is_dodging == 1: # Can't decrement yet; write() could
# read it.
# This is really necessary only because we monkeypatch
# stderr; the next test is about to start and will redraw
# the bar.
with bar._at_last_line():
bar.stream.write(bar.last)
bar.stream.flush()
bar._is_dodging -= 1
return ShyProgressBar() |
<SYSTEM_TASK:>
Return a Result that doesn't print dots.
<END_TASK>
<USER_TASK:>
Description:
def _makeResult(self):
"""Return a Result that doesn't print dots.
Nose's ResultProxy will wrap it, and other plugins can still print
stuff---but without smashing into our progress bar, care of
ProgressivePlugin's stderr/out wrapping.
""" |
return ProgressiveResult(self._cwd,
self._totalTests,
self.stream,
config=self.config) |
<SYSTEM_TASK:>
Print a nicely formatted traceback.
<END_TASK>
<USER_TASK:>
Description:
def _printTraceback(self, test, err):
"""Print a nicely formatted traceback.
:arg err: exc_info()-style traceback triple
:arg test: the test that precipitated this call
""" |
# Don't bind third item to a local var; that can create
# circular refs which are expensive to collect. See the
# sys.exc_info() docs.
exception_type, exception_value = err[:2]
# TODO: In Python 3, the traceback is attached to the exception
# instance through the __traceback__ attribute. If the instance
# is saved in a local variable that persists outside the except
# block, the traceback will create a reference cycle with the
# current frame and its dictionary of local variables. This will
# delay reclaiming dead resources until the next cyclic garbage
# collection pass.
extracted_tb = extract_relevant_tb(
err[2],
exception_type,
exception_type is test.failureException)
test_frame_index = index_of_test_frame(
extracted_tb,
exception_type,
exception_value,
test)
if test_frame_index:
# We have a good guess at which frame is the test, so
# trim everything until that. We don't care to see test
# framework frames.
extracted_tb = extracted_tb[test_frame_index:]
with self.bar.dodging():
self.stream.write(''.join(
format_traceback(
extracted_tb,
exception_type,
exception_value,
self._cwd,
self._term,
self._options.function_color,
self._options.dim_color,
self._options.editor,
self._options.editor_shortcut_template))) |
<SYSTEM_TASK:>
Output a 1-line error summary to the stream if appropriate.
<END_TASK>
<USER_TASK:>
Description:
def _printHeadline(self, kind, test, is_failure=True):
"""Output a 1-line error summary to the stream if appropriate.
The line contains the kind of error and the pathname of the test.
:arg kind: The (string) type of incident the precipitated this call
:arg test: The test that precipitated this call
""" |
if is_failure or self._options.show_advisories:
with self.bar.dodging():
self.stream.writeln(
'\n' +
(self._term.bold if is_failure else '') +
'%s: %s' % (kind, nose_selector(test)) +
(self._term.normal if is_failure else '')) |
<SYSTEM_TASK:>
Record that an error-like thing occurred, and print a summary.
<END_TASK>
<USER_TASK:>
Description:
def _recordAndPrintHeadline(self, test, error_class, artifact):
"""Record that an error-like thing occurred, and print a summary.
Store ``artifact`` with the record.
Return whether the test result is any sort of failure.
""" |
# We duplicate the errorclass handling from super rather than calling
# it and monkeying around with showAll flags to keep it from printing
# anything.
is_error_class = False
for cls, (storage, label, is_failure) in self.errorClasses.items():
if isclass(error_class) and issubclass(error_class, cls):
if is_failure:
test.passed = False
storage.append((test, artifact))
is_error_class = True
if not is_error_class:
self.errors.append((test, artifact))
test.passed = False
is_any_failure = not is_error_class or is_failure
self._printHeadline(label if is_error_class else 'ERROR',
test,
is_failure=is_any_failure)
return is_any_failure |
<SYSTEM_TASK:>
Catch skipped tests in Python 2.7 and above.
<END_TASK>
<USER_TASK:>
Description:
def addSkip(self, test, reason):
"""Catch skipped tests in Python 2.7 and above.
Though ``addSkip()`` is deprecated in the nose plugin API, it is very
much not deprecated as a Python 2.7 ``TestResult`` method. In Python
2.7, this will get called instead of ``addError()`` for skips.
:arg reason: Text describing why the test was skipped
""" |
self._recordAndPrintHeadline(test, SkipTest, reason)
# Python 2.7 users get a little bonus: the reason the test was skipped.
if isinstance(reason, Exception):
reason = getattr(reason, 'message', None) or getattr(
reason, 'args')[0]
if reason and self._options.show_advisories:
with self.bar.dodging():
self.stream.writeln(reason) |
<SYSTEM_TASK:>
As a final summary, print number of tests, broken down by result.
<END_TASK>
<USER_TASK:>
Description:
def printSummary(self, start, stop):
"""As a final summary, print number of tests, broken down by result.""" |
def renderResultType(type, number, is_failure):
"""Return a rendering like '2 failures'.
:arg type: A singular label, like "failure"
:arg number: The number of tests with a result of that type
:arg is_failure: Whether that type counts as a failure
"""
# I'd rather hope for the best with plurals than totally punt on
# being Englishlike:
ret = '%s %s%s' % (number, type, 's' if number != 1 else '')
if is_failure and number:
ret = self._term.bold(ret)
return ret
# Summarize the special cases:
counts = [('test', self.testsRun, False),
('failure', len(self.failures), True),
('error', len(self.errors), True)]
# Support custom errorclasses as well as normal failures and errors.
# Lowercase any all-caps labels, but leave the rest alone in case there
# are hard-to-read camelCaseWordBreaks.
counts.extend([(label.lower() if label.isupper() else label,
len(storage),
is_failure)
for (storage, label, is_failure) in
self.errorClasses.values() if len(storage)])
summary = (', '.join(renderResultType(*a) for a in counts) +
' in %.1fs' % (stop - start))
# Erase progress bar. Bash doesn't clear the whole line when printing
# the prompt, leaving a piece of the bar. Also, the prompt may not be
# at the bottom of the terminal.
self.bar.erase()
self.stream.writeln()
if self.wasSuccessful():
self.stream.write(self._term.bold_green('OK! '))
self.stream.writeln(summary) |
<SYSTEM_TASK:>
Return the string you can pass to nose to run `test`, including argument
<END_TASK>
<USER_TASK:>
Description:
def nose_selector(test):
"""Return the string you can pass to nose to run `test`, including argument
values if the test was made by a test generator.
Return "Unknown test" if it can't construct a decent path.
""" |
address = test_address(test)
if address:
file, module, rest = address
if module:
if rest:
try:
return '%s:%s%s' % (module, rest, test.test.arg or '')
except AttributeError:
return '%s:%s' % (module, rest)
else:
return module
return 'Unknown test' |
<SYSTEM_TASK:>
Return the most human-readable representation of the given path.
<END_TASK>
<USER_TASK:>
Description:
def human_path(path, cwd):
"""Return the most human-readable representation of the given path.
If an absolute path is given that's within the current directory, convert
it to a relative path to shorten it. Otherwise, return the absolute path.
""" |
# TODO: Canonicalize the path to remove /kitsune/../kitsune nonsense.
path = abspath(path)
if cwd and path.startswith(cwd):
path = path[len(cwd) + 1:] # Make path relative. Remove leading slash.
return path |
<SYSTEM_TASK:>
Know something with the given confidence, and return self for chaining.
<END_TASK>
<USER_TASK:>
Description:
def know(self, what, confidence):
"""Know something with the given confidence, and return self for chaining.
If confidence is higher than that of what we already know, replace
what we already know with what you're telling us.
""" |
if confidence > self.confidence:
self.best = what
self.confidence = confidence
return self |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.