INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Check if 'was passed a valid action in the command line and if so, executes it by passing parameters and returning the result. :return: (Any) Return the result of the called function, if provided, or None.
def check_command(self, **new_attributes): """ Check if 'was passed a valid action in the command line and if so, executes it by passing parameters and returning the result. :return: (Any) Return the result of the called function, if provided, or None. """ ...
Execute command.
def _execute(self, func, command, **new_attributes): """ Execute command. """ if self._cfg_factory: # if we have a cfg_factory try: # we try to load a config with the factory if self.cfg_file: self.cfg = self._cf...
Try to call events for cmd.
def _call_event(self, event_name, cmd, pargs, kwargs, **kws): """ Try to call events for cmd. """ def get_result_params(res): """return the right list of params""" if not isinstance(res, (list, tuple)): return res, pargs, kwargs elif le...
Call self event
def _self_event(self, event_name, cmd, *pargs, **kwargs): """Call self event""" if hasattr(self, event_name): getattr(self, event_name)(cmd, *pargs, **kwargs)
Add events
def add_event(cls, event, event_name=None): """Add events""" # setattr(cls, event_name, event) event_name = event_name or event.__name__ setattr(cls, event_name, types.MethodType(event, cls))
Writes to the output
def write(self, *string): """ Writes to the output """ self._output.write(' '.join([six.text_type(s) for s in string])) return self
Terminate the script.
def exit(self, status=EXIT_OK, message=None): """ Terminate the script. """ if not self.parser: self.parser = argparse.ArgumentParser() if self.msg_on_error_only: # if msg_on_error_only is True if status != EXIT_OK: # if we have...
Analysis of ligand SASA.
def analyse_ligand_sasa(self): """Analysis of ligand SASA.""" i=0 start = timer() if self.trajectory == []: self.trajectory = [self.topology_data.universe.filename] try: for traj in self.trajectory: new_traj = mdtraj.load(traj,top=self.topology_data.universe.filename) #Analyse only non-H ligand ...
Make a dictionary with SASA assigned to each ligand atom, stored as list of SASA values over the simulation time.
def assign_per_atom_sasa(self): """Make a dictionary with SASA assigned to each ligand atom, stored as list of SASA values over the simulation time.""" atom_names= [atom.name for atom in self.topology_data.universe.ligand_noH.atoms] sasa_dict = {} for atom in range(0,self.topology_data.universe.ligand_noH.n_a...
Return average SASA of the atoms.
def get_total_per_atom_sasa(self): """Return average SASA of the atoms.""" total_sasa = defaultdict(int) for traj in range(len(self.atom_sasa)): for atom in self.atom_sasa[traj]: total_sasa[atom]+=float(sum((self.atom_sasa[traj][atom])))/len(self.atom_sasa[traj][atom]) for atom in total_sasa: total_sa...
You can choose whether to use lock method when running threads.
def run(self, *args): """ You can choose whether to use lock method when running threads. """ if self.running: return self self._mut_finished(False) # in case of recovery from a disaster. self._mut_running(True) stream = self.target(*args) ...
Nanomsg fanout sub. (Experimental) This sub will use nanomsg to fanout the events. :param bind: the zmq pub socket or zmq device socket. :param tables: the events of tables to follow.
def nano_sub(bind, tables): """Nanomsg fanout sub. (Experimental) This sub will use nanomsg to fanout the events. :param bind: the zmq pub socket or zmq device socket. :param tables: the events of tables to follow. """ logger = logging.getLogger("meepo.sub.nano_sub") from nanomsg import S...
Add the impact severity for the most severe consequence Args: variant_obj (puzzle.models.Variant) gemini_variant (GeminiQueryRow)
def _add_impact_severity(self, variant_obj, gemini_variant): """Add the impact severity for the most severe consequence Args: variant_obj (puzzle.models.Variant) gemini_variant (GeminiQueryRow) """ gemini_impact = gemini_variant['impact_severi...
Add hgnc symbols to the variant If there are transcripts use the symbols found here, otherwise use phizz to get the gene ids.
def _add_hgnc_symbols(self, variant_obj): """Add hgnc symbols to the variant If there are transcripts use the symbols found here, otherwise use phizz to get the gene ids. """ hgnc_symbols = set() if variant_obj.transcripts: for transcript in v...
Add the Gene objects for a variant
def _add_genes(self, variant_obj): """Add the Gene objects for a variant""" genes = [] ensembl_ids = [] hgnc_symbols = [] if variant_obj.transcripts: for transcript in variant_obj.transcripts: if transcript.ensembl_id: ense...
Strict deco for RedisPrepareCommit The deco will choose whether to silent exception or not based on the strict attr in RedisPrepareCommit object.
def _redis_strict_pc(func): """Strict deco for RedisPrepareCommit The deco will choose whether to silent exception or not based on the strict attr in RedisPrepareCommit object. """ phase = "session_%s" % func.__name__ @functools.wraps(func) def wrapper(self, session, *args, **kwargs): ...
Determine the session phase in prepare commit. :param session: sqlalchemy session :return: phase "prepare" or "commit"
def phase(self, session): """Determine the session phase in prepare commit. :param session: sqlalchemy session :return: phase "prepare" or "commit" """ sp_key, _ = self._keygen(session) if self.r.sismember(sp_key, session.meepo_unique_id): return "prepare" ...
Prepare phase for session. :param session: sqlalchemy session
def prepare(self, session, event): """Prepare phase for session. :param session: sqlalchemy session """ if not event: self.logger.warn("event empty!") return sp_key, sp_hkey = self._keygen(session) def _pk(obj): pk_values = tuple(get...
Commit phase for session. :param session: sqlalchemy session
def commit(self, session): """Commit phase for session. :param session: sqlalchemy session """ sp_key, sp_hkey = self._keygen(session) with self.r.pipeline(transaction=False) as p: p.srem(sp_key, session.meepo_unique_id) p.expire(sp_hkey, 60 * 60) ...
Return all session unique ids recorded in prepare phase. :param ts: timestamp, default to current timestamp :return: set of session unique ids
def session_info(self, session): """Return all session unique ids recorded in prepare phase. :param ts: timestamp, default to current timestamp :return: set of session unique ids """ _, sp_hkey = self._keygen(session) picked_event = self.r.hgetall(sp_hkey) event ...
Return all session unique ids recorded in prepare phase. :param ts: timestamp, default to current timestamp :return: set of session unique ids
def prepare_info(self, ts=None): """Return all session unique ids recorded in prepare phase. :param ts: timestamp, default to current timestamp :return: set of session unique ids """ sp_key = "%s:session_prepare" % self.namespace(ts or int(time.time())) return set(s(m) f...
Clear all session in prepare phase. :param ts: timestamp used locate the namespace
def clear(self, ts=None): """Clear all session in prepare phase. :param ts: timestamp used locate the namespace """ sp_key = "%s:session_prepare" % self.namespace(ts or int(time.time())) return self.r.delete(sp_key)
Check what kind of file variant source is Args: variant_source (str): Path to variant source Returns: file_type (str): 'vcf', 'gemini' or 'unknown'
def get_file_type(variant_source): """Check what kind of file variant source is Args: variant_source (str): Path to variant source Returns: file_type (str): 'vcf', 'gemini' or 'unknown' """ file_type = 'unknown' valid_vcf_suffixes = ('.vcf', '.vcf.gz...
Try to find out what type of variants that exists in a variant source Args: variant_source (str): Path to variant source source_mode (str): 'vcf' or 'gemini' Returns: variant_type (str): 'sv' or 'snv'
def get_variant_type(variant_source): """Try to find out what type of variants that exists in a variant source Args: variant_source (str): Path to variant source source_mode (str): 'vcf' or 'gemini' Returns: variant_type (str): 'sv' or 'snv' """ ...
Event Code for Retrosheet :param event_tx: Event text :param ab_des: at bat description :return: event_cd(int)
def event_cd(cls, event_tx, ab_des): """ Event Code for Retrosheet :param event_tx: Event text :param ab_des: at bat description :return: event_cd(int) """ _event_tx = event_tx.lower() _ab_des = ab_des.lower() # Generic out(event_cd:2) if _...
Batted ball Code for Retrosheet :param event_cd: Event code :param event_tx: Event text :param ab_des: at bat description :return: battedball_cd(str)
def battedball_cd(cls, event_cd, event_tx, ab_des): """ Batted ball Code for Retrosheet :param event_cd: Event code :param event_tx: Event text :param ab_des: at bat description :return: battedball_cd(str) """ _event_tx = event_tx.lower() # Fly Out...
Batted ball Code for at bat description :param ab_des: at bat description :return: battedball_cd(str)
def _battedball_cd(cls, ab_des): """ Batted ball Code for at bat description :param ab_des: at bat description :return: battedball_cd(str) """ _ab_des = ab_des.lower() if ab_des.count("ground")>0: return 'G' elif _ab_des.count("lines")>0: ...
Ball/Strike counter :param ball_tally: Ball telly :param strike_tally: Strike telly :param pitch_res: pitching result(Retrosheet format) :return: ball count, strike count
def ball_count(cls, ball_tally, strike_tally, pitch_res): """ Ball/Strike counter :param ball_tally: Ball telly :param strike_tally: Strike telly :param pitch_res: pitching result(Retrosheet format) :return: ball count, strike count """ b, s = ball_tally, ...
Is PA terminal :param ball_tally: Ball telly :param strike_tally: Strike telly :param pitch_res: pitching result(Retrosheet format) :param event_cd: Event code :return: True or False
def is_pa_terminal(cls, ball_tally, strike_tally, pitch_res, event_cd): """ Is PA terminal :param ball_tally: Ball telly :param strike_tally: Strike telly :param pitch_res: pitching result(Retrosheet format) :param event_cd: Event code :return: True or False ...
Show all cases in the database. If no database was found run puzzle init first.
def cases(ctx, root): """ Show all cases in the database. If no database was found run puzzle init first. """ root = root or ctx.obj.get('root') or os.path.expanduser("~/.puzzle") if os.path.isfile(root): logger.error("'root' can't be a file") ctx.abort() logger.info("Root...
Copy skeleton
def copy_skeleton( name, src, dest, renames=None, description=None, ignore=False, exclude_dirs=None, exclude_files=None): """Copy skeleton""" fmt = DevFormatter(name, dest, description=description) if os.path.exists(dest): if ignore is False: print("project already exists...
Creates a standalone, subprojects or submodules script sctrucure
def init(name, subnames, dest, skeleton, description, project_type, skip_core): """Creates a standalone, subprojects or submodules script sctrucure""" dest = dest or CUR_DIR skeleton = join(skeleton or SKEL_PATH, project_type) project = join(dest, name) script = join(project, name + '.py') core ...
Assert the internal consistency of the instance's data structures. This method is for debugging only.
def _check(self): """ Assert the internal consistency of the instance's data structures. This method is for debugging only. """ for k,ix in six.iteritems(self._indices): assert k is not None, 'null key' assert ix, 'Key does not map to any indices' ...
Parse the contents of the `~io.IOBase.readline`-supporting file-like object ``fp`` as a simple line-oriented ``.properties`` file and return a `PropertiesFile` instance. ``fp`` may be either a text or binary filehandle, with or without universal newlines enabled. If it is a binary file...
def load(cls, fp): """ Parse the contents of the `~io.IOBase.readline`-supporting file-like object ``fp`` as a simple line-oriented ``.properties`` file and return a `PropertiesFile` instance. ``fp`` may be either a text or binary filehandle, with or without universal ne...
Parse the contents of the string ``s`` as a simple line-oriented ``.properties`` file and return a `PropertiesFile` instance. ``s`` may be either a text string or bytes string. If it is a bytes string, its contents are decoded as Latin-1. .. versionchanged:: 0.5.0 Invalid ...
def loads(cls, s): """ Parse the contents of the string ``s`` as a simple line-oriented ``.properties`` file and return a `PropertiesFile` instance. ``s`` may be either a text string or bytes string. If it is a bytes string, its contents are decoded as Latin-1. .. vers...
Write the mapping to a file in simple line-oriented ``.properties`` format. If the instance was originally created from a file or string with `PropertiesFile.load()` or `PropertiesFile.loads()`, then the output will include the comments and whitespace from the original input, and ...
def dump(self, fp, separator='='): """ Write the mapping to a file in simple line-oriented ``.properties`` format. If the instance was originally created from a file or string with `PropertiesFile.load()` or `PropertiesFile.loads()`, then the output will include the comm...
Convert the mapping to a text string in simple line-oriented ``.properties`` format. If the instance was originally created from a file or string with `PropertiesFile.load()` or `PropertiesFile.loads()`, then the output will include the comments and whitespace from the original input, a...
def dumps(self, separator='='): """ Convert the mapping to a text string in simple line-oriented ``.properties`` format. If the instance was originally created from a file or string with `PropertiesFile.load()` or `PropertiesFile.loads()`, then the output will include th...
Create a copy of the mapping, including formatting information
def copy(self): """ Create a copy of the mapping, including formatting information """ dup = type(self)() dup._indices = OrderedDict( (k, list(v)) for k,v in six.iteritems(self._indices) ) dup._lines = self._lines.copy() return dup
Create and normalize a vector across ring plane.
def prepare_normal_vectors(atomselection): """Create and normalize a vector across ring plane.""" ring_atomselection = [atomselection.coordinates()[a] for a in [0,2,4]] vect1 = self.vector(ring_atomselection[0],ring_atomselection[1]) vect2 = self.vector(ring_atomselection[2],ring_atomselection[0]) r...
Vector from p1 to p2. :param p1: coordinates of point p1 :param p2: coordinates of point p2 :returns : numpy array with vector coordinates
def vector(p1, p2): """Vector from p1 to p2. :param p1: coordinates of point p1 :param p2: coordinates of point p2 :returns : numpy array with vector coordinates """ return None if len(p1) != len(p2) else np.array([p2[i] - p1[i] for i in xrange(len(p1))])
Calculates the centroid from a 3D point cloud and returns the coordinates :param pnormal1: normal of plane :param ppoint: coordinates of point in the plane :param tpoint: coordinates of point to be projected :returns : coordinates of point orthogonally projected on the plane
def projection(pnormal1, ppoint, tpoint): """Calculates the centroid from a 3D point cloud and returns the coordinates :param pnormal1: normal of plane :param ppoint: coordinates of point in the plane :param tpoint: coordinates of point to be projected :returns : coordinates of point orthogonally pr...
Decorator to use on methods that are allowed to retry the request after reauthenticating the client. :param f: The original function :return: The decorated function
def refresh_session_if_necessary(f): """ Decorator to use on methods that are allowed to retry the request after reauthenticating the client. :param f: The original function :return: The decorated function """ @functools.wraps(f) def wrapped(self, *args, **kwargs): try: ...
Build the sqlite database
def init_db(db_path): """Build the sqlite database""" logger.info("Creating database") with closing(connect_database(db_path)) as db: with open(SCHEMA, 'r') as f: db.cursor().executescript(f.read()) db.commit() return
Populates result members. Performs the merge algorithm using the specified config and fills in the members that provide stats about the merging procedure. Attributes: merged_root: The result of the merge. aligned_root, aligned_head, aligned_update: Copies of root, head...
def merge(self): """Populates result members. Performs the merge algorithm using the specified config and fills in the members that provide stats about the merging procedure. Attributes: merged_root: The result of the merge. aligned_root, aligned_head, aligned_...
Return list of HGNC symbols matching HPO phenotype ids. Args: phenotype_ids (list): list of phenotype ids username (str): username to connect to phenomizer password (str): password to connect to phenomizer Returns: query_result: a list of dictionaries on the form { ...
def hpo_genes(phenotype_ids, username, password): """Return list of HGNC symbols matching HPO phenotype ids. Args: phenotype_ids (list): list of phenotype ids username (str): username to connect to phenomizer password (str): password to connect to phenomizer Returns: query_...
Utility to monkeypatch forms into paperinputs, untested
def mangle_form(form): "Utility to monkeypatch forms into paperinputs, untested" for field, widget in form.fields.iteritems(): if type(widget) is forms.widgets.TextInput: form.fields[field].widget = PaperTextInput() form.fields[field].label = '' if type(widget) is forms.w...
Generate redis key for event at timestamp. :param event: event name :param ts: timestamp, default to current timestamp if left as None
def _keygen(self, event, ts=None): """Generate redis key for event at timestamp. :param event: event name :param ts: timestamp, default to current timestamp if left as None """ return "%s:%s" % (self.namespace(ts or time.time()), event)
Redis lua func to add an event to the corresponding sorted set. :param key: the key to be stored in redis server :param pk: the primary key of event :param ts: timestamp of the event, default to redis_server's current timestamp :param ttl: the expiration time of event since the...
def _zadd(self, key, pk, ts=None, ttl=None): """Redis lua func to add an event to the corresponding sorted set. :param key: the key to be stored in redis server :param pk: the primary key of event :param ts: timestamp of the event, default to redis_server's current timestamp ...
Add an event to event store. All events were stored in a sorted set in redis with timestamp as rank score. :param event: the event to be added, format should be ``table_action`` :param pk: the primary key of event :param ts: timestamp of the event, default to redis_server's ...
def add(self, event, pk, ts=None, ttl=None): """Add an event to event store. All events were stored in a sorted set in redis with timestamp as rank score. :param event: the event to be added, format should be ``table_action`` :param pk: the primary key of event :param ...
Replay events based on timestamp. If you split namespace with ts, the replay will only return events within the same namespace. :param event: event name :param ts: replay events after ts, default from 0. :param end_ts: replay events to ts, default to "+inf". :param with...
def replay(self, event, ts=0, end_ts=None, with_ts=False): """Replay events based on timestamp. If you split namespace with ts, the replay will only return events within the same namespace. :param event: event name :param ts: replay events after ts, default from 0. :par...
Query the last update timestamp of an event pk. You can pass a timestamp to only look for events later than that within the same namespace. :param event: the event name. :param pk: the pk value for query. :param ts: query event pk after ts, default to None which will query ...
def query(self, event, pk, ts=None): """Query the last update timestamp of an event pk. You can pass a timestamp to only look for events later than that within the same namespace. :param event: the event name. :param pk: the pk value for query. :param ts: query event pk...
Clear all stored record of event. :param event: event name to be cleared. :param ts: timestamp used locate the namespace
def clear(self, event, ts=None): """Clear all stored record of event. :param event: event name to be cleared. :param ts: timestamp used locate the namespace """ return self.r.delete(self._keygen(event, ts))
Register a file path from which to read parameter values. This method can be called multiple times to register multiple files for querying. Files are expected to be ``ini`` formatted. No assumptions should be made about the order that the registered files are read and values defined i...
def add_configuration_file(self, file_name): '''Register a file path from which to read parameter values. This method can be called multiple times to register multiple files for querying. Files are expected to be ``ini`` formatted. No assumptions should be made about the order that th...
Add the parameter to ``Parameters``. **Arguments** The arguments are lumped into two groups:``Parameters.add_parameter`` and ``argparse.ArgumentParser.add_argument``. Parameters that are only used by ``Parameters.add_parameter`` are removed before ``kwargs`` is passed directly...
def add_parameter(self, **kwargs): '''Add the parameter to ``Parameters``. **Arguments** The arguments are lumped into two groups:``Parameters.add_parameter`` and ``argparse.ArgumentParser.add_argument``. Parameters that are only used by ``Parameters.add_parameter`` are remove...
Ensure all sources are ready to be queried. Parses ``sys.argv`` with the contained ``argparse.ArgumentParser`` and sets ``parsed`` to True if ``only_known`` is False. Once ``parsed`` is set to True, it is inadvisable to add more parameters (cf. ``add_parameter``). Also, if ``parsed`` ...
def parse(self, only_known = False): '''Ensure all sources are ready to be queried. Parses ``sys.argv`` with the contained ``argparse.ArgumentParser`` and sets ``parsed`` to True if ``only_known`` is False. Once ``parsed`` is set to True, it is inadvisable to add more parameters (cf. ...
Explicitly read the configuration files. Reads all configuration files in this Parameters object. Even if inotify is watching or a read has already occurred. .. note:: The order that the configuration files are read is not guaranteed.
def read_configuration_files(self): '''Explicitly read the configuration files. Reads all configuration files in this Parameters object. Even if inotify is watching or a read has already occurred. .. note:: The order that the configuration files are read is not guaranteed....
Return the number of genes
def nr_genes(self): """Return the number of genes""" if self['genes']: nr_genes = len(self['genes']) else: nr_genes = len(self['gene_symbols']) return nr_genes
Readable name for the variant.
def display_name(self): """Readable name for the variant.""" if self.is_snv: gene_ids = self.gene_symbols[:2] return ', '.join(gene_ids) else: return "{this.cytoband_start} ({this.sv_len})".format(this=self)
Return a md5 key string based on position, ref and alt
def md5(self): """Return a md5 key string based on position, ref and alt""" return hashlib.md5('_'.join([self.CHROM, str(self.POS), self.REF, self.ALT])).hexdigest()
Add a frequency that will be displayed on the variant level Args: name (str): The name of the frequency field
def add_frequency(self, name, value): """Add a frequency that will be displayed on the variant level Args: name (str): The name of the frequency field """ logger.debug("Adding frequency {0} with value {1} to variant {2}".format( name, value, self['variant...
Set the max frequency for the variant If max_freq use this, otherwise go through all frequencies and set the highest as self['max_freq'] Args: max_freq (float): The max frequency
def set_max_freq(self, max_freq=None): """Set the max frequency for the variant If max_freq use this, otherwise go through all frequencies and set the highest as self['max_freq'] Args: max_freq (float): The max frequency """ if max_freq: ...
Add a severity to the variant Args: name (str): The name of the severity value : The value of the severity
def add_severity(self, name, value): """Add a severity to the variant Args: name (str): The name of the severity value : The value of the severity """ logger.debug("Adding severity {0} with value {1} to variant {2}".format( name, value, se...
Add the information for a individual This adds a genotype dict to variant['individuals'] Args: genotype (dict): A genotype dictionary
def add_individual(self, genotype): """Add the information for a individual This adds a genotype dict to variant['individuals'] Args: genotype (dict): A genotype dictionary """ logger.debug("Adding genotype {0} to variant {1}".format( genotyp...
Add the information transcript This adds a transcript dict to variant['transcripts'] Args: transcript (dict): A transcript dictionary
def add_transcript(self, transcript): """Add the information transcript This adds a transcript dict to variant['transcripts'] Args: transcript (dict): A transcript dictionary """ logger.debug("Adding transcript {0} to variant {1}".format( tra...
Add the information of a gene This adds a gene dict to variant['genes'] Args: gene (dict): A gene dictionary
def add_gene(self, gene): """Add the information of a gene This adds a gene dict to variant['genes'] Args: gene (dict): A gene dictionary """ logger.debug("Adding gene {0} to variant {1}".format( gene, self['variant_id'])) self['gene...
Add the information of a compound variant This adds a compound dict to variant['compounds'] Args: compound (dict): A compound dictionary
def add_compound(self, compound): """Add the information of a compound variant This adds a compound dict to variant['compounds'] Args: compound (dict): A compound dictionary """ logger.debug("Adding compound {0} to variant {1}".format( compo...
Set the variant id for this variant
def _set_variant_id(self, variant_id=None): """Set the variant id for this variant""" if not variant_id: variant_id = '_'.join([ self.CHROM, str(self.POS), self.REF, self.ALT ]) logger.debug("Updating va...
Moves element from lst available at lst_idx.
def move_to_result(self, lst_idx): """Moves element from lst available at lst_idx.""" self.in_result_idx.add(lst_idx) if lst_idx in self.not_in_result_root_match_idx: self.not_in_result_root_match_idx.remove(lst_idx)
Adds a match for the elements avaialble at lst_idx and root_idx.
def add_root_match(self, lst_idx, root_idx): """Adds a match for the elements avaialble at lst_idx and root_idx.""" self.root_matches[lst_idx] = root_idx if lst_idx in self.in_result_idx: return self.not_in_result_root_match_idx.add(lst_idx)
Add all transcripts for a variant Go through all transcripts found for the variant Args: gemini_variant (GeminiQueryRow): The gemini variant Yields: transcript (puzzle.models.Transcript)
def _add_transcripts(self, variant_obj, gemini_variant): """ Add all transcripts for a variant Go through all transcripts found for the variant Args: gemini_variant (GeminiQueryRow): The gemini variant Yields: transcript (puzzle.models.T...
Fetch the value associated with the key ``key`` in the `Properties` object. If the key is not present, `defaults` is checked, and then *its* `defaults`, etc., until either a value for ``key`` is found or the next `defaults` is `None`, in which case `defaultValue` is returned. :...
def getProperty(self, key, defaultValue=None): """ Fetch the value associated with the key ``key`` in the `Properties` object. If the key is not present, `defaults` is checked, and then *its* `defaults`, etc., until either a value for ``key`` is found or the next `defaults` is `...
r""" Returns a generator of all distinct keys in the `Properties` object and its `defaults` (and its `defaults`\ ’s `defaults`, etc.) in unspecified order :rtype: generator of text strings
def propertyNames(self): r""" Returns a generator of all distinct keys in the `Properties` object and its `defaults` (and its `defaults`\ ’s `defaults`, etc.) in unspecified order :rtype: generator of text strings """ for k in self.data: yield k ...
r""" Returns a `set` of all keys in the `Properties` object and its `defaults` (and its `defaults`\ ’s `defaults`, etc.) :rtype: `set` of text strings
def stringPropertyNames(self): r""" Returns a `set` of all keys in the `Properties` object and its `defaults` (and its `defaults`\ ’s `defaults`, etc.) :rtype: `set` of text strings """ names = set(self.data) if self.defaults is not None: names.update...
Write the `Properties` object's entries (in unspecified order) in ``.properties`` format to ``out``, including the current timestamp. :param out: A file-like object to write the properties to. It must have been opened as a text file with a Latin-1-compatible encoding. :param commen...
def store(self, out, comments=None): """ Write the `Properties` object's entries (in unspecified order) in ``.properties`` format to ``out``, including the current timestamp. :param out: A file-like object to write the properties to. It must have been opened as a text file ...
Write the `Properties` object's entries (in unspecified order) in XML properties format to ``out``. :param out: a file-like object to write the properties to :type out: binary file-like object :param comment: if non-`None`, ``comment`` will be output as a ``<comment>`` eleme...
def storeToXML(self, out, comment=None, encoding='UTF-8'): """ Write the `Properties` object's entries (in unspecified order) in XML properties format to ``out``. :param out: a file-like object to write the properties to :type out: binary file-like object :param comment:...
Used when the entire index for model is updated.
def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.filter( modified__lte=datetime.datetime.now(), status=STATUS.published )
Loads mol file in rdkit without the hydrogens - they do not have to appear in the final figure. Once loaded, the molecule is converted to SMILES format which RDKit appears to draw best - since we do not care about the actual coordinates of the original molecule, it is sufficient to have just 2D ...
def load_molecule_in_rdkit_smiles(self, molSize,kekulize=True,bonds=[],bond_color=None,atom_color = {}, size= {} ): """ Loads mol file in rdkit without the hydrogens - they do not have to appear in the final figure. Once loaded, the molecule is converted to SMILES format which RDKit appears to ...
Config Factory
def cfg_factory(filename): """Config Factory""" try: # try to load config as yaml file. with open(filename, 'rb') as stream: return yaml.load(stream) except StandardError as error: # In case of error we use the **__argpi__** builtin to exit from # script _...
Draws a convex hull around ligand atoms and expands it, giving space to put diagramms on. This is done with the help of Shapely.geometry class. The initial convex hull the residue coordinates are inserted on, determines the order the coordinates are going to be moved, i.e. if the residue 1 is on...
def convex_hull(self): """ Draws a convex hull around ligand atoms and expands it, giving space to put diagramms on. This is done with the help of Shapely.geometry class. The initial convex hull the residue coordinates are inserted on, determines the order the coordinates are going to be...
Calculate overlap in 2D space
def calc_2d_forces(self,x1,y1,x2,y2,width): """Calculate overlap in 2D space""" #calculate a if x1>x2: a = x1-x2 else: a = x2-x1 a_sq=a*a #calculate b if y1>y2: b = y1-y2 else: b = y2-y1 b_sq=b*b ...
Calculates forces between two diagrams and pushes them apart by tenth of width
def do_step(self, values, xy_values,coeff, width): """Calculates forces between two diagrams and pushes them apart by tenth of width""" forces = {k:[] for k,i in enumerate(xy_values)} for (index1, value1), (index2,value2) in combinations(enumerate(xy_values),2): f = self.calc_2d_forc...
Run do_step function until the diagramms have diverged from each other. Also determines how big the figure is going to be by calculating the borders from new residue coordinates. These are then added some buffer space.
def make_new_projection_values(self,width=160): """Run do_step function until the diagramms have diverged from each other. Also determines how big the figure is going to be by calculating the borders from new residue coordinates. These are then added some buffer space. """ #Make...
Fetch variants for a case.
def variants(self, case_id, skip=0, count=1000, filters=None): """Fetch variants for a case.""" filters = filters or {} logger.debug("Fetching case with case_id: {0}".format(case_id)) case_obj = self.case(case_id) plugin, case_id = self.select_plugin(case_obj) self.filter...
Fetch a single variant from variant source.
def variant(self, case_id, variant_id): """Fetch a single variant from variant source.""" case_obj = self.case(case_id) plugin, case_id = self.select_plugin(case_obj) variant = plugin.variant(case_id, variant_id) return variant
Redis EventSourcing sub. This sub should be used together with sqlalchemy_es_pub, it will use RedisEventStore as events storage layer and use the prepare-commit pattern in :func:`sqlalchemy_es_pub` to ensure 100% security on events recording. :param session: the sqlalchemy to bind the signal :...
def redis_es_sub(session, tables, redis_dsn, strict=False, namespace=None, ttl=3600*24*3, socket_timeout=1): """Redis EventSourcing sub. This sub should be used together with sqlalchemy_es_pub, it will use RedisEventStore as events storage layer and use the prepare-commit pattern in :f...
Setup an ArgumentParser.
def setup_parser(): """Setup an ArgumentParser.""" parser = argparse.ArgumentParser() parser.add_argument('-p', '--port', type=int, default=5005) parser.add_argument('-i', '--interval', type=int, default=480) parser.add_argument('host', type=str, help='hostname') return parser
Connect to a McDevice
def main(): """Connect to a McDevice""" args = setup_parser().parse_args() host = getattr(args, "host") port = getattr(args, "port") ipv4 = socket.gethostbyname(host) interval = getattr(args, "interval") receiver = McDevice(ipv4, udp_port=port, mc_interval=interval) receiver.handle_stat...
Initialize a new Ghost API client, reading the client ID and secret from the SQlite database. :param database_path: The path to the database file. :param base_url: The base url of the server :param version: The server version to use (default: `auto`) :param client_id: The client...
def from_sqlite(cls, database_path, base_url, version='auto', client_id='ghost-admin'): """ Initialize a new Ghost API client, reading the client ID and secret from the SQlite database. :param database_path: The path to the database file. :param base_url: The base url of the ser...
:return: The version of the server when initialized as 'auto', otherwise the version passed in at initialization
def version(self): """ :return: The version of the server when initialized as 'auto', otherwise the version passed in at initialization """ if self._version != 'auto': return self._version if self._version == 'auto': try: data...
Authenticate with the server. :param username: The username of an existing user :param password: The password for the user :return: The authentication response from the REST endpoint
def login(self, username, password): """ Authenticate with the server. :param username: The username of an existing user :param password: The password for the user :return: The authentication response from the REST endpoint """ data = self._authenticate( ...
Re-authenticate using the refresh token if available. Otherwise log in using the username and password if it was used to authenticate initially. :return: The authentication response or `None` if not available
def refresh_session(self): """ Re-authenticate using the refresh token if available. Otherwise log in using the username and password if it was used to authenticate initially. :return: The authentication response or `None` if not available """ if not self._refre...
Revoke the access token currently in use.
def revoke_access_token(self): """ Revoke the access token currently in use. """ if not self._access_token: return self.execute_post('authentication/revoke', json=dict( token_type_hint='access_token', token=self._access_token )) ...
Revoke the refresh token currently active.
def revoke_refresh_token(self): """ Revoke the refresh token currently active. """ if not self._refresh_token: return self.execute_post('authentication/revoke', json=dict( token_type_hint='refresh_token', token=self._refresh_token )) ...
Log out, revoking the access tokens and forgetting the login details if they were given.
def logout(self): """ Log out, revoking the access tokens and forgetting the login details if they were given. """ self.revoke_refresh_token() self.revoke_access_token() self._username, self._password = None, None
Upload an image and return its path on the server. Either `file_obj` or `file_path` or `name` and `data` has to be specified. :param file_obj: A file object to upload :param file_path: A file path to upload from :param name: A file name for uploading :param data: The file conten...
def upload(self, file_obj=None, file_path=None, name=None, data=None): """ Upload an image and return its path on the server. Either `file_obj` or `file_path` or `name` and `data` has to be specified. :param file_obj: A file object to upload :param file_path: A file path to uplo...
Execute an HTTP GET request against the API endpoints. This method is meant for internal use. :param resource: The last part of the URI :param kwargs: Additional query parameters (and optionally headers) :return: The HTTP response as JSON or `GhostException` if unsuccessful
def execute_get(self, resource, **kwargs): """ Execute an HTTP GET request against the API endpoints. This method is meant for internal use. :param resource: The last part of the URI :param kwargs: Additional query parameters (and optionally headers) :return: The HTTP re...
Execute an HTTP POST request against the API endpoints. This method is meant for internal use. :param resource: The last part of the URI :param kwargs: Additional parameters for the HTTP call (`request` library) :return: The HTTP response as JSON or `GhostException` if unsuccessful
def execute_post(self, resource, **kwargs): """ Execute an HTTP POST request against the API endpoints. This method is meant for internal use. :param resource: The last part of the URI :param kwargs: Additional parameters for the HTTP call (`request` library) :return: Th...
Execute an HTTP PUT request against the API endpoints. This method is meant for internal use. :param resource: The last part of the URI :param kwargs: Additional parameters for the HTTP call (`request` library) :return: The HTTP response as JSON or `GhostException` if unsuccessful
def execute_put(self, resource, **kwargs): """ Execute an HTTP PUT request against the API endpoints. This method is meant for internal use. :param resource: The last part of the URI :param kwargs: Additional parameters for the HTTP call (`request` library) :return: The ...
Execute an HTTP DELETE request against the API endpoints. This method is meant for internal use. Does not return anything but raises an exception when failed. :param resource: The last part of the URI :param kwargs: Additional parameters for the HTTP call (`request` library)
def execute_delete(self, resource, **kwargs): """ Execute an HTTP DELETE request against the API endpoints. This method is meant for internal use. Does not return anything but raises an exception when failed. :param resource: The last part of the URI :param kwargs: Addit...
Get http content :param url: contents url :param headers: http header :return: BeautifulSoup object
def _get_content(cls, url, headers=HTTP_HEADERS): """ Get http content :param url: contents url :param headers: http header :return: BeautifulSoup object """ session = requests.Session() return session.get(url, headers=headers)