INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
use previously calculated variation of the rate to estimate the uncertainty in a particular numdate due to rate variation.
def date_uncertainty_due_to_rate(self, node, interval=(0.05, 0.095)): """use previously calculated variation of the rate to estimate the uncertainty in a particular numdate due to rate variation. Parameters ---------- node : PhyloTree.Clade node for which the confide...
If temporal reconstruction was done using the marginal ML mode the entire distribution of times is available. This function determines the 90% ( or other ) confidence interval defined as the range where 5% of probability is below and above. Note that this does not necessarily contain the highest probability position. I...
def get_confidence_interval(self, node, interval = (0.05, 0.95)): ''' If temporal reconstruction was done using the marginal ML mode, the entire distribution of times is available. This function determines the 90% (or other) confidence interval, defined as the range where 5% of probabili...
If temporal reconstruction was done using the marginal ML mode the entire distribution of times is available. This function determines the interval around the highest posterior probability region that contains the specified fraction of the probability mass. In absense of marginal reconstruction it will return uncertain...
def get_max_posterior_region(self, node, fraction = 0.9): ''' If temporal reconstruction was done using the marginal ML mode, the entire distribution of times is available. This function determines the interval around the highest posterior probability region that contains the specified f...
Reads in a vcf/ vcf. gz file and associated reference sequence fasta ( to which the VCF file is mapped ). Parses mutations insertions and deletions and stores them in a nested dict see returns for the dict structure. Calls with heterozygous values 0/ 1 0/ 2 etc and no - calls (./. ) are replaced with Ns at the associat...
def read_vcf(vcf_file, ref_file): """ Reads in a vcf/vcf.gz file and associated reference sequence fasta (to which the VCF file is mapped). Parses mutations, insertions, and deletions and stores them in a nested dict, see 'returns' for the dict structure. Calls with heterozygous values...
Writes out a VCF - style file ( which seems to be minimally handleable by vcftools and pyvcf ) of the alignment. This is created from a dict in a similar format to what s created by: py: meth: treetime. vcf_utils. read_vcf Positions of variable sites are transformed to start at 1 to match VCF convention. Parameters ---...
def write_vcf(tree_dict, file_name):#, compress=False): """ Writes out a VCF-style file (which seems to be minimally handleable by vcftools and pyvcf) of the alignment. This is created from a dict in a similar format to what's created by :py:meth:`treetime.vcf_utils.read_vcf` Positions of var...
Evaluates int_tau f ( t + tau ) * g ( tau ) or int_tau f ( t - tau ) g ( tau ) if inverse time is TRUE
def _convolution_integrand(t_val, f, g, inverse_time=None, return_log=False): ''' Evaluates int_tau f(t+tau)*g(tau) or int_tau f(t-tau)g(tau) if inverse time is TRUE Parameters ----------- t_val : double Time point f : Interpolation object First mu...
Evaluates max_tau f ( t + tau ) * g ( tau ) or max_tau f ( t - tau ) g ( tau ) if inverse time is TRUE
def _max_of_integrand(t_val, f, g, inverse_time=None, return_log=False): ''' Evaluates max_tau f(t+tau)*g(tau) or max_tau f(t-tau)g(tau) if inverse time is TRUE Parameters ----------- t_val : double Time point f : Interpolation object First multiplier in convolution g...
Calculate convolution F ( t ) = int { f ( tau ) g ( t - tau ) } dtau
def _evaluate_convolution(t_val, f, g, n_integral = 100, inverse_time=None, return_log=False): """ Calculate convolution F(t) = int { f(tau)g(t-tau) } dtau """ FG = _convolution_integrand(t_val, f, g, inverse_time, return_log) #integrate the interpolation object, return log, make neg_log ...
calculate H ( t ) = \ int_tau f ( t - tau ) g ( tau ) if inverse_time = True H ( t ) = \ int_tau f ( t + tau ) g ( tau ) if inverse_time = False
def convolve(cls, node_interp, branch_interp, max_or_integral='integral', n_grid_points = ttconf.NODE_GRID_SIZE, n_integral=ttconf.N_INTEGRAL, inverse_time=True, rel_tol=0.05, yc=10): ''' calculate H(t) = \int_tau f(t-tau)g(tau) if inverse_time=True H...
Find the global minimum of a function represented as an interpolation object.
def min_interp(interp_object): """ Find the global minimum of a function represented as an interpolation object. """ try: return interp_object.x[interp_object(interp_object.x).argmin()] except Exception as e: s = "Cannot find minimum of the interpolation object" + str(interp_object.x...
Find the median of the function represented as an interpolation object.
def median_interp(interp_object): """ Find the median of the function represented as an interpolation object. """ new_grid = np.sort(np.concatenate([interp_object.x[:-1] + 0.1*ii*np.diff(interp_object.x) for ii in range(10)]).flatten()) tmp_prop = np.exp(-(int...
Convert datetime object to the numeric date. The numeric date format is YYYY. F where F is the fraction of the year passed
def numeric_date(dt=None): """ Convert datetime object to the numeric date. The numeric date format is YYYY.F, where F is the fraction of the year passed Parameters ---------- dt: datetime.datetime, None date of to be converted. if None, assume today """ if dt is None: ...
parse dates from the arguments and return a dictionary mapping taxon names to numerical dates.
def parse_dates(date_file): """ parse dates from the arguments and return a dictionary mapping taxon names to numerical dates. Parameters ---------- date_file : str name of file to parse meta data from Returns ------- dict dictionary linking fields in a column inter...
parse an abiguous date such as 2017 - XX - XX to [ 2017 2017. 999 ]
def ambiguous_date_to_date_range(mydate, fmt="%Y-%m-%d", min_max_year=None): """parse an abiguous date such as 2017-XX-XX to [2017,2017.999] Parameters ---------- mydate : str date string to be parsed fmt : str format descriptor. default is %Y-%m-%d min_max_year : None, optional...
Create the conversion object automatically from the tree
def from_regression(cls, clock_model): """ Create the conversion object automatically from the tree Parameters ---------- clock_model : dict dictionary as returned from TreeRegression with fields intercept and slope """ dc = cls() dc.clock_...
Socket connection.
def client(self): """ Socket connection. """ if not self._client: self._client = socket.create_connection( (self.host, self.port), self.timeout) self.logger.debug('Client connected with guacd server (%s, %s, %s)' % (se...
Terminate connection with Guacamole guacd server.
def close(self): """ Terminate connection with Guacamole guacd server. """ self.client.close() self._client = None self.connected = False self.logger.debug('Connection closed.')
Receive instructions from Guacamole guacd server.
def receive(self): """ Receive instructions from Guacamole guacd server. """ start = 0 while True: idx = self._buffer.find(INST_TERM.encode(), start) if idx != -1: # instruction was fully received! line = self._buffer[:idx ...
Send encoded instructions to Guacamole guacd server.
def send(self, data): """ Send encoded instructions to Guacamole guacd server. """ self.logger.debug('Sending data: %s' % data) self.client.sendall(data.encode())
Send instruction after encoding.
def send_instruction(self, instruction): """ Send instruction after encoding. """ self.logger.debug('Sending instruction: %s' % str(instruction)) return self.send(instruction.encode())
Establish connection with Guacamole guacd server via handshake.
def handshake(self, protocol='vnc', width=1024, height=768, dpi=96, audio=None, video=None, image=None, **kwargs): """ Establish connection with Guacamole guacd server via handshake. """ if protocol not in PROTOCOLS: self.logger.debug('Invalid protocol: %s' ...
Return a utf - 8 encoded string from a valid unicode string.
def utf8(unicode_str): """ Return a utf-8 encoded string from a valid unicode string. :param unicode_str: Unicode string. :return: str """ if six.PY2 and isinstance(unicode_str, __unicode__): return unicode_str.encode('utf-8') return unicode_str
Loads a new GuacamoleInstruction from encoded instruction string.
def load(cls, instruction): """ Loads a new GuacamoleInstruction from encoded instruction string. :param instruction: Instruction string. :return: GuacamoleInstruction() """ if not instruction.endswith(INST_TERM): raise InvalidInstruction('Instruction termin...
Decode whole instruction and return list of args. Usually returned arg [ 0 ] is the instruction opcode.
def decode_instruction(instruction): """ Decode whole instruction and return list of args. Usually, returned arg[0] is the instruction opcode. example: >> args = decode_instruction('4.size,4.1024;') >> args == ['size', '1024'] >> True :param instruction:...
Encode argument to be sent in a valid GuacamoleInstruction.
def encode_arg(arg): """ Encode argument to be sent in a valid GuacamoleInstruction. example: >> arg = encode_arg('size') >> arg == '4.size' >> True :param arg: arg string. :return: str """ arg_utf8 = utf8(arg) return ELEM_SEP.j...
Prepare the instruction to be sent over the wire.
def encode(self): """ Prepare the instruction to be sent over the wire. :return: str """ instruction_iter = itertools.chain([self.opcode], self.args) elems = ARG_SEP.join(self.encode_arg(arg) for arg in instruction_iter) return elems + INST_TERM
Returns a versioned URI string for this class
def class_url(cls): """Returns a versioned URI string for this class""" base = 'v{0}'.format(getattr(cls, 'RESOURCE_VERSION', '1')) return "/{0}/{1}".format(base, class_to_api_name(cls.class_name()))
Get instance URL by ID
def instance_url(self): """Get instance URL by ID""" id_ = self.get(self.ID_ATTR) base = self.class_url() if id_: return '/'.join([base, six.text_type(id_)]) else: raise Exception( 'Could not determine which URL to request: %s instance ' ...
Returns a versioned URI string for this class and don t pluralize the class name.
def class_url(cls): """ Returns a versioned URI string for this class, and don't pluralize the class name. """ base = 'v{0}'.format(getattr(cls, 'RESOURCE_VERSION', '1')) return "/{0}/{1}".format(base, class_to_api_name( cls.class_name(), pluralize=False))
Download the file to the specified directory or file path. Downloads to a temporary directory if no path is specified.
def download(self, path=None, **kwargs): """ Download the file to the specified directory or file path. Downloads to a temporary directory if no path is specified. Returns the absolute path to the file. """ download_url = self.download_url(**kwargs) try: ...
Get the commit objects parent Import or Migration
def parent_object(self): """ Get the commit objects parent Import or Migration """ from . import types parent_klass = types.get(self.parent_job_model.split('.')[1]) return parent_klass.retrieve(self.parent_job_id, client=self._client)
Asks the user for their email and password.
def _ask_for_credentials(): """ Asks the user for their email and password. """ _print_msg('Please enter your SolveBio credentials') domain = raw_input('Domain (e.g. <domain>.solvebio.com): ') # Check to see if this domain supports password authentication try: account = client.reques...
Prompt user for login information ( domain/ email/ password ). Domain email and password are used to get the user s API key.
def login(*args, **kwargs): """ Prompt user for login information (domain/email/password). Domain, email and password are used to get the user's API key. Always updates the stored credentials file. """ if args and args[0].api_key: # Handle command-line arguments if provided. sol...
Force an interactive login via the command line. Sets the global API key and updates the client auth.
def interactive_login(): """ Force an interactive login via the command line. Sets the global API key and updates the client auth. """ solvebio.access_token = None solvebio.api_key = None client.set_token() domain, email, password = _ask_for_credentials() if not all([domain, email, ...
Prints information about the current user. Assumes the user is already logged - in.
def whoami(*args, **kwargs): """ Prints information about the current user. Assumes the user is already logged-in. """ user = client.whoami() if user: print_user(user) else: print('You are not logged-in.')
Prints information about the current user.
def print_user(user): """ Prints information about the current user. """ email = user['email'] domain = user['account']['domain'] role = user['role'] print('You are logged-in to the "{0}" domain ' 'as {1} with role {2}.' .format(domain, email, role))
Handles UCSC - style range queries ( chr1: 100 - 200 )
def from_string(cls, string, exact=False): """ Handles UCSC-style range queries (chr1:100-200) """ try: chromosome, pos = string.split(':') except ValueError: raise ValueError('Please use UCSC-style format: "chr2:1000-2000"') if '-' in pos: ...
Returns this Query instance with the query args combined with existing set with AND.
def filter(self, *filters, **kwargs): """ Returns this Query instance with the query args combined with existing set with AND. kwargs are simply passed to a new Filter object and combined to any other filters with AND. By default, everything is combined using AND. If yo...
Shortcut to do range filters on genomic datasets.
def range(self, chromosome, start, stop, exact=False): """ Shortcut to do range filters on genomic datasets. """ return self._clone( filters=[GenomicFilter(chromosome, start, stop, exact)])
Shortcut to do a single position filter on genomic datasets.
def position(self, chromosome, position, exact=False): """ Shortcut to do a single position filter on genomic datasets. """ return self._clone( filters=[GenomicFilter(chromosome, position, exact=exact)])
Returns a dictionary with the requested facets.
def facets(self, *args, **kwargs): """ Returns a dictionary with the requested facets. The facets function supports string args, and keyword args. q.facets('field_1', 'field_2') will return facets for field_1 and field_2. q.facets(field_1={'limit': 0}, field_2={...
Takes a list of filters and returns JSON
def _process_filters(cls, filters): """Takes a list of filters and returns JSON :Parameters: - `filters`: List of Filters, (key, val) tuples, or dicts Returns: List of JSON API filters """ data = [] # Filters should always be a list for f in filters: ...
Allows the Query object to be an iterable.
def next(self): """ Allows the Query object to be an iterable. This method will iterate through a cached result set and fetch successive pages as required. A `StopIteration` exception will be raised when there aren't any more results available or when the requested resu...
Executes a query. Additional query parameters can be passed as keyword arguments.
def execute(self, offset=0, **query): """ Executes a query. Additional query parameters can be passed as keyword arguments. Returns: The request parameters and the raw query response. """ _params = self._build_query(**query) self._page_offset = offset _p...
Migrate the data from the Query to a target dataset.
def migrate(self, target, follow=True, **kwargs): """ Migrate the data from the Query to a target dataset. Valid optional kwargs include: * target_fields * include_errors * validation_params * metadata * commit_mode """ from solvebio imp...
Sets up the auth credentials using the provided key/ token or checks the credentials file ( if no token provided ).
def login(**kwargs): """ Sets up the auth credentials using the provided key/token, or checks the credentials file (if no token provided). Lookup order: 1. access_token 2. api_key 3. local credentials No errors are raised if no key is found. """ from .cli.auth impor...
Main entry point for SolveBio CLI
def main(argv=sys.argv[1:]): """ Main entry point for SolveBio CLI """ parser = SolveArgumentParser() args = parser.parse_solvebio_args(argv) if args.api_host: solvebio.api_host = args.api_host if args.api_key: solvebio.api_key = args.api_key if not solvebio.api_key: #...
The _add_subcommands method must be separate from the __init__ method as infinite recursion will occur otherwise due to the fact that the __init__ method itself will be called when instantiating a subparser as we do below
def _add_subcommands(self): """ The _add_subcommands method must be separate from the __init__ method, as infinite recursion will occur otherwise, due to the fact that the __init__ method itself will be called when instantiating a subparser, as we do below ...
Try to parse the args first and then add the subparsers. We want to do this so that we can check to see if there are any unknown args. We can assume that if by this point there are no unknown args we can append shell to the unknown args as a default. However to do this we have to suppress stdout/ stderr during the init...
def parse_solvebio_args(self, args=None, namespace=None): """ Try to parse the args first, and then add the subparsers. We want to do this so that we can check to see if there are any unknown args. We can assume that if, by this point, there are no unknown args, w...
Recursively downloads a folder in a vault to a local directory. Only downloads files not datasets.
def download_vault_folder(remote_path, local_path, dry_run=False, force=False): """Recursively downloads a folder in a vault to a local directory. Only downloads files, not datasets.""" local_path = os.path.normpath(os.path.expanduser(local_path)) if not os.access(local_path, os.W_OK): raise Ex...
Used to create a new object from an HTTP response
def construct_from(cls, values, **kwargs): """Used to create a new object from an HTTP response""" instance = cls(values.get(cls.ID_ATTR), **kwargs) instance.refresh_from(values) return instance
Revoke the token and remove the cookie.
def logout(self): """Revoke the token and remove the cookie.""" if self._oauth_client_secret: try: oauth_token = flask.request.cookies[self.TOKEN_COOKIE_NAME] # Revoke the token requests.post( urljoin(self._api_host, self.OA...
Open the SolveBio shell ( IPython wrapper )
def launch_ipython_shell(args): # pylint: disable=unused-argument """Open the SolveBio shell (IPython wrapper)""" try: import IPython # noqa except ImportError: _print("The SolveBio Python shell requires IPython.\n" "To install, type: 'pip install ipython'") return F...
Open the SolveBio shell ( IPython wrapper ) with IPython 5 +
def launch_ipython_5_shell(args): """Open the SolveBio shell (IPython wrapper) with IPython 5+""" import IPython # noqa from traitlets.config import Config c = Config() path = os.path.dirname(os.path.abspath(__file__)) try: # see if we're already inside IPython get_ipython # ...
Open the SolveBio shell ( IPython wrapper ) for older IPython versions
def launch_ipython_legacy_shell(args): # pylint: disable=unused-argument """Open the SolveBio shell (IPython wrapper) for older IPython versions""" try: from IPython.config.loader import Config except ImportError: _print("The SolveBio Python shell requires IPython.\n" "To ins...
Issues an HTTP GET across the wire via the Python requests library. See * request () * for information on keyword args.
def get(self, url, params, **kwargs): """Issues an HTTP GET across the wire via the Python requests library. See *request()* for information on keyword args.""" kwargs['params'] = params return self.request('GET', url, **kwargs)
Issues an HTTP DELETE across the wire via the Python requests library. See * request * for information on keyword args.
def delete(self, url, data, **kwargs): """Issues an HTTP DELETE across the wire via the Python requests library. See *request* for information on keyword args.""" kwargs['data'] = data return self.request('DELETE', url, **kwargs)
Issues an HTTP Request across the wire via the Python requests library.
def request(self, method, url, **kwargs): """ Issues an HTTP Request across the wire via the Python requests library. Parameters ---------- method : str an HTTP method: GET, PUT, POST, DELETE, ... url : str the place to connect to. If the ...
Get Task child object class
def child_object(self): """ Get Task child object class """ from . import types child_klass = types.get(self.task_type.split('.')[1]) return child_klass.retrieve(self.task_id, client=self._client)
Cancel a task
def cancel(self): """ Cancel a task """ _status = self.status self.status = "canceled" try: self.save() except: # Reset status to what it was before # status update failure self.status = _status raise
Specialized INFO field parser for SnpEff ANN fields. Requires self. _snpeff_ann_fields to be set.
def _parse_info_snpeff(self, info): """ Specialized INFO field parser for SnpEff ANN fields. Requires self._snpeff_ann_fields to be set. """ ann = info.pop('ANN', []) or [] # Overwrite the existing ANN with something parsed # Split on '|', merge with the ANN keys ...
Expands multiple alleles into one record each using an internal buffer ( _next ).
def next(self): """ Expands multiple alleles into one record each using an internal buffer (_next). """ def _alt(alt): """Parses the VCF row ALT object.""" # If alt is '.' in VCF, PyVCF returns None, convert back to '.' if not alt: ...
Return a parsed dictionary for JSON.
def row_to_dict(self, row, allele, alternate_alleles): """Return a parsed dictionary for JSON.""" def _variant_sbid(**kwargs): """Generates a SolveBio variant ID (SBID).""" return '{build}-{chromosome}-{start}-{stop}-{allele}'\ .format(**kwargs).upper() ...
Returns the user s stored API key if a valid credentials file is found. Raises CredentialsError if no valid credentials file is found.
def get_credentials(): """ Returns the user's stored API key if a valid credentials file is found. Raises CredentialsError if no valid credentials file is found. """ try: netrc_path = netrc.path() auths = netrc(netrc_path).authenticators( urlparse(solvebio.api_host).netlo...
Dump the class data in the format of a. netrc file.
def save(self, path): """Dump the class data in the format of a .netrc file.""" rep = "" for host in self.hosts.keys(): attrs = self.hosts[host] rep = rep + "machine " + host + "\n\tlogin " \ + six.text_type(attrs[0]) + "\n" if attrs[1]: ...
>>> _isint ( 123 ) True >>> _isint ( 123. 45 ) False
def _isint(string): """ >>> _isint("123") True >>> _isint("123.45") False """ return type(string) is int or \ (isinstance(string, _binary_type) or isinstance(string, string_types)) and \ _isconvertible(int, string)
[ string ] - > [ padded_string ]
def _align_column(strings, alignment, minwidth=0, has_invisible=True): """ [string] -> [padded_string] >>> list(map(str,_align_column( \ ["12.345", "-1234.5", "1.23", "1234.5", \ "1e+234", "1.0e234"], "decimal"))) [' 12.345 ', '-1234.5 ', ' 1.23 ', \ ' 1234.5 ', ' ...
Format a value accoding to its type.
def _format(val, valtype, floatfmt, missingval=""): """ Format a value accoding to its type. Unicode is supported: >>> hrow = ['\u0431\u0443\u043a\u0432\u0430', \ '\u0446\u0438\u0444\u0440\u0430'] ; \ tbl = [['\u0430\u0437', 2], ['\u0431\u0443\u043a\u0438', 4]] ; \ good...
Transform a supported data type to a list of lists and a list of headers.
def _normalize_tabular_data(tabular_data, headers, sort=True): """ Transform a supported data type to a list of lists, and a list of headers. Supported tabular data types: * list-of-lists or another iterable of iterables * 2D NumPy arrays * dict of iterables (usually used with headers="keys"...
Return a string which represents a row of data cells.
def _build_row(cells, padding, begin, sep, end): "Return a string which represents a row of data cells." pad = " " * padding padded_cells = [pad + cell + pad for cell in cells] # SolveBio: we're only displaying Key-Value tuples (dimension of 2). # enforce that we don't wrap lines by setting a max...
Return a string which represents a horizontal line.
def _build_line(colwidths, padding, begin, fill, sep, end): "Return a string which represents a horizontal line." cells = [fill * (w + 2 * padding) for w in colwidths] return _build_row(cells, 0, begin, sep, end)
Prefix every cell in a row with an HTML alignment attribute.
def _mediawiki_cell_attrs(row, colaligns): "Prefix every cell in a row with an HTML alignment attribute." alignment = {"left": '', "right": 'align="right"| ', "center": 'align="center"| ', "decimal": 'align="right"| '} row2 = [alignment[a] + c for c, a in z...
Return a segment of a horizontal line with optional colons which indicate column s alignment ( as in pipe output format ).
def _line_segment_with_colons(linefmt, align, colwidth): """Return a segment of a horizontal line with optional colons which indicate column's alignment (as in `pipe` output format).""" fill = linefmt.hline w = colwidth if align in ["right", "decimal"]: return (fill[0] * (w - 1)) + ":" e...
Produce a plain - text representation of the table.
def _format_table(fmt, headers, rows, colwidths, colaligns): """Produce a plain-text representation of the table.""" lines = [] hidden = fmt.with_header_hide if headers else fmt.without_header_hide pad = fmt.padding headerrow = fmt.headerrow if fmt.headerrow else fmt.datarow if fmt.lineabove an...
This is a shortcut to creating a DatasetImport. Can t use import () because of Python.
def import_file(self, path, **kwargs): """ This is a shortcut to creating a DatasetImport. Can't use "import()" because of Python. """ from . import Manifest from . import DatasetImport if 'id' not in self or not self['id']: raise Exception( ...
Migrate the data from this dataset to a target dataset.
def migrate(self, target, follow=True, **kwargs): """ Migrate the data from this dataset to a target dataset. Valid optional kwargs include: * source_params * target_fields * include_errors * commit_mode """ if 'id' not in self or not self['id']...
Helper method to parse a full or partial path and return a full path as well as a dict containing path parts.
def validate_full_path(cls, full_path, **kwargs): """Helper method to parse a full or partial path and return a full path as well as a dict containing path parts. Uses the following rules when processing the path: * If no domain, uses the current user's account domain *...
Attempt to create a new dataset given the following params:
def create_dataset(args): """ Attempt to create a new dataset given the following params: * template_id * template_file * capacity * create_vault * [argument] dataset name or full path NOTE: genome_build has been deprecated and is no longer used. """ # For ...
Given a folder or file upload all the folders and files contained within it skipping ones that already exist on the remote.
def upload(args): """ Given a folder or file, upload all the folders and files contained within it, skipping ones that already exist on the remote. """ base_remote_path, path_dict = Object.validate_full_path( args.full_path, vault=args.vault, path=args.path) # Assert the vault exists an...
Given a dataset and a local path upload and import the file ( s ).
def import_file(args): """ Given a dataset and a local path, upload and import the file(s). Command arguments (args): * create_dataset * template_id * full_path * vault (optional, overrides the vault in full_path) * path (optional, overrides the path in full_path) ...
Helper method to return a full path from a full or partial path.
def validate_full_path(cls, full_path, **kwargs): """Helper method to return a full path from a full or partial path. If no domain, assumes user's account domain If the vault is "~", assumes personal vault. Valid vault paths include: domain:vault domain...
Validate SolveBio API host url.
def validate_api_host_url(url): """ Validate SolveBio API host url. Valid urls must not be empty and must contain either HTTP or HTTPS scheme. """ if not url: raise SolveError('No SolveBio API host is set') parsed = urlparse(url) if parsed.scheme not in ['http', 'https']: ...
Add one or more files or URLs to the manifest. If files contains a glob it is expanded.
def add(self, *args): """ Add one or more files or URLs to the manifest. If files contains a glob, it is expanded. All files are uploaded to SolveBio. The Upload object is used to fill the manifest. """ def _is_url(path): p = urlparse(path) ...
Annotate a set of records with stored fields.
def annotate(self, records, **kwargs): """Annotate a set of records with stored fields. Args: records: A list or iterator (can be a Query object) chunk_size: The number of records to annotate at once (max 500). Returns: A generator that yields one annotated ...
Evaluates the expression with the provided context and format.
def evaluate(self, data=None, data_type='string', is_list=False): """Evaluates the expression with the provided context and format.""" payload = { 'data': data, 'expression': self.expr, 'data_type': data_type, 'is_list': is_list } res = sel...
Format output using * format_name *.
def format_output(data, headers, format_name, **kwargs): """Format output using *format_name*. This is a wrapper around the :class:`TabularOutputFormatter` class. :param iterable data: An :term:`iterable` (e.g. list) of rows. :param iterable headers: The column headers. :param str format_name: The...
Set the default format name.
def format_name(self, format_name): """Set the default format name. :param str format_name: The display format name. :raises ValueError: if the format is not recognized. """ if format_name in self.supported_formats: self._format_name = format_name else: ...
Register a new output formatter.
def register_new_formatter(cls, format_name, handler, preprocessors=(), kwargs=None): """Register a new output formatter. :param str format_name: The name of the format. :param callable handler: The function that formats the data. :param tuple preprocessor...
Format the headers and data using a specific formatter.
def format_output(self, data, headers, format_name=None, preprocessors=(), column_types=None, **kwargs): """Format the headers and data using a specific formatter. *format_name* must be a supported formatter (see :attr:`supported_formats`). :param iterable data: A...
Get a list of the data types for each column in * data *.
def _get_column_types(self, data): """Get a list of the data types for each column in *data*.""" columns = list(zip_longest(*data)) return [self._get_column_type(column) for column in columns]
Get the most generic data type for iterable * column *.
def _get_column_type(self, column): """Get the most generic data type for iterable *column*.""" type_values = [TYPES[self._get_type(v)] for v in column] inverse_types = {v: k for k, v in TYPES.items()} return inverse_types[max(type_values)]
Get the data type for * value *.
def _get_type(self, value): """Get the data type for *value*.""" if value is None: return type(None) elif type(value) in int_types: return int elif type(value) in float_types: return float elif isinstance(value, binary_type): return...
Wrap tabulate inside a function for TabularOutputFormatter.
def adapter(data, headers, table_format=None, preserve_whitespace=False, **kwargs): """Wrap tabulate inside a function for TabularOutputFormatter.""" keys = ('floatfmt', 'numalign', 'stralign', 'showindex', 'disable_numparse') tkwargs = {'tablefmt': table_format} tkwargs.update(filter_dict_b...
Returns the config folder for the application. The default behavior is to return whatever is most appropriate for the operating system.
def get_user_config_dir(app_name, app_author, roaming=True, force_xdg=True): """Returns the config folder for the application. The default behavior is to return whatever is most appropriate for the operating system. For an example application called ``"My App"`` by ``"Acme"``, something like the follo...
r Returns a list of system - wide config folders for the application.
def get_system_config_dirs(app_name, app_author, force_xdg=True): r"""Returns a list of system-wide config folders for the application. For an example application called ``"My App"`` by ``"Acme"``, something like the following folders could be returned: macOS (non-XDG): ``['/Library/Application ...
Read the default config file.
def read_default_config(self): """Read the default config file. :raises DefaultConfigValidationError: There was a validation error with the *default* file. """ if self.validate: self.default_config = ConfigObj(configspec=self.def...
Read the default additional system and user config files.
def read(self): """Read the default, additional, system, and user config files. :raises DefaultConfigValidationError: There was a validation error with the *default* file. """ if self.default_file: self.read_default_config() ...
Get the absolute path to the user config file.
def user_config_file(self): """Get the absolute path to the user config file.""" return os.path.join( get_user_config_dir(self.app_name, self.app_author), self.filename)
Get a list of absolute paths to the system config files.
def system_config_files(self): """Get a list of absolute paths to the system config files.""" return [os.path.join(f, self.filename) for f in get_system_config_dirs( self.app_name, self.app_author)]
Get a list of absolute paths to the additional config files.
def additional_files(self): """Get a list of absolute paths to the additional config files.""" return [os.path.join(f, self.filename) for f in self.additional_dirs]