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 activate_version(self, service_id, version_number):
"""Activate the current version.""" |
content = self._fetch("/service/%s/version/%d/activate" % (service_id, version_number), method="PUT")
return FastlyVersion(self, content) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deactivate_version(self, service_id, version_number):
"""Deactivate the current version.""" |
content = self._fetch("/service/%s/version/%d/deactivate" % (service_id, version_number), method="PUT")
return FastlyVersion(self, content) |
<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_version(self, service_id, version_number):
"""Validate the version for a particular service and version.""" |
content = self._fetch("/service/%s/version/%d/validate" % (service_id, version_number))
return self._status(content) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lock_version(self, service_id, version_number):
"""Locks the specified version.""" |
content = self._fetch("/service/%s/version/%d/lock" % (service_id, version_number))
return self._status(content) |
<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_wordpressess(self, service_id, version_number):
"""Get all of the wordpresses for a specified service and version.""" |
content = self._fetch("/service/%s/version/%d/wordpress" % (service_id, version_number))
return map(lambda x: FastlyWordpress(self, x), content) |
<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_wordpress(self, service_id, version_number, name, path, comment=None):
"""Create a wordpress for the specified service and version.""" |
body = self._formdata({
"name": name,
"path": path,
"comment": comment,
}, FastlyWordpress.FIELDS)
content = self._fetch("/service/%s/version/%d/wordpress" % (service_id, version_number), method="POST", body=body)
return FastlyWordpress(self, content) |
<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_wordpress(self, service_id, version_number, name):
"""Get information on a specific wordpress.""" |
content = self._fetch("/service/%s/version/%d/wordpress/%s" % (service_id, version_number, name))
return FastlyWordpress(self, content) |
<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_wordpress(self, service_id, version_number, name_key, **kwargs):
"""Update a specified wordpress.""" |
body = self._formdata(kwargs, FastlyWordpress.FIELDS)
content = self._fetch("/service/%s/version/%d/wordpress/%s" % (service_id, version_number, name_key), method="PUT", body=body)
return FastlyWordpress(self, content) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def annotate(self, word):
'''Annotate 'word' for syllabification, stress, weights, and vowels.'''
info = [] # e.g., [ ('\'nak.su.`tus.ta', 'PUSU', 'HLHL', 'AUUA'), ]
for syllabification, _ in syllabify(self.normalize(word), stress=True):
stresses = ''
weights = ''
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serotype_escherichia(self):
""" Create attributes storing the best results for the O and H types """ |
for sample in self.runmetadata.samples:
# Initialise negative results to be overwritten when necessary
sample[self.analysistype].best_o_pid = '-'
sample[self.analysistype].o_genes = ['-']
sample[self.analysistype].o_set = ['-']
sample[self.analysistyp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gene_names(self):
""" Extract the names of the user-supplied targets """ |
# Iterate through all the target names in the formatted targets file
for record in SeqIO.parse(self.targets, 'fasta'):
# Append all the gene names to the list of names
self.genes.append(record.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 report(self):
""" Create the report for the user-supplied targets """ |
# Add all the genes to the header
header = 'Sample,'
data = str()
with open(os.path.join(self.reportpath, '{at}.csv'.format(at=self.analysistype)), 'w') as report:
write_header = True
for sample in self.runmetadata:
data += sample.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 on_add(self, item):
"""Convert to pseuso acces""" |
super(Tels, self).on_add(list_views.PseudoAccesCategorie(item)) |
<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_data(self, *args):
"""we cant to call set_data to manually update""" |
db = self.begining.get_data() or formats.DATE_DEFAULT
df = self.end.get_data() or formats.DATE_DEFAULT
jours = max((df - db).days + 1, 0)
self.setText(str(jours) + (jours >= 2 and " jours" or " jour")) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def same_syllabic_feature(ch1, ch2):
'''Return True if ch1 and ch2 are both vowels or both consonants.'''
if ch1 == '.' or ch2 == '.':
return False
ch1 = 'V' if ch1 in VOWELS else 'C' if ch1 in CONSONANTS else None
ch2 = 'V' if ch2 in VOWELS else 'C' if ch2 in CONSONANTS else None
return c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modifie(self, key: str, value: Any) -> None: """Store the modification. `value` should be dumped in DB compatible format.""" |
if key in self.FIELDS_OPTIONS:
self.modifie_options(key, value)
else:
self.modifications[key] = 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 modifie_many(self, dic: dict):
"""Convenience function which calls modifie on each element of dic""" |
for i, v in dic.items():
self.modifie(i, v) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modifie_options(self, field_option, value):
"""Set options in modifications. All options will be stored since it should be grouped in the DB.""" |
options = dict(self["options"] or {}, **{field_option: value})
self.modifications["options"] = options |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _from_list_dict(cls, list_dic):
"""Takes a list of dict like objects and uses `champ_id` field as Id""" |
return cls({_convert_id(dic[cls.CHAMP_ID]): dict(dic) for dic in list_dic}) |
<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_recherche_rapide(self, base, pattern, to_string_hook=None):
""" Return a collection of access matching `pattern`. `to_string_hook` is an optionnal calla... |
Ac = self.ACCES
if pattern == "*":
return groups.Collection(Ac(base, i) for i in self)
if len(pattern) >= MIN_CHAR_SEARCH: # Needed chars.
sub_patterns = pattern.split(" ")
try:
regexps = tuple(re.compile(sub_pattern, flags=re.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 select_by_field(self, base, field, value):
"""Return collection of acces whose field equal value""" |
Ac = self.ACCES
return groups.Collection(Ac(base, i) for i, row in self.items() if row[field] == 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 load_from_db(cls, callback_etat=print, out=None):
"""Launch data fetching then load data received. The method _load_remote_db should be overridden. If out is... |
dic = cls._load_remote_db(callback_etat)
callback_etat("Chargement...", 2, 3)
if out is None:
return cls(dic)
cls.__init__(out, datas=dic) |
<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_from_local(cls):
"""Load datas from local file.""" |
try:
with open(cls.LOCAL_DB_PATH, 'rb') as f:
b = f.read()
s = security.protege_data(b, False)
except (FileNotFoundError, KeyError):
logging.exception(cls.__name__)
raise StructureError(
"Erreur dans le chargement de la... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dumps(self):
"""Return a dictionnary of current tables""" |
return {table_name: getattr(self, table_name).dumps() for table_name in self.TABLES} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_to_local(self, callback_etat=print):
""" Saved current in memory base to local file. It's a backup, not a convenient way to update datas :param callback... |
callback_etat("Aquisition...", 0, 3)
d = self.dumps()
s = json.dumps(d, indent=4, cls=formats.JsonEncoder)
callback_etat("Chiffrement...", 1, 3)
s = security.protege_data(s, True)
callback_etat("Enregistrement...", 2, 3)
try:
with open(self.LOCAL_DB_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 read_cell(self, x, y):
""" reads the cell at position x and y; puts the default styles in xlwt """ |
cell = self._sheet.row(x)[y]
if self._file.xf_list[
cell.xf_index].background.pattern_colour_index == 64:
self._file.xf_list[
cell.xf_index].background.pattern_colour_index = 9
if self._file.xf_list[
cell.xf_index].background.pattern_colour_in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_cell(self, x, y, value, style=None):
""" writing style and value in the cell of x and y position """ |
if isinstance(style, str):
style = self.xlwt.easyxf(style)
if style:
self._sheet.write(x, y, label=value, style=style)
else:
self._sheet.write(x, y, label=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_string(string):
""" This function checks if a path was given as string, and tries to read the file and return the string. """ |
truestring = string
if string is not None:
if '/' in string:
if os.path.isfile(string):
try:
with open_(string,'r') as f:
truestring = ' '.join(line.strip() for line in f)
except: pass
if truestring.strip() == '': truestring = 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_arguments(options):
""" This function handles and validates the wrapper arguments. """ |
# These the next couple of lines defines the header of the Help output
parser = ArgumentParser(
formatter_class=RawDescriptionHelpFormatter,
usage=("""%(prog)s
--------------------------------------------------------------------------------
"""),
description=("""
Service Wrapper
===============... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_file_list(upload_path):
""" This function returns list of files in the given dir """ |
newlist = []
for el in sorted(os.listdir(upload_path)):
if ' ' in el:
raise Exception('Error: Spaces are not allowed in file names!\n')
newlist.append(os.path.normpath(upload_path+'/'+el))
debug.log('InputFiles: %s\n'%newlist)
return newlist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def date_decoder(dic):
"""Add python types decoding. See JsonEncoder""" |
if '__date__' in dic:
try:
d = datetime.date(**{c: v for c, v in dic.items() if not c == "__date__"})
except (TypeError, ValueError):
raise json.JSONDecodeError("Corrupted date format !", str(dic), 1)
elif '__datetime__' in dic:
try:
d = datetime.date... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _type_string(label, case=None):
"""Shortcut for string like fields""" |
return label, abstractSearch.in_string, lambda s: abstractRender.default(s, case=case), "" |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _type_bool(label,default=False):
"""Shortcut fot boolean like fields""" |
return label, abstractSearch.nothing, abstractRender.boolen, default |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def in_string(objet, pattern):
""" abstractSearch dans une chaine, sans tenir compte de la casse. """ |
return bool(re.search(pattern, str(objet), flags=re.I)) if objet else 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 in_date(objet, pattern):
""" abstractSearch dans une date datetime.date""" |
if objet:
pattern = re.sub(" ", '', pattern)
objet_str = abstractRender.date(objet)
return bool(re.search(pattern, objet_str))
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 date(objet):
""" abstractRender d'une date datetime.date""" |
if objet:
return "{}/{}/{}".format(objet.day, objet.month, objet.year)
return "" |
<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_available_languages(domain):
"""Lists the available languages for the given translation domain. :param domain: the domain to get languages for """ |
if domain in _AVAILABLE_LANGUAGES:
return copy.copy(_AVAILABLE_LANGUAGES[domain])
localedir = '%s_LOCALEDIR' % domain.upper()
find = lambda x: gettext.find(domain,
localedir=os.environ.get(localedir),
languages=[x])
# NOTE(mr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def translate(obj, desired_locale=None):
"""Gets the translated unicode representation of the given object. If the object is not translatable it is returned as-i... |
message = obj
if not isinstance(message, Message):
# If the object to translate is not already translatable,
# let's first get its unicode representation
message = six.text_type(obj)
if isinstance(message, Message):
# Even after unicoding() we still need to check if we are
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _translate_args(args, desired_locale=None):
"""Translates all the translatable elements of the given arguments object. This method is used for translating th... |
if isinstance(args, tuple):
return tuple(translate(v, desired_locale) for v in args)
if isinstance(args, dict):
translated_dict = {}
for (k, v) in six.iteritems(args):
translated_v = translate(v, desired_locale)
translated_dict[k] = translated_v
return tr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def translate(self, desired_locale=None):
"""Translate this message to the desired locale. :param desired_locale: The desired locale to translate the message to,... |
translated_message = Message._translate_msgid(self.msgid,
self.domain,
desired_locale)
if self.params is None:
# No need for more translation
return translated_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 _sanitize_mod_params(self, other):
"""Sanitize the object being modded with this Message. - Add support for modding 'None' so translation supports it - Trim ... |
if other is None:
params = (other,)
elif isinstance(other, dict):
params = self._trim_dictionary_parameters(other)
else:
params = self._copy_param(other)
return params |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _trim_dictionary_parameters(self, dict_param):
"""Return a dict that only has matching entries in the msgid.""" |
# NOTE(luisg): Here we trim down the dictionary passed as parameters
# to avoid carrying a lot of unnecessary weight around in the message
# object, for example if someone passes in Message() % locals() but
# only some params are used, and additionally we prevent errors for
# no... |
<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_ordering_for_column(self, column, direction):
""" Returns a tuple of lookups to order by for the given column and direction. Direction is an integer, eit... |
if direction == 0:
return ()
if column in self.orderings:
ordering = self.orderings[column]
else:
field = self.get_field(column)
if field is None:
return ()
ordering = column
if not isinstance(ordering, (tuple, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def model_to_json(self, object, cleanup=True):
"""Take a model instance and return it as a json struct""" |
model_name = type(object).__name__
if model_name not in self.swagger_dict['definitions']:
raise ValidationError("Swagger spec has no definition for model %s" % model_name)
model_def = self.swagger_dict['definitions'][model_name]
log.debug("Marshalling %s into json" % model_n... |
<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(self, model_name, object):
"""Validate an object against its swagger model""" |
if model_name not in self.swagger_dict['definitions']:
raise ValidationError("Swagger spec has no definition for model %s" % model_name)
model_def = self.swagger_dict['definitions'][model_name]
log.debug("Validating %s" % model_name)
return validate_schema_object(self.spec, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call_on_each_endpoint(self, callback):
"""Find all server endpoints defined in the swagger spec and calls 'callback' for each, with an instance of EndpointDa... |
if 'paths' not in self.swagger_dict:
return
for path, d in list(self.swagger_dict['paths'].items()):
for method, op_spec in list(d.items()):
data = EndpointData(path, method)
# Which server method handles this endpoint?
if 'x-bi... |
<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=None):
"""Buffer stdin and flush, and avoid incomplete files.""" |
parser = argparse.ArgumentParser(description=main.__doc__)
parser.add_argument(
'--binary',
dest='mode',
action='store_const',
const="wb",
default="w",
help='write in binary mode')
parser.add_argument(
'output', metavar='FILE', type=unicode, help='Out... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def basic_c_defines(
layout,
keyboard_prefix="KEY_",
led_prefix="LED_",
sysctrl_prefix="SYS_",
cons_prefix="CONS_",
code_suffix=True,
all_caps=True,
space_char="_"
):
'''
Generates a list of C defines that can be used to generate a header file
@param layout: Layout object
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new_email_marketing_campaign(self, name, email_content, from_email, from_name, reply_to_email, subject, text_content, address, is_view_as_webpage_enabled=Fals... |
url = self.api.join(self.EMAIL_MARKETING_CAMPAIGN_URL)
inlined_email_content = self.inline_css(email_content)
minified_email_content = html_minify(inlined_email_content)
worked_around_email_content = work_around(minified_email_content)
data = {
'name': 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 update_email_marketing_campaign(self, email_marketing_campaign, name, email_content, from_email, from_name, reply_to_email, subject, text_content, address, is... |
url = self.api.join(
'/'.join([self.EMAIL_MARKETING_CAMPAIGN_URL,
str(email_marketing_campaign.constant_contact_id)]))
inlined_email_content = self.inline_css(email_content)
minified_email_content = html_minify(inlined_email_content)
worked_around_emai... |
<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_email_marketing_campaign(self, email_marketing_campaign):
"""Deletes a Constant Contact email marketing campaign. """ |
url = self.api.join('/'.join([
self.EMAIL_MARKETING_CAMPAIGN_URL,
str(email_marketing_campaign.constant_contact_id)]))
response = url.delete()
self.handle_response_status(response)
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inline_css(self, html):
"""Inlines CSS defined in external style sheets. """ |
premailer = Premailer(html)
inlined_html = premailer.transform(pretty_print=True)
return inlined_html |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def preview_email_marketing_campaign(self, email_marketing_campaign):
"""Returns HTML and text previews of an EmailMarketingCampaign. """ |
url = self.api.join('/'.join([
self.EMAIL_MARKETING_CAMPAIGN_URL,
str(email_marketing_campaign.constant_contact_id),
'preview']))
response = url.get()
self.handle_response_status(response)
return (response.json()['preview_email_content'],
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pre_save(cls, sender, instance, *args, **kwargs):
"""Pull constant_contact_id out of data. """ |
instance.constant_contact_id = str(instance.data['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 pre_delete(cls, sender, instance, *args, **kwargs):
"""Deletes the CC email marketing campaign associated with me. """ |
cc = ConstantContact()
response = cc.delete_email_marketing_campaign(instance)
response.raise_for_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 send_email(recipients, subject, text_content=None, html_content=None, from_email=None, use_base_template=True, category=None, fail_silently=False, language=No... |
from django.conf import settings
if not bypass_queue and hasattr(settings, 'MAILING_USE_CELERY') and settings.MAILING_USE_CELERY:
from celery.execute import send_task
return send_task('mailing.queue_send_email',[recipients, subject, text_content, html_content, from_email, use_base_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 initialize_connections(self, scopefunc=None):
""" Initialize a database connection by each connection string defined in the configuration file """ |
for connection_name, connection_string in\
self.app.config['FLASK_PHILO_SQLALCHEMY'].items():
engine = create_engine(connection_string)
session = scoped_session(sessionmaker(), scopefunc=scopefunc)
session.configure(bind=engine)
self.connections[c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def index_from_id(self,Id):
"""Return the row of given Id if it'exists, otherwise None. Only works with pseudo-acces""" |
try:
return [a.Id for a in self].index(Id)
except IndexError:
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def append(self, acces, **kwargs):
"""Append acces to list. Quite slow since it checks uniqueness. kwargs may set `info` for this acces. """ |
if acces.Id in set(ac.Id for ac in self):
raise ValueError("Acces id already in list !")
list.append(self, acces)
if kwargs:
self.infos[acces.Id] = 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 remove_id(self,key):
"""Suppress acces with id = key""" |
self.infos.pop(key, "")
new_l = [a for a in self if not (a.Id == key)]
list.__init__(self, new_l) |
<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_info(self, key=None, Id=None) -> dict: """Returns information associated with Id or list index""" |
if key is not None:
Id = self[key].Id
return self.infos.get(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 extend(self, collection):
"""Merges collections. Ensure uniqueness of ids""" |
l_ids = set([a.Id for a in self])
for acces in collection:
if not acces.Id in l_ids:
list.append(self,acces)
info = collection.get_info(Id=acces.Id)
if info:
self.infos[acces.Id] = info |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def isotime(at=None, subsecond=False):
"""Stringify time in ISO 8601 format.""" |
if not at:
at = utcnow()
st = at.strftime(_ISO8601_TIME_FORMAT
if not subsecond
else _ISO8601_TIME_FORMAT_SUBSECOND)
tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC'
st += ('Z' if tz == 'UTC' else tz)
return st |
<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_isotime(timestr):
"""Parse time from ISO 8601 format.""" |
try:
return iso8601.parse_date(timestr)
except iso8601.ParseError as e:
raise ValueError(six.text_type(e))
except TypeError as e:
raise ValueError(six.text_type(e)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def strtime(at=None, fmt=PERFECT_TIME_FORMAT):
"""Returns formatted utcnow.""" |
if not at:
at = utcnow()
return at.strftime(fmt) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalize_time(timestamp):
"""Normalize time in arbitrary timezone to UTC naive object.""" |
offset = timestamp.utcoffset()
if offset is None:
return timestamp
return timestamp.replace(tzinfo=None) - offset |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_older_than(before, seconds):
"""Return True if before is older than seconds.""" |
if isinstance(before, six.string_types):
before = parse_strtime(before).replace(tzinfo=None)
else:
before = before.replace(tzinfo=None)
return utcnow() - before > datetime.timedelta(seconds=seconds) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_newer_than(after, seconds):
"""Return True if after is newer than seconds.""" |
if isinstance(after, six.string_types):
after = parse_strtime(after).replace(tzinfo=None)
else:
after = after.replace(tzinfo=None)
return after - utcnow() > datetime.timedelta(seconds=seconds) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def utcnow_ts():
"""Timestamp version of our utcnow function.""" |
if utcnow.override_time is None:
# NOTE(kgriffs): This is several times faster
# than going through calendar.timegm(...)
return int(time.time())
return calendar.timegm(utcnow().timetuple()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def utcnow():
"""Overridable version of utils.utcnow.""" |
if utcnow.override_time:
try:
return utcnow.override_time.pop(0)
except AttributeError:
return utcnow.override_time
return datetime.datetime.utcnow() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def advance_time_delta(timedelta):
"""Advance overridden time using a datetime.timedelta.""" |
assert(utcnow.override_time is not None)
try:
for dt in utcnow.override_time:
dt += timedelta
except TypeError:
utcnow.override_time += timedelta |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def marshall_now(now=None):
"""Make an rpc-safe datetime with microseconds. Note: tzinfo is stripped, but not required for relative times. """ |
if not now:
now = utcnow()
return dict(day=now.day, month=now.month, year=now.year, hour=now.hour,
minute=now.minute, second=now.second,
microsecond=now.microsecond) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unmarshall_time(tyme):
"""Unmarshall a datetime dict.""" |
return datetime.datetime(day=tyme['day'],
month=tyme['month'],
year=tyme['year'],
hour=tyme['hour'],
minute=tyme['minute'],
second=tyme['second'],
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def total_seconds(delta):
"""Return the total seconds of datetime.timedelta object. Compute total seconds of datetime.timedelta, datetime.timedelta doesn't have ... |
try:
return delta.total_seconds()
except AttributeError:
return ((delta.days * 24 * 3600) + delta.seconds +
float(delta.microseconds) / (10 ** 6)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_soon(dt, window):
"""Determines if time is going to happen in the next window seconds. :params dt: the time :params window: minimum seconds to remain to c... |
soon = (utcnow() + datetime.timedelta(seconds=window))
return normalize_time(dt) <= soon |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _build_install_args(options):
'''
Build the arguments to 'python setup.py install' on the setuptools package
'''
install_args = []
if options.user_install:
if sys.version_info < (2, 6):
log.warn('--user requires Python 2.6 or later')
raise SystemExit(1)
in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(name, value):
"""Temporarily change or set the environment variable during the execution of a function. Args: name: The name of the environment variabl... |
def wrapped(func):
@functools.wraps(func)
def _decorator(*args, **kwargs):
existing_env = core.read(name, allow_none=True)
core.write(name, value)
func_val = func(*args, **kwargs)
core.write(name, existing_env)
return func_val
retu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def isset(name):
"""Only execute the function if the variable is set. Args: name: The name of the environment variable Returns: The function return value or `Non... |
def wrapped(func):
@functools.wraps(func)
def _decorator(*args, **kwargs):
if core.isset(name):
return func(*args, **kwargs)
return _decorator
return wrapped |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bool(name, execute_bool=True, default=None):
"""Only execute the function if the boolean variable is set. Args: name: The name of the environment variable ex... |
def wrapped(func):
@functools.wraps(func)
def _decorator(*args, **kwargs):
if core.isset(name) and core.bool(name) == execute_bool:
return func(*args, **kwargs)
elif default is not None and default == execute_bool:
return func(*args, **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 flags(self, index: QModelIndex):
"""All fields are selectable""" |
if self.IS_EDITABLE and self.header[index.column()] in self.EDITABLE_FIELDS:
return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable
else:
return super().flags(index) | Qt.ItemIsSelectable |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sort(self, section: int, order=None):
"""Order is defined by the current state of sorting""" |
attr = self.header[section]
old_i, old_sort = self.sort_state
self.beginResetModel()
if section == old_i:
self.collection.sort(attr, not old_sort)
self.sort_state = (section, not old_sort)
else:
self.collection.sort(attr, True)
sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_line(self, section):
"""Base implementation just pops the item from collection. Re-implements to add global behaviour """ |
self.beginResetModel()
self.collection.pop(section)
self.endResetModel() |
<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(self):
"""Emit dataChanged signal on all cells""" |
self.dataChanged.emit(self.createIndex(0, 0), self.createIndex(
len(self.collection), len(self.header))) |
<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_collection(self, collection):
"""Reset sort state, set collection and emit resetModel signal""" |
self.beginResetModel()
self.collection = collection
self.sort_state = (-1, False)
self.endResetModel() |
<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_item(self, index, new_item):
""" Changes item at index in collection. Emit dataChanged signal. :param index: Number of row or index of cell :param new_it... |
row = index.row() if hasattr(index, "row") else index
self.collection[row] = new_item
self.dataChanged.emit(self.index(
row, 0), self.index(row, self.rowCount() - 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 set_data(self, index, value):
"""Uses given data setter, and emit modelReset signal""" |
acces, field = self.get_item(index), self.header[index.column()]
self.beginResetModel()
self.set_data_hook(acces, field, value)
self.endResetModel() |
<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_id(self, Id, is_added, index):
"""Update selected_ids and emit dataChanged""" |
if is_added:
self.selected_ids.add(Id)
else:
self.selected_ids.remove(Id)
self.dataChanged.emit(index, index) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setData(self, index: QModelIndex, value, role=None):
"""Update selected_ids on click on index cell.""" |
if not (index.isValid() and role == Qt.CheckStateRole):
return False
c_id = self.get_item(index).Id
self._set_id(c_id, value == Qt.Checked, index)
return 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 set_by_Id(self, Id, is_added):
"""Update selected_ids with given Id""" |
row = self.collection.index_from_id(Id)
if row is None:
return
self._set_id(Id, is_added, self.index(row, 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 _setup_delegate(self):
"""Add resize behavior on edit""" |
delegate = self.DELEGATE_CLASS(self)
self.setItemDelegate(delegate)
delegate.sizeHintChanged.connect(
lambda index: self.resizeRowToContents(index.row()))
if self.RESIZE_COLUMN:
delegate.sizeHintChanged.connect(
lambda index: self.resizeColumnToCo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _draw_placeholder(self):
"""To be used in QTreeView""" |
if self.model().rowCount() == 0:
painter = QPainter(self.viewport())
painter.setFont(_custom_font(is_italic=True))
painter.drawText(self.rect().adjusted(0, 0, -5, -5), Qt.AlignCenter | Qt.TextWordWrap,
self.PLACEHOLDER) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def model_from_list(l, header):
"""Return a model with a collection from a list of entry""" |
col = groups.sortableListe(PseudoAccesCategorie(n) for n in l)
return MultiSelectModel(col, header) |
<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_status_code(response):
""" Return error string code if the response is an error, otherwise ``"OK"`` """ |
# This happens when a status response is expected
if isinstance(response, string_types):
return response
# This happens when a list of structs are expected
is_single_list = isinstance(response, list) and len(response) == 1
if is_single_list and isinstance(response[0], string_types):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_zone_record(self, id, domain, subdomain=None):
""" Remove the zone record with the given ID that belongs to the given domain and sub domain. If no sub... |
if subdomain is None:
subdomain = "@"
_validate_int("id", id)
self._call("removeZoneRecord", domain, subdomain, 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 parse_module_class(self):
"""Parse the module and class name part of the fully qualifed class name. """ |
cname = self.class_name
match = re.match(self.CLASS_REGEX, cname)
if not match:
raise ValueError(f'not a fully qualified class name: {cname}')
return match.groups() |
<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_module_class(self):
"""Return the module and class as a tuple of the given class in the initializer. :param reload: if ``True`` then reload the module be... |
pkg, cname = self.parse_module_class()
logger.debug(f'pkg: {pkg}, class: {cname}')
pkg = pkg.split('.')
mod = reduce(lambda m, n: getattr(m, n), pkg[1:], __import__(pkg[0]))
logger.debug(f'mod: {mod}')
if self.reload:
importlib.reload(mod)
cls = getat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instance(self, *args, **kwargs):
"""Create an instance of the specified class in the initializer. :param args: the arguments given to the initializer of the ... |
mod, cls = self.get_module_class()
inst = cls(*args, **kwargs)
logger.debug(f'inst: {inst}')
return inst |
<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_log_level(self, level=logging.INFO):
"""Convenciene method to set the log level of the module given in the initializer of this class. :param level: and i... |
mod, cls = self.parse_module_class()
logging.getLogger(mod).setLevel(level) |
<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(cls, instance_class, name=None):
"""Register a class with the factory. :param instance_class: the class to register with the factory (not a string) ... |
if name is None:
name = instance_class.__name__
cls.INSTANCE_CLASSES[name] = instance_class |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _find_class(self, class_name):
"Resolve the class from the name."
classes = {}
classes.update(globals())
classes.update(self.INSTANCE_CLASSES)
logger.debug(f'looking up class: {class_name}')
cls = classes[class_name]
logger.debug(f'found class: {cls}')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.