Instruction:
Write a Python 3 script to
execute the reset command.

Response:
def execute(self, i, o):
        """
        Executes the command.

        :type i: cleo.inputs.input.Input
        :type o: cleo.outputs.output.Output
        """
        super(ResetCommand, self).execute(i, o)

        dialog = self.get_helper('dialog')
        confirm = dialog.ask_confirmation(
            o,
            '<question>Are you sure you want to reset all of the migrations?</question> ',
            False
        )
        if not confirm:
            return

        database = i.get_option('database')
        repository = DatabaseMigrationRepository(self._resolver, 'migrations')

        migrator = Migrator(repository, self._resolver)

        self._prepare_database(migrator, database, i, o)

        pretend = bool(i.get_option('pretend'))

        path = i.get_option('path')

        if path is None:
            path = self._get_migration_path()

        while True:
            count = migrator.rollback(path, pretend)

            for note in migrator.get_notes():
                o.writeln(note)

            if count == 0:
                break


Instruction:
Make a summary of the following Python 3 code
def get_relation_count_query(self, query, parent):
        query = super(MorphToMany, self).get_relation_count_query(query, parent)

        return query.where('%s.%s' % (self._table, self._morph_type), self._morph_class)

Response: Add the constraints for a relationship count query.


Instruction:
Write a Python 3 function that can
add constraints for an eager load of the relation.

Response:
def add_eager_constraints(self, models):
        """
        Set the constraints for an eager load of the relation.

        :type models: list
        """
        super(MorphToMany, self).add_eager_constraints(models)

        self._query.where('%s.%s' % (self._table, self._morph_type), self._morph_class)


Instruction:
Here you have a function in Python 3, explain what it does
def _create_attach_record(self, id, timed):
        record = super(MorphToMany, self)._create_attach_record(id, timed)

        record[self._morph_type] = self._morph_class

        return record

Response: Create a new pivot attachement record.


Instruction:
Implement a Python 3 function for
creating a new query builder for the pivot table.

Response:
def _new_pivot_query(self):
        """
        Create a new query builder for the pivot table.

        :rtype: eloquent.orm.Builder
        """
        query = super(MorphToMany, self)._new_pivot_query()

        return query.where(self._morph_type, self._morph_class)


Instruction:
Write a Python 3 function that can
create a new pivot model instance.

Response:
def new_pivot(self, attributes=None, exists=False):
        """
        Create a new pivot model instance.
        """
        from .morph_pivot import MorphPivot

        pivot = MorphPivot(self._parent, attributes, self._table, exists)

        pivot.set_pivot_keys(self._foreign_key, self._other_key)\
            .set_morph_type(self._morph_type)\
            .set_morph_class(self._morph_class)

        return pivot


Instruction:
Write a Python 3 function for
executing the install command.

Response:
def execute(self, i, o):
        """
        Executes the command.

        :type i: cleo.inputs.input.Input
        :type o: cleo.outputs.output.Output
        """
        super(InstallCommand, self).execute(i, o)

        database = i.get_option('database')
        repository = DatabaseMigrationRepository(self._resolver, 'migrations')

        repository.set_source(database)
        repository.create_repository()

        o.writeln('<info>Migration table created successfully</info>')


Instruction:
Given the following Python 3 function, write the documentation
def process_insert_get_id(self, query, sql, values, sequence=None):
        if not query.get_connection().transaction_level():
            with query.get_connection().transaction():
                query.get_connection().insert(sql, values)

                cursor = query.get_connection().get_cursor()
                if hasattr(cursor, 'lastrowid'):
                    id = cursor.lastrowid
                else:
                    id = query.get_connection().statement('SELECT LAST_INSERT_ID()')
        else:
            query.get_connection().insert(sql, values)

            cursor = query.get_connection().get_cursor()
            if hasattr(cursor, 'lastrowid'):
                id = cursor.lastrowid
            else:
                id = query.get_connection().statement('SELECT LAST_INSERT_ID()')

        if isinstance(id, int):
            return id

        if str(id).isdigit():
            return int(id)

        return id

Response: Process an insert get ID query.


Instruction:
Make a summary of the following Python 3 code
def chunk(self, count):
        page = 1
        results = self.for_page(page, count).get()

        while results:
            yield results

            page += 1

            results = self.for_page(page, count).get()

Response:
Returns a list of count items from the query
            API.


Instruction:
Implement a function in Python 3 to
get a list with the values of a given column and key.

Response:
def lists(self, column, key=None):
        """
        Get a list with the values of a given column

        :param column: The column to get the values for
        :type column: str

        :param key: The key
        :type key: str

        :return: The list of values
        :rtype: list or dict
        """
        results = self._query.lists(column, key)

        if self._model.has_get_mutator(column):
            if isinstance(results, dict):
                for key, value in results.items():
                    fill = {column: value}

                    results[key] = self._model.new_from_builder(fill).column
            else:
                for i, value in enumerate(results):
                    fill = {column: value}

                    results[i] = self._model.new_from_builder(fill).column

        return results


Instruction:
Can you generate a brief explanation for the following Python 3 code
def increment(self, column, amount=1, extras=None):
        extras = self._add_updated_at_column(extras)

        return self._query.increment(column, amount, extras)

Response: Increment a column s value by a given amount


Instruction:
Implement a function in Python 3 to
get the hydrated models without eager loading.

Response:
def get_models(self, columns=None):
        """
        Get the hydrated models without eager loading.

        :param columns: The columns to get
        :type columns: list

        :return: A list of models
        :rtype: list
        """
        results = self._query.get(columns)

        connection = self._model.get_connection_name()

        return self._model.hydrate(results, connection).all()


Instruction:
Here you have a function in Python 3, explain what it does
def _load_relation(self, models, name, constraints):
        relation = self.get_relation(name)

        relation.add_eager_constraints(models)

        if callable(constraints):
            constraints(relation)
        else:
            relation.merge_query(constraints)

        models = relation.init_relation(models, name)

        results = relation.get_eager()

        return relation.match(models, results, name)

Response: Load the relationship on a set of models.


Instruction:
Create a Python 3 function for
adding nested relationship count conditions to the query.

Response:
def _has_nested(self, relations, operator='>=', count=1, boolean='and', extra=None):
        """
        Add nested relationship count conditions to the query.

        :param relations: nested relations
        :type relations: str

        :param operator: The operator
        :type operator: str

        :param count: The count
        :type count: int

        :param boolean: The boolean value
        :type boolean: str

        :param extra: The extra query
        :type extra: Builder or callable

        :rtype: Builder
        """
        relations = relations.split('.')

        def closure(q):
            if len(relations) > 1:
                q.where_has(relations.pop(0), closure)
            else:
                q.has(relations.pop(0), operator, count, boolean, extra)

        return self.where_has(relations.pop(0), closure)


Instruction:
How would you code a function in Python 3 to
add a relationship count to the query.

Response:
def doesnt_have(self, relation, boolean='and', extra=None):
        """
        Add a relationship count to the query.

        :param relation: The relation to count
        :type relation: str

        :param boolean: The boolean value
        :type boolean: str

        :param extra: The extra query
        :type extra: Builder or callable

        :rtype: Builder
        """
        return self.has(relation, '<', 1, boolean, extra)


Instruction:
Write a Python 3 script for
adding a relationship count condition to the query with where clauses.

Response:
def where_has(self, relation, extra, operator='>=', count=1):
        """
        Add a relationship count condition to the query with where clauses.

        :param relation: The relation to count
        :type relation: str

        :param extra: The extra query
        :type extra: Builder or callable

        :param operator: The operator
        :type operator: str

        :param count: The count
        :type count: int

        :rtype: Builder
        """
        return self.has(relation, operator, count, 'and', extra)


Instruction:
Can you tell what is the following Python 3 function doing
def or_has(self, relation, operator='>=', count=1):
        return self.has(relation, operator, count, 'or')

Response: Add a relationship count condition to the query with an or.


Instruction:
Create a Python 3 function for
adding a relationship count condition to the query with where clauses and an or.

Response:
def or_where_has(self, relation, extra, operator='>=', count=1):
        """
        Add a relationship count condition to the query with where clauses and an "or".

        :param relation: The relation to count
        :type relation: str

        :param extra: The extra query
        :type extra: Builder or callable

        :param operator: The operator
        :type operator: str

        :param count: The count
        :type count: int

        :rtype: Builder
        """
        return self.has(relation, operator, count, 'or', extra)


Instruction:
Can you generate the documentation for the following Python 3 function
def _merge_wheres_to_has(self, has_query, relation):
        relation_query = relation.get_base_query()

        has_query.merge_wheres(relation_query.wheres, relation_query.get_bindings())

        self._query.merge_bindings(has_query.get_query())

Response: Merge the wheres from the relation query to a has query.


Instruction:
How would you implement a function in Python 3 that
gets the has relation base query

Response:
def _get_has_relation_query(self, relation):
        """
        Get the "has" relation base query

        :type relation: str

        :rtype: Builder
        """
        from .relations import Relation

        return Relation.no_constraints(
            lambda: getattr(self.get_model(), relation)()
        )


Instruction:
Make a summary of the following Python 3 code
def with_(self, *relations):
        if not relations:
            return self

        eagers = self._parse_relations(list(relations))

        self._eager_load.update(eagers)

        return self

Response: Sets the relationships that should be eager loaded.


Instruction:
Can you generate the documentation for the following Python 3 function
def _parse_relations(self, relations):
        results = {}

        for relation in relations:
            if isinstance(relation, dict):
                name = list(relation.keys())[0]
                constraints = relation[name]
            else:
                name = relation
                constraints = self.__class__(self.get_query().new_query())

            results = self._parse_nested(name, results)

            results[name] = constraints

        return results

Response: Parse a list of relations into individual related objects.


Instruction:
Given the following Python 3 function, write the documentation
def _parse_nested(self, name, results):
        progress = []

        for segment in name.split('.'):
            progress.append(segment)

            last = '.'.join(progress)
            if last not in results:
                results[last] = self.__class__(self.get_query().new_query())

        return results

Response: Parse the nested relationship in a relation.


Instruction:
Write a Python 3 function that can
call the given model scope.

Response:
def _call_scope(self, scope, *args, **kwargs):
        """
        Call the given model scope.

        :param scope: The scope to call
        :type scope: str
        """
        result = getattr(self._model, scope)(self, *args, **kwargs)

        return result or self


Instruction:
How would you implement a function in Python 3 that
runs an up migration instance.

Response:
def _run_up(self, path, migration_file, batch, pretend=False):
        """
        Run "up" a migration instance.

        :type migration_file: str

        :type batch: int

        :type pretend: bool
        """
        migration = self._resolve(path, migration_file)

        if pretend:
            return self._pretend_to_run(migration, 'up')

        migration.up()

        self._repository.log(migration_file, batch)

        self._note('<info>✓ Migrated</info> %s' % migration_file)


Instruction:
Can you tell what is the following Python 3 function doing
def _run_down(self, path, migration, pretend=False):
        migration_file = migration['migration']

        instance = self._resolve(path, migration_file)

        if pretend:
            return self._pretend_to_run(instance, 'down')

        instance.down()

        self._repository.delete(migration)

        self._note('<info>✓ Rolled back</info> %s' % migration_file)

Response: Run down a migration instance.


Instruction:
Write a Python 3 function for
pretending to run the migration.

Response:
def _pretend_to_run(self, migration, method):
        """
        Pretend to run the migration.

        :param migration: The migration
        :type migration: eloquent.migrations.migration.Migration

        :param method: The method to execute
        :type method: str
        """
        for query in self._get_queries(migration, method):
            name = migration.__class__.__name__

            self._note('<info>%s:</info> <comment>%s</comment>' % (name, query))


Instruction:
Create a Python 3 function for
getting all of the queries that would be run for a migration.

Response:
def _get_queries(self, migration, method):
        """
        Get all of the queries that would be run for a migration.

        :param migration: The migration
        :type migration: eloquent.migrations.migration.Migration

        :param method: The method to execute
        :type method: str

        :rtype: list
        """
        connection = migration.get_connection()

        db = self.resolve_connection(connection)

        logger = logging.getLogger('eloquent.connection.queries')
        level = logger.level
        logger.setLevel(logging.DEBUG)
        handler = MigratorHandler()
        handler.setLevel(logging.DEBUG)
        logger.addHandler(handler)

        db.pretend(lambda _: getattr(migration, method)())

        logger.removeHandler(handler)
        logger.setLevel(level)

        return handler.queries


Instruction:
Explain what the following Python 3 code does
def _resolve(self, path, migration_file):
        variables = {}

        name = '_'.join(migration_file.split('_')[4:])
        migration_file = os.path.join(path, '%s.py' % migration_file)

        with open(migration_file) as fh:
            exec(fh.read(), {}, variables)

        klass = variables[inflection.camelize(name)]

        instance = klass()
        instance.set_schema_builder(self.get_repository().get_connection().get_schema_builder())

        return instance

Response: Resolve a migration instance from a file.


Instruction:
Can you write a function in Python 3 where it
gets the ALTER TABLE SQL statement for the given table diff.

Response:
def get_alter_table_sql(self, diff):
        """
        Get the ALTER TABLE SQL statement

        :param diff: The table diff
        :type diff: eloquent.dbal.table_diff.TableDiff

        :rtype: list
        """
        column_sql = []
        query_parts = []

        if diff.new_name is not False:
            query_parts.append('RENAME TO %s' % diff.new_name)

        # Added columns?

        # Removed columns?

        for column_diff in diff.changed_columns.values():
            column = column_diff.column
            column_dict = column.to_dict()

            # Don't propagate default value changes for unsupported column types.
            if column_diff.has_changed('default') \
                    and len(column_diff.changed_properties) == 1 \
                    and (column_dict['type'] == 'text' or column_dict['type'] == 'blob'):
                continue

            query_parts.append('CHANGE %s %s'
                               % (column_diff.get_old_column_name(),
                                  self.get_column_declaration_sql(column.get_name(), column_dict)))

        for old_column_name, column in diff.renamed_columns.items():
            column_dict = column.to_dict()
            query_parts.append('CHANGE %s %s'
                               % (self.quote(old_column_name),
                                  self.get_column_declaration_sql(self.quote(column.get_name()), column_dict)))

        sql = []

        if len(query_parts) > 0:
            sql.append('ALTER TABLE %s %s' % (diff.name, ', '.join(query_parts)))

        return sql


Instruction:
Can you create a Python 3 function that
returns the difference between the tables table1 and table2.

Response:
def diff_table(self, table1, table2):
        """
        Returns the difference between the tables table1 and table2.

        :type table1: Table
        :type table2: Table

        :rtype: TableDiff
        """
        changes = 0
        table_differences = TableDiff(table1.get_name())
        table_differences.from_table = table1

        table1_columns = table1.get_columns()
        table2_columns = table2.get_columns()

        # See if all the fields in table1 exist in table2
        for column_name, column in table2_columns.items():
            if not table1.has_column(column_name):
                table_differences.added_columns[column_name] = column
                changes += 1

        # See if there are any removed fields in table2
        for column_name, column in table1_columns.items():
            if not table2.has_column(column_name):
                table_differences.removed_columns[column_name] = column
                changes += 1
                continue

            # See if column has changed properties in table2
            changed_properties = self.diff_column(column, table2.get_column(column_name))

            if changed_properties:
                column_diff = ColumnDiff(column.get_name(),
                                         table2.get_column(column_name),
                                         changed_properties)
                column_diff.from_column = column
                table_differences.changed_columns[column.get_name()] = column_diff
                changes += 1

        self.detect_column_renamings(table_differences)

        # table1_indexes = table1.get_indexes()
        # table2_indexes = table2.get_indexes()
        #
        # # See if all the fields in table1 exist in table2
        # for index_name, index in table2_indexes.items():
        #     if (index.is_primary() and table1.has_primary_key()) or table1.has_index(index_name):
        #         continue
        #
        #     table_differences.added_indexes[index_name] = index
        #     changes += 1
        #
        # # See if there are any removed fields in table2
        # for index_name, index in table1_indexes.items():
        #     if (index.is_primary() and not table2.has_primary_key())\
        #             or (not index.is_primary() and not table2.has_index(index_name)):
        #         table_differences.removed_indexes[index_name] = index
        #         changes += 1
        #         continue
        #
        #     if index.is_primary():
        #         table2_index = table2.get_primary_key()
        #     else:
        #         table2_index = table2.get_index(index_name)
        #
        #     if self.diff_index(index, table2_index):
        #         table_differences.changed_indexes[index_name] = index
        #         changes += 1
        #
        # self.detect_index_renamings(table_differences)
        #
        # from_fkeys = table1.get_foreign_keys()
        # to_fkeys = table2.get_foreign_keys()
        #
        # for key1, constraint1 in from_fkeys.items():
        #     for key2, constraint2 in to_fkeys.items():
        #         if self.diff_foreign_key(constraint1, constraint2) is False:
        #             del from_fkeys[key1]
        #             del to_fkeys[key2]
        #         else:
        #             if constraint1.get_name().lower() == constraint2.get_name().lower():
        #                 table_differences.changed_foreign_keys.append(constraint2)
        #                 changes += 1
        #                 del from_fkeys[key1]
        #                 del to_fkeys[key2]
        #
        # for constraint1 in from_fkeys.values():
        #     table_differences.removed_foreign_keys.append(constraint1)
        #     changes += 1
        #
        # for constraint2 in to_fkeys.values():
        #     table_differences.added_foreign_keys.append(constraint2)
        #     changes += 1

        if changes:
            return table_differences

        return False


Instruction:
Can you write a function in Python 3 where it
detects if any of the columns that only changed their names.

Response:
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 removed_column in table_differences.removed_columns.values():
                if len(self.diff_column(added_column, removed_column)) == 0:
                    if added_column.get_name() not in rename_candidates:
                        rename_candidates[added_column.get_name()] = []

                    rename_candidates[added_column.get_name()] = (removed_column, added_column, added_column_name)

        for candidate_columns in rename_candidates.values():
            if len(candidate_columns) == 1:
                removed_column, added_column, _ = candidate_columns[0]
                removed_column_name = removed_column.get_name().lower()
                added_column_name = added_column.get_name().lower()

                if removed_column_name not in table_differences.renamed_columns:
                    table_differences.renamed_columns[removed_column_name] = added_column
                    del table_differences.added_columns[added_column_name]
                    del table_differences.removed_columns[removed_column_name]


Instruction:
Write a Python 3 script to
return the difference between column1 and column2.

Response:
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.to_dict()

        changed_properties = []

        for prop in ['type', 'notnull', 'unsigned', 'autoincrement']:
            if properties1[prop] != properties2[prop]:
                changed_properties.append(prop)

        if properties1['default'] != properties2['default']\
                or (properties1['default'] is None and properties2['default'] is not None)\
                or (properties2['default'] is None and properties1['default'] is not None):
            changed_properties.append('default')

        if properties1['type'] == 'string' and properties1['type'] != 'guid'\
                or properties1['type'] in ['binary', 'blob']:
            length1 = properties1['length'] or 255
            length2 = properties2['length'] or 255

            if length1 != length2:
                changed_properties.append('length')

            if properties1['fixed'] != properties2['fixed']:
                changed_properties.append('fixed')
        elif properties1['type'] in ['decimal', 'float', 'double precision']:
            precision1 = properties1['precision'] or 10
            precision2 = properties2['precision'] or 10

            if precision1 != precision2:
                changed_properties.append('precision')

            if properties1['scale'] != properties2['scale']:
                changed_properties.append('scale')

        return list(set(changed_properties))


Instruction:
Can you create a Python 3 function that
executes the command. :type i: cleo.inputs.input.Input :type o: cleo.outputs.output.Output

Response:
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)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def call(self, name, options=None, o=None):
        if options is None:
            options = []

        command = self.get_application().find(name)

        options = [('command', command.get_name())] + options

        return command.run(ListInput(options), o)

Response:
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


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _get_config(self, i):
        variables = {}
        if not i.get_option('config'):
            raise Exception('The --config|-c option is missing.')

        with open(i.get_option('config')) as fh:
            exec(fh.read(), {}, variables)

        return variables['DATABASES']

Response:
Get the config.

        :type i: cleo.inputs.input.Input

        :rtype: dict


Instruction:
Make a summary of the following Python 3 code
def associate(self, model):
        self._parent.set_attribute(self._foreign_key, model.get_key())
        self._parent.set_attribute(self._morph_type, model.get_morph_class())

        return self._parent.set_relation(self._relation, model)

Response: Associate the given model instance with the given parent.


Instruction:
Explain what the following Python 3 code does
def _create_model_by_type(self, type):
        klass = None
        for cls in eloquent.orm.model.Model.__subclasses__():
            morph_class = cls.__morph_class__ or cls.__name__
            if morph_class == type:
                klass = cls
                break

        return klass()

Response: Create a new model instance by type.


Instruction:
How would you code a function in Python 3 to
get the column listing for a given table.

Response:
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._connection.get_table_prefix() + table

        results = self._connection.select(sql, [database, table])

        return self._connection.get_post_processor().process_column_listing(results)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _populate_stub(self, name, stub, table):
        stub = stub.replace('DummyClass', self._get_class_name(name))

        if table is not None:
            stub = stub.replace('dummy_table', table)

        return stub

Response: Populate the placeholders in the migration stub.


Instruction:
Implement a function in Python 3 to
set the keys for a save update query.

Response:
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._morph_class)

        return super(MorphPivot, self)._set_keys_for_save_query(query)


Instruction:
Make a summary of the following Python 3 code
def delete(self):
        query = self._get_delete_query()

        query.where(self._morph_type, self._morph_class)

        return query.delete()

Response: Delete the pivot model record from the database.


Instruction:
Implement a Python 3 function for
adding the constraints for a relationship count query.

Response:
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 query.where(self._morph_type, self._morph_class)


Instruction:
Write a Python 3 function for
adding constraints for an eager load of the relation.

Response:
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)


Instruction:
Write a Python 3 function that can
save a new instance of the current record.

Response:
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, self).save(model)


Instruction:
Can you create a Python 3 function that
finds a model by its primary key or return a new instance of the related model.

Response:
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
        """
        if columns is None:
            columns = ['*']

        instance = self.find(id, columns)

        if instance is None:
            instance = self._related.new_instance()
            self._set_foreign_attributes_for_create(instance)

        return instance


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _set_foreign_attributes_for_create(self, model):
        model.set_attribute(self.get_plain_foreign_key(), self.get_parent_key())

        model.set_attribute(self.get_plain_morph_type(), self._morph_class)

Response: Set the foreign ID and type for creation a related model.


Instruction:
Can you tell what is the following Python 3 function doing
def _parse_connection_name(self, name):
        if name is None:
            name = self.get_default_connection()

        if name.endswith(('::read', '::write')):
            return name.split('::', 1)

        return name, None

Response: Parse the connection name into a tuple of the name read and write types.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def purge(self, name=None):
        self.disconnect(name)

        if name in self._connections:
            del self._connections[name]

Response: Disconnect from the given database and remove from local cache.


Instruction:
Here you have a function in Python 3, explain what it does
def no_constraints(cls, callback):
        cls._constraints = False

        results = callback()

        cls._constraints = True

        return results

Response: Runs a callback with constraints disabled on the relation.


Instruction:
Implement a function in Python 3 to
get all the primary keys for an array of models.

Response:
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)))


Instruction:
Make a summary of the following Python 3 code
def add_constraints(self):
        parent_table = self._parent.get_table()

        self._set_join()

        if self._constraints:
            self._query.where('%s.%s' % (parent_table, self._first_key), '=', self._far_parent.get_key())

Response: Add constraints on the relation query.


Instruction:
Make a summary of the following Python 3 code
def get_relation_count_query(self, query, parent):
        parent_table = self._parent.get_table()

        self._set_join(query)

        query.select(QueryExpression('COUNT(*)'))

        key = self.wrap('%s.%s' % (parent_table, self._first_key))

        return query.where(self.get_has_compare_key(), '=', QueryExpression(key))

Response: Add the constraints for a relationship count query.


Instruction:
Write a Python 3 function for
setting the join clause for the query.

Response:
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(), '=', foreign_key)


Instruction:
Write a Python 3 function that can
plot the highest and lowest scoring of each modality.

Response:
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, ncols=ncols,
                             figsize=(nrows*4, ncols*6))

    axes_iter = axes.flat

    fits = 'Highest', 'Lowest'

    for modality, df in assignments_df.groupby(modality_col):
        df = df.sort_values(score)

        color = MODALITY_TO_COLOR[modality]

        for fit in fits:
            if fit == 'Highest':
                ids = df['Feature ID'][-10:]
            else:
                ids = df['Feature ID'][:10]
            fit_psi = data[ids]
            tidy_fit_psi = fit_psi.stack().reset_index()
            tidy_fit_psi = tidy_fit_psi.rename(columns={'level_0': 'Sample ID',
                                                        'level_1':
                                                            'Feature ID',
                                                        0: '$\Psi$'})
            if tidy_fit_psi.empty:
                continue
            ax = six.next(axes_iter)
            violinplot(x='Feature ID', y='$\Psi$', data=tidy_fit_psi,
                       color=color, ax=ax)
            ax.set(title='{} {} {}'.format(fit, score, modality), xticks=[])
    sns.despine()
    fig.tight_layout()


Instruction:
How would you implement a function in Python 3 that
wraps around Seaborn s Violinplot specifically for [ 0 1 ) ranged data

Response:
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 width of all violinplots to be the same
    - inner = None: Don't plot a boxplot or points inside the violinplot
    """
    if ax is None:
        ax = plt.gca()

    sns.violinplot(x, y, data=data, bw=bw, scale=scale, inner=inner, ax=ax,
                   **kwargs)
    ax.set(ylim=(0, 1), yticks=(0, 0.5, 1))
    return ax


Instruction:
Write a Python 3 script for
drawing a barplot grouped by modality of modality percentage per group.

Response:
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 * (counts.T / counts.T.sum()).T

        # with sns.set(style='whitegrid'):
        if ax is None:
            ax = plt.gca()

        full_width = 0.8
        width = full_width / counts.shape[0]
        for i, (group, series) in enumerate(counts.iterrows()):
            left = np.arange(len(self.modality_order)) + i * width
            height = [series[i] if i in series else 0
                      for i in self.modality_order]
            color = phenotype_to_color[group]
            ax.bar(left, height, width=width, color=color, label=group,
                   linewidth=.5, edgecolor='k')
        ylabel = 'Percentage of events' if percentages else 'Number of events'
        ax.set_ylabel(ylabel)
        ax.set_xticks(np.arange(len(self.modality_order)) + full_width / 2)
        ax.set_xticklabels(self.modality_order)
        ax.set_xlabel('Splicing modality')
        ax.set_xlim(0, len(self.modality_order))
        ax.legend(loc='best')
        ax.grid(axis='y', linestyle='-', linewidth=0.5)
        sns.despine()


Instruction:
Can you create a Python 3 function that
shows the values underlying bayesian modality estimations of an event

Response:
def event_estimation(self, event, logliks, logsumexps, renamed=''):
        """Show the values underlying bayesian modality estimations of an event

        Parameters
        ----------

        Returns
        -------

        Raises
        ------
        """
        plotter = _ModelLoglikPlotter()
        plotter.plot(event, logliks, logsumexps, self.modality_to_color,
                     renamed=renamed)
        return plotter


Instruction:
Here you have a function in Python 3, explain what it does
def predict(self, fitted):
        if fitted.shape[0] != len(self.modalities):
            raise ValueError("This data doesn't look like it had the distance "
                             "between it and the five modalities calculated")
        return fitted.idxmin()

Response: Assign the most likely modality given the fitted data.


Instruction:
Make a summary of the following Python 3 code
def logliks(self, x):
        x = x.copy()

        # Replace exactly 0 and exactly 1 values with a very small number
        # (machine epsilon, the smallest number that this computer is capable
        # of storing) because 0 and 1 are not in the Beta distribution.
        x[x == 0] = VERY_SMALL_NUMBER
        x[x == 1] = 1 - VERY_SMALL_NUMBER

        return np.array([np.log(prob) + rv.logpdf(x[np.isfinite(x)]).sum()
                         for prob, rv in
                         zip(self.prob_parameters, self.rvs)])

Response: Calculate the log - likelihood of a feature x for each model.


Instruction:
How would you code a function in Python 3 to
convert floats to integers or a nice looking fraction

Response:
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):
                return r'\frac{{1}}{{{}}}'.format(int(inverse))
        else:
            template = '{{:.{0}}}'.format(decimal_places)
            return template.format(number)


Instruction:
Can you tell what is the following Python 3 function doing
def violinplot(self, n=1000, **kwargs):
        kwargs.setdefault('palette', 'Purples')

        dfs = []

        for rv in self.rvs:
            psi = rv.rvs(n)
            df = pd.Series(psi, name=self.ylabel).to_frame()
            alpha, beta = rv.args
            alpha = self.nice_number_string(alpha, decimal_places=2)
            beta = self.nice_number_string(beta, decimal_places=2)

            df['parameters'] = '$\\alpha = {0}$\n$\\beta = {1}$'.format(
                alpha, beta)
            dfs.append(df)
        data = pd.concat(dfs)

        if 'ax' not in kwargs:
            fig, ax = plt.subplots(figsize=(len(self.alphas)*0.625, 4))
        else:
            ax = kwargs.pop('ax')
        ax = violinplot(x='parameters', y=self.ylabel, data=data,
                        ax=ax, **kwargs)
        sns.despine(ax=ax)
        return ax

Response: Plot violins of each distribution in the model family.


Instruction:
Can you generate the documentation for the following Python 3 function
def _single_feature_logliks_one_step(self, feature, models):
        x_non_na = feature[~feature.isnull()]
        if x_non_na.empty:
            return pd.DataFrame()
        else:
            dfs = []
            for name, model in models.items():
                df = model.single_feature_logliks(feature)
                df['Modality'] = name
                dfs.append(df)
            return pd.concat(dfs, ignore_index=True)

Response: Get log - likelihood of models at each parameterization for a single feature.


Instruction:
How would you implement a function in Python 3 that
fits the log2 bayes factor for each modality assignment in the data.

Response:
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
        -------
        log2_bayes_factors : pandas.DataFrame
            A (n_modalities, n_events) dataframe of the estimated log2
            bayes factor for each splicing event, for each modality

        Raises
        ------
        AssertionError
            If any value in ``data`` does not fall only between 0 and 1.
        """
        self.assert_less_than_or_equal_1(data.values.flat)
        self.assert_non_negative(data.values.flat)

        if isinstance(data, pd.DataFrame):
            log2_bayes_factors = data.apply(self.single_feature_fit)
        elif isinstance(data, pd.Series):
            log2_bayes_factors = self.single_feature_fit(data)
        log2_bayes_factors.name = self.score_name
        return log2_bayes_factors


Instruction:
Can you implement a function in Python 3 that
predicts the most likely modality for each event.

Response:
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' modality, because we cannot
        reject the null hypothesis that these did not come from the uniform
        distribution.

        Parameters
        ----------
        log2_bayes_factors : pandas.DataFrame
            A (4, n_events) dataframe with bayes factors for the Psi~1, Psi~0,
            bimodal, and middle modalities. If an event has no bayes factors
            for any of those modalities, it is ignored
        reset_index : bool
            If True, remove the first level of the index from the dataframe.
            Useful if you are using this function to apply to a grouped
            dataframe where the first level is something other than the
            modality, e.g. the celltype

        Returns
        -------
        modalities : pandas.Series
            A (n_events,) series with the most likely modality for each event

        """
        if reset_index:
            x = log2_bayes_factors.reset_index(level=0, drop=True)
        else:
            x = log2_bayes_factors
        if isinstance(x, pd.DataFrame):
            not_na = (x.notnull() > 0).any()
            not_na_columns = not_na[not_na].index
            x.ix[NULL_MODEL, not_na_columns] = self.logbf_thresh
        elif isinstance(x, pd.Series):
            x[NULL_MODEL] = self.logbf_thresh
        return x.idxmax()


Instruction:
Can you write a function in Python 3 where it
calculates log - likelihoods of each modality s parameterization for each single feature.

Response:
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.

        Returns
        -------
        logliks : pandas.DataFrame
            The log-likelihood the data, for each model, for each
            parameterization

        Raises
        ------
        AssertionError
            If any value in ``x`` does not fall only between 0 and 1.
        """
        self.assert_less_than_or_equal_1(feature.values)
        self.assert_non_negative(feature.values)

        logliks = self._single_feature_logliks_one_step(
            feature, self.one_param_models)

        logsumexps = self.logliks_to_logsumexp(logliks)

        # If none of the one-parameter models passed, try the two-param models
        if (logsumexps <= self.logbf_thresh).all():
            logliks_two_params = self._single_feature_logliks_one_step(
                feature, self.two_param_models)
            logliks = pd.concat([logliks, logliks_two_params])
        return logliks


Instruction:
Write a Python 3 function that can
get the log2 bayes factor of the fit for each modality

Response:
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
                 k, v in self.one_param_models.items()})

            # Check if none of the previous features fit
            if (logbf_one_param <= self.logbf_thresh).all():
                logbf_two_param = pd.Series(
                    {k: v.logsumexp_logliks(feature)
                     for k, v in self.two_param_models.items()})
                series = pd.concat([logbf_one_param, logbf_two_param])
                series[NULL_MODEL] = self.logbf_thresh
            else:
                series = logbf_one_param
        series.index.name = 'Modality'
        series.name = self.score_name
        return series


Instruction:
Can you generate a brief explanation for the following Python 3 code
def bin_range_strings(bins, fmt=':g'):
    return [('{' + fmt + '}-{' + fmt + '}').format(i, j)
            for i, j in zip(bins, bins[1:])]

Response: Given a list of bins make a list of strings of those bin ranges


Instruction:
Can you implement a function in Python 3 that
makes a histogram of each column into a set of binsize

Response:
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. Must include the final bin
        value, e.g. (0, 0.5, 1) for the two bins (0, 0.5) and (0.5, 1).
        nbins = len(bins) - 1

    Returns
    -------
    binned : pandas.DataFrame
        An nbins x features DataFrame of each column binned across rows
    """
    if bins is None:
        raise ValueError('Must specify "bins"')
    if isinstance(data, pd.DataFrame):
        binned = data.apply(lambda x: pd.Series(np.histogram(x, bins=bins,
                                                             range=(0, 1))[0]))
    elif isinstance(data, pd.Series):
        binned = pd.Series(np.histogram(data, bins=bins, range=(0, 1))[0])
    else:
        raise ValueError('`data` must be either a 1d vector or 2d matrix')
    binned.index = bin_range_strings(bins)

    # Normalize so each column sums to 1
    binned = binned / binned.sum().astype(float)
    return binned


Instruction:
Make a summary of the following Python 3 code
def kld(p, q):
    try:
        _check_prob_dist(p)
        _check_prob_dist(q)
    except ValueError:
        return np.nan
    # If one of them is zero, then the other should be considered to be 0.
    # In this problem formulation, log0 = 0
    p = p.replace(0, np.nan)
    q = q.replace(0, np.nan)

    return (np.log2(p / q) * p).sum(axis=0)

Response:
Compute the Kullback - Leiber divergence of two probability distributions pandas
    dataframes p and q.


Instruction:
Can you implement a function in Python 3 that
calculates the Jensen - Shannon divergence between two probability distributions pandasDataFrame p and q.

Response:
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 nbins x features DataFrame.
    q : pandas.DataFrame
        An nbins x features DataFrame.

    Returns
    -------
    jsd : pandas.Series
        Jensen-Shannon divergence of each column with the same names between
        p and q

    Raises
    ------
    ValueError
        If the data provided is not a probability distribution, i.e. it has
        negative values or its columns do not sum to 1, raise ValueError
    """
    try:
        _check_prob_dist(p)
        _check_prob_dist(q)
    except ValueError:
        return np.nan
    weight = 0.5
    m = weight * (p + q)

    result = weight * kld(p, m) + (1 - weight) * kld(q, m)
    return result


Instruction:
Make a summary of the following Python 3 code
def entropy(binned, base=2):
    try:
        _check_prob_dist(binned)
    except ValueError:
        np.nan
    return -((np.log(binned) / np.log(base)) * binned).sum(axis=0)

Response: Find the entropy of each column of a dataframe.


Instruction:
Explain what the following Python 3 code does
def binify_and_jsd(df1, df2, bins, pair=None):
    binned1 = binify(df1, bins=bins).dropna(how='all', axis=1)
    binned2 = binify(df2, bins=bins).dropna(how='all', axis=1)

    binned1, binned2 = binned1.align(binned2, axis=1, join='inner')

    series = np.sqrt(jsd(binned1, binned2))
    series.name = pair
    return series

Response: Binify and calculate jensen - shannon divergence between two dataframes.


Instruction:
Write a Python 3 script to
transform a tall JSD dataframe to a square matrix of mean JSDs

Response:
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.DataFrame
        A (n_phenotypes, n_phenotypes) symmetric dataframe of the mean JSD
        between and within phenotypes
    """
    jsd_2d = jsd_df.mean().reset_index()
    jsd_2d = jsd_2d.rename(
        columns={'level_0': 'phenotype1', 'level_1': 'phenotype2', 0: 'jsd'})
    jsd_2d = jsd_2d.pivot(index='phenotype1', columns='phenotype2',
                          values='jsd')
    return jsd_2d + np.tril(jsd_2d.T, -1)


Instruction:
Create a Python 3 function for
starting the loop over the interface calling the given callback for each packet intercepted .

Response:
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 is equivalent to infinity)
        """
        if self._handle is None:
            raise self.DeviceIsNotOpen()
        # Set new callback
        self._callback = callback
        # Run loop with callback wrapper
        wtypes.pcap_loop(self._handle, limit, self._callback_wrapper, None)


Instruction:
Write a Python 3 function that can
send a packet to the network interface.

Response:
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)
        buf_send = ctypes.cast(ctypes.create_string_buffer(packet_buffer, buffer_length),
                               ctypes.POINTER(ctypes.c_ubyte))
        wtypes.pcap_sendpacket(self._handle, buf_send, buffer_length)


Instruction:
Can you implement a function in Python 3 that
captures packets on a specific network interface.

Response:
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)
        if device_name is not None:
            with WinPcap(device_name) as capture:
                capture.run(callback=callback)


Instruction:
How would you implement a function in Python 3 that
captures on a device name.

Response:
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(callback=callback)


Instruction:
Create a Python 3 function for
sending a packet to a network interface and optionally capture a response on the next request.

Response:
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 buffer to send (length shouldn't exceed MAX_INT)
        :param callback: If not None, a function to call with each intercepted packet
        :param limit: how many packets to capture (A value of -1 or 0 is equivalent to infinity)
        """
        device_name, desc = WinPcapDevices.get_matching_device(pattern)
        if device_name is not None:
            with WinPcap(device_name) as capture:
                capture.send(packet_buffer)
                if callback is not None:
                    capture.run(callback=callback, limit=limit)


Instruction:
Can you create a Python 3 function that
gets the next value for a given sequence.

Response:
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_value is not None:
        assert initial_value < reset_value

    if using is None:
        using = router.db_for_write(Sequence)

    connection = connections[using]

    if (getattr(connection, 'pg_version', 0) >= 90500
            and reset_value is None and not nowait):

        # PostgreSQL ≥ 9.5 supports "upsert".

        with connection.cursor() as cursor:
            cursor.execute(UPSERT_QUERY, [sequence_name, initial_value])
            last, = cursor.fetchone()
        return last

    else:

        # Other databases require making more database queries.

        with transaction.atomic(using=using, savepoint=False):
            sequence, created = (
                Sequence.objects
                        .select_for_update(nowait=nowait)
                        .get_or_create(name=sequence_name,
                                       defaults={'last': initial_value})
            )

            if not created:
                sequence.last += 1
                if reset_value is not None and sequence.last >= reset_value:
                    sequence.last = initial_value
                sequence.save()

            return sequence.last


Instruction:
Can you generate the documentation for the following Python 3 function
def check(self, final_line_count):
        if self._lines_seen["version"]:
            self._process_version_lines()
        self._process_plan_lines(final_line_count)

Response: Check the status of all provided data and update the suite.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _process_version_lines(self):
        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."))

Response: Process version line rules.


Instruction:
Write a Python 3 function for
processing plan line rules.

Response:
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."))
            return

        plan, at_line = self._lines_seen["plan"][0]
        if not self._plan_on_valid_line(at_line, final_line_count):
            self._add_error(
                _("A plan must appear at the beginning or end of the file.")
            )
            return

        if plan.expected_tests != self._lines_seen["test"]:
            self._add_error(
                _("Expected {expected_count} tests but only {seen_count} ran.").format(
                    expected_count=plan.expected_tests,
                    seen_count=self._lines_seen["test"],
                )
            )


Instruction:
Create a Python 3 function to
check if a plan is on a valid line.

Response:
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_version = (
            self._lines_seen["version"]
            and self._lines_seen["version"][0] == 1
            and at_line == 2
        )
        if after_version:
            return True

        return False


Instruction:
Write a Python 3 function that can
handle a bail line.

Response:
def handle_bail(self, bail):
        """Handle a bail line."""
        self._add_error(_("Bailed: {reason}").format(reason=bail.reason))


Instruction:
Can you write a function in Python 3 where it
handles a SKIP plan that contains a SKIP directive.

Response:
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))


Instruction:
Write a Python 3 function for
adding an error test to the suite.

Response:
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))


Instruction:
Can you write a function in Python 3 where it
formats an exception as diagnostics output.

Response:
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 (i.e. some elements have new
    # line characters in the middle). Normalize that oddity.
    lines = "".join(exception_lines).splitlines(True)
    return format_as_diagnostics(lines)


Instruction:
Create a Python 3 function to
parse a file - like object fh and return a generator of tap. line. Line objects.

Response:
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 newline characters will be automatically
        stripped from the input lines.
        """
        with fh:
            try:
                first_line = next(fh)
            except StopIteration:
                return
            first_parsed = self.parse_line(first_line.rstrip())
            fh_new = itertools.chain([first_line], fh)
            if first_parsed.category == "version" and first_parsed.version >= 13:
                if ENABLE_VERSION_13:
                    fh_new = peekable(itertools.chain([first_line], fh))
                    self._try_peeking = True
                else:  # pragma no cover
                    print(
                        """
WARNING: Optional imports not found, TAP 13 output will be
    ignored. To parse yaml, see requirements in docs:
    https://tappy.readthedocs.io/en/latest/consumers.html#tap-version-13"""
                    )

            for line in fh_new:
                yield self.parse_line(line.rstrip(), fh_new)


Instruction:
Here you have a function in Python 3, explain what it does
def parse_line(self, text, fh=None):
        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, match, fh)

        if self.diagnostic.match(text):
            return Diagnostic(text)

        match = self.plan.match(text)
        if match:
            return self._parse_plan(match)

        match = self.bail.match(text)
        if match:
            return Bail(match.group("reason"))

        match = self.version.match(text)
        if match:
            return self._parse_version(match)

        return Unknown()

Response: Parse a line into whatever TAP category it belongs.


Instruction:
Here you have a function in Python 3, explain what it does
def _parse_plan(self, match):
        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()

        return Plan(expected_tests, directive)

Response: Parse a matching plan line.


Instruction:
Can you write a function in Python 3 where it
parses a matching result line into a result instance.

Response:
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
        if peek_match is None:
            return Result(
                ok,
                number=match.group("number"),
                description=match.group("description").strip(),
                directive=Directive(match.group("directive")),
            )
        indent = peek_match.group("indent")
        concat_yaml = self._extract_yaml_block(indent, fh)
        return Result(
            ok,
            number=match.group("number"),
            description=match.group("description").strip(),
            directive=Directive(match.group("directive")),
            raw_yaml_block=concat_yaml,
        )


Instruction:
Can you tell what is the following Python 3 function doing
def _extract_yaml_block(self, indent, fh):
        raw_yaml = []
        indent_match = re.compile(r"^{}".format(indent))
        try:
            fh.next()
            while indent_match.match(fh.peek()):
                raw_yaml.append(fh.next().replace(indent, "", 1))
                # check for the end and stop adding yaml if encountered
                if self.yaml_block_end.match(fh.peek()):
                    fh.next()
                    break
        except StopIteration:
            pass
        return "\n".join(raw_yaml)

Response: Extract a raw yaml block from a file handler


Instruction:
Given the following Python 3 function, write the documentation
def yaml_block(self):
        if LOAD_YAML and self._yaml_block is not None:
            try:
                yaml_dict = yaml.load(self._yaml_block)
                return yaml_dict
            except yaml.error.YAMLError:
                print("Error parsing yaml block. Check formatting.")
        return None

Response: Lazy load a yaml_block.


Instruction:
Implement a function in Python 3 to
load any files found into a test suite.

Response:
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):
                self._find_tests_in_directory(filepath, suite)
            else:
                suite.addTest(self.load_suite_from_file(filepath))
        return suite


Instruction:
Implement a function in Python 3 to
load a test suite with test lines from the provided TAP file.

Response:
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.handle_file_does_not_exist()
            return suite

        line_generator = self._parser.parse_file(filename)
        return self._load_lines(filename, line_generator, suite, rules)


Instruction:
How would you code a function in Python 3 to
load a test suite with test lines from the TAP stream on STDIN.

Response:
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_lines("stream", line_generator, suite, rules)


Instruction:
Can you tell what is the following Python 3 function doing
def _load_lines(self, filename, line_generator, suite, rules):
        line_counter = 0
        for line in line_generator:
            line_counter += 1

            if line.category in self.ignored_lines:
                continue

            if line.category == "test":
                suite.addTest(Adapter(filename, line))
                rules.saw_test()
            elif line.category == "plan":
                if line.skip:
                    rules.handle_skipping_plan(line)
                    return suite
                rules.saw_plan(line, line_counter)
            elif line.category == "bail":
                rules.handle_bail(line)
                return suite
            elif line.category == "version":
                rules.saw_version_at(line_counter)

        rules.check(line_counter)
        return suite

Response: Load a suite with lines produced by the line generator.


Instruction:
Write a Python 3 function for
keeping track of which test cases have executed.

Response:
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] = []
            if self.combined:
                self.combined_test_cases_seen.append(class_name)


Instruction:
Explain what the following Python 3 code does
def set_plan(self, total):
        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 we can't just write the plan out
            # right here).
            if not self.combined_test_cases_seen:
                self._write_plan(self.stream)
        elif not self.combined:
            raise ValueError(
                "set_plan can only be used with combined or streaming output"
            )

Response: Notify the tracker how many total tests there will be.


Instruction:
Given the following Python 3 function, write the documentation
def generate_tap_reports(self):
        # We're streaming but set_plan wasn't called, so we can only
        # know the plan now (at the end).
        if self.streaming and not self._plan_written:
            print("1..{0}".format(self.combined_line_number), file=self.stream)
            self._plan_written = True
            return

        if self.combined:
            combined_file = "testresults.tap"
            if self.outdir:
                combined_file = os.path.join(self.outdir, combined_file)
            with open(combined_file, "w") as out_file:
                self._write_tap_version(out_file)
                if self.plan is not None:
                    print("1..{0}".format(self.plan), file=out_file)
                for test_case in self.combined_test_cases_seen:
                    self.generate_tap_report(
                        test_case, self._test_cases[test_case], out_file
                    )
                if self.plan is None:
                    print("1..{0}".format(self.combined_line_number), file=out_file)
        else:
            for test_case, tap_lines in self._test_cases.items():
                with open(self._get_tap_file_path(test_case), "w") as out_file:
                    self._write_tap_version(out_file)
                    self.generate_tap_report(test_case, tap_lines, out_file)

Response:
Generate TAP reports.

        The results are either combined into a single output file or
        the output file name is generated from the test case.


Instruction:
How would you implement a function in Python 3 that
writes the plan line to the given stream.

Response:
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=stream)
            self._plan_written = True


Instruction:
Can you tell what is the following Python 3 function doing
def _get_tap_file_path(self, 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 tap_file

Response: Get the TAP output file path for the test case.


Instruction:
Here you have a function in Python 3, explain what it does
def main(argv=sys.argv, stream=sys.stderr):
    args = parse_args(argv)
    suite = build_suite(args)
    runner = unittest.TextTestRunner(verbosity=args.verbose, stream=stream)
    result = runner.run(suite)

    return get_status(result)

Response: Entry point for tappy command.


Instruction:
Make a summary of the following Python 3 code
def build_suite(args):
    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

Response: Build a test suite by loading TAP files or a TAP stream.


Instruction:
Implement a Python 3 function for
adding a failure to the result.

Response:
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.failures[-1] = (test, "")


Instruction:
Can you write a function in Python 3 where it
bases on example https://bitbucket.org/zzzeek/sqlalchemy/src/73095b353124/examples/nested_sets/nested_sets.py?at=master

Response:
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 instance.parent_id is None:
        instance.left = 1
        instance.right = 2
        instance.level = instance.get_default_level()
        tree_id = connection.scalar(
            select(
                [
                    func.max(table.c.tree_id) + 1
                ]
            )
        ) or 1
        instance.tree_id = tree_id
    else:
        (parent_pos_left,
         parent_pos_right,
         parent_tree_id,
         parent_level) = connection.execute(
            select(
                [
                    table.c.lft,
                    table.c.rgt,
                    table.c.tree_id,
                    table.c.level
                ]
            ).where(
                table_pk == instance.parent_id
            )
        ).fetchone()

        # Update key of right side
        connection.execute(
            table.update(
                and_(table.c.rgt >= parent_pos_right,
                     table.c.tree_id == parent_tree_id)
            ).values(
                lft=case(
                    [
                        (
                            table.c.lft > parent_pos_right,
                            table.c.lft + 2
                        )
                    ],
                    else_=table.c.lft
                ),
                rgt=case(
                    [
                        (
                            table.c.rgt >= parent_pos_right,
                            table.c.rgt + 2
                        )
                    ],
                    else_=table.c.rgt
                )
            )
        )

        instance.level = parent_level + 1
        instance.tree_id = parent_tree_id
        instance.left = parent_pos_right
        instance.right = parent_pos_right + 1


Instruction:
How would you explain what the following Python 3 function does
def mptt_before_update(mapper, connection, instance):
    node_id = getattr(instance, instance.get_pk_name())
    table = _get_tree_table(mapper)
    db_pk = instance.get_pk_column()
    default_level = instance.get_default_level()
    table_pk = getattr(table.c, db_pk.name)
    mptt_move_inside = None
    left_sibling = None
    left_sibling_tree_id = None

    if hasattr(instance, 'mptt_move_inside'):
        mptt_move_inside = instance.mptt_move_inside

    if hasattr(instance, 'mptt_move_before'):
        (
            right_sibling_left,
            right_sibling_right,
            right_sibling_parent,
            right_sibling_level,
            right_sibling_tree_id
        ) = connection.execute(
            select(
                [
                    table.c.lft,
                    table.c.rgt,
                    table.c.parent_id,
                    table.c.level,
                    table.c.tree_id
                ]
            ).where(
                table_pk == instance.mptt_move_before
            )
        ).fetchone()
        current_lvl_nodes = connection.execute(
            select(
                [
                    table.c.lft,
                    table.c.rgt,
                    table.c.parent_id,
                    table.c.tree_id
                ]
            ).where(
                and_(
                    table.c.level == right_sibling_level,
                    table.c.tree_id == right_sibling_tree_id,
                    table.c.lft < right_sibling_left
                )
            )
        ).fetchall()
        if current_lvl_nodes:
            (
                left_sibling_left,
                left_sibling_right,
                left_sibling_parent,
                left_sibling_tree_id
            ) = current_lvl_nodes[-1]
            instance.parent_id = left_sibling_parent
            left_sibling = {
                'lft': left_sibling_left,
                'rgt': left_sibling_right,
                'is_parent': False
            }
        # if move_before to top level
        elif not right_sibling_parent:
            left_sibling_tree_id = right_sibling_tree_id - 1

    # if placed after a particular node
    if hasattr(instance, 'mptt_move_after'):
        (
            left_sibling_left,
            left_sibling_right,
            left_sibling_parent,
            left_sibling_tree_id
        ) = connection.execute(
            select(
                [
                    table.c.lft,
                    table.c.rgt,
                    table.c.parent_id,
                    table.c.tree_id
                ]
            ).where(
                table_pk == instance.mptt_move_after
            )
        ).fetchone()
        instance.parent_id = left_sibling_parent
        left_sibling = {
            'lft': left_sibling_left,
            'rgt': left_sibling_right,
            'is_parent': False
        }

    """ Get subtree from node

        SELECT id, name, level FROM my_tree
        WHERE left_key >= $left_key AND right_key <= $right_key
        ORDER BY left_key
    """
    subtree = connection.execute(
        select([table_pk])
        .where(
            and_(
                table.c.lft >= instance.left,
                table.c.rgt <= instance.right,
                table.c.tree_id == instance.tree_id
            )
        ).order_by(
            table.c.lft
        )
    ).fetchall()
    subtree = [x[0] for x in subtree]

    """ step 0: Initialize parameters.

        Put there left and right position of moving node
    """
    (
        node_pos_left,
        node_pos_right,
        node_tree_id,
        node_parent_id,
        node_level
    ) = connection.execute(
        select(
            [
                table.c.lft,
                table.c.rgt,
                table.c.tree_id,
                table.c.parent_id,
                table.c.level
            ]
        ).where(
            table_pk == node_id
        )
    ).fetchone()

    # if instance just update w/o move
    # XXX why this str() around parent_id comparison?
    if not left_sibling \
            and str(node_parent_id) == str(instance.parent_id) \
            and not mptt_move_inside:
        if left_sibling_tree_id is None:
            return

    # fix tree shorting
    if instance.parent_id is not None:
        (
            parent_id,
            parent_pos_right,
            parent_pos_left,
            parent_tree_id,
            parent_level
        ) = connection.execute(
            select(
                [
                    table_pk,
                    table.c.rgt,
                    table.c.lft,
                    table.c.tree_id,
                    table.c.level
                ]
            ).where(
                table_pk == instance.parent_id
            )
        ).fetchone()
        if node_parent_id is None and node_tree_id == parent_tree_id:
            instance.parent_id = None
            return

    # delete from old tree
    mptt_before_delete(mapper, connection, instance, False)

    if instance.parent_id is not None:
        """ Put there right position of new parent node (there moving node
            should be moved)
        """
        (
            parent_id,
            parent_pos_right,
            parent_pos_left,
            parent_tree_id,
            parent_level
        ) = connection.execute(
            select(
                [
                    table_pk,
                    table.c.rgt,
                    table.c.lft,
                    table.c.tree_id,
                    table.c.level
                ]
            ).where(
                table_pk == instance.parent_id
            )
        ).fetchone()
        # 'size' of moving node (including all it's sub nodes)
        node_size = node_pos_right - node_pos_left + 1

        # left sibling node
        if not left_sibling:
            left_sibling = {
                'lft': parent_pos_left,
                'rgt': parent_pos_right,
                'is_parent': True
            }

        # insert subtree in exist tree
        instance.tree_id = parent_tree_id
        _insert_subtree(
            table,
            connection,
            node_size,
            node_pos_left,
            node_pos_right,
            parent_pos_left,
            parent_pos_right,
            subtree,
            parent_tree_id,
            parent_level,
            node_level,
            left_sibling,
            table_pk
        )
    else:
        # if insert after
        if left_sibling_tree_id or left_sibling_tree_id == 0:
            tree_id = left_sibling_tree_id + 1
            connection.execute(
                table.update(
                    table.c.tree_id > left_sibling_tree_id
                ).values(
                    tree_id=table.c.tree_id + 1
                )
            )
        # if just insert
        else:
            tree_id = connection.scalar(
                select(
                    [
                        func.max(table.c.tree_id) + 1
                    ]
                )
            )

        connection.execute(
            table.update(
                table_pk.in_(
                    subtree
                )
            ).values(
                lft=table.c.lft - node_pos_left + 1,
                rgt=table.c.rgt - node_pos_left + 1,
                level=table.c.level - node_level + default_level,
                tree_id=tree_id
            )
        )

Response: This function is used to move a node in nested set to the new tree.


Instruction:
Write a Python 3 function for
calling by the flush event listener to recursively expire left and right attributes of all modified instances in the specified session.

Response:
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()
            if instance not in session:
                continue
            parent = self.get_parent_value(instance)

            while parent != NO_VALUE and parent is not None:
                instances.discard(parent)
                session.expire(parent, ['left', 'right', 'tree_id', 'level'])
                parent = self.get_parent_value(parent)
            else:
                session.expire(instance, ['left', 'right', 'tree_id', 'level'])
                self.expire_session_for_children(session, instance)


Instruction:
How would you explain what the following Python 3 function does
def is_ancestor_of(self, other, inclusive=False):
        if inclusive:
            return (self.tree_id == other.tree_id) \
                & (self.left <= other.left) \
                & (other.right <= self.right)
        return (self.tree_id == other.tree_id) \
            & (self.left < other.left) \
            & (other.right < self.right)

Response: class or instance level method which returns True if self is an ancestor of other else False.


Instruction:
How would you explain what the following Python 3 function does
def move_inside(self, parent_id):
        session = Session.object_session(self)
        self.parent_id = parent_id
        self.mptt_move_inside = parent_id
        session.add(self)

Response: Moving one node of tree inside another node


Instruction:
Write a Python 3 function that can
move one node of tree after another node

Response:
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_id
        session.add(self)


Instruction:
Make a summary of the following Python 3 code
def move_before(self, node_id):
        session = Session.object_session(self)
        table = _get_tree_table(self.__mapper__)
        pk = getattr(table.c, self.get_pk_column().name)
        node = session.query(table).filter(pk == node_id).one()
        self.parent_id = node.parent_id
        self.mptt_move_before = node_id
        session.add(self)

Response: Moving one node of tree before another node


Instruction:
Can you tell what is the following Python 3 function doing
def drilldown_tree(self, session=None, json=False, json_fields=None):
        if not session:
            session = object_session(self)
        return self.get_tree(
            session,
            json=json,
            json_fields=json_fields,
            query=self._drilldown_query
        )

Response: This method generates a branch from a tree.


Instruction:
Can you tell what is the following Python 3 function doing
def path_to_root(self, session=None, order=desc):
        table = self.__class__
        query = self._base_query_obj(session=session)
        query = query.filter(table.is_ancestor_of(self, inclusive=True))
        return self._base_order(query, order=order)

Response: Generate a path from a leaf or intermediate node to the root.


Instruction:
How would you explain what the following Python 3 function does
def rebuild_tree(cls, session, tree_id):
        session.query(cls).filter_by(tree_id=tree_id)\
            .update({cls.left: 0, cls.right: 0, cls.level: 0})
        top = session.query(cls).filter_by(parent_id=None)\
            .filter_by(tree_id=tree_id).one()
        top.left = left = 1
        top.right = right = 2
        top.level = level = cls.get_default_level()

        def recursive(children, left, right, level):
            level = level + 1
            for i, node in enumerate(children):
                same_level_right = children[i - 1].right
                left = left + 1

                if i > 0:
                    left = left + 1
                if same_level_right:
                    left = same_level_right + 1

                right = left + 1
                node.left = left
                node.right = right
                parent = node.parent

                j = 0
                while parent:
                    parent.right = right + 1 + j
                    parent = parent.parent
                    j += 1

                node.level = level
                recursive(node.children, left, right, level)

        recursive(top.children, left, right, level)

Response: This method rebuid tree.


Instruction:
Write a Python 3 function for
rebuilding the tree of the related objects.

Response:
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.test_rebuild`
        """

        trees = session.query(cls).filter_by(parent_id=None)
        if tree_id:
            trees = trees.filter_by(tree_id=tree_id)
        for tree in trees:
            cls.rebuild_tree(session, tree.tree_id)


Instruction:
Write a Python 3 script to
return the probability that a life aged x dies before 1 year Returns 0 if the age is not in the mortality table qx

Response:
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


Instruction:
Given the following Python 3 function, write the documentation
def lx(mt, x):
    if x < len(mt.lx):
        return mt.lx[x]
    else:
        return 0

Response: Returns the number of survivors at begining of age x


Instruction:
Can you generate a brief explanation for the following Python 3 code
def dx(mt, 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

Response: Returns the number of dying at begining of age x


Instruction:
Can you write a function in Python 3 where it
returns the probability that x will survive within t years

Response:
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]


Instruction:
Can you generate a brief explanation for the following Python 3 code
def ex(mt, x):
    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

Response: ex - Returns the curtate expectation of life. Life expectancy


Instruction:
Can you create a Python 3 function that
returns the Sx of the given MT

Response:
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


Instruction:
Can you create a Python 3 function that
returns the Cx of the given mt

Response:
def Cx(mt, x):
    """ Return the Cx """
    return ((1 / (1 + mt.i)) ** (x + 1)) * mt.dx[x] * ((1 + mt.i) ** 0.5)


Instruction:
Write a Python 3 script to
return the Mx of the given MT

Response:
def Mx(mt, x):
    """ Return the Mx """
    n = len(mt.Cx)
    sum1 = 0
    for j in range(x, n):
        k = mt.Cx[j]
        sum1 += k
    return sum1


Instruction:
Can you generate the documentation for the following Python 3 function
def Axn(mt, x, n):
    return (mt.Mx[x] - mt.Mx[x + n]) / mt.Dx[x]

Response: (A^1)x:n : Returns the EPV (net single premium) of a term insurance.


Instruction:
How would you explain what the following Python 3 function does
def AExn(mt, x, n):
    return (mt.Mx[x] - mt.Mx[x + n]) / mt.Dx[x] + mt.Dx[x + n] / mt.Dx[x]

Response: Returns the EPV of a term insurance.


Instruction:
Make a summary of the following Python 3 code
def tAx(mt, x, t):
    return mt.Mx[x + t] / mt.Dx[x]

Response: n/Ax : Returns the EPV (net single premium) of a deferred whole life insurance.


Instruction:
How would you implement a function in Python 3 that
returns the actuarial present value of a temporal annuity

Response:
def aaxn(mt, x, n, m=1):
    """ äxn : Return the actuarial present value of a (immediate) temporal (term certain) annuity:
    n-year temporary life annuity-anticipatory. Payable 'm' per year at the beginning of the period
    """
    if m == 1:
        return (mt.Nx[x] - mt.Nx[x + n]) / mt.Dx[x]
    else:
        return (mt.Nx[x] - mt.Nx[x + n]) / mt.Dx[x] - ((float(m - 1) / float(m * 2)) * (1 - nEx(mt, x, n)))


Instruction:
Can you generate the documentation for the following Python 3 function
def aax(mt, x, m=1):
    return mt.Nx[x] / mt.Dx[x] - (float(m - 1) / float(m * 2))

Response: äx : Returns the actuarial present value of an annuity of 1 per time period


Instruction:
Can you write a function in Python 3 where it
returns the actuarial present value of an annuity of 1 per time period

Response:
def ax(mt, x, m=1):
    """ ax : Returns the actuarial present value of an (immediate) annuity of 1 per time period
    (whole life annuity-late). Payable 'm' per year at the ends of the period
    """
    return (mt.Nx[x] / mt.Dx[x] - 1) + (float(m - 1) / float(m * 2))


Instruction:
Make a summary of the following Python 3 code
def taax(mt, x, t, m=1):
    return mt.Nx[x + t] / mt.Dx[x] - ((float(m - 1) / float(m * 2)) * (1 - nEx(mt, x, t)))

Response: Return the actuarial present value of a deferred annuity at a given time.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def Iaaxn(mt, x, n, *args):
    return (Sx(mt, x) - Sx(nt, x + n) - n * Nx(nt, x + n)) / Dx(nt, x)

Response: during a term certain, IAn


Instruction:
Can you generate a brief explanation for the following Python 3 code
def Iaxn(mt, x, n, *args):
    return (Sx(mt, x + 1) - Sx(mt, x + n + 1) - n * Nx(mt, x + n + 1)) / Dx(mt, x)

Response: during a term certain, IAn


Instruction:
Can you tell what is the following Python 3 function doing
def Itaax(mt, x, t):
    return (Sx(mt, x) - Sx(mt, x + t)) / Dx(mt, x)

Response: Itaax of a given time.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _meanvalueattr(self,v):
        sug = self.layout
        if not self.prevlayer(): return sug.grx[v].bar
        bars = [sug.grx[x].bar for x in self._neighbors(v)]
        return sug.grx[v].bar if len(bars)==0 else float(sum(bars))/len(bars)

Response: find new position of vertex v according to adjacency in prevlayer and return the mean value of adjacent positions.


Instruction:
Implement a Python 3 function for
finding new position of vertex v according to adjacency in layer l + dir

Response:
def _medianindex(self,v):
        """
        find new position of vertex v according to adjacency in layer l+dir.
        position is given by the median value of adjacent positions.
        median heuristic is proven to achieve at most 3 times the minimum
        of crossings (while barycenter achieve in theory the order of |V|)
        """
        assert self.prevlayer()!=None
        N = self._neighbors(v)
        g=self.layout.grx
        pos = [g[x].pos for x in N]
        lp = len(pos)
        if lp==0: return []
        pos.sort()
        pos = pos[::self.layout.dirh]
        i,j = divmod(lp-1,2)
        return [pos[i]] if j==0 else [pos[i],pos[i+j]]


Instruction:
Create a Python 3 function for
getting neighbors of a node in the graph

Response:
def _neighbors(self,v):
        """
        neighbors refer to upper/lower adjacent nodes.
        Note that v.N() provides neighbors of v in the graph, while
        this method provides the Vertex and DummyVertex adjacent to v in the
        upper or lower layer (depending on layout.dirv state).
        """
        assert self.layout.dag
        dirv = self.layout.dirv
        grxv = self.layout.grx[v]
        try: #(cache)
            return grxv.nvs[dirv]
        except AttributeError:
            grxv.nvs={-1:v.N(-1),+1:v.N(+1)}
            if grxv.dummy: return grxv.nvs[dirv]
            # v is real, v.N are graph neigbors but we need layers neighbors
            for d in (-1,+1):
                tr=grxv.rank+d
                for i,x in enumerate(v.N(d)):
                    if self.layout.grx[x].rank==tr:continue
                    e=v.e_with(x)
                    dum = self.layout.ctrls[e][tr]
                    grxv.nvs[d][i]=dum
            return grxv.nvs[dirv]


Instruction:
Implement a function in Python 3 to
count the number of crossings between two layers.

Response:
def _crossings(self):
        """
        counts (inefficently but at least accurately) the number of
        crossing edges between layer l and l+dirv.
        P[i][j] counts the number of crossings from j-th edge of vertex i.
        The total count of crossings is the sum of flattened P:
        x = sum(sum(P,[]))
        """
        g=self.layout.grx
        P=[]
        for v in self:
            P.append([g[x].pos for x in self._neighbors(v)])
        for i,p in enumerate(P):
            candidates = sum(P[i+1:],[])
            for j,e in enumerate(p):
                p[j] = len(filter((lambda nx:nx<e), candidates))
            del candidates
        return P


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _cc(self):
        g=self.layout.grx
        P=[]
        for v in self:
            P.extend(sorted([g[x].pos for x in self._neighbors(v)]))
        # count inversions in P:
        s = []
        count = 0
        for i,p in enumerate(P):
            j = bisect(s,p)
            if j<i: count += (i-j)
            s.insert(j,p)
        return count

Response: Returns the number of inversions in the cross count of the current instance of the class.


Instruction:
Write a Python 3 function that can
initialize the layout algorithm by computing all roots and inverted edges and creates all dummy vertex and edge for long edges.

Response:
def init_all(self,roots=None,inverted_edges=None,optimize=False):
        """initializes the layout algorithm by computing roots (unless provided),
           inverted edges (unless provided), vertices ranks and creates all dummy
           vertices and layers.

             Parameters:
                roots (list[Vertex]): set *root* vertices (layer 0)
                inverted_edges (list[Edge]): set edges to invert to have a DAG.
                optimize (bool): optimize ranking if True (default False)
        """
        if self.initdone: return
        # For layered sugiyama algorithm, the input graph must be acyclic,
        # so we must provide a list of root nodes and a list of inverted edges.
        if roots==None:
            roots = [v for v in self.g.sV if len(v.e_in())==0]
        if inverted_edges==None:
            L = self.g.get_scs_with_feedback(roots)
            inverted_edges = [x for x in self.g.sE if x.feedback]
        self.alt_e = inverted_edges
        # assign rank to all vertices:
        self.rank_all(roots,optimize)
        # add dummy vertex/edge for 'long' edges:
        for e in self.g.E():
            self.setdummies(e)
        # precompute some layers values:
        for l in self.layers: l.setup(self)
        self.initdone = True