code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
return self.attributes.removeNamedItem(attr) | def removeAttributeNode(self, attr: Attr) -> Optional[Attr] | Remove ``Attr`` node from this node. | 18.391821 | 16.126047 | 1.140504 |
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 = CSSS... | def style(self, style: _AttrValueType) -> None | Set style attribute of this node.
If argument ``style`` is string, it will be parsed to
``CSSStyleDeclaration``. | 3.72739 | 3.508501 | 1.062388 |
if not self.hasAttribute('draggable'):
return False
return self.getAttribute('draggable') | def draggable(self) -> Union[bool, str] | Get ``draggable`` property. | 4.442649 | 4.113795 | 1.079939 |
if value is False:
self.removeAttribute('draggable')
else:
self.setAttribute('draggable', value) | def draggable(self, value: Union[bool, str]) -> None | Set ``draggable`` property.
``value`` is boolean or string. | 4.195288 | 4.279728 | 0.98027 |
if self.__form:
return self.__form
parent = self.parentNode
while parent:
if isinstance(parent, HTMLFormElement):
return parent
else:
parent = parent.parentNode
return None | def form(self) -> Optional['HTMLFormElement'] | Get ``HTMLFormElement`` object related to this node. | 2.48159 | 2.369998 | 1.047085 |
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(... | def on_event_pre(self, e: Event) -> None | Set values set on browser before calling event listeners. | 3.949423 | 3.657938 | 1.079686 |
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:
... | def control(self) -> Optional[HTMLElement] | Return related HTMLElement object. | 3.756172 | 3.50337 | 1.07216 |
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 i... | def on_event_pre(self, e: Event) -> None | Set values set on browser before calling event listeners. | 4.402678 | 3.952164 | 1.113992 |
return NodeList(list(opt for opt in self.options if opt.selected)) | def selectedOptions(self) -> NodeList | Return all selected option nodes. | 8.320939 | 6.387608 | 1.302669 |
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 '') | def on_event_pre(self, e: Event) -> None | Set values set on browser before calling event listeners. | 9.652792 | 7.887491 | 1.22381 |
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)))
... | 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.
... | 4.742836 | 5.459424 | 0.868743 |
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 | def _clone_node(self) -> 'Tag' | Need to copy class, not tag.
So need to re-implement copy. | 3.965129 | 4.017733 | 0.986907 |
self._inner_element.textContent = text
else:
# Need a trick to call property of super-class
super().textContent = text | def textContent(self, text: str) -> None: # type: ignore
if self._inner_element | Set text content to inner node. | 17.545019 | 11.174387 | 1.57011 |
if self._inner_element:
return self.start_tag + self._inner_element.html + self.end_tag
return super().html | def html(self) -> str | Get whole html representation of this node. | 5.549723 | 4.327842 | 1.28233 |
if self._inner_element:
return self._inner_element.innerHTML
return super().innerHTML | def innerHTML(self) -> str | Get innerHTML of the inner node. | 5.96087 | 4.118229 | 1.447435 |
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 ser... | def start_server(app: web.Application = None, port: int = None,
address: str = None, **kwargs: Any) -> HTTPServer | Start server with ``app`` on ``localhost:port``.
If port is not specified, use command line option of ``--port``. | 2.913269 | 3.084464 | 0.944498 |
from wdom.document import get_document
logger.info('connected')
self.write(get_document().build()) | def get(self) -> None | Return whole html representation of the root document. | 16.069077 | 12.122025 | 1.32561 |
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() | async def terminate(self) -> None | Terminate server if no more connection exists. | 9.696934 | 5.873874 | 1.650858 |
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():
... | def on_close(self) -> None | Execute when connection closed. | 7.799228 | 6.931095 | 1.125252 |
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_... | def log_request(self, handler: web.RequestHandler) -> None | Handle access log. | 2.266613 | 2.133404 | 1.06244 |
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, ... | 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. | 5.759853 | 5.141854 | 1.12019 |
spec = web.URLSpec(
'/(favicon.ico)',
StaticFileHandler,
dict(path=path)
)
# Need some check
handlers = self.handlers[0][1]
handlers.append(spec) | 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. | 10.263747 | 9.873642 | 1.03951 |
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,
... | def _exec_action(self,
method,
type,
chaincodeID,
function,
args,
id,
secure_context=None,
confidentiality_level=CHAINCODE_CONFIDENTIAL_PUB,
... | 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: M... | 2.811117 | 2.762376 | 1.017644 |
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,
... | 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,
confid... | POST host:port/chaincode
{
"jsonrpc": "2.0",
"method": "deploy",
"params": {
"type": 1,
"chaincodeID":{
"path":"github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02"
},
"ctorMsg": {
"fun... | 2.334765 | 2.755192 | 0.847406 |
return self._exec_action(method="query", type=type,
chaincodeID={"name": chaincode_name},
function=function, args=args, id=id,
secure_context=secure_context,
confidentiali... | 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) | {
"jsonrpc": "2.0",
"method": "query",
"params": {
"type": 1,
"chaincodeID":{
"name":"52b0d803fc395b5e34d8d4a7cd69fb6aa00099b8fabed83504ac1c5d61a425aca5b3ad3bf96643ea4fdaac132c417c37b00f88fa800de7ece387d008a76d3586"
},
... | 2.359253 | 2.581334 | 0.913967 |
conn = super(SSLAdapter, self).get_connection(*args, **kwargs)
if conn.assert_hostname != self.assert_hostname:
conn.assert_hostname = self.assert_hostname
return conn | def get_connection(self, *args, **kwargs) | 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 | 2.98975 | 2.696154 | 1.108895 |
res = self._get(self._url("/chain"))
return self._result(res, True) | def chain_list(self) | 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;
}
... | 10.915887 | 10.559933 | 1.033708 |
res = self._get(self._url("/network/peers"))
return self._result(res, True) | def peer_list(self) | 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;
... | 10.017179 | 9.058138 | 1.105876 |
res = self._get(self._url("/transactions/{0}", tran_uuid))
return self._result(res, json=True) | def transaction_get(self, tran_uuid) | 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 {
U... | 5.758797 | 7.216039 | 0.798055 |
_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) | def watch_dir(path: str) -> None | Add ``path`` to watch for autoreload. | 10.042065 | 7.387277 | 1.359373 |
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) | def open_browser(url: str, browser: str = None) -> None | Open web browser. | 5.085748 | 4.385829 | 1.159586 |
res = self._get(self._url("/registrar/{0}", enrollment_id))
return self._result(res, True) | def enrollmentID_get(self, enrollment_id) | 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;
... | 8.000811 | 7.275269 | 1.099727 |
_style = CSSStyleDeclaration(style, owner=owner)
return _style | def parse_style_decl(style: str, owner: AbstractNode = None
) -> CSSStyleDeclaration | Make CSSStyleDeclaration from style string.
:arg AbstractNode owner: Owner of the style. | 7.927447 | 10.285763 | 0.77072 |
rules = CSSRuleList()
for m in _style_rule_re.finditer(styles):
rules.append(CSSStyleRule(m.group(1), parse_style_decl(m.group(2))))
return rules | def parse_style_rules(styles: str) -> CSSRuleList | Make CSSRuleList object from style string. | 2.83323 | 2.638032 | 1.073994 |
text = '; '.join('{0}: {1}'.format(k, v) for k, v in self.items())
if text:
text += ';'
return text | def cssText(self) -> str | String-representation. | 3.917141 | 3.249397 | 1.205498 |
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 | def removeProperty(self, prop: str) -> str | Remove the css property. | 5.961203 | 5.452938 | 1.093209 |
self[prop] = value | def setProperty(self, prop: str, value: str, priority: str = None
) -> None | Set property as the value.
The third argument ``priority`` is not implemented yet. | 70.836647 | 33.483852 | 2.115547 |
_style = self.style.cssText
if _style:
return '{0} {{{1}}}'.format(self.selectorText, _style)
return '' | def cssText(self) -> str | Return string representation of this rule. | 6.917459 | 4.184608 | 1.653072 |
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) | 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``. | 2.974875 | 3.376558 | 0.881038 |
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 | 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``. | 6.917196 | 4.772309 | 1.449444 |
from wdom import options
options.root_logger.removeHandler(options._log_handler)
options.root_logger.addHandler(logging.NullHandler()) | 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. | 6.46387 | 4.389921 | 1.472434 |
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._... | 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. | 5.471199 | 4.402997 | 1.242608 |
# 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 | def _ipaddress_match(ipname, host_ip) | Exact matching of IP addresses.
RFC 6125 explicitly doesn't define an algorithm for this
(section 1.7.2 - "Out of Scope"). | 9.353676 | 10.394067 | 0.899905 |
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 ... | 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 | 3.48572 | 3.342897 | 1.042724 |
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:
... | def match_hostname(cert, hostname) | 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. | 2.72943 | 2.592303 | 1.052898 |
if isinstance(node, str):
return Text(node)
elif isinstance(node, Node):
return node
else:
raise TypeError('Invalid type to append: {}'.format(node)) | def _ensure_node(node: Union[str, AbstractNode]) -> AbstractNode | Ensure to be node.
If ``node`` is string, convert it to ``Text`` node. | 4.408332 | 3.770891 | 1.169043 |
parent = self.parentNode
if parent is None:
return None
return parent.childNodes.item(parent.childNodes.index(self) - 1) | def previousSibling(self) -> Optional[AbstractNode] | Return the previous sibling of this node.
If there is no previous sibling, return ``None``. | 3.038161 | 3.130866 | 0.97039 |
if self.nodeType == Node.DOCUMENT_NODE:
return self
elif self.parentNode:
return self.parentNode.ownerDocument
return None | 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 | 2.975484 | 3.937397 | 0.755698 |
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
... | def index(self, node: AbstractNode) -> int | Return index of the node.
If the node is not a child of this node, raise ``ValueError``. | 4.345347 | 3.923092 | 1.107633 |
return self._insert_before(node, ref_node) | def insertBefore(self, node: AbstractNode,
ref_node: AbstractNode) -> AbstractNode | Insert a node just before the reference node. | 6.556551 | 4.386045 | 1.494866 |
return self._replace_child(new_child, old_child) | def replaceChild(self, new_child: AbstractNode,
old_child: AbstractNode) -> AbstractNode | Replace an old child with new child. | 5.573176 | 3.638122 | 1.531883 |
if deep:
return self._clone_node_deep()
return self._clone_node() | 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). | 4.603176 | 7.036932 | 0.654145 |
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 | 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. | 4.090763 | 3.921148 | 1.043257 |
for n in self:
if n.getAttribute('id') == name:
return n
for n in self:
if n.getAttribute('name') == name:
return n
return None | def namedItem(self, name: str) -> Optional[Node] | TODO. | 2.650635 | 2.343123 | 1.13124 |
return NodeList([e for e in self.childNodes
if e.nodeType == Node.ELEMENT_NODE]) | def children(self) -> NodeList | Return list of child nodes.
Currently this is not a live object. | 5.184875 | 4.814159 | 1.077005 |
for child in self.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
return child
return None | def firstElementChild(self) -> Optional[AbstractNode] | First Element child node.
If this node has no element child, return None. | 2.669243 | 2.804925 | 0.951627 |
for child in reversed(self.childNodes): # type: ignore
if child.nodeType == Node.ELEMENT_NODE:
return child
return None | def lastElementChild(self) -> Optional[AbstractNode] | Last Element child node.
If this node has no element child, return None. | 3.094985 | 3.079166 | 1.005137 |
node = _to_node_list(nodes)
if self.firstChild:
self.insertBefore(node, self.firstChild)
else:
self.appendChild(node) | def prepend(self, *nodes: Union[str, AbstractNode]) -> None | Insert new nodes before first child node. | 4.218329 | 3.124714 | 1.349989 |
node = _to_node_list(nodes)
self.appendChild(node) | def append(self, *nodes: Union[AbstractNode, str]) -> None | Append new nodes after last child node. | 12.107302 | 7.554368 | 1.602689 |
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 | def nextElementSibling(self) -> Optional[AbstractNode] | Next Element Node.
If this node has no next element node, return None. | 1.962118 | 2.085266 | 0.940944 |
if self.parentNode:
node = _to_node_list(nodes)
self.parentNode.insertBefore(node, self) | def before(self, *nodes: Union[AbstractNode, str]) -> None | Insert nodes before this node.
If nodes contains ``str``, it will be converted to Text node. | 7.823482 | 7.639026 | 1.024146 |
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) | def after(self, *nodes: Union[AbstractNode, str]) -> None | Append nodes after this node.
If nodes contains ``str``, it will be converted to Text node. | 4.043126 | 3.917178 | 1.032153 |
if self.parentNode:
node = _to_node_list(nodes)
self.parentNode.replaceChild(node, self) | def replaceWith(self, *nodes: Union[AbstractNode, str]) -> None | Replace this node with nodes.
If nodes contains ``str``, it will be converted to Text node. | 6.41646 | 6.710208 | 0.956224 |
self._insert_data(offset, string) | def insertData(self, offset: int, string: str) -> None | Insert ``string`` at offset on this node. | 16.056578 | 7.456368 | 2.153405 |
self._delete_data(offset, count) | def deleteData(self, offset: int, count: int) -> None | Delete data by offset to count letters. | 15.152278 | 6.930658 | 2.186268 |
self._replace_data(offset, count, string) | def replaceData(self, offset: int, count: int, string: str) -> None | Replace data from offset to count by string. | 10.330919 | 5.728456 | 1.803439 |
if self.parentNode and self.parentNode._should_escape_text:
return html.escape(self.data)
return self.data | def html(self) -> str | Return html-escaped string representation of this node. | 10.441602 | 6.41172 | 1.628518 |
proto = msg.get('proto', '')
cls = proto_dict.get(proto, Event)
e = cls(msg['type'], msg)
return e | 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. | 7.115936 | 9.115211 | 0.780666 |
return self.__data.get(normalize_type(type), '') | 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'. | 15.082672 | 14.300464 | 1.054698 |
type = normalize_type(type)
if type in self.__data:
del self.__data[type]
self.__data[type] = data | def setData(self, type: str, data: str) -> None | Set data of type format.
:arg str type: Data format of the data, like 'text/plain'. | 3.863935 | 4.976153 | 0.77649 |
type = normalize_type(type)
if not type:
self.__data.clear()
elif type in self.__data:
del self.__data[type] | def clearData(self, type: str = '') -> None | Remove data of type foramt.
If type argument is omitted, remove all data. | 4.147374 | 3.731333 | 1.111499 |
self._add_event_listener(event, listener) | 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``. | 7.533095 | 9.574063 | 0.786823 |
self._remove_event_listener(event, listener) | 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. | 8.638393 | 8.428862 | 1.024859 |
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')) | def on_response(self, msg: Dict[str, str]) -> None | Run when get response from browser. | 4.50139 | 3.93535 | 1.143835 |
if self.connected:
self.ws_send(dict(method=method, params=args)) | 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. | 6.949245 | 9.423888 | 0.737407 |
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 | def js_query(self, query: str) -> Awaitable | Send query to related DOM on browser.
:param str query: single string which indicates query type. | 4.03722 | 4.571964 | 0.883038 |
from wdom import server
if self.ownerDocument is not None:
obj['target'] = 'node'
obj['id'] = self.wdom_id
server.push_message(obj) | 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. | 10.720045 | 9.987486 | 1.073348 |
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:
... | def generate_url(query, first, recent, country_code) | (str, str) -> str
A url in the required format is generated. | 5.664234 | 5.631022 | 1.005898 |
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... | def generate_news_url(query, first, recent, country_code) | (str, str) -> str
A url in the required format is generated. | 5.407799 | 5.359065 | 1.009094 |
try:
temp = re.findall('\d', str(s))
temp = ''.join(temp)
return int(temp)
except:
return s | def try_cast_int(s) | (str) -> int
All the digits in a given string are concatenated and converted into a single number. | 4.211123 | 4.160656 | 1.012129 |
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 | def generate_url(query, num, start, recent, country_code) | (str, str, str) -> str
A url in the required format is generated. | 2.306975 | 2.345869 | 0.98342 |
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(t... | def estimate_cp(ts, method="mean", Q=1, penalty_value=0.175) | Estimate changepoints in a time series by using R. | 4.409162 | 4.225238 | 1.04353 |
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("m... | def estimate_cp_pval(ts, method="mean") | Estimate changepoints in a time series by using R. | 3.239499 | 3.028106 | 1.06981 |
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 | 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 actual number of bootstrap
samples. | 2.820541 | 2.60205 | 1.083969 |
l = len(ts)
return np.random.normal(mu, sigma, l) | def generate_null_timeseries(self, ts, mu, sigma) | Generate a time series with a given mu and sigma. This serves as the
NULL distribution. | 3.899056 | 3.829307 | 1.018215 |
return np.mean(ts[t + 1:]) - np.mean(ts[:t + 1]) | def compute_balance_mean(self, ts, t) | Compute the balance. The right end - the left end. | 4.167254 | 3.21652 | 1.295579 |
balance = [self.compute_balance_mean(ts, t) for t in np.arange(0, len(ts) - 1)]
return balance | def compute_balance_mean_ts(self, ts) | Compute the balance at each time 't' of the time series. | 4.10077 | 3.339237 | 1.228056 |
return np.median(ts[t + 1:]) - np.median(ts[:t + 1]) | def compute_balance_median(self, ts, t) | Compute the balance at either end. | 3.795582 | 3.307089 | 1.147711 |
balance = [self.compute_balance_median(ts, t) for t in np.arange(0, len(ts) - 1)]
return balance | def compute_balance_median_ts(self, ts) | Compute the balance at each time 't' of the time series. | 4.33861 | 3.40155 | 1.27548 |
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 | def compute_cusum_ts(self, ts) | Compute the Cumulative Sum at each point 't' of the time series. | 2.541584 | 2.457505 | 1.034213 |
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 | def detect_mean_shift(self, ts, B=1000) | Detect mean shift in a time series. B is number of bootstrapped
samples to draw. | 6.124322 | 6.018126 | 1.017646 |
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) | def parallelize_func(iterable, func, chunksz=1, n_jobs=16, *args, **kwargs) | Parallelize a function over each element of an iterable. | 2.69957 | 2.63262 | 1.025431 |
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 =... | 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. | 2.596866 | 2.668619 | 0.973112 |
beta_star = np.empty(B)
z = y
z_star = np.empty(len(z))
for boot_i in range(B):
for block_i, start in enumerate(np.random.randint(len(z) - b + 1, size=len(z) / b)):
z_star[block_i * b:(block_i + 1) * b] = z[start:start + b]
beta_star[boot_i] = func(z_star)
return... | def bootstrap_ts(y, func, B=1000, b=3) | Bootstrap a timeseries using a window size:b. | 2.627532 | 2.658046 | 0.98852 |
# get rid of nans while we sort
b_star = np.sort(theta_star[~np.isnan(theta_star)])
se = np.std(b_star) * np.sqrt(blockratio)
# bootstrap 95% CI based on empirical percentiles
ci = [b_star[int(len(b_star) * .025)], b_star[int(len(b_star) * .975)]]
return ci | def get_ci(theta_star, blockratio=1.0) | Get the confidence interval. | 3.500608 | 3.443008 | 1.01673 |
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 | def get_pvalue(value, ci) | Get the p-value from the confidence interval. | 3.275853 | 3.028402 | 1.08171 |
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 | 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. | 3.978556 | 4.254274 | 0.93519 |
def format_shortcut(editor,
path,
line_number,
function=None):
return template.format(editor=editor,
line_number=line_number or 0,
path=path,
... | def format_traceback(extracted_tb,
exc_type,
exc_value,
cwd='',
term=None,
function_color=12,
dim_color=8,
editor='vi',
template=DEFAULT_EDITOR_SHORTCUT... | 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. | 5.062464 | 5.023796 | 1.007697 |
# 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) | 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(). | 4.255267 | 4.141626 | 1.027439 |
return [(_decode(file), line_number, _decode(function), _decode(text))
for file, line_number, function, text in extracted_tb] | def _unicode_decode_extracted_tb(extracted_tb) | Return a traceback with the string elements translated into Unicode. | 3.609212 | 3.495165 | 1.03263 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.