code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
params = {"email": self.email_address} body = { "EmailAddress": new_email_address, "Name": name} response = self._put("/admins.json", body=json.dumps(body), params=params) # Update self.email_address, so this object can contin...
def update(self, new_email_address, name)
Updates the details for an administrator.
4.493753
4.221545
1.064481
params = {"email": self.email_address} response = self._delete("/admins.json", params=params)
def delete(self)
Deletes the administrator from the account.
9.319987
5.656689
1.647605
if not cert: raise ValueError("empty or no certificate") dnsnames = [] san = cert.get('subjectAltName', ()) for key, value in san: if key == 'DNS': if _dnsname_to_pat(value).match(hostname): return dnsnames.append(value) if not san: ...
def match_hostname(cert, hostname)
This is a backport of the match_hostname() function from Python 3.2, essential when using SSL. Verifies that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules are mostly followed, but IP addresses are not accepted for *hostname*. CertificateEr...
2.562296
2.384249
1.074676
body = { "Title": title, "UnsubscribePage": unsubscribe_page, "ConfirmedOptIn": confirmed_opt_in, "ConfirmationSuccessPage": confirmation_success_page, "UnsubscribeSetting": unsubscribe_setting} response = self._post("/lists/%s.json" %...
def create(self, client_id, title, unsubscribe_page, confirmed_opt_in, confirmation_success_page, unsubscribe_setting="AllClientLists")
Creates a new list for a client.
2.340402
2.224536
1.052085
body = { "FieldName": field_name, "DataType": data_type, "Options": options, "VisibleInPreferenceCenter": visible_in_preference_center} response = self._post(self.uri_for("customfields"), json.dumps(body)) return json_to_py(response)
def create_custom_field(self, field_name, data_type, options=[], visible_in_preference_center=True)
Creates a new custom field for this list.
2.900458
2.859558
1.014303
custom_field_key = quote(custom_field_key, '') body = { "FieldName": field_name, "VisibleInPreferenceCenter": visible_in_preference_center} response = self._put(self.uri_for("customfields/%s" % custom_field_key), json.dum...
def update_custom_field(self, custom_field_key, field_name, visible_in_preference_center)
Updates a custom field belonging to this list.
3.639776
4.132259
0.88082
custom_field_key = quote(custom_field_key, '') response = self._delete("/lists/%s/customfields/%s.json" % (self.list_id, custom_field_key))
def delete_custom_field(self, custom_field_key)
Deletes a custom field associated with this list.
3.857748
3.338695
1.155466
custom_field_key = quote(custom_field_key, '') body = { "Options": new_options, "KeepExistingOptions": keep_existing_options} response = self._put(self.uri_for( "customfields/%s/options" % custom_field_key), json.dumps(body))
def update_custom_field_options(self, custom_field_key, new_options, keep_existing_options)
Updates the options of a multi-optioned custom field on this list.
3.634318
3.963762
0.916886
params = { "date": date, "page": page, "pagesize": page_size, "orderfield": order_field, "orderdirection": order_direction, "includetrackingpreference": include_tracking_preference, } response = self._get(self.uri_f...
def active(self, date="", page=1, page_size=1000, order_field="email", order_direction="asc", include_tracking_preference=False)
Gets the active subscribers for this list.
2.180061
2.198601
0.991567
body = { "Title": title, "UnsubscribePage": unsubscribe_page, "ConfirmedOptIn": confirmed_opt_in, "ConfirmationSuccessPage": confirmation_success_page, "UnsubscribeSetting": unsubscribe_setting, "AddUnsubscribesToSuppList": add_uns...
def update(self, title, unsubscribe_page, confirmed_opt_in, confirmation_success_page, unsubscribe_setting="AllClientLists", add_unsubscribes_to_supp_list=False, scrub_active_with_supp_list=False)
Updates this list.
1.578198
1.545363
1.021248
body = { "Events": events, "Url": url, "PayloadFormat": payload_format} response = self._post(self.uri_for("webhooks"), json.dumps(body)) return json_to_py(response)
def create_webhook(self, events, url, payload_format)
Creates a new webhook for the specified events (an array of strings). Valid events are "Subscribe", "Deactivate", and "Update". Valid payload formats are "json", and "xml".
4.007451
4.505397
0.889478
params = { "email": email_address or self.email_address, "includetrackingpreference": include_tracking_preference, } response = self._get("/subscribers/%s.json" % (list_id or self.list_id), params=params) return json_to_py(res...
def get(self, list_id=None, email_address=None, include_tracking_preference=False)
Gets a subscriber by list ID and email address.
3.266624
3.158648
1.034184
validate_consent_to_track(consent_to_track) body = { "EmailAddress": email_address, "Name": name, "CustomFields": custom_fields, "Resubscribe": resubscribe, "ConsentToTrack": consent_to_track, "RestartSubscriptionBasedAutor...
def add(self, list_id, email_address, name, custom_fields, resubscribe, consent_to_track, restart_subscription_based_autoresponders=False)
Adds a subscriber to a subscriber list.
2.31444
2.322013
0.996739
validate_consent_to_track(consent_to_track) params = {"email": self.email_address} body = { "EmailAddress": new_email_address, "Name": name, "CustomFields": custom_fields, "Resubscribe": resubscribe, "ConsentToTrack": consent_t...
def update(self, new_email_address, name, custom_fields, resubscribe, consent_to_track, restart_subscription_based_autoresponders=False)
Updates any aspect of a subscriber, including email address, name, and custom field data if supplied.
2.613752
2.680869
0.974965
body = { "Subscribers": subscribers, "Resubscribe": resubscribe, "QueueSubscriptionBasedAutoresponders": queue_subscription_based_autoresponders, "RestartSubscriptionBasedAutoresponders": restart_subscription_based_autoresponders} try: ...
def import_subscribers(self, list_id, subscribers, resubscribe, queue_subscription_based_autoresponders=False, restart_subscription_based_autoresponders=False)
Imports subscribers into a subscriber list.
4.520947
4.599123
0.983002
body = { "EmailAddress": self.email_address} response = self._post("/subscribers/%s/unsubscribe.json" % self.list_id, json.dumps(body))
def unsubscribe(self)
Unsubscribes this subscriber from the associated list.
6.184314
5.409523
1.143227
params = {"email": self.email_address} response = self._get("/subscribers/%s/history.json" % self.list_id, params=params) return json_to_py(response)
def history(self)
Gets the historical record of this subscriber's trackable actions.
6.595182
5.13848
1.283489
columns = [] value = 1 for i in range(n): if start <= end: columns.append(value if (start <= i < end) else 0) else: columns.append(value if (start <= i or i < end) else 0) value <<= 1 return BitColumnMatrix(colu...
def mask(n, start, end)
Make a BitColumnMatrix that represents a mask. BitColumnMatrix size of n*n, to manipulate n binary bits. If start <= end, then bits in half-open range [start, end) are set. If end < start, then bits in ranges [0, end) and [start, n) are set, i.e. bits in range [end, start) are clear; oth...
3.157453
2.372063
1.3311
def render_form(form, exclude=None, **kwargs): if hasattr(form, "Meta") and hasattr(form.Meta, "layout"): return render_layout_form(form, getattr(form.Meta, "layout"), **kwargs) if exclude: exclude = exclude.split(",") for field in exclude: form.fields.pop(field) return mark_safe("".join([ ...
Render an entire form with Semantic UI wrappers for each field Args: form (form): Django Form exclude (string): exclude fields by name, separated by commas kwargs (dict): other attributes will be passed to fields Returns: string: HTML of Django Form fields with Semantic UI wrappers
null
null
null
def render_layout_form(form, layout=None, **kwargs): def make_component(type_, *args): if type_ == "Text": return "".join(args) elif type_ == "Field": result = "" for c in args: if isinstance(c, tuple): result += make_component(*c) elif isinstance(c, str): result += re...
Render an entire form with Semantic UI wrappers for each field with a layout provided in the template or in the form class Args: form (form): Django Form layout (tuple): layout design kwargs (dict): other attributes will be passed to fields Returns: string: HTML of Django Form fields with Semant...
null
null
null
def set_input(self): name = self.attrs.get("_override", self.widget.__class__.__name__) self.values["field"] = str(FIELDS.get(name, FIELDS.get(None))(self.field, self.attrs))
Returns form input field of Field.
null
null
null
def set_label(self): if not self.field.label or self.attrs.get("_no_label"): return self.values["label"] = format_html( LABEL_TEMPLATE, self.field.html_name, mark_safe(self.field.label) )
Set label markup.
null
null
null
def set_help(self): if not (self.field.help_text and self.attrs.get("_help")): return self.values["help"] = HELP_TEMPLATE.format(self.field.help_text)
Set help text markup.
null
null
null
def set_errors(self): if not self.field.errors or self.attrs.get("_no_errors"): return self.values["class"].append("error") for error in self.field.errors: self.values["errors"] += ERROR_WRAPPER % {"message": error}
Set errors markup.
null
null
null
def set_icon(self): if not self.attrs.get("_icon"): return if "Date" in self.field.field.__class__.__name__: return self.values["field"] = INPUT_WRAPPER % { "field": self.values["field"], "help": self.values["help"], "style": "%sicon " % escape(pad(self.attrs.get("_align", ""))), ...
Wrap current field with icon wrapper. This setter must be the last setter called.
null
null
null
def set_classes(self): # Custom field classes on field wrapper if self.attrs.get("_field_class"): self.values["class"].append(escape(self.attrs.get("_field_class"))) # Inline class if self.attrs.get("_inline"): self.values["class"].append("inline") # Disabled class if self.field.field....
Set field properties and custom classes.
null
null
null
def render(self): self.widget.attrs = { k: v for k, v in self.attrs.items() if k[0] != "_" } self.set_input() if not self.attrs.get("_no_wrapper"): self.set_label() self.set_help() self.set_errors() self.set_classes() self.set_icon() # Must be the bottom-most setter self....
Render field as HTML.
null
null
null
from .models import Friend # Requires migrations, not necessary try: Friend.objects.get_or_create(first_name="Michael", last_name="1", age=22) Friend.objects.get_or_create(first_name="Joe", last_name="2", age=21) Friend.objects.get_or_create(first_name="Bill", last_name="3", age=20) except: pass
def ready(self)
Create test friends for displaying.
3.218815
2.828827
1.137862
attrs.setdefault("_no_label", True) # No normal label for booleanfields attrs.setdefault("_inline", True) # Checkbox should be inline field.field.widget.attrs["style"] = "display:hidden" # Hidden field return wrappers.CHECKBOX_WRAPPER % { "style": pad(attrs.get("_style", "")), "field": field, "label": f...
def render_booleanfield(field, attrs)
Render BooleanField with label next to instead of above.
6.235775
6.192959
1.006914
# Allow custom choice list, but if no custom choice list then wrap all # choices into the `wrappers.CHOICE_TEMPLATE` if not choices: choices = format_html_join("", wrappers.CHOICE_TEMPLATE, get_choices(field)) # Accessing the widget attrs directly saves them for a new use after # a POST request field.field.w...
def render_choicefield(field, attrs, choices=None)
Render ChoiceField as 'div' dropdown rather than select for more customization.
6.3819
6.496378
0.982378
choices = "" # Loop over every choice to manipulate for choice in field.field._choices: value = choice[1].split("|") # Value|Icon # Each choice is formatted with the choice value being split with # the "|" as the delimeter. First element is the value, the second # is the icon to be used. choices += fo...
def render_iconchoicefield(field, attrs)
Render a ChoiceField with icon support; where the value is split by a pipe (|): first element being the value, last element is the icon.
6.200574
5.942935
1.043352
choices = ((k, k.lower(), v) for k, v in field.field._choices[1:]) # Render a `ChoiceField` with all countries return render_choicefield( field, attrs, format_html_join("", wrappers.COUNTRY_TEMPLATE, choices) )
def render_countryfield(field, attrs)
Render a custom ChoiceField specific for CountryFields.
8.928591
7.977632
1.119203
choices = format_html_join("", wrappers.CHOICE_TEMPLATE, get_choices(field)) return wrappers.MULTIPLE_DROPDOWN_WRAPPER % { "name": field.html_name, "field": field, "choices": choices, "placeholder": attrs.get("placeholder") or get_placeholder_text(), "style": pad(attrs.get("_style", "")), "icon": format...
def render_multiplechoicefield(field, attrs, choices=None)
MultipleChoiceField uses its own field, but also uses a queryset.
5.041938
5.126093
0.983583
return wrappers.CALENDAR_WRAPPER % { "field": field, "style": pad(style), "align": pad(attrs.get("_align", "")), "icon": format_html(wrappers.ICON_TEMPLATE, attrs.get("_icon")), }
def render_datefield(field, attrs, style="date")
DateField that uses wrappers.CALENDAR_WRAPPER.
6.314055
4.932344
1.280133
field.field.widget.attrs["style"] = "display:none" if not "_no_label" in attrs: attrs["_no_label"] = True return wrappers.FILE_WRAPPER % { "field": field, "id": "id_" + field.name, "style": pad(attrs.get("_style", "")), "text": escape(attrs.get("_text", "Select File")), "icon": format_html(wrappers.I...
def render_filefield(field, attrs)
Render a typical File Field.
4.754442
4.727559
1.005686
SIMPLERANDOM_BITS = 32 SIMPLERANDOM_MOD = 2**SIMPLERANDOM_BITS SIMPLERANDOM_MASK = SIMPLERANDOM_MOD - 1 if isinstance(o, tree_types) or getattr(o, '__iter__', False): for value in o: for subvalue in _traverse_iter(value): while True: yield sub...
def _traverse_iter(o, tree_types=(list, tuple))
Iterate over nested containers and/or iterators. This allows generator __init__() functions to be passed seeds either as a series of arguments, or as a list/tuple.
4.659234
4.500805
1.0352
last_value = None for value in input_iter: last_value = value yield value if last_value is not None: while True: yield last_value
def _repeat_iter(input_iter)
Iterate over the input iter values. Then repeat the last value indefinitely. This is useful to repeat seed values when an insufficient number of seeds are provided. E.g. KISS(1) effectively becomes KISS(1, 1, 1, 1), rather than (if we just used default values) KISS(1, default-value, default-value, defa...
2.512464
3.66257
0.685984
if n == 0: return 0 if n == 1 or r == 0: return 1 m = 2**32 # Split (r - 1) into common factors with the modulo 2**32 -- i.e. all # factors of 2; and other factors which are coprime with the modulo 2**32. other_factors = r - 1 common_factor = 1 while (other_factors %...
def _geom_series_uint32(r, n)
Unsigned integer calculation of sum of geometric series: 1 + r + r^2 + r^3 + ... r^(n-1) summed to n terms. Calculated modulo 2**32. Use the formula (r**n - 1) / (r - 1)
3.716573
3.454798
1.075772
try: seed = seed_iter.next() except StopIteration: return 0xFFFFFFFF else: if seed is None: return 0xFFFFFFFF else: seed = int(seed) & 0xFFFFFFFF working_seed = (seed ^ (seed << 16)) & 0xFFFFFFFF min_value = 1 << min_value...
def lfsr_next_one_seed(seed_iter, min_value_shift)
High-quality seeding for LFSR generators. The LFSR generator components discard a certain number of their lower bits when generating each output. The significant bits of their state must not all be zero. We must ensure that when seeding the generator. In case generators are seeded from an incr...
2.7841
2.870684
0.969839
if x is None: # Use same random seed code copied from Python's random.Random try: x = long(_hexlify(_urandom(16)), 16) except NotImplementedError: import time x = long(time.time() * 256) # use fractional seconds ...
def seed(self, x=None, *args)
For consistent cross-platform seeding, provide an integer seed.
7.356217
7.683359
0.957422
self._bpf = min(bpf, self.BPF) self._rng_n = int((self._bpf + self.RNG_RANGE_BITS - 1) / self.RNG_RANGE_BITS)
def setbpf(self, bpf)
Set number of bits per float output
5.473014
5.211062
1.050268
mod = try_import(cls.mod_name) if not mod: return None version = getattr(mod, '__version__', None) or getattr(mod, 'version', None) return BackendInfo(version or 'deprecated', '')
def get_info(cls)
Return information about backend and its availability. :return: A BackendInfo tuple if the import worked, none otherwise.
7.721138
6.229193
1.239509
empty_label = getattr(field.field, "empty_label", False) needs_empty_value = False choices = [] # Data is the choices if hasattr(field.field, "_choices"): choices = field.field._choices # Data is a queryset elif hasattr(field.field, "_queryset"): queryset = field.field._queryset field_name = getattr(f...
def get_choices(field)
Find choices of a field, whether it has choices or has a queryset. Args: field (BoundField): Django form boundfield Returns: list: List of choices
2.851762
2.894722
0.985159
try: response.raise_for_status() except requests.exceptions.HTTPError as e: if e.response.status_code == 404: raise errors.NotFound(e, response, explanation=explanation) raise errors.APIError(e, response, explanation=explanation)
def _raise_for_status(self, response, explanation=None)
Raises stored :class:`APIError`, if one occurred.
2.169395
2.054881
1.055727
cl = [] cl.append(DOMTokenList(cls, cls.class_)) if cls.inherit_class: for base_cls in cls.__bases__: if issubclass(base_cls, WdomElement): cl.append(base_cls.get_class_list()) # Reverse order so that parent's class comes to front ...
def get_class_list(cls) -> DOMTokenList
Get class-level class list, including all super class's.
5.800818
5.636002
1.029243
_remove_cl = [] for class_ in classes: if class_ not in self.classList: if class_ in self.get_class_list(): logger.warning( 'tried to remove class-level class: ' '{}'.format(class_) ...
def removeClass(self, *classes: str) -> None
[Not Standard] Remove classes from this node.
3.351465
3.103796
1.079796
if self.connected: self._append_child_web(child) return self._append_child(child)
def appendChild(self, child: 'WdomElement') -> Node
Append child node at the last of child nodes. If this instance is connected to the node on browser, the child node is also added to it.
10.043872
6.417419
1.565095
if self.connected: self._insert_before_web(child, ref_node) return self._insert_before(child, ref_node)
def insertBefore(self, child: Node, ref_node: Node) -> Node
Insert new child node before the reference child node. If the reference node is not a child of this node, raise ValueError. If this instance is connected to the node on browser, the child node is also added to it.
6.521106
3.749808
1.73905
if self.connected: self._remove_child_web(child) return self._remove_child(child)
def removeChild(self, child: Node) -> Node
Remove the child node from this node. If the node is not a child of this node, raise ValueError.
10.411803
8.00895
1.300021
if self.connected: self._replace_child_web(new_child, old_child) return self._replace_child(new_child, old_child)
def replaceChild(self, new_child: 'WdomElement', old_child: 'WdomElement' ) -> Node
Replace child nodes.
4.547029
3.934326
1.155732
self._set_text_content_web(text)
def textContent(self, text: str) -> None: # type: ignore self._set_text_content(text) if self.connected
Set textContent both on this node and related browser node.
27.803701
8.666142
3.208314
self._set_inner_html_web(df.html) self._empty() self._append_child(df)
def innerHTML(self, html: str) -> None: # type: ignore df = self._parse_html(html) if self.connected
Set innerHTML both on this node and related browser node.
18.742819
9.813419
1.909917
if self.connected: self.js_exec('click') else: # Web上に表示されてれば勝手にブラウザ側からクリックイベント発生する # のでローカルのクリックイベント不要 msg = {'proto': '', 'type': 'click', 'currentTarget': {'id': self.wdom_id}, 'target': {'id': self.wdom_id...
def click(self) -> None
Send click event.
8.961859
8.069682
1.110559
elm = Element._elements_with_id.get(id) return elm
def getElementById(id: str) -> Optional[Node]
Get element with ``id``.
11.193637
10.8836
1.028487
if not id: return None elif id == 'document': return get_document() elif id == 'window': return get_document().defaultView elm = WdomElement._elements_with_wdom_id.get(id) return elm
def getElementByWdomId(id: str) -> Optional[WebEventTarget]
Get element with ``wdom_id``.
4.192529
3.68459
1.137855
if os.path.isdir(path): shutil.rmtree(path)
def _cleanup(path: str) -> None
Cleanup temporary directory.
4.429765
2.787847
1.588955
from wdom.web_node import WdomElement from wdom.tag import Tag from wdom.window import customElements if attr is None: attr = {} if name: base_class = customElements.get((name, tag)) else: base_class = customElements.get((tag, None)) if base_class is None: ...
def create_element(tag: str, name: str = None, base: type = None, attr: dict = None) -> Node
Create element with a tag of ``name``. :arg str name: html tag. :arg type base: Base class of the created element (defatlt: ``WdomElement``) :arg dict attr: Attributes (key-value pairs dict) of the new element.
3.244781
3.118001
1.040661
document = document_factory( autoreload=autoreload, reload_wait=reload_wait, **kwargs ) if log_level is None: log_level = config.logging if message_wait is None: message_wait = config.message_wait log_script = [] log_script.append('var WDOM_MESSAGE_...
def get_new_document( # noqa: C901 include_wdom_js: bool = True, include_skeleton: bool = False, include_normalizecss: bool = False, autoreload: bool = None, reload_wait: float = None, log_level: Union[int, str] = None, log_prefix: str = None, log_console...
Create new :class:`Document` object with options. :arg bool include_wdom_js: Include wdom.js file. Usually should be True. :arg bool include_skeleton: Include skelton.css. :arg bool include_normalizecss: Include normalize.css. :arg bool autoreload: Enable autoreload flag. This flag overwrites `...
2.007482
2.160131
0.929334
charset_node = self._find_charset_node() or Meta(parent=self.head) charset_node.setAttribute('charset', charset)
def characterSet(self, charset: str) -> None
Set character set of this document.
13.174437
10.710376
1.230063
title_element = _find_tag(self.head, 'title') if title_element: return title_element.textContent return ''
def title(self) -> str
Get/Set title string of this document.
6.993166
5.338803
1.309875
return getElementsBy(self, cond)
def getElementsBy(self, cond: Callable[[Element], bool]) -> NodeList
Get elements in this document which matches condition.
13.014258
6.115339
2.128134
elm = getElementById(id) if elm and elm.ownerDocument is self: return elm return None
def getElementById(self, id: str) -> Optional[Node]
Get element by ``id``. If this document does not have the element with the id, return None.
6.155083
5.376619
1.144787
return create_element(tag, base=self._default_class)
def createElement(self, tag: str) -> Node
Create new element whose tag name is ``tag``.
23.513556
16.986561
1.384245
elm = getElementByWdomId(id) if elm and elm.ownerDocument is self: return elm return None
def getElementByWdomId(self, id: Union[str]) -> Optional[WebEventTarget]
Get an element node with ``wdom_id``. If this document does not have the element with the id, return None.
5.477482
4.894475
1.119115
self.body.appendChild(Script(src=src))
def add_jsfile(self, src: str) -> None
Add JS file to load at this document's bottom of the body.
26.61445
7.701905
3.455567
self.head.appendChild(Script(src=src))
def add_jsfile_head(self, src: str) -> None
Add JS file to load at this document's header.
20.368809
8.568163
2.377267
self.head.appendChild(Link(rel='stylesheet', href=src))
def add_cssfile(self, src: str) -> None
Add CSS file to load at this document's header.
12.97889
6.510482
1.993537
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 getatt...
def register_theme(self, theme: ModuleType) -> None
Set theme for this docuemnt. This method sets theme's js/css files and headers on this document. :arg ModuleType theme: a module which has ``js_files``, ``css_files``, ``headers``, and ``extended_classes``. see ``wdom.themes`` directory actual theme module structures.
3.364354
2.503804
1.343697
self._set_autoreload() return ''.join(child.html for child in self.childNodes)
def build(self) -> str
Return HTML representation of this document.
23.852472
13.531471
1.76274
res = self._get(self._url("/chain/blocks/{0}", block)) return self._result(res, True)
def block_get(self, block)
GET /chain/blocks/{Block} Use the Block API to retrieve the contents of various blocks from the blockchain. The returned Block message structure is defined inside fabric.proto. ```golang message Block { uint32 version = 1; google.protobuf.Timestamp Times...
8.520316
8.11375
1.050108
if not _msg_queue: return msg = json.dumps(_msg_queue) _msg_queue.clear() for conn in module.connections: conn.write_message(msg)
def send_message() -> None
Send message via WS to all client connections.
5.308725
3.804499
1.395381
app = get_app() app.add_static_path(prefix, path) if not no_watch: watch_dir(path)
def add_static_path(prefix: str, path: str, no_watch: bool = False) -> None
Add directory to serve static files. First argument ``prefix`` is a URL prefix for the ``path``. ``path`` must be a directory. If ``no_watch`` is True, any change of the files in the path do not trigger restart if ``--autoreload`` is enabled.
3.498128
4.272162
0.818819
# Add application's static files directory from wdom.document import get_document add_static_path('_static', STATIC_DIR) doc = get_document() if os.path.exists(doc.tempdir): add_static_path('tmp', doc.tempdir, no_watch=True) if doc._autoreload or config.autoreload or config.debug: ...
def start_server(address: str = None, port: int = None, check_time: int = 500, **kwargs: Any) -> module.HTTPServer
Start web server on ``address:port``. Use wrapper function :func:`start` instead. :arg str address: address of the server [default: localhost]. :arg int port: tcp port of the server [default: 8888]. :arg int check_time: millisecondes to wait until reload browser when autoreload is enabled [def...
4.474115
4.488214
0.996859
start_server(**kwargs) try: asyncio.get_event_loop().run_forever() except KeyboardInterrupt: stop_server()
def start(**kwargs: Any) -> None
Start web server. Run until ``Ctrl-c`` pressed, or if auto-shutdown is enabled, until when all browser windows are closed. This function accepts keyword areguments same as :func:`start_server` and all arguments passed to it.
3.40883
4.753175
0.717169
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))
def define(self, *args: Any, **kwargs: Any) -> None
Add new custom element.
3.341389
2.991612
1.116919
message = 'JS: ' + str(message) if level == 'error': logger.error(message) elif level == 'warn': logger.warning(message) elif level == 'info': logger.info(message) elif level == 'debug': logger.debug(message)
def log_handler(level: str, message: str) -> None
Handle logs from client (browser).
2.321423
1.994859
1.163703
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...
def event_handler(msg: EventMsgDict) -> Event
Handle events emitted on browser.
6.500848
6.307661
1.030627
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))
def response_handler(msg: Dict[str, str]) -> None
Handle response sent by browser.
4.551621
3.864901
1.177681
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 _typ...
def on_websocket_message(message: str) -> None
Handle messages from browser.
2.797056
2.527032
1.106854
parser = parser or FragmentParser() parser.feed(html) return parser.root
def parse_html(html: str, parser: FragmentParser = None) -> Node
Parse HTML fragment and return DocumentFragment object. DocumentFragment object has parsed Node objects as its child nodes.
3.946906
4.425518
0.891852
elements = [] for child in start_node.children: if cond(child): elements.append(child) elements.extend(child.getElementsBy(cond)) return NodeList(elements)
def getElementsBy(start_node: ParentNode, cond: Callable[['Element'], bool]) -> NodeList
Return list of child elements of start_node which matches ``cond``. ``cond`` must be a function which gets a single argument ``Element``, and returns boolean. If the node matches requested condition, ``cond`` should return True. This searches all child elements recursively. :arg ParentNode start_n...
2.801731
3.828883
0.731736
_tag = tag.upper() return getElementsBy(start_node, lambda node: node.tagName == _tag)
def getElementsByTagName(start_node: ParentNode, tag: str) -> NodeList
Get child nodes which tag name is ``tag``.
6.425034
4.788561
1.341746
classes = set(class_name.split(' ')) return getElementsBy( start_node, lambda node: classes.issubset(set(node.classList)) )
def getElementsByClassName(start_node: ParentNode, class_name: str ) -> NodeList
Get child nodes which has ``class_name`` class attribute.
4.612886
4.21767
1.093705
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, WdomEleme...
def add(self, *tokens: str) -> None
Add new tokens to list.
4.461751
3.849494
1.159049
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) an...
def remove(self, *tokens: str) -> None
Remove tokens from list.
4.607301
4.179285
1.102414
self._validate_token(token) if token in self: self.remove(token) else: self.add(token)
def toggle(self, token: str) -> None
Add or remove token to/from list. If token is in this list, the token will be removed. Otherwise add it to list.
3.678476
2.829917
1.299853
self._validate_token(token) return token in self
def contains(self, token: str) -> bool
Return if the token is in the list or not.
8.598001
4.669533
1.841298
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)
def html(self) -> str
Return string representation of this. Used in start tag of HTML representation of the Element node.
4.898881
4.209734
1.163703
if isinstance(self.value, bool): val = 'true' if self.value else 'false' else: val = str(self.value) return 'draggable="{}"'.format(val)
def html(self) -> str
Return html representation.
3.656961
3.024639
1.209057
return self._dict.get(name, None)
def getNamedItem(self, name: str) -> Optional[Attr]
Get ``Attr`` object which has ``name``. If does not have ``name`` attr, return None.
7.582724
9.983556
0.759521
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.v...
def setNamedItem(self, item: Attr) -> None
Set ``Attr`` object in this collection.
4.020573
3.886006
1.034629
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, No...
def removeNamedItem(self, item: Attr) -> Optional[Attr]
Set ``Attr`` object and return it (if exists).
3.599472
3.652309
0.985533
if 0 <= index < len(self): return self._dict[tuple(self._dict.keys())[index]] return None
def item(self, index: int) -> Optional[Attr]
Return ``index``-th attr node.
4.237715
3.887805
1.090002
return ' '.join(attr.html for attr in self._dict.values())
def toString(self) -> str
Return string representation of collections.
22.948097
15.3224
1.497683
tag = '<' + self.tag attrs = self._get_attrs_by_string() if attrs: tag = ' '.join((tag, attrs)) return tag + '>'
def start_tag(self) -> str
Return HTML start tag.
5.149373
3.829193
1.344767
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) ...
def insertAdjacentHTML(self, position: str, html: str) -> None
Parse ``html`` to DOM and insert to ``position``. ``position`` is a case-insensive string, and must be one of "beforeBegin", "afterBegin", "beforeEnd", or "afterEnd".
2.280622
2.240858
1.017745
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
def getAttribute(self, attr: str) -> _AttrValueType
Get attribute of this node as string format. If this node does not have ``attr``, return None.
3.743723
3.40292
1.10015
return self.attributes.getNamedItem(attr)
def getAttributeNode(self, attr: str) -> Optional[Attr]
Get attribute of this node as Attr format. If this node does not have ``attr``, return None.
11.322124
15.834148
0.715045
if attr == 'class': return bool(self.classList) return attr in self.attributes
def hasAttribute(self, attr: str) -> bool
Return True if this node has ``attr``.
7.847698
6.000025
1.307944
self._set_attribute(attr, value)
def setAttribute(self, attr: str, value: _AttrValueType) -> None
Set ``attr`` and ``value`` in this node.
12.074322
6.598387
1.82989