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 = ''
vowels = ''
for syll in syllable_split(syllabification):
try:
vowels += get_vowel(syll)
weights += get_weight(syll)
stresses += {'\'': 'P', '`': 'S'}.get(syll[0], 'U')
except AttributeError:
# if the syllable is vowel-less...
if syll[-1].isalpha():
stresses += '*'
weights += '*'
vowels += '*'
else:
stresses += ' '
weights += ' '
vowels += ' '
info.append((
syllabification,
stresses,
weights,
vowels,
))
return 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 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.analysistype].best_h_pid = '-'
sample[self.analysistype].h_genes = ['-']
sample[self.analysistype].h_set = ['-']
if sample.general.bestassemblyfile != 'NA':
if sample.general.closestrefseqgenus == 'Escherichia':
o = dict()
h = dict()
for result, percentid in sample[self.analysistype].results.items():
if 'O' in result.split('_')[-1]:
o.update({result: float(percentid)})
if 'H' in result.split('_')[-1]:
h.update({result: float(percentid)})
# O
try:
sorted_o = sorted(o.items(), key=operator.itemgetter(1), reverse=True)
sample[self.analysistype].best_o_pid = str(sorted_o[0][1])
sample[self.analysistype].o_genes = [gene for gene, pid in o.items()
if str(pid) == sample[self.analysistype].best_o_pid]
sample[self.analysistype].o_set = \
list(set(gene.split('_')[-1] for gene in sample[self.analysistype].o_genes))
except (KeyError, IndexError):
pass
# H
try:
sorted_h = sorted(h.items(), key=operator.itemgetter(1), reverse=True)
sample[self.analysistype].best_h_pid = str(sorted_h[0][1])
sample[self.analysistype].h_genes = [gene for gene, pid in h.items()
if str(pid) == sample[self.analysistype].best_h_pid]
sample[self.analysistype].h_set = \
list(set(gene.split('_')[-1] for gene in sample[self.analysistype].h_genes))
except (KeyError, IndexError):
pass |
<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 + ','
# Iterate through all the user-supplied target names
for target in sorted(self.genes):
write_results = False
# There was an issue with 'target' not matching 'name' due to a dash being replaced by an underscore
# only in 'name'. This will hopefully address this issue
target = target.replace('-', '_')
if write_header:
header += '{target}_match_details,{target},'.format(target=target)
for name, identity in sample[self.analysistype].results.items():
# Ensure that all dashes are replaced with underscores
name = name.replace('-', '_')
# If the current target matches the target in the header, add the data to the string
if name == target:
write_results = True
gene_results = '{percent_id}% ({avgdepth} +/- {stddev}),{record},'\
.format(percent_id=identity,
avgdepth=sample[self.analysistype].avgdepth[name],
stddev=sample[self.analysistype].standarddev[name],
record=sample[self.analysistype].sequences[target])
# Populate the data string appropriately
data += gene_results
# If the target is not present, write dashes to represent the results and sequence
if not write_results:
data += '-,-,'
data += ' \n'
write_header = False
header += '\n'
# Write the strings to the report
report.write(header)
report.write(data) |
<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 ch1 == ch2 |
<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 callable dict -> str to map record to string. Default to _record_to_string """ |
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)
for sub_pattern in sub_patterns)
except re.error:
return groups.Collection()
def search(string):
for regexp in regexps:
if not regexp.search(string):
return False
return True
to_string_hook = to_string_hook or self._record_to_string
return groups.Collection(Ac(base, i) for i, p in self.items() if search(to_string_hook(p)))
return groups.Collection() |
<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 given, datas are set in it, instead of returning a new base object. """ |
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 sauvegarde locale !")
else:
return cls(cls.decode_json_str(s)) |
<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_etat: state callback, taking str,int,int as args """ |
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_PATH, 'wb') as f:
f.write(s)
except (FileNotFoundError):
logging.exception(self.__class__.__name__)
raise StructureError("Chemin de sauvegarde introuvable !") |
<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_index in self.colors.keys():
style = self.colors[self._file.xf_list[
cell.xf_index].background.pattern_colour_index]
else:
style = self.xlwt.easyxf(
'pattern: pattern solid; border: top thin, right thin, bottom thin, left thin;')
style.pattern.pattern_fore_colour = self._file.xf_list[
cell.xf_index].background.pattern_colour_index
self.colors[self._file.xf_list[
cell.xf_index].background.pattern_colour_index] = style
style.font.name = self._file.font_list[
self._file.xf_list[cell.xf_index].font_index].name
style.font.bold = self._file.font_list[
self._file.xf_list[cell.xf_index].font_index].bold
if isinstance(self.header[y], tuple):
header = self.header[y][0]
else:
header = self.header[y]
if self.strip:
if is_str_or_unicode(cell.value):
cell.value = cell.value.strip()
if self.style:
return {header: (cell.value, style)}
else:
return {header: cell.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 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
return truestring |
<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
===============
This is the service wrapper script, which is a part of the CGE services.
Read the online manual for help.
A list of all published services can be found at:
cge.cbs.dtu.dk/services
"""), epilog=("""
--------------------------------------------------------------------------------
"""))
#ADDING ARGUMENTS
setarg = parser.add_argument
#SERVICE SPECIFIC ARGUMENTS
if isinstance(options, str):
options = [[x for i,x in enumerate(line.split()) if i in [1,2]] for line in options.split('\n') if len(line)>0]
for o in options:
try:
setarg(o[1], type=str, dest=o[0], default=None, help=SUPPRESS)
except:
None
else:
for o in options:
if o[2] is True:
# Handle negative flags
setarg(o[0], action="store_false", dest=o[1], default=o[2],
help=o[3])
elif o[2] is False:
# Handle positive flags
setarg(o[0], action="store_true", dest=o[1], default=o[2],
help=o[3])
else:
help_ = o[3] if o[2] is None else "%s [%s]"%(o[3], '%(default)s')
setarg(o[0], type=str, dest=o[1], default=o[2],
help=help_)
# VALIDATION OF ARGUMENTS
args = parser.parse_args()
debug.log("ARGS: %s"%args)
return args |
<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.datetime(**{c: v for c, v in dic.items() if not c == "__datetime__"})
except (TypeError, ValueError):
raise json.JSONDecodeError("Corrupted datetime format !", str(dic), 1)
else:
return dic
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 _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(mrodden): en_US should always be available (and first in case
# order matters) since our in-line message strings are en_US
language_list = ['en_US']
# NOTE(luisg): Babel <1.0 used a function called list(), which was
# renamed to locale_identifiers() in >=1.0, the requirements master list
# requires >=0.9.6, uncapped, so defensively work with both. We can remove
# this check when the master list updates to >=1.0, and update all projects
list_identifiers = (getattr(localedata, 'list', None) or
getattr(localedata, 'locale_identifiers'))
locale_identifiers = list_identifiers()
for i in locale_identifiers:
if find(i) is not None:
language_list.append(i)
# NOTE(luisg): Babel>=1.0,<1.3 has a bug where some OpenStack supported
# locales (e.g. 'zh_CN', and 'zh_TW') aren't supported even though they
# are perfectly legitimate locales:
# https://github.com/mitsuhiko/babel/issues/37
# In Babel 1.3 they fixed the bug and they support these locales, but
# they are still not explicitly "listed" by locale_identifiers().
# That is why we add the locales here explicitly if necessary so that
# they are listed as supported.
aliases = {'zh': 'zh_CN',
'zh_Hant_HK': 'zh_HK',
'zh_Hant': 'zh_TW',
'fil': 'tl_PH'}
for (locale_, alias) in six.iteritems(aliases):
if locale_ in language_list and alias not in language_list:
language_list.append(alias)
_AVAILABLE_LANGUAGES[domain] = language_list
return copy.copy(language_list) |
<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-is. If the locale is None the object is translated to the system locale. :param obj: the object to translate :param desired_locale: the locale to translate the message to, if None the default system locale will be used :returns: the translated object in unicode, or the original object if it could not be translated """ |
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
# running with translatable unicode before translating
return message.translate(desired_locale)
return obj |
<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 the translatable values in method arguments which include values of tuples or dictionaries. If the object is not a tuple or a dictionary the object itself is translated if it is translatable. If the locale is None the object is translated to the system locale. :param args: the args to translate :param desired_locale: the locale to translate the args to, if None the default system locale will be used :returns: a new args object with the translated contents of the original """ |
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 translated_dict
return translate(args, desired_locale) |
<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, if no locale is provided the message will be translated to the system's default locale. :returns: the translated message in unicode """ |
translated_message = Message._translate_msgid(self.msgid,
self.domain,
desired_locale)
if self.params is None:
# No need for more translation
return translated_message
# This Message object may have been formatted with one or more
# Message objects as substitution arguments, given either as a single
# argument, part of a tuple, or as one or more values in a dictionary.
# When translating this Message we need to translate those Messages too
translated_params = _translate_args(self.params, desired_locale)
translated_message = translated_message % translated_params
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 the modded object, which can be a large dictionary, to only those keys that would actually be used in a translation - Snapshot the object being modded, in case the message is translated, it will be used as it was when the Message was created """ |
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
# non-deepcopyable objects by unicoding() them.
# Look for %(param) keys in msgid;
# Skip %% and deal with the case where % is first character on the line
keys = re.findall('(?:[^%]|^)?%\((\w*)\)[a-z]', self.msgid)
# If we don't find any %(param) keys but have a %s
if not keys and re.findall('(?:[^%]|^)%[a-z]', self.msgid):
# Apparently the full dictionary is the parameter
params = self._copy_param(dict_param)
else:
params = {}
# Save our existing parameters as defaults to protect
# ourselves from losing values if we are called through an
# (erroneous) chain that builds a valid Message with
# arguments, and then does something like "msg % kwds"
# where kwds is an empty dictionary.
src = {}
if isinstance(self.params, dict):
src.update(self.params)
src.update(dict_param)
for key in keys:
params[key] = self._copy_param(src[key])
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 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, either -1, 0 or 1. """ |
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, list)):
ordering = [ordering]
if direction == 1:
return ordering
return [lookup[1:] if lookup[0] == '-' else '-' + lookup
for lookup in ordering] |
<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_name)
m = marshal_model(self.spec, model_def, object)
if cleanup:
self.cleanup_model(m)
return m |
<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, model_def, 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 call_on_each_endpoint(self, callback):
"""Find all server endpoints defined in the swagger spec and calls 'callback' for each, with an instance of EndpointData as argument. """ |
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-bind-server' not in op_spec:
if 'x-no-bind-server' in op_spec:
# That route should not be auto-generated
log.info("Skipping generation of %s %s" % (method, path))
continue
else:
raise Exception("Swagger api defines no x-bind-server for %s %s" % (method, path))
data.handler_server = op_spec['x-bind-server']
# Make sure that endpoint only produces 'application/json'
if 'produces' not in op_spec:
raise Exception("Swagger api has no 'produces' section for %s %s" % (method, path))
if len(op_spec['produces']) != 1:
raise Exception("Expecting only one type under 'produces' for %s %s" % (method, path))
if op_spec['produces'][0] == 'application/json':
data.produces_json = True
elif op_spec['produces'][0] == 'text/html':
data.produces_html = True
else:
raise Exception("Only 'application/json' or 'text/html' are supported. See %s %s" % (method, path))
# Which client method handles this endpoint?
if 'x-bind-client' in op_spec:
data.handler_client = op_spec['x-bind-client']
# Should we decorate the server handler?
if 'x-decorate-server' in op_spec:
data.decorate_server = op_spec['x-decorate-server']
# Should we manipulate the requests parameters?
if 'x-decorate-request' in op_spec:
data.decorate_request = op_spec['x-decorate-request']
# Generate a bravado-core operation object
data.operation = Operation.from_spec(self.spec, path, method, op_spec)
# Figure out how parameters are passed: one json in body? one or
# more values in query?
if 'parameters' in op_spec:
params = op_spec['parameters']
for p in params:
if p['in'] == 'body':
data.param_in_body = True
if p['in'] == 'query':
data.param_in_query = True
if p['in'] == 'path':
data.param_in_path = True
if data.param_in_path:
# Substitute {...} with <...> in path, to make a Flask friendly path
data.path = data.path.replace('{', '<').replace('}', '>')
if data.param_in_body and data.param_in_query:
raise Exception("Cannot support params in both body and param (%s %s)" % (method, path))
else:
data.no_params = True
callback(data) |
<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='Output file')
logging.basicConfig(
level=logging.DEBUG,
stream=sys.stderr,
format='[%(levelname)s elapsed=%(relativeCreated)dms] %(message)s')
args = parser.parse_args(args or sys.argv[1:])
with open(args.output, args.mode) as fd:
for line in sys.stdin:
fd.write(line) |
<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
@keyboard_prefix: Prefix used for to_hid_keyboard
@led_prefix: Prefix used for to_hid_led
@sysctrl_prefix: Prefix used for to_hid_sysctrl
@cons_prefix: Prefix used for to_hid_consumer
@code_suffix: Append _<usb code> to each name
@all_caps: Set to true if labels should be converted to all caps
@space_char: Character to replace space with
@returns: List of C tuples (<name>, <number>) that can be used to generate C-style defines. Each section has it's own list.
'''
# Keyboard Codes
keyboard_defines = []
for code, name in layout.json()['to_hid_keyboard'].items():
new_name = "{}{}".format(keyboard_prefix, name.replace(' ', space_char))
if all_caps:
new_name = new_name.upper()
if code_suffix:
new_name = "{}_{}".format(new_name, int(code, 0))
define = (new_name, code)
keyboard_defines.append(define)
# LED Codes
led_defines = []
for code, name in layout.json()['to_hid_led'].items():
new_name = "{}{}".format(led_prefix, name.replace(' ', space_char))
if all_caps:
new_name = new_name.upper()
if code_suffix:
new_name = "{}_{}".format(new_name, int(code, 0))
define = (new_name, code)
led_defines.append(define)
# System Control Codes
sysctrl_defines = []
for code, name in layout.json()['to_hid_sysctrl'].items():
new_name = "{}{}".format(sysctrl_prefix, name.replace(' ', space_char))
if all_caps:
new_name = new_name.upper()
if code_suffix:
new_name = "{}_{}".format(new_name, int(code, 0))
define = (new_name, code)
sysctrl_defines.append(define)
# Consumer Codes
cons_defines = []
for code, name in layout.json()['to_hid_consumer'].items():
new_name = "{}{}".format(cons_prefix, name.replace(' ', space_char))
if all_caps:
new_name = new_name.upper()
if code_suffix:
new_name = "{}_{}".format(new_name, int(code, 0))
define = (new_name, code)
cons_defines.append(define)
# Return list of list of tuples
defines = [keyboard_defines, led_defines, sysctrl_defines, cons_defines]
return defines |
<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=False, view_as_web_page_link_text='', view_as_web_page_text='', is_permission_reminder_enabled=False, permission_reminder_text=''):
"""Create a Constant Contact email marketing campaign. Returns an EmailMarketingCampaign object. """ |
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,
'subject': subject,
'from_name': from_name,
'from_email': from_email,
'reply_to_email': reply_to_email,
'email_content': worked_around_email_content,
'email_content_format': 'HTML',
'text_content': text_content,
'message_footer': {
'organization_name': address['organization_name'],
'address_line_1': address['address_line_1'],
'address_line_2': address['address_line_2'],
'address_line_3': address['address_line_3'],
'city': address['city'],
'state': address['state'],
'international_state': address['international_state'],
'postal_code': address['postal_code'],
'country': address['country']
},
'is_view_as_webpage_enabled': is_view_as_webpage_enabled,
'view_as_web_page_link_text': view_as_web_page_link_text,
'view_as_web_page_text': view_as_web_page_text,
'is_permission_reminder_enabled': is_permission_reminder_enabled,
'permission_reminder_text': permission_reminder_text
}
response = url.post(data=json.dumps(data),
headers={'content-type': 'application/json'})
self.handle_response_status(response)
return EmailMarketingCampaign.objects.create(data=response.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 update_email_marketing_campaign(self, email_marketing_campaign, name, email_content, from_email, from_name, reply_to_email, subject, text_content, address, is_view_as_webpage_enabled=False, view_as_web_page_link_text='', view_as_web_page_text='', is_permission_reminder_enabled=False, permission_reminder_text=''):
"""Update a Constant Contact email marketing campaign. Returns the updated EmailMarketingCampaign object. """ |
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_email_content = work_around(minified_email_content)
data = {
'name': name,
'subject': subject,
'from_name': from_name,
'from_email': from_email,
'reply_to_email': reply_to_email,
'email_content': worked_around_email_content,
'email_content_format': 'HTML',
'text_content': text_content,
'message_footer': {
'organization_name': address['organization_name'],
'address_line_1': address['address_line_1'],
'address_line_2': address['address_line_2'],
'address_line_3': address['address_line_3'],
'city': address['city'],
'state': address['state'],
'international_state': address['international_state'],
'postal_code': address['postal_code'],
'country': address['country']
},
'is_view_as_webpage_enabled': is_view_as_webpage_enabled,
'view_as_web_page_link_text': view_as_web_page_link_text,
'view_as_web_page_text': view_as_web_page_text,
'is_permission_reminder_enabled': is_permission_reminder_enabled,
'permission_reminder_text': permission_reminder_text
}
response = url.put(data=json.dumps(data),
headers={'content-type': 'application/json'})
self.handle_response_status(response)
email_marketing_campaign.data = response.json()
email_marketing_campaign.save()
return email_marketing_campaign |
<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'],
response.json()['preview_text_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=None, cc=None, bcc=None, attachments=None, headers=None, bypass_queue=False, bypass_hijacking=False, attach_files=None):
"""
Will send a multi-format email to recipients. Email may be queued through celery
""" |
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, category, fail_silently, language if language else translation.get_language(), cc, bcc, attachments, headers, bypass_hijacking, attach_files])
else:
header_category_value = '%s%s' % (settings.MAILING_HEADER_CATEGORY_PREFIX if hasattr(settings, 'MAILING_HEADER_CATEGORY_PREFIX') else '', category)
# Check for sendgrid support and add category header
# --------------------------------
if hasattr(settings, 'MAILING_USE_SENDGRID'):
send_grid_support = settings.MAILING_USE_SENDGRID
else:
send_grid_support = False
if not headers:
headers = dict()
if send_grid_support and category:
headers['X-SMTPAPI'] = '{"category": "%s"}' % header_category_value
# Check for Mailgun support and add label header
# --------------------------------
if hasattr(settings, 'MAILING_USE_MAILGUN'):
mailgun_support = settings.MAILING_USE_MAILGUN
else:
mailgun_support = False
if not headers:
headers = dict()
if mailgun_support and category:
headers['X-Mailgun-Tag'] = header_category_value
# Ensure recipients are in a list
# --------------------------------
if isinstance(recipients, basestring):
recipients_list = [recipients]
else:
recipients_list = recipients
# Check if we need to hijack the email
# --------------------------------
if hasattr(settings, 'MAILING_MAILTO_HIJACK') and not bypass_hijacking:
headers['X-MAILER-ORIGINAL-MAILTO'] = ','.join(recipients_list)
recipients_list = [settings.MAILING_MAILTO_HIJACK]
if not subject:
raise MailerMissingSubjectError('Subject not supplied')
# Send ascii, html or multi-part email
# --------------------------------
if text_content or html_content:
if use_base_template:
prev_language = translation.get_language()
language and translation.activate(language)
text_content = render_to_string('mailing/base.txt', {'mailing_text_body': text_content, 'mailing_subject': subject, 'settings': settings}) if text_content else None
html_content = render_to_string('mailing/base.html', {'mailing_html_body': html_content, 'mailing_subject': subject, 'settings': settings}) if html_content else None
translation.activate(prev_language)
msg = EmailMultiAlternatives(subject, text_content if text_content else html_content, from_email if from_email else settings.DEFAULT_FROM_EMAIL, recipients_list, cc=cc, bcc=bcc, attachments=attachments, headers = headers)
if html_content and text_content:
msg.attach_alternative(html_content, "text/html")
elif html_content: # Only HTML
msg.content_subtype = "html"
# Attach files through attach_files helper
# --------------------------------
if attach_files:
for att in attach_files: # attachments are tuples of (filepath, mimetype, filename)
with open(att[0], 'rb') as f:
content = f.read()
msg.attach(att[2], content, att[1])
# Send email
# --------------------------------
msg.send(fail_silently=fail_silently)
else:
raise MailerInvalidBodyError('No text or html body supplied.') |
<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[connection_name] = Connection(engine, session) |
<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'],
microsecond=tyme['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 total_seconds(delta):
"""Return the total seconds of datetime.timedelta object. Compute total seconds of datetime.timedelta, datetime.timedelta doesn't have method total_seconds in Python2.6, calculate it manually. """ |
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 consider the time not soon :return: True if expiration is within the given duration """ |
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)
install_args.append('--user')
return install_args |
<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 variable value: A value to set for the environment variable Returns: The function return value. """ |
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
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 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 `None` if the function was skipped. """ |
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 execute_bool: The boolean value to execute the function on default: The default value if the environment variable is not set (respects `execute_bool`) Returns: The function return value or `None` if the function was skipped. """ |
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)
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 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)
self.sort_state = (section, True)
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 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_item: Dict-like object """ |
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.resizeColumnToContents(index.column()))
delegate.closeEditor.connect(
lambda ed: self.resizeRowToContents(delegate.row_done_)) |
<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):
return response[0]
# This happens when a struct of any kind is returned
return "OK" |
<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 domain is given the wildcard sub-domain is assumed. """ |
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 before returning the class """ |
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 = getattr(mod, cname)
logger.debug(f'class: {cls}')
return mod, cls |
<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 new class :param kwargs: the keyword arguments given to the initializer of the new class """ |
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 instance of ``logging.<level>`` """ |
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) :param name: the name to use as the key for instance class lookups; defaults to the name of the class """ |
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}')
return cls |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.