code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def remove(self, *tokens: str) -> None: 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)
Remove tokens from list.
def toggle(self, token: str) -> None: self._validate_token(token) if token in self: self.remove(token) else: self.add(token)
Add or remove token to/from list. If token is in this list, the token will be removed. Otherwise add it to list.
def contains(self, token: str) -> bool: self._validate_token(token) return token in self
Return if the token is in the list or not.
def html(self) -> str: 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)
Return string representation of this. Used in start tag of HTML representation of the Element node.
def html(self) -> str: if isinstance(self.value, bool): val = 'true' if self.value else 'false' else: val = str(self.value) return 'draggable="{}"'.format(val)
Return html representation.
def getNamedItem(self, name: str) -> Optional[Attr]: return self._dict.get(name, None)
Get ``Attr`` object which has ``name``. If does not have ``name`` attr, return None.
def setNamedItem(self, item: Attr) -> None: 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) self._dict[item.name] = item item._owner = self._owner
Set ``Attr`` object in this collection.
def removeNamedItem(self, item: Attr) -> Optional[Attr]: 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('removeAttribute', item.name) removed_item = self._dict.pop(item.name, None) if removed_item: removed_item._owner = self._owner return removed_item
Set ``Attr`` object and return it (if exists).
def item(self, index: int) -> Optional[Attr]: if 0 <= index < len(self): return self._dict[tuple(self._dict.keys())[index]] return None
Return ``index``-th attr node.
def toString(self) -> str: return ' '.join(attr.html for attr in self._dict.values())
Return string representation of collections.
def start_tag(self) -> str: tag = '<' + self.tag attrs = self._get_attrs_by_string() if attrs: tag = ' '.join((tag, attrs)) return tag + '>'
Return HTML start tag.
def insertAdjacentHTML(self, position: str, html: str) -> None: 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) )
Parse ``html`` to DOM and insert to ``position``. ``position`` is a case-insensive string, and must be one of "beforeBegin", "afterBegin", "beforeEnd", or "afterEnd".
def getAttribute(self, attr: str) -> _AttrValueType: 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
Get attribute of this node as string format. If this node does not have ``attr``, return None.
def getAttributeNode(self, attr: str) -> Optional[Attr]: return self.attributes.getNamedItem(attr)
Get attribute of this node as Attr format. If this node does not have ``attr``, return None.
def hasAttribute(self, attr: str) -> bool: if attr == 'class': return bool(self.classList) return attr in self.attributes
Return True if this node has ``attr``.
def setAttribute(self, attr: str, value: _AttrValueType) -> None: self._set_attribute(attr, value)
Set ``attr`` and ``value`` in this node.
def removeAttributeNode(self, attr: Attr) -> Optional[Attr]: return self.attributes.removeNamedItem(attr)
Remove ``Attr`` node from this node.
def style(self, style: _AttrValueType) -> None: 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)))
Set style attribute of this node. If argument ``style`` is string, it will be parsed to ``CSSStyleDeclaration``.
def draggable(self) -> Union[bool, str]: if not self.hasAttribute('draggable'): return False return self.getAttribute('draggable')
Get ``draggable`` property.
def draggable(self, value: Union[bool, str]) -> None: if value is False: self.removeAttribute('draggable') else: self.setAttribute('draggable', value)
Set ``draggable`` property. ``value`` is boolean or string.
def form(self) -> Optional['HTMLFormElement']: if self.__form: return self.__form parent = self.parentNode while parent: if isinstance(parent, HTMLFormElement): return parent else: parent = parent.parentNode return None
Get ``HTMLFormElement`` object related to this node.
def on_event_pre(self, e: Event) -> None: super().on_event_pre(e) ct_msg = e.init.get('currentTarget', dict()) if e.type in ('input', 'change'): # Update user inputs if self.type.lower() == 'checkbox': self._set_attribute('checked', ct_msg.get('checked')) elif self.type.lower() == 'radio': self._set_attribute('checked', ct_msg.get('checked')) for other in self._find_grouped_nodes(): if other is not self: other._remove_attribute('checked') else: self._set_attribute('value', ct_msg.get('value'))
Set values set on browser before calling event listeners.
def control(self) -> Optional[HTMLElement]: 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: raise TypeError('"for" attribute must be string') return None
Return related HTMLElement object.
def on_event_pre(self, e: Event) -> None: super().on_event_pre(e) ct_msg = e.init.get('currentTarget', dict()) if e.type in ('input', 'change'): self._set_attribute('value', ct_msg.get('value')) _selected = ct_msg.get('selectedOptions', []) self._selected_options.clear() for opt in self.options: if opt.wdom_id in _selected: self._selected_options.append(opt) opt._set_attribute('selected', True) else: opt._remove_attribute('selected')
Set values set on browser before calling event listeners.
def selectedOptions(self) -> NodeList: return NodeList(list(opt for opt in self.options if opt.selected))
Return all selected option nodes.
def on_event_pre(self, e: Event) -> None: super().on_event_pre(e) ct_msg = e.init.get('currentTarget', dict()) if e.type in ('input', 'change'): # Update user inputs self._set_text_content(ct_msg.get('value') or '')
Set values set on browser before calling event listeners.
def NewTagClass(class_name: str, tag: str = None, bases: Union[type, Iterable] = (Tag, ), **kwargs: Any) -> type: 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
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>
def _clone_node(self) -> 'Tag': 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
Need to copy class, not tag. So need to re-implement copy.
def textContent(self, text: str) -> None: # type: ignore if self._inner_element: self._inner_element.textContent = text else: # Need a trick to call property of super-class super().textContent = text
Set text content to inner node.
def html(self) -> str: if self._inner_element: return self.start_tag + self._inner_element.html + self.end_tag return super().html
Get whole html representation of this node.
def innerHTML(self) -> str: if self._inner_element: return self._inner_element.innerHTML return super().innerHTML
Get innerHTML of the inner node.
def start_server(app: web.Application = None, port: int = None, address: str = None, **kwargs: Any) -> HTTPServer: app = app or get_app() port = port if port is not None else config.port address = address if address is not None else config.address server = app.listen(port, address=address) app.server = server app.loop = asyncio.get_event_loop() server_config['address'] = address for sock in server._sockets.values(): if sock.family == socket.AF_INET: server_config['port'] = sock.getsockname()[1] break return server
Start server with ``app`` on ``localhost:port``. If port is not specified, use command line option of ``--port``.
def get(self) -> None: from wdom.document import get_document logger.info('connected') self.write(get_document().build())
Return whole html representation of the root document.
async def terminate(self) -> None: 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()
Terminate server if no more connection exists.
def on_close(self) -> None: 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())
Execute when connection closed.
def log_request(self, handler: web.RequestHandler) -> None: 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 = logger.error request_time = 1000.0 * handler.request.request_time() if request_time > 10: logger.warning('%d %s %.2fms', status, handler._request_summary(), request_time) else: log_method('%d %s', status, handler._request_summary())
Handle access log.
def add_static_path(self, prefix: str, path: str) -> None: 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))] )
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.
def add_favicon_path(self, path: str) -> None: spec = web.URLSpec( '/(favicon.ico)', StaticFileHandler, dict(path=path) ) # Need some check handlers = self.handlers[0][1] handlers.append(spec)
Add path to serve favicon file. ``path`` should be a directory, which contains favicon file (``favicon.ico``) for your app.
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, "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)
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.
def chaincode_deploy(self, chaincode_path=DEFAULT_CHAINCODE_PATH, type=CHAINCODE_LANG_GO, function=DEFAULT_CHAINCODE_INIT_FUNC, args=DEFAULT_CHAINCODE_INIT_ARGS, id=1, secure_context=None, confidentiality_level=CHAINCODE_CONFIDENTIAL_PUB, metadata=None, chaincode_name=None): chaincodeID = {"name": chaincode_name} if chaincode_name else \ {"path": chaincode_path} return self._exec_action(method="deploy", type=type, chaincodeID=chaincodeID, function=function, args=args, id=id, secure_context=secure_context, confidentiality_level=confidentiality_level, metadata=metadata)
POST host:port/chaincode { "jsonrpc": "2.0", "method": "deploy", "params": { "type": 1, "chaincodeID":{ "path":"github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02" }, "ctorMsg": { "function":"init", "args":["a", "1000", "b", "2000"] } }, "id": 1 } :param chaincode_path: path of the chaincode in local or repo URL :param type: :param function: :param args: :param id: :param secure_context: :param confidentiality_level: :param metadata: :param chaincode_name: chaincode name is only required in dev mode. If chaincode_name then chaincodeID will use chaincode_name :return: json obj of the chaincode instance
def chaincode_query(self, chaincode_name, type=CHAINCODE_LANG_GO, function="query", args=["a"], id=1, secure_context=None, confidentiality_level=CHAINCODE_CONFIDENTIAL_PUB, metadata=None): return self._exec_action(method="query", type=type, chaincodeID={"name": chaincode_name}, function=function, args=args, id=id, secure_context=secure_context, confidentiality_level=confidentiality_level, metadata=metadata)
{ "jsonrpc": "2.0", "method": "query", "params": { "type": 1, "chaincodeID":{ "name":"52b0d803fc395b5e34d8d4a7cd69fb6aa00099b8fabed83504ac1c5d61a425aca5b3ad3bf96643ea4fdaac132c417c37b00f88fa800de7ece387d008a76d3586" }, "ctorMsg": { "function":"query", "args":["a"] } }, "id": 3 } :return: json obj of the chaincode instance
def get_connection(self, *args, **kwargs): conn = super(SSLAdapter, self).get_connection(*args, **kwargs) if conn.assert_hostname != self.assert_hostname: conn.assert_hostname = self.assert_hostname return conn
Ensure assert_hostname is set correctly on our pool We already take care of a normal poolmanager via init_poolmanager But we still need to take care of when there is a proxy poolmanager
def chain_list(self): res = self._get(self._url("/chain")) return self._result(res, True)
GET /chain Use the Chain API to retrieve the current state of the blockchain. The returned BlockchainInfo message is defined inside fabric.proto. message BlockchainInfo { uint64 height = 1; bytes currentBlockHash = 2; bytes previousBlockHash = 3; } ``` :return: json body of the blockchain info
def peer_list(self): res = self._get(self._url("/network/peers")) return self._result(res, True)
GET /network/peers Use the Network APIs to retrieve information about the network of peer nodes comprising the blockchain network. ```golang message PeersMessage { repeated PeerEndpoint peers = 1; } message PeerEndpoint { PeerID ID = 1; string address = 2; enum Type { UNDEFINED = 0; VALIDATOR = 1; NON_VALIDATOR = 2; } Type type = 3; bytes pkiID = 4; } message PeerID { string name = 1; } ``` :return: json body of the network peers info
def transaction_get(self, tran_uuid): res = self._get(self._url("/transactions/{0}", tran_uuid)) return self._result(res, json=True)
GET /transactions/{UUID} Use the /transactions/{UUID} endpoint to retrieve an individual transaction matching the UUID from the blockchain. The returned transaction message is defined inside fabric.proto. ```golang message Transaction { enum Type { UNDEFINED = 0; CHAINCODE_DEPLOY = 1; CHAINCODE_INVOKE = 2; CHAINCODE_QUERY = 3; CHAINCODE_TERMINATE = 4; } Type type = 1; bytes chaincodeID = 2; bytes payload = 3; string uuid = 4; google.protobuf.Timestamp timestamp = 5; ConfidentialityLevel confidentialityLevel = 6; bytes nonce = 7; bytes cert = 8; bytes signature = 9; } ``` :param tran_uuid: The uuid of the transaction to retrieve :return: json body of the transaction info
def watch_dir(path: str) -> None: _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)
Add ``path`` to watch for autoreload.
def open_browser(url: str, browser: str = None) -> None: 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)
Open web browser.
def enrollmentID_get(self, enrollment_id): res = self._get(self._url("/registrar/{0}", enrollment_id)) return self._result(res, True)
GET /registrar/{enrollmentID} Use the Registrar APIs to manage end user registration with the CA. ```golang message Block { uint32 version = 1; google.protobuf.Timestamp Timestamp = 2; repeated Transaction transactions = 3; bytes stateHash = 4; bytes previousBlockHash = 5; } ``` :param enrollment_id: The id of the enrollment to retrieve :return: json body of the enrollmentID info
def parse_style_decl(style: str, owner: AbstractNode = None ) -> CSSStyleDeclaration: _style = CSSStyleDeclaration(style, owner=owner) return _style
Make CSSStyleDeclaration from style string. :arg AbstractNode owner: Owner of the style.
def parse_style_rules(styles: str) -> CSSRuleList: rules = CSSRuleList() for m in _style_rule_re.finditer(styles): rules.append(CSSStyleRule(m.group(1), parse_style_decl(m.group(2)))) return rules
Make CSSRuleList object from style string.
def cssText(self) -> str: text = '; '.join('{0}: {1}'.format(k, v) for k, v in self.items()) if text: text += ';' return text
String-representation.
def removeProperty(self, prop: str) -> str: 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
Remove the css property.
def setProperty(self, prop: str, value: str, priority: str = None ) -> None: self[prop] = value
Set property as the value. The third argument ``priority`` is not implemented yet.
def cssText(self) -> str: _style = self.style.cssText if _style: return '{0} {{{1}}}'.format(self.selectorText, _style) return ''
Return string representation of this rule.
def set_loglevel(level: Union[int, str, None] = None) -> None: 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)
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``.
def parse_command_line() -> Namespace: 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
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``.
def suppress_logging() -> None: from wdom import options options.root_logger.removeHandler(options._log_handler) options.root_logger.addHandler(logging.NullHandler())
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.
def reset() -> None: 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()
Reset all wdom objects. This function clear all connections, elements, and resistered custom elements. This function also makes new document/application and set them.
def _ipaddress_match(ipname, host_ip): # OpenSSL may add a trailing newline to a subjectAltName's IP address ip = ipaddress.ip_address(six.text_type(ipname.rstrip())) return ip == host_ip
Exact matching of IP addresses. RFC 6125 explicitly doesn't define an algorithm for this (section 1.7.2 - "Out of Scope").
def _dnsname_match(dn, hostname, max_wildcards=1): 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 survey of established # policy among SSL implementations showed it to be a # reasonable choice. raise CertificateError( "too many wildcards in certificate DNS name: " + repr(dn)) # speed up common case w/o wildcards if not wildcards: return dn.lower() == hostname.lower() # RFC 6125, section 6.4.3, subitem 1. # The client SHOULD NOT attempt to match a presented identifier in which # the wildcard character comprises a label other than the left-most label. if leftmost == '*': # When '*' is a fragment by itself, it matches a non-empty dotless # fragment. pats.append('[^.]+') elif leftmost.startswith('xn--') or hostname.startswith('xn--'): # RFC 6125, section 6.4.3, subitem 3. # The client SHOULD NOT attempt to match a presented identifier # where the wildcard character is embedded within an A-label or # U-label of an internationalized domain name. pats.append(re.escape(leftmost)) else: # Otherwise, '*' matches any dotless string, e.g. www* pats.append(re.escape(leftmost).replace(r'\*', '[^.]*')) # add the remaining fragments, ignore any wildcards for frag in remainder: pats.append(re.escape(frag)) pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE) return pat.match(hostname)
Matching according to RFC 6125, section 6.4.3 http://tools.ietf.org/html/rfc6125#section-6.4.3
def match_hostname(cert, hostname): if not cert: raise ValueError("empty or no certificate, match_hostname needs a " "SSL socket or SSL context with either " "CERT_OPTIONAL or CERT_REQUIRED") try: host_ip = ipaddress.ip_address(six.text_type(hostname)) except ValueError: # Not an IP address (common case) host_ip = None dnsnames = [] san = cert.get('subjectAltName', ()) for key, value in san: if key == 'DNS': if host_ip is None and _dnsname_match(value, hostname): return dnsnames.append(value) elif key == 'IP Address': if host_ip is not None and _ipaddress_match(value, host_ip): return dnsnames.append(value) if not dnsnames: # The subject is only checked when there is no dNSName entry # in subjectAltName for sub in cert.get('subject', ()): for key, value in sub: # XXX according to RFC 2818, the most specific Common Name # must be used. if key == 'commonName': if _dnsname_match(value, hostname): return dnsnames.append(value) if len(dnsnames) > 1: raise CertificateError( "hostname %r doesn't match either of %s" % (hostname, ', '.join(map(repr, dnsnames)))) elif len(dnsnames) == 1: raise CertificateError( "hostname %r doesn't match %r" % (hostname, dnsnames[0]) ) else: raise CertificateError( "no appropriate commonName or " "subjectAltName fields were found" )
Verify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 rules are followed, but IP addresses are not accepted for *hostname*. CertificateError is raised on failure. On success, the function returns nothing.
def _ensure_node(node: Union[str, AbstractNode]) -> AbstractNode: if isinstance(node, str): return Text(node) elif isinstance(node, Node): return node else: raise TypeError('Invalid type to append: {}'.format(node))
Ensure to be node. If ``node`` is string, convert it to ``Text`` node.
def previousSibling(self) -> Optional[AbstractNode]: parent = self.parentNode if parent is None: return None return parent.childNodes.item(parent.childNodes.index(self) - 1)
Return the previous sibling of this node. If there is no previous sibling, return ``None``.
def ownerDocument(self) -> Optional[AbstractNode]: if self.nodeType == Node.DOCUMENT_NODE: return self elif self.parentNode: return self.parentNode.ownerDocument return None
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
def index(self, node: AbstractNode) -> int: 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')
Return index of the node. If the node is not a child of this node, raise ``ValueError``.
def insertBefore(self, node: AbstractNode, ref_node: AbstractNode) -> AbstractNode: return self._insert_before(node, ref_node)
Insert a node just before the reference node.
def replaceChild(self, new_child: AbstractNode, old_child: AbstractNode) -> AbstractNode: return self._replace_child(new_child, old_child)
Replace an old child with new child.
def cloneNode(self, deep: bool=False) -> AbstractNode: if deep: return self._clone_node_deep() return self._clone_node()
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).
def item(self, index: int) -> Optional[Node]: 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
Return item with the index. If the index is negative number or out of the list, return None.
def namedItem(self, name: str) -> Optional[Node]: for n in self: if n.getAttribute('id') == name: return n for n in self: if n.getAttribute('name') == name: return n return None
TODO.
def children(self) -> NodeList: return NodeList([e for e in self.childNodes if e.nodeType == Node.ELEMENT_NODE])
Return list of child nodes. Currently this is not a live object.
def firstElementChild(self) -> Optional[AbstractNode]: for child in self.childNodes: if child.nodeType == Node.ELEMENT_NODE: return child return None
First Element child node. If this node has no element child, return None.
def lastElementChild(self) -> Optional[AbstractNode]: for child in reversed(self.childNodes): # type: ignore if child.nodeType == Node.ELEMENT_NODE: return child return None
Last Element child node. If this node has no element child, return None.
def prepend(self, *nodes: Union[str, AbstractNode]) -> None: node = _to_node_list(nodes) if self.firstChild: self.insertBefore(node, self.firstChild) else: self.appendChild(node)
Insert new nodes before first child node.
def append(self, *nodes: Union[AbstractNode, str]) -> None: node = _to_node_list(nodes) self.appendChild(node)
Append new nodes after last child node.
def nextElementSibling(self) -> Optional[AbstractNode]: 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
Next Element Node. If this node has no next element node, return None.
def before(self, *nodes: Union[AbstractNode, str]) -> None: if self.parentNode: node = _to_node_list(nodes) self.parentNode.insertBefore(node, self)
Insert nodes before this node. If nodes contains ``str``, it will be converted to Text node.
def after(self, *nodes: Union[AbstractNode, str]) -> None: 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)
Append nodes after this node. If nodes contains ``str``, it will be converted to Text node.
def replaceWith(self, *nodes: Union[AbstractNode, str]) -> None: if self.parentNode: node = _to_node_list(nodes) self.parentNode.replaceChild(node, self)
Replace this node with nodes. If nodes contains ``str``, it will be converted to Text node.
def insertData(self, offset: int, string: str) -> None: self._insert_data(offset, string)
Insert ``string`` at offset on this node.
def deleteData(self, offset: int, count: int) -> None: self._delete_data(offset, count)
Delete data by offset to count letters.
def replaceData(self, offset: int, count: int, string: str) -> None: self._replace_data(offset, count, string)
Replace data from offset to count by string.
def html(self) -> str: if self.parentNode and self.parentNode._should_escape_text: return html.escape(self.data) return self.data
Return html-escaped string representation of this node.
def create_event(msg: EventMsgDict) -> Event: proto = msg.get('proto', '') cls = proto_dict.get(proto, Event) e = cls(msg['type'], msg) return e
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.
def getData(self, type: str) -> str: return self.__data.get(normalize_type(type), '')
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'.
def setData(self, type: str, data: str) -> None: type = normalize_type(type) if type in self.__data: del self.__data[type] self.__data[type] = data
Set data of type format. :arg str type: Data format of the data, like 'text/plain'.
def clearData(self, type: str = '') -> None: type = normalize_type(type) if not type: self.__data.clear() elif type in self.__data: del self.__data[type]
Remove data of type foramt. If type argument is omitted, remove all data.
def addEventListener(self, event: str, listener: _EventListenerType ) -> None: self._add_event_listener(event, listener)
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``.
def removeEventListener(self, event: str, listener: _EventListenerType ) -> None: self._remove_event_listener(event, listener)
Remove an event listener of this node. The listener is removed only when both event type and listener is matched.
def on_response(self, msg: Dict[str, str]) -> None: 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'))
Run when get response from browser.
def js_exec(self, method: str, *args: Union[int, str, bool]) -> None: if self.connected: self.ws_send(dict(method=method, params=args))
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.
def js_query(self, query: str) -> Awaitable: 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
Send query to related DOM on browser. :param str query: single string which indicates query type.
def ws_send(self, obj: Dict[str, Union[Iterable[_T_MsgItem], _T_MsgItem]] ) -> None: from wdom import server if self.ownerDocument is not None: obj['target'] = 'node' obj['id'] = self.wdom_id server.push_message(obj)
Send ``obj`` as message to the related nodes on browser. :arg dict obj: Message is serialized by JSON object and send via WebSocket connection.
def generate_url(query, first, recent, country_code): query = '+'.join(query.split()) url = 'http://www.bing.com/search?q=' + query + '&first=' + first if recent in ['h', 'd', 'w', 'm', 'y']: # A True/False would be enough. This is just to maintain consistancy with google. url = url + '&filters=ex1%3a%22ez1%22' if country_code is not None: url += '&cc=' + country_code return url
(str, str) -> str A url in the required format is generated.
def generate_news_url(query, first, recent, country_code): query = '+'.join(query.split()) url = 'http://www.bing.com/news/search?q=' + query + '&first' + first if recent in ['h', 'd', 'w', 'm', 'y']: # A True/False would be enough. This is just to maintain consistancy with google. url = url + '&qft=sortbydate%3d%221%22' if country_code is not None: url += '&cc=' + country_code return url
(str, str) -> str A url in the required format is generated.
def try_cast_int(s): try: temp = re.findall('\d', str(s)) temp = ''.join(temp) return int(temp) except: return s
(str) -> int All the digits in a given string are concatenated and converted into a single number.
def generate_url(query, num, start, recent, country_code): query = '+'.join(query.split()) url = 'https://www.google.com/search?q=' + query + '&num=' + num + '&start=' + start if recent in ['h', 'd', 'w', 'm', 'y']: url += '&tbs=qdr:' + recent if country_code is not None: url += '&gl=' + country_code return url
(str, str, str) -> str A url in the required format is generated.
def estimate_cp(ts, method="mean", Q=1, penalty_value=0.175): """ ts: time series method: look for a single changepoint in 'mean' , 'var', 'mean and var' or use binary segmentatiom to detect multiple changepoints in mean (binseg). Q: Number of change points to look for (only for binseg) penalty_value: Penalty to use as threshold (only for binseg) Returns: returns indices of the changepoints """ robjects.r("library(changepoint)") method_map = { "mean": "cpt.mean({})", "var": "cpt.var({})", "meanvar": "cpt.meanvar({})", "binseg.mean.CUSUM": "cpt.mean({},penalty='Manual', test.stat='CUSUM',method='BinSeg',Q={},pen.value={})" } mt = robjects.FloatVector(ts) robjects.globalenv["mt"] = mt if method == "binseg.mean.CUSUM": cmd = method_map[method].format("mt", Q, penalty_value) else: cmd = method_map[method].format("mt") robjects.globalenv["mycpt"] = robjects.r(cmd) ecp = robjects.r("cpts(mycpt)") return ecp
Estimate changepoints in a time series by using R.
def estimate_cp_pval(ts, method="mean"): """ ts: time series method: look for a single changepoint in 'mean' , 'var', 'mean and var' Returns: returns index of the changepoint, and pvalue. Here pvalue = 1 means statistically significant """ robjects.r("library(changepoint)") method_map = { "mean": "cpt.mean({}, class=FALSE)", "var": "cpt.var({}, class=FALSE)", "meanvar": "cpt.meanvar({}, class=FALSE)", } mt = robjects.FloatVector(ts) robjects.globalenv["mt"] = mt cmd = method_map[method].format("mt") robjects.globalenv["mycpt"] = robjects.r(cmd) ecp_pval = robjects.r("mycpt") ecp = ecp_pval[0] pval = ecp_pval[1] return ecp, pval
Estimate changepoints in a time series by using R.
def get_ts_stats_significance(self, x, ts, stat_ts_func, null_ts_func, B=1000, permute_fast=False, label_ts=''): 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
Returns the statistics, pvalues and the actual number of bootstrap samples.