INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Insert a new axis corresponding to a given position in the array shape
def expand_dims(a, axis): """Insert a new axis, corresponding to a given position in the array shape Args: a (array_like): Input array. axis (int): Position (amongst axes) where new axis is to be inserted. """ if hasattr(a, 'expand_dims') and hasattr(type(a), '__array_interface__'): ...
Join a sequence of arrays together. Will aim to join ndarray RemoteArray and DistArray without moving their data if they happen to be on different engines.
def concatenate(tup, axis=0): """Join a sequence of arrays together. Will aim to join `ndarray`, `RemoteArray`, and `DistArray` without moving their data, if they happen to be on different engines. Args: tup (sequence of array_like): Arrays to be concatenated. They must have the same sh...
Stack arrays in sequence vertically ( row wise ) handling RemoteArray and DistArray without moving data.
def vstack(tup): """Stack arrays in sequence vertically (row wise), handling ``RemoteArray`` and ``DistArray`` without moving data. Args: tup (sequence of array_like) Returns: res: `ndarray`, if inputs were all local `RemoteArray`, if inputs were all on the same remote engine ...
Stack arrays in sequence horizontally ( column wise ) handling RemoteArray and DistArray without moving data.
def hstack(tup): """Stack arrays in sequence horizontally (column wise), handling ``RemoteArray`` and ``DistArray`` without moving data. Args: tup (sequence of array_like) Returns: res: `ndarray`, if inputs were all local `RemoteArray`, if inputs were all on the same remote en...
Stack arrays in sequence depth wise ( along third dimension ) handling RemoteArray and DistArray without moving data.
def dstack(tup): """Stack arrays in sequence depth wise (along third dimension), handling ``RemoteArray`` and ``DistArray`` without moving data. Args: tup (sequence of array_like) Returns: res: `ndarray`, if inputs were all local `RemoteArray`, if inputs were all on the same r...
Return the shape that would result from broadcasting the inputs
def _broadcast_shape(*args): """Return the shape that would result from broadcasting the inputs""" #TODO: currently incorrect result if a Sequence is provided as an input shapes = [a.shape if hasattr(type(a), '__array_interface__') else () for a in args] ndim = max(len(sh) for sh in shapes...
Compute the arithmetic mean along the specified axis.
def mean(a, axis=None, dtype=None, out=None, keepdims=False): """ Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. `float64` intermediate and return values a...
forces update of a local cached copy of the real object ( regardless of the preference setting self. cache )
def _fetch(self): """forces update of a local cached copy of the real object (regardless of the preference setting self.cache)""" if not self._obcache_current: from distob import engine ax = self._distaxis self._obcache = concatenate([ra._ob for ra in self._su...
Maps a slice object for whole array to slice objects for subarrays. Returns pair ( ss ms ) where ss is a list of subarrays and ms is a list giving the slice object that should be applied to each subarray.
def _tosubslices(self, sl): """Maps a slice object for whole array to slice objects for subarrays. Returns pair (ss, ms) where ss is a list of subarrays and ms is a list giving the slice object that should be applied to each subarray. """ N = self.shape[self._distaxis] st...
ax is a valid candidate for a distributed axis if the given subarray shapes are all the same when ignoring axis ax
def _valid_distaxis(shapes, ax): """`ax` is a valid candidate for a distributed axis if the given subarray shapes are all the same when ignoring axis `ax`""" compare_shapes = np.vstack(shapes) if ax < compare_shapes.shape[1]: compare_shapes[:, ax] = -1 return np.count...
Insert a new axis at a given position in the array shape Args: axis ( int ): Position ( amongst axes ) where new axis is to be inserted.
def expand_dims(self, axis): """Insert a new axis, at a given position in the array shape Args: axis (int): Position (amongst axes) where new axis is to be inserted. """ if axis == -1: axis = self.ndim if axis <= self._distaxis: subaxis = axis ...
Compute the arithmetic mean along the specified axis. See np. mean () for details.
def mean(self, axis=None, dtype=None, out=None, keepdims=False): """Compute the arithmetic mean along the specified axis. See np.mean() for details.""" if axis == -1: axis = self.ndim if axis is None: results = vectorize(mean)(self, axis, dtype, keepdims=False) ...
Returns True if successful False if failure
def run(*args, **kwargs): '''Returns True if successful, False if failure''' kwargs.setdefault('env', os.environ) kwargs.setdefault('shell', True) try: subprocess.check_call(' '.join(args), **kwargs) return True except subprocess.CalledProcessError: logger.debug('Error runn...
Return a command to launch a subshell
def cmd(): '''Return a command to launch a subshell''' if platform == 'win': return ['cmd.exe', '/K'] elif platform == 'linux': ppid = os.getppid() ppid_cmdline_file = '/proc/{0}/cmdline'.format(ppid) try: with open(ppid_cmdline_file) as f: cmd =...
Generate a prompt with a given prefix
def prompt(prefix=None, colored=True): '''Generate a prompt with a given prefix linux/osx: [prefix] user@host cwd $ win: [prefix] cwd: ''' if platform == 'win': return '[{0}] $P$G'.format(prefix) else: if colored: return ( '[{0}] ' # White pre...
Launch a subshell
def launch(prompt_prefix=None): '''Launch a subshell''' if prompt_prefix: os.environ['PROMPT'] = prompt(prompt_prefix) subprocess.call(cmd(), env=os.environ.data)
Append a file to file repository.
def add_file(self, file, **kwargs): """Append a file to file repository. For file monitoring, monitor instance needs file. Please put the name of file to `file` argument. :param file: the name of file you want monitor. """ if os.access(file, os.F_OK): if ...
Append files to file repository. ModificationMonitor can append files to repository using this. Please put the list of file names to filelist argument.
def add_files(self, filelist, **kwargs): """Append files to file repository. ModificationMonitor can append files to repository using this. Please put the list of file names to `filelist` argument. :param filelist: the list of file nmaes """ # check filelist is...
Run file modification monitor.
def monitor(self, sleep=5): """Run file modification monitor. The monitor can catch file modification using timestamp and file body. Monitor has timestamp data and file body data. And insert timestamp data and file body data before into while roop. In while roop, monitor get ...
Initialize a: class: ~flask. Flask application for use with this extension.
def init_app(self, app): """Initialize a :class:`~flask.Flask` application for use with this extension. """ self._jobs = [] if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['restpoints'] = self app.restpoints_instance = self ...
Adds a job to be included during calls to the/ status endpoint.
def add_status_job(self, job_func, name=None, timeout=3): """Adds a job to be included during calls to the `/status` endpoint. :param job_func: the status function. :param name: the name used in the JSON response for the given status function. The name of the function is th...
Decorator that invokes add_status_job.
def status_job(self, fn=None, name=None, timeout=3): """Decorator that invokes `add_status_job`. :: @app.status_job def postgresql(): # query/ping postgres @app.status_job(name="Active Directory") def active_directory(): ...
Page through text by feeding it to another program. Invoking a pager through this might support colors.
def _pipepager(text, cmd, color): """Page through text by feeding it to another program. Invoking a pager through this might support colors. """ import subprocess env = dict(os.environ) # If we're piping to less we might support colors under the # condition that cmd_detail = cmd.rsplit...
Renvoie une fonction numpy correspondant au nom passé en paramètre sinon renvoie la fonction elle - même
def _get_funky(func): """Renvoie une fonction numpy correspondant au nom passé en paramètre, sinon renvoie la fonction elle-même""" if isinstance(func, str): try: func = getattr(np, func) except: raise NameError("Nom de fonction non comprise") return func
Calcul du profil journalier
def profil_journalier(df, func='mean'): """ Calcul du profil journalier Paramètres: df: DataFrame de données dont l'index est une série temporelle (cf module xair par exemple) func: function permettant le calcul. Soit un nom de fonction numpy ('mean', 'max', ...) soit la fonction el...
Calcul du profil journalier
def profil_hebdo(df, func='mean'): """ Calcul du profil journalier Paramètres: df: DataFrame de données dont l'index est une série temporelle (cf module xair par exemple) func: function permettant le calcul. Soit un nom de fonction numpy ('mean', 'max', ...) soit la fonction elle-mê...
Calcul du profil annuel
def profil_annuel(df, func='mean'): """ Calcul du profil annuel Paramètres: df: DataFrame de données dont l'index est une série temporelle (cf module xair par exemple) func: function permettant le calcul. Soit un nom de fonction numpy ('mean', 'max', ...) soit la fonction elle-même ...
Transforme un champ date vers un objet python datetime Paramètres: date: - si None renvoie la date du jour - si de type str renvoie un objet python datetime - si de type datetime le retourne sans modification dayfirst: Si True aide l analyse du champ date de type str en informant le décrypteur que le jour se situe en d...
def to_date(date, dayfirst=False, format=None): """ Transforme un champ date vers un objet python datetime Paramètres: date: - si None, renvoie la date du jour - si de type str, renvoie un objet python datetime - si de type datetime, le retourne sans modification dayfirst: Si...
Formate une donnée d entrée pour être exploitable dans les fonctions liste_ * et get_ *.
def _format(noms): """ Formate une donnée d'entrée pour être exploitable dans les fonctions liste_* et get_*. Paramètres: noms: chaîne de caractère, liste ou tuples de chaînes de caractères ou pandas.Series de chaînes de caractères. Retourne: Une chaînes de caractères dont chaque éléme...
Génère une liste de date en tenant compte des heures de début et fin d une journée. La date de début sera toujours calée à 0h et celle de fin à 23h
def date_range(debut, fin, freq): """ Génère une liste de date en tenant compte des heures de début et fin d'une journée. La date de début sera toujours calée à 0h, et celle de fin à 23h Paramètres: debut: datetime représentant la date de début fin: datetime représentant la date de fin freq...
Connexion à la base XAIR
def _connect(self): """ Connexion à la base XAIR """ try: # On passe par Oracle Instant Client avec le TNS ORA_FULL self.conn = cx_Oracle.connect(self._ORA_FULL) self.cursor = self.conn.cursor() print('XAIR: Connexion établie') exc...
Liste des paramètres
def liste_parametres(self, parametre=None): """ Liste des paramètres Paramètres: parametre: si fourni, retourne l'entrée pour ce parametre uniquement """ condition = "" if parametre: condition = "WHERE CCHIM='%s'" % parametre _sql = """SELECT...
Décrit les mesures: - d un ou des reseaux - d une ou des stations - d un ou des parametres ou décrit une ( des ) mesures suivant son ( leur ) identifiant ( s ) Chaque attribut peut être étendu en rajoutant des noms séparés par des virgules ou en les mettant dans une liste/ tuple/ pandas. Series. Ainsi pour avoir la lis...
def liste_mesures(self, reseau=None, station=None, parametre=None, mesure=None): """ Décrit les mesures: - d'un ou des reseaux, - d'une ou des stations, - d'un ou des parametres ou décrit une (des) mesures suivant son (leur) identifiant(s) Chaque attribut peut êtr...
Liste des stations
def liste_stations(self, station=None, detail=False): """ Liste des stations Paramètres: station : un nom de station valide (si vide, liste toutes les stations) detail : si True, affiche plus de détail sur la (les) station(s). """ condition = "" if stati...
Liste des campagnes de mesure et des stations associées
def liste_campagnes(self, campagne=None): """ Liste des campagnes de mesure et des stations associées Paramètres: campagne: Si définie, liste des stations que pour cette campagne """ condition = "" if campagne: condition = "WHERE NOM_COURT_CM='%s' "...
Récupération des données de mesure.
def get_mesures(self, mes, debut=None, fin=None, freq='H', format=None, dayfirst=False, brut=False): """ Récupération des données de mesure. Paramètres: mes: Un nom de mesure ou plusieurs séparées par des virgules, une liste (list, tuple, pandas.Series) d...
Recupération des mesures manuelles ( labo ) pour un site
def get_manuelles(self, site, code_parametre, debut, fin, court=False): """ Recupération des mesures manuelles (labo) pour un site site: numéro du site (voir fonction liste_sites_prelevement) code_parametre: code ISO du paramètre à rechercher (C6H6=V4) debut: date de début du pr...
Récupération des indices ATMO pour un réseau donné.
def get_indices(self, res, debut, fin): """ Récupération des indices ATMO pour un réseau donné. Paramètres: res : Nom du ou des réseaux à chercher (str, list, pandas.Series) debut: date de début, format YYYY-MM-JJ (str) fin: Date de fin, format YYYY-MM-JJ (str) ...
Renvoie l indice et les sous_indices complet: renvoyer les complets ou les prévus reseau: nom du réseau à renvoyer debut: date de début à renvoyer fin: date de fin à renvoyer
def get_indices_et_ssi(self, reseau, debut, fin, complet=True): """Renvoie l'indice et les sous_indices complet: renvoyer les complets ou les prévus reseau: nom du réseau à renvoyer debut: date de début à renvoyer fin: date de fin à renvoyer Renvoi : reseau, date, Indice...
retourne les requêtes actuellement lancées sur le serveur
def get_sqltext(self, format_=1): """retourne les requêtes actuellement lancées sur le serveur""" if format_ == 1: _sql = """SELECT u.sid, substr(u.username,1,12) user_name, s.sql_text FROM v$sql s,v$session u WHERE s.hash_value = u.sql_hash_value AND sql...
Attempt to run a global hook by name with args
def run_global_hook(hook_name, *args): '''Attempt to run a global hook by name with args''' hook_finder = HookFinder(get_global_hook_path()) hook = hook_finder(hook_name) if hook: hook.run(*args)
Handler that calls each status job in a worker pool attempting to timeout. The resulting durations/ errors are written to the response as JSON.
def status(jobs): """Handler that calls each status job in a worker pool, attempting to timeout. The resulting durations/errors are written to the response as JSON. eg. `{ "endpoints": [ { "endpoint": "Jenny's Database", "duration": 1.002556324005127 }, { "endpoint"...
Calcule de moyennes glissantes
def moyennes_glissantes(df, sur=8, rep=0.75): """ Calcule de moyennes glissantes Paramètres: df: DataFrame de mesures sur lequel appliqué le calcul sur: (int, par défaut 8) Nombre d'observations sur lequel s'appuiera le calcul rep: (float, défaut 0.75) Taux de réprésentativité en dessous du...
Calcule si une valeur est dépassée durant une période donnée. Détecte un dépassement de valeur sur X heures/ jours/... consécutifs
def consecutive(df, valeur, sur=3): """Calcule si une valeur est dépassée durant une période donnée. Détecte un dépassement de valeur sur X heures/jours/... consécutifs Paramètres: df: DataFrame de mesures sur lequel appliqué le calcul valeur: (float) valeur à chercher le dépassement (strictement s...
Calcule le nombre de dépassement d une valeur sur l intégralité du temps ou suivant un regroupement temporel.
def nombre_depassement(df, valeur, freq=None): """ Calcule le nombre de dépassement d'une valeur sur l'intégralité du temps, ou suivant un regroupement temporel. Paramètres: df: DataFrame de mesures sur lequel appliqué le calcul valeur: (float) valeur à chercher le dépassement (strictement supé...
Calcul de l AOT40 du 1er mai au 31 juillet
def aot40_vegetation(df, nb_an): """ Calcul de l'AOT40 du 1er mai au 31 juillet *AOT40 : AOT 40 ( exprimé en micro g/m³ par heure ) signifie la somme des différences entre les concentrations horaires supérieures à 40 parties par milliard ( 40 ppb soit 80 micro g/m³ ), durant une période donnée en ...
Calcul de l AOT de manière paramètrable. Voir AOT40_vegetation ou AOT40_foret pour des paramètres préalablement fixés.
def _aot(df, nb_an=1, limite=80, mois_debut=5, mois_fin=7, heure_debut=7, heure_fin=19): """ Calcul de l'AOT de manière paramètrable. Voir AOT40_vegetation ou AOT40_foret pour des paramètres préalablement fixés. Paramètres: df: DataFrame de mesures sur lequel appliqué le calcul nb_an: ...
Calculs réglementaires pour le dioxyde d azote
def no2(df): """ Calculs réglementaires pour le dioxyde d'azote Paramètres: df: DataFrame contenant les mesures, avec un index temporel (voir xair.get_mesure) Retourne: Une série de résultats dans un DataFrame : ****** unité (u): µg/m3 (microgramme par mètre cube) Seuil de RI ...
Calculs réglementaires pour les particules PM10
def pm10(df): """ Calculs réglementaires pour les particules PM10 Paramètres: df: DataFrame contenant les mesures, avec un index temporel (voir xair.get_mesure) Retourne: Une série de résultats dans un DataFrame : ****** unité (u): µg/m3 (microgramme par mètre cube) Seuil de R...
Calculs réglementaires pour le dioxyde de soufre
def so2(df): """ Calculs réglementaires pour le dioxyde de soufre Paramètres: df: DataFrame contenant les mesures, avec un index temporel (voir xair.get_mesure) Retourne: Une série de résultats dans un DataFrame : ****** unité (u): µg/m3 (microgramme par mètre cube) Seuil de R...
Calculs réglementaires pour le monoxyde de carbone
def co(df): """ Calculs réglementaires pour le monoxyde de carbone Paramètres: df: DataFrame contenant les mesures, avec un index temporel (voir xair.get_mesure) Retourne: Une série de résultats dans un DataFrame : ****** unité (u): µg/m3 (microgramme par mètre cube) Valeur li...
Calculs réglementaires pour l ozone
def o3(df): """ Calculs réglementaires pour l'ozone Paramètres: df: DataFrame contenant les mesures, avec un index temporel (voir xair.get_mesure) Retourne: Une série de résultats dans un DataFrame : ****** unité (u): µg/m3 (microgramme par mètre cube) Seuil de RI sur 1H: 180u...
Calculs réglementaires pour le benzène
def c6h6(df): """ Calculs réglementaires pour le benzène Paramètres: df: DataFrame contenant les mesures, avec un index temporel (voir xair.get_mesure) Retourne: Une série de résultats dans un DataFrame : ****** unité (u): µg/m3 (microgramme par mètre cube) Objectif de qualité...
Calculs réglementaires pour l arsenic
def arsenic(df): """ Calculs réglementaires pour l'arsenic Paramètres: df: DataFrame contenant les mesures, avec un index temporel (voir xair.get_mesure) Retourne: Une série de résultats dans un DataFrame : ****** unité (u): ng/m3 (nanogramme par mètre cube) Valeur cible en mo...
Présente une synthèse des calculs réglementaires en fournissant les valeurs calculées suivant les réglementations définies dans chaque fonction de calcul et un tableau de nombre de dépassement.
def print_synthese(fct, df): """ Présente une synthèse des calculs réglementaires en fournissant les valeurs calculées suivant les réglementations définies dans chaque fonction de calcul et un tableau de nombre de dépassement. Paramètres: fct: fonction renvoyant les éléments calculées df: D...
Enregistre dans un fichier Excel une synthèse des calculs réglementaires en fournissant les valeurs calculées suivant les réglementations définies dans chaque fonction de calcul et un tableau de nombre de dépassement. Les résultats sont enregistrés
def excel_synthese(fct, df, excel_file): """ Enregistre dans un fichier Excel une synthèse des calculs réglementaires en fournissant les valeurs calculées suivant les réglementations définies dans chaque fonction de calcul et un tableau de nombre de dépassement. Les résultats sont enregistrés P...
Retourne au format html une synthèse des calculs réglementaires en fournissant les valeurs calculées suivant les réglementations définies dans chaque fonction de calcul et un tableau de nombre de dépassement.
def html_synthese(fct, df): """ Retourne au format html une synthèse des calculs réglementaires en fournissant les valeurs calculées suivant les réglementations définies dans chaque fonction de calcul et un tableau de nombre de dépassement. Paramètres: fct: fonction renvoyant les éléments calcu...
Pour chaque serie ( colonne ) d un DataFrame va rechercher la ( les ) valeur ( s ) et la ( les ) date ( s ) du ( des ) max.
def show_max(df): """Pour chaque serie (colonne) d'un DataFrame, va rechercher la (les) valeur(s) et la (les) date(s) du (des) max. Paramètres: df: DataFrame de valeurs à calculer Retourne: Un DataFrame montrant pour chaque serie (colonne), les valeurs maxs aux dates d'apparition. """ ...
Calcul le taux de représentativité d un dataframe
def taux_de_representativite(df): """Calcul le taux de représentativité d'un dataframe""" return (df.count().astype(pd.np.float) / df.shape[0] * 100).round(1)
Validate all the entries in the environment cache.
def validate(self): '''Validate all the entries in the environment cache.''' for env in list(self): if not env.exists: self.remove(env)
Load the environment cache from disk.
def load(self): '''Load the environment cache from disk.''' if not os.path.exists(self.path): return with open(self.path, 'r') as f: env_data = yaml.load(f.read()) if env_data: for env in env_data: self.add(VirtualEnvironment(env['ro...
Save the environment cache to disk.
def save(self): '''Save the environment cache to disk.''' env_data = [dict(name=env.name, root=env.path) for env in self] encode = yaml.safe_dump(env_data, default_flow_style=False) with open(self.path, 'w') as f: f.write(encode)
Prompts a user for input. This is a convenience function that can be used to prompt a user for input later.
def prompt(text, default=None, hide_input=False, confirmation_prompt=False, type=None, value_proc=None, prompt_suffix=': ', show_default=True, err=False): """Prompts a user for input. This is a convenience function that can be used to prompt a user for input later. If the ...
This function takes a text and shows it via an environment specific pager on stdout.
def echo_via_pager(text, color=None): """This function takes a text and shows it via an environment specific pager on stdout. .. versionchanged:: 3.0 Added the `color` flag. :param text: the text to page. :param color: controls if the pager supports ANSI colors or not. The ...
( Executed on remote engine ) creates an ObjectEngine instance
def _remote_setup_engine(engine_id, nengines): """(Executed on remote engine) creates an ObjectEngine instance """ if distob.engine is None: distob.engine = distob.ObjectEngine(engine_id, nengines) # TODO these imports should be unnecessary with improved deserialization import numpy as np fr...
Prepare all iPython engines for distributed object processing.
def setup_engines(client=None): """Prepare all iPython engines for distributed object processing. Args: client (ipyparallel.Client, optional): If None, will create a client using the default ipyparallel profile. """ if not client: try: client = ipyparallel.Client() ...
Select local or remote execution and prepare arguments accordingly. Assumes any remote args have already been moved to a common engine.
def _process_args(args, kwargs, prefer_local=True, recurse=True): """Select local or remote execution and prepare arguments accordingly. Assumes any remote args have already been moved to a common engine. Local execution will be chosen if: - all args are ordinary objects or Remote instances on the loca...
( Executed on remote engine ) convert Ids to real objects call f
def _remote_call(f, *args, **kwargs): """(Executed on remote engine) convert Ids to real objects, call f """ nargs = [] for a in args: if isinstance(a, Id): nargs.append(distob.engine[a]) elif (isinstance(a, collections.Sequence) and not isinstance(a, string_types...
Execute f on the arguments either locally or remotely as appropriate. If there are multiple remote arguments they must be on the same engine. kwargs: prefer_local ( bool optional ): Whether to return cached local results if available in preference to returning Remote objects. Default is True. block ( bool optional ): W...
def call(f, *args, **kwargs): """Execute f on the arguments, either locally or remotely as appropriate. If there are multiple remote arguments, they must be on the same engine. kwargs: prefer_local (bool, optional): Whether to return cached local results if available, in preference to ret...
Waits for and converts any AsyncResults. Converts any Ref into a Remote. Args: r: can be an ordinary object ipyparallel. AsyncResult a Ref or a Sequence of objects AsyncResults and Refs. Returns: either an ordinary object or a Remote instance
def convert_result(r): """Waits for and converts any AsyncResults. Converts any Ref into a Remote. Args: r: can be an ordinary object, ipyparallel.AsyncResult, a Ref, or a Sequence of objects, AsyncResults and Refs. Returns: either an ordinary object or a Remote instance""" if (isin...
( Executed on remote engine ) convert Ids to real objects call method
def _remote_methodcall(id, method_name, *args, **kwargs): """(Executed on remote engine) convert Ids to real objects, call method """ obj = distob.engine[id] nargs = [] for a in args: if isinstance(a, Id): nargs.append(distob.engine[a]) elif (isinstance(a, collections.Sequenc...
Call a method of obj either locally or remotely as appropriate. obj may be an ordinary object or a Remote object ( or Ref or object Id ) If there are multiple remote arguments they must be on the same engine. kwargs: prefer_local ( bool optional ): Whether to return cached local results if available in preference to re...
def methodcall(obj, method_name, *args, **kwargs): """Call a method of `obj`, either locally or remotely as appropriate. obj may be an ordinary object, or a Remote object (or Ref or object Id) If there are multiple remote arguments, they must be on the same engine. kwargs: prefer_local (bool,...
( Executed on remote or local engine ) Examines an object and returns info about any instance - specific methods or attributes. ( For example any attributes that were set by __init__ () )
def _scan_instance(obj, include_underscore, exclude): """(Executed on remote or local engine) Examines an object and returns info about any instance-specific methods or attributes. (For example, any attributes that were set by __init__() ) By default, methods or attributes starting with an underscore a...
class decorator. Modifies Remote subclasses to add proxy methods and attributes that mimic those defined in class base.
def proxy_methods(base, include_underscore=None, exclude=None, supers=True): """class decorator. Modifies `Remote` subclasses to add proxy methods and attributes that mimic those defined in class `base`. Example: @proxy_methods(Tree) class RemoteTree(Remote, Tree) The decorator registers ...
Distribute an obj or list to remote engines. Return an async result or ( possibly nested ) lists of async results each of which is a Ref
def _async_scatter(obj, destination=None): """Distribute an obj or list to remote engines. Return an async result or (possibly nested) lists of async results, each of which is a Ref """ #TODO Instead of special cases for strings and Remote, should have a # list of types that should not be ...
wait for async results and return proxy objects Args: ars: AsyncResult ( or sequence of AsyncResults ) each result type Ref. Returns: Remote * proxy object ( or list of them )
def _ars_to_proxies(ars): """wait for async results and return proxy objects Args: ars: AsyncResult (or sequence of AsyncResults), each result type ``Ref``. Returns: Remote* proxy object (or list of them) """ if (isinstance(ars, Remote) or isinstance(ars, numbers.Number) or ...
Turn a numpy ndarray into a DistArray or RemoteArray Args: ar ( array_like ) axis ( int optional ): specifies along which axis to split the array to distribute it. The default is to split along the last axis. None means do not distribute. destination ( int or list of int optional ): Optionally force the array to go to ...
def _scatter_ndarray(ar, axis=-1, destination=None, blocksize=None): """Turn a numpy ndarray into a DistArray or RemoteArray Args: ar (array_like) axis (int, optional): specifies along which axis to split the array to distribute it. The default is to split along the last axis. `None` means ...
Distribute obj or list to remote engines returning proxy objects Args: obj: any python object or list of objects axis ( int optional ): Can be used if scattering a numpy array specifying along which axis to split the array to distribute it. The default is to split along the last axis. None means do not distribute block...
def scatter(obj, axis=-1, blocksize=None): """Distribute obj or list to remote engines, returning proxy objects Args: obj: any python object, or list of objects axis (int, optional): Can be used if scattering a numpy array, specifying along which axis to split the array to distribute it. The...
Retrieve objects that have been distributed making them local again
def gather(obj): """Retrieve objects that have been distributed, making them local again""" if hasattr(obj, '__distob_gather__'): return obj.__distob_gather__() elif (isinstance(obj, collections.Sequence) and not isinstance(obj, string_types)): return [gather(subobj) for subobj ...
Upgrade normal function f to act in parallel on distibuted lists/ arrays
def vectorize(f): """Upgrade normal function f to act in parallel on distibuted lists/arrays Args: f (callable): an ordinary function which expects as its first argument a single object, or a numpy array of N dimensions. Returns: vf (callable): new function that takes as its first argu...
Apply a function in parallel to each element of the input
def apply(f, obj, *args, **kwargs): """Apply a function in parallel to each element of the input""" return vectorize(f)(obj, *args, **kwargs)
Call a method on each element of a sequence in parallel. Returns: list of results
def call_all(sequence, method_name, *args, **kwargs): """Call a method on each element of a sequence, in parallel. Returns: list of results """ kwargs = kwargs.copy() kwargs['block'] = False results = [] for obj in sequence: results.append(methodcall(obj, method_name, *args, **...
Configure engines so that remote methods returning values of type real_type will instead return by proxy as type proxy_type
def register_proxy_type(cls, real_type, proxy_type): """Configure engines so that remote methods returning values of type `real_type` will instead return by proxy, as type `proxy_type` """ if distob.engine is None: cls._initial_proxy_types[real_type] = proxy_type elif...
forces update of a local cached copy of the real object ( regardless of the preference setting self. cache )
def _fetch(self): """forces update of a local cached copy of the real object (regardless of the preference setting self.cache)""" if not self.is_local and not self._obcache_current: #print('fetching data from %s' % self._ref.id) def _remote_fetch(id): retu...
Supports: gettext ngettext. See package README or github ( https:// github. com/ tigrawap/ pybabel - json ) for more usage info.
def extract_json(fileobj, keywords, comment_tags, options): """ Supports: gettext, ngettext. See package README or github ( https://github.com/tigrawap/pybabel-json ) for more usage info. """ data=fileobj.read() json_extractor=JsonExtractor(data) strings_data=json_extractor.get_lines_data() ...
Returns string: line_numbers list Since all strings are unique it is OK to get line numbers this way. Since same string can occur several times inside single. json file the values should be popped ( FIFO ) from the list: rtype: list
def get_lines_data(self): """ Returns string:line_numbers list Since all strings are unique it is OK to get line numbers this way. Since same string can occur several times inside single .json file the values should be popped(FIFO) from the list :rtype: list """ ...
Returns True if path is a git repository.
def is_git_repo(path): '''Returns True if path is a git repository.''' if path.startswith('git@') or path.startswith('https://'): return True if os.path.exists(unipath(path, '.git')): return True return False
Returns True if path is in CPENV_HOME
def is_home_environment(path): '''Returns True if path is in CPENV_HOME''' home = unipath(os.environ.get('CPENV_HOME', '~/.cpenv')) path = unipath(path) return path.startswith(home)
Returns True if path contains a. cpenv file
def is_redirecting(path): '''Returns True if path contains a .cpenv file''' candidate = unipath(path, '.cpenv') return os.path.exists(candidate) and os.path.isfile(candidate)
Get environment path from redirect file
def redirect_to_env_paths(path): '''Get environment path from redirect file''' with open(path, 'r') as f: redirected = f.read() return shlex.split(redirected)
Returns an absolute expanded path
def expandpath(path): '''Returns an absolute expanded path''' return os.path.abspath(os.path.expandvars(os.path.expanduser(path)))
Like os. path. join but also expands and normalizes path parts.
def unipath(*paths): '''Like os.path.join but also expands and normalizes path parts.''' return os.path.normpath(expandpath(os.path.join(*paths)))
Like os. path. join but acts relative to this packages bin path.
def binpath(*paths): '''Like os.path.join but acts relative to this packages bin path.''' package_root = os.path.dirname(__file__) return os.path.normpath(os.path.join(package_root, 'bin', *paths))
Like os. makedirs but keeps quiet if path already exists
def ensure_path_exists(path, *args): '''Like os.makedirs but keeps quiet if path already exists''' if os.path.exists(path): return os.makedirs(path, *args)
Walk down a directory tree. Same as os. walk but allows for a depth limit via depth argument
def walk_dn(start_dir, depth=10): ''' Walk down a directory tree. Same as os.walk but allows for a depth limit via depth argument ''' start_depth = len(os.path.split(start_dir)) end_depth = start_depth + depth for root, subdirs, files in os.walk(start_dir): yield root, subdirs, fil...
Walk up a directory tree
def walk_up(start_dir, depth=20): ''' Walk up a directory tree ''' root = start_dir for i in xrange(depth): contents = os.listdir(root) subdirs, files = [], [] for f in contents: if os.path.isdir(os.path.join(root, f)): subdirs.append(f) ...
Preprocess a dict to be used as environment variables.
def preprocess_dict(d): ''' Preprocess a dict to be used as environment variables. :param d: dict to be processed ''' out_env = {} for k, v in d.items(): if not type(v) in PREPROCESSORS: raise KeyError('Invalid type in dict: {}'.format(type(v))) out_env[k] = PREPR...
Add a sequence value to env dict
def _join_seq(d, k, v): '''Add a sequence value to env dict''' if k not in d: d[k] = list(v) elif isinstance(d[k], list): for item in v: if item not in d[k]: d[k].insert(0, item) elif isinstance(d[k], string_types): v.append(d[k]) d[k] = v
Join a bunch of dicts
def join_dicts(*dicts): '''Join a bunch of dicts''' out_dict = {} for d in dicts: for k, v in d.iteritems(): if not type(v) in JOINERS: raise KeyError('Invalid type in dict: {}'.format(type(v))) JOINERS[type(v)](out_dict, k, v) return out_dict
Convert a dict containing environment variables into a standard dict. Variables containing multiple values will be split into a list based on the argument passed to pathsep.
def env_to_dict(env, pathsep=os.pathsep): ''' Convert a dict containing environment variables into a standard dict. Variables containing multiple values will be split into a list based on the argument passed to pathsep. :param env: Environment dict like os.environ.data :param pathsep: Path sepa...