text
stringlengths
81
112k
Writes the RST file to our destination RST filename, making any necessary directories. Args: prefix: as for :func:`rst_content` suffix: as for :func:`rst_content` heading_underline_char: as for :func:`rst_content` method: as for :func:`rst_content` ...
Adds source files to the index. Args: source_filenames_or_globs: string containing a filename or a glob, describing the file(s) to be added, or a list of such strings method: optional method to override ``self.method`` recursive: use :func:`gl...
Returns a sorted list of filenames to process, from a filename, a glob string, or a list of filenames/globs. Args: source_filenames_or_globs: filename/glob, or list of them recursive: use :func:`glob.glob` in recursive mode? Returns: sorted list of files to ...
The ``glob.glob`` function doesn't do exclusion very well. We don't want to have to specify root directories for exclusion patterns. We don't want to have to trawl a massive set of files to find exclusion files. So let's implement a glob match. Args: filename: filename ...
Should we exclude this file from consideration? def should_exclude(self, filename) -> bool: """ Should we exclude this file from consideration? """ for skip_glob in self.skip_globs: if self.filename_matches_glob(filename, skip_glob): return True retur...
Gets the RST filename corresponding to a source filename. See the help for the constructor for more details. Args: source_filename: source filename within current project Returns: RST filename Note in particular: the way we structure the directories means that ...
Writes both the individual RST files and the index. Args: overwrite: allow existing files to be overwritten? mock: pretend to write, but don't def write_index_and_rst_files(self, overwrite: bool = False, mock: bool = False) -> None: """ ...
Returns the filename of this index, relative to the director of another index. (For inserting a reference to this index into ``other``.) Args: other: the other index Returns: relative filename of our index def index_filename_rel_other_index(self, other: str) -> str: ...
Returns the contents of the index RST file. def index_content(self) -> str: """ Returns the contents of the index RST file. """ # Build the toctree command index_filename = self.index_filename spacer = " " toctree_lines = [ ".. toctree::", ...
Writes the index file, if permitted. Args: overwrite: allow existing files to be overwritten? mock: pretend to write, but don't def write_index(self, overwrite: bool = False, mock: bool = False) -> None: """ Writes the index file, if permitted. Args: ...
Parsing the hosts parameter, * currently support only one host :param hosts: the hosts json to parse :return: the full host and the authentication if exists def parse_host(hosts): """ Parsing the hosts parameter, * currently support only one host :param hosts: th...
Update the host ssl params (port or scheme) if needed. :param host: :return: def _update_ssl_params(host): """ Update the host ssl params (port or scheme) if needed. :param host: :return: """ if host[HostParsing.HOST] \ and EsParser._is_se...
Parse host string into a dictionary host :param host_str: :return: def _parse_string_host(host_str): """ Parse host string into a dictionary host :param host_str: :return: """ host_str = EsParser._fix_host_prefix(host_str) parsed_url = urlparse(ho...
Create a path from a list of sub paths. :param sub_paths: a list of sub paths :return: def make_path(*sub_paths): """ Create a path from a list of sub paths. :param sub_paths: a list of sub paths :return: """ queued_params = [quote(c.encode('utf-8'), '') ...
Prepare Elasticsearch request url. :param hostname: host name :param path: request path :param params: optional url params :return: def prepare_url(hostname, path, params=None): """ Prepare Elasticsearch request url. :param hostname: host name :param path...
Plot a basic sine wave with oscillating amplitude def basic_animation(frames=100, interval=30): """Plot a basic sine wave with oscillating amplitude""" fig = plt.figure() ax = plt.axes(xlim=(0, 10), ylim=(-2, 2)) line, = ax.plot([], [], lw=2) x = np.linspace(0, 10, 1000) def init(): l...
Plot a 3D visualization of the dynamics of the Lorenz system def lorenz_animation(N_trajectories=20, rseed=1, frames=200, interval=30): """Plot a 3D visualization of the dynamics of the Lorenz system""" from scipy import integrate from mpl_toolkits.mplot3d import Axes3D from matplotlib.colors import cn...
frame_list should be a list of filenames def _included_frames(frame_list, frame_format): """frame_list should be a list of filenames""" return INCLUDED_FRAMES.format(Nframes=len(frame_list), frame_dir=os.path.dirname(frame_list[0]), frame_form...
frame_list should be a list of base64-encoded png files def _embedded_frames(frame_list, frame_format): """frame_list should be a list of base64-encoded png files""" template = ' frames[{0}] = "data:image/{1};base64,{2}"\n' embedded = "\n" for i, frame_data in enumerate(frame_list): embedded +...
Points within 'std_limit' standard deviations from the mean and with errors greater than 'error_limit' times the error mean are considered as noise and thus are eliminated. def remove_noise(time, magnitude, error, error_limit=3, std_limit=5): """Points within 'std_limit' standard deviations from the mean a...
Synchronizes the light-curves in the two different bands. Returns ------- aligned_time aligned_magnitude aligned_magnitude2 aligned_error aligned_error2 def align(time, time2, magnitude, magnitude2, error, error2): """Synchronizes the light-curves in the two different bands. Retu...
Return the full list of variables stars of OGLE-3 as a DataFrame def load_OGLE3_catalog(): """Return the full list of variables stars of OGLE-3 as a DataFrame """ with bz2.BZ2File(CATALOG_PATH) as bz2fp, warnings.catch_warnings(): warnings.simplefilter("ignore") df = pd.read_table(bz2fp, s...
Retrieve a lighte curve from OGLE-3 database Parameters ---------- ogle3_id : str The id of the source (see: ``load_OGLE3_catalog()`` for available sources. data_home : optional, default: None Specify another download and cache folder for the datasets. By default all fee...
Calculate the Feature Extractor Resolution Order. def sort_by_dependencies(exts, retry=None): """Calculate the Feature Extractor Resolution Order. """ sorted_ext, features_from_sorted = [], set() pending = [(e, 0) for e in exts] retry = len(exts) * 100 if retry is None else retry while pending...
returns the peak false alarm probabilities Hence the lower is the probability and the more significant is the peak def getSignificance(wk1, wk2, nout, ofac): """ returns the peak false alarm probabilities Hence the lower is the probability and the more significant is the peak """ expy = exp(-wk2) effm = 2....
Retrieve data from an url and store it into dest. Parameters ---------- url: str Link to the remote data dest: str Path where the file must be stored force: bool (default=False) Overwrite if the file exists Returns ------- cached: bool True if the file a...
Generate a data with any given random function. Parameters ---------- magf : callable Function to generate the magnitudes. magf_params : dict-like Parameters to feed the `magf` function. errf : callable Function to generate the magnitudes. errf_params : dict-like ...
Generate a data with magnitudes that follows a Gaussian distribution. Also their errors are gaussian. Parameters ---------- mu : float (default=0) Mean of the gaussian distribution of magnitudes sigma : float (default=1) Standar deviation of the gaussian distribution of magnitude ...
Generate a data with magnitudes that follows a uniform distribution; the error instead are gaussian. Parameters ---------- low : float, optional Lower boundary of the output interval. All values generated will be greater than or equal to low. The default value is 0. high : float...
Generate a data with magnitudes with periodic variability distribution; the error instead are gaussian. Parameters ---------- mu_err : float (default=0) Mean of the gaussian distribution of magnitudes sigma_err : float (default=1) Standar deviation of the gaussian distribution of m...
Probability density function for Lomb-Scargle periodogram Compute the expected probability density function of the periodogram for the null hypothesis - i.e. data consisting of Gaussian noise. Parameters ---------- z : array-like the periodogram value N : int the number of data...
Cumulative distribution for the Lomb-Scargle periodogram Compute the expected cumulative distribution of the periodogram for the null hypothesis - i.e. data consisting of Gaussian noise. Parameters ---------- z : array-like the periodogram value N : int the number of data point...
tau factor for estimating Davies bound (Baluev 2008, Table 1) def tau_davies(Z, fmax, t, y, dy, normalization='standard', dH=1, dK=3): """tau factor for estimating Davies bound (Baluev 2008, Table 1)""" N = len(t) NH = N - dH # DOF for null hypothesis NK = N - dK # DOF for periodic hypothesis Dt ...
False Alarm Probability based on estimated number of indep frequencies def fap_simple(Z, fmax, t, y, dy, normalization='standard'): """False Alarm Probability based on estimated number of indep frequencies """ N = len(t) T = max(t) - min(t) N_eff = fmax * T p_s = cdf_single(Z, N, normalization...
Davies upper-bound to the false alarm probability (Eqn 5 of Baluev 2008) def fap_davies(Z, fmax, t, y, dy, normalization='standard'): """Davies upper-bound to the false alarm probability (Eqn 5 of Baluev 2008) """ N = len(t) fap_s = fap_single(Z, N, normalization=normalization) tau = tau_...
Alias-free approximation to false alarm probability (Eqn 6 of Baluev 2008) def fap_baluev(Z, fmax, t, y, dy, normalization='standard'): """Alias-free approximation to false alarm probability (Eqn 6 of Baluev 2008) """ cdf = cdf_single(Z, len(t), normalization) tau = tau_davies(Z, fmax, t, y, ...
Approximate the False Alarm Probability Parameters ---------- TODO Returns ------- TODO def false_alarm_probability(Z, fmax, t, y, dy, normalization, method='baluev', method_kwds=None): """Approximate the False Alarm Probability Parameters ---------- ...
lightcurve of 2 bands (R, B) from the MACHO survey. Notes ----- The files are gathered from the original FATS project tutorial: https://github.com/isadoranun/tsfeat def load_MACHO(macho_id): """lightcurve of 2 bands (R, B) from the MACHO survey. Notes ----- The files are gathered fr...
Generate HTML representation of the animation def anim_to_html(anim, fps=None, embed_frames=True, default_mode='loop'): """Generate HTML representation of the animation""" if fps is None and hasattr(anim, '_interval'): # Convert interval in ms to frames per second fps = 1000. / anim._interval ...
Display the animation with an IPython HTML object def display_animation(anim, **kwargs): """Display the animation with an IPython HTML object""" from IPython.display import HTML return HTML(anim_to_html(anim, **kwargs))
Indent the string 's' with the character 'c', 'n' times. Parameters ---------- s : str String to indent c : str, default space String to use as indentation n : int, default 4 Number of chars to indent def indent(s, c=" ", n=4): """Indent the string 's' with the charact...
Generate a list of RangeQueries usable to boost the scores of more recent documents. Example: ``` queries = generate_date_tail_boost_queries("publish_date", { timedelta(days=90): 1, timedelta(days=30): 2, timedelta(days=10): 4, }) s = Search(BoolQuery(must=....
Recursively remove None-valued items from dict. :param in_dict: :return: def _clean_dict(in_dict): """ Recursively remove None-valued items from dict. :param in_dict: :return: """ out = {} for key, value in iteritems(in_dict): if isinstance(value, dict): value = ...
Yield batches of `count` items from the given iterable. >>> for x in batch([1, 2, 3, 4, 5, 6, 7], 3): >>> print(x) [1, 2, 3] [4, 5, 6] [7] :param iterable: An iterable :type iterable: Iterable :param count: Number of items per batch. If <= 0, nothing is yielded. :type count: int ...
Return an iterator of Django model objects in Elasticsearch order, optionally using the given Django queryset. If no queryset is given, a default queryset (Model.objects.all) is used. :param queryset: Optional queryset to filter in. :return: def get_objects(self, queryset=None): ...
Reset target collection (rebuild index). def reset(self): """ Reset target collection (rebuild index). """ self.connection.rebuild_index( self.index, coll_name=self.target_coll_name)
Update (upsert) the wordgatherer collection. :param index: Source index. :param fields: Fields to read. :param tokenizer: Tokenizer callable. Should split unicode to words :param cutoff: Ignore words with less than this many occurrences. def update(self, index, fields, tokenizer=default...
Search for a word within the wordgatherer collection. :param word: Word to search for. :param limit: Maximum number of results to return. def search(self, word, limit=30): """ Search for a word within the wordgatherer collection. :param word: Word to search for. :param l...
Validate that given notebook JSON is importable - Check for nbformat == 4 - Check that language is python Do not re-implement nbformat here :D def validate_nb(nb): """ Validate that given notebook JSON is importable - Check for nbformat == 4 - Check that language is python Do not re...
Filters a given module ast, removing non-whitelisted nodes It allows only the following top level items: - imports - function definitions - class definitions - top level assignments where all the targets on the LHS are all caps def filter_ast(module_ast): """ Filters a given module ast...
Get the code for a given notebook nb is passed in as a dictionary that's a parsed ipynb file def code_from_ipynb(nb, markdown=False): """ Get the code for a given notebook nb is passed in as a dictionary that's a parsed ipynb file """ code = PREAMBLE for cell in nb['cells']: if ce...
Generate ordered list of paths we should look for fullname module in def _get_paths(self, fullname): """ Generate ordered list of paths we should look for fullname module in """ real_path = os.path.join(*fullname[len(self.package_prefix):].split('.')) for base_path in sys.path: ...
Claims modules that are under ipynb.fs def find_spec(self, fullname, path, target=None): """ Claims modules that are under ipynb.fs """ if fullname.startswith(self.package_prefix): for path in self._get_paths(fullname): if os.path.exists(path): ...
Decorator for priming generator-based coroutines. def coroutine(func): """Decorator for priming generator-based coroutines. """ @wraps(func) def start(*args, **kwargs): g = func(*args, **kwargs) next(g) return g return start
Yield numbers from 0 to `to` every `delay` seconds. async def ticker(delay, to): """Yield numbers from 0 to `to` every `delay` seconds.""" for i in range(to): yield i await asyncio.sleep(delay)
A coroutine sink which prints received items stdout Args: sep: Optional separator to be printed between received items. end: Optional terminator to be printed after the last item. file: Optional stream to which to print. flush: Optional flag to force flushing after each item. def r...
Convert an iterable into a stream of events. Args: iterable: A series of items which will be sent to the target one by one. target: The target coroutine or sink. Returns: An iterator over any remaining items. def iterable_source(iterable, target): """Convert an iterable into a str...
Send events at random times with uniform probability. Args: rate: The average number of events to send per second. iterable: A series of items which will be sent to the target one by one. target: The target coroutine or sink. Returns: An iterator over any remaining items. def ...
Compose functions right to left. compose(f, g, h)(x) -> f(g(h(x))) Args: f, *fs: The head and rest of a sequence of callables. The rightmost function passed can accept any arguments and the returned function will have the same signature as this last prov...
Create a reducing transducer with the given reducer. Args: reducer: A two-argument function which will be used to combine the partial cumulative result in the first argument with the next item from the input stream in the second argument. Returns: A reducing transducer: A singl...
Create a scanning reducer. def scanning(reducer, init=UNSET): """Create a scanning reducer.""" reducer2 = reducer def scanning_transducer(reducer): return Scanning(reducer, reducer2, init) return scanning_transducer
Create a transducer which takes the first n items def taking(n): """Create a transducer which takes the first n items""" if n < 0: raise ValueError("Cannot take fewer than zero ({}) items".format(n)) def taking_transducer(reducer): return Taking(reducer, n) return taking_transducer
Create a transducer which drops the first n items def dropping(n): """Create a transducer which drops the first n items""" if n < 0: raise ValueError("Cannot drop fewer than zero ({}) items".format(n)) def dropping_transducer(reducer): return Dropping(reducer, n) return dropping_tran...
Create a transducer which produces non-overlapping batches. def batching(size): """Create a transducer which produces non-overlapping batches.""" if size < 1: raise ValueError("batching() size must be at least 1") def batching_transducer(reducer): return Batching(reducer, size) retur...
Create a transducer which produces a moving window over items. def windowing(size, padding=UNSET, window_type=tuple): """Create a transducer which produces a moving window over items.""" if size < 1: raise ValueError("windowing() size {} is not at least 1".format(size)) def windowing_transducer(r...
Create a transducer which obtains the first item, then terminates. def first(predicate=None): """Create a transducer which obtains the first item, then terminates.""" predicate = true if predicate is None else predicate def first_transducer(reducer): return First(reducer, predicate) return f...
Create a transducer which obtains the last item. def last(predicate=None): """Create a transducer which obtains the last item.""" predicate = true if predicate is None else predicate def last_transducer(reducer): return Last(reducer, predicate) return last_transducer
Create a transducer which obtains the item at the specified index. def element_at(index): """Create a transducer which obtains the item at the specified index.""" if index < 0: raise IndexError("element_at used with illegal index {}".format(index)) def element_at_transducer(reducer): retu...
Compile source code files to object files. Parameters ---------- files: iterable of path strings source files, if cwd is given, the paths are taken as relative. CompilerRunner_: CompilerRunner instance (optional) could be e.g. pycompilation.FortranCompilerRunner Will be inferred...
Link object files. Parameters ---------- obj_files: iterable of path strings out_file: path string (optional) path to executable/shared library, if missing it will be deduced from the last item in obj_files. shared: bool Generate a shared library? default: False Compiler...
Link python extension module (shared object) for importing Parameters ---------- obj_files: iterable of path strings object files to be linked so_file: path string Name (path) of shared object file to create. If not specified it will have the basname of the last object f...
Generates a C file from a Cython source file. Parameters ---------- src: path string path to Cython source destdir: path string (optional) Path to output directory (default: '.') cwd: path string (optional) Root of relative paths (default: '.') logger: logging.Logger ...
Compiles a source code file to an object file. Files ending with '.pyx' assumed to be cython files and are dispatched to pyx2obj. Parameters ---------- srcpath: path string path to source file CompilerRunner_: pycompilation.CompilerRunner subclass (optional) Default: deduced fro...
Convenience function If cwd is specified, pyxpath and dst are taken to be relative If only_update is set to `True` the modification time is checked and compilation is only run if the source is newer than the destination Parameters ---------- pyxpath: path string path to Cython sour...
Compiles sources in `srcs` to a shared object (python extension) which is imported. If shared object is newer than the sources, they are not recompiled but instead it is imported. Parameters ---------- srcs: string list of paths to sources extname: string name of extension (defa...
Creates a temporary directory and dumps, compiles and links provided source code. Parameters ---------- codes: iterable of name/source pair tuples build_dir: string (default: None) path to cache_dir. None implies use a temporary directory. **kwargs: keyword arguments passed onto...
Hack to switch Flask-Pymongo db :param name: db name def switch_db(name): """ Hack to switch Flask-Pymongo db :param name: db name """ with app.app_context(): app.extensions['pymongo'][mongo.config_prefix] = mongo.cx, mongo.cx[name]
Dictionary providing the list of arguments for every benchmark def arguments(self): """Dictionary providing the list of arguments for every benchmark""" if 'arguments' in self.attributes: LOGGER.warning( "WARNING: 'arguments' use in OSU yaml configuration fil...
ISO 8601 format. Interprets naive datetime as UTC with zulu suffix. def _(obj): """ISO 8601 format. Interprets naive datetime as UTC with zulu suffix.""" tz_offset = obj.utcoffset() if not tz_offset or tz_offset == UTC_ZERO: iso_datetime = obj.strftime('%Y-%m-%dT%H:%M:%S.%fZ') else: i...
Return a row generator for a reference def get_row_generator(self, ref, cache=None): """Return a row generator for a reference""" from inspect import isgenerator from rowgenerators import get_generator g = get_generator(ref) if not g: raise GenerateError("Cant fig...
Generate combinations of key, value pairs for each key in properties. Examples -------- properties = {'ent': ['geo_rev', 'supply_chain'], 'own', 'fi'} >> create_key_filter(properties) --> [('ent', 'geo_rev'), ('ent', 'supply_chain'), ('own', 'fi')] def create_key_filter(properties: Dict[str, lis...
Create indexer function to pluck values from list. def create_indexer(indexes: list): """Create indexer function to pluck values from list.""" if len(indexes) == 1: index = indexes[0] return lambda x: (x[index],) else: return itemgetter(*indexes)
Include the sequence elements matching the filter set. def including(self, sequence) -> Generator: """Include the sequence elements matching the filter set.""" return (element for element in sequence if self.indexer(element) in self.predicates)
Exclude the sequence elements matching the filter set. def excluding(self, sequence) -> Generator: """Exclude the sequence elements matching the filter set.""" return (element for element in sequence if self.indexer(element) not in self.predicates)
Check user permissions. :return: ``True`` if the identity is allowed the permission, else return ``False``. async def can(self, identity, permission) -> bool: """ Check user permissions. :return: ``True`` if the identity is allowed the permission, else return ``False``. """ ...
Works like :func:`Security.identity`, but when check is failed :func:`UnauthorizedError` exception is raised. :param identity: Claim :return: Checked claim or return ``None`` :raise: :func:`UnauthorizedError` async def check_authorized(self, identity): """ Works like :f...
Works like :func:`Security.can`, but when check is failed :func:`ForbiddenError` exception is raised. :param identity: Claim :param permission: Permission :return: Checked claim :raise: :func:`ForbiddenError` async def check_permission(self, identity, permission): """ ...
Pulls in command line arguments. def arguments(): """Pulls in command line arguments.""" DESCRIPTION = """\ """ parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=Raw) parser.add_argument("--email", dest="email", action='store', required=False, default=False, ...
Execute benchmarks on every node specified in arguments. If none are given, then execute benchmarks on every nodes specified in the ``network.nodes`` campaign configuration. def run(self, *nodes): """Execute benchmarks on every node specified in arguments. If none are given, then execut...
Execute benchmark on the specified node def run(self): """Execute benchmark on the specified node """ with self._scp_bensh_runner(): self._execute_bensh_runner() path = self._retrieve_tarball() try: self._aggregate_tarball(path) fi...
if "node" then test current node and next one if "tag", then create tests for every pair of the current tag. def node_pairing(self): """if "node" then test current node and next one if "tag", then create tests for every pair of the current tag. """ value = self.attributes['node_...
Write a valid gentoo make.conf file to :path:. Args: path - The output path of the make.conf def write_makeconfig(_path): """ Write a valid gentoo make.conf file to :path:. Args: path - The output path of the make.conf """ http_proxy = str(CFG["gentoo"]["http_proxy"]) ftp_...
Write a valid gentoo bashrc file to :path:. Args: path - The output path of the make.conf def write_bashrc(_path): """ Write a valid gentoo bashrc file to :path:. Args: path - The output path of the make.conf """ cfg_mounts = CFG["container"]["mounts"].value cfg_prefix = C...
Write a valid gentoo layout file to :path:. Args: path - The output path of the layout.conf def write_layout(_path): """ Write a valid gentoo layout file to :path:. Args: path - The output path of the layout.conf """ path.mkdir_uchroot("/etc/portage/metadata") path.mkfile...
Write a valid gentoo wgetrc file to :path:. Args: path - The output path of the wgetrc def write_wgetrc(_path): """ Write a valid gentoo wgetrc file to :path:. Args: path - The output path of the wgetrc """ http_proxy = str(CFG["gentoo"]["http_proxy"]) ftp_proxy = str(CFG[...
Setup benchbuild inside a container. This will query a for an existing installation of benchbuild and try to upgrade it to the latest version, if possible. def setup_benchbuild(): """ Setup benchbuild inside a container. This will query a for an existing installation of benchbuild and try to ...
ben-nett entry point def main(argv=None): """ben-nett entry point""" arguments = cli_common(__doc__, argv=argv) benet = BeNet(arguments['CAMPAIGN_FILE']) benet.run() if argv is not None: return benet
ben-elastic entry point def main(argv=None): """ben-elastic entry point""" arguments = cli_common(__doc__, argv=argv) es_export = ESExporter(arguments['CAMPAIGN-DIR'], arguments['--es']) es_export.export() if argv is not None: return es_export
Setter for **self.__name** attribute. :param value: Attribute value. :type value: unicode def name(self, value): """ Setter for **self.__name** attribute. :param value: Attribute value. :type value: unicode """ if value is not None: assert ...
Setter for **self.__activated** attribute. :param value: Attribute value. :type value: bool def activated(self, value): """ Setter for **self.__activated** attribute. :param value: Attribute value. :type value: bool """ if value is not None: ...