Search is not available for this dataset
text
stringlengths
75
104k
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...
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...
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)
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...
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: ...
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...
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: ...
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....
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:...
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...
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()
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 ...
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)
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...
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 ...
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)
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: ...
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...
def no_constraints(cls, callback): """ Runs a callback with constraints disabled on the relation. """ cls._constraints = False results = callback() cls._constraints = True return results
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)))
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...
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...
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(), '='...
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...
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...
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 ...
def event_estimation(self, event, logliks, logsumexps, renamed=''): """Show the values underlying bayesian modality estimations of an event Parameters ---------- Returns ------- Raises ------ """ plotter = _ModelLoglikPlotter() plotter...
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...
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...
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...
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 ...
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...
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 ...
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...
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....
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 ...
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 ...
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...
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...
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...
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...
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 ...
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...
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...
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...
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 ...
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...
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) ...
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...
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 ...
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...
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)
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."))
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."))...
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...
def handle_bail(self, bail): """Handle a bail line.""" self._add_error(_("Bailed: {reason}").format(reason=bail.reason))
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))
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))
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...
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...
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...
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() ...
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 ...
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...
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...
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): ...
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...
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...
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...
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...
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...
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). ...
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...
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...
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)
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
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...
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...
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...
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...
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...
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 ...
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...
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...
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) ...
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: ...
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...
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 ...
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 --------------------------------...
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` """ ...
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...
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
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
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
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]
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]
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)
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
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
def Cx(mt, x): """ Return the Cx """ return ((1 / (1 + mt.i)) ** (x + 1)) * mt.dx[x] * ((1 + mt.i) ** 0.5)