text
stringlengths
81
112k
Delete a job. :param job_id: Job identifier to delete. :type job_id: :py:class:`uuid.UUID` :param bool wait: If the job is currently running, wait for it to complete before deleting it. def job_delete(self, job_id, wait=True): """ Delete a job. :param job_id: Job identifier to delete. :type job_id: :py...
Check if a job is enabled. :param job_id: Job identifier to check the status of. :type job_id: :py:class:`uuid.UUID` :rtype: bool def job_is_enabled(self, job_id): """ Check if a job is enabled. :param job_id: Job identifier to check the status of. :type job_id: :py:class:`uuid.UUID` :rtype: bool "...
Check if a job is currently running. False is returned if the job does not exist. :param job_id: Job identifier to check the status of. :type job_id: :py:class:`uuid.UUID` :rtype: bool def job_is_running(self, job_id): """ Check if a job is currently running. False is returned if the job does not exist....
An argparse type representing binary data encoded in base64. def bin_b64_type(arg): """An argparse type representing binary data encoded in base64.""" try: arg = base64.standard_b64decode(arg) except (binascii.Error, TypeError): raise argparse.ArgumentTypeError("{0} is invalid base64 data".format(repr(arg))) r...
An argparse type representing binary data encoded in hex. def bin_hex_type(arg): """An argparse type representing binary data encoded in hex.""" if re.match(r'^[a-f0-9]{2}(:[a-f0-9]{2})+$', arg, re.I): arg = arg.replace(':', '') elif re.match(r'^(\\x[a-f0-9]{2})+$', arg, re.I): arg = arg.replace('\\x', '') try...
An argparse type representing a valid directory. def dir_type(arg): """An argparse type representing a valid directory.""" if not os.path.isdir(arg): raise argparse.ArgumentTypeError("{0} is not a valid directory".format(repr(arg))) return arg
An argparse type representing an email address. def email_type(arg): """An argparse type representing an email address.""" if not is_valid_email_address(arg): raise argparse.ArgumentTypeError("{0} is not a valid email address".format(repr(arg))) return arg
An argparse type representing a logging level. def log_level_type(arg): """An argparse type representing a logging level.""" if not arg.upper() in ('NOTSET', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'): raise argparse.ArgumentTypeError("{0} is not a valid log level".format(repr(arg))) return getattr(logging,...
An argparse type representing a tcp or udp port number. def port_type(arg): """An argparse type representing a tcp or udp port number.""" error_msg = "{0} is not a valid port".format(repr(arg)) try: arg = ast.literal_eval(arg) except ValueError: raise argparse.ArgumentTypeError(error_msg) if arg < 0 or arg > ...
An argparse type representing a timespan such as 6h for 6 hours. def timespan_type(arg): """An argparse type representing a timespan such as 6h for 6 hours.""" try: arg = parse_timespan(arg) except ValueError: raise argparse.ArgumentTypeError("{0} is not a valid time span".format(repr(arg))) return arg
*trigger the conesearch* **Return:** - ``matchIndies`` -- the indicies of the input transient sources (syncs with ``uniqueMatchDicts``) - ``uniqueMatchDicts`` -- the crossmatch results **Usage:** See class docstring for usage examples .. todo :: ...
*match the transients against the sherlock-catalogues according to the search algorithm and return matches alongside the predicted classification(s)* **Return:** - ``classification`` -- the crossmatch results and classifications assigned to the transients See the class docstring for usage....
*perform an angular separation crossmatch against a given catalogue in the database and annotate the crossmatch with some value added parameters (distances, physical separations, sub-type of transient etc)* **Key Arguments:** - ``objectList`` -- the list of transient locations to match against the ...
*annotate each crossmatch with physical parameters such are distances etc* **Key Arguments:** - ``crossmatchDict`` -- the crossmatch dictionary - ``catalogueName`` -- the name of the catalogue the crossmatch results from - ``searchPara`` -- the search parameters for this ind...
*perform a bright star match on the crossmatch results if required by the catalogue search* **Key Arguments:** - ``matchedObjects`` -- the list of matched sources from the catalogue crossmatch - ``catalogueName`` -- the name of the catalogue the crossmatch results from - ``m...
*perform a bright star match on the crossmatch results if required by the catalogue search* **Key Arguments:** - ``matchedObjects`` -- the list of matched sources from the catalogue crossmatch - ``catalogueName`` -- the name of the catalogue the crossmatch results from - ``m...
*perform an physical separation crossmatch against a given catalogue in the database* This search is basically the same as the angular separation search except extra filtering is done to exclude sources outside the physical search radius (matched sources require distance info to calulate physical separations) ...
Get the host's ip number. def get_own_ip(): """Get the host's ip number. """ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: sock.connect(("8.8.8.8", 80)) except socket.gaierror: ip_ = "127.0.0.1" else: ip_ = sock.getsockname()[0] finally: sock.c...
Send the given message. def send(self, msg): """Send the given message. """ with self._pub_lock: self.publish.send_string(msg) return self
Stop the publisher. def stop(self): """Stop the publisher. """ self.publish.setsockopt(zmq.LINGER, 1) self.publish.close() return self
Send a heartbeat ... but only if *min_interval* seconds has passed since last beat. def heartbeat(self, min_interval=0): """Send a heartbeat ... but only if *min_interval* seconds has passed since last beat. """ if not self._heartbeat: self._heartbeat = _PublisherHea...
Start the publisher. def start(self): """Start the publisher. """ pub_addr = "tcp://*:" + str(self._port) self._publisher = self._publisher_class(pub_addr, self._name) LOGGER.debug("entering publish %s", str(self._publisher.destination)) addr = ("tcp://" + str(get_own_ip...
Stop the publisher. def stop(self): """Stop the publisher. """ LOGGER.debug("exiting publish") if self._publisher is not None: self._publisher.stop() self._publisher = None if self._broadcaster is not None: self._broadcaster.stop() ...
Get the light curve evaluated at a list of times using the current model. :param t: The times where the light curve should be evaluated (in days). :param tol: The stopping criterion for the exposure time integration. :param maxdepth: The maximum rec...
Get the light curve evaluated at a list of times using the current model. :param t: The times where the light curve should be evaluated (in days). :param tol: The stopping criterion for the exposure time integration. :param maxdepth: The maximum rec...
Configure the default stream handler for logging messages to the console, remove other logging handlers, and enable capturing warnings. .. versionadded:: 1.3.0 :param str logger: The logger to add the stream handler for. :param level: The level to set the logger to, will default to WARNING if no level is specifie...
Download a file from a url and save it to disk. :param str url: The URL to fetch the file from. :param str filename: The destination file to write the data to. def download(url, filename=None): """ Download a file from a url and save it to disk. :param str url: The URL to fetch the file from. :param str filena...
Take a number of bytes and convert it to a human readable number. :param int val: The number of bytes to format. :return: The size in a human readable format. :rtype: str def format_bytes_size(val): """ Take a number of bytes and convert it to a human readable number. :param int val: The number of bytes to for...
Search a file and return a list of all lines that match a regular expression. :param str expression: The regex to search for. :param file: The file to search in. :type file: str, file :param int flags: The regex flags to use when searching. :param bool invert: Select non matching lines instead. :return: All the ...
Open a URI in a platform intelligent way. On Windows this will use 'cmd.exe /c start' and on Linux this will use gvfs-open or xdg-open depending on which is available. If no suitable application can be found to open the URI, a RuntimeError will be raised. .. versionadded:: 1.3.0 :param str uri: The URI to open. ...
Convert a string from snake_case to CamelCase. :param str snake: The snake_case string to convert. :param bool upper_first: Whether or not to capitalize the first character of the string. :return: The CamelCase version of string. :rtype: str def parse_case_snake_to_camel(snake, upper_first=True): """ Convert ...
Convert a server string to a tuple suitable for passing to connect, for example converting 'www.google.com:443' to ('www.google.com', 443). :param str server: The server string to convert. :param int default_port: The port to use in case one is not specified in the server string. :return: The parsed server infor...
Convert a string timespan definition to seconds, for example converting '1m30s' to 90. If *timedef* is already an int, the value will be returned unmodified. :param timedef: The timespan definition to convert to seconds. :type timedef: int, str :return: The converted value in seconds. :rtype: int def parse_time...
Parse a string into a slug format suitable for use in URLs and other character restricted applications. Only utf-8 strings are supported at this time. :param str words: The words to parse. :param int maxlen: The maximum length of the slug. :return: The parsed words as a slug. :rtype: str def parse_to_slug(words...
Generate a random string of *size* length consisting of mixed case letters and numbers. This function is not meant for cryptographic purposes. :param int size: The length of the string to return. :return: A string consisting of random characters. :rtype: str def random_string_alphanumeric(size): """ Generate a ...
Generate a random string of *size* length consisting of lowercase letters and numbers. This function is not meant for cryptographic purposes. :param int size: The length of the string to return. :return: A string consisting of random characters. :rtype: str def random_string_lower_numeric(size): """ Generate a ...
Calculate the probability that two random values selected from an arbitrary sized pool of unique values will be equal. This is commonly known as the "Birthday Problem". :param int selections: The number of random selections. :param int poolsize: The number of unique random values in the pool to choose from. :rtyp...
Create a unique list or tuple from a provided list or tuple and preserve the order. :param seq: The list or tuple to preserve unique items from. :type seq: list, tuple :param key: If key is provided it will be called during the comparison process. :type key: function, None def unique(seq, key=None): """ Crea...
Make a random selection from the specified choices. Apply the *weight* function to each to return a positive integer representing shares of selection pool the choice should received. The *weight* function is passed a single argument of the choice from the *choices* iterable. :param choices: The choices to select f...
Iterate through an arithmetic progression. :param start: Starting number. :type start: float, int, long :param stop: Stopping number. :type stop: float, int, long :param step: Stepping size. :type step: float, int, long def xfrange(start, stop=None, step=1): """ Iterate through an arithmetic progression. :p...
Remove expired items from the cache. def cache_clean(self): """ Remove expired items from the cache. """ now = time.time() keys_for_removal = collections.deque() for key, (_, expiration) in self.__cache.items(): if expiration < now: keys_for_removal.append(key) for key in keys_for_removal: del ...
Set an option to an arbitrary value. :param str option: The name of the option to set. :param value: The value to set the option to. def set(self, option, value): """ Set an option to an arbitrary value. :param str option: The name of the option to set. :param value: The value to set the option to. """...
Reformats an exception by adding a message to it and reporting the original exception name and message def reformat_exception(cls, message, err, *format_args, **format_kwds): """ Reformats an exception by adding a message to it and reporting the original exception name and message ...
provides a context manager that will intercept exceptions and repackage them as Buzz instances with a message attached: .. code-block:: python with Buzz.handle_errors("It didn't work"): some_code_that_might_raise_an_exception() :param: message: The message to attach...
used to assert a certain state. If the expression renders a false value, an exception will be raised with the supplied message :param: message: The failure message to attach to the raised Buzz :param: expr: A boolean value indicating an evaluated expression :param: format_arg...
A simple wrapper that creates a new :class:`User`. :param username: String containing the username of the new user. :param email: String containing the email address of the new user. :param password: String containing the password for the new user. ...
Activate an :class:`User` by supplying a valid ``activation_key``. If the key is valid and an user is found, activates the user and return it. Also sends the ``activation_complete`` signal. :param activation_key: String containing the secret SHA1 for a valid activation. :r...
Checks for expired users and delete's the ``User`` associated with it. Skips if the user ``is_staff``. :return: A list containing the deleted users. def delete_expired_users(self): """ Checks for expired users and delete's the ``User`` associated with it. Skips if the user ``is...
Confirm an email address by checking a ``confirmation_key``. A valid ``confirmation_key`` will set the newly wanted email address as the current email address. Returns the user after success or ``False`` when the confirmation key is invalid. :param confirmation_key: String ...
Returns all the visible profiles available to this user. For now keeps it simple by just applying the cases when a user is not active, a user has it's profile closed to everyone or a user only allows registered users to view their profile. :param user: A Django :class:`User...
Generate html elements and schematic json def visit_html(self, node): """ Generate html elements and schematic json """ parentClsNode = node.parent.parent assert parentClsNode.attributes['objtype'] == 'class' assert parentClsNode.attributes['domain'] == 'py' sign...
Download npm packages required by package.json and extract required files from them def run(self): has_npm = npm_installation_check() if has_npm: run_npm_install() else: print("Warning: npm not installed using prebuilded js files!", file=sys.std...
Stellar density in CGS units def density(self): """Stellar density in CGS units """ r = self.radius * _Rsun m = self.mass * _Msun return 0.75 * m / (np.pi * r * r * r)
The approximate duration of the transit :math:`T_\mathrm{tot}` from Equation (14) in Winn (2010). def duration(self): """ The approximate duration of the transit :math:`T_\mathrm{tot}` from Equation (14) in Winn (2010). """ self._check_ps() rstar = self.system....
Add a :class:`Body` to the system. This function also sets the ``system`` attribute of the body. :param body: The :class:`Body` to add. def add_body(self, body): """ Add a :class:`Body` to the system. This function also sets the ``system`` attribute of the body. ...
Get the light curve evaluated at a list of times using the current model. :param t: The times where the light curve should be evaluated (in days). :param tol: The stopping criterion for the exposure time integration. :param maxdepth: The maximum rec...
Get the light curve evaluated at a list of times using the current model. :param t: The times where the light curve should be evaluated (in days). :param tol: The stopping criterion for the exposure time integration. :param maxdepth: The maximum rec...
Tags the current repository and commits changes to news files def main(): """Tags the current repository and commits changes to news files """ # see: # https://packaging.python.org/tutorials/distributing-packages/#uploading-your-project-to-pypi twine_repo = os.getenv('TWINE_REPOSITORY_URL...
Provide the context to use. This function takes care of creating new contexts in case of forks. def get_context(): """Provide the context to use. This function takes care of creating new contexts in case of forks. """ pid = os.getpid() if pid not in context: context[pid] = zmq.Context...
Decode an ISO formatted string to a datetime object. Allow a time-string without microseconds. We handle input like: 2011-11-14T12:51:25.123456 def strp_isoformat(strg): """Decode an ISO formatted string to a datetime object. Allow a time-string without microseconds. We handle input like: 2011-11...
Delete an analysis log from the database. def delete(context, force, yes, analysis_id): """Delete an analysis log from the database.""" analysis_obj = context.obj['store'].analysis(analysis_id) if analysis_obj is None: print(click.style('analysis log not found', fg='red')) context.abort() ...
*Import data in the list of dictionaries in the requested database table* Also adds HTMIDs and updates the sherlock-catalogue database helper table with the time-stamp of when the imported catlogue was last updated **Key Arguments:** - ``dictList`` - a list of dictionaries containing all t...
*Add HTMIDs to database table once all the data has been imported (HTM Levels 10,13,16)* **Usage:** .. code-block:: python self._add_htmids_to_database_table() def _add_htmids_to_database_table( self): """*Add HTMIDs to database table once all the data has be...
*Update the sherlock catalogues database helper table with the time-stamp of when this catlogue was last updated* **Usage:** .. code-block:: python self._update_database_helper_table() def _update_database_helper_table( self): """*Update the sherlock catalogu...
Attempt to resolve all internal links (locally). In case the linked resources are found either as members of the array or within the `includes` element, those will be replaced and reference the actual resources. No network calls will be performed. def resolve_links(self): """Attempt...
Authenticates a user through the combination email/username with password. :param identification: A string containing the username or email of the user that is trying to authenticate. :password: Optional string containing the password for the user. ...
Find a single analysis. def find_analysis(self, family, started_at, status): """Find a single analysis.""" query = self.Analysis.query.filter_by( family=family, started_at=started_at, status=status, ) return query.first()
Fetch analyses form the database. def analyses(self, *, family: str=None, query: str=None, status: str=None, deleted: bool=None, temp: bool=False, before: dt.datetime=None, is_visible: bool=None): """Fetch analyses form the database.""" analysis_query = self.Analysis.query if f...
Get a single analysis. def analysis(self, analysis_id: int) -> models.Analysis: """Get a single analysis.""" return self.Analysis.query.get(analysis_id)
Update the lastest updated date in the database. def track_update(self): """Update the lastest updated date in the database.""" metadata = self.info() metadata.updated_at = dt.datetime.now() self.commit()
Check if an analysis is currently running/pending for a family. def is_running(self, family: str) -> bool: """Check if an analysis is currently running/pending for a family.""" latest_analysis = self.analyses(family=family).first() return latest_analysis and latest_analysis.status in TEMP_STATU...
Add pending entry for an analysis. def add_pending(self, family: str, email: str=None) -> models.Analysis: """Add pending entry for an analysis.""" started_at = dt.datetime.now() new_log = self.Analysis(family=family, status='pending', started_at=started_at) new_log.user = self.user(ema...
Add a new user to the database. def add_user(self, name: str, email: str) -> models.User: """Add a new user to the database.""" new_user = self.User(name=name, email=email) self.add_commit(new_user) return new_user
Fetch a user from the database. def user(self, email: str) -> models.User: """Fetch a user from the database.""" return self.User.query.filter_by(email=email).first()
Count the number of failed jobs per category (name). def aggregate_failed(self) -> List: """Count the number of failed jobs per category (name).""" categories = self.session.query( self.Job.name.label('name'), sqa.func.count(self.Job.id).label('count') ).filter(self.Job....
*Perform conesearches of the online NED database and import the results into a the sherlock-database* The code: 1. uses the list of transient coordinates and queries NED for the results within the given search radius 2. Creates the `tcs_cat_ned_stream` table if it doesn't exist ...
*Create a list of dictionaries containing all the object ids (NED names) in the ned stream* **Return:** - ``dictList`` - a list of dictionaries containing all the object ids (NED names) in the ned stream **Usage:** .. code-block:: python dictList = stream._cre...
*Update the database helper table to give details of the ned cone searches performed* *Usage:* .. code-block:: python stream._update_ned_query_history() def _update_ned_query_history( self): """*Update the database helper table to give details of the ned cone ...
*Query NED using the names of the NED sources in our local database to retrieve extra metadata* *Usage:* .. code-block:: python stream._download_ned_source_metadata() def _download_ned_source_metadata( self): """*Query NED using the names of the NED sources in...
*Get the names of 50000 or less NED sources that still require metabase in the database* **Return:** - ``len(self.theseIds)`` -- the number of NED IDs returned *Usage:* .. code-block:: python numberSources = stream._get_ned_sources_needing_metadata() def _get...
*Query NED via name searcha and add result metadata to database* **Key Arguments:** - ``batchCount`` - the index number of the batch sent to NED (only needed for printing to STDOUT to give user idea of progress) *Usage:* .. code-block:: python numberSources = ...
*Count the sources in the NED table requiring metadata* **Return:** - ``self.total``, ``self.batches`` -- total number of galaxies needing metadata & the number of batches required to be sent to NED *Usage:* .. code-block:: python totalRemaining, numberOfBatch...
Start the receiver. def start(self): """Start the receiver. """ if not self._is_running: self._do_run = True self._thread.start() return self
Get the address(es). def get(self, name=""): """Get the address(es). """ addrs = [] with self._address_lock: for metadata in self._addresses.values(): if (name == "" or (name and name in metadata["service"])): mda ...
Check the age of the receiver. def _check_age(self, pub, min_interval=timedelta(seconds=0)): """Check the age of the receiver. """ now = datetime.utcnow() if (now - self._last_age_check) <= min_interval: return LOGGER.debug("%s - checking addresses", str(datetime.ut...
Run the receiver. def _run(self): """Run the receiver. """ port = broadcast_port nameservers = [] if self._multicast_enabled: recv = MulticastReceiver(port).settimeout(2.) while True: try: recv = MulticastReceiver(port)...
Add an address. def _add(self, adr, metadata): """Add an address. """ with self._address_lock: metadata["receive_time"] = datetime.utcnow() self._addresses[adr] = metadata
*Import the IFS catalogue into the sherlock-catalogues database* The method first generates a list of python dictionaries from the IFS datafile, imports this list of dictionaries into a database table and then generates the HTMIDs for that table. **Usage:** See class docstring for usage ...
*Generate the list of dictionaries containing all the rows in the IFS stream* **Return:** - ``dictList`` - a list of dictionaries containing all the rows in the IFS stream **Usage:** .. code-block:: python from sherlock.imports import IFS stre...
Humansize.py from Dive into Python3 Mark Pilgrim - http://www.diveintopython3.net/ Copyright (c) 2009, Mark Pilgrim, All rights reserved. Convert a file size to human-readable form. Keyword arguments: size -- file size in bytes a_kilobyte_is_1024_bytes -- if True (default), use multiples of 102...
Return width of available window area. Autodetection works for Windows and POSIX platforms. Returns 80 for others Code from http://bitbucket.org/techtonik/python-pager def get_console_width(): """Return width of available window area. Autodetection works for Windows and POSIX platforms. Retur...
:return: detected filename or None def filename_from_url(url): """:return: detected filename or None""" fname = os.path.basename(urlparse.urlparse(url).path) if len(fname.strip(" \n\t.")) == 0: return None return fname
Detect filename from Content-Disposition headers if present. http://greenbytes.de/tech/tc2231/ :param: headers as dict, list or string :return: filename from content-disposition header or None def filename_from_headers(headers): """Detect filename from Content-Disposition headers if present. http:...
Expands name portion of filename with numeric ' (x)' suffix to return filename that doesn't exist already. def filename_fix_existing(filename, dirname): """Expands name portion of filename with numeric ' (x)' suffix to return filename that doesn't exist already. """ name, ext = filename.rsplit('.',...
This callback for the download function is used to print the download bar def report_bar(bytes_so_far, total_size, speed, eta): ''' This callback for the download function is used to print the download bar ''' percent = int(bytes_so_far * 100 / total_size) current = approximate_size(bytes_so_far).c...
This callback for the download function is used when the total size is unknown def report_unknown(bytes_so_far, total_size, speed, eta): ''' This callback for the download function is used when the total size is unknown ''' sys.stdout.write( "Downloading: {0} / Unknown - {1}/s ".fo...
This callback for the download function is used when console width is not enough to print the bar. It prints only the sizes def report_onlysize(bytes_so_far, total_size, speed, eta): ''' This callback for the download function is used when console width is not enough to print the bar. It prints...
This is the Main function, which downloads a given link and saves on outdir (default = current directory) def download(link, outdir='.', chunk_size=4096): ''' This is the Main function, which downloads a given link and saves on outdir (default = current directory) ''' url = None fh = None ...
Display recent logs for analyses. def ls_cmd(context, before, status): """Display recent logs for analyses.""" runs = context.obj['store'].analyses( status=status, deleted=False, before=parse_date(before) if before else None, ).limit(30) for run_obj in runs: if run_obj.s...
Simple Google Analytics integration. First looks for an ``account`` parameter. If not supplied, uses Django ``GOOGLE_ANALYTICS_ACCOUNT`` setting. If account not set, raises ``TemplateSyntaxError``. :param account: Google Analytics account id to be used. def analytics(account=None, *args, **k...