output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
set the data of the record | Given the following Python 3 function, write the documentation
def set_data(self, *args):
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... | As a Python code composer, you craft elegant and concise scripts. |
def runner(self):
"""
Run the necessary methods in the correct order
"""
logging.info('Starting {} analysis pipeline'.format(self.analysistype))
if not self.pipeline:
general = None
for sample in self.runmetadata.samples:
general = getattr(... | Implement a function in Python 3 to
run the necessary methods in the correct order | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return True if ch1 and ch2 are both vowels or both consonants. | How would you explain what the following Python 3 function does
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... | As a Python code analyst, you investigate and solve complex coding mysteries |
def syllabify(word):
'''Syllabify the given word.'''
word = replace_umlauts(word)
word = apply_T1(word)
word = apply_T2(word)
word = apply_T4(word)
word = apply_T5(word)
word = apply_T6(word)
word = apply_T7(word)
word = replace_umlauts(word, put_back=True)[1:] # FENCEPOST
r... | How would you implement a function in Python 3 that
syllabifies the given word. | As a Python code composer, you craft elegant and concise scripts. |
This function applies T1 to the given word. | Here you have a function in Python 3, explain what it does
def apply_T1(word):
'''There is a syllable boundary in front of every CV-sequence.'''
WORD = _split_consonants_and_vowels(word)
for k, v in WORD.iteritems():
if k == 1 and is_consonantal_onset(v):
WORD[k] = '.' + v
eli... | You are a Python code generator, capable of creating scripts from specifications. |
This function applies T5 to the word. | Here you have a function in Python 3, explain what it does
def apply_T5(word):
'''If a (V)VVV-sequence contains a VV-sequence that could be an /i/-final
diphthong, there is a syllable boundary between it and the third vowel,
e.g., [raa.ois.sa], [huo.uim.me], [la.eis.sa], [sel.vi.äi.si], [tai.an],
[säi.e... | You are a Python code architect, reviewing and designing scalable and efficient code |
def apply_T6(word):
'''If a VVV-sequence contains a long vowel, there is a syllable boundary
between it and the third vowel, e.g. [kor.ke.aa], [yh.ti.öön], [ruu.an],
[mää.yt.te].'''
WORD = _split_consonants_and_vowels(word)
for k, v in WORD.iteritems():
if len(v) == 3 and is_vowel(v[0]):
... | Write a Python 3 script for
applying T6 to a word. | You are a Python code generator, capable of creating scripts from specifications. |
Syllabify the given word whether simplex or complex. | Here you have a function in Python 3, explain what it does
def syllabify(word):
'''Syllabify the given word, whether simplex or complex.'''
compound = not word.isalpha()
syllabify = _syllabify_complex if compound else _syllabify_simplex
syllabifications = list(syllabify(word))
# if variation, order... | You are a Python code generator, capable of creating scripts from specifications. |
def wsp(word):
'''Return the number of unstressed superheavy syllables.'''
violations = 0
unstressed = []
for w in extract_words(word):
unstressed += w.split('.')[1::2] # even syllables
# include extrametrical odd syllables as potential WSP violations
if w.count('.') % 2 == 0:... | Create a Python 3 function to
return the number of unstressed superheavy syllables. | As a python code expert, you are capable of creating scripts from specifications. |
Store the modification. value should be dumped in DB compatible format. | How would you explain what the following Python 3 function does
def modifie(self, key: str, value: Any) -> None:
if key in self.FIELDS_OPTIONS:
self.modifie_options(key, value)
else:
self.modifications[key] = value | As a Python code translator, you convert algorithms and pseudocode into Python. |
def save(self) -> sql.Executant:
"""Prepare a SQL request to save the current modifications.
Returns actually a LIST of requests (which may be of length one).
Note than it can include modifications on other part of the data.
After succes, the base should be updated.
"""
r... | Create a Python 3 function to
prepare a SQL request to save the current modifications. | As a Python code composer, you craft elegant and concise scripts. |
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 | How would you code a function in Python 3 to
set options in modifications. All options will be stored since it should be grouped in the DB. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _from_dict_dict(cls, dic):
"""Takes a dict {id : dict_attributes} """
return cls({_convert_id(i): v for i, v in dic.items()}) | Implement a Python 3 function for
taking a dict containing id and attributes and returns a new dict containing the attributes. | As a Python code analyst, you investigate and solve complex coding mysteries |
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}) | Write a Python 3 function that can
take a list of dict like objects and uses Champ_ID field as Id | You are a Python code generator, capable of creating scripts from specifications. |
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 == "*":
... | Write a Python 3 script for
returning a collection of access matching pattern. | You are a Python code architect, reviewing and designing scalable and efficient code |
Return collection of acces whose field equal value | Here you have a function in Python 3, explain what it does
def select_by_field(self, base, field, value):
Ac = self.ACCES
return groups.Collection(Ac(base, i) for i, row in self.items() if row[field] == value) | You are a Python code generator, capable of creating scripts from specifications. |
def select_by_critere(self, base, criteria):
"""
:param base: Reference on whole base
:param criteria: Callable abstractAcces -> Bool, acting as filter
:return: Collection on acces passing the criteria
"""
Ac = self.ACCES
return groups.Collection(Ac(base, i) for i... | Create a Python 3 function to
select the set of acces that satisfy the criteria. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Launch data fetching then load data received. | Here you have a function in Python 3, explain what it does
def load_from_db(cls, callback_etat=print, out=None):
dic = cls._load_remote_db(callback_etat)
callback_etat("Chargement...", 2, 3)
if out is None:
return cls(dic)
cls.__init__(out, datas=dic) | You are a Python code generator, capable of creating scripts from specifications. |
Returns a dict of table interpreted from s.
s should be Json string encoding a dict | Given the following Python 3 function, write the documentation
def _parse_text_DB(self, s):
dic = self.decode_json_str(s)
new_dic = {}
for table_name, (header, rows) in dic.items():
newl = [{c: ligne[i]
for i, c in enumerate(header)} for ligne in rows]
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Load datas from local file. | How would you explain what the following Python 3 function does
def load_from_local(cls):
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.__n... | You are a Python code generator, capable of creating scripts from specifications. |
Return a dictionnary of current tables | How would you explain what the following Python 3 function does
def dumps(self):
return {table_name: getattr(self, table_name).dumps() for table_name in self.TABLES} | You are a Python code analyst, evaluating scripts for potential improvements. |
Save current in memory base to local file. | Here you have a function in Python 3, explain what it does
def save_to_local(self, callback_etat=print):
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, T... | As a python code expert, you are capable of creating scripts from specifications. |
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... | Create a Python 3 function for
reading the cell at position x and y and puts the default styles in xlwt | You are a Python code architect, reviewing and designing scalable and efficient code |
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:
... | Write a Python 3 script for
writing a cell to the current cell | As a Python code translator, you convert algorithms and pseudocode into Python. |
This function handles and validates the arguments of the service wrapper script. | Here you have a function in Python 3, explain what it does
def get_arguments(options):
# These the next couple of lines defines the header of the Help output
parser = ArgumentParser(
formatter_class=RawDescriptionHelpFormatter,
usage=("""%(prog)s
-------------------------------------------------------... | As a Python code analyst, you investigate and solve complex coding mysteries |
Check whether the input files are in fasta format reads format or other format. | Can you generate a brief explanation for the following Python 3 code
def check_file_type(files):
all_are_fasta = True
all_are_reads = True
all_are_empty = True
if sys.version_info < (3, 0):
if isinstance(files, (str, unicode)): files = [files]
else:
if isinstance(files, str): files = [files]
... | As a Python code analyst, you investigate and solve complex coding mysteries |
This function returns a list of files in the given dir | How would you explain what the following Python 3 function does
def make_file_list(upload_path):
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))
debu... | As a python code expert, you are capable of creating scripts from specifications. |
Create Rackspace Instance and save it in local json file | How would you explain what the following Python 3 function does
def create_server_rackspace(connection,
distribution,
disk_name,
disk_size,
ami,
region,
... | You are a Python code generator, capable of creating scripts from specifications. |
def destroy_rackspace(connection, region, instance_id):
""" terminates the instance """
server = connection.servers.get(instance_id)
log_yellow('deleting rackspace instance ...')
server.delete()
# wait for server to be deleted
try:
while True:
server = connection.servers.ge... | Write a Python 3 script for
deleting the rackspace instance. | As a Python code composer, you craft elegant and concise scripts. |
queries Rackspace for details about a particular server id
| Can you generate a brief explanation for the following Python 3 code
def get_rackspace_info(connection,
server_id):
""" queries Rackspace for details about a particular server id
"""
server = connection.servers.get(server_id)
data = {}
data['ip_address'] = server.accessIPv4
... | You are a Python code generator, capable of creating scripts from specifications. |
Add python types decoding. See JsonEncoder | Can you generate a brief explanation for the following Python 3 code
def date_decoder(dic):
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 ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Shortcut fot boolean like fields | Make a summary of the following Python 3 code
def _type_bool(label,default=False):
return label, abstractSearch.nothing, abstractRender.boolen, default | You are a Python code analyst, evaluating scripts for potential improvements. |
abstractSearch une chaine sans tenir compte de la casse | Here you have a function in Python 3, explain what it does
def in_string(objet, pattern):
return bool(re.search(pattern, str(objet), flags=re.I)) if objet else False | You are a Python code architect, reviewing and designing scalable and efficient code |
abstractSearch une date objet et et | Can you generate the documentation for the following Python 3 function
def in_date(objet, pattern):
if objet:
pattern = re.sub(" ", '', pattern)
objet_str = abstractRender.date(objet)
return bool(re.search(pattern, objet_str))
return False | As a Python code translator, you convert algorithms and pseudocode into Python. |
returns True if objet is in date - heure | Explain what the following Python 3 code does
def in_dateheure(objet, pattern):
if objet:
pattern = re.sub(" ", '', pattern)
objet_str = abstractRender.dateheure(objet)
return bool(re.search(pattern, objet_str))
return False | You are a Python code architect, reviewing and designing scalable and efficient code |
abstractRender d un date datetime. date | Make a summary of the following Python 3 code
def date(objet):
if objet:
return "{}/{}/{}".format(objet.day, objet.month, objet.year)
return "" | You are a Python code analyst, evaluating scripts for potential improvements. |
Install a _ function using the given translation domain. | Explain what the following Python 3 code does
def install(domain, lazy=False):
if lazy:
# NOTE(mrodden): Lazy gettext functionality.
#
# The following introduces a deferred way to do translations on
# messages in OpenStack. We override the standard _() function
# and % (forma... | As a Python code composer, you craft elegant and concise scripts. |
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 ... | Create a Python 3 function for
listing the available languages for the given translation domain. | As a Python code composer, you craft elegant and concise scripts. |
Translate the object in unicode representation to the desired locale. | Given the following Python 3 function, write the documentation
def translate(obj, desired_locale=None):
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)
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Translates all the translatable elements of the given arguments object. | Given the following Python 3 function, write the documentation
def _translate_args(args, desired_locale=None):
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):
... | As a python code expert, you are capable of creating scripts from specifications. |
Translate this message to the desired locale. | Can you generate a brief explanation for the following Python 3 code
def translate(self, desired_locale=None):
translated_message = Message._translate_msgid(self.msgid,
self.domain,
desired_locale)
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Sanitize the parameters used to modulate the object being modded with this Message. | Make a summary of the following Python 3 code
def _sanitize_mod_params(self, other):
if other is None:
params = (other,)
elif isinstance(other, dict):
params = self._trim_dictionary_parameters(other)
else:
params = self._copy_param(other)
return params | As a Python code translator, you convert algorithms and pseudocode into Python. |
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 ... | Create a Python 3 function for
returning a dict that only has matching entries in the msgid. | You are a Python code analyst, evaluating scripts for potential improvements. |
def registry_adapter(obj, request):
"""
Adapter for rendering a :class:`pyramid_urireferencer.models.RegistryResponse` to json.
:param pyramid_urireferencer.models.RegistryResponse obj: The response to be rendered.
:rtype: :class:`dict`
"""
return {
'query_uri': obj.query_uri,
'... | Implement a function in Python 3 to
return a dictionary that can be used to render a registry response to json. | You are a Python code generator, capable of creating scripts from specifications. |
Returns a dictionary representation of an application response. | Explain what the following Python 3 code does
def application_adapter(obj, request):
return {
'title': obj.title,
'uri': obj.uri,
'service_url': obj.service_url,
'success': obj.success,
'has_references': obj.has_references,
'count': obj.count,
'items': [{
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def replace_umlauts(word, put_back=False): # use translate()
'''If put_back is True, put in umlauts; else, take them out!'''
if put_back:
word = word.replace('A', 'ä')
word = word.replace('O', 'ö')
else:
word = word.replace('ä', 'A').replace('\xc3\xa4', 'A')
word = word.rep... | Can you create a Python 3 function that
replaces umlauts in a word | As a Python code composer, you craft elegant and concise scripts. |
def get_query_align(hit, contig):
"""
Function for extracting extra seqeunce data to the query
alignment if the full reference length are not covered
"""
# Getting data needed to extract sequences
query_seq = hit['query_string']
homo_seq = hit['homo_string']
sbjct_... | Can you implement a function in Python 3 that
functions for extracting extra seqeunce data to the query atom | As a Python code analyst, you investigate and solve complex coding mysteries |
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 ... | Write a Python 3 function that can
return a tuple of lookups to order by for the given column and direction. | As a Python code composer, you craft elegant and concise scripts. |
Take a model instance and return it as a json struct | Can you tell what is the following Python 3 function doing
def model_to_json(self, object, cleanup=True):
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_... | As a python code expert, you are capable of creating scripts from specifications. |
Take a json strust and a model name and return a model instance | Here you have a function in Python 3, explain what it does
def json_to_model(self, model_name, j):
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]... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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]... | Write a Python 3 script to
validate an object against its swagger model | As a Python code translator, you convert algorithms and pseudocode into Python. |
Find all server endpoints defined in the swagger spec and calls callback for each one with an instance of EndpointData as argument. | Can you generate the documentation for the following Python 3 function
def call_on_each_endpoint(self, callback):
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 = ... | You are a Python code generator, capable of creating scripts from specifications. |
Buffer stdin and flush and avoid incomplete files. | Can you generate the documentation for the following Python 3 function
def main(args=None):
parser = argparse.ArgumentParser(description=main.__doc__)
parser.add_argument(
'--binary',
dest='mode',
action='store_const',
const="wb",
default="w",
help='write in binar... | You are a Python code analyst, evaluating scripts for potential improvements. |
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
... | Implement a Python 3 function for
generating a list of basic C - style defines that can be used to generate a header file. | You are a Python code generator, capable of creating scripts from specifications. |
Creates a new EmailMarketingCampaign object. | Can you tell what is the following Python 3 function doing
def new_email_marketing_campaign(self, name, email_content, from_email,
from_name, reply_to_email, subject,
text_content, address,
is_view_as_webpage_... | You are a Python code generator, capable of creating scripts from specifications. |
Updates an existing Constant Contact email marketing campaign. | How would you explain what the following Python 3 function does
def update_email_marketing_campaign(self, email_marketing_campaign,
name, email_content, from_email,
from_name, reply_to_email, subject,
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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.d... | Write a Python 3 function that can
delete a Constant Contact email marketing campaign. | As a Python code analyst, you investigate and solve complex coding mysteries |
Inlines CSS defined in external style sheets. | Given the following Python 3 function, write the documentation
def inline_css(self, html):
premailer = Premailer(html)
inlined_html = premailer.transform(pretty_print=True)
return inlined_html | As a Python code composer, you craft elegant and concise scripts. |
Returns HTML and text previews of an EmailMarketingCampaign. | Can you tell what is the following Python 3 function doing
def preview_email_marketing_campaign(self, email_marketing_campaign):
url = self.api.join('/'.join([
self.EMAIL_MARKETING_CAMPAIGN_URL,
str(email_marketing_campaign.constant_contact_id),
'preview']))
response ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def pre_save(cls, sender, instance, *args, **kwargs):
"""Pull constant_contact_id out of data.
"""
instance.constant_contact_id = str(instance.data['id']) | Implement a Python 3 function for
pulling constant_contact_id out of data. | You are a Python code analyst, evaluating scripts for potential improvements. |
Deletes the CC email marketing campaign associated with me. | Can you tell what is the following Python 3 function doing
def pre_delete(cls, sender, instance, *args, **kwargs):
cc = ConstantContact()
response = cc.delete_email_marketing_campaign(instance)
response.raise_for_status() | You are a Python code analyst, evaluating scripts for potential improvements. |
def runner(self):
"""
Run the necessary methods in the correct order
"""
printtime('Starting {} analysis pipeline'.format(self.analysistype), self.starttime)
if not self.pipeline:
# If the metadata has been passed from the method script, self.pipeline must still be fa... | Create a Python 3 function to
run the necessary methods in the correct order. | As a Python code composer, you craft elegant and concise scripts. |
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 ... | Write a Python 3 function for
sending an email to the specified recipients. | You are a Python code generator, capable of creating scripts from specifications. |
Initialize a database connection by each connection string in the configuration file. | How would you explain what the following Python 3 function does
def initialize_connections(self, scopefunc=None):
for connection_name, connection_string in\
self.app.config['FLASK_PHILO_SQLALCHEMY'].items():
engine = create_engine(connection_string)
session = scoped_sessi... | You are a Python code analyst, evaluating scripts for potential improvements. |
def sort(self, attribut, order=False):
"""
Implément un tri par attrbut.
:param str attribut: Nom du champ concerné
:param bool order: Ordre croissant ou décroissant
"""
value_default = formats.ASSOCIATION[attribut][3]
if type(value_default) is str: # case inse... | Can you write a function in Python 3 where it
sorts the list according to the attribute attribut | You are a Python code analyst, evaluating scripts for potential improvements. |
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 | Implement a Python 3 function for
returning the row of given Id if it exists otherwise None. Only works with pseudo - acces | As a Python code analyst, you investigate and solve complex coding mysteries |
Append a new entry to the list. | Explain what the following Python 3 code does
def append(self, acces, **kwargs):
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 | As a Python code analyst, you investigate and solve complex coding mysteries |
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) | Write a Python 3 function for
suppressing acces with id = key | As a Python code composer, you craft elegant and concise scripts. |
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,{}) | Write a Python 3 function for
returning information associated with Id or list index | As a python code expert, you are capable of creating scripts from specifications. |
Performs a search field by field using functions defined in formats. ASSOCIATION. | Explain what the following Python 3 code does
def recherche(self, pattern, entete):
new_liste = []
sub_patterns = pattern.split(" ")
for p in self:
d_font = {att: False for att in entete}
row_valid = True
for sub_pattern in sub_patterns:
found... | You are a Python code architect, reviewing and designing scalable and efficient code |
Merges the list with the items in the collection. Ensure uniqueness of ids. | Explain what the following Python 3 code does
def extend(self, collection):
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:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Stringify time in ISO 8601 format. | Make a summary of the following Python 3 code
def isotime(at=None, subsecond=False):
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'
... | You are a Python code analyst, evaluating scripts for potential improvements. |
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)) | Can you create a Python 3 function that
parses time from ISO 8601 format. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Normalize time in arbitrary timezone to UTC naive object. | Given the following Python 3 function, write the documentation
def normalize_time(timestamp):
offset = timestamp.utcoffset()
if offset is None:
return timestamp
return timestamp.replace(tzinfo=None) - offset | You are a Python code architect, reviewing and designing scalable and efficient code |
Return True if before is older than seconds. | Can you generate a brief explanation for the following Python 3 code
def is_older_than(before, 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(seco... | As a Python code analyst, you investigate and solve complex coding mysteries |
Return True if after is newer than seconds. | Can you tell what is the following Python 3 function doing
def is_newer_than(after, 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) | As a Python code composer, you craft elegant and concise scripts. |
Timestamp version of our utcnow function. | Here you have a function in Python 3, explain what it does
def utcnow_ts():
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()) | As a python code expert, you are capable of creating scripts from specifications. |
Overridable version of utils. utcnow. | Make a summary of the following Python 3 code
def utcnow():
if utcnow.override_time:
try:
return utcnow.override_time.pop(0)
except AttributeError:
return utcnow.override_time
return datetime.datetime.utcnow() | You are a Python code architect, reviewing and designing scalable and efficient code |
Advance overridden time using a datetime. timedelta. | Make a summary of the following Python 3 code
def advance_time_delta(timedelta):
assert(utcnow.override_time is not None)
try:
for dt in utcnow.override_time:
dt += timedelta
except TypeError:
utcnow.override_time += timedelta | You are a Python code generator, capable of creating scripts from specifications. |
Make an rpc - safe datetime with microseconds. | Here you have a function in Python 3, explain what it does
def marshall_now(now=None):
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) | You are a Python code architect, reviewing and designing scalable and efficient code |
Unmarshall a datetime dict. | Make a summary of the following Python 3 code
def unmarshall_time(tyme):
return datetime.datetime(day=tyme['day'],
month=tyme['month'],
year=tyme['year'],
hour=tyme['hour'],
minute=tyme['minute'],
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return the total seconds of a datetime. timedelta object. | Given the following Python 3 function, write the documentation
def total_seconds(delta):
try:
return delta.total_seconds()
except AttributeError:
return ((delta.days * 24 * 3600) + delta.seconds +
float(delta.microseconds) / (10 ** 6)) | You are a Python code architect, reviewing and designing scalable and efficient code |
Determines if the given time is going to happen in the next window seconds. | Here you have a function in Python 3, explain what it does
def is_soon(dt, window):
soon = (utcnow() + datetime.timedelta(seconds=window))
return normalize_time(dt) <= soon | As a Python code composer, you craft elegant and concise scripts. |
Download the file at url to target using Powershell. | Make a summary of the following Python 3 code
def download_file_powershell(url, target):
'''
Download the file at url to target using Powershell (which will validate
trust). Raise an exception if the command cannot complete.
'''
target = os.path.abspath(target)
cmd = [
'powershell',
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Download a file from a URL and save it to a file. | Can you generate a brief explanation for the following Python 3 code
def download_file_insecure(url, target):
'''
Use Python to download the file, even though it cannot authenticate the
connection.
'''
try:
from urllib.request import urlopen
except ImportError:
from urllib2 impor... | As a Python code composer, you craft elegant and concise scripts. |
Build the arguments to python setup. py install on the setuptools package | Can you generate the documentation for the following Python 3 function
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 re... | As a Python code composer, you craft elegant and concise scripts. |
Decorator that changes or sets the environment variable for the specified resource. | Given the following Python 3 function, write the documentation
def write(name, 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, **kwarg... | You are a Python code analyst, evaluating scripts for potential improvements. |
Only execute the function if the variable is set. | Here you have a function in Python 3, explain what it does
def isset(name):
def wrapped(func):
@functools.wraps(func)
def _decorator(*args, **kwargs):
if core.isset(name):
return func(*args, **kwargs)
return _decorator
return wrapped | As a Python code analyst, you investigate and solve complex coding mysteries |
Decorator to execute the function only if the boolean variable is set. | Can you tell what is the following Python 3 function doing
def bool(name, execute_bool=True, default=None):
def wrapped(func):
@functools.wraps(func)
def _decorator(*args, **kwargs):
if core.isset(name) and core.bool(name) == execute_bool:
return func(*args, **kwargs)
... | As a Python code composer, you craft elegant and concise scripts. |
Reads the cell at position x and y and returns value | How would you explain what the following Python 3 function does
def read_cell(self, x, y):
if isinstance(self.header[y], tuple):
header = self.header[y][0]
else:
header = self.header[y]
x += 1
y += 1
if self.strip:
self._sheet.cell(x, y).value ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def write_cell(self, x, y, value):
"""
Writing value in the cell of x+1 and y+1 position
:param x: line index
:param y: coll index
:param value: value to be written
:return:
"""
x += 1
y += 1
self._sheet.update_cell(x, y, value) | Create a Python 3 function to
write the value in the cell of x y to value | As a Python code composer, you craft elegant and concise scripts. |
def _open(self):
"""
Open the file; get sheets
:return:
"""
if not hasattr(self, '_file'):
self._file = self.gc.open(self.name)
self.sheet_names = self._file.worksheets() | Write a Python 3 script for
opening the file and get sheets | As a Python code composer, you craft elegant and concise scripts. |
def _open_sheet(self):
"""
Read the sheet, get value the header, get number columns and rows
:return:
"""
if self.sheet_name and not self.header:
self._sheet = self._file.worksheet(self.sheet_name.title)
self.ncols = self._sheet.col_count
self.... | How would you implement a function in Python 3 that
reads the sheet and set the header and number columns and rows. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _import(self):
"""
Makes imports
:return:
"""
import os.path
import gspread
self.path = os.path
self.gspread = gspread
self._login() | How would you implement a function in Python 3 that
makes imports Makes imports | As a python code expert, you are capable of creating scripts from specifications. |
Login with your Google account
| Can you tell what is the following Python 3 function doing
def _login(self):
# TODO(dmvieira) login changed to oauth2
self.gc = self.gspread.login(self.email, self.password) | You are a Python code architect, reviewing and designing scalable and efficient code |
Flags for the item at the given index. | How would you explain what the following Python 3 function does
def flags(self, index: QModelIndex):
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) | ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Sort the entries in the specified section. | Given the following Python 3 function, write the documentation
def sort(self, section: int, order=None):
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_st... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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() | Create a Python 3 function for
basing implementation just pops the item from the collection and removes the section from the collection. | You are a Python code generator, capable of creating scripts from specifications. |
def _update(self):
"""Emit dataChanged signal on all cells"""
self.dataChanged.emit(self.createIndex(0, 0), self.createIndex(
len(self.collection), len(self.header))) | Implement a Python 3 function for
updating the data of the current instance of the class. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the item with the given index. | Can you generate a brief explanation for the following Python 3 code
def get_item(self, index):
row = index.row() if hasattr(index, "row") else index
try:
return self.collection[row]
except IndexError: # invalid index for exemple
return None | As a Python code translator, you convert algorithms and pseudocode into Python. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.