code
stringlengths 52
7.75k
| docs
stringlengths 1
5.85k
|
---|---|
def unsuppress(self, email):
params = {"email": email}
response = self._put(self.uri_for("unsuppress"),
body=" ", params=params) | Unsuppresses an email address by removing it from the the client's
suppression list |
def set_payg_billing(self, currency, can_purchase_credits, client_pays, markup_percentage,
markup_on_delivery=0, markup_per_recipient=0, markup_on_design_spam_test=0):
body = {
"Currency": currency,
"CanPurchaseCredits": can_purchase_credits,
"ClientPays": client_pays,
"MarkupPercentage": markup_percentage,
"MarkupOnDelivery": markup_on_delivery,
"MarkupPerRecipient": markup_per_recipient,
"MarkupOnDesignSpamTest": markup_on_design_spam_test}
response = self._put(self.uri_for('setpaygbilling'), json.dumps(body)) | Sets the PAYG billing settings for this client. |
def set_monthly_billing(self, currency, client_pays, markup_percentage, monthly_scheme=None):
body = {
"Currency": currency,
"ClientPays": client_pays,
"MarkupPercentage": markup_percentage}
if monthly_scheme is not None:
body["MonthlyScheme"] = monthly_scheme
response = self._put(self.uri_for(
'setmonthlybilling'), json.dumps(body)) | Sets the monthly billing settings for this client. |
def transfer_credits(self, credits, can_use_my_credits_when_they_run_out):
body = {
"Credits": credits,
"CanUseMyCreditsWhenTheyRunOut": can_use_my_credits_when_they_run_out}
response = self._post(self.uri_for('credits'), json.dumps(body))
return json_to_py(response) | Transfer credits to or from this client.
:param credits: An Integer representing the number of credits to transfer.
This value may be either positive if you want to allocate credits from
your account to the client, or negative if you want to deduct credits
from the client back into your account.
:param can_use_my_credits_when_they_run_out: A Boolean value representing
which, if set to true, will allow the client to continue sending using
your credits or payment details once they run out of credits, and if
set to false, will prevent the client from using your credits to
continue sending until you allocate more credits to them.
:returns: An object of the following form representing the result:
{
AccountCredits # Integer representing credits in your account now
ClientCredits # Integer representing credits in this client's
account now
} |
def set_primary_contact(self, email):
params = {"email": email}
response = self._put(self.uri_for('primarycontact'), params=params)
return json_to_py(response) | assigns the primary contact for this client |
def smart_email_list(self, status="all", client_id=None):
if client_id is None:
response = self._get(
"/transactional/smartEmail?status=%s" % status)
else:
response = self._get(
"/transactional/smartEmail?status=%s&clientID=%s" % (status, client_id))
return json_to_py(response) | Gets the smart email list. |
def smart_email_send(self, smart_email_id, to, consent_to_track, cc=None, bcc=None, attachments=None, data=None, add_recipients_to_list=None):
validate_consent_to_track(consent_to_track)
body = {
"To": to,
"CC": cc,
"BCC": bcc,
"Attachments": attachments,
"Data": data,
"AddRecipientsToList": add_recipients_to_list,
"ConsentToTrack": consent_to_track,
}
response = self._post("/transactional/smartEmail/%s/send" %
smart_email_id, json.dumps(body))
return json_to_py(response) | Sends the smart email. |
def classic_email_send(self, subject, from_address, to, consent_to_track, client_id=None, cc=None, bcc=None, html=None, text=None, attachments=None, track_opens=True, track_clicks=True, inline_css=True, group=None, add_recipients_to_list=None):
validate_consent_to_track(consent_to_track)
body = {
"Subject": subject,
"From": from_address,
"To": to,
"CC": cc,
"BCC": bcc,
"HTML": html,
"Text": text,
"Attachments": attachments,
"TrackOpens": track_opens,
"TrackClicks": track_clicks,
"InlineCSS": inline_css,
"Group": group,
"AddRecipientsToList": add_recipients_to_list,
"ConsentToTrack": consent_to_track,
}
if client_id is None:
response = self._post(
"/transactional/classicEmail/send", json.dumps(body))
else:
response = self._post(
"/transactional/classicEmail/send?clientID=%s" % client_id, json.dumps(body))
return json_to_py(response) | Sends a classic email. |
def classic_email_groups(self, client_id=None):
if client_id is None:
response = self._get("/transactional/classicEmail/groups")
else:
response = self._get(
"/transactional/classicEmail/groups?clientID=%s" % client_id)
return json_to_py(response) | Gets the list of classic email groups. |
def message_details(self, message_id, statistics=False):
response = self._get(
"/transactional/messages/%s?statistics=%s" % (message_id, statistics))
return json_to_py(response) | Gets the details of this message. |
def create(self, list_id, title, rulegroups):
body = {
"Title": title,
"RuleGroups": rulegroups}
response = self._post("/segments/%s.json" % list_id, json.dumps(body))
self.segment_id = json_to_py(response)
return self.segment_id | Creates a new segment. |
def update(self, title, rulegroups):
body = {
"Title": title,
"RuleGroups": rulegroups}
response = self._put("/segments/%s.json" %
self.segment_id, json.dumps(body)) | Updates this segment. |
def add_rulegroup(self, rulegroup):
body = rulegroup
response = self._post("/segments/%s/rules.json" %
self.segment_id, json.dumps(body)) | Adds a rulegroup to this segment. |
def subscribers(self, date="", page=1, page_size=1000, order_field="email", order_direction="asc", include_tracking_information=False):
params = {
"date": date,
"page": page,
"pagesize": page_size,
"orderfield": order_field,
"orderdirection": order_direction,
"includetrackinginformation": include_tracking_information
}
response = self._get(self.uri_for("active"), params=params)
return json_to_py(response) | Gets the active subscribers in this segment. |
def create(self, client_id, name, html_url, zip_url):
body = {
"Name": name,
"HtmlPageURL": html_url,
"ZipFileURL": zip_url}
response = self._post("/templates/%s.json" %
client_id, json.dumps(body))
self.template_id = json_to_py(response)
return self.template_id | Creates a new email template. |
def update(self, name, html_url, zip_url):
body = {
"Name": name,
"HtmlPageURL": html_url,
"ZipFileURL": zip_url}
response = self._put("/templates/%s.json" %
self.template_id, json.dumps(body)) | Updates this email template. |
def add(self, email_address, name):
body = {
"EmailAddress": email_address,
"Name": name}
response = self._post("/admins.json", json.dumps(body))
return json_to_py(response) | Adds an administrator to an account. |
def update(self, new_email_address, name):
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 continue to be used
# reliably
self.email_address = new_email_address | Updates the details for an administrator. |
def delete(self):
params = {"email": self.email_address}
response = self._delete("/admins.json", params=params) | Deletes the administrator from the account. |
def match_hostname(cert, hostname):
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:
# The subject is only checked when subjectAltName is empty
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_to_pat(value).match(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") | 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*.
CertificateError is raised on failure. On success, the function
returns nothing. |
def create(self, client_id, title, unsubscribe_page, confirmed_opt_in,
confirmation_success_page, unsubscribe_setting="AllClientLists"):
body = {
"Title": title,
"UnsubscribePage": unsubscribe_page,
"ConfirmedOptIn": confirmed_opt_in,
"ConfirmationSuccessPage": confirmation_success_page,
"UnsubscribeSetting": unsubscribe_setting}
response = self._post("/lists/%s.json" % client_id, json.dumps(body))
self.list_id = json_to_py(response)
return self.list_id | Creates a new list for a client. |
def create_custom_field(self, field_name, data_type, options=[],
visible_in_preference_center=True):
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) | Creates a new custom field for this list. |
def update_custom_field(self, custom_field_key, field_name,
visible_in_preference_center):
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.dumps(body))
return json_to_py(response) | Updates a custom field belonging to this list. |
def delete_custom_field(self, custom_field_key):
custom_field_key = quote(custom_field_key, '')
response = self._delete("/lists/%s/customfields/%s.json" %
(self.list_id, custom_field_key)) | Deletes a custom field associated with this list. |
def update_custom_field_options(self, custom_field_key, new_options,
keep_existing_options):
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)) | Updates the options of a multi-optioned custom field on this list. |
def active(self, date="", page=1, page_size=1000, order_field="email", order_direction="asc", include_tracking_preference=False):
params = {
"date": date,
"page": page,
"pagesize": page_size,
"orderfield": order_field,
"orderdirection": order_direction,
"includetrackingpreference": include_tracking_preference,
}
response = self._get(self.uri_for("active"), params=params)
return json_to_py(response) | Gets the active subscribers for this list. |
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):
body = {
"Title": title,
"UnsubscribePage": unsubscribe_page,
"ConfirmedOptIn": confirmed_opt_in,
"ConfirmationSuccessPage": confirmation_success_page,
"UnsubscribeSetting": unsubscribe_setting,
"AddUnsubscribesToSuppList": add_unsubscribes_to_supp_list,
"ScrubActiveWithSuppList": scrub_active_with_supp_list}
response = self._put("/lists/%s.json" % self.list_id, json.dumps(body)) | Updates this list. |
def create_webhook(self, events, url, payload_format):
body = {
"Events": events,
"Url": url,
"PayloadFormat": payload_format}
response = self._post(self.uri_for("webhooks"), json.dumps(body))
return json_to_py(response) | 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". |
def get(self, list_id=None, email_address=None, include_tracking_preference=False):
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(response) | Gets a subscriber by list ID and email address. |
def add(self, list_id, email_address, name, custom_fields, resubscribe, consent_to_track, restart_subscription_based_autoresponders=False):
validate_consent_to_track(consent_to_track)
body = {
"EmailAddress": email_address,
"Name": name,
"CustomFields": custom_fields,
"Resubscribe": resubscribe,
"ConsentToTrack": consent_to_track,
"RestartSubscriptionBasedAutoresponders": restart_subscription_based_autoresponders}
response = self._post("/subscribers/%s.json" %
list_id, json.dumps(body))
return json_to_py(response) | Adds a subscriber to a subscriber list. |
def update(self, new_email_address, name, custom_fields, resubscribe, consent_to_track, restart_subscription_based_autoresponders=False):
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_to_track,
"RestartSubscriptionBasedAutoresponders": restart_subscription_based_autoresponders}
response = self._put("/subscribers/%s.json" % self.list_id,
body=json.dumps(body), params=params)
# Update self.email_address, so this object can continue to be used
# reliably
self.email_address = new_email_address | Updates any aspect of a subscriber, including email address, name, and
custom field data if supplied. |
def import_subscribers(self, list_id, subscribers, resubscribe, queue_subscription_based_autoresponders=False, restart_subscription_based_autoresponders=False):
body = {
"Subscribers": subscribers,
"Resubscribe": resubscribe,
"QueueSubscriptionBasedAutoresponders": queue_subscription_based_autoresponders,
"RestartSubscriptionBasedAutoresponders": restart_subscription_based_autoresponders}
try:
response = self._post("/subscribers/%s/import.json" %
list_id, json.dumps(body))
except BadRequest as br:
# Subscriber import will throw BadRequest if some subscribers are not imported
# successfully. If this occurs, we want to return the ResultData property of
# the BadRequest exception (which is of the same "form" as the response we'd
# receive upon a completely successful import)
if hasattr(br.data, 'ResultData'):
return br.data.ResultData
else:
raise br
return json_to_py(response) | Imports subscribers into a subscriber list. |
def unsubscribe(self):
body = {
"EmailAddress": self.email_address}
response = self._post("/subscribers/%s/unsubscribe.json" %
self.list_id, json.dumps(body)) | Unsubscribes this subscriber from the associated list. |
def history(self):
params = {"email": self.email_address}
response = self._get("/subscribers/%s/history.json" %
self.list_id, params=params)
return json_to_py(response) | Gets the historical record of this subscriber's trackable actions. |
def mask(n, start, end):
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(columns) | 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; others are set. |
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_field(field, **kwargs) for field in form
])) | 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 |
def render_layout_form(form, layout=None, **kwargs):
def make_component(type_, *args):
"""Loop through tuples to make field wrappers for fields.
"""
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 += render_field(form.__getitem__(c), **kwargs)
return result
else:
if len(args) < 2:
return ""
result = "".join([make_component(*c) for c in args])
if type_:
return "<div class=\"%s\">%s</div>" % (type_.lower(), result)
else:
return result
return mark_safe("".join([make_component(*component) for component in layout])) | 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 Semantic UI wrappers |
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. |
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. |
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. |
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. |
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", ""))),
"icon": format_html(ICON_TEMPLATE, self.attrs.get("_icon")),
} | Wrap current field with icon wrapper.
This setter must be the last setter called. |
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.disabled:
self.values["class"].append("disabled")
# Required class
if self.field.field.required and not self.attrs.get("_no_required"):
self.values["class"].append("required")
elif self.attrs.get("_required") and not self.field.field.required:
self.values["class"].append("required") | Set field properties and custom classes. |
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.values["class"] = pad(" ".join(self.values["class"])).lstrip()
result = mark_safe(FIELD_WRAPPER % self.values)
self.widget.attrs = self.attrs # Re-assign variables
return result | Render field as HTML. |
def ready(self):
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 | Create test friends for displaying. |
def render_booleanfield(field, attrs):
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": format_html(
wrappers.LABEL_TEMPLATE, field.html_name, mark_safe(field.label)
)
} | Render BooleanField with label next to instead of above. |
def render_choicefield(field, attrs, choices=None):
# 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.widget.attrs["value"] = field.value() or attrs.get("value", "")
return wrappers.DROPDOWN_WRAPPER % {
"name": field.html_name,
"attrs": pad(flatatt(field.field.widget.attrs)),
"placeholder": attrs.get("placeholder") or get_placeholder_text(),
"style": pad(attrs.get("_style", "")),
"icon": format_html(wrappers.ICON_TEMPLATE, attrs.get("_dropdown_icon") or "dropdown"),
"choices": choices
} | Render ChoiceField as 'div' dropdown rather than select for more
customization. |
def render_iconchoicefield(field, attrs):
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 += format_html(
wrappers.ICON_CHOICE_TEMPLATE,
choice[0], # Key
mark_safe(wrappers.ICON_TEMPLATE.format(value[-1])), # Icon
value[0] # Value
)
# Render a dropdown field
return render_choicefield(field, attrs, choices) | Render a ChoiceField with icon support; where the value is split by a pipe
(|): first element being the value, last element is the icon. |
def render_countryfield(field, attrs):
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)
) | Render a custom ChoiceField specific for CountryFields. |
def render_multiplechoicefield(field, attrs, choices=None):
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_html(wrappers.ICON_TEMPLATE, attrs.get("_dropdown_icon") or "dropdown"),
} | MultipleChoiceField uses its own field, but also uses a queryset. |
def render_datefield(field, attrs, style="date"):
return wrappers.CALENDAR_WRAPPER % {
"field": field,
"style": pad(style),
"align": pad(attrs.get("_align", "")),
"icon": format_html(wrappers.ICON_TEMPLATE, attrs.get("_icon")),
} | DateField that uses wrappers.CALENDAR_WRAPPER. |
def render_filefield(field, attrs):
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.ICON_TEMPLATE, attrs.get("_icon", "file outline"))
} | Render a typical File Field. |
def _traverse_iter(o, tree_types=(list, tuple)):
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 subvalue & SIMPLERANDOM_MASK
subvalue >>= SIMPLERANDOM_BITS
# If value is negative, then it effectively has infinitely extending
# '1' bits (modelled as a 2's complement representation). So when
# right-shifting it, it will eventually get to -1, and any further
# right-shifting will not change it.
if subvalue == 0 or subvalue == -1:
break
else:
yield o | 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. |
def _repeat_iter(input_iter):
last_value = None
for value in input_iter:
last_value = value
yield value
if last_value is not None:
while True:
yield last_value | 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, default-value)
It is better to repeat the last seed value, rather than just using default
values. Given two generators seeded with an insufficient number of seeds,
repeating the last seed value means their states are more different from
each other, with less correlation between their generated outputs. |
def _geom_series_uint32(r, n):
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 % 2) == 0:
other_factors //= 2
common_factor *= 2
other_factors_inverse = pow(other_factors, m - 1, m)
numerator = pow(r, n, common_factor * m) - 1
return (numerator // common_factor * other_factors_inverse) % m | 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) |
def lfsr_next_one_seed(seed_iter, min_value_shift):
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_shift
if working_seed < min_value:
working_seed = (seed << 24) & 0xFFFFFFFF
if working_seed < min_value:
working_seed ^= 0xFFFFFFFF
return working_seed | 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 incrementing input (such as a system
timer), and between increments only the lower bits may change, we would
also like the lower bits of the input to change the initial state, and not
just be discarded. So we do basic manipulation of the seed input value to
ensure that all bits of the seed input affect the initial state. |
def seed(self, x=None, *args):
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
elif not isinstance(x, _Integral):
# Use the hash of the input seed object. Note this does not give
# consistent results cross-platform--between Python versions or
# between 32-bit and 64-bit systems.
x = hash(x)
self.rng_iterator.seed(x, *args, mix_extras=True) | For consistent cross-platform seeding, provide an integer seed. |
def setbpf(self, bpf):
self._bpf = min(bpf, self.BPF)
self._rng_n = int((self._bpf + self.RNG_RANGE_BITS - 1) / self.RNG_RANGE_BITS) | Set number of bits per float output |
def get_info(cls):
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', '') | Return information about backend and its availability.
:return: A BackendInfo tuple if the import worked, none otherwise. |
def get_choices(field):
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(field.field, "to_field_name") or "pk"
choices += ((getattr(obj, field_name), str(obj)) for obj in queryset)
# Determine if an empty value is needed
if choices and (choices[0][1] == BLANK_CHOICE_DASH[0][1] or choices[0][0]):
needs_empty_value = True
# Delete empty option
if not choices[0][0]:
del choices[0]
# Remove dashed empty choice
if empty_label == BLANK_CHOICE_DASH[0][1]:
empty_label = None
# Add custom empty value
if empty_label or not field.field.required:
if needs_empty_value:
choices.insert(0, ("", empty_label or BLANK_CHOICE_DASH[0][1]))
return choices | Find choices of a field, whether it has choices or has a queryset.
Args:
field (BoundField): Django form boundfield
Returns:
list: List of choices |
def _raise_for_status(self, response, explanation=None):
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) | Raises stored :class:`APIError`, if one occurred. |
def get_class_list(cls) -> DOMTokenList:
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 <- why?
cl.reverse()
return DOMTokenList(cls, *cl) | Get class-level class list, including all super class's. |
def removeClass(self, *classes: str) -> None:
_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_)
)
else:
logger.warning(
'tried to remove non-existing class: {}'.format(class_)
)
else:
_remove_cl.append(class_)
self.classList.remove(*_remove_cl) | [Not Standard] Remove classes from this node. |
def appendChild(self, child: 'WdomElement') -> Node:
if self.connected:
self._append_child_web(child)
return self._append_child(child) | 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. |
def insertBefore(self, child: Node, ref_node: Node) -> Node:
if self.connected:
self._insert_before_web(child, ref_node)
return self._insert_before(child, ref_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. |
def removeChild(self, child: Node) -> Node:
if self.connected:
self._remove_child_web(child)
return self._remove_child(child) | Remove the child node from this node.
If the node is not a child of this node, raise ValueError. |
def replaceChild(self, new_child: 'WdomElement', old_child: 'WdomElement'
) -> Node:
if self.connected:
self._replace_child_web(new_child, old_child)
return self._replace_child(new_child, old_child) | Replace child nodes. |
def textContent(self, text: str) -> None: # type: ignore
self._set_text_content(text)
if self.connected:
self._set_text_content_web(text) | Set textContent both on this node and related browser node. |
def innerHTML(self, html: str) -> None: # type: ignore
df = self._parse_html(html)
if self.connected:
self._set_inner_html_web(df.html)
self._empty()
self._append_child(df) | Set innerHTML both on this node and related browser node. |
def click(self) -> None:
if self.connected:
self.js_exec('click')
else:
# Web上に表示されてれば勝手にブラウザ側からクリックイベント発生する
# のでローカルのクリックイベント不要
msg = {'proto': '', 'type': 'click',
'currentTarget': {'id': self.wdom_id},
'target': {'id': self.wdom_id}}
e = create_event(msg)
self._dispatch_event(e) | Send click event. |
def getElementById(id: str) -> Optional[Node]:
elm = Element._elements_with_id.get(id)
return elm | Get element with ``id``. |
def getElementByWdomId(id: str) -> Optional[WebEventTarget]:
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 | Get element with ``wdom_id``. |
def _cleanup(path: str) -> None:
if os.path.isdir(path):
shutil.rmtree(path) | Cleanup temporary directory. |
def create_element(tag: str, name: str = None, base: type = None,
attr: dict = None) -> Node:
from wdom.web_node import WdomElement
from wdom.tag import Tag
from wdom.window import customElements
if attr is None:
attr = {}
if name:
base_class = customElements.get((name, tag))
else:
base_class = customElements.get((tag, None))
if base_class is None:
attr['_registered'] = False
base_class = base or WdomElement
if issubclass(base_class, Tag):
return base_class(**attr)
return base_class(tag, **attr) | 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. |
def characterSet(self, charset: str) -> None:
charset_node = self._find_charset_node() or Meta(parent=self.head)
charset_node.setAttribute('charset', charset) | Set character set of this document. |
def title(self) -> str:
title_element = _find_tag(self.head, 'title')
if title_element:
return title_element.textContent
return '' | Get/Set title string of this document. |
def getElementsBy(self, cond: Callable[[Element], bool]) -> NodeList:
return getElementsBy(self, cond) | Get elements in this document which matches condition. |
def getElementById(self, id: str) -> Optional[Node]:
elm = getElementById(id)
if elm and elm.ownerDocument is self:
return elm
return None | Get element by ``id``.
If this document does not have the element with the id, return None. |
def createElement(self, tag: str) -> Node:
return create_element(tag, base=self._default_class) | Create new element whose tag name is ``tag``. |
def getElementByWdomId(self, id: Union[str]) -> Optional[WebEventTarget]:
elm = getElementByWdomId(id)
if elm and elm.ownerDocument is self:
return elm
return None | Get an element node with ``wdom_id``.
If this document does not have the element with the id, return None. |
def add_jsfile(self, src: str) -> None:
self.body.appendChild(Script(src=src)) | Add JS file to load at this document's bottom of the body. |
def add_jsfile_head(self, src: str) -> None:
self.head.appendChild(Script(src=src)) | Add JS file to load at this document's header. |
def add_cssfile(self, src: str) -> None:
self.head.appendChild(Link(rel='stylesheet', href=src)) | Add CSS file to load at this document's header. |
def register_theme(self, theme: ModuleType) -> None:
if not hasattr(theme, 'css_files'):
raise ValueError('theme module must include `css_files`.')
for css in getattr(theme, 'css_files', []):
self.add_cssfile(css)
for js in getattr(theme, 'js_files', []):
self.add_jsfile(js)
for header in getattr(theme, 'headers', []):
self.add_header(header)
for cls in getattr(theme, 'extended_classes', []):
self.defaultView.customElements.define(cls) | 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. |
def build(self) -> str:
self._set_autoreload()
return ''.join(child.html for child in self.childNodes) | Return HTML representation of this document. |
def block_get(self, block):
res = self._get(self._url("/chain/blocks/{0}", block))
return self._result(res, True) | 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 Timestamp = 2;
repeated Transaction transactions = 3;
bytes stateHash = 4;
bytes previousBlockHash = 5;
}
```
:param block: The id of the block to retrieve
:return: json body of the block info |
def send_message() -> None:
if not _msg_queue:
return
msg = json.dumps(_msg_queue)
_msg_queue.clear()
for conn in module.connections:
conn.write_message(msg) | Send message via WS to all client connections. |
def add_static_path(prefix: str, path: str, no_watch: bool = False) -> None:
app = get_app()
app.add_static_path(prefix, path)
if not no_watch:
watch_dir(path) | 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. |
def start_server(address: str = None, port: int = None,
check_time: int = 500, **kwargs: Any) -> module.HTTPServer:
# 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:
autoreload.start(check_time=check_time)
global _server
_server = module.start_server(address=address, port=port, **kwargs)
logger.info('Start server on {0}:{1:d}'.format(
server_config['address'], server_config['port']))
# start messaging loop
asyncio.ensure_future(_message_loop())
if config.open_browser:
open_browser('http://{}:{}/'.format(server_config['address'],
server_config['port']),
config.browser)
return _server | 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 [default: 500]. |
def start(**kwargs: Any) -> None:
start_server(**kwargs)
try:
asyncio.get_event_loop().run_forever()
except KeyboardInterrupt:
stop_server() | 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. |
def define(self, *args: Any, **kwargs: Any) -> None:
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)) | Add new custom element. |
def log_handler(level: str, message: str) -> None:
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) | Handle logs from client (browser). |
def event_handler(msg: EventMsgDict) -> Event:
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)
return e | Handle events emitted on browser. |
def response_handler(msg: Dict[str, str]) -> None:
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)) | Handle response sent by browser. |
def on_websocket_message(message: str) -> None:
msgs = json.loads(message)
for msg in msgs:
if not isinstance(msg, dict):
logger.error('Invalid WS message format: {}'.format(message))
continue
_type = msg.get('type')
if _type == 'log':
log_handler(msg['level'], msg['message'])
elif _type == 'event':
event_handler(msg['event'])
elif _type == 'response':
response_handler(msg)
else:
raise ValueError('Unkown message type: {}'.format(message)) | Handle messages from browser. |
def parse_html(html: str, parser: FragmentParser = None) -> Node:
parser = parser or FragmentParser()
parser.feed(html)
return parser.root | Parse HTML fragment and return DocumentFragment object.
DocumentFragment object has parsed Node objects as its child nodes. |
def getElementsBy(start_node: ParentNode,
cond: Callable[['Element'], bool]) -> NodeList:
elements = []
for child in start_node.children:
if cond(child):
elements.append(child)
elements.extend(child.getElementsBy(cond))
return NodeList(elements) | Return list of child elements of start_node which matches ``cond``.
``cond`` must be a function which gets a single argument ``Element``,
and returns boolean. If the node matches requested condition, ``cond``
should return True.
This searches all child elements recursively.
:arg ParentNode start_node:
:arg cond: Callable[[Element], bool]
:rtype: NodeList[Element] |
def getElementsByTagName(start_node: ParentNode, tag: str) -> NodeList:
_tag = tag.upper()
return getElementsBy(start_node, lambda node: node.tagName == _tag) | Get child nodes which tag name is ``tag``. |
def getElementsByClassName(start_node: ParentNode, class_name: str
) -> NodeList:
classes = set(class_name.split(' '))
return getElementsBy(
start_node,
lambda node: classes.issubset(set(node.classList))
) | Get child nodes which has ``class_name`` class attribute. |
def add(self, *tokens: str) -> None:
from wdom.web_node import WdomElement
_new_tokens = []
for token in tokens:
self._validate_token(token)
if token and token not in self:
self._list.append(token)
_new_tokens.append(token)
if isinstance(self._owner, WdomElement) and _new_tokens:
self._owner.js_exec('addClass', _new_tokens) | Add new tokens to list. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.