text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(*filenames, **kwargs):
""" Read file contents into string. Used by setup.py to concatenate long_description. :param string filenames: Files to be read a... |
encoding = kwargs.get('encoding', 'utf-8')
sep = kwargs.get('sep', '\n')
buf = []
for filename in filenames:
if path.splitext(filename)[1] == ".md":
try:
import pypandoc
buf.append(pypandoc.convert_file(filename, 'rst'))
continue
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(cls, pid_type, pid_value, pid_provider=None, status=PIDStatus.NEW, object_type=None, object_uuid=None,):
"""Create a new persistent identifier with sp... |
try:
with db.session.begin_nested():
obj = cls(pid_type=pid_type,
pid_value=pid_value,
pid_provider=pid_provider,
status=status)
if object_type and object_uuid:
obj.assi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(cls, pid_type, pid_value, pid_provider=None):
"""Get persistent identifier. :param pid_type: Persistent identifier type. :param pid_value: Persistent ide... |
try:
args = dict(pid_type=pid_type, pid_value=six.text_type(pid_value))
if pid_provider:
args['pid_provider'] = pid_provider
return cls.query.filter_by(**args).one()
except NoResultFound:
raise PIDDoesNotExistError(pid_type, pid_value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_by_object(cls, pid_type, object_type, object_uuid):
"""Get a persistent identifier for a given object. :param pid_type: Persistent identifier type. :para... |
try:
return cls.query.filter_by(
pid_type=pid_type,
object_type=object_type,
object_uuid=object_uuid
).one()
except NoResultFound:
raise PIDDoesNotExistError(pid_type, None) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_assigned_object(self, object_type=None):
"""Return the current assigned object UUID. :param object_type: If it's specified, returns only if the PID objec... |
if object_type is not None:
if self.object_type == object_type:
return self.object_uuid
else:
return None
return self.object_uuid |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assign(self, object_type, object_uuid, overwrite=False):
"""Assign this persistent identifier to a given object. Note, the persistent identifier must first h... |
if self.is_deleted():
raise PIDInvalidAction(
"You cannot assign objects to a deleted/redirected persistent"
" identifier."
)
if not isinstance(object_uuid, uuid.UUID):
object_uuid = uuid.UUID(object_uuid)
if self.object_type... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unassign(self):
"""Unassign the registered object. Note: Only registered PIDs can be redirected so we set it back to registered. :returns: `True` if the PID ... |
if self.object_uuid is None and self.object_type is None:
return True
try:
with db.session.begin_nested():
if self.is_redirected():
db.session.delete(Redirect.query.get(self.object_uuid))
# Only registered PIDs can be redi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def redirect(self, pid):
"""Redirect persistent identifier to another persistent identifier. :param pid: The :class:`invenio_pidstore.models.PersistentIdentifier... |
if not (self.is_registered() or self.is_redirected()):
raise PIDInvalidAction("Persistent identifier is not registered.")
try:
with db.session.begin_nested():
if self.is_redirected():
r = Redirect.query.get(self.object_uuid)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reserve(self):
"""Reserve the persistent identifier. Note, the reserve method may be called multiple times, even if it was already reserved. :raises: :exc:`i... |
if not (self.is_new() or self.is_reserved()):
raise PIDInvalidAction(
"Persistent identifier is not new or reserved.")
try:
with db.session.begin_nested():
self.status = PIDStatus.RESERVED
db.session.add(self)
except SQLAl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(self):
"""Register the persistent identifier with the provider. :raises invenio_pidstore.errors.PIDInvalidAction: If the PID is not already register... |
if self.is_registered() or self.is_deleted() or self.is_redirected():
raise PIDInvalidAction(
"Persistent identifier has already been registered"
" or is deleted.")
try:
with db.session.begin_nested():
self.status = PIDStatus.REGI... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self):
"""Delete the persistent identifier. If the persistent identifier haven't been registered yet, it is removed from the database. Otherwise, it's... |
removed = False
try:
with db.session.begin_nested():
if self.is_new():
# New persistent identifier which haven't been registered
# yet.
db.session.delete(self)
removed = True
else... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sync_status(self, status):
"""Synchronize persistent identifier status. Used when the provider uses an external service, which might have been modified outsi... |
if self.status == status:
return True
try:
with db.session.begin_nested():
self.status = status
db.session.add(self)
except SQLAlchemyError:
logger.exception("Failed to sync status {0}.".format(status),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def next(cls):
"""Return next available record identifier.""" |
try:
with db.session.begin_nested():
obj = cls()
db.session.add(obj)
except IntegrityError: # pragma: no cover
with db.session.begin_nested():
# Someone has likely modified the table without using the
# models API.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def max(cls):
"""Get max record identifier.""" |
max_recid = db.session.query(func.max(cls.recid)).scalar()
return max_recid if max_recid else 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_sequence(cls, val):
"""Internal function to reset sequence to specific value. Note: this function is for PostgreSQL compatibility. :param val: The value... |
if db.engine.dialect.name == 'postgresql': # pragma: no cover
db.session.execute(
"SELECT setval(pg_get_serial_sequence("
"'{0}', 'recid'), :newval)".format(
cls.__tablename__), dict(newval=val)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def insert(cls, val):
"""Insert a record identifier. :param val: The `recid` column value to insert. """ |
with db.session.begin_nested():
obj = cls(recid=val)
db.session.add(obj)
cls._set_sequence(cls.max()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve(self, pid_value):
"""Resolve a persistent identifier to an internal object. :param pid_value: Persistent identifier. :returns: A tuple containing (pi... |
pid = PersistentIdentifier.get(self.pid_type, pid_value)
if pid.is_new() or pid.is_reserved():
raise PIDUnregistered(pid)
if pid.is_deleted():
obj_id = pid.get_assigned_object(object_type=self.object_type)
try:
obj = self.object_getter(obj_i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_sheet(self, title):
""" Create a sheet with the given title. This does not check if another sheet by the same name already exists. """ |
ws = self.conn.sheets_service.AddWorksheet(title, 10, 10, self.id)
self._wsf = None
return Sheet(self, ws) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open(cls, title, conn=None, google_user=None, google_password=None):
""" Open the spreadsheet named ``title``. If no spreadsheet with that name exists, a new... |
spreadsheet = cls.by_title(title, conn=conn, google_user=google_user,
google_password=google_password)
if spreadsheet is None:
spreadsheet = cls.create(title, conn=conn, google_user=google_user,
google_password=google_p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(cls, title, conn=None, google_user=None, google_password=None):
""" Create a new spreadsheet with the given ``title``. """ |
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, conn, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 b... |
conn = Connection.connect(conn=conn, google_user=google_user,
google_password=google_password)
return cls(id=id, conn=conn) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 se... |
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.text == t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_common(app):
"""Post initialization.""" |
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.reg... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_ui(state):
"""Post initialization for UI application.""" |
app = state.app
init_common(app)
# Register blueprint for templates
app.register_blueprint(
blueprint, url_prefix=app.config['USERPROFILES_PROFILE_URL']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def profile():
"""View for editing a profile.""" |
# 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':
handl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def profile_form_factory():
"""Create a profile form.""" |
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,
pre... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_verification_form(form):
"""Handle email sending verification form.""" |
form.process(formdata=request.form)
if form.validate_on_submit():
send_confirmation_instructions(current_user)
# NOTE: Flash message.
flash(_("Verification email sent."), category="success") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_profile_form(form):
"""Handle profile update form.""" |
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.ses... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_errors(self, data):
"""Check for errors on data payload.""" |
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 False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_text(self, text):
"""Send text message to telegram user. Text message should be markdown formatted. :param text: markdown formatted text. :return: statu... |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_figure(self, fig, caption=''):
"""Render matplotlib figure into temporary bytes buffer and then send it to telegram user. :param fig: matplotlib figure ... |
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, filenam... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prune_clusters(clusters, index, n=3):
""" Delete clusters with fewer than n elements. """ |
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:
del... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def monitor(self, field, callback, poll_interval=None):
""" Monitor `field` for change Will monitor ``field`` for change and execute ``callback`` when change is ... |
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_pool,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_form_factory(Form):
"""Factory for creating an extended user registration form.""" |
class CsrfDisabledProfileForm(ProfileForm):
"""Subclass of ProfileForm to disable CSRF token in the inner form.
This class will always be a inner form field of the parent class
`Form`. The parent will add/remove the CSRF token in the form.
"""
def __init__(self, *args, **k... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def confirm_register_form_factory(Form):
"""Factory for creating a confirm register form.""" |
class CsrfDisabledProfileForm(ProfileForm):
"""Subclass of ProfileForm to disable CSRF token in the inner form.
This class will always be a inner form field of the parent class
`Form`. The parent will add/remove the CSRF token in the form.
"""
def __init__(self, *args, **k... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ha... |
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_enab... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_username(form, field):
"""Wrap username validator for WTForms.""" |
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 != user_prof... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter_pages(pages, pagenum, pagename):
""" Choices pages by pagenum and pagename """ |
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 fou... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def export_img(visio_filename, image_filename, pagenum=None, pagename=None):
""" Exports images from visio file """ |
# 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_pages(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_options(args):
""" Parses command line options """ |
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='store'... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(args=sys.argv[1:]):
""" main funcion of visio2img """ |
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.stderr.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_custom_providers():
"""Imports providers classes by paths given in SITEMETRICS_PROVIDERS setting.""" |
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])
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __query(cls, url):
"""Reads a URL""" |
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:
_, exception,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __query_cmd(self, command, device=None):
"""Calls a command""" |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_sid(self):
"""Returns a valid SID""" |
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 as exc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def switch_onoff(self, device, status):
"""Switch a Socket""" |
if status == 1 or status == True or status == '1':
return self.switch_on(device)
else:
return self.switch_off(device) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def switch_toggle(self, device):
"""Toggles the current state of the given device""" |
state = self.get_state(device)
if(state == '1'):
return self.switch_off(device)
elif(state == '0'):
return self.switch_on(device)
else:
return state |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_power(self):
"""Returns the Power in Watt""" |
power_dict = self.get_power_all()
for device in power_dict.keys():
power_dict[device] = float(power_dict[device]) / 1000.0
return power_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_device_names(self):
"""Returns a Dict with devicenames""" |
dev_names = {}
for device in self.get_device_ids():
dev_names[device] = self.get_device_name(device)
return dev_names |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_power_all(self):
"""Returns the power in mW for all devices""" |
power_dict = {}
for device in self.get_device_names().keys():
power_dict[device] = self.get_power_single(device)
return power_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_state_all(self):
"""Returns all device states""" |
state_dict = {}
for device in self.get_device_names().keys():
state_dict[device] = self.get_state(device)
return state_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_entrypoints(entry_point):
"""List defined entry points.""" |
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
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def migrate_secret_key(old_key):
"""Call entry points exposed for the SECRET_KEY change.""" |
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)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_secret_key():
"""Generate secret key.""" |
import string
import random
rng = random.SystemRandom()
return ''.join(
rng.choice(string.ascii_letters + string.digits)
for dummy in range(0, 256)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_provider_choices():
"""Returns a list of currently available metrics providers suitable for use as model fields choices. """ |
choices = []
for provider in METRICS_PROVIDERS:
choices.append((provider.alias, provider.title))
return choices |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 AP... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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`.
:par... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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`
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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: Us... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def data(self):
'''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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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.
'''
if self.headers is None:
self.headers = []
self.headers.append(dict(Name=name, Value=value)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def recipients(self):
'''A list of all recipients for this message.
'''
cc = self._cc or []
bcc = self._bcc or []
return self._to + cc + bcc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _detect_content_type(self, filename):
'''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 ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _verify_attachments(self):
'''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') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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`.
'''
if sender is ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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`
'''
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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
'''
if self.endpoint i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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`
'''
message = self._cast_message(message=message)
return message.json() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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`
'''
if not message:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 htt... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_app_factory(app_name, config_loader=None, extension_entry_points=None, extensions=None, blueprint_entry_points=None, blueprints=None, converter_entry_p... |
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, **kwargs)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_cli(create_app=None):
"""Create CLI for ``inveniomanage`` command. :param create_app: Flask application factory. :returns: Click command group. .. ver... |
def create_cli_app(info):
"""Application factory for CLI app.
Internal function for creating the CLI. When invoked via
``inveniomanage`` FLASK_APP must be set.
"""
if create_app is None:
# Fallback to normal Flask behavior
info.create_app = None
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def app_loader(app, entry_points=None, modules=None):
"""Run default application loader. :param entry_points: List of entry points providing to Flask extensions.... |
_loader(app, lambda ext: ext(app), entry_points=entry_points,
modules=modules) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 insta... |
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, modules=mo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def converter_loader(app, entry_points=None, modules=None):
"""Run default converter loader. :param entry_points: List of entry points providing to Blue. :param ... |
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(
'Failed ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 initial... |
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 poi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def base_app(import_name, instance_path=None, static_folder=None, static_url_path='/static', template_folder='templates', instance_relative_config=True, app_class... |
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=template_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure_warnings():
"""Configure warnings by routing warnings to the logging system. It also unhides ``DeprecationWarning``. .. versionadded: 1.0.0 """ |
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', D... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def config_loader(app, **kwargs):
"""Custom config loader.""" |
app.config.from_object(Config)
app.config.update(**kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_project(self, project_short_name):
"""Return project object.""" |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_tasks(self, task_id=None, state='completed', json_file=None):
"""Load all project Tasks.""" |
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_data_fra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_task_runs(self, json_file=None):
"""Load all project Task Runs from Tasks.""" |
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()
self.task_r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def describe(self, element):
# pragma: no cover """Return tasks or task_runs Panda describe.""" |
if (element == 'tasks'):
return self.tasks_df.describe()
elif (element == 'task_runs'):
return self.task_runs_df.describe()
else:
return "ERROR: %s not found" % element |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_wsgi_factory(mounts_factories):
"""Create a WSGI application factory. Usage example: .. code-block:: python wsgi_factory = create_wsgi_factory({'/api'... |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 pr... |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_migration_files(self):
"""Find migrations files.""" |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_unregistered_migrations(self):
"""Find unregistered migrations.""" |
return [m for m in self.get_migration_files()
if not self.collection.find_one({'filename': m.filename})] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_directory(self):
"""Check if migrations directory exists.""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_status(self):
"""Show status of unregistered migrations""" |
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.info(se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_new_filename(self, name):
"""Generate filename for new migration.""" |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self, name):
"""Create a new empty migration.""" |
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")
logger.inf... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_migration_file(self, filename):
"""Load migration file as module.""" |
path = os.path.join(self.directory, filename)
# spec = spec_from_file_location("migration", path)
# module = module_from_spec(spec)
# spec.loader.exec_module(module)
module = imp.load_source("migration", path)
return module |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_migrations_to_up(self, migration_id=None):
"""Find migrations to execute.""" |
if migration_id is not None:
migration_id = MigrationFile.validate_id(migration_id)
if not migration_id:
return []
migrations = self.get_unregistered_migrations()
if not migrations:
logger.info(self.NO_MIGRATIONS_MSG)
return []
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.