sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def detect_column_renamings(self, table_differences): """ Try to find columns that only changed their names. :type table_differences: TableDiff """ rename_candidates = {} for added_column_name, added_column in table_differences.added_columns.items(): for rem...
Try to find columns that only changed their names. :type table_differences: TableDiff
entailment
def diff_column(self, column1, column2): """ Returns the difference between column1 and column2 :type column1: eloquent.dbal.column.Column :type column2: eloquent.dbal.column.Column :rtype: list """ properties1 = column1.to_dict() properties2 = column2.t...
Returns the difference between column1 and column2 :type column1: eloquent.dbal.column.Column :type column2: eloquent.dbal.column.Column :rtype: list
entailment
def execute(self, i, o): """ Executes the command. :type i: cleo.inputs.input.Input :type o: cleo.outputs.output.Output """ config = self._get_config(i) self._resolver = DatabaseManager(config)
Executes the command. :type i: cleo.inputs.input.Input :type o: cleo.outputs.output.Output
entailment
def call(self, name, options=None, o=None): """ Call another command. :param name: The command name :type name: str :param options: The options :type options: list or None :param o: The output :type o: cleo.outputs.output.Output """ if o...
Call another command. :param name: The command name :type name: str :param options: The options :type options: list or None :param o: The output :type o: cleo.outputs.output.Output
entailment
def _get_config(self, i): """ Get the config. :type i: cleo.inputs.input.Input :rtype: dict """ variables = {} if not i.get_option('config'): raise Exception('The --config|-c option is missing.') with open(i.get_option('config')) as fh: ...
Get the config. :type i: cleo.inputs.input.Input :rtype: dict
entailment
def associate(self, model): """ Associate the model instance to the given parent. :type model: eloquent.Model :rtype: eloquent.Model """ self._parent.set_attribute(self._foreign_key, model.get_key()) self._parent.set_attribute(self._morph_type, model.get_morph_c...
Associate the model instance to the given parent. :type model: eloquent.Model :rtype: eloquent.Model
entailment
def _create_model_by_type(self, type): """ Create a new model instance by type. :rtype: Model """ klass = None for cls in eloquent.orm.model.Model.__subclasses__(): morph_class = cls.__morph_class__ or cls.__name__ if morph_class == type: ...
Create a new model instance by type. :rtype: Model
entailment
def get_column_listing(self, table): """ Get the column listing for a given table. :param table: The table :type table: str :rtype: list """ sql = self._grammar.compile_column_exists() database = self._connection.get_database_name() table = self....
Get the column listing for a given table. :param table: The table :type table: str :rtype: list
entailment
def _populate_stub(self, name, stub, table): """ Populate the placeholders in the migration stub. :param name: The name of the migration :type name: str :param stub: The stub :type stub: str :param table: The table name :type table: str :rtype:...
Populate the placeholders in the migration stub. :param name: The name of the migration :type name: str :param stub: The stub :type stub: str :param table: The table name :type table: str :rtype: str
entailment
def _set_keys_for_save_query(self, query): """ Set the keys for a save update query. :param query: A Builder instance :type query: eloquent.orm.Builder :return: The Builder instance :rtype: eloquent.orm.Builder """ query.where(self._morph_type, self._mor...
Set the keys for a save update query. :param query: A Builder instance :type query: eloquent.orm.Builder :return: The Builder instance :rtype: eloquent.orm.Builder
entailment
def delete(self): """ Delete the pivot model record from the database. :rtype: int """ query = self._get_delete_query() query.where(self._morph_type, self._morph_class) return query.delete()
Delete the pivot model record from the database. :rtype: int
entailment
def get_relation_count_query(self, query, parent): """ Add the constraints for a relationship count query. :type query: Builder :type parent: Builder :rtype: Builder """ query = super(MorphOneOrMany, self).get_relation_count_query(query, parent) return ...
Add the constraints for a relationship count query. :type query: Builder :type parent: Builder :rtype: Builder
entailment
def add_eager_constraints(self, models): """ Set the constraints for an eager load of the relation. :type models: list """ super(MorphOneOrMany, self).add_eager_constraints(models) self._query.where(self._morph_type, self._morph_class)
Set the constraints for an eager load of the relation. :type models: list
entailment
def save(self, model): """ Attach a model instance to the parent models. :param model: The model instance to attach :type model: Model :rtype: Model """ model.set_attribute(self.get_plain_morph_type(), self._morph_class) return super(MorphOneOrMany, sel...
Attach a model instance to the parent models. :param model: The model instance to attach :type model: Model :rtype: Model
entailment
def find_or_new(self, id, columns=None): """ Find a model by its primary key or return new instance of the related model. :param id: The primary key :type id: mixed :param columns: The columns to retrieve :type columns: list :rtype: Collection or Model ...
Find a model by its primary key or return new instance of the related model. :param id: The primary key :type id: mixed :param columns: The columns to retrieve :type columns: list :rtype: Collection or Model
entailment
def _set_foreign_attributes_for_create(self, model): """ Set the foreign ID and type for creation a related model. """ model.set_attribute(self.get_plain_foreign_key(), self.get_parent_key()) model.set_attribute(self.get_plain_morph_type(), self._morph_class)
Set the foreign ID and type for creation a related model.
entailment
def _parse_connection_name(self, name): """ Parse the connection into a tuple of the name and read / write type :param name: The name of the connection :type name: str :return: A tuple of the name and read / write type :rtype: tuple """ if name is None: ...
Parse the connection into a tuple of the name and read / write type :param name: The name of the connection :type name: str :return: A tuple of the name and read / write type :rtype: tuple
entailment
def purge(self, name=None): """ Disconnect from the given database and remove from local cache :param name: The name of the connection :type name: str :rtype: None """ self.disconnect(name) if name in self._connections: del self._connections...
Disconnect from the given database and remove from local cache :param name: The name of the connection :type name: str :rtype: None
entailment
def no_constraints(cls, callback): """ Runs a callback with constraints disabled on the relation. """ cls._constraints = False results = callback() cls._constraints = True return results
Runs a callback with constraints disabled on the relation.
entailment
def get_keys(self, models, key=None): """ Get all the primary keys for an array of models. :type models: list :type key: str :rtype: list """ return list(set(map(lambda value: value.get_attribute(key) if key else value.get_key(), models)))
Get all the primary keys for an array of models. :type models: list :type key: str :rtype: list
entailment
def add_constraints(self): """ Set the base constraints on the relation query. :rtype: None """ parent_table = self._parent.get_table() self._set_join() if self._constraints: self._query.where('%s.%s' % (parent_table, self._first_key), '=', self._fa...
Set the base constraints on the relation query. :rtype: None
entailment
def get_relation_count_query(self, query, parent): """ Add the constraints for a relationship count query. :type query: Builder :type parent: Builder :rtype: Builder """ parent_table = self._parent.get_table() self._set_join(query) query.select...
Add the constraints for a relationship count query. :type query: Builder :type parent: Builder :rtype: Builder
entailment
def _set_join(self, query=None): """ Set the join clause for the query. """ if not query: query = self._query foreign_key = '%s.%s' % (self._related.get_table(), self._second_key) query.join(self._parent.get_table(), self.get_qualified_parent_key_name(), '='...
Set the join clause for the query.
entailment
def plot_best_worst_fits(assignments_df, data, modality_col='Modality', score='$\log_2 K$'): """Violinplots of the highest and lowest scoring of each modality""" ncols = 2 nrows = len(assignments_df.groupby(modality_col).groups.keys()) fig, axes = plt.subplots(nrows=nrows, ncol...
Violinplots of the highest and lowest scoring of each modality
entailment
def violinplot(x=None, y=None, data=None, bw=0.2, scale='width', inner=None, ax=None, **kwargs): """Wrapper around Seaborn's Violinplot specifically for [0, 1] ranged data What's different: - bw = 0.2: Sets bandwidth to be small and the same between datasets - scale = 'width': Sets the w...
Wrapper around Seaborn's Violinplot specifically for [0, 1] ranged data What's different: - bw = 0.2: Sets bandwidth to be small and the same between datasets - scale = 'width': Sets the width of all violinplots to be the same - inner = None: Don't plot a boxplot or points inside the violinplot
entailment
def bar(self, counts, phenotype_to_color=None, ax=None, percentages=True): """Draw barplots grouped by modality of modality percentage per group Parameters ---------- Returns ------- Raises ------ """ if percentages: counts = 100 ...
Draw barplots grouped by modality of modality percentage per group Parameters ---------- Returns ------- Raises ------
entailment
def event_estimation(self, event, logliks, logsumexps, renamed=''): """Show the values underlying bayesian modality estimations of an event Parameters ---------- Returns ------- Raises ------ """ plotter = _ModelLoglikPlotter() plotter...
Show the values underlying bayesian modality estimations of an event Parameters ---------- Returns ------- Raises ------
entailment
def predict(self, fitted): """Assign the most likely modality given the fitted data Parameters ---------- fitted : pandas.DataFrame or pandas.Series Either a (n_modalities, features) DatFrame or (n_modalities,) Series, either of which will return the best modalit...
Assign the most likely modality given the fitted data Parameters ---------- fitted : pandas.DataFrame or pandas.Series Either a (n_modalities, features) DatFrame or (n_modalities,) Series, either of which will return the best modality for each feature.
entailment
def logliks(self, x): """Calculate log-likelihood of a feature x for each model Converts all values that are exactly 1 or exactly 0 to 0.999 and 0.001 because they are out of range of the beta distribution. Parameters ---------- x : numpy.array-like A single...
Calculate log-likelihood of a feature x for each model Converts all values that are exactly 1 or exactly 0 to 0.999 and 0.001 because they are out of range of the beta distribution. Parameters ---------- x : numpy.array-like A single vector to estimate the log-likel...
entailment
def nice_number_string(number, decimal_places=2): """Convert floats to either integers or a nice looking fraction""" if number == np.round(number): return str(int(number)) elif number < 1 and number > 0: inverse = 1 / number if int(inverse) == np.round(inverse...
Convert floats to either integers or a nice looking fraction
entailment
def violinplot(self, n=1000, **kwargs): """Plot violins of each distribution in the model family Parameters ---------- n : int Number of random variables to generate kwargs : dict or keywords Any keyword arguments to seaborn.violinplot Returns ...
Plot violins of each distribution in the model family Parameters ---------- n : int Number of random variables to generate kwargs : dict or keywords Any keyword arguments to seaborn.violinplot Returns ------- ax : matplotlib.Axes object ...
entailment
def _single_feature_logliks_one_step(self, feature, models): """Get log-likelihood of models at each parameterization for given data Parameters ---------- feature : pandas.Series Percent-based values of a single feature. May contain NAs, but only non-NA values ar...
Get log-likelihood of models at each parameterization for given data Parameters ---------- feature : pandas.Series Percent-based values of a single feature. May contain NAs, but only non-NA values are used. Returns ------- logliks : pandas.DataFr...
entailment
def fit(self, data): """Get the modality assignments of each splicing event in the data Parameters ---------- data : pandas.DataFrame A (n_samples, n_events) dataframe of splicing events' PSI scores. Must be psi scores which range from 0 to 1 Returns ...
Get the modality assignments of each splicing event in the data Parameters ---------- data : pandas.DataFrame A (n_samples, n_events) dataframe of splicing events' PSI scores. Must be psi scores which range from 0 to 1 Returns ------- log2_bayes_...
entailment
def predict(self, log2_bayes_factors, reset_index=False): """Guess the most likely modality for each event For each event that has at least one non-NA value, if no modalilites have logsumexp'd logliks greater than the log Bayes factor threshold, then they are assigned the 'multimodal' m...
Guess the most likely modality for each event For each event that has at least one non-NA value, if no modalilites have logsumexp'd logliks greater than the log Bayes factor threshold, then they are assigned the 'multimodal' modality, because we cannot reject the null hypothesis that th...
entailment
def single_feature_logliks(self, feature): """Calculate log-likelihoods of each modality's parameterization Used for plotting the estimates of a single feature Parameters ---------- featre : pandas.Series A single feature's values. All values must range from 0 to 1....
Calculate log-likelihoods of each modality's parameterization Used for plotting the estimates of a single feature Parameters ---------- featre : pandas.Series A single feature's values. All values must range from 0 to 1. Returns ------- logliks : pa...
entailment
def single_feature_fit(self, feature): """Get the log2 bayes factor of the fit for each modality""" if np.isfinite(feature).sum() == 0: series = pd.Series(index=MODALITY_ORDER) else: logbf_one_param = pd.Series( {k: v.logsumexp_logliks(feature) for ...
Get the log2 bayes factor of the fit for each modality
entailment
def violinplot(self, n=1000, figsize=None, **kwargs): r"""Visualize all modality family members with parameters Use violinplots to visualize distributions of modality family members Parameters ---------- n : int Number of random variables to generate kwargs ...
r"""Visualize all modality family members with parameters Use violinplots to visualize distributions of modality family members Parameters ---------- n : int Number of random variables to generate kwargs : dict or keywords Any keyword arguments to seabor...
entailment
def bin_range_strings(bins, fmt=':g'): """Given a list of bins, make a list of strings of those bin ranges Parameters ---------- bins : list_like List of anything, usually values of bin edges Returns ------- bin_ranges : list List of bin ranges >>> bin_range_strings((0...
Given a list of bins, make a list of strings of those bin ranges Parameters ---------- bins : list_like List of anything, usually values of bin edges Returns ------- bin_ranges : list List of bin ranges >>> bin_range_strings((0, 0.5, 1)) ['0-0.5', '0.5-1']
entailment
def binify(data, bins): """Makes a histogram of each column the provided binsize Parameters ---------- data : pandas.DataFrame A samples x features dataframe. Each feature (column) will be binned into the provided bins bins : iterable Bins you would like to use for this data...
Makes a histogram of each column the provided binsize Parameters ---------- data : pandas.DataFrame A samples x features dataframe. Each feature (column) will be binned into the provided bins bins : iterable Bins you would like to use for this data. Must include the final bin ...
entailment
def kld(p, q): """Kullback-Leiber divergence of two probability distributions pandas dataframes, p and q Parameters ---------- p : pandas.DataFrame An nbins x features DataFrame, or (nbins,) Series q : pandas.DataFrame An nbins x features DataFrame, or (nbins,) Series Retur...
Kullback-Leiber divergence of two probability distributions pandas dataframes, p and q Parameters ---------- p : pandas.DataFrame An nbins x features DataFrame, or (nbins,) Series q : pandas.DataFrame An nbins x features DataFrame, or (nbins,) Series Returns ------- kld...
entailment
def jsd(p, q): """Finds the per-column JSD between dataframes p and q Jensen-Shannon divergence of two probability distrubutions pandas dataframes, p and q. These distributions are usually created by running binify() on the dataframe. Parameters ---------- p : pandas.DataFrame An n...
Finds the per-column JSD between dataframes p and q Jensen-Shannon divergence of two probability distrubutions pandas dataframes, p and q. These distributions are usually created by running binify() on the dataframe. Parameters ---------- p : pandas.DataFrame An nbins x features DataFr...
entailment
def entropy(binned, base=2): """Find the entropy of each column of a dataframe Parameters ---------- binned : pandas.DataFrame A nbins x features DataFrame of probability distributions, where each column sums to 1 base : numeric The log-base of the entropy. Default is 2, so ...
Find the entropy of each column of a dataframe Parameters ---------- binned : pandas.DataFrame A nbins x features DataFrame of probability distributions, where each column sums to 1 base : numeric The log-base of the entropy. Default is 2, so the resulting entropy is in ...
entailment
def binify_and_jsd(df1, df2, bins, pair=None): """Binify and calculate jensen-shannon divergence between two dataframes Parameters ---------- df1, df2 : pandas.DataFrames Dataframes to calculate JSD between columns of. Must have overlapping column names bins : array-like Bin...
Binify and calculate jensen-shannon divergence between two dataframes Parameters ---------- df1, df2 : pandas.DataFrames Dataframes to calculate JSD between columns of. Must have overlapping column names bins : array-like Bins to use for transforming df{1,2} into probability dis...
entailment
def cross_phenotype_jsd(data, groupby, bins, n_iter=100): """Jensen-Shannon divergence of features across phenotypes Parameters ---------- data : pandas.DataFrame A (n_samples, n_features) Dataframe groupby : mappable A samples to phenotypes mapping n_iter : int Number o...
Jensen-Shannon divergence of features across phenotypes Parameters ---------- data : pandas.DataFrame A (n_samples, n_features) Dataframe groupby : mappable A samples to phenotypes mapping n_iter : int Number of bootstrap resampling iterations to perform for the with...
entailment
def jsd_df_to_2d(jsd_df): """Transform a tall JSD dataframe to a square matrix of mean JSDs Parameters ---------- jsd_df : pandas.DataFrame A (n_features, n_phenotypes^2) dataframe of the JSD between each feature between and within phenotypes Returns ------- jsd_2d : pandas...
Transform a tall JSD dataframe to a square matrix of mean JSDs Parameters ---------- jsd_df : pandas.DataFrame A (n_features, n_phenotypes^2) dataframe of the JSD between each feature between and within phenotypes Returns ------- jsd_2d : pandas.DataFrame A (n_phenotype...
entailment
def run(self, callback=None, limit=0): """ Start pcap's loop over the interface, calling the given callback for each packet :param callback: a function receiving (win_pcap, param, header, pkt_data) for each packet intercepted :param limit: how many packets to capture (A value of -1 or 0 ...
Start pcap's loop over the interface, calling the given callback for each packet :param callback: a function receiving (win_pcap, param, header, pkt_data) for each packet intercepted :param limit: how many packets to capture (A value of -1 or 0 is equivalent to infinity)
entailment
def send(self, packet_buffer): """ send a buffer as a packet to the network interface :param packet_buffer: buffer to send (length shouldn't exceed MAX_INT) """ if self._handle is None: raise self.DeviceIsNotOpen() buffer_length = len(packet_buffer) bu...
send a buffer as a packet to the network interface :param packet_buffer: buffer to send (length shouldn't exceed MAX_INT)
entailment
def capture_on(pattern, callback): """ :param pattern: a wildcard pattern to match the description of a network interface to capture packets on :param callback: a function to call with each intercepted packet """ device_name, desc = WinPcapDevices.get_matching_device(pattern) ...
:param pattern: a wildcard pattern to match the description of a network interface to capture packets on :param callback: a function to call with each intercepted packet
entailment
def capture_on_device_name(device_name, callback): """ :param device_name: the name (guid) of a device as provided by WinPcapDevices.list_devices() :param callback: a function to call with each intercepted packet """ with WinPcap(device_name) as capture: capture.run(c...
:param device_name: the name (guid) of a device as provided by WinPcapDevices.list_devices() :param callback: a function to call with each intercepted packet
entailment
def send_packet(self, pattern, packet_buffer, callback=None, limit=10): """ Send a buffer as a packet to a network interface and optionally capture a response :param pattern: a wildcard pattern to match the description of a network interface to capture packets on :param packet_buffer: a ...
Send a buffer as a packet to a network interface and optionally capture a response :param pattern: a wildcard pattern to match the description of a network interface to capture packets on :param packet_buffer: a buffer to send (length shouldn't exceed MAX_INT) :param callback: If not None, a fun...
entailment
def get_next_value( sequence_name='default', initial_value=1, reset_value=None, *, nowait=False, using=None): """ Return the next value for a given sequence. """ # Inner import because models cannot be imported before their application. from .models import Sequence if reset_val...
Return the next value for a given sequence.
entailment
def check(self, final_line_count): """Check the status of all provided data and update the suite.""" if self._lines_seen["version"]: self._process_version_lines() self._process_plan_lines(final_line_count)
Check the status of all provided data and update the suite.
entailment
def _process_version_lines(self): """Process version line rules.""" if len(self._lines_seen["version"]) > 1: self._add_error(_("Multiple version lines appeared.")) elif self._lines_seen["version"][0] != 1: self._add_error(_("The version must be on the first line."))
Process version line rules.
entailment
def _process_plan_lines(self, final_line_count): """Process plan line rules.""" if not self._lines_seen["plan"]: self._add_error(_("Missing a plan.")) return if len(self._lines_seen["plan"]) > 1: self._add_error(_("Only one plan line is permitted per file."))...
Process plan line rules.
entailment
def _plan_on_valid_line(self, at_line, final_line_count): """Check if a plan is on a valid line.""" # Put the common cases first. if at_line == 1 or at_line == final_line_count: return True # The plan may only appear on line 2 if the version is at line 1. after_versi...
Check if a plan is on a valid line.
entailment
def handle_bail(self, bail): """Handle a bail line.""" self._add_error(_("Bailed: {reason}").format(reason=bail.reason))
Handle a bail line.
entailment
def handle_skipping_plan(self, skip_plan): """Handle a plan that contains a SKIP directive.""" skip_line = Result(True, None, skip_plan.directive.text, Directive("SKIP")) self._suite.addTest(Adapter(self._filename, skip_line))
Handle a plan that contains a SKIP directive.
entailment
def _add_error(self, message): """Add an error test to the suite.""" error_line = Result(False, None, message, Directive("")) self._suite.addTest(Adapter(self._filename, error_line))
Add an error test to the suite.
entailment
def format_exception(exception): """Format an exception as diagnostics output. exception is the tuple as expected from sys.exc_info. """ exception_lines = traceback.format_exception(*exception) # The lines returned from format_exception do not strictly contain # one line per element in the list...
Format an exception as diagnostics output. exception is the tuple as expected from sys.exc_info.
entailment
def parse(self, fh): """Generate tap.line.Line objects, given a file-like object `fh`. `fh` may be any object that implements both the iterator and context management protocol (i.e. it can be used in both a "with" statement and a "for...in" statement.) Trailing whitespace and n...
Generate tap.line.Line objects, given a file-like object `fh`. `fh` may be any object that implements both the iterator and context management protocol (i.e. it can be used in both a "with" statement and a "for...in" statement.) Trailing whitespace and newline characters will be automa...
entailment
def parse_line(self, text, fh=None): """Parse a line into whatever TAP category it belongs.""" match = self.ok.match(text) if match: return self._parse_result(True, match, fh) match = self.not_ok.match(text) if match: return self._parse_result(False, matc...
Parse a line into whatever TAP category it belongs.
entailment
def _parse_plan(self, match): """Parse a matching plan line.""" expected_tests = int(match.group("expected")) directive = Directive(match.group("directive")) # Only SKIP directives are allowed in the plan. if directive.text and not directive.skip: return Unknown() ...
Parse a matching plan line.
entailment
def _parse_result(self, ok, match, fh=None): """Parse a matching result line into a result instance.""" peek_match = None try: if fh is not None and self._try_peeking: peek_match = self.yaml_block_start.match(fh.peek()) except StopIteration: pass ...
Parse a matching result line into a result instance.
entailment
def _extract_yaml_block(self, indent, fh): """Extract a raw yaml block from a file handler""" raw_yaml = [] indent_match = re.compile(r"^{}".format(indent)) try: fh.next() while indent_match.match(fh.peek()): raw_yaml.append(fh.next().replace(inden...
Extract a raw yaml block from a file handler
entailment
def yaml_block(self): """Lazy load a yaml_block. If yaml support is not available, there is an error in parsing the yaml block, or no yaml is associated with this result, ``None`` will be returned. :rtype: dict """ if LOAD_YAML and self._yaml_block is no...
Lazy load a yaml_block. If yaml support is not available, there is an error in parsing the yaml block, or no yaml is associated with this result, ``None`` will be returned. :rtype: dict
entailment
def load(self, files): """Load any files found into a suite. Any directories are walked and their files are added as TAP files. :returns: A ``unittest.TestSuite`` instance """ suite = unittest.TestSuite() for filepath in files: if os.path.isdir(filepath): ...
Load any files found into a suite. Any directories are walked and their files are added as TAP files. :returns: A ``unittest.TestSuite`` instance
entailment
def load_suite_from_file(self, filename): """Load a test suite with test lines from the provided TAP file. :returns: A ``unittest.TestSuite`` instance """ suite = unittest.TestSuite() rules = Rules(filename, suite) if not os.path.exists(filename): rules.hand...
Load a test suite with test lines from the provided TAP file. :returns: A ``unittest.TestSuite`` instance
entailment
def load_suite_from_stdin(self): """Load a test suite with test lines from the TAP stream on STDIN. :returns: A ``unittest.TestSuite`` instance """ suite = unittest.TestSuite() rules = Rules("stream", suite) line_generator = self._parser.parse_stdin() return self...
Load a test suite with test lines from the TAP stream on STDIN. :returns: A ``unittest.TestSuite`` instance
entailment
def _load_lines(self, filename, line_generator, suite, rules): """Load a suite with lines produced by the line generator.""" line_counter = 0 for line in line_generator: line_counter += 1 if line.category in self.ignored_lines: continue if li...
Load a suite with lines produced by the line generator.
entailment
def _track(self, class_name): """Keep track of which test cases have executed.""" if self._test_cases.get(class_name) is None: if self.streaming and self.header: self._write_test_case_header(class_name, self.stream) self._test_cases[class_name] = [] i...
Keep track of which test cases have executed.
entailment
def set_plan(self, total): """Notify the tracker how many total tests there will be.""" self.plan = total if self.streaming: # This will only write the plan if we haven't written it # already but we want to check if we already wrote a # test out (in which case...
Notify the tracker how many total tests there will be.
entailment
def generate_tap_reports(self): """Generate TAP reports. The results are either combined into a single output file or the output file name is generated from the test case. """ # We're streaming but set_plan wasn't called, so we can only # know the plan now (at the end). ...
Generate TAP reports. The results are either combined into a single output file or the output file name is generated from the test case.
entailment
def _write_plan(self, stream): """Write the plan line to the stream. If we have a plan and have not yet written it out, write it to the given stream. """ if self.plan is not None: if not self._plan_written: print("1..{0}".format(self.plan), file=strea...
Write the plan line to the stream. If we have a plan and have not yet written it out, write it to the given stream.
entailment
def _get_tap_file_path(self, test_case): """Get the TAP output file path for the test case.""" sanitized_test_case = test_case.translate(self._sanitized_table) tap_file = sanitized_test_case + ".tap" if self.outdir: return os.path.join(self.outdir, tap_file) return ta...
Get the TAP output file path for the test case.
entailment
def main(argv=sys.argv, stream=sys.stderr): """Entry point for ``tappy`` command.""" args = parse_args(argv) suite = build_suite(args) runner = unittest.TextTestRunner(verbosity=args.verbose, stream=stream) result = runner.run(suite) return get_status(result)
Entry point for ``tappy`` command.
entailment
def build_suite(args): """Build a test suite by loading TAP files or a TAP stream.""" loader = Loader() if len(args.files) == 0 or args.files[0] == "-": suite = loader.load_suite_from_stdin() else: suite = loader.load(args.files) return suite
Build a test suite by loading TAP files or a TAP stream.
entailment
def addFailure(self, result): """Add a failure to the result.""" result.addFailure(self, (Exception, Exception(), None)) # Since TAP will not provide assertion data, clean up the assertion # section so it is not so spaced out. test, err = result.failures[-1] result.failur...
Add a failure to the result.
entailment
def mptt_before_insert(mapper, connection, instance): """ Based on example https://bitbucket.org/zzzeek/sqlalchemy/src/73095b353124/examples/nested_sets/nested_sets.py?at=master """ table = _get_tree_table(mapper) db_pk = instance.get_pk_column() table_pk = getattr(table.c, db_pk.name) if i...
Based on example https://bitbucket.org/zzzeek/sqlalchemy/src/73095b353124/examples/nested_sets/nested_sets.py?at=master
entailment
def mptt_before_update(mapper, connection, instance): """ Based on this example: http://stackoverflow.com/questions/889527/move-node-in-nested-set """ node_id = getattr(instance, instance.get_pk_name()) table = _get_tree_table(mapper) db_pk = instance.get_pk_column() default_level = inst...
Based on this example: http://stackoverflow.com/questions/889527/move-node-in-nested-set
entailment
def after_flush_postexec(self, session, context): """ Event listener to recursively expire `left` and `right` attributes the parents of all modified instances part of this flush. """ instances = self.instances[session] while instances: instance = instances.pop...
Event listener to recursively expire `left` and `right` attributes the parents of all modified instances part of this flush.
entailment
def is_ancestor_of(self, other, inclusive=False): """ class or instance level method which returns True if self is ancestor (closer to root) of other else False. Optional flag `inclusive` on whether or not to treat self as ancestor of self. For example see: * :mod:`sqlalchemy_m...
class or instance level method which returns True if self is ancestor (closer to root) of other else False. Optional flag `inclusive` on whether or not to treat self as ancestor of self. For example see: * :mod:`sqlalchemy_mptt.tests.cases.integrity.test_hierarchy_structure`
entailment
def move_inside(self, parent_id): """ Moving one node of tree inside another For example see: * :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_inside_function` * :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_inside_to_the_same_parent_function` """ # noqa ...
Moving one node of tree inside another For example see: * :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_inside_function` * :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_inside_to_the_same_parent_function`
entailment
def move_after(self, node_id): """ Moving one node of tree after another For example see :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_after_function` """ # noqa session = Session.object_session(self) self.parent_id = self.parent_id self.mptt_move_after = node_i...
Moving one node of tree after another For example see :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_after_function`
entailment
def move_before(self, node_id): """ Moving one node of tree before another For example see: * :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_before_function` * :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_before_to_other_tree` * :mod:`sqlalchemy_mptt.tests.cases...
Moving one node of tree before another For example see: * :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_before_function` * :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_before_to_other_tree` * :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_before_to_top_level`
entailment
def leftsibling_in_level(self): """ Node to the left of the current node at the same level For example see :mod:`sqlalchemy_mptt.tests.cases.get_tree.test_leftsibling_in_level` """ # noqa table = _get_tree_table(self.__mapper__) session = Session.object_session(self) ...
Node to the left of the current node at the same level For example see :mod:`sqlalchemy_mptt.tests.cases.get_tree.test_leftsibling_in_level`
entailment
def _node_to_dict(cls, node, json, json_fields): """ Helper method for ``get_tree``. """ if json: pk_name = node.get_pk_name() # jqTree or jsTree format result = {'id': getattr(node, pk_name), 'label': node.__repr__()} if json_fields: ...
Helper method for ``get_tree``.
entailment
def get_tree(cls, session=None, json=False, json_fields=None, query=None): """ This method generate tree of current node table in dict or json format. You can make custom query with attribute ``query``. By default it return all nodes in table. Args: session (:mod:`sqlalchemy...
This method generate tree of current node table in dict or json format. You can make custom query with attribute ``query``. By default it return all nodes in table. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session Kwargs: json (bool): if...
entailment
def drilldown_tree(self, session=None, json=False, json_fields=None): """ This method generate a branch from a tree, begining with current node. For example: node7.drilldown_tree() .. code:: level Nested sets example 1 ...
This method generate a branch from a tree, begining with current node. For example: node7.drilldown_tree() .. code:: level Nested sets example 1 1(1)22 --------------------- ___________...
entailment
def path_to_root(self, session=None, order=desc): """Generate path from a leaf or intermediate node to the root. For example: node11.path_to_root() .. code:: level Nested sets example --------------------------------...
Generate path from a leaf or intermediate node to the root. For example: node11.path_to_root() .. code:: level Nested sets example ----------------------------------------- 1 | 1(1)22 ...
entailment
def rebuild_tree(cls, session, tree_id): """ This method rebuid tree. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session tree_id (int or str): id of tree Example: * :mod:`sqlalchemy_mptt.tests.cases.get_tree.test_rebuild` """ ...
This method rebuid tree. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session tree_id (int or str): id of tree Example: * :mod:`sqlalchemy_mptt.tests.cases.get_tree.test_rebuild`
entailment
def rebuild(cls, session, tree_id=None): """ This function rebuid tree. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session Kwargs: tree_id (int or str): id of tree, default None Example: * :mod:`sqlalchemy_mptt.tests.TestTree.tes...
This function rebuid tree. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session Kwargs: tree_id (int or str): id of tree, default None Example: * :mod:`sqlalchemy_mptt.tests.TestTree.test_rebuild`
entailment
def qx(mt, x): """ qx: Returns the probability that a life aged x dies before 1 year With the convention: the true probability is qx/1000 Args: mt: the mortality table x: the age as integer number. """ if x < len(mt.qx): return mt.qx[x] else: return 0
qx: Returns the probability that a life aged x dies before 1 year With the convention: the true probability is qx/1000 Args: mt: the mortality table x: the age as integer number.
entailment
def lx(mt, x): """ lx : Returns the number of survivors at begining of age x """ if x < len(mt.lx): return mt.lx[x] else: return 0
lx : Returns the number of survivors at begining of age x
entailment
def dx(mt, x): """ Returns the number of dying at begining of age x """ end_x_val = mt.lx.index(0) if x < end_x_val: return mt.lx[x] - mt.lx[x + 1] else: return 0.0
Returns the number of dying at begining of age x
entailment
def tpx(mt, x, t): """ tpx : Returns the probability that x will survive within t years """ """ npx : Returns n years survival probability at age x """ return mt.lx[x + t] / mt.lx[x]
tpx : Returns the probability that x will survive within t years
entailment
def tqx(mt, x, t): """ nqx : Returns the probability to die within n years at age x """ return (mt.lx[x] - mt.lx[x + t]) / mt.lx[x]
nqx : Returns the probability to die within n years at age x
entailment
def tqxn(mt, x, n, t): """ n/qx : Probability to die in n years being alive at age x. Probability that x survives n year, and then dies in th subsequent t years """ return tpx(mt, x, t) * qx(mt, x + n)
n/qx : Probability to die in n years being alive at age x. Probability that x survives n year, and then dies in th subsequent t years
entailment
def ex(mt, x): """ ex : Returns the curtate expectation of life. Life expectancy """ sum1 = 0 for j in mt.lx[x + 1:-1]: sum1 += j #print sum1 try: return sum1 / mt.lx[x] + 0.5 except: return 0
ex : Returns the curtate expectation of life. Life expectancy
entailment
def Sx(mt, x): """ Return the Sx """ n = len(mt.Nx) sum1 = 0 for j in range(x, n): k = mt.Nx[j] sum1 += k return sum1
Return the Sx
entailment
def Cx(mt, x): """ Return the Cx """ return ((1 / (1 + mt.i)) ** (x + 1)) * mt.dx[x] * ((1 + mt.i) ** 0.5)
Return the Cx
entailment