text
stringlengths
81
112k
Display analyses. def analyses(): """Display analyses.""" per_page = int(request.args.get('per_page', 50)) page = int(request.args.get('page', 1)) query = store.analyses(status=request.args.get('status'), query=request.args.get('query'), is_visible=...
Display a single analysis. def analysis(analysis_id): """Display a single analysis.""" analysis_obj = store.analysis(analysis_id) if analysis_obj is None: return abort(404) if request.method == 'PUT': analysis_obj.update(request.json) store.commit() data = analysis_obj.to_...
Get's a Gravatar for a email address. :param size: The size in pixels of one side of the Gravatar's square image. Optional, if not supplied will default to ``80``. :param default: Defines what should be displayed if no image is found for this user. Optional argument which defau...
Redirect user after successful sign in. First looks for a ``requested_redirect``. If not supplied will fall-back to the user specific account page. If all fails, will fall-back to the standard Django ``LOGIN_REDIRECT_URL`` setting. Returns a string defining the URI to go next. :param redirect: ...
Generates a sha1 hash for supplied string. Doesn't need to be very secure because it's not used for password checking. We got Django for that. :param string: The string that needs to be encrypted. :param salt: Optionally define your own salt. If none is supplied, will use a random...
Returns datetime object with current point in time. In Django 1.4+ it uses Django's django.utils.timezone.now() which returns an aware or naive datetime that represents the current point in time when ``USE_TZ`` in project's settings is True or False respectively. In older versions of Django it uses dat...
This function demonstrates a more complex usage of the handle_errors ctx_mgr. The following features are demonstrated:: * Handling a specific exception type with ``exception_class`` * Absorbing exceptions by setting ``re_raise`` to ``False`` * Branching with ``do_except``, ``do_else``, and ``do_f...
Check if data is JSON serializable. def is_valid_data(obj): """Check if data is JSON serializable. """ if obj: try: tmp = json.dumps(obj, default=datetime_encoder) del tmp except (TypeError, UnicodeDecodeError): return False return True
Decode datetimes to python objects. def datetime_decoder(dct): """Decode datetimes to python objects. """ if isinstance(dct, list): pairs = enumerate(dct) elif isinstance(dct, dict): pairs = dct.items() result = [] for key, val in pairs: if isinstance(val, six.string_typ...
Convert a raw string to a Message. def _decode(rawstr): """Convert a raw string to a Message. """ # Check for the magick word. try: rawstr = rawstr.decode('utf-8') except (AttributeError, UnicodeEncodeError): pass except (UnicodeDecodeError): try: rawstr = ra...
Convert a Message to a raw string. def _encode(msg, head=False, binary=False): """Convert a Message to a raw string. """ rawstr = str(_MAGICK) + u"{0:s} {1:s} {2:s} {3:s} {4:s}".format( msg.subject, msg.type, msg.sender, msg.time.isoformat(), msg.version) if not head and msg.data: if n...
Return local sender. Don't use the getpass module, it looks at various environment variables and is unreliable. def _getsender(): """Return local sender. Don't use the getpass module, it looks at various environment variables and is unreliable. """ import os import pwd import socket...
Validate a messages attributes. def _validate(self): """Validate a messages attributes. """ if not is_valid_subject(self.subject): raise MessageError("Invalid subject: '%s'" % self.subject) if not is_valid_type(self.type): raise MessageError("Invalid type: '%s'" ...
Generate a new PK and sign its public key using the IK, add the timestamp aswell to allow for periodic rotations. def __generateSPK(self): """ Generate a new PK and sign its public key using the IK, add the timestamp aswell to allow for periodic rotations. """ key = sel...
Generate the given amount of OTPKs. :param num_otpks: Either an integer or None. If the value of num_otpks is None, set it to the max_num_otpks value of the configuration. def __generateOTPKs(self, num_otpks = None): """ Generate the given amount of OTPKs. :param num_...
:param secret_key_material: A bytes-like object encoding the secret key material. :returns: A bytes-like object encoding the shared secret key. def __kdf(self, secret_key_material): """ :param secret_key_material: A bytes-like object encoding the secret key material. :returns: A bytes-l...
Check whether the SPK is too old and generate a new one in that case. def __checkSPKTimestamp(self): """ Check whether the SPK is too old and generate a new one in that case. """ if time.time() - self.__spk["timestamp"] > self.__spk_timeout: self.__generateSPK()
If the amount of available OTPKs fell under the minimum, refills the OTPKs up to the maximum limit again. def __refillOTPKs(self): """ If the amount of available OTPKs fell under the minimum, refills the OTPKs up to the maximum limit again. """ remainingOTPKs = len(self...
Hide a one-time pre key from the public bundle. :param otpk_pub: The public key of the one-time pre key to hide, encoded as a bytes-like object. def hideFromPublicBundle(self, otpk_pub): """ Hide a one-time pre key from the public bundle. :param otpk_pub: The public key of...
Delete a one-time pre key, either publicly visible or hidden. :param otpk_pub: The public key of the one-time pre key to delete, encoded as a bytes-like object. def deleteOTPK(self, otpk_pub): """ Delete a one-time pre key, either publicly visible or hidden. :param otpk_pu...
Fill a PublicBundle object with the public bundle data of this State. :returns: An instance of PublicBundle, filled with the public data of this State. def getPublicBundle(self): """ Fill a PublicBundle object with the public bundle data of this State. :returns: An instance of PublicB...
Read, whether this State has changed since it was loaded/since this flag was last cleared. :returns: A boolean indicating, whether the public bundle data has changed since last reading this flag. Clears the flag when reading. def changed(self): """ Read, whether th...
Do the key exchange, as the active party. This involves selecting keys from the passive parties' public bundle. :param other_public_bundle: An instance of PublicBundle, filled with the public data of the passive party. :param allow_zero_otpks: A flag indicating whether bundles with ...
Do the key exchange, as the passive party. This involves retrieving data about the key exchange from the active party. :param passive_exchange_data: A structure generated by the active party, which contains data requried to complete the key exchange. See the "to_other" part of t...
Serialize the config data to the user home directory. :param mode: The octal Unix mode (permissions) for the config file. def save(self, mode=0o600): """ Serialize the config data to the user home directory. :param mode: The octal Unix mode (permissions) for the config file. "...
Piority of Arguments: Arguments passed in `kwargs` has the most piority, 'param' key in `kwargs` has less piority than `kwargs` and dictionary arguments in `args` have the least piority. Other arguments are ignored. Argument List: model - set model type, default value 'default'; ...
Call solver in order to calculate chemical potential. def getChemicalPotential(self, solution): """Call solver in order to calculate chemical potential. """ if isinstance(solution, Solution): solution = solution.getSolution() self.mu = self.solver.chemicalPotential(solution...
Store object to mat-file. TODO: determine format specification def store(self, filename=None, label=None, desc=None, date=None): """Store object to mat-file. TODO: determine format specification """ date = date if date else datetime.now() date = date.replace(microsecond=0).isoformat() ...
Restore object from mat-file. TODO: determine format specification def restore(self, filename): """Restore object from mat-file. TODO: determine format specification """ matfile = loadmat(filename) matfile['originals'] = matfile['originals'][0, 0] if matfile['dim'] == 1: ...
Calculate integral of damping terms of hamiltonian using rectangular method. def getDampingIntegral(self): """Calculate integral of damping terms of hamiltonian using rectangular method. """ reservoir = self.getReservoir() density = self.getDensity() length = self.model.getSpati...
Store object to mat-file. TODO: determine format specification def store(self, filename=None, label=None, desc=None, date=None): """Store object to mat-file. TODO: determine format specification """ date = datetime.now() if date is None else date filename = filename if filename else dat...
Restore object from mat-file. TODO: determine format specification def restore(self, filename): """Restore object from mat-file. TODO: determine format specification """ matfile = loadmat(filename) if matfile['dim'] == 1: matfile['solution'] = matfile['solution'][0, :] ...
Format a value for inclusion in an informative text string. def fmt_val(val, shorten=True): """Format a value for inclusion in an informative text string. """ val = repr(val) max = 50 if shorten: if len(val) > max: close = val[-1] val = val[0:max-4] + "..."...
Returns list of key=val pairs formatted for inclusion in an informative text string. def fmt_dict_vals(dict_vals, shorten=True): """Returns list of key=val pairs formatted for inclusion in an informative text string. """ items = dict_vals.items() if not items: return [fmt_val(None, shor...
Builds the command to execute MIP. def build_command(self, config, **kwargs): """Builds the command to execute MIP.""" command = ['perl', self.script, CLI_OPTIONS['config']['option'], config] for key, value in kwargs.items(): # enable passing in flags as "False" - shouldn't add comm...
Start a new MIP run. def execute(self, command): """Start a new MIP run.""" process = subprocess.Popen( command, preexec_fn=lambda: signal.signal(signal.SIGPIPE, signal.SIG_DFL) ) return process
Update wiki pages See class docstring for usage def update(self): """ Update wiki pages See class docstring for usage """ self.log.debug('starting the ``update`` method') if "sherlock wiki root" not in self.settings: print "Sherlock wiki settings n...
query the sherlock-catalogues database table metadata def _get_table_infos( self, trimmed=False): """query the sherlock-catalogues database table metadata """ self.log.debug('starting the ``_get_table_infos`` method') sqlQuery = u""" SELECT * FROM cr...
query the sherlock-catalogues database view metadata def _get_view_infos( self, trimmed=False): """query the sherlock-catalogues database view metadata """ self.log.debug('starting the ``_get_view_infos`` method') sqlQuery = u""" SELECT v.*, t.descri...
query the sherlock-catalogues database streamed data tables' metadata def _get_stream_view_infos( self, trimmed=False): """query the sherlock-catalogues database streamed data tables' metadata """ self.log.debug('starting the ``_get_stream_view_infos`` method') ...
generate markdown format tables from the database query results **Key Arguments:** - ``tableData`` -- the sherlock-catalogues database table metadata. - ``viewData`` -- the sherlock-catalogues database view metadata. - ``streamData`` -- the sherlock-catalogues database strea...
write the markdown formated content of the database tables' metadata to local wiki pages def _write_wiki_pages( self): """write the markdown formated content of the database tables' metadata to local wiki pages """ self.log.debug('starting the ``_write_wiki_pages`` method') ...
commit the changes and push them to github def _update_github( self): """commit the changes and push them to github """ self.log.debug('starting the ``_update_github`` method') from subprocess import Popen, PIPE, STDOUT gdir = self.settings["sherlock wiki root"] ...
Sends an email to this User. If settings.EMAIL_OVERRIDE_ADDRESS is set, this mail will be redirected to the alternate mail address. def email_user( self, subject, message, from_email=settings.DEFAULT_FROM_EMAIL, **kwargs ): """ Sends an email to this User. If settings.EMA...
Clean up files from "old" analyses runs. def clean(context, days_ago, yes): """Clean up files from "old" analyses runs.""" number_of_days_ago = dt.datetime.now() - dt.timedelta(days=days_ago) analyses = context.obj['store'].analyses( status='completed', before=number_of_days_ago, de...
*Query the sherlock-catalogues helper tables to generate a map of the important columns of each catalogue* Within your sherlock-catalogues database you need to manually map the inhomogeneous column-names from the sherlock-catalogues to an internal homogeneous name-set which includes *ra*, *dec*, *redshift*, *objec...
Grep out all lines with scancel example. def job_ids(log_stream): """Grep out all lines with scancel example.""" id_rows = [line for line in log_stream if 'scancel' in line] jobs = [id_row.strip()[-7:-1] for id_row in id_rows] return jobs
Using TOML format, load config from given path, or write out example based on defaults def get_or_create_config(path, config): """Using TOML format, load config from given path, or write out example based on defaults""" if os.path.isfile(path): with open(path) as fh: _LOG.debug("loading con...
Prepare for serialisation - returns a dictionary def _deflate(cls): """Prepare for serialisation - returns a dictionary""" data = {k: v for k, v in vars(cls).items() if not k.startswith("_")} return {Constants.CONFIG_KEY: data}
Update config by deserialising input dictionary def _inflate(cls, data): """Update config by deserialising input dictionary""" for k, v in data[Constants.CONFIG_KEY].items(): setattr(cls, k, v) return cls._deflate()
Decorator that patches an object before the decorated method is called and restores it afterwards. This is a wrapper around :func:`fudge.patcher.patch_object` Example:: >>> from fudge import with_patched_object >>> class Session: ... state = 'clean' ... >>> @wi...
Patches an object and returns an instance of :class:`fudge.patcher.PatchHandler` for later restoration. Note that if *obj* is not an object but a path to a module then it will be imported. You may want to use a more convenient wrapper :func:`with_patched_object` or :func:`patched_context` Example:: ...
Set a new value for the attribute of the object. def patch(self, patched_value): """Set a new value for the attribute of the object.""" try: if self.getter: setattr(self.getter_class, self.attr_name, patched_value) else: setattr(self.orig_object, ...
Restore the saved value for the attribute of the object. def restore(self): """Restore the saved value for the attribute of the object.""" if self.proxy_object is None: if self.getter: setattr(self.getter_class, self.attr_name, self.getter) elif self.is_local: ...
Parse MIP config file. Args: data (dict): raw YAML input from MIP analysis config file Returns: dict: parsed data def parse_config(data: dict) -> dict: """Parse MIP config file. Args: data (dict): raw YAML input from MIP analysis config file Returns: dict: parsed...
Parse MIP sample info file. Args: data (dict): raw YAML input from MIP qc sample info file Returns: dict: parsed data def parse_sampleinfo(data: dict) -> dict: """Parse MIP sample info file. Args: data (dict): raw YAML input from MIP qc sample info file Returns: ...
Parse MIP qc metrics file. Args: metrics (dict): raw YAML input from MIP qc metrics file Returns: dict: parsed data def parse_qcmetrics(metrics: dict) -> dict: """Parse MIP qc metrics file. Args: metrics (dict): raw YAML input from MIP qc metrics file Returns: dict...
Parse Peddy sexcheck output. def parse_peddy_sexcheck(handle: TextIO): """Parse Peddy sexcheck output.""" data = {} samples = csv.DictReader(handle) for sample in samples: data[sample['sample_id']] = { 'predicted_sex': sample['predicted_sex'], 'het_ratio': float(sample['...
Parse Chanjo sex-check output. def parse_chanjo_sexcheck(handle: TextIO): """Parse Chanjo sex-check output.""" samples = csv.DictReader(handle, delimiter='\t') for sample in samples: return { 'predicted_sex': sample['sex'], 'x_coverage': float(sample['#X_coverage']), ...
Usage: @owner_required(Entry) def manage_entry(request, pk=None, object=None): @owner_required() def entry_delete(*args, **kwargs): kwargs["post_delete_redirect"] = reverse('manage_blogs') return delete_object(*args, **kwargs) def owner_required(Model=None): """ Usage:...
Lazily imports a utils (class, function,or variable) from a module) from a string. @param imp: def import_util(imp): ''' Lazily imports a utils (class, function,or variable) from a module) from a string. @param imp: ''' mod_name, obj_name = imp.rsplit('.', 1) mod = importli...
Load cli options def get_cli(): """Load cli options""" parser = argparse.ArgumentParser( prog="auto_version", description="auto version v%s: a tool to control version numbers" % __version__, ) parser.add_argument( "--target", action="append", default=[], ...
r"""Subsitute temporary text buffers for `stdio` in a managed context. Context manager. Substitutes empty :cls:`~io.StringIO`\ s for :cls:`sys.stdout` and :cls:`sys.stderr`, and a :cls:`TeeStdin` for :cls:`sys.stdin` within the managed context. Upon exiting the context, the original stream object...
draws segments on image def draw_segments(image, segments, color=(255, 0, 0), line_width=1): """draws segments on image""" for segment in segments: x, y, w, h = segment cv2.rectangle(image, (x, y), (x + w, y + h), color, line_width)
draws horizontal lines def draw_lines(image, ys, color=(255, 0, 0), line_width=1): """draws horizontal lines""" for y in ys: cv2.line(image, (0, y), (image.shape[1], y), color, line_width)
Convert time in string format to seconds. Skipping seconds since sometimes the last column is truncated for entries where >10 days. def time_to_sec(time_str: str) -> int: """Convert time in string format to seconds. Skipping seconds since sometimes the last column is truncated for entries where >...
Convert sacct row to dict. def convert_job(row: list) -> dict: """Convert sacct row to dict.""" state = row[-2] start_time_raw = row[-4] end_time_raw = row[-3] if state not in ('PENDING', 'CANCELLED'): start_time = datetime.strptime(start_time_raw, '%Y-%m-%dT%H:%M:%S') if state != '...
Parse out information from sacct status output. def parse_sacct(sacct_stream): """Parse out information from sacct status output.""" rows = (line.split() for line in sacct_stream) # filter rows that begin with a SLURM job id relevant_rows = (row for row in rows if row[0].isdigit()) jobs = [convert_...
Filter jobs that have a FAILED etc. status. def filter_jobs(sacct_jobs, failed=True): """Filter jobs that have a FAILED etc. status.""" categories = FAILED_CATEGORIES if failed else NORMAL_CATEGORIES filtered_jobs = [job for job in sacct_jobs if job['state'] in categories] return filtered_jobs
given segments, outputs a array of line numbers, or -1 if it doesn't belong to any def guess_segments_lines(segments, lines, nearline_tolerance=5.0): """ given segments, outputs a array of line numbers, or -1 if it doesn't belong to any """ ys = segments[:, 1] closeness = numpy.abs(numpy.su...
givens a n*n matrix m, n=len(segments), in which m[i,j] means segments[i] is contained inside segments[j] def contained_segments_matrix(segments): """ givens a n*n matrix m, n=len(segments), in which m[i,j] means segments[i] is contained inside segments[j] """ x1, y1 = segments[:, 0], segments[...
sort segments in read order - left to right, up to down def _process(self, segments): """sort segments in read order - left to right, up to down""" # sort_f= lambda r: max_line_width*(r[1]/max_line_height)+r[0] # segments= sorted(segments, key=sort_f) # segments= segments_to_numpy( segm...
guesses and returns text inter-line distance, number of lines, y_position of first line def _guess_lines(ys, max_lines=50, confidence_minimum=0.0): """guesses and returns text inter-line distance, number of lines, y_position of first line""" ys = ys.astype(numpy.float32) compactness_list, means...
send data to *address* and *port* without verification of response. def _send_to_address(self, address, data, timeout=10): """send data to *address* and *port* without verification of response. """ # Socket to talk to server socket = get_context().socket(REQ) try: so...
Broadcasts forever. def _run(self): """Broadcasts forever. """ self._is_running = True network_fail = False try: while self._do_run: try: if network_fail is True: LOGGER.info("Network connection re-establish...
Create resource out of JSON data. :param json: JSON dict. :return: Resource with a type defined by the given JSON data. def from_json(self, json): """Create resource out of JSON data. :param json: JSON dict. :return: Resource with a type defined by the given JSON data. ...
Create :class:`.resources.Entry` from JSON. :param json: JSON dict. :return: Entry instance. def create_entry(self, json): """Create :class:`.resources.Entry` from JSON. :param json: JSON dict. :return: Entry instance. """ sys = json['sys'] ct = sys['co...
Create :class:`.resources.Asset` from JSON. :param json: JSON dict. :return: Asset instance. def create_asset(json): """Create :class:`.resources.Asset` from JSON. :param json: JSON dict. :return: Asset instance. """ result = Asset(json['sys']) file_dic...
Create :class:`.resource.ContentType` from JSON. :param json: JSON dict. :return: ContentType instance. def create_content_type(json): """Create :class:`.resource.ContentType` from JSON. :param json: JSON dict. :return: ContentType instance. """ result = Conten...
Given a :class:`.fields.Field` and a value, ensure that the value matches the given type, otherwise attempt to convert it. :param value: field value. :param field: :class:`.fields.Field` instance. :return: Result value. def convert_value(value, field): """Given a :class:`.field...
Iterate through all `items` and create a resource for each. In addition map the resources under the `items_mapped` by the resource id and type. :param array: Array resource. :param json: Raw JSON dictionary. def process_array_items(self, array, json): """Iterate through all `items` an...
Iterate through all `includes` and create a resource for every item. In addition map the resources under the `items_mapped` by the resource id and type. :param array: Array resource. :param json: Raw JSON dictionary. def process_array_includes(self, array, json): """Iterate through al...
Create :class:`.resources.Array` from JSON. :param json: JSON dict. :return: Array instance. def create_array(self, json): """Create :class:`.resources.Array` from JSON. :param json: JSON dict. :return: Array instance. """ result = Array(json['sys']) re...
Decorator that calls :func:`fudge.clear_calls` before method() and :func:`fudge.verify` afterwards. def with_fakes(method): """Decorator that calls :func:`fudge.clear_calls` before method() and :func:`fudge.verify` afterwards. """ @wraps(method) def apply_clear_and_verify(*args, **kw): clear_ca...
Clears out any calls that were made on previously registered fake objects and resets all call stacks. You do not need to use this directly. Use fudge.clear_calls() def clear_calls(self): """Clears out any calls that were made on previously registered fake objects and resets all call s...
Ensure all expected calls were called, raise AssertionError otherwise. You do not need to use this directly. Use fudge.verify() def verify(self): """Ensure all expected calls were called, raise AssertionError otherwise. You do not need to use this directly. Use fudge.verify(...
assert that calls have been made in the right order. def assert_order_met(self, finalize=False): """assert that calls have been made in the right order.""" error = None actual_call_len = len(self._actual_calls) expected_call_len = len(self._call_order) if actual_call_len == 0: ...
The fake must be called. .. doctest:: :hide: >>> import fudge >>> fudge.clear_expectations() >>> fudge.clear_calls() This is useful for when you stub out a function as opposed to a class. For example:: >>> import fudge ...
The fake can be called. This is useful for when you stub out a function as opposed to a class. For example:: >>> import fudge >>> remove = Fake('os.remove').is_callable() >>> remove('some/path') def is_callable(self): """The fake can be called. Th...
Redefine a call. The fake method will execute your function. I.E.:: >>> f = Fake().provides('hello').calls(lambda: 'Why, hello there') >>> f.hello() 'Why, hello there' def calls(self, call): """Redefine a call. The fake method will execute your function. ...
Expect a call. .. doctest:: :hide: >>> import fudge >>> fudge.clear_expectations() >>> fudge.clear_calls() If the method *call_name* is never called, then raise an error. I.E.:: >>> session = Fake('session').expects('open').expects('close'...
Start expecting or providing multiple calls. .. note:: next_call() cannot be used in combination with :func:`fudge.Fake.times_called` Up until calling this method, calls are infinite. For example, before next_call() ... :: >>> from fudge import Fake >>> f = Fake().pro...
Provide a call. The call acts as a stub -- no error is raised if it is not called.:: >>> session = Fake('session').provides('open').provides('close') >>> import fudge >>> fudge.clear_expectations() # from any previously declared fakes >>> fudge.clear_calls() ...
Set last call to raise an exception class or instance. For example:: >>> import fudge >>> db = fudge.Fake('db').provides('insert').raises(ValueError("not enough parameters for insert")) >>> db.insert() Traceback (most recent call last): ... ...
Verify that subsequent :func:`fudge.Fake.expects` are called in the right order. For example:: >>> import fudge >>> db = fudge.Fake('db').remember_order().expects('insert').expects('update') >>> db.update() Traceback (most recent call last): ... ...
Set the last call to return a value. Set a static value to return when a method is called. I.E.:: >>> f = Fake().provides('get_number').returns(64) >>> f.get_number() 64 def returns(self, val): """Set the last call to return a value. Set a static value to...
Set the last call to return a new :class:`fudge.Fake`. Any given arguments are passed to the :class:`fudge.Fake` constructor Take note that this is different from the cascading nature of other methods. This will return an instance of the *new* Fake, not self, so you should be careful ...
Set the number of times an object can be called. When working with provided calls, you'll only see an error if the expected call count is exceeded :: >>> auth = Fake('auth').provides('login').times_called(1) >>> auth.login() >>> auth.login() Traceback (m...
Set the last call to expect specific argument values. The app under test must send all declared arguments and keyword arguments otherwise your test will raise an AssertionError. For example: .. doctest:: >>> import fudge >>> counter = fudge.Fake('counter').expects('in...
Set the last call to expect specific argument values if those arguments exist. Unlike :func:`fudge.Fake.with_args` use this if you want to only declare expectations about matching arguments. Any unknown keyword arguments used by the app under test will be allowed. For example, you can...