_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 31
13.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q277300
|
parse_node
|
test
|
def parse_node(s, strip_comments=False, **kw):
"""
Parse a Newick formatted string into a `Node` object.
:param s: Newick formatted string to parse.
:param strip_comments: Flag signaling whether to strip comments enclosed in square \
brackets.
:param kw: Keyword arguments are passed through to `Node.create`.
:return: `Node` instance.
"""
if strip_comments:
s = COMMENT.sub('', s)
s = s.strip()
parts = s.split(')')
if len(parts) == 1:
descendants, label = [], s
else:
if
|
python
|
{
"resource": ""
}
|
q277301
|
Node.create
|
test
|
def create(cls, name=None, length=None, descendants=None, **kw):
"""
Create a new `Node` object.
:param name: Node label.
:param length: Branch length from the new node to its parent.
:param descendants: list of descendants or `None`.
:param kw: Additonal keyword arguments are passed through to `Node.__init__`.
:return: `Node` instance.
|
python
|
{
"resource": ""
}
|
q277302
|
Node.newick
|
test
|
def newick(self):
"""The representation of the Node in Newick format."""
label = self.name or ''
if self._length:
label += ':' + self._length
|
python
|
{
"resource": ""
}
|
q277303
|
Node.ascii_art
|
test
|
def ascii_art(self, strict=False, show_internal=True):
"""
Return a unicode string representing a tree in ASCII art fashion.
:param strict: Use ASCII characters strictly (for the tree symbols).
:param show_internal: Show labels of internal nodes.
:return: unicode string
>>> node = loads('((A,B)C,((D,E)F,G,H)I)J;')[0]
>>> print(node.ascii_art(show_internal=False, strict=True))
/-A
/---|
| \-B
----| /-D
| /---|
| | \-E
\---|
|-G
\-H
"""
cmap = {
'\u2500': '-',
'\u2502': '|',
'\u250c': '/',
'\u2514': '\\',
'\u251c': '|',
'\u2524': '|',
'\u253c': '+',
}
|
python
|
{
"resource": ""
}
|
q277304
|
Node.get_node
|
test
|
def get_node(self, label):
"""
Gets the specified node by name.
:return: Node or None if name does not exist in tree
|
python
|
{
"resource": ""
}
|
q277305
|
Node.prune
|
test
|
def prune(self, leaves, inverse=False):
"""
Remove all those nodes in the specified list, or if inverse=True,
remove all those nodes not in the specified list. The specified nodes
must be leaves and distinct from the root node.
:param nodes: A list of Node objects
:param inverse: Specifies whether to remove nodes in the list or not\
in the list.
"""
self.visit(
lambda n: n.ancestor.descendants.remove(n),
|
python
|
{
"resource": ""
}
|
q277306
|
Node.resolve_polytomies
|
test
|
def resolve_polytomies(self):
"""
Insert additional nodes with length=0 into the subtree in such a way
that all non-leaf nodes have only 2 descendants, i.e. the tree becomes
a fully resolved binary tree.
"""
def _resolve_polytomies(n):
new = Node(length=self._length_formatter(self._length_parser('0')))
|
python
|
{
"resource": ""
}
|
q277307
|
Node.remove_internal_names
|
test
|
def remove_internal_names(self):
"""
Set the name of all non-leaf nodes in the subtree to None.
"""
|
python
|
{
"resource": ""
}
|
q277308
|
Node.remove_leaf_names
|
test
|
def remove_leaf_names(self):
"""
Set the name of all leaf nodes in the subtree to None.
"""
|
python
|
{
"resource": ""
}
|
q277309
|
auth_required
|
test
|
def auth_required(realm, auth_func):
'''Decorator that protect methods with HTTP authentication.'''
def auth_decorator(func):
def inner(self, *args, **kw):
|
python
|
{
"resource": ""
}
|
q277310
|
dispose
|
test
|
def dispose(json_str):
"""Clear all comments in json_str.
Clear JS-style comments like // and /**/ in json_str.
Accept a str or unicode as input.
Args:
json_str: A json string of str or unicode to clean up comment
Returns:
str: The str without comments (or unicode if you pass in unicode)
"""
result_str = list(json_str)
escaped = False
normal = True
sl_comment = False
ml_comment = False
quoted = False
a_step_from_comment = False
a_step_from_comment_away = False
former_index = None
for index, char in enumerate(json_str):
if escaped: # We have just met a '\'
escaped = False
continue
if a_step_from_comment: # We have just met a '/'
if char != '/' and char != '*':
a_step_from_comment = False
normal = True
continue
if a_step_from_comment_away: # We have just met a '*'
if char != '/':
a_step_from_comment_away = False
if char == '"':
if normal and not escaped:
# We are now in a string
quoted = True
normal = False
elif quoted and not escaped:
# We are now out of a string
quoted = False
normal = True
elif char == '\\':
# '\' should not take effect in comment
if normal or quoted:
escaped = True
elif char == '/':
if a_step_from_comment:
# Now we are in single line comment
a_step_from_comment = False
sl_comment = True
normal = False
former_index = index - 1
elif a_step_from_comment_away:
|
python
|
{
"resource": ""
}
|
q277311
|
GenericAuth.require_setting
|
test
|
def require_setting(self, name, feature="this feature"):
"""Raises an exception if the given app setting is not defined."""
if name not in self.settings:
|
python
|
{
"resource": ""
}
|
q277312
|
GenericAuth.get_argument
|
test
|
def get_argument(self, name, default=_ARG_DEFAULT, strip=True):
"""Returns the value of the argument with the given name.
If default is not provided, the argument is considered to be
required, and we throw an HTTP 400 exception if it is missing.
|
python
|
{
"resource": ""
}
|
q277313
|
GenericAuth.get_arguments
|
test
|
def get_arguments(self, name, strip=True):
"""Returns a list of the arguments with the given name.
If the argument is not present, returns an empty list.
The returned values are always unicode.
"""
values = []
for v in self.request.params.getall(name):
|
python
|
{
"resource": ""
}
|
q277314
|
GenericAuth.async_callback
|
test
|
def async_callback(self, callback, *args, **kwargs):
"""Obsolete - catches exceptions from the wrapped function.
This function is unnecessary since Tornado 1.1.
"""
if callback is None:
return
|
python
|
{
"resource": ""
}
|
q277315
|
GenericAuth.get_cookie
|
test
|
def get_cookie(self, name, default=None):
"""Gets the value of the cookie with the given name, else default."""
|
python
|
{
"resource": ""
}
|
q277316
|
GenericAuth.clear_cookie
|
test
|
def clear_cookie(self, name, path="/", domain=None):
"""Deletes the cookie with the given name."""
assert self.cookie_monster, 'Cookie Monster not set'
|
python
|
{
"resource": ""
}
|
q277317
|
OpenIdMixin.authenticate_redirect
|
test
|
def authenticate_redirect(
self, callback_uri=None, ax_attrs=["name", "email", "language",
"username"]):
"""Returns the authentication URL for this service.
After authentication, the service will redirect back to the given
callback URI.
|
python
|
{
"resource": ""
}
|
q277318
|
OAuthMixin.get_authenticated_user
|
test
|
def get_authenticated_user(self, callback):
"""Gets the OAuth authorized user and access token on callback.
This method should be called from the handler for your registered
OAuth Callback URL to complete the registration process. We call
callback with the authenticated user, which in addition to standard
attributes like 'name' includes the 'access_key' attribute, which
contains the OAuth access you can use to make authorized requests
to this service on behalf of the user.
"""
request_key = self.get_argument("oauth_token")
oauth_verifier = self.get_argument("oauth_verifier", None)
request_cookie = self.get_cookie("_oauth_request_token")
if not request_cookie:
log.warning("Missing OAuth request token cookie")
callback(None)
|
python
|
{
"resource": ""
}
|
q277319
|
OAuthMixin._oauth_request_parameters
|
test
|
def _oauth_request_parameters(self, url, access_token, parameters={},
method="GET"):
"""Returns the OAuth parameters as a dict for the given request.
parameters should include all POST arguments and query string arguments
that will be sent with the request.
"""
consumer_token = self._oauth_consumer_token()
base_args = dict(
oauth_consumer_key=consumer_token["key"],
oauth_token=access_token["key"],
oauth_signature_method="HMAC-SHA1",
oauth_timestamp=str(int(time.time())),
oauth_nonce=binascii.b2a_hex(uuid.uuid4().bytes),
oauth_version=getattr(self, "_OAUTH_VERSION", "1.0a"),
)
args =
|
python
|
{
"resource": ""
}
|
q277320
|
GoogleMixin.authorize_redirect
|
test
|
def authorize_redirect(self, oauth_scope, callback_uri=None,
ax_attrs=["name","email","language","username"]):
"""Authenticates and authorizes for the given Google resource.
Some of the available resources are:
* Gmail Contacts - http://www.google.com/m8/feeds/
* Calendar
|
python
|
{
"resource": ""
}
|
q277321
|
FacebookMixin.facebook_request
|
test
|
def facebook_request(self, method, callback, **args):
"""Makes a Facebook API REST request.
We automatically include the Facebook API key and signature, but
it is the callers responsibility to include 'session_key' and any
other required arguments to the method.
The available Facebook methods are documented here:
http://wiki.developers.facebook.com/index.php/API
Here is an example for the stream.get() method::
class MainHandler(tornado.web.RequestHandler,
tornado.auth.FacebookMixin):
@tornado.web.authenticated
@tornado.web.asynchronous
def get(self):
self.facebook_request(
method="stream.get",
callback=self.async_callback(self._on_stream),
session_key=self.current_user["session_key"])
def _on_stream(self, stream):
if stream is None:
# Not authorized to read the stream yet?
|
python
|
{
"resource": ""
}
|
q277322
|
FacebookGraphMixin.get_authenticated_user
|
test
|
def get_authenticated_user(self, redirect_uri, client_id, client_secret,
code, callback, fields=None):
"""Handles the login for the Facebook user, returning a user object.
Example usage::
class FacebookGraphLoginHandler(LoginHandler, tornado.auth.FacebookGraphMixin):
@tornado.web.asynchronous
def get(self):
if self.get_argument("code", False):
self.get_authenticated_user(
redirect_uri='/auth/facebookgraph/',
client_id=self.settings["facebook_api_key"],
client_secret=self.settings["facebook_secret"],
code=self.get_argument("code"),
callback=self.async_callback(
self._on_login))
return
self.authorize_redirect(redirect_uri='/auth/facebookgraph/',
client_id=self.settings["facebook_api_key"],
|
python
|
{
"resource": ""
}
|
q277323
|
url_concat
|
test
|
def url_concat(url, args):
"""Concatenate url and argument dictionary regardless of whether
url has existing query parameters.
>>> url_concat("http://example.com/foo?a=b", dict(c="d"))
'http://example.com/foo?a=b&c=d'
"""
if not args:
|
python
|
{
"resource": ""
}
|
q277324
|
_parse_header
|
test
|
def _parse_header(line):
"""Parse a Content-type like header.
Return the main content-type and a dictionary of options.
"""
parts = _parseparam(';' + line)
key = parts.next()
pdict = {}
for p in parts:
|
python
|
{
"resource": ""
}
|
q277325
|
HTTPHeaders.add
|
test
|
def add(self, name, value):
"""Adds a new value for the given key."""
norm_name = HTTPHeaders._normalize_name(name)
self._last_key = norm_name
if norm_name in self:
# bypass our override of __setitem__ since it modifies _as_list
|
python
|
{
"resource": ""
}
|
q277326
|
HTTPHeaders.get_list
|
test
|
def get_list(self, name):
"""Returns all values for the given header as a list."""
|
python
|
{
"resource": ""
}
|
q277327
|
HTTPHeaders.parse_line
|
test
|
def parse_line(self, line):
"""Updates the dictionary with a single header line.
>>> h = HTTPHeaders()
>>> h.parse_line("Content-Type: text/html")
>>> h.get('content-type')
'text/html'
"""
if line[0].isspace():
|
python
|
{
"resource": ""
}
|
q277328
|
HTTPHeaders.parse
|
test
|
def parse(cls, headers):
"""Returns a dictionary from HTTP header text.
>>> h = HTTPHeaders.parse("Content-Type: text/html\\r\\nContent-Length: 42\\r\\n")
>>> sorted(h.iteritems())
[('Content-Length', '42'), ('Content-Type', 'text/html')]
"""
|
python
|
{
"resource": ""
}
|
q277329
|
HTTPHeaders._normalize_name
|
test
|
def _normalize_name(name):
"""Converts a name to Http-Header-Case.
>>> HTTPHeaders._normalize_name("coNtent-TYPE")
'Content-Type'
"""
try:
return HTTPHeaders._normalized_headers[name]
|
python
|
{
"resource": ""
}
|
q277330
|
utf8
|
test
|
def utf8(value):
"""Converts a string argument to a byte string.
If the argument is already a byte string or None, it is returned unchanged.
Otherwise it must be a unicode string and is encoded as utf8.
|
python
|
{
"resource": ""
}
|
q277331
|
to_unicode
|
test
|
def to_unicode(value):
"""Converts a string argument to a unicode string.
If the argument is already a unicode string or None, it is returned
unchanged. Otherwise it must be a byte string and is decoded as utf8.
|
python
|
{
"resource": ""
}
|
q277332
|
to_basestring
|
test
|
def to_basestring(value):
"""Converts a string argument to a subclass of basestring.
In python2, byte and unicode strings are mostly interchangeable,
so functions that deal with a user-supplied argument in combination
with ascii string constants can use either and should return the type
the user supplied. In python3, the two types are not interchangeable,
so this method is
|
python
|
{
"resource": ""
}
|
q277333
|
recursive_unicode
|
test
|
def recursive_unicode(obj):
"""Walks a simple data structure, converting byte strings to unicode.
Supports lists, tuples, and dictionaries.
"""
if isinstance(obj, dict):
return dict((recursive_unicode(k), recursive_unicode(v)) for
|
python
|
{
"resource": ""
}
|
q277334
|
AuthPlugin.setup
|
test
|
def setup(self, app):
""" Make sure that other installed plugins don't affect the same
keyword argument and check if metadata is available."""
for other in app.plugins:
if not isinstance(other, AuthPlugin):
continue
if other.keyword == self.keyword:
|
python
|
{
"resource": ""
}
|
q277335
|
iter_subclasses
|
test
|
def iter_subclasses(cls, _seen=None):
"""
Generator over all subclasses of a given class, in depth-first order.
>>> bool in list(iter_subclasses(int))
True
>>> class A(object): pass
>>> class B(A): pass
>>> class C(A): pass
>>> class D(B,C): pass
>>> class E(D): pass
>>>
>>> for cls in iter_subclasses(A):
... print(cls.__name__)
B
D
E
C
>>> # get ALL (new-style) classes currently defined
>>> res = [cls.__name__ for cls in iter_subclasses(object)]
>>> 'type' in res
True
>>> 'tuple' in res
True
>>> len(res) > 100
True
"""
|
python
|
{
"resource": ""
}
|
q277336
|
CORS.selectPolicy
|
test
|
def selectPolicy(self, origin, request_method=None):
"Based on the matching strategy and the origin and optionally the requested method a tuple of policyname and origin to pass back is returned."
ret_origin = None
policyname = None
if self.matchstrategy in ("firstmatch", "verbmatch"):
for pol in self.activepolicies:
policy=self.policies[pol]
ret_origin = None
policyname = policy.name
if policyname == "deny":
break
if self.matchstrategy == "verbmatch":
if policy.methods != "*" and not CORS.matchlist(request_method, policy.methods, case_sensitive=True):
continue
if origin and policy.match:
|
python
|
{
"resource": ""
}
|
q277337
|
occupancy
|
test
|
def occupancy(grid, points, spacing=0.01):
"""Return a vector with the occupancy of each grid point for
given array of points"""
|
python
|
{
"resource": ""
}
|
q277338
|
write_gro
|
test
|
def write_gro(outfile, title, atoms, box):
"""
Write a GRO file.
Parameters
----------
outfile
The stream to write in.
title
The title of the GRO file. Must be a single line.
atoms
An instance of Structure containing the atoms to write.
box
The periodic box as a 3x3 matrix.
"""
# Print the title
print(title, file=outfile)
# Print the number of atoms
|
python
|
{
"resource": ""
}
|
q277339
|
write_pdb
|
test
|
def write_pdb(outfile, title, atoms, box):
"""
Write a PDB file.
Parameters
----------
outfile
The stream to write in.
title
The title of the GRO file. Must be a single line.
atoms
An instance of Structure containing the atoms to write.
|
python
|
{
"resource": ""
}
|
q277340
|
determine_molecule_numbers
|
test
|
def determine_molecule_numbers(total, molecules, absolute, relative):
"""Determine molecule numbers for given total,
absolute and relative numbers"""
weight = sum(relative)
if not any(absolute):
# Only relative numbers
numbers = [int(total*i/weight) for i in relative]
elif any(relative):
# Absolute numbers and fill the rest with relative numbers
|
python
|
{
"resource": ""
}
|
q277341
|
resize_pbc_for_lipids
|
test
|
def resize_pbc_for_lipids(pbc, relL, relU, absL, absU,
uparea, area, hole, proteins):
"""
Adapt the size of the box to accomodate the lipids.
The PBC is changed **in place**.
"""
if any(relL) and any(relU):
# Determine box from size
# If one leaflet is defined with an absolute number of lipids
# then the other leaflet (with relative numbers) will follow
# from that.
# box/d/x/y/z needed to define unit cell
# box is set up already...
# yet it may be set to 0, then there is nothing we can do.
if 0 in (pbc.x, pbc.y, pbc.z):
raise PBCException('Not enough information to set the box size.')
elif any(absL) or any(absU):
# All numbers are absolute.. determine size from number of lipids
# Box x/y will be set, d/dz/z is needed to set third box vector.
# The area is needed to determine the size of the x/y plane OR
# the area will be SET if a box is given.
if pbc.z == 0:
raise PBCException('Not enough information to set the box size.')
|
python
|
{
"resource": ""
}
|
q277342
|
write_top
|
test
|
def write_top(outpath, molecules, title):
"""
Write a basic TOP file.
The topology is written in *outpath*. If *outpath* is en empty string, or
anything for which ``bool(outpath) == False``, the topology is written on
the standard error, and the header is omitted, and only what has been buit
by Insane id displayed (e.g. Proteins are excluded).
Parameters
----------
outpath
The path to the file to write. If empty, a simplify topology is
written on stderr.
molecules
List of molecules with the number of them.
title
Title of the system.
"""
topmolecules = []
for i in molecules:
if i[0].endswith('.o'):
topmolecules.append(tuple([i[0][:-2]]+list(i[1:])))
else:
topmolecules.append(i)
if outpath:
# Write a rudimentary topology file
with open(outpath, "w") as top:
print('#include "martini.itp"\n', file=top)
print('[ system ]', file=top)
print('; name', file=top)
print(title, file=top)
print('\n', file=top)
|
python
|
{
"resource": ""
}
|
q277343
|
iter_resource
|
test
|
def iter_resource(filename):
"""
Return a stream for a given resource file in the module.
The resource file has to be part of the module and its filenane given
relative to the module.
"""
|
python
|
{
"resource": ""
}
|
q277344
|
message_user
|
test
|
def message_user(user, message, level=constants.INFO):
"""
Send a message to a particular user.
:param user: User instance
:param message: Message to show
:param level: Message level
"""
# We store a list of messages in the cache so we can have multiple messages
# queued up for a
|
python
|
{
"resource": ""
}
|
q277345
|
message_users
|
test
|
def message_users(users, message, level=constants.INFO):
"""
Send a message to a group of users.
:param users: Users queryset
:param message: Message to show
:param level:
|
python
|
{
"resource": ""
}
|
q277346
|
get_messages
|
test
|
def get_messages(user):
"""
Fetch messages for given user. Returns None if no such message exists.
:param user: User instance
"""
key = _user_key(user)
|
python
|
{
"resource": ""
}
|
q277347
|
AsyncMiddleware.process_response
|
test
|
def process_response(self, request, response):
"""
Check for messages for this user and, if it exists,
call the messages API with it
"""
if hasattr(request, "session") and hasattr(request, "user") and request.user.is_authenticated():
|
python
|
{
"resource": ""
}
|
q277348
|
check_config_file
|
test
|
def check_config_file(msg):
"""
Checks the config.json file for default settings and auth values.
Args:
:msg: (Message class) an instance of a message class.
"""
with jsonconfig.Config("messages", indent=4) as cfg:
verify_profile_name(msg, cfg)
retrieve_data_from_config(msg, cfg)
if msg._auth is
|
python
|
{
"resource": ""
}
|
q277349
|
verify_profile_name
|
test
|
def verify_profile_name(msg, cfg):
"""
Verifies the profile name exists in the config.json file.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config)
|
python
|
{
"resource": ""
}
|
q277350
|
retrieve_data_from_config
|
test
|
def retrieve_data_from_config(msg, cfg):
"""
Update msg attrs with values from the profile configuration if the
msg.attr=None, else leave it alone.
Args:
:msg: (Message class) an instance of a
|
python
|
{
"resource": ""
}
|
q277351
|
retrieve_pwd_from_config
|
test
|
def retrieve_pwd_from_config(msg, cfg):
"""
Retrieve auth from profile configuration and set in msg.auth attr.
Args:
:msg: (Message class) an instance of a message class.
|
python
|
{
"resource": ""
}
|
q277352
|
update_config_data
|
test
|
def update_config_data(msg, cfg):
"""
Updates the profile's config entry with values set in each attr by the
user. This will overwrite existing values.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance.
"""
|
python
|
{
"resource": ""
}
|
q277353
|
update_config_pwd
|
test
|
def update_config_pwd(msg, cfg):
"""
Updates the profile's auth entry with values set by the user.
This will overwrite existing values.
Args:
:msg: (Message class) an instance of a message class.
|
python
|
{
"resource": ""
}
|
q277354
|
create_config_profile
|
test
|
def create_config_profile(msg_type):
"""
Create a profile for the given message type.
Args:
:msg_type: (str) message type to create config entry.
"""
msg_type = msg_type.lower()
if msg_type not in CONFIG.keys():
raise UnsupportedMessageTypeError(msg_type)
display_required_items(msg_type)
if get_user_ack():
profile_name =
|
python
|
{
"resource": ""
}
|
q277355
|
display_required_items
|
test
|
def display_required_items(msg_type):
"""
Display the required items needed to configure a profile for the given
message type.
Args:
:msg_type: (str) message type to create config entry.
|
python
|
{
"resource": ""
}
|
q277356
|
get_data_from_user
|
test
|
def get_data_from_user(msg_type):
"""Get the required 'settings' from the user and return as a dict."""
data = {}
for k, v in
|
python
|
{
"resource": ""
}
|
q277357
|
get_auth_from_user
|
test
|
def get_auth_from_user(msg_type):
"""Get the required 'auth' from the user and return as a dict."""
|
python
|
{
"resource": ""
}
|
q277358
|
configure_profile
|
test
|
def configure_profile(msg_type, profile_name, data, auth):
"""
Create the profile entry.
Args:
:msg_type: (str) message type to create config entry.
:profile_name: (str) name of the profile entry
:data: (dict) dict values for the 'settings'
:auth: (dict) auth parameters
"""
with jsonconfig.Config("messages", indent=4) as cfg:
|
python
|
{
"resource": ""
}
|
q277359
|
write_data
|
test
|
def write_data(msg_type, profile_name, data, cfg):
"""
Write the settings into the data portion of the cfg.
Args:
:msg_type: (str) message type to create config entry.
:profile_name: (str) name of the profile entry
:data: (dict) dict values for the 'settings'
|
python
|
{
"resource": ""
}
|
q277360
|
write_auth
|
test
|
def write_auth(msg_type, profile_name, auth, cfg):
"""
Write the settings into the auth portion of the cfg.
Args:
:msg_type: (str) message type to create config entry.
:profile_name: (str) name of the profile entry
:auth: (dict) auth parameters
:cfg: (jsonconfig.Config) config instance.
"""
key_fmt =
|
python
|
{
"resource": ""
}
|
q277361
|
Slack._add_attachments
|
test
|
def _add_attachments(self):
"""Add attachments."""
if self.attachments:
if not isinstance(self.attachments, list):
self.attachments = [self.attachments]
self.message["attachments"] = [
{"image_url": url, "author_name": ""}
|
python
|
{
"resource": ""
}
|
q277362
|
Slack.send
|
test
|
def send(self, encoding="json"):
"""Send the message via HTTP POST, default is json-encoded."""
self._construct_message()
if self.verbose:
print(
"Debugging info"
"\n--------------"
"\n{} Message created.".format(timestamp())
)
if encoding == "json":
resp = requests.post(self.url, json=self.message)
elif encoding == "url":
resp = requests.post(self.url, data=self.message)
try:
resp.raise_for_status()
if resp.history and resp.history[0].status_code >= 300:
raise MessageSendError("HTTP Redirect: Possibly Invalid authentication")
|
python
|
{
"resource": ""
}
|
q277363
|
send
|
test
|
def send(msg_type, send_async=False, *args, **kwargs):
"""
Constructs a message class and sends the message.
Defaults to sending synchronously. Set send_async=True to send
asynchronously.
Args:
:msg_type: (str) the type of message to send, i.e. 'Email'
:send_async: (bool) default is False, set True to send asynchronously.
:kwargs: (dict) keywords arguments that are required for the
various message types. See docstrings for each type.
i.e. help(messages.Email), help(messages.Twilio), etc.
Example:
>>> kwargs = {
from_: '[email protected]',
to: '[email protected]',
auth: 'yourPassword',
subject: 'Email Subject',
body: 'Your message to send',
|
python
|
{
"resource": ""
}
|
q277364
|
message_factory
|
test
|
def message_factory(msg_type, msg_types=MESSAGE_TYPES, *args, **kwargs):
"""
Factory function to return the specified message instance.
Args:
:msg_type: (str) the type of message to send, i.e. 'Email'
:msg_types: (str, list, or set) the supported message types
:kwargs: (dict) keywords arguments that
|
python
|
{
"resource": ""
}
|
q277365
|
credential_property
|
test
|
def credential_property(cred):
"""
A credential property factory for each message class that will set
private attributes and return obfuscated credentials when requested.
|
python
|
{
"resource": ""
}
|
q277366
|
validate_property
|
test
|
def validate_property(attr):
"""
A property factory that will dispatch the to a specific validator function
that will validate the user's input to ensure critical parameters are of a
specific type.
"""
def getter(instance):
return instance.__dict__[attr]
def
|
python
|
{
"resource": ""
}
|
q277367
|
validate_input
|
test
|
def validate_input(msg_type, attr, value):
"""Base function to validate input, dispatched via message type."""
try:
valid = {
"Email": validate_email,
"Twilio": validate_twilio,
"SlackWebhook": validate_slackwebhook,
"SlackPost": validate_slackpost,
|
python
|
{
"resource": ""
}
|
q277368
|
validate_twilio
|
test
|
def validate_twilio(attr, value):
"""Twilio input validator function."""
if attr in ("from_", "to"):
|
python
|
{
"resource": ""
}
|
q277369
|
validate_slackpost
|
test
|
def validate_slackpost(attr, value):
"""SlackPost input validator function."""
if attr in ("channel", "credentials"):
if not isinstance(value, str):
raise InvalidMessageInputError("SlackPost", attr, value,
|
python
|
{
"resource": ""
}
|
q277370
|
validate_whatsapp
|
test
|
def validate_whatsapp(attr, value):
"""WhatsApp input validator function."""
if attr in ("from_", "to"):
if value is not None and "whatsapp:" in value:
value = value.split("whatsapp:+")[-1]
check_valid(
"WhatsApp",
attr,
value,
validus.isint,
|
python
|
{
"resource": ""
}
|
q277371
|
_send_coroutine
|
test
|
def _send_coroutine():
"""
Creates a running coroutine to receive message instances and send
them in a futures executor.
"""
with PoolExecutor() as executor:
while True:
msg
|
python
|
{
"resource": ""
}
|
q277372
|
MessageLoop.add_message
|
test
|
def add_message(self, msg):
"""Add a message to the futures executor."""
try:
self._coro.send(msg)
|
python
|
{
"resource": ""
}
|
q277373
|
get_body_from_file
|
test
|
def get_body_from_file(kwds):
"""Reads message body if specified via filepath."""
if kwds["file"] and os.path.isfile(kwds["file"]):
|
python
|
{
"resource": ""
}
|
q277374
|
trim_args
|
test
|
def trim_args(kwds):
"""Gets rid of args with value of None, as well as select keys."""
reject_key = ("type", "types", "configure")
reject_val = (None, ())
kwargs = {
k: v for k, v in kwds.items() if k not in reject_key and v not in reject_val
|
python
|
{
"resource": ""
}
|
q277375
|
send_message
|
test
|
def send_message(msg_type, kwds):
"""Do some final preprocessing and send the message."""
if kwds["file"]:
get_body_from_file(kwds)
|
python
|
{
"resource": ""
}
|
q277376
|
TelegramBot.get_chat_id
|
test
|
def get_chat_id(self, username):
"""Lookup chat_id of username if chat_id is unknown via API call."""
if username is not None:
chats = requests.get(self.base_url + "/getUpdates").json()
|
python
|
{
"resource": ""
}
|
q277377
|
TelegramBot._send_content
|
test
|
def _send_content(self, method="/sendMessage"):
"""send via HTTP Post."""
url = self.base_url + method
try:
resp = requests.post(url, json=self.message)
resp.raise_for_status()
except requests.exceptions.HTTPError as e:
raise MessageSendError(e)
if self.verbose:
|
python
|
{
"resource": ""
}
|
q277378
|
TelegramBot.send
|
test
|
def send(self):
"""Start sending the message and attachments."""
self._construct_message()
if self.verbose:
print(
"Debugging info"
"\n--------------"
"\n{} Message created.".format(timestamp())
)
self._send_content("/sendMessage")
if self.attachments:
if isinstance(self.attachments, str):
self.attachments = [self.attachments]
for a in self.attachments:
|
python
|
{
"resource": ""
}
|
q277379
|
Email.get_server
|
test
|
def get_server(address=None):
"""Return an SMTP servername guess from outgoing email address."""
if address:
domain = address.split("@")[1]
try:
|
python
|
{
"resource": ""
}
|
q277380
|
Email._generate_email
|
test
|
def _generate_email(self):
"""Put the parts of the email together."""
|
python
|
{
"resource": ""
}
|
q277381
|
Email._add_header
|
test
|
def _add_header(self):
"""Add email header info."""
self.message["From"] = self.from_
self.message["Subject"] = self.subject
if self.to:
self.message["To"] = self.list_to_string(self.to)
if self.cc:
|
python
|
{
"resource": ""
}
|
q277382
|
Email._add_body
|
test
|
def _add_body(self):
"""Add body content of email."""
if self.body:
b = MIMEText("text", "plain")
|
python
|
{
"resource": ""
}
|
q277383
|
Email._add_attachments
|
test
|
def _add_attachments(self):
"""Add required attachments."""
num_attached = 0
if self.attachments:
if isinstance(self.attachments, str):
self.attachments = [self.attachments]
for item in self.attachments:
doc =
|
python
|
{
"resource": ""
}
|
q277384
|
Email._get_session
|
test
|
def _get_session(self):
"""Start session with email server."""
if self.port in (465, "465"):
session = self._get_ssl()
elif self.port in (587, "587"):
session = self._get_tls()
try:
|
python
|
{
"resource": ""
}
|
q277385
|
Email._get_ssl
|
test
|
def _get_ssl(self):
"""Get an SMTP session with SSL."""
return
|
python
|
{
"resource": ""
}
|
q277386
|
Email._get_tls
|
test
|
def _get_tls(self):
"""Get an SMTP session with TLS."""
session = smtplib.SMTP(self.server, self.port)
session.ehlo()
|
python
|
{
"resource": ""
}
|
q277387
|
Email.send
|
test
|
def send(self):
"""
Send the message.
First, a message is constructed, then a session with the email
servers is created, finally the message is sent and the session
is stopped.
"""
self._generate_email()
if self.verbose:
print(
"Debugging info"
"\n--------------"
"\n{} Message created.".format(timestamp())
)
recipients = []
for i in (self.to, self.cc, self.bcc):
if i:
if isinstance(i, MutableSequence):
recipients += i
else:
recipients.append(i)
session = self._get_session()
if self.verbose:
print(timestamp(), "Login successful.")
|
python
|
{
"resource": ""
}
|
q277388
|
FileType.save
|
test
|
def save(self, filename=None, **kwargs):
"""Save metadata tags."""
if filename is None:
filename = self.filename
else:
warnings.warn(
"save(filename=...) is deprecated, reload the file",
|
python
|
{
"resource": ""
}
|
q277389
|
Image.unload
|
test
|
def unload(self):
'''Releases renderer resources associated with this image.'''
if self._handle != -1:
|
python
|
{
"resource": ""
}
|
q277390
|
Image.get_region
|
test
|
def get_region(self, x1, y1, x2, y2):
'''Get an image that refers to the given rectangle within this image. The image data is not actually
copied; if the image region is rendered into, it will affect this image.
:param int x1: left edge of the image region to return
|
python
|
{
"resource": ""
}
|
q277391
|
VComment.validate
|
test
|
def validate(self):
"""Validate keys and values.
Check to make sure every key used is a valid Vorbis key, and
that every value used is a valid Unicode or UTF-8 string. If
any invalid keys or values are found, a ValueError is raised.
In Python 3 all keys and values have to be a string.
"""
# be stricter in Python 3
if PY3:
if not isinstance(self.vendor, text_type):
raise ValueError
for key, value in self:
if not isinstance(key, text_type):
raise ValueError
if not isinstance(value, text_type):
raise ValueError
if not isinstance(self.vendor, text_type):
try:
self.vendor.decode('utf-8')
except UnicodeDecodeError:
raise ValueError
|
python
|
{
"resource": ""
}
|
q277392
|
VComment.clear
|
test
|
def clear(self):
"""Clear all keys from the comment."""
|
python
|
{
"resource": ""
}
|
q277393
|
VComment.write
|
test
|
def write(self, framing=True):
"""Return a string representation of the data.
Validation is always performed, so calling this function on
invalid data may raise a ValueError.
Keyword arguments:
* framing -- if true, append a framing bit (see load)
"""
self.validate()
def _encode(value):
if not isinstance(value, bytes):
return value.encode('utf-8')
return value
f = BytesIO()
vendor = _encode(self.vendor)
f.write(cdata.to_uint_le(len(vendor)))
|
python
|
{
"resource": ""
}
|
q277394
|
IFFChunk.read
|
test
|
def read(self):
"""Read the chunks data"""
self.__fileobj.seek(self.data_offset)
|
python
|
{
"resource": ""
}
|
q277395
|
IFFChunk.delete
|
test
|
def delete(self):
"""Removes the chunk from the file"""
delete_bytes(self.__fileobj, self.size, self.offset)
if self.parent_chunk is not None:
|
python
|
{
"resource": ""
}
|
q277396
|
IFFChunk.resize
|
test
|
def resize(self, data_size):
"""Update the size of the chunk"""
self.__fileobj.seek(self.offset + 4)
self.__fileobj.write(pack('>I', data_size))
if self.parent_chunk is not None:
size_diff = self.data_size - data_size
|
python
|
{
"resource": ""
}
|
q277397
|
IFFFile.insert_chunk
|
test
|
def insert_chunk(self, id_):
"""Insert a new chunk at the end of the IFF file"""
if not isinstance(id_, text_type):
id_ = id_.decode('ascii')
if not is_valid_chunk_id(id_):
raise KeyError("AIFF key must be four ASCII characters.")
self.__fileobj.seek(self.__next_offset)
self.__fileobj.write(pack('>4si', id_.ljust(4).encode('ascii'), 0))
self.__fileobj.seek(self.__next_offset)
|
python
|
{
"resource": ""
}
|
q277398
|
_IFFID3.save
|
test
|
def save(self, filename=None, v2_version=4, v23_sep='/'):
"""Save ID3v2 data to the AIFF file"""
framedata = self._prepare_framedata(v2_version, v23_sep)
framesize = len(framedata)
if filename is None:
filename = self.filename
# Unlike the parent ID3.save method, we won't save to a blank file
# since we would have to construct a empty AIFF file
fileobj = open(filename, 'rb+')
iff_file = IFFFile(fileobj)
try:
if u'ID3' not in iff_file:
iff_file.insert_chunk(u'ID3')
chunk = iff_file[u'ID3']
fileobj.seek(chunk.data_offset)
header = fileobj.read(10)
header = self._prepare_id3_header(header, framesize, v2_version)
header, new_size, _ = header
data = header + framedata + (b'\x00' * (new_size - framesize))
# Include ID3 header size in 'new_size' calculation
new_size += 10
|
python
|
{
"resource": ""
}
|
q277399
|
_IFFID3.delete
|
test
|
def delete(self, filename=None):
"""Completely removes the ID3 chunk from the AIFF file"""
if filename is None:
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.