code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
conn = Connection.connect(conn=conn, google_user=google_user,
google_password=google_password)
res = Resource(type='spreadsheet', title=title)
res = conn.docs_client.CreateResource(res)
id = res.id.text.rsplit('%3A', 1)[-1]
return cls(id... | def create(cls, title, conn=None, google_user=None,
google_password=None) | Create a new spreadsheet with the given ``title``. | 4.744532 | 4.510478 | 1.051891 |
conn = Connection.connect(conn=conn, google_user=google_user,
google_password=google_password)
return cls(id=id, conn=conn) | def by_id(cls, id, conn=None, google_user=None,
google_password=None) | Open a spreadsheet via its resource ID. This is more precise
than opening a document by title, and should be used with
preference. | 2.925404 | 3.035553 | 0.963714 |
conn = Connection.connect(conn=conn, google_user=google_user,
google_password=google_password)
q = DocsQuery(categories=['spreadsheet'], title=title)
feed = conn.docs_client.GetResources(q=q)
for entry in feed.entry:
if entry.title.t... | def by_title(cls, title, conn=None, google_user=None,
google_password=None) | Open the first document with the given ``title`` that is
returned by document search. | 4.001546 | 4.028098 | 0.993408 |
if app.config['USERPROFILES_EXTEND_SECURITY_FORMS']:
security_ext = app.extensions['security']
security_ext.confirm_register_form = confirm_register_form_factory(
security_ext.confirm_register_form)
security_ext.register_form = register_form_factory(
security_ext... | def init_common(app) | Post initialization. | 3.244456 | 3.198402 | 1.014399 |
app = state.app
init_common(app)
# Register blueprint for templates
app.register_blueprint(
blueprint, url_prefix=app.config['USERPROFILES_PROFILE_URL']) | def init_ui(state) | Post initialization for UI application. | 9.993632 | 9.418306 | 1.061086 |
# Create forms
verification_form = VerificationForm(formdata=None, prefix="verification")
profile_form = profile_form_factory()
# Process forms
form = request.form.get('submit', None)
if form == 'profile':
handle_profile_form(profile_form)
elif form == 'verification':
h... | def profile() | View for editing a profile. | 3.456938 | 3.425719 | 1.009113 |
if current_app.config['USERPROFILES_EMAIL_ENABLED']:
return EmailProfileForm(
formdata=None,
username=current_userprofile.username,
full_name=current_userprofile.full_name,
email=current_user.email,
email_repeat=current_user.email,
... | def profile_form_factory() | Create a profile form. | 3.952104 | 4.012875 | 0.984856 |
form.process(formdata=request.form)
if form.validate_on_submit():
send_confirmation_instructions(current_user)
# NOTE: Flash message.
flash(_("Verification email sent."), category="success") | def handle_verification_form(form) | Handle email sending verification form. | 6.008497 | 5.423071 | 1.107951 |
form.process(formdata=request.form)
if form.validate_on_submit():
email_changed = False
with db.session.begin_nested():
# Update profile.
current_userprofile.username = form.username.data
current_userprofile.full_name = form.full_name.data
db... | def handle_profile_form(form) | Handle profile update form. | 2.526088 | 2.490178 | 1.01442 |
if (type(data) == dict and 'status' in data.keys()
and data['status'] == 'failed'):
if data.get('exception_msg') and 'last_id' in data.get('exception_msg'):
raise PyBossaServerNoKeysetPagination
else:
raise Error(data)
return ... | def check_errors(self, data) | Check for errors on data payload. | 9.270057 | 8.976251 | 1.032731 |
if not self.is_token_set:
raise ValueError('TelepythClient: Access token is not set!')
stream = StringIO()
stream.write(text)
stream.seek(0)
return self(stream) | def send_text(self, text) | Send text message to telegram user. Text message should be markdown
formatted.
:param text: markdown formatted text.
:return: status code on error. | 7.691464 | 8.434763 | 0.911877 |
if not self.is_token_set:
raise ValueError('TelepythClient: Access token is not set!')
figure = BytesIO()
fig.savefig(figure, format='png')
figure.seek(0)
parts = [ContentDisposition('caption', caption),
ContentDisposition('figure', figure,... | def send_figure(self, fig, caption='') | Render matplotlib figure into temporary bytes buffer and then send
it to telegram user.
:param fig: matplotlib figure object.
:param caption: text caption of picture.
:return: status code on error. | 3.609463 | 3.553956 | 1.015618 |
torem = set(c for c in clusters if c.size < n)
pruned_clusters = [c for c in clusters if c.size >= n]
terms_torem = []
for term, clusters in index.items():
index[term] = clusters - torem
if len(index[term]) == 0:
terms_torem.append(term)
for t in terms_torem:
... | def prune_clusters(clusters, index, n=3) | Delete clusters with fewer than n elements. | 2.66529 | 2.627729 | 1.014294 |
poll_interval = poll_interval or self.api.poll_interval
monitor = self.monitor_class(
resource=self,
field=field,
callback=callback,
poll_interval=poll_interval,
event_queue=self.api.event_queue,
poll_pool=self.api.poll_po... | def monitor(self, field, callback, poll_interval=None) | Monitor `field` for change
Will monitor ``field`` for change and execute ``callback`` when
change is detected.
Example usage::
def handle(resource, field, previous, current):
print "Change from {} to {}".format(previous, current)
switch = TapSwitch.obj... | 2.765447 | 3.918723 | 0.705701 |
class CsrfDisabledProfileForm(ProfileForm):
def __init__(self, *args, **kwargs):
kwargs = _update_with_csrf_disabled(kwargs)
super(CsrfDisabledProfileForm, self).__init__(*args, **kwargs)
class RegisterForm(Form):
profile = FormField... | def register_form_factory(Form) | Factory for creating an extended user registration form. | 4.468499 | 4.321662 | 1.033977 |
class CsrfDisabledProfileForm(ProfileForm):
def __init__(self, *args, **kwargs):
kwargs = _update_with_csrf_disabled(kwargs)
super(CsrfDisabledProfileForm, self).__init__(*args, **kwargs)
class ConfirmRegisterForm(Form):
profile = Fo... | def confirm_register_form_factory(Form) | Factory for creating a confirm register form. | 4.190934 | 4.130597 | 1.014607 |
if d is None:
d = {}
import flask_wtf
from pkg_resources import parse_version
supports_meta = parse_version(flask_wtf.__version__) >= parse_version(
"0.14.0")
if supports_meta:
d.setdefault('meta', {})
d['meta'].update({'csrf': False})
else:
d['csrf_... | def _update_with_csrf_disabled(d=None) | Update the input dict with CSRF disabled depending on WTF-Form version.
From Flask-WTF 0.14.0, `csrf_enabled` param has been deprecated in favor of
`meta={csrf: True/False}`. | 3.1615 | 2.584013 | 1.223485 |
try:
validate_username(field.data)
except ValueError as e:
raise ValidationError(e)
try:
user_profile = UserProfile.get_by_username(field.data)
if current_userprofile.is_anonymous or \
(current_userprofile.user_id != u... | def validate_username(form, field) | Wrap username validator for WTForms. | 3.54425 | 3.383652 | 1.047463 |
if pagenum:
try:
pages = [list(pages)[pagenum - 1]]
except IndexError:
raise IndexError('Invalid page number: %d' % pagenum)
if pagename:
pages = [page for page in pages if page.name == pagename]
if pages == []:
raise IndexError('Page not... | def filter_pages(pages, pagenum, pagename) | Choices pages by pagenum and pagename | 2.673153 | 2.53818 | 1.053177 |
# visio requires absolute path
image_pathname = os.path.abspath(image_filename)
if not os.path.isdir(os.path.dirname(image_pathname)):
msg = 'Could not write image file: %s' % image_filename
raise IOError(msg)
with VisioFile.Open(visio_filename) as visio:
pages = filter_pa... | def export_img(visio_filename, image_filename, pagenum=None, pagename=None) | Exports images from visio file | 2.401898 | 2.4358 | 0.986082 |
usage = 'usage: %prog [options] visio_filename image_filename'
parser = OptionParser(usage=usage)
parser.add_option('-p', '--page', action='store',
type='int', dest='pagenum',
help='pick a page by page number')
parser.add_option('-n', '--name', action='st... | def parse_options(args) | Parses command line options | 2.394776 | 2.367398 | 1.011565 |
if not is_pywin32_available():
sys.stderr.write('win32com module not found')
return -1
try:
options, argv = parse_options(args)
export_img(argv[0], argv[1], options.pagenum, options.pagename)
return 0
except (IOError, OSError, IndexError) as err:
sys.std... | def main(args=sys.argv[1:]) | main funcion of visio2img | 4.663314 | 4.100091 | 1.137369 |
providers = getattr(settings, 'SITEMETRICS_PROVIDERS', False)
if not providers:
return []
p_clss = []
for provider_path in providers:
path_splitted = provider_path.split('.')
mod = import_module('.'.join(path_splitted[:-1]))
p_cls = getattr(mod, path_splitted[-1])... | def get_custom_providers() | Imports providers classes by paths given in SITEMETRICS_PROVIDERS setting. | 3.0515 | 2.147284 | 1.421098 |
try:
return urllib2.urlopen(url).read().decode('utf-8').replace('\n', '')
except urllib2.HTTPError:
_, exception, _ = sys.exc_info()
if cls.__debug:
print('HTTPError = ' + str(exception.code))
except urllib2.URLError:
_, ex... | def __query(cls, url) | Reads a URL | 2.393251 | 2.415775 | 0.990677 |
base_url = u'%s&switchcmd=%s' % (self.__homeauto_url_with_sid(), command)
if device is None:
url = base_url
else:
url = '%s&ain=%s' % (base_url, device)
if self.__debug:
print(u'Query Command URI: ' + url)
return self.__query(url) | def __query_cmd(self, command, device=None) | Calls a command | 5.505491 | 5.548331 | 0.992279 |
base_url = u'%s/login_sid.lua' % self.__fritz_url
get_challenge = None
try:
get_challenge = urllib2.urlopen(base_url).read().decode('ascii')
except urllib2.HTTPError as exception:
print('HTTPError = ' + str(exception.code))
except urllib2.URLError... | def get_sid(self) | Returns a valid SID | 3.158092 | 3.095667 | 1.020165 |
if status == 1 or status == True or status == '1':
return self.switch_on(device)
else:
return self.switch_off(device) | def switch_onoff(self, device, status) | Switch a Socket | 2.683845 | 2.903593 | 0.924318 |
state = self.get_state(device)
if(state == '1'):
return self.switch_off(device)
elif(state == '0'):
return self.switch_on(device)
else:
return state | def switch_toggle(self, device) | Toggles the current state of the given device | 2.831686 | 2.812654 | 1.006767 |
power_dict = self.get_power_all()
for device in power_dict.keys():
power_dict[device] = float(power_dict[device]) / 1000.0
return power_dict | def get_power(self) | Returns the Power in Watt | 2.954274 | 2.770555 | 1.066311 |
dev_names = {}
for device in self.get_device_ids():
dev_names[device] = self.get_device_name(device)
return dev_names | def get_device_names(self) | Returns a Dict with devicenames | 2.655567 | 2.386457 | 1.112766 |
temp_str = self.__query_cmd('gettemperature', device)
if temp_str.lstrip('-').isdigit():
return float(temp_str) / 10.0
return 'inval' | def get_temperature_single(self, device) | Returns the temperature in 0.1 °C for a single device | 6.908228 | 5.873351 | 1.176199 |
power_dict = {}
for device in self.get_device_names().keys():
power_dict[device] = self.get_power_single(device)
return power_dict | def get_power_all(self) | Returns the power in mW for all devices | 3.270792 | 2.74846 | 1.190046 |
state_dict = {}
for device in self.get_device_names().keys():
state_dict[device] = self.get_state(device)
return state_dict | def get_state_all(self) | Returns all device states | 3.495358 | 2.73469 | 1.278155 |
self.init_config(app)
# Register current_profile
app.context_processor(lambda: dict(
current_userprofile=current_userprofile))
app.extensions['invenio-userprofiles'] = self | def init_app(self, app) | Flask application initialization. | 6.068526 | 6.249522 | 0.971038 |
found_entry_points = {}
for dist in working_set:
entry_map = dist.get_entry_map()
for group_name, entry_points in entry_map.items():
# Filter entry points
if entry_point is None and \
not group_name.startswith('invenio'):
continue
... | def list_entrypoints(entry_point) | List defined entry points. | 2.322683 | 2.262544 | 1.02658 |
if 'SECRET_KEY' not in current_app.config or \
current_app.config['SECRET_KEY'] is None:
raise click.ClickException(
'SECRET_KEY is not set in the configuration.')
for ep in iter_entry_points('invenio_base.secret_key'):
try:
ep.load()(old_key=old_key)
... | def migrate_secret_key(old_key) | Call entry points exposed for the SECRET_KEY change. | 3.555531 | 3.137295 | 1.133311 |
import string
import random
rng = random.SystemRandom()
return ''.join(
rng.choice(string.ascii_letters + string.digits)
for dummy in range(0, 256)
) | def generate_secret_key() | Generate secret key. | 3.804696 | 3.472747 | 1.095587 |
op.create_table(
'userprofiles_userprofile',
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(length=255), nullable=True),
sa.Column('displayname', sa.String(length=255), nullable=True),
sa.Column('full_name', sa.String(length=255), nul... | def upgrade() | Upgrade database. | 1.729803 | 1.751347 | 0.987699 |
choices = []
for provider in METRICS_PROVIDERS:
choices.append((provider.alias, provider.title))
return choices | def get_provider_choices() | Returns a list of currently available metrics providers
suitable for use as model fields choices. | 3.976875 | 3.208975 | 1.239298 |
'''Send a message.
:param message: Message to send.
:type message: `dict` or :class:`Message`
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. De... | def send(message, api_key=None, secure=None, test=None, **request_args) | Send a message.
:param message: Message to send.
:type message: `dict` or :class:`Message`
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults ... | 3.292694 | 1.739191 | 1.893233 |
'''Send a message.
:param message: Message to send.
:type message: `dict` or :class:`Message`
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. De... | def send_with_template(message,
api_key=None,
secure=None,
test=None,
**request_args) | Send a message.
:param message: Message to send.
:type message: `dict` or :class:`Message`
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults ... | 3.322617 | 1.798775 | 1.847155 |
'''Send a batch of messages.
:param messages: Messages to send.
:type message: A list of `dict` or :class:`Message`
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the... | def send_batch(messages, api_key=None, secure=None, test=None, **request_args) | Send a batch of messages.
:param messages: Messages to send.
:type message: A list of `dict` or :class:`Message`
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postma... | 3.64315 | 1.779898 | 2.046831 |
'''Get delivery stats for your Postmark account.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to `False`.
:param \*\*request_args: Keywo... | def get_delivery_stats(api_key=None, secure=None, test=None, **request_args) | Get delivery stats for your Postmark account.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to `False`.
:param \*\*request_args: Keyword argu... | 3.32572 | 1.600976 | 2.077309 |
'''Get a paginated list of bounces.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to `False`.
:param \*\*request_args: Keyword arguments ... | def get_bounces(api_key=None, secure=None, test=None, **request_args) | Get a paginated list of bounces.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to `False`.
:param \*\*request_args: Keyword arguments to pass... | 3.450172 | 1.603876 | 2.151146 |
'''Get a single bounce.
:param bounce_id: The bounce's id. Get the id with :func:`get_bounces`.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defa... | def get_bounce(bounce_id, api_key=None, secure=None, test=None,
**request_args) | Get a single bounce.
:param bounce_id: The bounce's id. Get the id with :func:`get_bounces`.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to... | 2.924797 | 1.462326 | 2.0001 |
'''Get the raw email dump for a single bounce.
:param bounce_id: The bounce's id. Get the id with :func:`get_bounces`.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the ... | def get_bounce_dump(bounce_id, api_key=None, secure=None, test=None,
**request_args) | Get the raw email dump for a single bounce.
:param bounce_id: The bounce's id. Get the id with :func:`get_bounces`.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmar... | 3.1908 | 1.474898 | 2.163405 |
'''Get a list of tags for bounces associated with your Postmark server.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to `False`.
:param ... | def get_bounce_tags(api_key=None, secure=None, test=None, **request_args) | Get a list of tags for bounces associated with your Postmark server.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to `False`.
:param \*\*req... | 3.684528 | 1.583802 | 2.326382 |
'''Activate a deactivated bounce.
:param bounce_id: The bounce's id. Get the id with :func:`get_bounces`.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test... | def activate_bounce(bounce_id, api_key=None, secure=None, test=None,
**request_args) | Activate a deactivated bounce.
:param bounce_id: The bounce's id. Get the id with :func:`get_bounces`.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. D... | 3.119144 | 1.531101 | 2.037191 |
'''Returns data formatted for a POST request to the Postmark send API.
:rtype: `dict`
'''
d = {}
for val, key in self._fields.items():
val = getattr(self, val)
if val is not None:
d[key] = val
return d | def data(self) | Returns data formatted for a POST request to the Postmark send API.
:rtype: `dict` | 5.482075 | 2.658044 | 2.062447 |
'''Create a :class:`Message` from a message data `dict`.
:param message: A `dict` of message data.
:param \*\*kwargs: Additional keyword arguments to construct
:class:`Message` with.
:rtype: :class:`Message`
'''
kwargs.update(message)
message = kwargs... | def load_message(self, message, **kwargs) | Create a :class:`Message` from a message data `dict`.
:param message: A `dict` of message data.
:param \*\*kwargs: Additional keyword arguments to construct
:class:`Message` with.
:rtype: :class:`Message` | 4.051547 | 2.528608 | 1.602283 |
'''Create a :class:`Message` by merging `other` with `self`.
Values from `other` will be copied to `self` if the value was not
set on `self` and is set on `other`.
:param other: The :class:`Message` to copy defaults from.
:type other: :class:`Message`
:param \*\*kwargs: ... | def load_from(self, other, **kwargs) | Create a :class:`Message` by merging `other` with `self`.
Values from `other` will be copied to `self` if the value was not
set on `self` and is set on `other`.
:param other: The :class:`Message` to copy defaults from.
:type other: :class:`Message`
:param \*\*kwargs: Additional ... | 3.352971 | 1.585114 | 2.115288 |
'''Attach an email header to send with the message.
:param name: The name of the header value.
:param value: The header value.
'''
if self.headers is None:
self.headers = []
self.headers.append(dict(Name=name, Value=value)) | def add_header(self, name, value) | Attach an email header to send with the message.
:param name: The name of the header value.
:param value: The header value. | 3.927479 | 2.847676 | 1.379188 |
'''Attach a file to the message given raw binary data.
:param data: Raw data to attach to the message.
:param filename: Name of the file for the data.
:param content_type: mimetype of the data. It will be guessed from the
filename if not provided.
:param content_id: ... | def attach_binary(self, data, filename, content_type=None,
content_id=None) | Attach a file to the message given raw binary data.
:param data: Raw data to attach to the message.
:param filename: Name of the file for the data.
:param content_type: mimetype of the data. It will be guessed from the
filename if not provided.
:param content_id: ContentID U... | 3.0937 | 1.742269 | 1.775673 |
'''Attach a file to the message given a filename.
:param filename: Name of the file to attach.
:param content_type: mimetype of the data. It will be guessed from the
filename if not provided.
:param content_id: ContentID URL of the attachment. A RFC 2392-
compli... | def attach_file(self, filename, content_type=None,
content_id=None) | Attach a file to the message given a filename.
:param filename: Name of the file to attach.
:param content_type: mimetype of the data. It will be guessed from the
filename if not provided.
:param content_id: ContentID URL of the attachment. A RFC 2392-
compliant URL for... | 4.175629 | 2.16115 | 1.932133 |
'''Verifies the message data based on rules and restrictions defined
in the Postmark API docs. There can be no more than 20 recipients
in total. NOTE: This does not check that your attachments total less
than 10MB, you must do that yourself.
'''
if self.to is None:
... | def verify(self) | Verifies the message data based on rules and restrictions defined
in the Postmark API docs. There can be no more than 20 recipients
in total. NOTE: This does not check that your attachments total less
than 10MB, you must do that yourself. | 4.513206 | 2.177962 | 2.072215 |
'''A list of all recipients for this message.
'''
cc = self._cc or []
bcc = self._bcc or []
return self._to + cc + bcc | def recipients(self) | A list of all recipients for this message. | 6.016122 | 4.559753 | 1.319396 |
'''
:param to: Email addresses for the 'To' API field.
:type to: :keyword:`list` or `str`
'''
if isinstance(to, basestring):
to = to.split(',')
self._to = to | def to(self, to) | :param to: Email addresses for the 'To' API field.
:type to: :keyword:`list` or `str` | 5.704114 | 2.420212 | 2.356866 |
'''
:param cc: Email addresses for the 'Cc' API field.
:type cc: :keyword:`list` or `str`
'''
if isinstance(cc, basestring):
cc = cc.split(',')
self._cc = cc | def cc(self, cc) | :param cc: Email addresses for the 'Cc' API field.
:type cc: :keyword:`list` or `str` | 5.986916 | 2.450683 | 2.442959 |
'''
:param bcc: Email addresses for the 'Bcc' API field.
:type bcc: :keyword:`list` or `str`
'''
if isinstance(bcc, basestring):
bcc = bcc.split(',')
self._bcc = bcc | def bcc(self, bcc) | :param bcc: Email addresses for the 'Bcc' API field.
:type bcc: :keyword:`list` or `str` | 4.566984 | 2.302868 | 1.983172 |
'''Converts Postmark message API field names to their corresponding
:class:`Message` attribute names.
:param message: Postmark message data, with API fields using Postmark
API names.
:type message: `dict`
'''
d = {}
for dest, src in cls._fields.items(... | def _convert_postmark_to_native(cls, message) | Converts Postmark message API field names to their corresponding
:class:`Message` attribute names.
:param message: Postmark message data, with API fields using Postmark
API names.
:type message: `dict` | 5.787137 | 2.184094 | 2.649673 |
'''Determine the mimetype for a file.
:param filename: Filename of file to detect.
'''
name, ext = os.path.splitext(filename)
if not ext:
raise MessageError('File requires an extension.')
ext = ext.lower()
if ext.lstrip('.') in self._banned_extensions... | def _detect_content_type(self, filename) | Determine the mimetype for a file.
:param filename: Filename of file to detect. | 3.194676 | 2.965299 | 1.077354 |
'''Verify that attachment values match the format expected by the
Postmark API.
'''
if self.attachments is None:
return
keys = ('Name', 'Content', 'ContentType')
self._verify_dict_list(self.attachments, keys, 'Attachment') | def _verify_attachments(self) | Verify that attachment values match the format expected by the
Postmark API. | 7.746423 | 3.746224 | 2.067795 |
'''Validate a list of `dict`, ensuring it has specific keys
and no others.
:param values: A list of `dict` to validate.
:param keys: A list of keys to validate each `dict` against.
:param name: Name describing the values, to show in error messages.
'''
keys = set... | def _verify_dict_list(self, values, keys, name) | Validate a list of `dict`, ensuring it has specific keys
and no others.
:param values: A list of `dict` to validate.
:param keys: A list of keys to validate each `dict` against.
:param name: Name describing the values, to show in error messages. | 3.281139 | 2.210437 | 1.484385 |
'''Retrieve raw email dump for this bounce.
:param sender: A :class:`BounceDump` object to get dump with.
Defaults to `None`.
:param \*\*kwargs: Keyword arguments passed to
:func:`requests.request`.
'''
if sender is None:
if self._sender is No... | def dump(self, sender=None, **kwargs) | Retrieve raw email dump for this bounce.
:param sender: A :class:`BounceDump` object to get dump with.
Defaults to `None`.
:param \*\*kwargs: Keyword arguments passed to
:func:`requests.request`. | 4.96622 | 2.296367 | 2.162642 |
'''Raise Postmark-specific HTTP errors. If there isn't one, the
standard HTTP error is raised.
HTTP 401 raises :class:`UnauthorizedError`
HTTP 422 raises :class:`UnprocessableEntityError`
HTTP 500 raises :class:`InternalServerError`
'''
if self.status_code == 4... | def raise_for_status(self) | Raise Postmark-specific HTTP errors. If there isn't one, the
standard HTTP error is raised.
HTTP 401 raises :class:`UnauthorizedError`
HTTP 422 raises :class:`UnprocessableEntityError`
HTTP 500 raises :class:`InternalServerError` | 2.885147 | 1.56487 | 1.843697 |
'''Inner :func:`requests.request` wrapper.
:param url: Endpoint url
:param \*\*kwargs: Keyword arguments to pass to
:func:`requests.request`.
'''
if self.method is None:
raise NotImplementedError('method must be defined on a subclass')
response = ... | def _request(self, url, **kwargs) | Inner :func:`requests.request` wrapper.
:param url: Endpoint url
:param \*\*kwargs: Keyword arguments to pass to
:func:`requests.request`. | 4.687335 | 2.930909 | 1.599277 |
'''Constructs Postmark API url
:param secure: Use the https Postmark API.
:param \*\*formatters: :func:`string.format` keyword arguments to
format the url with.
:rtype: Postmark API url
'''
if self.endpoint is None:
raise NotImplementedError('endp... | def _get_api_url(self, secure=None, **formatters) | Constructs Postmark API url
:param secure: Use the https Postmark API.
:param \*\*formatters: :func:`string.format` keyword arguments to
format the url with.
:rtype: Postmark API url | 3.593703 | 2.037618 | 1.763679 |
'''Constructs the headers to use for the request.
:param api_key: Your Postmark API key. Defaults to `None`.
:param test: Use the Postmark test API. Defaults to `self.test`.
:param request_args: Keyword args to pass to :func:`requests.request`.
Defaults to `None`.
:r... | def _get_headers(self, api_key=None, test=None, request_args=None) | Constructs the headers to use for the request.
:param api_key: Your Postmark API key. Defaults to `None`.
:param test: Use the Postmark test API. Defaults to `self.test`.
:param request_args: Keyword args to pass to :func:`requests.request`.
Defaults to `None`.
:rtype: `dict... | 2.5773 | 1.706861 | 1.509964 |
'''Send request to Postmark API.
Returns result of :func:`requests.post`.
:param message: Your Postmark message data.
:type message: `dict` or :class:`Message`
:param api_key: Your Postmark API key.
:type api_key: `str`
:param test: Make a test request to the Pos... | def send(self, message=None, api_key=None, secure=None, test=None,
**request_args) | Send request to Postmark API.
Returns result of :func:`requests.post`.
:param message: Your Postmark message data.
:type message: `dict` or :class:`Message`
:param api_key: Your Postmark API key.
:type api_key: `str`
:param test: Make a test request to the Postmark API.
... | 2.763617 | 1.590508 | 1.737569 |
'''Converts message to :class:`Message` and sets it on `self`'''
if message is None:
message = Message(verify=False)
if isinstance(message, Mapping):
message = Message.load_message(message)
self.message = message | def _load_initial_message(self, message=None) | Converts message to :class:`Message` and sets it on `self` | 5.898156 | 3.896265 | 1.513797 |
'''Convert message data to :class:`Message` if needed, and
merge with the default message.
:param message: Message to merge with the default message.
:rtype: :class:`Message`
'''
if message is None:
message = {}
if isinstance(message, Mapping):
... | def _cast_message(self, message=None) | Convert message data to :class:`Message` if needed, and
merge with the default message.
:param message: Message to merge with the default message.
:rtype: :class:`Message` | 5.266982 | 2.935725 | 1.794099 |
'''Updates message with default message paramaters.
:param message: Postmark message data
:type message: `dict`
:rtype: JSON encoded `unicode`
'''
message = self._cast_message(message=message)
return message.json() | def _get_request_content(self, message=None) | Updates message with default message paramaters.
:param message: Postmark message data
:type message: `dict`
:rtype: JSON encoded `unicode` | 13.757796 | 3.341637 | 4.117082 |
'''Send batch request to Postmark API.
Returns result of :func:`requests.post`.
:param messages: Batch messages to send to the Postmark API.
:type messages: A list of :class:`Message`
:param api_key: Your Postmark API key. Defaults to `self.api_key`.
:param test: Make a ... | def send(self, messages=None, api_key=None, secure=None, test=None,
**request_args) | Send batch request to Postmark API.
Returns result of :func:`requests.post`.
:param messages: Batch messages to send to the Postmark API.
:type messages: A list of :class:`Message`
:param api_key: Your Postmark API key. Defaults to `self.api_key`.
:param test: Make a test reques... | 3.189342 | 1.459659 | 2.184992 |
'''Updates all messages in message with default message
parameters.
:param message: A collection of Postmark message data
:type message: a collection of message `dict`s
:rtype: JSON encoded `str`
'''
if not message:
raise MessageError('No messages to ... | def _get_request_content(self, message=None) | Updates all messages in message with default message
parameters.
:param message: A collection of Postmark message data
:type message: a collection of message `dict`s
:rtype: JSON encoded `str` | 6.038711 | 2.922172 | 2.066515 |
'''Builds query string params from inputs. It handles offset and
count defaults and validation.
:param bounce_type: The type of bounces retrieve. See `bounce_types`
for a list of types, or read the Postmark API docs. Defaults to
`None`.
:param inactive: If `True`... | def get(self, bounce_type=None, inactive=None, email_filter=None,
message_id=None, count=None, offset=None, api_key=None,
secure=None, test=None, **request_args) | Builds query string params from inputs. It handles offset and
count defaults and validation.
:param bounce_type: The type of bounces retrieve. See `bounce_types`
for a list of types, or read the Postmark API docs. Defaults to
`None`.
:param inactive: If `True`, retrieves... | 2.899669 | 1.299622 | 2.231163 |
'''Makes request to :func:`Interface.request` and caches it.
:param url: endpoint url
:params \*\*kwargs: kwargs to pass to :func:`requests.request`
'''
response = super(Bounces, self)._request(url, **kwargs)
self._last_response = response
return response | def _request(self, url, **kwargs) | Makes request to :func:`Interface.request` and caches it.
:param url: endpoint url
:params \*\*kwargs: kwargs to pass to :func:`requests.request` | 6.608699 | 2.750303 | 2.402898 |
'''Builds query string params from inputs. It handles offset and
count defaults and validation.
:param bounce_type: The type of bounces retrieve. See `bounce_types`
for a list of types, or read the Postmark API docs. Defaults to
`None`.
:param inactive: If `True`... | def _construct_params(self, bounce_type=None, inactive=None,
email_filter=None, message_id=None, count=None,
offset=None) | Builds query string params from inputs. It handles offset and
count defaults and validation.
:param bounce_type: The type of bounces retrieve. See `bounce_types`
for a list of types, or read the Postmark API docs. Defaults to
`None`.
:param inactive: If `True`, retrieves... | 2.691952 | 1.506527 | 1.786859 |
'''Retrieves a single bounce's data.
:param bounce_id: A bounce's ID retrieved with :class:`Bounces`.
:param api_key: Your Postmark API key. Defaults to `self.api_key`.
:param secure: Use the https scheme for Postmark API.
Defaults to `self.secure`.
:param test: Make... | def get(self, bounce_id, api_key=None, secure=None, test=None,
**request_args) | Retrieves a single bounce's data.
:param bounce_id: A bounce's ID retrieved with :class:`Bounces`.
:param api_key: Your Postmark API key. Defaults to `self.api_key`.
:param secure: Use the https scheme for Postmark API.
Defaults to `self.secure`.
:param test: Make a test req... | 2.875015 | 1.507605 | 1.907008 |
def _create_app(**kwargs):
app = base_app(app_name, **app_kwargs)
app_created.send(_create_app, app=app)
debug = kwargs.get('debug')
if debug is not None:
app.debug = debug
# Load configuration
if config_loader:
config_loader(app, **kwar... | def create_app_factory(app_name, config_loader=None,
extension_entry_points=None, extensions=None,
blueprint_entry_points=None, blueprints=None,
converter_entry_points=None, converters=None,
wsgi_factory=None, **app_kwargs) | Create a Flask application factory.
The application factory will load Flask extensions and blueprints specified
using both entry points and directly in the arguments. Loading order of
entry points are not guaranteed and can happen in any order.
:param app_name: Flask application name.
:param confi... | 2.618922 | 2.61455 | 1.001672 |
def create_cli_app(info):
if create_app is None:
# Fallback to normal Flask behavior
info.create_app = None
app = info.load_app()
else:
app = create_app(debug=get_debug_flag())
return app
@click.group(cls=FlaskGroup, create_a... | def create_cli(create_app=None) | Create CLI for ``inveniomanage`` command.
:param create_app: Flask application factory.
:returns: Click command group.
.. versionadded: 1.0.0 | 4.43418 | 5.026303 | 0.882195 |
_loader(app, lambda ext: ext(app), entry_points=entry_points,
modules=modules) | def app_loader(app, entry_points=None, modules=None) | Run default application loader.
:param entry_points: List of entry points providing to Flask extensions.
:param modules: List of Flask extensions.
.. versionadded: 1.0.0 | 7.597785 | 10.198662 | 0.744979 |
url_prefixes = app.config.get('BLUEPRINTS_URL_PREFIXES', {})
def loader_init_func(bp_or_func):
bp = bp_or_func(app) if callable(bp_or_func) else bp_or_func
app.register_blueprint(bp, url_prefix=url_prefixes.get(bp.name))
_loader(app, loader_init_func, entry_points=entry_points, module... | def blueprint_loader(app, entry_points=None, modules=None) | Run default blueprint loader.
The value of any entry_point or module passed can be either an instance of
``flask.Blueprint`` or a callable accepting a ``flask.Flask`` application
instance as a single argument and returning an instance of
``flask.Blueprint``.
:param entry_points: List of entry poin... | 2.854355 | 3.389521 | 0.842112 |
if entry_points:
for entry_point in entry_points:
for ep in pkg_resources.iter_entry_points(entry_point):
try:
app.url_map.converters[ep.name] = ep.load()
except Exception:
app.logger.error(
'Fai... | def converter_loader(app, entry_points=None, modules=None) | Run default converter loader.
:param entry_points: List of entry points providing to Blue.
:param modules: Map of coverters.
.. versionadded: 1.0.0 | 2.412643 | 2.691056 | 0.896541 |
if entry_points:
for entry_point in entry_points:
for ep in pkg_resources.iter_entry_points(entry_point):
try:
init_func(ep.load())
except Exception:
app.logger.error(
'Failed to initialize entry... | def _loader(app, init_func, entry_points=None, modules=None) | Run generic loader.
Used to load and initialize entry points and modules using an custom
initialization function.
.. versionadded: 1.0.0 | 1.813274 | 1.948861 | 0.930427 |
configure_warnings()
# Create the Flask application instance
app = app_class(
import_name,
instance_path=instance_path,
instance_relative_config=instance_relative_config,
static_folder=static_folder,
static_url_path=static_url_path,
template_folder=templ... | def base_app(import_name, instance_path=None, static_folder=None,
static_url_path='/static', template_folder='templates',
instance_relative_config=True, app_class=Flask) | Invenio base application factory.
If the instance folder does not exists, it will be created.
:param import_name: The name of the application package.
:param env_prefix: Environment variable prefix.
:param instance_path: Instance path for Flask application.
:param static_folder: Static folder path... | 2.119509 | 2.343744 | 0.904326 |
if not sys.warnoptions:
# Route warnings through python logging
logging.captureWarnings(True)
# DeprecationWarning is by default hidden, hence we force the
# 'default' behavior on deprecation warnings which is not to hide
# errors.
warnings.simplefilter('default... | def configure_warnings() | Configure warnings by routing warnings to the logging system.
It also unhides ``DeprecationWarning``.
.. versionadded: 1.0.0 | 6.658804 | 6.69394 | 0.994751 |
app.config.from_object(Config)
app.config.update(**kwargs) | def config_loader(app, **kwargs) | Custom config loader. | 3.863451 | 3.426009 | 1.127683 |
project = pbclient.find_project(short_name=project_short_name,
all=self.all)
if (len(project) == 1):
return project[0]
else:
raise ProjectNotFound(project_short_name) | def get_project(self, project_short_name) | Return project object. | 3.644528 | 3.308738 | 1.101486 |
if self.project is None:
raise ProjectError
loader = create_tasks_loader(self.project.id, task_id,
state, json_file, self.all)
self.tasks = loader.load()
self._check_project_has_tasks()
self.tasks_df = dataframer.create_... | def get_tasks(self, task_id=None, state='completed', json_file=None) | Load all project Tasks. | 6.021589 | 5.580104 | 1.079118 |
if self.project is None:
raise ProjectError
loader = create_task_runs_loader(self.project.id, self.tasks,
json_file, self.all)
self.task_runs, self.task_runs_file = loader.load()
self._check_project_has_taskruns()
sel... | def get_task_runs(self, json_file=None) | Load all project Task Runs from Tasks. | 5.475428 | 5.151831 | 1.062812 |
return self.tasks_df.describe()
elif (element == 'task_runs'):
return self.task_runs_df.describe()
else:
return "ERROR: %s not found" % element | def describe(self, element): # pragma: no cover
if (element == 'tasks') | Return tasks or task_runs Panda describe. | 4.555176 | 3.748362 | 1.215244 |
x, y = rgb_to_xy(red, green, blue)
self.xy = [x, y] | def set_rgb(self, red, green, blue) | The red/green/blue color value of the light
This will be converted and set as the :attr:`xy` value | 3.865408 | 2.854033 | 1.354367 |
def create_wsgi(app, **kwargs):
mounts = {
mount: factory(**kwargs)
for mount, factory in mounts_factories.items()
}
return DispatcherMiddleware(app.wsgi_app, mounts)
return create_wsgi | def create_wsgi_factory(mounts_factories) | Create a WSGI application factory.
Usage example:
.. code-block:: python
wsgi_factory = create_wsgi_factory({'/api': create_api})
:param mounts_factories: Dictionary of mount points per application
factory.
.. versionadded:: 1.0.0 | 3.173566 | 3.724625 | 0.85205 |
def create_wsgi(app, **kwargs):
wsgi_app = factory(app, **kwargs) if factory else app.wsgi_app
if app.config.get('WSGI_PROXIES'):
return ProxyFix(wsgi_app, num_proxies=app.config['WSGI_PROXIES'])
return wsgi_app
return create_wsgi | def wsgi_proxyfix(factory=None) | Fix ``REMOTE_ADDR`` based on ``X-Forwarded-For`` headers.
.. note::
You must set ``WSGI_PROXIES`` to the correct number of proxies,
otherwise you application is susceptible to malicious attacks.
.. versionadded:: 1.0.0 | 2.581233 | 2.869521 | 0.899534 |
migrations = (re.match(MigrationFile.PATTERN, filename)
for filename in os.listdir(self.directory))
migrations = (MigrationFile(m.group('id'), m.group(0))
for m in migrations if m)
return sorted(migrations, key=lambda m: m.id) | def get_migration_files(self) | Find migrations files. | 3.723963 | 3.520183 | 1.057889 |
return [m for m in self.get_migration_files()
if not self.collection.find_one({'filename': m.filename})] | def get_unregistered_migrations(self) | Find unregistered migrations. | 5.868738 | 4.819904 | 1.217605 |
exists = os.path.exists(self.directory)
if not exists:
logger.error("No migrations directory found. Check your path or create a migration first.")
logger.error("Directory: %s" % self.directory)
return exists | def check_directory(self) | Check if migrations directory exists. | 5.583461 | 4.185681 | 1.333943 |
if not self.check_directory():
return
migrations = self.get_unregistered_migrations()
if migrations:
logger.info('Unregistered migrations:')
for migration in migrations:
logger.info(migration.filename)
else:
logger... | def show_status(self) | Show status of unregistered migrations | 4.499966 | 3.002256 | 1.498861 |
name = MigrationFile.normalize_name(name)
migrations = self.get_migration_files()
migration_id = migrations[-1].id if migrations else 0
migration_id += 1
return '{:04}_{}.py'.format(migration_id, name) | def get_new_filename(self, name) | Generate filename for new migration. | 4.307641 | 3.585989 | 1.201242 |
if not os.path.exists(self.directory):
os.makedirs(self.directory)
filename = self.get_new_filename(name)
with open(os.path.join(self.directory, filename), 'w') as fp:
fp.write("def up(db): pass\n\n\n")
fp.write("def down(db): pass\n")
lo... | def create(self, name) | Create a new empty migration. | 2.829988 | 2.366411 | 1.195899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.