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 createElement(self, tag: str) -> Node: """Create new element whose tag name is ``tag``."""
return create_element(tag, base=self._default_class)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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...
elm = getElementByWdomId(id) if elm and elm.ownerDocument is self: return elm 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 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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 Modu...
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,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build(self) -> str: """Return HTML representation of this document."""
self._set_autoreload() return ''.join(child.html for child in self.childNodes)
<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() -> 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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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...
app = get_app() app.add_static_path(prefix, path) if not no_watch: watch_dir(path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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. Th...
start_server(**kwargs) try: asyncio.get_event_loop().run_forever() except KeyboardInterrupt: stop_server()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def define(self, *args: Any, **kwargs: Any) -> None: """Add new custom element."""
if isinstance(args[0], str): self._define_orig(*args, **kwargs) elif isinstance(args[0], type): self._define_class(*args, **kwargs) else: raise TypeError( 'Invalid argument for define: {}, {}'.format(args, 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 event_handler(msg: EventMsgDict) -> Event: """Handle events emitted on browser."""
e = create_event_from_msg(msg) if e.currentTarget is None: if e.type not in ['mount', 'unmount']: id = msg['currentTarget']['id'] logger.warning('No such element: wdom_id={}'.format(id)) return e e.currentTarget.on_event_pre(e) e.currentTarget.dispatchEvent(e) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 ==...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_html(html: str, parser: FragmentParser = None) -> Node: """Parse HTML fragment and return DocumentFragment object. DocumentFragment object has parsed No...
parser = parser or FragmentParser() parser.feed(html) return parser.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 getElementsBy(start_node: ParentNode, cond: Callable[['Element'], bool]) -> NodeList: """Return list of child elements of start_node which matches ``cond``. `...
elements = [] for child in start_node.children: if cond(child): elements.append(child) elements.extend(child.getElementsBy(cond)) return NodeList(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 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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, *tokens: str) -> None: """Add new tokens to list."""
from wdom.web_node import WdomElement _new_tokens = [] for token in tokens: self._validate_token(token) if token and token not in self: self._list.append(token) _new_tokens.append(token) if isinstance(self._owner, WdomElement) and ...
<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(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 _remov...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def html(self) -> str: """Return html representation."""
if isinstance(self.value, bool): val = 'true' if self.value else 'false' else: val = str(self.value) return 'draggable="{}"'.format(val)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setNamedItem(self, item: Attr) -> None: """Set ``Attr`` object in this collection."""
from wdom.web_node import WdomElement if not isinstance(item, Attr): raise TypeError('item must be an instance of Attr') if isinstance(self._owner, WdomElement): self._owner.js_exec('setAttribute', item.name, # type: ignore item.value) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def item(self, index: int) -> Optional[Attr]: """Return ``index``-th attr node."""
if 0 <= index < len(self): return self._dict[tuple(self._dict.keys())[index]] 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 toString(self) -> str: """Return string representation of collections."""
return ' '.join(attr.html for attr in self._dict.values())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_tag(self) -> str: """Return HTML start tag."""
tag = '<' + self.tag attrs = self._get_attrs_by_string() if attrs: tag = ' '.join((tag, attrs)) return tag + '>'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 ...
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) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 = CSSStyleDecl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draggable(self) -> Union[bool, str]: """Get ``draggable`` property."""
if not self.hasAttribute('draggable'): return False return self.getAttribute('draggable')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def form(self) -> Optional['HTMLFormElement']: """Get ``HTMLFormElement`` object related to this node."""
if self.__form: return self.__form parent = self.parentNode while parent: if isinstance(parent, HTMLFormElement): return parent else: parent = parent.parentNode 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 control(self) -> Optional[HTMLElement]: """Return related HTMLElement object."""
id = self.getAttribute('for') if id: if self.ownerDocument: return self.ownerDocument.getElementById(id) elif isinstance(id, str): from wdom.document import getElementById return getElementById(id) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def selectedOptions(self) -> NodeList: """Return all selected option nodes."""
return NodeList(list(opt for opt in self.options if opt.selected))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 ``t...
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))) kwar...
<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_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:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def textContent(self, text: str) -> None: # type: ignore """Set text content to inner node."""
if self._inner_element: self._inner_element.textContent = text else: # Need a trick to call property of super-class super().textContent = 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 html(self) -> str: """Get whole html representation of this node."""
if self._inner_element: return self.start_tag + self._inner_element.html + self.end_tag return super().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 innerHTML(self) -> str: """Get innerHTML of the inner node."""
if self._inner_element: return self._inner_element.innerHTML return super().innerHTML
<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(self) -> None: """Return whole html representation of the root document."""
from wdom.document import get_document logger.info('connected') self.write(get_document().build())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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....
<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_request(self, handler: web.RequestHandler) -> None: """Handle access log."""
if 'log_function' in self.settings: self.settings['log_function'](handler) return status = handler.get_status() if status < 400: log_method = logger.info elif status < 500: log_method = logger.warning else: log_method =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_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``...
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(pat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_favicon_path(self, path: str) -> None: """Add path to serve favicon file. ``path`` should be a directory, which contains favicon file (``favicon.ico``) fo...
spec = web.URLSpec( '/(favicon.ico)', StaticFileHandler, dict(path=path) ) # Need some check handlers = self.handlers[0][1] handlers.append(spec)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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): """ ...
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, "...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def watch_dir(path: str) -> None: """Add ``path`` to watch for autoreload."""
_compile_exclude_patterns() if config.autoreload or config.debug: # Add files to watch for autoreload p = pathlib.Path(path) p.resolve() _add_watch_path(p)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open_browser(url: str, browser: str = None) -> None: """Open web browser."""
if '--open-browser' in sys.argv: # Remove open browser to prevent making new tab on autoreload sys.argv.remove('--open-browser') if browser is None: browser = config.browser if browser in _browsers: webbrowser.get(browser).open(url) else: webbrowser.open(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 parse_style_decl(style: str, owner: AbstractNode = None ) -> CSSStyleDeclaration: """Make CSSStyleDeclaration from style string. :arg AbstractNode owner: Owne...
_style = CSSStyleDeclaration(style, owner=owner) return _style
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_style_rules(styles: str) -> CSSRuleList: """Make CSSRuleList object from style string."""
rules = CSSRuleList() for m in _style_rule_re.finditer(styles): rules.append(CSSStyleRule(m.group(1), parse_style_decl(m.group(2)))) return rules
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cssText(self) -> str: """String-representation."""
text = '; '.join('{0}: {1}'.format(k, v) for k, v in self.items()) if text: text += ';' return 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 removeProperty(self, prop: str) -> str: """Remove the css property."""
removed_prop = self.get(prop) # removed_prop may be False or '', so need to check it is None if removed_prop is not None: del self[prop] return removed_prop
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 le...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 o...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 ``wdo...
from wdom import options options.root_logger.removeHandler(options._log_handler) options.root_logger.addHandler(logging.NullHandler())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 docume...
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._elem...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _dnsname_match(dn, hostname, max_wildcards=1): """Matching according to RFC 6125, section 6.4.3 http://tools.ietf.org/html/rfc6125#section-6.4.3 """
pats = [] if not dn: return False split_dn = dn.split(r'.') leftmost, remainder = split_dn[0], split_dn[1:] wildcards = leftmost.count('*') if wildcards > max_wildcards: # Issue #17980: avoid denials of service by refusing more # than one wildcard per fragment. A surv...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 no...
if self.nodeType == Node.DOCUMENT_NODE: return self elif self.parentNode: return self.parentNode.ownerDocument 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 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 r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 clone...
if deep: return self._clone_node_deep() return self._clone_node()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def firstElementChild(self) -> Optional[AbstractNode]: """First Element child node. If this node has no element child, return None. """
for child in self.childNodes: if child.nodeType == Node.ELEMENT_NODE: return child 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 lastElementChild(self) -> Optional[AbstractNode]: """Last Element child node. If this node has no element child, return None. """
for child in reversed(self.childNodes): # type: ignore if child.nodeType == Node.ELEMENT_NODE: return child 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 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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nextElementSibling(self) -> Optional[AbstractNode]: """Next Element Node. If this node has no next element node, return None. """
if self.parentNode is None: return None siblings = self.parentNode.childNodes for i in range(siblings.index(self) + 1, len(siblings)): n = siblings[i] if n.nodeType == Node.ELEMENT_NODE: return n 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 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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def html(self) -> str: """Return html-escaped string representation of this node."""
if self.parentNode and self.parentNode._should_escape_text: return html.escape(self.data) return self.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_event(msg: EventMsgDict) -> Event: """Create Event from JSOM msg and set target nodes. :arg EventTarget currentTarget: Current event target node. :arg ...
proto = msg.get('proto', '') cls = proto_dict.get(proto, Event) e = cls(msg['type'], msg) return e
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 f...
return self.__data.get(normalize_type(type), '')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setData(self, type: str, data: str) -> None: """Set data of type format. :arg str type: Data format of the data, like 'text/plain'. """
type = normalize_type(type) if type in self.__data: del self.__data[type] self.__data[type] = 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 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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 even...
self._add_event_listener(event, listener)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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...
self._remove_event_listener(event, listener)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 ...
if self.connected: self.ws_send(dict(method=method, params=args))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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: Me...
from wdom import server if self.ownerDocument is not None: obj['target'] = 'node' obj['id'] = self.wdom_id server.push_message(obj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_ts_stats_significance(self, x, ts, stat_ts_func, null_ts_func, B=1000, permute_fast=False, label_ts=''): """ Returns the statistics, pvalues and the actu...
stats_ts, pvals, nums = ts_stats_significance( ts, stat_ts_func, null_ts_func, B=B, permute_fast=permute_fast) return stats_ts, pvals, nums
<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_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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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])