sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def run(self): """ Tornado worker which handles HTTP requests. """ setproctitle.setproctitle("{:s}: worker {:s}".format( self.context.config.name, self._tornado_app.settings['interface'].name)) self.logger.info( "Worker '%s' has been started wi...
Tornado worker which handles HTTP requests.
entailment
def initialize(self): """ Initialize instance attributes. You can override this method in the subclasses. """ self.main_pid = os.getpid() self.processes.extend(self.init_service_processes()) self.processes.extend(self.init_tornado_workers())
Initialize instance attributes. You can override this method in the subclasses.
entailment
def sigusr1_handler(self, unused_signum, unused_frame): """ Handle SIGUSR1 signal. Call function which is defined in the **settings.SIGUSR1_HANDLER**. If main process, forward the signal to all child processes. """ for process in self.processes: if process.pid...
Handle SIGUSR1 signal. Call function which is defined in the **settings.SIGUSR1_HANDLER**. If main process, forward the signal to all child processes.
entailment
def init_service_processes(self): """ Prepare processes defined in the **settings.SERVICE_PROCESSES**. Return :class:`list` of the :class:`ProcessWrapper` instances. """ processes = [] for process_struct in getattr( self.context.config.settings, 'SERVICE_...
Prepare processes defined in the **settings.SERVICE_PROCESSES**. Return :class:`list` of the :class:`ProcessWrapper` instances.
entailment
def init_tornado_workers(self): """ Prepare worker instances for all Tornado applications. Return :class:`list` of the :class:`ProcessWrapper` instances. """ workers = [] for tornado_app in get_tornado_apps(self.context, debug=False): interface = tornado_app....
Prepare worker instances for all Tornado applications. Return :class:`list` of the :class:`ProcessWrapper` instances.
entailment
def start_processes(self, max_restarts=-1): """ Start processes and check their status. When some process crashes, start it again. *max_restarts* is maximum amount of the restarts across all processes. *processes* is a :class:`list` of the :class:`ProcessWrapper` instances. ...
Start processes and check their status. When some process crashes, start it again. *max_restarts* is maximum amount of the restarts across all processes. *processes* is a :class:`list` of the :class:`ProcessWrapper` instances.
entailment
def command(self): """ **runserver** command implementation. """ setproctitle.setproctitle( "{:s}: master process '{:s}'".format( self.context.config.name, " ".join(sys.argv) )) # Init and start processes try: self.star...
**runserver** command implementation.
entailment
def taxtable_to_tree(handle): """Read a CSV taxonomy from *handle* into a Tree.""" c = csv.reader(handle, quoting=csv.QUOTE_NONNUMERIC) header = next(c) rootdict = dict(list(zip(header, next(c)))) t = Tree(rootdict['tax_id'], rank=rootdict[ 'rank'], tax_name=rootdict['tax_name']) fo...
Read a CSV taxonomy from *handle* into a Tree.
entailment
def lonely_company(taxonomy, tax_ids): """Return a set of species tax_ids which will makes those in *tax_ids* not lonely. The returned species will probably themselves be lonely. """ return [taxonomy.species_below(taxonomy.sibling_of(t)) for t in tax_ids]
Return a set of species tax_ids which will makes those in *tax_ids* not lonely. The returned species will probably themselves be lonely.
entailment
def solid_company(taxonomy, tax_ids): """Return a set of non-lonely species tax_ids that will make those in *tax_ids* not lonely.""" res = [] for t in tax_ids: res.extend(taxonomy.nary_subtree(taxonomy.sibling_of(t), 2) or []) return res
Return a set of non-lonely species tax_ids that will make those in *tax_ids* not lonely.
entailment
def eval_algorithm(curr, prev): """ Evaluates OBV Args: curr: Dict of current volume and close prev: Dict of previous OBV and close Returns: Float of OBV """ if curr['close'] > prev['close']: v = curr['volume'] elif curr['...
Evaluates OBV Args: curr: Dict of current volume and close prev: Dict of previous OBV and close Returns: Float of OBV
entailment
def eval_from_json(json): """ Evaluates OBV from JSON (typically Poloniex API response) Args: json: List of dates where each entry is a dict of raw market data. Returns: Float of OBV """ closes = poloniex.get_attribute(json, 'close') volumes = po...
Evaluates OBV from JSON (typically Poloniex API response) Args: json: List of dates where each entry is a dict of raw market data. Returns: Float of OBV
entailment
def scratch_file(unlink=True, **kwargs): """Create a temporary file and return its name. Additional arguments are passed to :class:`tempfile.NamedTemporaryFile` At the start of the with block a secure, temporary file is created and its name returned. At the end of the with block it is deleted. ...
Create a temporary file and return its name. Additional arguments are passed to :class:`tempfile.NamedTemporaryFile` At the start of the with block a secure, temporary file is created and its name returned. At the end of the with block it is deleted.
entailment
def open(self, name, *mode): """ Return an open file object for a file in the reference package. """ return self.file_factory(self.file_path(name), *mode)
Return an open file object for a file in the reference package.
entailment
def open_resource(self, resource, *mode): """ Return an open file object for a particular named resource in this reference package. """ return self.open(self.resource_name(resource), *mode)
Return an open file object for a particular named resource in this reference package.
entailment
def resource_name(self, resource): """ Return the name of the file within the reference package for a particular named resource. """ if not(resource in self.contents['files']): raise ValueError("No such resource %r in refpkg" % (resource,)) return self.content...
Return the name of the file within the reference package for a particular named resource.
entailment
def resource_md5(self, resource): """Return the stored MD5 sum for a particular named resource.""" if not(resource in self.contents['md5']): raise ValueError("No such resource %r in refpkg" % (resource,)) return self.contents['md5'][resource]
Return the stored MD5 sum for a particular named resource.
entailment
def _set_defaults(self): """ Set some default values in the manifest. This method should be called after loading from disk, but before checking the integrity of the reference package. """ self.contents.setdefault('log', []) self.contents.setdefault('rollback', No...
Set some default values in the manifest. This method should be called after loading from disk, but before checking the integrity of the reference package.
entailment
def _sync_to_disk(self): """Write any changes made on Refpkg to disk. Other methods of Refpkg that alter the contents of the package will call this method themselves. Generally you should never have to call it by hand. The only exception would be if another program has changed...
Write any changes made on Refpkg to disk. Other methods of Refpkg that alter the contents of the package will call this method themselves. Generally you should never have to call it by hand. The only exception would be if another program has changed the Refpkg on disk while your ...
entailment
def _sync_from_disk(self): """Read any changes made on disk to this Refpkg. This is necessary if other programs are making changes to the Refpkg on disk and your program must be synchronized to them. """ try: fobj = self.open_manifest('r') except IOError as ...
Read any changes made on disk to this Refpkg. This is necessary if other programs are making changes to the Refpkg on disk and your program must be synchronized to them.
entailment
def _add_file(self, key, path): """Copy a file into the reference package.""" filename = os.path.basename(path) base, ext = os.path.splitext(filename) if os.path.exists(self.file_path(filename)): with tempfile.NamedTemporaryFile( dir=self.path, prefix=base...
Copy a file into the reference package.
entailment
def is_invalid(self): """Check if this RefPkg is invalid. Valid means that it contains a properly named manifest, and each of the files described in the manifest exists and has the proper MD5 hashsum. If the Refpkg is valid, is_invalid returns False. Otherwise it retur...
Check if this RefPkg is invalid. Valid means that it contains a properly named manifest, and each of the files described in the manifest exists and has the proper MD5 hashsum. If the Refpkg is valid, is_invalid returns False. Otherwise it returns a nonempty string describing t...
entailment
def update_metadata(self, key, value): """Set *key* in the metadata to *value*. Returns the previous value of *key*, or None if the key was not previously set. """ old_value = self.contents['metadata'].get(key) self.contents['metadata'][key] = value self._log('Up...
Set *key* in the metadata to *value*. Returns the previous value of *key*, or None if the key was not previously set.
entailment
def update_file(self, key, new_path): """Insert file *new_path* into the refpkg under *key*. The filename of *new_path* will be preserved in the refpkg unless it would conflict with a previously existing file, in which case a suffix is appended which makes it unique. The previo...
Insert file *new_path* into the refpkg under *key*. The filename of *new_path* will be preserved in the refpkg unless it would conflict with a previously existing file, in which case a suffix is appended which makes it unique. The previous file, if there was one, is left in the refpkg....
entailment
def reroot(self, rppr=None, pretend=False): """Reroot the phylogenetic tree. This operation calls ``rppr reroot`` to generate the rerooted tree, so you must have ``pplacer`` and its auxiliary tools ``rppr`` and ``guppy`` installed for it to work. You can specify the path to ``r...
Reroot the phylogenetic tree. This operation calls ``rppr reroot`` to generate the rerooted tree, so you must have ``pplacer`` and its auxiliary tools ``rppr`` and ``guppy`` installed for it to work. You can specify the path to ``rppr`` by giving it as the *rppr* argument. ...
entailment
def update_phylo_model(self, stats_type, stats_file, frequency_type=None): """Parse a stats log and use it to update ``phylo_model``. ``pplacer`` expects its input to include the deatils of the phylogenetic model used for creating a tree in JSON format under the key ``phylo_model``, but...
Parse a stats log and use it to update ``phylo_model``. ``pplacer`` expects its input to include the deatils of the phylogenetic model used for creating a tree in JSON format under the key ``phylo_model``, but no program actually outputs that format. This function takes a log g...
entailment
def rollback(self): """Revert the previous modification to the refpkg. """ # This is slightly complicated because of Python's freakish # assignment semantics and because we don't store multiple # copies of the log. if self.contents['rollback'] is None: raise V...
Revert the previous modification to the refpkg.
entailment
def rollforward(self): """Restore a reverted modification to the refpkg. """ if self.contents['rollforward'] is None: raise ValueError("No operation to roll forward on refpkg") new_log_message = self.contents['rollforward'][0] new_contents = self.contents['rollforward...
Restore a reverted modification to the refpkg.
entailment
def strip(self): """Remove rollbacks, rollforwards, and all non-current files. When distributing a refpkg, you probably want to distribute as small a one as possible. strip removes everything from the refpkg which is not relevant to its current state. """ self._sync_fro...
Remove rollbacks, rollforwards, and all non-current files. When distributing a refpkg, you probably want to distribute as small a one as possible. strip removes everything from the refpkg which is not relevant to its current state.
entailment
def start_transaction(self): """Begin a transaction to group operations on the refpkg. All the operations until the next call to ``commit_transaction`` will be recorded as a single operation for rollback and rollforward, and recorded with a single line in the log. """ ...
Begin a transaction to group operations on the refpkg. All the operations until the next call to ``commit_transaction`` will be recorded as a single operation for rollback and rollforward, and recorded with a single line in the log.
entailment
def commit_transaction(self, log=None): """Commit a transaction, with *log* as the log entry.""" self.current_transaction['rollback'].pop('log') self.current_transaction['rollback'].pop('rollforward') self.contents['log'].insert( 0, log and log or self.current_transaction['lo...
Commit a transaction, with *log* as the log entry.
entailment
def is_ill_formed(self): """Stronger set of checks than is_invalid for Refpkg. Checks that FASTA, Stockholm, JSON, and CSV files under known keys are all valid as well as calling is_invalid. Returns either False or a string describing the error. """ m = self.is_invalid(...
Stronger set of checks than is_invalid for Refpkg. Checks that FASTA, Stockholm, JSON, and CSV files under known keys are all valid as well as calling is_invalid. Returns either False or a string describing the error.
entailment
def load_db(self): """Load the taxonomy into a sqlite3 database. This will set ``self.db`` to a sqlite3 database which contains all of the taxonomic information in the reference package. """ db = taxdb.Taxdb() db.create_tables() reader = csv.DictReader(self.open...
Load the taxonomy into a sqlite3 database. This will set ``self.db`` to a sqlite3 database which contains all of the taxonomic information in the reference package.
entailment
def most_recent_common_ancestor(self, *ts): """Find the MRCA of some tax_ids. Returns the MRCA of the specified tax_ids, or raises ``NoAncestor`` if no ancestor of the specified tax_ids could be found. """ if len(ts) > 200: res = self._large_mrca(ts) else: ...
Find the MRCA of some tax_ids. Returns the MRCA of the specified tax_ids, or raises ``NoAncestor`` if no ancestor of the specified tax_ids could be found.
entailment
def _large_mrca(self, ts): """Find the MRCA using a temporary table.""" cursor = self.db.cursor() cursor.execute(""" DROP TABLE IF EXISTS _mrca_temp """) cursor.execute(""" CREATE TEMPORARY TABLE _mrca_temp( child TEXT PRIMARY KEY REFEREN...
Find the MRCA using a temporary table.
entailment
def _small_mrca(self, ts): """Find a MRCA using query parameters. This only supports a limited number of tax_ids; ``_large_mrca`` will support an arbitrary number. """ cursor = self.db.cursor() qmarks = ', '.join('?' * len(ts)) cursor.execute(""" SELE...
Find a MRCA using query parameters. This only supports a limited number of tax_ids; ``_large_mrca`` will support an arbitrary number.
entailment
def file_abspath(self, resource): """Deprecated alias for *resource_path*.""" warnings.warn( "file_abspath is deprecated; use resource_path instead", DeprecationWarning, stacklevel=2) return self.resource_path(resource)
Deprecated alias for *resource_path*.
entailment
def file_name(self, resource): """Deprecated alias for *resource_name*.""" warnings.warn( "file_name is deprecated; use resource_name instead", DeprecationWarning, stacklevel=2) return self.resource_name(resource)
Deprecated alias for *resource_name*.
entailment
def file_md5(self, resource): """Deprecated alias for *resource_md5*.""" warnings.warn( "file_md5 is deprecated; use resource_md5 instead", DeprecationWarning, stacklevel=2) return self.resource_md5(resource)
Deprecated alias for *resource_md5*.
entailment
def get_app_settings(parser, known_args): """ Return **settings** module of the application according to either command line argument or **SHELTER_SETTINGS_MODULE** environment variable. """ args, dummy_remaining = parser.parse_known_args(known_args) settings_module_path = ( args.set...
Return **settings** module of the application according to either command line argument or **SHELTER_SETTINGS_MODULE** environment variable.
entailment
def get_management_commands(settings): """ Find registered managemend commands and return their classes as a :class:`dict`. Keys are names of the management command and values are classes of the management command. """ app_commands = getattr(settings, 'MANAGEMENT_COMMANDS', ()) commands = {}...
Find registered managemend commands and return their classes as a :class:`dict`. Keys are names of the management command and values are classes of the management command.
entailment
def get_config_class(settings): """ According to **settings.CONFIG_CLASS** return either config class defined by user or default :class:`shelter.core.config.Config`. """ config_cls_name = getattr(settings, 'CONFIG_CLASS', '') if config_cls_name: config_cls = import_object(config_cls_name...
According to **settings.CONFIG_CLASS** return either config class defined by user or default :class:`shelter.core.config.Config`.
entailment
def main(args=None): """ Run management command handled from command line. """ # Base command line parser. Help is not allowed because command # line is parsed in two stages - in the first stage is found setting # module of the application, in the second stage are found management # command'...
Run management command handled from command line.
entailment
def as_length(self, value): """Return a new vector scaled to given length""" new_vec = self.copy() new_vec.length = value return new_vec
Return a new vector scaled to given length
entailment
def as_percent(self, value): """Return a new vector scaled by given decimal percent""" new_vec = self.copy() new_vec.length = value * self.length return new_vec
Return a new vector scaled by given decimal percent
entailment
def dot(self, vec): """Dot product with another vector""" if not isinstance(vec, self.__class__): raise TypeError('Dot product operand must be a vector') return np.dot(self, vec)
Dot product with another vector
entailment
def cross(self, vec): """Cross product with another vector""" if not isinstance(vec, self.__class__): raise TypeError('Cross product operand must be a vector') return self.__class__(np.cross(self, vec))
Cross product with another vector
entailment
def angle(self, vec, unit='rad'): """Calculate the angle between two Vectors unit: unit for returned angle, either 'rad' or 'deg'. Defaults to 'rad' """ if not isinstance(vec, self.__class__): raise TypeError('Angle operand must be of class {}' .f...
Calculate the angle between two Vectors unit: unit for returned angle, either 'rad' or 'deg'. Defaults to 'rad'
entailment
def phi(self): """Polar angle / inclination of this vector in radians Based on sperical coordinate space returns angle between this vector and the positive z-azis range: (0 <= phi <= pi) """ return np.arctan2(np.sqrt(self.x**2 + self.y**2), self.z)
Polar angle / inclination of this vector in radians Based on sperical coordinate space returns angle between this vector and the positive z-azis range: (0 <= phi <= pi)
entailment
def cross(self, vec): """Cross product with another vector""" if not isinstance(vec, self.__class__): raise TypeError('Cross product operand must be a vector') return Vector3(0, 0, np.asscalar(np.cross(self, vec)))
Cross product with another vector
entailment
def length(self): """Array of vector lengths""" return np.sqrt(np.sum(self**2, axis=1)).view(np.ndarray)
Array of vector lengths
entailment
def dot(self, vec): """Dot product with another vector""" if not isinstance(vec, self.__class__): raise TypeError('Dot product operand must be a VectorArray') if self.nV != 1 and vec.nV != 1 and self.nV != vec.nV: raise ValueError('Dot product operands must have the same ...
Dot product with another vector
entailment
def cross(self, vec): """Cross product with another Vector3Array""" if not isinstance(vec, Vector3Array): raise TypeError('Cross product operand must be a Vector3Array') if self.nV != 1 and vec.nV != 1 and self.nV != vec.nV: raise ValueError('Cross product operands must h...
Cross product with another Vector3Array
entailment
def eval_rs(gains, losses): """ Evaluates the RS variable in RSI algorithm Args: gains: List of price gains. losses: List of prices losses. Returns: Float of average gains over average losses. """ # Number of days that the data was collected ...
Evaluates the RS variable in RSI algorithm Args: gains: List of price gains. losses: List of prices losses. Returns: Float of average gains over average losses.
entailment
def eval_from_json(json): """ Evaluates RSI from JSON (typically Poloniex API response) Args: json: List of dates where each entry is a dict of raw market data. Returns: Float between 0 and 100, momentum indicator of a market measuring the speed and change o...
Evaluates RSI from JSON (typically Poloniex API response) Args: json: List of dates where each entry is a dict of raw market data. Returns: Float between 0 and 100, momentum indicator of a market measuring the speed and change of price movements.
entailment
def sigusr1_handler(self, unused_signum, unused_frame): """ Handle SIGUSR1 signal. Call function which is defined in the **settings.SIGUSR1_HANDLER**. """ if self._sigusr1_handler_func is not None: self._sigusr1_handler_func(self.context)
Handle SIGUSR1 signal. Call function which is defined in the **settings.SIGUSR1_HANDLER**.
entailment
def sigusr2_handler(self, unused_signum, unused_frame): """ Handle SIGUSR2 signal. Call function which is defined in the **settings.SIGUSR2_HANDLER**. """ if self._sigusr1_handler_func is not None: self._sigusr2_handler_func(self.context)
Handle SIGUSR2 signal. Call function which is defined in the **settings.SIGUSR2_HANDLER**.
entailment
def action(args): """ Show information about reference packages. """ log.info('loading reference package') pkg = refpkg.Refpkg(args.refpkg, create=False) with open(pkg.file_abspath('seq_info'), 'rU') as seq_info: seqinfo = list(csv.DictReader(seq_info)) snames = [row['seqname']...
Show information about reference packages.
entailment
def json_to_url(json, symbol): """ Converts a JSON to a URL by the Poloniex API Args: json: JSON data as a list of dict dates, where the keys are the raw market statistics. symbol: String of currency pair, like a ticker symbol. Returns: String URL to Poloniex API repre...
Converts a JSON to a URL by the Poloniex API Args: json: JSON data as a list of dict dates, where the keys are the raw market statistics. symbol: String of currency pair, like a ticker symbol. Returns: String URL to Poloniex API representing the given JSON.
entailment
def chart_json(start, end, period, symbol): """ Requests chart data from Poloniex API Args: start: Int epoch date to START getting market stats from. Note that this epoch is FURTHER from the current date. end: Int epoch date to STOP getting market stats from. Note th...
Requests chart data from Poloniex API Args: start: Int epoch date to START getting market stats from. Note that this epoch is FURTHER from the current date. end: Int epoch date to STOP getting market stats from. Note that this epoch is CLOSER to the current date. ...
entailment
def parse_changes(json): """ Gets price changes from JSON Args: json: JSON data as a list of dict dates, where the keys are the raw market statistics. Returns: List of floats of price changes between entries in JSON. """ changes = [] dates = len(json) for date i...
Gets price changes from JSON Args: json: JSON data as a list of dict dates, where the keys are the raw market statistics. Returns: List of floats of price changes between entries in JSON.
entailment
def get_gains_losses(changes): """ Categorizes changes into gains and losses Args: changes: List of floats of price changes between entries in JSON. Returns: Dict of changes with keys 'gains' and 'losses'. All values are positive. """ res = {'gains': [], 'losses': []} f...
Categorizes changes into gains and losses Args: changes: List of floats of price changes between entries in JSON. Returns: Dict of changes with keys 'gains' and 'losses'. All values are positive.
entailment
def get_attribute(json, attr): """ Gets the values of an attribute from JSON Args: json: JSON data as a list of dict dates, where the keys are the raw market statistics. attr: String of attribute in JSON file to collect. Returns: List of values of specified attribute fr...
Gets the values of an attribute from JSON Args: json: JSON data as a list of dict dates, where the keys are the raw market statistics. attr: String of attribute in JSON file to collect. Returns: List of values of specified attribute from JSON
entailment
def get_json_shift(year, month, day, unit, count, period, symbol): """ Gets JSON from shifted date by the Poloniex API Args: year: Int between 1 and 9999. month: Int between 1 and 12. day: Int between 1 and 31. unit: String of time period unit for count argument. How...
Gets JSON from shifted date by the Poloniex API Args: year: Int between 1 and 9999. month: Int between 1 and 12. day: Int between 1 and 31. unit: String of time period unit for count argument. How far back to check historical market data. Valid values: 'hour'...
entailment
def filter_ranks(results): """ Find just the first rank for all the results for a given tax_id. """ for _, group in itertools.groupby(results, operator.itemgetter(0)): yield next(group)
Find just the first rank for all the results for a given tax_id.
entailment
def eval_algorithm(closing, low, high): """ Evaluates the SO algorithm Args: closing: Float of current closing price. low: Float of lowest low closing price throughout some duration. high: Float of highest high closing price throughout some duration. Returns...
Evaluates the SO algorithm Args: closing: Float of current closing price. low: Float of lowest low closing price throughout some duration. high: Float of highest high closing price throughout some duration. Returns: Float SO between 0 and 100.
entailment
def eval_from_json(json): """ Evaluates SO from JSON (typically Poloniex API response) Args: json: List of dates where each entry is a dict of raw market data. Returns: Float SO between 0 and 100. """ close = json[-1]['close'] # Latest closing price ...
Evaluates SO from JSON (typically Poloniex API response) Args: json: List of dates where each entry is a dict of raw market data. Returns: Float SO between 0 and 100.
entailment
def avg(vals, count=None): """ Returns the average value Args: vals: List of numbers to calculate average from. count: Int of total count that vals was part of. Returns: Float average value throughout a count. """ sum = 0 for v in vals: sum += v if count is...
Returns the average value Args: vals: List of numbers to calculate average from. count: Int of total count that vals was part of. Returns: Float average value throughout a count.
entailment
def db_connect(engine, schema=None, clobber=False): """Create a connection object to a database. Attempt to establish a schema. If there are existing tables, delete them if clobber is True and return otherwise. Returns a sqlalchemy engine object. """ if schema is None: base = declarative_b...
Create a connection object to a database. Attempt to establish a schema. If there are existing tables, delete them if clobber is True and return otherwise. Returns a sqlalchemy engine object.
entailment
def read_nodes(rows, source_id=1): """ Return an iterator of rows ready to insert into table "nodes". * rows - iterator of lists (eg, output from read_archive or read_dmp) """ ncbi_keys = ['tax_id', 'parent_id', 'rank', 'embl_code', 'division_id'] extra_keys = ['source_id', 'is_valid'] is_...
Return an iterator of rows ready to insert into table "nodes". * rows - iterator of lists (eg, output from read_archive or read_dmp)
entailment
def read_names(rows, source_id=1): """Return an iterator of rows ready to insert into table "names". Adds columns "is_primary" (identifying the primary name for each tax_id with a vaule of 1) and "is_classified" (always None). * rows - iterator of lists (eg, output from read_archive or read_dmp) * ...
Return an iterator of rows ready to insert into table "names". Adds columns "is_primary" (identifying the primary name for each tax_id with a vaule of 1) and "is_classified" (always None). * rows - iterator of lists (eg, output from read_archive or read_dmp) * unclassified_regex - a compiled re matchin...
entailment
def fetch_data(dest_dir='.', clobber=False, url=DATA_URL): """ Download data from NCBI required to generate local taxonomy database. Default url is ncbi.DATA_URL * dest_dir - directory in which to save output files (created if necessary). * clobber - don't download if False and target of url exists...
Download data from NCBI required to generate local taxonomy database. Default url is ncbi.DATA_URL * dest_dir - directory in which to save output files (created if necessary). * clobber - don't download if False and target of url exists in dest_dir * url - url to archive; default is ncbi.DATA_URL ...
entailment
def read_archive(archive, fname): """Return an iterator of unique rows from a zip archive. * archive - path to the zip archive. * fname - name of the compressed file within the archive. """ # Note that deduplication here is equivalent to an upsert/ignore, # but avoids requirement for a databa...
Return an iterator of unique rows from a zip archive. * archive - path to the zip archive. * fname - name of the compressed file within the archive.
entailment
def prepend_schema(self, name): """Prepend schema name to 'name' when a schema is specified """ return '.'.join([self.schema, name]) if self.schema else name
Prepend schema name to 'name' when a schema is specified
entailment
def load_table(self, table, rows, colnames=None, limit=None): """Load 'rows' into table 'table'. If 'colnames' is not provided, the first element of 'rows' must provide column names. """ conn = self.engine.raw_connection() cur = conn.cursor() colnames = colnames or nex...
Load 'rows' into table 'table'. If 'colnames' is not provided, the first element of 'rows' must provide column names.
entailment
def load_archive(self, archive): """Load data from the zip archive of the NCBI taxonomy. """ # source self.load_table( 'source', rows=[('ncbi', DATA_URL)], colnames=['name', 'description'], ) conn = self.engine.raw_connection() ...
Load data from the zip archive of the NCBI taxonomy.
entailment
def date_to_delorean(year, month, day): """ Converts date arguments to a Delorean instance in UTC Args: year: int between 1 and 9999. month: int between 1 and 12. day: int between 1 and 31. Returns: Delorean instance in UTC of date. """ return Delorean(datetime=...
Converts date arguments to a Delorean instance in UTC Args: year: int between 1 and 9999. month: int between 1 and 12. day: int between 1 and 31. Returns: Delorean instance in UTC of date.
entailment
def date_to_epoch(year, month, day): """ Converts a date to epoch in UTC Args: year: int between 1 and 9999. month: int between 1 and 12. day: int between 1 and 31. Returns: Int epoch in UTC from date. """ return int(date_to_delorean(year, month, day).epoch)
Converts a date to epoch in UTC Args: year: int between 1 and 9999. month: int between 1 and 12. day: int between 1 and 31. Returns: Int epoch in UTC from date.
entailment
def shift_epoch(delorean, direction, unit, count): """ Gets the resulting epoch after a time shift of a Delorean Args: delorean: Delorean datetime instance to shift from. direction: String to shift time forwards or backwards. Valid values: 'last', 'next'. unit: String of...
Gets the resulting epoch after a time shift of a Delorean Args: delorean: Delorean datetime instance to shift from. direction: String to shift time forwards or backwards. Valid values: 'last', 'next'. unit: String of time period unit for count argument. What unit...
entailment
def generate_epochs(delorean, direction, unit, count): """ Generates epochs from a shifted Delorean instance Args: delorean: Delorean datetime instance to shift from. direction: String to shift time forwards or backwards. Valid values: 'last', 'next'. unit: String of tim...
Generates epochs from a shifted Delorean instance Args: delorean: Delorean datetime instance to shift from. direction: String to shift time forwards or backwards. Valid values: 'last', 'next'. unit: String of time period unit for count argument. What unit in dire...
entailment
def get_end_start_epochs(year, month, day, direction, unit, count): """ Gets epoch from a start date and epoch from a shifted date Args: year: Int between 1 and 9999. month: Int between 1 and 12. day: Int between 1 and 31. direction: String to shift time forwards or backwards. ...
Gets epoch from a start date and epoch from a shifted date Args: year: Int between 1 and 9999. month: Int between 1 and 12. day: Int between 1 and 31. direction: String to shift time forwards or backwards. Valid values: 'last', 'next'. unit: String of time period...
entailment
def add_child(self, child): """ Add a child to this node. """ assert child != self child.parent = self child.ranks = self.ranks child.index = self.index assert child.tax_id not in self.index self.index[child.tax_id] = child self.children.ad...
Add a child to this node.
entailment
def remove_child(self, child): """ Remove a child from this node. """ assert child in self.children self.children.remove(child) self.index.pop(child.tax_id) if child.parent is self: child.parent = None if child.index is self.index: ...
Remove a child from this node.
entailment
def drop(self): """ Remove this node from the taxonomy, maintaining child subtrees by adding them to the node's parent, and moving sequences at this node to the parent. Not valid for root node. """ if self.is_root: raise ValueError("Cannot drop root n...
Remove this node from the taxonomy, maintaining child subtrees by adding them to the node's parent, and moving sequences at this node to the parent. Not valid for root node.
entailment
def prune_unrepresented(self): """ Remove nodes without sequences or children below this node. """ for node in self.depth_first_iter(self_first=False): if (not node.children and not node.sequence_ids and node is not self): ...
Remove nodes without sequences or children below this node.
entailment
def at_rank(self, rank): """ Find the node above this node at rank ``rank`` """ s = self while s: if s.rank == rank: return s s = s.parent raise ValueError("No node at rank {0} for {1}".format( rank, self.tax_id))
Find the node above this node at rank ``rank``
entailment
def depth_first_iter(self, self_first=True): """ Iterate over nodes below this node, optionally yielding children before self. """ if self_first: yield self for child in list(self.children): for i in child.depth_first_iter(self_first): ...
Iterate over nodes below this node, optionally yielding children before self.
entailment
def path(self, tax_ids): """Get the node at the end of the path described by tax_ids.""" assert tax_ids[0] == self.tax_id if len(tax_ids) == 1: return self n = tax_ids[1] try: child = next(i for i in self.children if i.tax_id == n) except StopIter...
Get the node at the end of the path described by tax_ids.
entailment
def lineage(self): """ Return all nodes between this node and the root, including this one. """ if not self.parent: return [self] else: L = self.parent.lineage() L.append(self) return L
Return all nodes between this node and the root, including this one.
entailment
def write_taxtable(self, out_fp, **kwargs): """ Write a taxtable for this node and all descendants, including the lineage leading to this node. """ ranks_represented = frozenset(i.rank for i in self) | \ frozenset(i.rank for i in self.lineage()) ranks = [i for...
Write a taxtable for this node and all descendants, including the lineage leading to this node.
entailment
def populate_from_seqinfo(self, seqinfo): """Populate sequence_ids below this node from a seqinfo file object.""" for row in csv.DictReader(seqinfo): node = self.index.get(row['tax_id']) if node: node.sequence_ids.add(row['seqname'])
Populate sequence_ids below this node from a seqinfo file object.
entailment
def collapse(self, remove=False): """ Move all ``sequence_ids`` in the subtree below this node to this node. If ``remove`` is True, nodes below this one are deleted from the taxonomy. """ descendants = iter(self) # Skip this node assert next(descendants) ...
Move all ``sequence_ids`` in the subtree below this node to this node. If ``remove`` is True, nodes below this one are deleted from the taxonomy.
entailment
def write_seqinfo(self, out_fp, include_name=True): """ Write a simple seq_info file, suitable for use in taxtastic. Useful for printing out the results of collapsing tax nodes - super bare bones, just tax_id and seqname. If include_name is True, a column with the taxon name is ...
Write a simple seq_info file, suitable for use in taxtastic. Useful for printing out the results of collapsing tax nodes - super bare bones, just tax_id and seqname. If include_name is True, a column with the taxon name is included.
entailment
def from_taxtable(cls, taxtable_fp): """ Generate a node from an open handle to a taxtable, as generated by ``taxit taxtable`` """ r = csv.reader(taxtable_fp) headers = next(r) rows = (collections.OrderedDict(list(zip(headers, i))) for i in r) row = next(...
Generate a node from an open handle to a taxtable, as generated by ``taxit taxtable``
entailment
def from_taxdb(cls, con, root=None): """ Generate a TaxNode from a taxonomy database """ cursor = con.cursor() if root is None: cursor.execute( "SELECT tax_id, rank FROM nodes WHERE tax_id = parent_id") else: cursor.execute( ...
Generate a TaxNode from a taxonomy database
entailment
def parse_host(host): """ Parse *host* in format ``"[hostname:]port"`` and return :class:`tuple` ``(address, port)``. >>> parse_host('localhost:4444') ('localhost', 4444) >>> parse_host(':4444') ('', 4444) >>> parse_host('4444') ('', 4444) >>> parse_h...
Parse *host* in format ``"[hostname:]port"`` and return :class:`tuple` ``(address, port)``. >>> parse_host('localhost:4444') ('localhost', 4444) >>> parse_host(':4444') ('', 4444) >>> parse_host('4444') ('', 4444) >>> parse_host('2001:db8::1428:57ab:4444') ...
entailment
def get_children(engine, parent_ids, rank='species', schema=None): """ Recursively fetch children of tax_ids in `parent_ids` until the rank of `rank` """ if not parent_ids: return [] nodes = schema + '.nodes' if schema else 'nodes' names = schema + '.names' if schema else 'names' ...
Recursively fetch children of tax_ids in `parent_ids` until the rank of `rank`
entailment
def get_config_items(self): """ Return current configuration as a :class:`tuple` with option-value pairs. :: (('option1', value1), ('option2', value2)) """ return ( ('settings', self.settings), ('context_class', self.context_class), ...
Return current configuration as a :class:`tuple` with option-value pairs. :: (('option1', value1), ('option2', value2))
entailment
def context_class(self): """ Context as a :class:`shelter.core.context.Context` class or subclass. """ if 'context_class' not in self._cached_values: context_cls_name = getattr(self.settings, 'CONTEXT_CLASS', '') if context_cls_name: context_class ...
Context as a :class:`shelter.core.context.Context` class or subclass.
entailment
def interfaces(self): """ Interfaces as a :class:`list`of the :class:`shelter.core.config.Config.Interface` instances. """ if 'interfaces' not in self._cached_values: self._cached_values['interfaces'] = [] for name, interface in six.iteritems(self.settings...
Interfaces as a :class:`list`of the :class:`shelter.core.config.Config.Interface` instances.
entailment