INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
A decorator that returns a clone of the current object so that we can re-use the object for similar requests.
def _makes_clone(_func, *args, **kw): """ A decorator that returns a clone of the current object so that we can re-use the object for similar requests. """ self = args[0]._clone() _func(self, *args[1:], **kw) return self
Deserializes JSON if the content-type matches, otherwise returns the response body as is.
def _handle_response(self, response, data): """ Deserializes JSON if the content-type matches, otherwise returns the response body as is. """ # Content-Type headers can include additional parameters(RFC 1521), so # we split on ; to match against only the type/subtype ...
Add a body to the request. When `body` is a: - string, it will be used as is. - dict or list of (key, value) pairs, it will be form encoded - None, remove request body - anything else, a TypeError will be raised If `body` is a dict or None ...
def with_body(self, body=None, **params): """ Add a body to the request. When `body` is a: - string, it will be used as is. - dict or list of (key, value) pairs, it will be form encoded - None, remove request body - anything else, a TypeError wil...
Add a json body to the request. :param data: A json string, a dict, or a list of key, value pairs :param params: A dict of key value pairs to JSON encode
def with_json(self, data=None, **params): """ Add a json body to the request. :param data: A json string, a dict, or a list of key, value pairs :param params: A dict of key value pairs to JSON encode """ if isinstance(data, (tuple, list)): dat...
Add headers to the request. :param headers: A dict, or a list of key, value pairs :param params: A dict of key value pairs
def with_headers(self, headers=None, **params): """ Add headers to the request. :param headers: A dict, or a list of key, value pairs :param params: A dict of key value pairs """ if isinstance(headers, (tuple, list)): headers = dict(head...
Returns the URL for this request. :param paths: Additional URL path parts to add to the request :param params: Additional query parameters to add to the request
def get_url(self, *paths, **params): """ Returns the URL for this request. :param paths: Additional URL path parts to add to the request :param params: Additional query parameters to add to the request """ path_stack = self._attribute_stack[:] if paths: ...
Clones the state of the current operation. The state is cloned so that you can freeze the state at a certain point for re-use. :: >>> cat = dolt.cat >>> cat.get_url() '/cat' >>> o = cat.foo >>> o.get_url() '/cat/foo' ...
def _clone(self): """ Clones the state of the current operation. The state is cloned so that you can freeze the state at a certain point for re-use. :: >>> cat = dolt.cat >>> cat.get_url() '/cat' >>> o = cat.foo >>> o.get_url...
Delete a case or individual from the database. If no database was found run puzzle init first.
def delete(ctx, family_id, individual_id, root): """ Delete a case or individual from 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") ...
Show all variants for a case.
def variants(case_id): """Show all variants for a case.""" filters = parse_filters() values = [value for key, value in iteritems(filters) if not isinstance(value, dict) and key != 'skip'] is_active = any(values) variants, nr_of_variants = app.db.variants( case_id, skip=...
Show a single variant.
def variant(case_id, variant_id): """Show a single variant.""" case_obj = app.db.case(case_id) variant = app.db.variant(case_id, variant_id) if variant is None: return abort(404, "variant not found") comments = app.db.comments(variant_id=variant.md5) template = 'sv_variant.html' if app....
Parse variant filters from the request object.
def parse_filters(): """Parse variant filters from the request object.""" genes_str = request.args.get('gene_symbol') filters = {} for key in ('frequency', 'cadd', 'sv_len'): try: filters[key] = float(request.args.get(key)) except (ValueError, TypeError): pass ...
Pin a variant as a suspect for a given case.
def suspects(case_id, variant_id): """Pin a variant as a suspect for a given case.""" case_obj = app.db.case(case_id) variant_obj = app.db.variant(case_id, variant_id) app.db.add_suspect(case_obj, variant_obj) return redirect(request.referrer)
Store a new GEMINI query.
def queries(): """Store a new GEMINI query.""" query = request.form['query'] name = request.form.get('name') app.db.add_gemini_query(name, query) return redirect(request.referrer)
>>> from Redy.Opt.ConstExpr import constexpr, const, optimize, macro >>> import dis >>> a = 1; b = ""; c = object() >>> x = 1 >>> @optimize >>> def f(y): >>> val1: const[int] = a >>> val2: const = b >>> if constexpr[x is c]: >>> return val1, y >>> elif con...
def _constexpr_transform(fn): """ >>> from Redy.Opt.ConstExpr import constexpr, const, optimize, macro >>> import dis >>> a = 1; b = ""; c = object() >>> x = 1 >>> @optimize >>> def f(y): >>> val1: const[int] = a >>> val2: const = b >>> if constexpr[x is c]: >>> ...
Parse the contents of the `~io.IOBase.readline`-supporting file-like object ``fp`` as a simple line-oriented ``.properties`` file and return a `dict` of the key-value pairs. ``fp`` may be either a text or binary filehandle, with or without universal newlines enabled. If it is a binary filehandle, its ...
def load(fp, object_pairs_hook=dict): """ Parse the contents of the `~io.IOBase.readline`-supporting file-like object ``fp`` as a simple line-oriented ``.properties`` file and return a `dict` of the key-value pairs. ``fp`` may be either a text or binary filehandle, with or without universal new...
Parse the contents of the `~io.IOBase.readline`-supporting file-like object ``fp`` as a simple line-oriented ``.properties`` file and return a generator of ``(key, value, original_lines)`` triples for every entry in ``fp`` (including duplicate keys) in order of occurrence. The third element of each tri...
def parse(fp): """ Parse the contents of the `~io.IOBase.readline`-supporting file-like object ``fp`` as a simple line-oriented ``.properties`` file and return a generator of ``(key, value, original_lines)`` triples for every entry in ``fp`` (including duplicate keys) in order of occurrence. The th...
Parse the contents of the string ``s`` as a simple line-oriented ``.properties`` file and return a `dict` of the key-value pairs. ``s`` may be either a text string or bytes string. If it is a bytes string, its contents are decoded as Latin-1. By default, the key-value pairs extracted from ``s`` are c...
def loads(s, object_pairs_hook=dict): """ Parse the contents of the string ``s`` as a simple line-oriented ``.properties`` file and return a `dict` of the key-value pairs. ``s`` may be either a text string or bytes string. If it is a bytes string, its contents are decoded as Latin-1. By defau...
Decode escape sequences in a ``.properties`` key or value. The following escape sequences are recognized:: \\t \\n \\f \\r \\uXXXX \\\\ If a backslash is followed by any other character, the backslash is dropped. In addition, any valid UTF-16 surrogate pairs in the string after escape-de...
def unescape(field): """ Decode escape sequences in a ``.properties`` key or value. The following escape sequences are recognized:: \\t \\n \\f \\r \\uXXXX \\\\ If a backslash is followed by any other character, the backslash is dropped. In addition, any valid UTF-16 surrogate pairs ...
Extract clips according to the specification file or string. Arguments: specsFilePathOrStr (str): Specification file path or string outputDir (str): Location of the extracted clips zipOutput (bool): Archive extracted clips' flag Specifications format: ...
def extractClips(self, specsFilePathOrStr, outputDir=None, zipOutput=False): """Extract clips according to the specification file or string. Arguments: specsFilePathOrStr (str): Specification file path or string outputDir (str): Location of the extracted clips ...
Extracts a single clip according to audioClipSpec. Arguments: audioClipSpec (AudioClipSpec): Clip specification showLogs (bool): Show ffmpeg output
def _extractClipData(self, audioClipSpec, showLogs=False): """Extracts a single clip according to audioClipSpec. Arguments: audioClipSpec (AudioClipSpec): Clip specification showLogs (bool): Show ffmpeg output """ command = [self._ffmpegPath] if not show...
Add a phenotype term to the case.
def add_phenotype(self, ind_obj, phenotype_id): """Add a phenotype term to the case.""" if phenotype_id.startswith('HP:') or len(phenotype_id) == 7: logger.debug('querying on HPO term') hpo_results = phizz.query_hpo([phenotype_id]) else: logger.debug('querying...
Update the HPO gene list for a case based on current terms.
def update_hpolist(self, case_obj): """Update the HPO gene list for a case based on current terms.""" hpo_list = self.case_genelist(case_obj) hpo_results = hpo_genes(case_obj.phenotype_ids(), *self.phenomizer_auth) if hpo_results is None: pass...
Remove multiple phenotypes from an individual.
def remove_phenotype(self, ind_obj, phenotypes=None): """Remove multiple phenotypes from an individual.""" if phenotypes is None: logger.info("delete all phenotypes related to %s", ind_obj.ind_id) self.query(PhenotypeTerm).filter_by(ind_id=ind_obj.id).delete() else: ...
>>> from Redy.ADT.Core import data >>> from Redy.Magic.Classic import cast >>> from Redy.ADT.traits import ConsInd, Discrete >>> @data >>> class S(ConsInd): # ConsInd class makes it available to index from this data as from a tuple. >>> a: '1' >>> b: lambda x: x >>> c: lambda x, y ...
def data(cls_def: type): """ >>> from Redy.ADT.Core import data >>> from Redy.Magic.Classic import cast >>> from Redy.ADT.traits import ConsInd, Discrete >>> @data >>> class S(ConsInd): # ConsInd class makes it available to index from this data as from a tuple. >>> a: '1' >>> b: l...
>>> from Redy.ADT.Core import match, data, P >>> from Redy.ADT.traits import ConsInd, Discrete >>> @data >>> class List(ConsInd, Discrete): >>> # ConsInd(index following constructing) >>> # |-> Ind; >>> # Discrete >>> # |-> Im(Immutable), Eq >>> Nil : ... >>...
def match(mode_lst: list, obj: 'object that has __destruct__ method'): """ >>> from Redy.ADT.Core import match, data, P >>> from Redy.ADT.traits import ConsInd, Discrete >>> @data >>> class List(ConsInd, Discrete): >>> # ConsInd(index following constructing) >>> # |-> Ind; >>>...
Return a gemini query Args: name (str)
def gemini_query(self, query_id): """Return a gemini query Args: name (str) """ logger.debug("Looking for query with id {0}".format(query_id)) return self.query(GeminiQuery).filter_by(id=query_id).first()
Add a user defined gemini query Args: name (str) query (str)
def add_gemini_query(self, name, query): """Add a user defined gemini query Args: name (str) query (str) """ logger.info("Adding query {0} with text {1}".format(name, query)) new_query = GeminiQuery(name=name, query=query) self.session.add(new_que...
Delete a gemini query Args: name (str)
def delete_gemini_query(self, query_id): """Delete a gemini query Args: name (str) """ query_obj = self.gemini_query(query_id) logger.debug("Delete query: {0}".format(query_obj.name_query)) self.session.delete(query_obj) self.save()
The main routine.
def main(args=None): """The main routine.""" if args is None: args = sys.argv[1:] print("This is the main routine.") print("It should do something interesting.") ################################################################################################################# parser = A...
Box Score Dataset(Row) :return: { 'retro_game_id': Retrosheet Game id 'home_team_id': Home Team Id 'away_team_id': Away Team Id 'home_lineup_[1-9]_id': Starting Member Player Id(Home) 'home_lineup_[1-9]_name': Starting Member Player Box Name(Home) ...
def row(self): """ Box Score Dataset(Row) :return: { 'retro_game_id': Retrosheet Game id 'home_team_id': Home Team Id 'away_team_id': Away Team Id 'home_lineup_[1-9]_id': Starting Member Player Id(Home) 'home_lineup_[1-9]_name': Startin...
read xml object :param url: contents url :param features: markup provider :param game: MLBAM Game object :param players: MLBAM Players object :return: pitchpx.box_score.box_score.BoxScore object
def read_xml(cls, url, features, game, players): """ read xml object :param url: contents url :param features: markup provider :param game: MLBAM Game object :param players: MLBAM Players object :return: pitchpx.box_score.box_score.BoxScore object """ ...
get box_score data :param soup: Beautifulsoup object :param game: MLBAM Game object :param players: MLBAM Players object :return: pitchpx.box_score.box_score.BoxScore object
def _generate_object(cls, soup, game, players): """ get box_score data :param soup: Beautifulsoup object :param game: MLBAM Game object :param players: MLBAM Players object :return: pitchpx.box_score.box_score.BoxScore object """ def get_batter(soup, team...
get batter object :param batter: Beautifulsoup object(batter element) :return: batter(dict)
def _get_batter(self, batter): """ get batter object :param batter: Beautifulsoup object(batter element) :return: batter(dict) """ values = OrderedDict() player = self.players.rosters.get(batter.get('id')) bo, starting = self._get_batting_order_starting_fl...
get batting order and starting member flg :param batter: Beautifulsoup object(batter element) :return: batting order(1-9), starting member flg(True or False)
def _get_batting_order_starting_flg(cls, batter): """ get batting order and starting member flg :param batter: Beautifulsoup object(batter element) :return: batting order(1-9), starting member flg(True or False) """ bo = batter.get('bo', None) if not bo or len(bo)...
get pitcher object :param pitcher: Beautifulsoup object(pitcher element) :return: pitcher(dict)
def _get_pitcher(self, pitcher): """ get pitcher object :param pitcher: Beautifulsoup object(pitcher element) :return: pitcher(dict) """ values = OrderedDict() player = self.players.rosters.get(pitcher.get('id')) values['pos'] = pitcher.get('pos', MlbamCon...
increment the version number with `n` at index `i`. >>> from Redy.Tools.Version import Version >>> a = Version('1.0.0.2') >>> a.increment(version_number_idx=2, increment=1) >>> assert a == ('1.0.1.0') >>> print(a[0]) >>> a[0] = 2
def increment(self, version_number_idx: int, increment: int): """ increment the version number with `n` at index `i`. >>> from Redy.Tools.Version import Version >>> a = Version('1.0.0.2') >>> a.increment(version_number_idx=2, increment=1) >>> assert a == ('1.0.1.0') ...
Calculate distance in miles or kilometers between current and other passed point.
def distance_to(self, point, unit='km'): """ Calculate distance in miles or kilometers between current and other passed point. """ assert isinstance(point, GeoPoint), ( 'Other point should also be a Point instance.' ) if self == point: retu...
Lazy conversion degrees latitude to radians.
def rad_latitude(self): """ Lazy conversion degrees latitude to radians. """ if self._rad_latitude is None: self._rad_latitude = math.radians(self.latitude) return self._rad_latitude
Lazy conversion degrees longitude to radians.
def rad_longitude(self): """ Lazy conversion degrees longitude to radians. """ if self._rad_longitude is None: self._rad_longitude = math.radians(self.longitude) return self._rad_longitude
Write an Erlang term to an output stream.
def send(term, stream): """Write an Erlang term to an output stream.""" payload = erlang.term_to_binary(term) header = struct.pack('!I', len(payload)) stream.write(header) stream.write(payload) stream.flush()
Read an Erlang term from an input stream.
def recv(stream): """Read an Erlang term from an input stream.""" header = stream.read(4) if len(header) != 4: return None # EOF (length,) = struct.unpack('!I', header) payload = stream.read(length) if len(payload) != length: return None term = erlang.binary_to_term(payload) ...
Yield Erlang terms from an input stream.
def recv_loop(stream): """Yield Erlang terms from an input stream.""" message = recv(stream) while message: yield message message = recv(stream)
Add the genotype calls for the variant Args: variant_obj (puzzle.models.Variant) variant_dict (dict): A variant dictionary case_obj (puzzle.models.Case)
def _add_genotype_calls(self, variant_obj, variant_line, case_obj): """Add the genotype calls for the variant Args: variant_obj (puzzle.models.Variant) variant_dict (dict): A variant dictionary case_obj (puzzle.models.Case) """ variant_line = variant...
Returns a new conflict with a prepended prefix as a path.
def with_prefix(self, root_path): """Returns a new conflict with a prepended prefix as a path.""" return Conflict(self.conflict_type, root_path + self.path, self.body)
Deserializes conflict to a JSON object. It returns list of: `json-patch <https://tools.ietf.org/html/rfc6902>`_ format. - REORDER, SET_FIELD become "op": "replace" - MANUAL_MERGE, ADD_BACK_TO_HEAD become "op": "add" - Path becomes `json-pointer <https://tools.ietf.org/html/...
def to_json(self): """Deserializes conflict to a JSON object. It returns list of: `json-patch <https://tools.ietf.org/html/rfc6902>`_ format. - REORDER, SET_FIELD become "op": "replace" - MANUAL_MERGE, ADD_BACK_TO_HEAD become "op": "add" - Path becomes `json-pointer...
Write a series of key-value pairs to a file in simple line-oriented ``.properties`` format. :param props: A mapping or iterable of ``(key, value)`` pairs to write to ``fp``. All keys and values in ``props`` must be text strings. If ``sort_keys`` is `False`, the entries are output in iteration...
def dump(props, fp, separator='=', comments=None, timestamp=True, sort_keys=False): """ Write a series of key-value pairs to a file in simple line-oriented ``.properties`` format. :param props: A mapping or iterable of ``(key, value)`` pairs to write to ``fp``. All keys and values in ...
Convert a series of key-value pairs to a text string in simple line-oriented ``.properties`` format. :param props: A mapping or iterable of ``(key, value)`` pairs to serialize. All keys and values in ``props`` must be text strings. If ``sort_keys`` is `False`, the entries are output in iterati...
def dumps(props, separator='=', comments=None, timestamp=True, sort_keys=False): """ Convert a series of key-value pairs to a text string in simple line-oriented ``.properties`` format. :param props: A mapping or iterable of ``(key, value)`` pairs to serialize. All keys and values in ``props`` ...
Convert a string to a ``.properties`` file comment. All non-Latin-1 characters in the string are escaped using ``\\uXXXX`` escapes (after converting non-BMP characters to surrogate pairs), a ``#`` is prepended to the string, any CR LF or CR line breaks in the string are converted to LF, and a ``#`` is ...
def to_comment(comment): """ Convert a string to a ``.properties`` file comment. All non-Latin-1 characters in the string are escaped using ``\\uXXXX`` escapes (after converting non-BMP characters to surrogate pairs), a ``#`` is prepended to the string, any CR LF or CR line breaks in the string are...
r""" Join a key and value together into a single line suitable for adding to a simple line-oriented ``.properties`` file. No trailing newline is added. >>> join_key_value('possible separators', '= : space') 'possible\\ separators=\\= \\: space' :param key: the key :type key: text string :...
def join_key_value(key, value, separator='='): r""" Join a key and value together into a single line suitable for adding to a simple line-oriented ``.properties`` file. No trailing newline is added. >>> join_key_value('possible separators', '= : space') 'possible\\ separators=\\= \\: space' :...
.. versionadded:: 0.2.0 Returns a timestamp in the format produced by |date_tostring|_, e.g.:: Mon Sep 02 14:00:54 EDT 2016 If ``timestamp`` is `True` (the default), the current date & time is returned. If ``timestamp`` is `None` or `False`, an empty string is returned. If ``timestamp``...
def java_timestamp(timestamp=True): """ .. versionadded:: 0.2.0 Returns a timestamp in the format produced by |date_tostring|_, e.g.:: Mon Sep 02 14:00:54 EDT 2016 If ``timestamp`` is `True` (the default), the current date & time is returned. If ``timestamp`` is `None` or `False`, an...
Gets a set of playlists. :param int start: The index of the first playlist to be fetched (according to the ordering). :param int max_count: The maximum number of playlists to fetch. :param str order: The ordering that should be used. :param bool reversed: Whet...
def GetPlaylists(self, start, max_count, order, reversed): """Gets a set of playlists. :param int start: The index of the first playlist to be fetched (according to the ordering). :param int max_count: The maximum number of playlists to fetch. :param str order...
Initializes the Flask application with this extension. It grabs the necessary configuration values from ``app.config``, those being HASHING_METHOD and HASHING_ROUNDS. HASHING_METHOD defaults to ``sha256`` but can be any one of ``hashlib.algorithms``. HASHING_ROUNDS specifies the number o...
def init_app(self, app): '''Initializes the Flask application with this extension. It grabs the necessary configuration values from ``app.config``, those being HASHING_METHOD and HASHING_ROUNDS. HASHING_METHOD defaults to ``sha256`` but can be any one of ``hashlib.algorithms``. HASHING_R...
Hashes the specified value combined with the specified salt. The hash is done HASHING_ROUNDS times as specified by the application configuration. An example usage of :class:``hash_value`` would be:: val_hash = hashing.hash_value('mysecretdata', salt='abcd') # save to a ...
def hash_value(self, value, salt=''): '''Hashes the specified value combined with the specified salt. The hash is done HASHING_ROUNDS times as specified by the application configuration. An example usage of :class:``hash_value`` would be:: val_hash = hashing.hash_value('mys...
Checks the specified hash value against the hash of the provided salt and value. An example usage of :class:`check_value` would be:: val_hash = hashing.hash_value('mysecretdata', salt='abcd') if hashing.check_value(val_hash, 'mysecretdata', salt='abcd'): # do so...
def check_value(self, value_hash, value, salt=''): '''Checks the specified hash value against the hash of the provided salt and value. An example usage of :class:`check_value` would be:: val_hash = hashing.hash_value('mysecretdata', salt='abcd') if hashing.check_value(v...
* the `self` Path object is assumed to be a directory :param filter_fn: a `None` object or a predicative function `str -> bool` which will be applied on the filename/directory in `self` directory. :return: a tuple of Path objects each of whic...
def list_dir(self, filter_fn=None) -> 'Tuple[Path, ...]': """ * the `self` Path object is assumed to be a directory :param filter_fn: a `None` object or a predicative function `str -> bool` which will be applied on the filename/directory in `self` directory. ...
:param start: an object of NoneType or Path or str. :return: a string If `start` is None: returns the relative path of current Path object from its own directory. Else: returns the relative path of current Path object from the `start` path. e.g ...
def relative(self, start: typing.Optional[typing.Union['Path', str]] = None ) -> str: """ :param start: an object of NoneType or Path or str. :return: a string If `start` is None: returns the relative path of current Path object from ...
:param mode: the same as the argument `mode` of `builtins.open` :param encoding: similar to the argument `encoding` of `builtins.open` which is compatible to io.open. - `encoding='auto'` to automatically detect the encoding. - `encoding is a <list|tuple|set>` to...
def open(self, mode='r', encoding: typing.Union[list, tuple, set, str, typing. Callable] = 'auto'): """ :param mode: the same as the argument `mode` of `builtins.open` :param encoding: similar to the argument `encoding` of `builtins.o...
Adds a URI in the TrackList. :param str uri: The uri of the item to add. :param str after_track: The identifier of the track after which the new item should be inserted. :param bool set_as_current: Whether the newly inserted track ...
def AddTrack(self, uri, after_track, set_as_current): """Adds a URI in the TrackList. :param str uri: The uri of the item to add. :param str after_track: The identifier of the track after which the new item should be inserted. :param bool set_as_current: ...
Delete one or more gene ids form the list.
def delete_gene(self, *gene_ids): """Delete one or more gene ids form the list.""" self.gene_ids = [gene_id for gene_id in self.gene_ids if gene_id not in gene_ids]
Add a case obj with individuals to adapter Args: case_obj (puzzle.models.Case)
def add_case(self, case_obj): """Add a case obj with individuals to adapter Args: case_obj (puzzle.models.Case) """ for ind_obj in case_obj.individuals: self._add_individual(ind_obj) logger.debug("Adding case {0} to plugin...
Return a Case object If no case_id is given return one case Args: case_id (str): A case id Returns: A Case object
def case(self, case_id=None): """Return a Case object If no case_id is given return one case Args: case_id (str): A case id Returns: A Case object """ if case_id: for case in self.case_objs: if cas...
Return a individual object Args: ind_id (str): A individual id Returns: individual (puzzle.models.individual)
def individual(self, ind_id=None): """Return a individual object Args: ind_id (str): A individual id Returns: individual (puzzle.models.individual) """ for ind_obj in self.individual_objs: if ind_obj.ind_id...
Return information about individuals Args: ind_ids (list(str)): List of individual ids Returns: individuals (Iterable): Iterable with Individuals
def individuals(self, ind_ids=None): """Return information about individuals Args: ind_ids (list(str)): List of individual ids Returns: individuals (Iterable): Iterable with Individuals """ if ind_ids: for ...
Check state of update timer.
def healthy_update_timer(self): """Check state of update timer.""" state = None if self.update_status_timer and self.update_status_timer.is_alive(): _LOGGER.debug("Timer: healthy") state = True else: _LOGGER.debug("Timer: not healthy") sta...
initialize the object
def initialize(self): """initialize the object""" self.network_status = self.get_network_status() self.name = self.network_status.get('network_name', 'Unknown') self.location_info = self.get_location_info() self.device_info = self.get_device_info() self.device_id = ( ...
initialize the socket
def initialize_socket(self): """initialize the socket""" try: _LOGGER.debug("Trying to open socket.") self._socket = socket.socket( socket.AF_INET, # IPv4 socket.SOCK_DGRAM # UDP ) self._socket.bind(('', self._udp_port...
initialize the worker thread
def initialize_worker(self): """initialize the worker thread""" worker_thread = threading.Thread( name="WorkerThread", target=message_worker, args=(self,)) worker_thread.setDaemon(True) worker_thread.start()
initialize receiver zones
def initialize_zones(self): """initialize receiver zones""" zone_list = self.location_info.get('zone_list', {'main': True}) for zone_id in zone_list: if zone_list[zone_id]: # Location setup is valid self.zones[zone_id] = Zone(self, zone_id=zone_id) else:...
Get status from device to register/keep alive UDP
def get_status(self): """Get status from device to register/keep alive UDP""" headers = { "X-AppName": "MusicCast/0.1(python)", "X-AppPort": str(self._udp_port) } req_url = ENDPOINTS["getStatus"].format(self.ip_address, 'main') return request(req_url, head...
Handle status from device
def handle_status(self): """Handle status from device""" status = self.get_status() if status: # Update main-zone self.zones['main'].update_status(status)
Handles 'netusb' in message
def handle_netusb(self, message): """Handles 'netusb' in message""" # _LOGGER.debug("message: {}".format(message)) needs_update = 0 if self._yamaha: if 'play_info_updated' in message: play_info = self.get_play_info() # _LOGGER.debug(play_info)...
Handles features of the device
def handle_features(self, device_features): """Handles features of the device""" self.device_features = device_features if device_features and 'zone' in device_features: for zone in device_features['zone']: zone_id = zone.get('id') if zone_id in self...
Dispatch all event messages
def handle_event(self, message): """Dispatch all event messages""" # _LOGGER.debug(message) needs_update = 0 for zone in self.zones: if zone in message: _LOGGER.debug("Received message for zone: %s", zone) self.zones[zone].update_status(message...
Update device status.
def update_status(self, reset=False): """Update device status.""" if self.healthy_update_timer and not reset: return # get device features only once if not self.device_features: self.handle_features(self.get_features()) # Get status from device to regist...
Schedule a Timer Thread.
def setup_update_timer(self, reset=False): """Schedule a Timer Thread.""" _LOGGER.debug("Timer: firing again in %d seconds", self._interval) self.update_status_timer = threading.Timer( self._interval, self.update_status, [True]) self.update_status_timer.setDaemon(True) ...
Send Playback command.
def set_playback(self, playback): """Send Playback command.""" req_url = ENDPOINTS["setPlayback"].format(self._ip_address) params = {"playback": playback} return request(req_url, params=params)
Append sql to a gemini query Args: query(str): The gemini query extra_info(str): The text that should be added Return: extended_query(str)
def build_gemini_query(self, query, extra_info): """Append sql to a gemini query Args: query(str): The gemini query extra_info(str): The text that should be added Return: extended_query(str) """ if 'WHERE' in query: return "{0} AN...
Return count variants for a case. This function needs to have different behaviours based on what is asked for. It should allways try to give minimal information back to improve on speed. For example, if consequences are not asked for we will not build all transcripts. If not sv variants...
def variants(self, case_id, skip=0, count=1000, filters=None): """Return count variants for a case. This function needs to have different behaviours based on what is asked for. It should allways try to give minimal information back to improve on speed. For example, if consequences are n...
Return a specific variant. We solve this by building a gemini query and send it to _variants Args: case_id (str): Path to a gemini database variant_id (int): A gemini variant id Returns: variant_obj (dict): A puzzle variant
def variant(self, case_id, variant_id): """Return a specific variant. We solve this by building a gemini query and send it to _variants Args: case_id (str): Path to a gemini database variant_id (int): A gemini variant id Returns: ...
Return variants found in the gemini database Args: case_id (str): The case for which we want to see information gemini_query (str): What variants should be chosen filters (dict): A dictionary with filters Yields: variant_obj (dict...
def _variants(self, case_id, gemini_query): """Return variants found in the gemini database Args: case_id (str): The case for which we want to see information gemini_query (str): What variants should be chosen filters (dict): A dictionary with filters...
Make a puzzle variant from a gemini variant Args: case_id (str): related case id gemini_variant (GeminiQueryRow): The gemini variant individual_objs (list(dict)): A list of Individuals index(int): The index of the variant Returns:...
def _format_variant(self, case_id, gemini_variant, individual_objs, index=0, add_all_info=False): """Make a puzzle variant from a gemini variant Args: case_id (str): related case id gemini_variant (GeminiQueryRow): The gemini variant ...
Check if the variant is a variation in any of the individuals Args: gemini_variant (GeminiQueryRow): The gemini variant ind_objs (list(puzzle.models.individual)): A list of individuals to check Returns: bool : If any of the individuals has the variant
def _is_variant(self, gemini_variant, ind_objs): """Check if the variant is a variation in any of the individuals Args: gemini_variant (GeminiQueryRow): The gemini variant ind_objs (list(puzzle.models.individual)): A list of individuals to check Returns: boo...
Boolean for telling if the sample is affected.
def is_affected(self): """Boolean for telling if the sample is affected.""" phenotype = self.phenotype if phenotype == '1': return False elif phenotype == '2': return True else: return False
Get a gene list from the database.
def gene_list(self, list_id): """Get a gene list from the database.""" return self.query(GeneList).filter_by(list_id=list_id).first()
Create a new gene list and optionally link to cases.
def add_genelist(self, list_id, gene_ids, case_obj=None): """Create a new gene list and optionally link to cases.""" new_genelist = GeneList(list_id=list_id) new_genelist.gene_ids = gene_ids if case_obj: new_genelist.cases.append(case_obj) self.session.add(new_geneli...
Remove a gene list and links to cases.
def remove_genelist(self, list_id, case_obj=None): """Remove a gene list and links to cases.""" gene_list = self.gene_list(list_id) if case_obj: # remove a single link between case and gene list case_ids = [case_obj.id] else: # remove all links and th...
Get or create a new case specific gene list record.
def case_genelist(self, case_obj): """Get or create a new case specific gene list record.""" list_id = "{}-HPO".format(case_obj.case_id) gene_list = self.gene_list(list_id) if gene_list is None: gene_list = GeneList(list_id=list_id) case_obj.gene_lists.append(gen...
Each plotted residue SVG file is edited and the contents of the file transfered into an SVG group (g). This allows a plot to be included in the final image and the group transform function allows to move the plot to the correct 2D coordinates in respect to the 2D drug molecule. The groups are ad...
def manage_the_plots(self): """ Each plotted residue SVG file is edited and the contents of the file transfered into an SVG group (g). This allows a plot to be included in the final image and the group transform function allows to move the plot to the correct 2D coordinates in respect ...
Sets the size of the figure by expanding the space of molecule.svg file. These dimension have been previously determined. Also makes the lines of the molecule thicker.
def add_bigger_box(self): """ Sets the size of the figure by expanding the space of molecule.svg file. These dimension have been previously determined. Also makes the lines of the molecule thicker. """ start1 = "width='"+str(int(self.molecule.molsize1))+"px' height='"+str(int(sel...
The plots are transparent and therefore this function is required to cover up the middle part of the plots (that contains text). This function creates white circles that provide background.
def draw_white_circles(self): """ The plots are transparent and therefore this function is required to cover up the middle part of the plots (that contains text). This function creates white circles that provide background. """ for atom in sorted(self.molecule.nearest_poi...
All of the elements of the final SVG file are put together in the correct order (e.g. lines are placed behind plots and the molecule).
def put_everything_together(self): """ All of the elements of the final SVG file are put together in the correct order (e.g. lines are placed behind plots and the molecule). """ molecule_list = [self.filestart]+[self.white_circles]+[self.draw_molecule]+[self.draw.draw_hbonds]+[se...
The result of put_everything_together() function is writen in a file. Takes: * output_name * - name for the output file
def write_final_draw_file(self, output_name): """The result of put_everything_together() function is writen in a file. Takes: * output_name * - name for the output file """ finalsvg = open(output_name+".svg","w") finalsvg.writelines(self.final_molecule) finals...
Formatter factory
def formatter_factory(show_defaults=True): """Formatter factory""" def get_help_string(self, action): lhelp = action.help if isinstance(show_defaults, (list, tuple)): if "-" + action.dest in show_defaults: return lhelp if '%(default)' not in action.help: ...
Extends with class or function
def extend_with(func): """Extends with class or function""" if not func.__name__ in ArgParseInator._plugins: ArgParseInator._plugins[func.__name__] = func
Dcorates a function or a class method to add to the argument parser
def arg(*args, **kwargs): """ Dcorates a function or a class method to add to the argument parser """ def decorate(func): """ Decorate """ # we'll set the command name with the passed cmd_name argument, if # exist, else the command name will be the function name ...
Decorates a class to handle the arguments parser.
def class_args(cls): """ Decorates a class to handle the arguments parser. """ # get the Singleton ap_ = ArgParseInator(skip_init=True) # collect special vars (really need?) utils.collect_appendvars(ap_, cls) # set class reference cls.__cls__ = cls cmds = {} # get eventual cl...
set authorization for command or subcommand.
def cmd_auth(auth_phrase=None): """ set authorization for command or subcommand. """ def decorate(func): """ decorates the funcion """ # get the Singleton ap_ = ArgParseInator(skip_init=True) # set the authorization name auth_name = id(func) ...
Compile functions for argparsing.
def _compile(self, module=None): """ Compile functions for argparsing. """ # get the main module mod = module or sys.modules['__main__'] self.mod = mod # setup the script version if hasattr(mod, '__version__'): version = "%(prog)s " + mod.__ver...
Parse our arguments.
def parse_args(self): """ Parse our arguments. """ # compile the parser self._compile() # clear the args self.args = None self._self_event('before_parse', 'parse', *sys.argv[1:], **{}) # list commands/subcommands in argv cmds = [cmd for cmd...
Check the authorization for the command
def check_auth(self, name): """ Check the authorization for the command """ if name in self.auths: # if the command name is in the **need authorization list** # get the authorization for the command auth = self.auths[name] if self.args.auth...