text
stringlengths
81
112k
Upload a vcl file to a fastly service, cloning the current version if necessary. The uploaded vcl is set as main unless --include is given. All existing vcl files will be deleted first if --delete is given. def main(): """ Upload a vcl file to a fastly service, cloning the current version i...
Run the necessary methods in the correct order def main(self): """ Run the necessary methods in the correct order """ self.target_validate() self.gene_names() Sippr(inputobject=self, k=self.kmer_size, allow_soft_clips=self.allow_soft_clips) ...
Extract the names of the user-supplied targets 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 na...
Create the report for the user-supplied targets 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.analysist...
Convert to pseuso acces def on_add(self, item): """Convert to pseuso acces""" super(Tels, self).on_add(list_views.PseudoAccesCategorie(item))
we cant to call set_data to manually update 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(jou...
Run the necessary methods in the correct order 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.runmeta...
Return True if ch1 and ch2 are both vowels or both consonants. 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...
Syllabify the given word. 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=Tr...
There is a syllable boundary in front of every CV-sequence. 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 e...
There is a syllable boundary within a sequence VV of two nonidentical that are not a genuine diphthong, e.g., [ta.e], [ko.et.taa]. def apply_T2(word): '''There is a syllable boundary within a sequence VV of two nonidentical that are not a genuine diphthong, e.g., [ta.e], [ko.et.taa].''' WORD = _split_c...
An agglutination diphthong that ends in /u, y/ usually contains a syllable boundary when -C# or -CCV follow, e.g., [lau.ka.us], [va.ka.ut.taa]. def apply_T4(word): # OPTIMIZE '''An agglutination diphthong that ends in /u, y/ usually contains a syllable boundary when -C# or -CCV follow, e.g., [lau.ka.u...
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], [oi.om.me]. def apply_T5(word): '''If a (V)VVV-sequence contains a VV-sequence...
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]. 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....
If a VVV-sequence does not contain a potential /i/-final diphthong, there is a syllable boundary between the second and third vowels, e.g. [kau.an], [leu.an], [kiu.as]. def apply_T7(word): '''If a VVV-sequence does not contain a potential /i/-final diphthong, there is a syllable boundary between the se...
Syllabify the given word, whether simplex or complex. 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 var...
Return the number of unstressed superheavy syllables. 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 pot...
Store the modification. `value` should be dumped in DB compatible format. 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: ...
Convenience function which calls modifie on each element of dic 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)
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. def save(self) -> sql.Executant: """Prepare a SQL reques...
Set options in modifications. All options will be stored since it should be grouped in the DB. 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 {}, **{fi...
Takes a dict {id : dict_attributes} def _from_dict_dict(cls, dic): """Takes a dict {id : dict_attributes} """ return cls({_convert_id(i): v for i, v in dic.items()})
Takes a list of dict like objects and uses `champ_id` field as Id 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})
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 def base_recherche_rapide(self, base, pattern, to_string_hook=None): """ Return a collection of access matching `pattern`. `to_st...
Return collection of acces whose field equal value 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)
:param base: Reference on whole base :param criteria: Callable abstractAcces -> Bool, acting as filter :return: Collection on acces passing the criteria def select_by_critere(self, base, criteria): """ :param base: Reference on whole base :param criteria: Callable abstractAcces ...
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. def load_from_db(cls, callback_etat=print, out=None): """Launch data fetching then load data received. The method ...
Returns a dict of table interpreted from s. s should be Json string encoding a dict { table_name : [fields_name,...] , [rows,... ] } def _parse_text_DB(self, s): """Returns a dict of table interpreted from s. s should be Json string encoding a dict { table_name : [fields_name,...] , [rows,......
Load datas from local file. 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(...
Return a dictionnary of current tables def dumps(self): """Return a dictionnary of current tables""" return {table_name: getattr(self, table_name).dumps() for table_name in self.TABLES}
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 def save_to_local(self, callback_etat=print): """ Saved current in memory base to local file. It's a backup, not a c...
reads the cell at position x and y; puts the default styles in xlwt 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...
writing style and value in the cell of x and y position 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.wri...
This function checks if a path was given as string, and tries to read the file and return the string. 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 '/' i...
This function handles and validates the wrapper arguments. 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, usa...
Check whether the input files are in fasta format, reads format or other/mix formats. def check_file_type(files): """ Check whether the input files are in fasta format, reads format or other/mix formats. """ all_are_fasta = True all_are_reads = True all_are_empty = True if sys.version_i...
This function returns list of files in the given dir 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') newlis...
Creates Rackspace Instance and saves it state in a local json file def create_server_rackspace(connection, distribution, disk_name, disk_size, ami, region, ...
terminates the instance 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: serve...
queries Rackspace for details about a particular server id 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 data['...
Add python types decoding. See JsonEncoder 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.JSONDecodeE...
Shortcut for string like fields def _type_string(label, case=None): """Shortcut for string like fields""" return label, abstractSearch.in_string, lambda s: abstractRender.default(s, case=case), ""
Shortcut fot boolean like fields def _type_bool(label,default=False): """Shortcut fot boolean like fields""" return label, abstractSearch.nothing, abstractRender.boolen, default
abstractSearch dans une chaine, sans tenir compte de la casse. 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
abstractSearch dans une date datetime.date 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 Fal...
abstractSearch dans une date-heure datetime.datetime (cf abstractRender.dateheure) def in_dateheure(objet, pattern): """ abstractSearch dans une date-heure datetime.datetime (cf abstractRender.dateheure) """ if objet: pattern = re.sub(" ", '', pattern) objet_str = abstractRender...
abstractSearch dans une liste de téléphones. def in_telephones(objet, pattern): """ abstractSearch dans une liste de téléphones.""" objet = objet or [] if pattern == '' or not objet: return False return max(bool(re.search(pattern, t)) for t in objet)
abstractRender d'une date datetime.date def date(objet): """ abstractRender d'une date datetime.date""" if objet: return "{}/{}/{}".format(objet.day, objet.month, objet.year) return ""
abstractRender d'une date-heure datetime.datetime au format JJ/MM/AAAAàHH:mm def dateheure(objet): """ abstractRender d'une date-heure datetime.datetime au format JJ/MM/AAAAàHH:mm """ if objet: return "{}/{}/{} à {:02}:{:02}".format(objet.day, objet.month, objet.year, objet.hour, objet.minu...
Install a _() function using the given translation domain. Given a translation domain, install a _() function using gettext's install() function. The main difference from gettext.install() is that we allow overriding the default localedir (e.g. /usr/share/locale) using a translation-domain-specifi...
Lists the available languages for the given translation domain. :param domain: the domain to get languages for 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_LANGUAG...
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 ...
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. ...
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...
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 mess...
Return a dict that only has matching entries in the msgid. 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 aro...
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` def registry_adapter(obj, request): """ Adapter for rendering a :class:`pyramid_urireferencer.models.Regi...
Adapter for rendering a :class:`pyramid_urireferencer.models.ApplicationResponse` to json. :param pyramid_urireferencer.models.ApplicationResponse obj: The response to be rendered. :rtype: :class:`dict` def application_adapter(obj, request): """ Adapter for rendering a :class:`pyramid_urireferencer.mo...
If put_back is True, put in umlauts; else, take them out! 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...
Function for extracting extra seqeunce data to the query alignment if the full reference length are not covered def get_query_align(hit, contig): """ Function for extracting extra seqeunce data to the query alignment if the full reference length are not covered """ # Getti...
Returns a tuple of lookups to order by for the given column and direction. Direction is an integer, either -1, 0 or 1. 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,...
Take a model instance and return it as a json struct 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 spe...
Take a json strust and a model name, and return a model instance def json_to_model(self, model_name, j): """Take a json strust and a model name, and return a model instance""" if model_name not in self.swagger_dict['definitions']: raise ValidationError("Swagger spec has no definition for mo...
Validate an object against its swagger model 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 ...
Find all server endpoints defined in the swagger spec and calls 'callback' for each, with an instance of EndpointData as argument. 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 ...
Buffer stdin and flush, and avoid incomplete files. 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", ...
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_suf...
Create a Constant Contact email marketing campaign. Returns an EmailMarketingCampaign object. def new_email_marketing_campaign(self, name, email_content, from_email, from_name, reply_to_email, subject, text_content, address, ...
Update a Constant Contact email marketing campaign. Returns the updated EmailMarketingCampaign object. def update_email_marketing_campaign(self, email_marketing_campaign, name, email_content, from_email, from_name, reply_to_email, ...
Deletes a Constant Contact email marketing campaign. 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_cam...
Inlines CSS defined in external style sheets. 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
Returns HTML and text previews of an EmailMarketingCampaign. 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(em...
Pull constant_contact_id out of data. def pre_save(cls, sender, instance, *args, **kwargs): """Pull constant_contact_id out of data. """ instance.constant_contact_id = str(instance.data['id'])
Deletes the CC email marketing campaign associated with me. 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_fo...
Run the necessary methods in the correct order 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 t...
Will send a multi-format email to recipients. Email may be queued through celery 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, b...
Initialize a database connection by each connection string defined in the configuration file def initialize_connections(self, scopefunc=None): """ Initialize a database connection by each connection string defined in the configuration file """ for connection_name, connec...
Implément un tri par attrbut. :param str attribut: Nom du champ concerné :param bool order: Ordre croissant ou décroissant def sort(self, attribut, order=False): """ Implément un tri par attrbut. :param str attribut: Nom du champ concerné :param bool order: Ordre crois...
Return the row of given Id if it'exists, otherwise None. Only works with pseudo-acces 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: ret...
Append acces to list. Quite slow since it checks uniqueness. kwargs may set `info` for this acces. 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...
Suppress acces with id = key 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)
Returns information associated with Id or list index 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,{})
Performs a search field by field, using functions defined in formats. Matchs are marked with info[`font`] :param pattern: String to look for :param entete: Fields to look into :return: Nothing. The collection is changed in place def recherche(self, pattern, entete): """Performs...
Merges collections. Ensure uniqueness of ids 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 = collectio...
Stringify time in ISO 8601 format. 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...
Parse time from ISO 8601 format. 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))
Returns formatted utcnow. def strtime(at=None, fmt=PERFECT_TIME_FORMAT): """Returns formatted utcnow.""" if not at: at = utcnow() return at.strftime(fmt)
Normalize time in arbitrary timezone to UTC naive object. 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
Return True if before is older than seconds. 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() - ...
Return True if after is newer than seconds. 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() > ...
Timestamp version of our utcnow function. 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(...
Overridable version of utils.utcnow. 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()
Advance overridden time using a datetime.timedelta. 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_ti...
Make an rpc-safe datetime with microseconds. Note: tzinfo is stripped, but not required for relative times. 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 ...
Unmarshall a datetime dict. def unmarshall_time(tyme): """Unmarshall a datetime dict.""" return datetime.datetime(day=tyme['day'], month=tyme['month'], year=tyme['year'], hour=tyme['hour'], minut...
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. def total_seconds(delta): """Return the total seconds of datetime.timedelta object. Compute total seconds of da...
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 def is_soon(dt, window): """Determines if time is going to happen in the next window ...
Download the file at url to target using Powershell (which will validate trust). Raise an exception if the command cannot complete. 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 co...
Use Python to download the file, even though it cannot authenticate the connection. 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: ...
Build the arguments to 'python setup.py install' on the setuptools package 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('--us...