Instruction:
Can you write a function in Python 3 where it
recognizes and claims VarScan VCFs form the set of all input VCFs.

Response:
def claim(self, file_readers):
        """Recognizes and claims VarScan VCFs form the set of all input VCFs.

        Each defined caller has a chance to evaluate and claim all the incoming
        files as something that it can process. Since VarScan can claim
        high-confidence files as well, this process is significantly more
        complex than for other callers.

        Args:
            file_readers: the collection of currently unclaimed files

        Returns:
            A tuple of unclaimed readers and VarScanVcfReaders.
        """

        (prefix_to_readers,
         filter_files,
         unclaimed_set) = self._find_varscan_files(file_readers)

        prefix_by_patients = self._split_prefix_by_patient(prefix_to_readers)
        self._validate_vcf_readers(prefix_by_patients)
        vcf_hc_pairs = self._pair_files(prefix_to_readers, filter_files)
        self._validate_vcf_hc_pairs(vcf_hc_pairs)
        vcf_readers = self._create_vcf_readers(vcf_hc_pairs)

        return list(unclaimed_set), vcf_readers


Instruction:
Can you write a function in Python 3 where it
extracts ( float ) value of dependent tag or None.

Response:
def _get_dependent_value(tag_values, dependent_tag_id):
        '''Extract (float) value of dependent tag or None if absent.'''
        try:
            values = tag_values[dependent_tag_id].split(",")
            return max([float(value) for value in values])
        except KeyError:
            return None
        except ValueError:
            return None


Instruction:
Create a Python 3 function to
derive mean and stdev.

Response:
def _init_population_stats(self, vcf_reader, dependent_tag_id):
        '''Derive mean and stdev.

        Adapted from online variance algorithm from Knuth, The Art of Computer
        Programming, volume 2

        Returns: mean and stdev when len(values) > 1, otherwise (None, None)
            Values rounded to _MAX_PRECISION to ameliorate discrepancies between
            python versions.'''
        #pylint: disable=invalid-name
        n = 0
        mean = 0
        M2 = 0
        try:
            vcf_reader.open()
            for vcf_record in vcf_reader.vcf_records():
                for tag_values in vcf_record.sample_tag_values.values():
                    value = self._get_dependent_value(tag_values,
                                                      dependent_tag_id)
                    if value is not None:
                        n += 1
                        delta = value - mean
                        mean += delta / n
                        M2 += delta * (value - mean)
        finally:
            vcf_reader.close()

        mean = round(mean, self._MAX_PRECISION)

        stdev = 0
        if n == 0:
            mean = None
            stdev = None
        elif n >= 2:
            variance = M2/n
            stdev = round(math.sqrt(variance), self._MAX_PRECISION)

        return mean, stdev


Instruction:
Given the following Python 3 function, write the documentation
def claim(self, unclaimed_file_readers):
        claimed_vcf_readers = []
        for caller in self._callers:
            (unclaimed_file_readers,
             translated_vcf_readers) = caller.claim(unclaimed_file_readers)
            claimed_vcf_readers.extend(translated_vcf_readers)

        return unclaimed_file_readers, claimed_vcf_readers

Response: Allows each caller to claim incoming files as they are recognized.


Instruction:
Explain what the following Python 3 code does
def vcf_records(self, format_tags=None, qualified=False):
        if qualified:
            sample_names = self.qualified_sample_names
        else:
            sample_names = self.sample_names

        for line in self._file_reader.read_lines():
            if line.startswith("#"):
                continue
            vcf_record = vcf.VcfRecord.parse_record(line, sample_names)
            if format_tags:
                vcf_record = self.modify_format_tag(vcf_record, format_tags)
            yield vcf_record

Response: Generates parsed VcfRecords objects.


Instruction:
Can you create a Python 3 function that
follows a file at the given path.

Response:
def follow_path(file_path, buffering=-1, encoding=None, errors='strict'):
    """
    Similar to follow, but also looks up if inode of file is changed
    e.g. if it was re-created.

    Returned generator yields strings encoded by using encoding.
    If encoding is not specified, it defaults to locale.getpreferredencoding()

    >>> import io
    >>> import os
    >>> f = io.open('test_follow_path.txt', 'w+')
    >>> generator = follow_path('test_follow_path.txt')
    >>> _ = f.write('Line 1\\n')
    >>> f.flush()
    >>> print(next(generator))
    Line 1
    >>> _ = f.write('Line 2\\n')
    >>> f.flush()
    >>> print(next(generator))
    Line 2
    >>> _ = f.truncate(0)
    >>> _ = f.seek(0)
    >>> _ = f.write('Line 3\\n')
    >>> f.flush()
    >>> print(next(generator))
    Line 3
    >>> f.close()
    >>> os.remove('test_follow_path.txt')
    >>> f = io.open('test_follow_path.txt', 'w+')
    >>> _ = f.write('Line 4\\n')
    >>> f.flush()
    >>> print(next(generator))
    Line 4
    >>> print(next(generator))
    None
    >>> f.close()
    >>> os.remove('test_follow_path.txt')
    """
    if encoding is None:
        encoding = locale.getpreferredencoding()

    class FollowPathGenerator(object):
        def __init__(self):
            if os.path.isfile(file_path):
                self.following_file = io.open(file_path, 'rb', buffering)
                self.follow_generator = Tailer(self.following_file, end=True).follow()
                self.follow_from_end_on_open = False
            else:
                self.following_file = None
                self.follow_generator = None
                self.follow_from_end_on_open = True

        def next(self):
            while True:
                if self.follow_generator:
                    line = next(self.follow_generator)
                else:
                    line = None

                if line is None:
                    if self.follow_generator:
                        try:
                            is_file_changed = not os.path.isfile(file_path) or os.stat(file_path).st_ino != os.fstat(self.following_file.fileno()).st_ino
                        except OSError:
                            # File could be deleted between isfile and stat invocations, which will make the latter to fail.
                            is_file_changed = True

                        if is_file_changed:
                            # File was deleted or re-created.
                            self.following_file.close()
                            self.following_file = None
                            self.follow_generator = None

                    if not self.follow_generator and os.path.isfile(file_path):
                        # New file is available. Open it.
                        try:
                            self.following_file = io.open(file_path, 'rb', buffering)
                            self.follow_generator = Tailer(self.following_file, end=self.follow_from_end_on_open).follow()
                            self.follow_from_end_on_open = False  # something could be written before we noticed change of file
                        except (IOError, OSError) as e:
                            LOG.info("Unable to tail file: %s", e)
                            if self.following_file:
                                self.following_file.close()

                            self.following_file= None
                            self.follow_generator = None
                            line = None
                        else:
                            line = next(self.follow_generator)

                return line.decode(encoding, errors) if line is not None else line

        def __iter__(self):
            return self

        def __next__(self):
            return self.next()

    return FollowPathGenerator()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def splitlines(self, data):
        return re.split(b'|'.join(self.LINE_TERMINATORS), data)

Response: Split data into lines where lines are separated by LINE_TERMINATORS.


Instruction:
Here you have a function in Python 3, explain what it does
def read(self, read_size=-1):
        read_str = self.file.read(read_size)
        return len(read_str), read_str

Response: Reads given number of bytes from file.


Instruction:
Create a Python 3 function for
returning the first line terminator that starts with data or None.

Response:
def prefix_line_terminator(self, data):
        """
        Return line terminator data begins with or None.
        """
        for t in self.LINE_TERMINATORS:
            if data.startswith(t):
                return t

        return None


Instruction:
How would you explain what the following Python 3 function does
def suffix_line_terminator(self, data):
        for t in self.LINE_TERMINATORS:
            if data.endswith(t):
                return t

        return None

Response: Return the suffix of the data with a line terminator or None if the data does not end with one of the line terminators.


Instruction:
Can you create a Python 3 function that
seeks to the next line in the file.

Response:
def seek_next_line(self):
        """
        Seek next line relative to the current file position.

        :return: Position of the line or -1 if next line was not found.
        """
        where = self.file.tell()
        offset = 0

        while True:
            data_len, data = self.read(self.read_size)
            data_where = 0

            if not data_len:
                break

            # Consider the following example: Foo\r | \nBar where " | " denotes current position,
            # 'Foo\r' is the read part and '\nBar' is the remaining part.
            # We should completely consume terminator "\r\n" by reading one extra byte.
            if b'\r\n' in self.LINE_TERMINATORS and data[-1] == b'\r'[0]:
                terminator_where = self.file.tell()
                terminator_len, terminator_data = self.read(1)

                if terminator_len and terminator_data[0] == b'\n'[0]:
                    data_len += 1
                    data += b'\n'
                else:
                    self.file.seek(terminator_where)

            while data_where < data_len:
                terminator = self.prefix_line_terminator(data[data_where:])
                if terminator:
                    self.file.seek(where + offset + data_where + len(terminator))
                    return self.file.tell()
                else:
                    data_where += 1

            offset += data_len
            self.file.seek(where + offset)

        return -1


Instruction:
Explain what the following Python 3 code does
def seek_previous_line(self):
        where = self.file.tell()
        offset = 0

        while True:
            if offset == where:
                break

            read_size = self.read_size if self.read_size <= where else where
            self.file.seek(where - offset - read_size, SEEK_SET)
            data_len, data = self.read(read_size)

            # Consider the following example: Foo\r | \nBar where " | " denotes current position,
            # '\nBar' is the read part and 'Foo\r' is the remaining part.
            # We should completely consume terminator "\r\n" by reading one extra byte.
            if b'\r\n' in self.LINE_TERMINATORS and data[0] == b'\n'[0]:
                terminator_where = self.file.tell()
                if terminator_where > data_len + 1:
                    self.file.seek(where - offset - data_len - 1, SEEK_SET)
                    terminator_len, terminator_data = self.read(1)

                    if terminator_data[0] == b'\r'[0]:
                        data_len += 1
                        data = b'\r' + data

                    self.file.seek(terminator_where)

            data_where = data_len

            while data_where > 0:
                terminator = self.suffix_line_terminator(data[:data_where])
                if terminator and offset == 0 and data_where == data_len:
                    # The last character is a line terminator that finishes current line. Ignore it.
                    data_where -= len(terminator)
                elif terminator:
                    self.file.seek(where - offset - (data_len - data_where))
                    return self.file.tell()
                else:
                    data_where -= 1

            offset += data_len

        if where == 0:
            # Nothing more to read.
            return -1
        else:
            # Very first line.
            self.file.seek(0)
            return 0

Response: Seek to the previous line in the file.


Instruction:
Given the following Python 3 function, write the documentation
def tail(self, lines=10):
        self.file.seek(0, SEEK_END)

        for i in range(lines):
            if self.seek_previous_line() == -1:
                break

        data = self.file.read()

        for t in self.LINE_TERMINATORS:
            if data.endswith(t):
                # Only terminators _between_ lines should be preserved.
                # Otherwise terminator of the last line will be treated as separtaing line and empty line.
                data = data[:-len(t)]
                break

        if data:
            return self.splitlines(data)
        else:
            return []

Response: Return the last lines of the file.


Instruction:
Explain what the following Python 3 code does
def head(self, lines=10):
        self.file.seek(0)

        for i in range(lines):
            if self.seek_next_line() == -1:
                break

        end_pos = self.file.tell()

        self.file.seek(0)
        data = self.file.read(end_pos)

        for t in self.LINE_TERMINATORS:
            if data.endswith(t):
                # Only terminators _between_ lines should be preserved.
                # Otherwise terminator of the last line will be treated as separtaing line and empty line.
                data = data[:-len(t)]
                break

        if data:
            return self.splitlines(data)
        else:
            return []

Response: Return the first lines of the file.


Instruction:
Make a summary of the following Python 3 code
def follow(self):
        trailing = True

        while True:
            where = self.file.tell()

            if where > os.fstat(self.file.fileno()).st_size:
                # File was truncated.
                where = 0
                self.file.seek(where)

            line = self.file.readline()

            if line:
                if trailing and line in self.LINE_TERMINATORS:
                    # This is just the line terminator added to the end of the file
                    # before a new line, ignore.
                    trailing = False
                    continue

                terminator = self.suffix_line_terminator(line)
                if terminator:
                    line = line[:-len(terminator)]

                trailing = False
                yield line
            else:
                trailing = True
                self.file.seek(where)
                yield None

Response: Iterator that returns lines as data is added to the file.


Instruction:
Write a Python 3 script to
recognize and claims Strelka VCFs form the set of all input VCFs.

Response:
def claim(self, file_readers):
        """Recognizes and claims Strelka VCFs form the set of all input VCFs.

        Each defined caller has a chance to evaluate and claim all the incoming
        files as something that it can process.

        Args:
            file_readers: the collection of currently unclaimed files

        Returns:
            A tuple of unclaimed readers and StrelkaVcfReaders.
        """
        (prefix_to_reader,
         unclaimed_readers) = self._find_strelka_files(file_readers)
        prefix_by_patients = self._split_prefix_by_patient(prefix_to_reader)
        self._validate_vcf_readers(prefix_by_patients)
        vcf_readers = self._create_vcf_readers(prefix_to_reader)

        return (unclaimed_readers, vcf_readers)


Instruction:
Explain what the following Python 3 code does
def vcf_records(self, qualified=False):
        if qualified:
            sample_names = self.qualified_sample_names
        else:
            sample_names = self.sample_names

        for line in self._file_reader.read_lines():
            if line.startswith("#"):
                continue
            yield VcfRecord.parse_record(line, sample_names)

Response: Generates parsed VcfRecords objects.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def parse_record(cls, vcf_line, sample_names):
        vcf_fields = vcf_line.rstrip("\r\n").split("\t")
        chrom, pos, rid, ref, alt, qual, rfilter, info \
                = vcf_fields[0:8]
        sample_fields = []
        sample_tag_values = {}
        if len(vcf_fields) > 9:
            rformat = vcf_fields[8]
            sample_fields = vcf_fields[9:]
            sample_tag_values = VcfRecord._sample_tag_values(sample_names,
                                                             rformat,
                                                             sample_fields)
        return VcfRecord(chrom, pos, ref, alt,
                         rid, qual, rfilter, info,
                         sample_tag_values)

Response: Alternative constructor that parses a VCF record from a string.


Instruction:
Can you generate the documentation for the following Python 3 function
def _sample_tag_values(cls, sample_names, rformat, sample_fields):
        sample_tag_values = OrderedDict()
        tag_names = VcfRecord._format_list(rformat)
        for i, sample_field in enumerate(sample_fields):
            tag_values = sample_field.split(":") if sample_field else "."
            sample_tag_values[sample_names[i]] = OrderedDict(zip(tag_names,
                                                                 tag_values))
        return sample_tag_values

Response: Create a sample dict of tag - value dicts for a single variant record.


Instruction:
Write a Python 3 function for
returning set of format tags.

Response:
def format_tags(self):
        """Returns set of format tags."""
        tags = VcfRecord._EMPTY_SET
        if self.sample_tag_values:
            first_sample = list(self.sample_tag_values.keys())[0]
            tags = set(self.sample_tag_values[first_sample].keys())
        return tags


Instruction:
Can you generate a brief explanation for the following Python 3 code
def add_info_field(self, field):
        if field in self.info_dict:
            msg = "New info field [{}] already exists.".format(field)
            raise KeyError(msg)

        if "=" in field:
            key, value = field.split("=")
            self.info_dict[key] = value
        else:
            self.info_dict[field] = field

        self._join_info_fields()

Response: Adds new info field to the internal dictionary.


Instruction:
Can you generate the documentation for the following Python 3 function
def _join_info_fields(self):
        if self.info_dict:
            info_fields = []
            if len(self.info_dict) > 1:
                self.info_dict.pop(".", None)
            for field, value in self.info_dict.items():
                if field == value:
                    info_fields.append(value)
                else:
                    info_fields.append("=".join([field, value]))
            self.info = ";".join(info_fields)
        else:
            self.info = "."

Response: Updates info attribute from info dict.


Instruction:
How would you explain what the following Python 3 function does
def _format_field(self):
        format_field = "."
        if self.sample_tag_values:
            first_sample = list(self.sample_tag_values.keys())[0]
            tag_names = self.sample_tag_values[first_sample].keys()
            if tag_names:
                format_field = ":".join(tag_names)
        return format_field

Response: Returns string representation of format field.


Instruction:
Explain what the following Python 3 code does
def _sample_field(self, sample):
        tag_values = self.sample_tag_values[sample].values()
        if tag_values:
            return ":".join(tag_values)
        else:
            return "."

Response: Returns the string representation of sample - format values.


Instruction:
Can you implement a function in Python 3 that
returns tab - delimited newline terminated string of VcfRecord.

Response:
def text(self):
        "Returns tab-delimited, newline terminated string of VcfRecord."
        stringifier = [self.chrom, self.pos, self.vcf_id, self.ref, self.alt,
                       self.qual, self.filter, self.info,
                       self._format_field()]

        for sample in self.sample_tag_values:
            stringifier.append(self._sample_field(sample))

        return "\t".join(stringifier) + "\n"


Instruction:
Create a Python 3 function to
append a new format tag - value for all samples.

Response:
def add_sample_tag_value(self, tag_name, new_sample_values):
        """Appends a new format tag-value for all samples.

        Args:
            tag_name: string tag name; must not already exist
            new_sample

        Raises:
            KeyError: if tag_name to be added already exists
        """
        if tag_name in self.format_tags:
            msg = "New format value [{}] already exists.".format(tag_name)
            raise KeyError(msg)

        if not self._samples_match(new_sample_values):
            raise KeyError("Sample name values must match "
                           "existing sample names")
        for sample in self.sample_tag_values.keys():
            value = str(new_sample_values[sample])
            self.sample_tag_values[sample][tag_name] = value


Instruction:
Write a Python 3 function that can
replace null or blank filter or adds new_filter to existing list.

Response:
def add_or_replace_filter(self, new_filter):
        """Replaces null or blank filter or adds filter to existing list."""
        if self.filter.lower() in self._FILTERS_TO_REPLACE:
            self.filter = new_filter
        elif new_filter not in self.filter.split(";"):
            self.filter = ";".join([self.filter,
                                    new_filter])


Instruction:
Can you tell what is the following Python 3 function doing
def available_categories(cls, user, products=AllProducts):
        ''' Returns the categories available to the user. Specify `products` if
        you want to restrict to just the categories that hold the specified
        products, otherwise it'll do all. '''

        # STOPGAP -- this needs to be elsewhere tbqh
        from .product import ProductController

        if products is AllProducts:
            products = inventory.Product.objects.all().select_related(
                "category",
            )

        available = ProductController.available_products(
            user,
            products=products,
        )

        return sorted(set(i.category for i in available), key=attrgetter("order"))

Response:
Returns the available categories to the user. Specify products to restrict to just the categories that hold the specified
        products.


Instruction:
Can you implement a function in Python 3 that
produces an appropriate _ProductsForm subclass for the given category and products.

Response:
def ProductsForm(category, products):
    ''' Produces an appropriate _ProductsForm subclass for the given render
    type. '''

    # Each Category.RENDER_TYPE value has a subclass here.
    cat = inventory.Category
    RENDER_TYPES = {
        cat.RENDER_TYPE_QUANTITY: _QuantityBoxProductsForm,
        cat.RENDER_TYPE_RADIO: _RadioButtonProductsForm,
        cat.RENDER_TYPE_ITEM_QUANTITY: _ItemQuantityProductsForm,
        cat.RENDER_TYPE_CHECKBOX: _CheckboxProductsForm,
    }

    # Produce a subclass of _ProductsForm which we can alter the base_fields on
    class ProductsForm(RENDER_TYPES[category.render_type]):
        pass

    products = list(products)
    products.sort(key=lambda prod: prod.order)

    ProductsForm.set_fields(category, products)

    if category.render_type == inventory.Category.RENDER_TYPE_ITEM_QUANTITY:
        ProductsForm = forms.formset_factory(
            ProductsForm,
            formset=_ItemQuantityProductsFormSet,
        )

    return ProductsForm


Instruction:
How would you explain what the following Python 3 function does
def staff_products_form_factory(user):
    ''' Creates a StaffProductsForm that restricts the available products to
    those that are available to a user. '''

    products = inventory.Product.objects.all()
    products = ProductController.available_products(user, products=products)

    product_ids = [product.id for product in products]
    product_set = inventory.Product.objects.filter(id__in=product_ids)

    class StaffProductsForm(forms.Form):
        ''' Form for allowing staff to add an item to a user's cart. '''

        product = forms.ModelChoiceField(
            widget=forms.Select,
            queryset=product_set,
        )

        quantity = forms.IntegerField(
            min_value=0,
        )

    return StaffProductsForm

Response:
Creates a StaffProductsForm that restricts the available products to
    those that are available to a user.


Instruction:
Here you have a function in Python 3, explain what it does
def add_product_error(self, product, error):
        ''' Adds an error to the given product's field '''

        ''' if product in field_names:
            field = field_names[product]
        elif isinstance(product, inventory.Product):
            return
        else:
            field = None '''

        self.add_error(self.field_name(product), error)

Response: Adds an error to the given product s field.


Instruction:
Make a summary of the following Python 3 code
def initial_data(cls, product_quantities):
        ''' Prepares initial data for an instance of this form.
        product_quantities is a sequence of (product,quantity) tuples '''

        f = [
            {
                _ItemQuantityProductsForm.CHOICE_FIELD: product.id,
                _ItemQuantityProductsForm.QUANTITY_FIELD: quantity,
            }
            for product, quantity in product_quantities
            if quantity > 0
        ]
        return f

Response: Prepares initial data for an instance of this form.


Instruction:
Make a summary of the following Python 3 code
def product_quantities(self):
        ''' Yields a sequence of (product, quantity) tuples from the
        cleaned form data. '''

        products = set()
        # Track everything so that we can yield some zeroes
        all_products = set()

        for form in self:
            if form.empty_permitted and not form.cleaned_data:
                # This is the magical empty form at the end of the list.
                continue

            for product, quantity in form.product_quantities():
                all_products.add(product)
                if quantity == 0:
                    continue
                if product in products:
                    form.add_error(
                        _ItemQuantityProductsForm.CHOICE_FIELD,
                        "You may only choose each product type once.",
                    )
                    form.add_error(
                        _ItemQuantityProductsForm.QUANTITY_FIELD,
                        "You may only choose each product type once.",
                    )
                products.add(product)
                yield product, quantity

        for product in (all_products - products):
            yield product, 0

Response:
Yields a sequence of tuples from the the
EffectiveProductForm cleaned form data.


Instruction:
Create a Python 3 function to
create a form for specifying fields from a model to display.

Response:
def model_fields_form_factory(model):
    ''' Creates a form for specifying fields from a model to display. '''

    fields = model._meta.get_fields()

    choices = []
    for field in fields:
        if hasattr(field, "verbose_name"):
            choices.append((field.name, field.verbose_name))

    class ModelFieldsForm(forms.Form):
        fields = forms.MultipleChoiceField(
            choices=choices,
            required=False,
        )

    return ModelFieldsForm


Instruction:
Can you implement a function in Python 3 that
returns a list of product - and - quantity pairs for all items in the cart that have purchased.

Response:
def _items(self, cart_status, category=None):
        ''' Aggregates the items that this user has purchased.

        Arguments:
            cart_status (int or Iterable(int)): etc
            category (Optional[models.inventory.Category]): the category
                of items to restrict to.

        Returns:
            [ProductAndQuantity, ...]: A list of product-quantity pairs,
                aggregating like products from across multiple invoices.

        '''

        if not isinstance(cart_status, Iterable):
            cart_status = [cart_status]

        status_query = (
            Q(productitem__cart__status=status) for status in cart_status
        )

        in_cart = Q(productitem__cart__user=self.user)
        in_cart = in_cart & reduce(operator.__or__, status_query)

        quantities_in_cart = When(
            in_cart,
            then="productitem__quantity",
        )

        quantities_or_zero = Case(
            quantities_in_cart,
            default=Value(0),
        )

        products = inventory.Product.objects

        if category:
            products = products.filter(category=category)

        products = products.select_related("category")
        products = products.annotate(quantity=Sum(quantities_or_zero))
        products = products.filter(quantity__gt=0)

        out = []
        for prod in products:
            out.append(ProductAndQuantity(prod, prod.quantity))
        return out


Instruction:
Make a summary of the following Python 3 code
def items_pending_or_purchased(self):
        ''' Returns the items that this user has purchased or has pending. '''
        status = [commerce.Cart.STATUS_PAID, commerce.Cart.STATUS_ACTIVE]
        return self._items(status)

Response: Returns the items that this user has purchased or has pending.


Instruction:
Can you generate the documentation for the following Python 3 function
def items_purchased(self, category=None):
        ''' Aggregates the items that this user has purchased.

        Arguments:
            category (Optional[models.inventory.Category]): the category
                of items to restrict to.

        Returns:
            [ProductAndQuantity, ...]: A list of product-quantity pairs,
                aggregating like products from across multiple invoices.

        '''
        return self._items(commerce.Cart.STATUS_PAID, category=category)

Response: Returns a list of items that this user has purchased.


Instruction:
Can you generate the documentation for the following Python 3 function
def send_email(self, to, kind, **kwargs):
        ''' Sends an e-mail to the given address.

        to: The address
        kind: the ID for an e-mail kind; it should point to a subdirectory of
            self.template_prefix containing subject.txt and message.html, which
            are django templates for the subject and HTML message respectively.

        context: a context for rendering the e-mail.

        '''

        return __send_email__(self.template_prefix, to, kind, **kwargs)

Response: Sends an e - mail to the given address.


Instruction:
How would you implement a function in Python 3 that
starts processing an OSM changeset stream and yield one tuple at a time to the caller.

Response:
def iter_changeset_stream(start_sqn=None, base_url='https://planet.openstreetmap.org/replication/changesets', expected_interval=60, parse_timestamps=True, state_dir=None):
    """Start processing an OSM changeset stream and yield one (action, primitive) tuple
    at a time to the caller."""

    # This is a lot like the other osm_stream except there's no
    # state file for each of the diffs, so just push ahead until
    # we run into a 404.

    # If the user specifies a state_dir, read the state from the statefile there
    if state_dir:
        if not os.path.exists(state_dir):
            raise Exception('Specified state_dir "%s" doesn\'t exist.' % state_dir)

        if os.path.exists('%s/state.yaml' % state_dir):
            with open('%s/state.yaml' % state_dir) as f:
                state = readState(f, ': ')
                start_sqn = state['sequence']

    # If no start_sqn, assume to start from the most recent changeset file
    if not start_sqn:
        u = urllib2.urlopen('%s/state.yaml' % base_url)
        state = readState(u, ': ')
        sequenceNumber = int(state['sequence'])
    else:
        sequenceNumber = int(start_sqn)

    interval_fudge = 0.0
    while True:
        sqnStr = str(sequenceNumber).zfill(9)
        url = '%s/%s/%s/%s.osm.gz' % (base_url, sqnStr[0:3], sqnStr[3:6], sqnStr[6:9])

        delay = 1.0
        while True:
            try:
                content = urllib2.urlopen(url)
                content = StringIO.StringIO(content.read())
                gzipper = gzip.GzipFile(fileobj=content)
                interval_fudge -= (interval_fudge / 2.0)
                break
            except urllib2.HTTPError as e:
                if e.code == 404:
                    time.sleep(delay)
                    delay = min(delay * 2, 13)
                    interval_fudge += delay

        obj = None
        for event, elem in etree.iterparse(gzipper, events=('start', 'end')):
            if event == 'start':
                if elem.tag == 'changeset':
                    obj = model.Changeset(
                        int(elem.attrib['id']),
                        isoToDatetime(elem.attrib.get('created_at')) if parse_timestamps else elem.attrib.get('created_at'),
                        isoToDatetime(elem.attrib.get('closed_at')) if parse_timestamps else elem.attrib.get('closed_at'),
                        maybeBool(elem.attrib['open']),
                        maybeFloat(elem.get('min_lat')),
                        maybeFloat(elem.get('max_lat')),
                        maybeFloat(elem.get('min_lon')),
                        maybeFloat(elem.get('max_lon')),
                        elem.attrib.get('user'),
                        maybeInt(elem.attrib.get('uid')),
                        []
                    )
                elif elem.tag == 'tag':
                    obj.tags.append(
                        model.Tag(
                            elem.attrib['k'],
                            elem.attrib['v']
                        )
                    )
            elif event == 'end':
                if elem.tag == 'changeset':
                    yield obj
                    obj = None

        yield model.Finished(sequenceNumber, None)

        sequenceNumber += 1

        if state_dir:
            with open('%s/state.yaml' % state_dir, 'w') as f:
                f.write('sequence: %d' % sequenceNumber)


Instruction:
Can you implement a function in Python 3 that
starts processing an OSM diff stream and yield one changeset at a time to the caller.

Response:
def iter_osm_stream(start_sqn=None, base_url='https://planet.openstreetmap.org/replication/minute', expected_interval=60, parse_timestamps=True, state_dir=None):
    """Start processing an OSM diff stream and yield one changeset at a time to
    the caller."""

    # If the user specifies a state_dir, read the state from the statefile there
    if state_dir:
        if not os.path.exists(state_dir):
            raise Exception('Specified state_dir "%s" doesn\'t exist.' % state_dir)

        if os.path.exists('%s/state.txt' % state_dir):
            with open('%s/state.txt' % state_dir) as f:
                state = readState(f)
                start_sqn = state['sequenceNumber']

    # If no start_sqn, assume to start from the most recent diff
    if not start_sqn:
        u = urllib2.urlopen('%s/state.txt' % base_url)
        state = readState(u)
    else:
        sqnStr = str(start_sqn).zfill(9)
        u = urllib2.urlopen('%s/%s/%s/%s.state.txt' % (base_url, sqnStr[0:3], sqnStr[3:6], sqnStr[6:9]))
        state = readState(u)

    interval_fudge = 0.0

    while True:
        sqnStr = state['sequenceNumber'].zfill(9)
        url = '%s/%s/%s/%s.osc.gz' % (base_url, sqnStr[0:3], sqnStr[3:6], sqnStr[6:9])
        content = urllib2.urlopen(url)
        content = StringIO.StringIO(content.read())
        gzipper = gzip.GzipFile(fileobj=content)

        for a in iter_osm_change_file(gzipper, parse_timestamps):
            yield a

        # After parsing the OSC, check to see how much time is remaining
        stateTs = datetime.datetime.strptime(state['timestamp'], "%Y-%m-%dT%H:%M:%SZ")
        yield (None, model.Finished(state['sequenceNumber'], stateTs))

        nextTs = stateTs + datetime.timedelta(seconds=expected_interval + interval_fudge)
        if datetime.datetime.utcnow() < nextTs:
            timeToSleep = (nextTs - datetime.datetime.utcnow()).total_seconds()
        else:
            timeToSleep = 0.0
        time.sleep(timeToSleep)

        # Then try to fetch the next state file
        sqnStr = str(int(state['sequenceNumber']) + 1).zfill(9)
        url = '%s/%s/%s/%s.state.txt' % (base_url, sqnStr[0:3], sqnStr[3:6], sqnStr[6:9])
        delay = 1.0
        while True:
            try:
                u = urllib2.urlopen(url)
                interval_fudge -= (interval_fudge / 2.0)
                break
            except urllib2.HTTPError as e:
                if e.code == 404:
                    time.sleep(delay)
                    delay = min(delay * 2, 13)
                    interval_fudge += delay

        if state_dir:
            with open('%s/state.txt' % state_dir, 'w') as f:
                f.write(u.read())
            with open('%s/state.txt' % state_dir, 'r') as f:
                state = readState(f)
        else:
            state = readState(u)


Instruction:
Explain what the following Python 3 code does
def parse_osm_file(f, parse_timestamps=True):

    nodes = []
    ways = []
    relations = []

    for p in iter_osm_file(f, parse_timestamps):

        if type(p) == model.Node:
            nodes.append(p)
        elif type(p) == model.Way:
            ways.append(p)
        elif type(p) == model.Relation:
            relations.append(p)

    return (nodes, ways, relations)

Response:
Parse an OSM XML file into memory and return an object with
    the nodes ways and relations it contains.


Instruction:
Create a Python 3 function for
yielding all OSM Note objects in the feed.

Response:
def iter_osm_notes(feed_limit=25, interval=60, parse_timestamps=True):
    """ Parses the global OSM Notes feed and yields as much Note information as possible. """

    last_seen_guid = None
    while True:
        u = urllib2.urlopen('https://www.openstreetmap.org/api/0.6/notes/feed?limit=%d' % feed_limit)

        tree = etree.parse(u)

        new_notes = []
        for note_item in tree.xpath('/rss/channel/item'):
            title = note_item.xpath('title')[0].text

            if title.startswith('new note ('):
                action = 'create'
            elif title.startswith('new comment ('):
                action = 'comment'
            elif title.startswith('closed note ('):
                action = 'close'

            # Note that (at least for now) the link and guid are the same in the feed.
            guid = note_item.xpath('link')[0].text

            if last_seen_guid == guid:
                break
            elif last_seen_guid == None:
                # The first time through we want the first item to be the "last seen"
                # because the RSS feed is newest-to-oldest
                last_seen_guid = guid
            else:
                note_id = int(guid.split('/')[-1].split('#c')[0])
                new_notes.append((action, get_note(note_id, parse_timestamps)))

        # We yield the reversed list because we want to yield in change order
        # (i.e. "oldest to most current")
        for note in reversed(new_notes):
            yield note

        yield model.Finished(None, None)

        time.sleep(interval)


Instruction:
Can you create a Python 3 function that
returns true if the condition passes the filter

Response:
def passes_filter(self, user):
        ''' Returns true if the condition passes the filter '''

        cls = type(self.condition)
        qs = cls.objects.filter(pk=self.condition.id)
        return self.condition in self.pre_filter(qs, user)


Instruction:
Create a Python 3 function to
return the number of items covered by this flag condition the user can add to the current cart.

Response:
def user_quantity_remaining(self, user, filtered=False):
        ''' Returns the number of items covered by this flag condition the
        user can add to the current cart. This default implementation returns
        a big number if is_met() is true, otherwise 0.

        Either this method, or is_met() must be overridden in subclasses.
        '''

        return _BIG_QUANTITY if self.is_met(user, filtered) else 0


Instruction:
Write a Python 3 function for
returning True if this flag condition is met otherwise returns False.

Response:
def is_met(self, user, filtered=False):
        ''' Returns True if this flag condition is met, otherwise returns
        False. It determines if the condition is met by calling pre_filter
        with a queryset containing only self.condition. '''

        if filtered:
            return True  # Why query again?

        return self.passes_filter(user)


Instruction:
Explain what the following Python 3 code does
def user_quantity_remaining(self, user, filtered=True):
        ''' returns 0 if the date range is violated, otherwise, it will return
        the quantity remaining under the stock limit.

        The filter for this condition must add an annotation called "remainder"
        in order for this to work.
        '''

        if filtered:
            if hasattr(self.condition, "remainder"):
                return self.condition.remainder

        # Mark self.condition with a remainder
        qs = type(self.condition).objects.filter(pk=self.condition.id)
        qs = self.pre_filter(qs, user)

        if len(qs) > 0:
            return qs[0].remainder
        else:
            return 0

Response:
returns 0 if the date range is violated otherwise it will return
        the quantity remaining under the stock limit.


Instruction:
Create a Python 3 function for
returning all of the items from queryset where the user has a product from a category from a category invoking that item s condition in one of their carts.

Response:
def pre_filter(self, queryset, user):
        ''' Returns all of the items from queryset where the user has a
        product from a category invoking that item's condition in one of their
        carts. '''

        in_user_carts = Q(
            enabling_category__product__productitem__cart__user=user
        )
        released = commerce.Cart.STATUS_RELEASED
        in_released_carts = Q(
            enabling_category__product__productitem__cart__status=released
        )
        queryset = queryset.filter(in_user_carts)
        queryset = queryset.exclude(in_released_carts)

        return queryset


Instruction:
Can you generate a brief explanation for the following Python 3 code
def pre_filter(self, queryset, user):
        ''' Returns all of the items from queryset where the user has a
        product invoking that item's condition in one of their carts. '''

        in_user_carts = Q(enabling_products__productitem__cart__user=user)
        released = commerce.Cart.STATUS_RELEASED
        paid = commerce.Cart.STATUS_PAID
        active = commerce.Cart.STATUS_ACTIVE
        in_released_carts = Q(
            enabling_products__productitem__cart__status=released
        )
        not_in_paid_or_active_carts = ~(
            Q(enabling_products__productitem__cart__status=paid) |
            Q(enabling_products__productitem__cart__status=active)
        )

        queryset = queryset.filter(in_user_carts)
        queryset = queryset.exclude(
            in_released_carts & not_in_paid_or_active_carts
        )

        return queryset

Response:
Returns all of the items from queryset where the user has a
        product invoking that item s condition in one of their carts.


Instruction:
Here you have a function in Python 3, explain what it does
def pre_filter(self, queryset, user):
        ''' Returns all of the items from queryset where the date falls into
        any specified range, but not yet where the stock limit is not yet
        reached.'''

        now = timezone.now()

        # Keep items with no start time, or start time not yet met.
        queryset = queryset.filter(Q(start_time=None) | Q(start_time__lte=now))
        queryset = queryset.filter(Q(end_time=None) | Q(end_time__gte=now))

        # Filter out items that have been reserved beyond the limits
        quantity_or_zero = self._calculate_quantities(user)

        remainder = Case(
            When(limit=None, then=Value(_BIG_QUANTITY)),
            default=F("limit") - Sum(quantity_or_zero),
        )

        queryset = queryset.annotate(remainder=remainder)
        queryset = queryset.filter(remainder__gt=0)

        return queryset

Response:
Returns all of the items from queryset where the date falls into any specified range but not yet where the stock limit is not yet
        reached.


Instruction:
Write a Python 3 script for
filtering out items which are enabled by a user being a presenter or copresenter of a non - cancelled proposal.

Response:
def pre_filter(self, queryset, user):
        ''' Returns all of the items from queryset which are enabled by a user
        being a presenter or copresenter of a non-cancelled proposal. '''

        # Filter out cancelled proposals
        queryset = queryset.filter(
            proposal_kind__proposalbase__presentation__cancelled=False
        )

        u = user
        # User is a presenter
        user_is_presenter = Q(
            is_presenter=True,
            proposal_kind__proposalbase__presentation__speaker__user=u,
        )
        # User is a copresenter
        user_is_copresenter = Q(
            is_copresenter=True,
            proposal_kind__proposalbase__presentation__additional_speakers__user=u,  # NOQA
        )

        return queryset.filter(user_is_presenter | user_is_copresenter)


Instruction:
Can you write a function in Python 3 where it
returns all items from conditions which are enabled by a Django Auth Group user being member of Django Auth Group.

Response:
def pre_filter(self, conditions, user):
        ''' Returns all of the items from conditions which are enabled by a
        user being member of a Django Auth Group. '''

        return conditions.filter(group__in=user.groups.all())


Instruction:
Create a Python 3 function to
return the user s current cart or creates a new one if there isn t one.

Response:
def for_user(cls, user):
        ''' Returns the user's current cart, or creates a new cart
        if there isn't one ready yet. '''

        try:
            existing = commerce.Cart.objects.get(
                user=user,
                status=commerce.Cart.STATUS_ACTIVE,
            )
        except ObjectDoesNotExist:
            existing = commerce.Cart.objects.create(
                user=user,
                time_last_updated=timezone.now(),
                reservation_duration=datetime.timedelta(),
            )
        return cls(existing)


Instruction:
How would you explain what the following Python 3 function does
def _autoextend_reservation(self):
        ''' Updates the cart's time last updated value, which is used to
        determine whether the cart has reserved the items and discounts it
        holds. '''

        time = timezone.now()

        # Calculate the residual of the _old_ reservation duration
        # if it's greater than what's in the cart now, keep it.
        time_elapsed_since_updated = (time - self.cart.time_last_updated)
        residual = self.cart.reservation_duration - time_elapsed_since_updated

        reservations = [datetime.timedelta(0), residual]

        # If we have vouchers, we're entitled to an hour at minimum.
        if len(self.cart.vouchers.all()) >= 1:
            reservations.append(inventory.Voucher.RESERVATION_DURATION)

        # Else, it's the maximum of the included products
        items = commerce.ProductItem.objects.filter(cart=self.cart)
        agg = items.aggregate(Max("product__reservation_duration"))
        product_max = agg["product__reservation_duration__max"]

        if product_max is not None:
            reservations.append(product_max)

        self.cart.time_last_updated = time
        self.cart.reservation_duration = max(reservations)

Response:
Updates the cart s time last updated value which is used to determine whether the cart has reserved the items and discounts it
        holds.


Instruction:
Explain what the following Python 3 code does
def _end_batch(self):
        ''' Performs operations that occur occur at the end of a batch of
        product changes/voucher applications etc.

        You need to call this after you've finished modifying the user's cart.
        This is normally done by wrapping a block of code using
        ``operations_batch``.

        '''

        self.cart.refresh_from_db()

        self._recalculate_discounts()

        self._autoextend_reservation()
        self.cart.revision += 1
        self.cart.save()

Response: Ends the batch of operations.


Instruction:
Explain what the following Python 3 code does
def extend_reservation(self, timedelta):
        ''' Extends the reservation on this cart by the given timedelta.
        This can only be done if the current state of the cart is valid (i.e
        all items and discounts in the cart are still available.)

        Arguments:
            timedelta (timedelta): The amount of time to extend the cart by.
                The resulting reservation_duration will be now() + timedelta,
                unless the requested extension is *LESS* than the current
                reservation deadline.

        '''

        self.validate_cart()
        cart = self.cart
        cart.refresh_from_db()

        elapsed = (timezone.now() - cart.time_last_updated)

        if cart.reservation_duration - elapsed > timedelta:
            return

        cart.time_last_updated = timezone.now()
        cart.reservation_duration = timedelta
        cart.save()

Response: Extends the reservation on this cart by the given timedelta.


Instruction:
How would you code a function in Python 3 to
set the quantities on each of the products on each of the theCOOKIES products specified. Raises an exception if a limit is violated.

Response:
def set_quantities(self, product_quantities):
        ''' Sets the quantities on each of the products on each of the
        products specified. Raises an exception (ValidationError) if a limit
        is violated. `product_quantities` is an iterable of (product, quantity)
        pairs. '''

        items_in_cart = commerce.ProductItem.objects.filter(cart=self.cart)
        items_in_cart = items_in_cart.select_related(
            "product",
            "product__category",
        )

        product_quantities = list(product_quantities)

        # n.b need to add have the existing items first so that the new
        # items override the old ones.
        all_product_quantities = dict(itertools.chain(
            ((i.product, i.quantity) for i in items_in_cart.all()),
            product_quantities,
        )).items()

        # Validate that the limits we're adding are OK
        products = set(product for product, q in product_quantities)
        try:
            self._test_limits(all_product_quantities)
        except CartValidationError as ve:
            # Only raise errors for products that we're explicitly
            # Manipulating here.
            for ve_field in ve.error_list:
                product, message = ve_field.message
                if product in products:
                    raise ve

        new_items = []
        products = []
        for product, quantity in product_quantities:
            products.append(product)

            if quantity == 0:
                continue

            item = commerce.ProductItem(
                cart=self.cart,
                product=product,
                quantity=quantity,
            )
            new_items.append(item)

        to_delete = (
            Q(quantity=0) |
            Q(product__in=products)
        )

        items_in_cart.filter(to_delete).delete()
        commerce.ProductItem.objects.bulk_create(new_items)


Instruction:
Can you tell what is the following Python 3 function doing
def apply_voucher(self, voucher_code):
        ''' Applies the voucher with the given code to this cart. '''

        # Try and find the voucher
        voucher = inventory.Voucher.objects.get(code=voucher_code.upper())

        # Re-applying vouchers should be idempotent
        if voucher in self.cart.vouchers.all():
            return

        self._test_voucher(voucher)

        # If successful...
        self.cart.vouchers.add(voucher)

Response: Applies the voucher with the given code to this cart.


Instruction:
Implement a function in Python 3 to
validate the status of the current cart and returns True if the status of the current cart is valid False otherwise.

Response:
def validate_cart(self):
        ''' Determines whether the status of the current cart is valid;
        this is normally called before generating or paying an invoice '''

        cart = self.cart
        user = self.cart.user
        errors = []

        try:
            self._test_vouchers(self.cart.vouchers.all())
        except ValidationError as ve:
            errors.append(ve)

        items = commerce.ProductItem.objects.filter(cart=cart)
        items = items.select_related("product", "product__category")

        product_quantities = list((i.product, i.quantity) for i in items)
        try:
            self._test_limits(product_quantities)
        except ValidationError as ve:
            self._append_errors(errors, ve)

        try:
            self._test_required_categories()
        except ValidationError as ve:
            self._append_errors(errors, ve)

        # Validate the discounts
        # TODO: refactor in terms of available_discounts
        # why aren't we doing that here?!

        #     def available_discounts(cls, user, categories, products):

        products = [i.product for i in items]
        discounts_with_quantity = DiscountController.available_discounts(
            user,
            [],
            products,
        )
        discounts = set(i.discount.id for i in discounts_with_quantity)

        discount_items = commerce.DiscountItem.objects.filter(cart=cart)
        for discount_item in discount_items:
            discount = discount_item.discount

            if discount.id not in discounts:
                errors.append(
                    ValidationError("Discounts are no longer available")
                )

        if errors:
            raise ValidationError(errors)


Instruction:
Explain what the following Python 3 code does
def _recalculate_discounts(self):
        ''' Calculates all of the discounts available for this product.'''

        # Delete the existing entries.
        commerce.DiscountItem.objects.filter(cart=self.cart).delete()

        # Order the products such that the most expensive ones are
        # processed first.
        product_items = self.cart.productitem_set.all().select_related(
            "product", "product__category"
        ).order_by("-product__price")

        products = [i.product for i in product_items]
        discounts = DiscountController.available_discounts(
            self.cart.user,
            [],
            products,
        )

        # The highest-value discounts will apply to the highest-value
        # products first, because of the order_by clause
        for item in product_items:
            self._add_discount(item.product, item.quantity, discounts)

Response: Calculates all of the discounts available for this product.


Instruction:
Can you generate the documentation for the following Python 3 function
def _add_discount(self, product, quantity, discounts):
        ''' Applies the best discounts on the given product, from the given
        discounts.'''

        def matches(discount):
            ''' Returns True if and only if the given discount apples to
            our product. '''
            if isinstance(discount.clause, conditions.DiscountForCategory):
                return discount.clause.category == product.category
            else:
                return discount.clause.product == product

        def value(discount):
            ''' Returns the value of this discount clause
            as applied to this product '''
            if discount.clause.percentage is not None:
                return discount.clause.percentage * product.price
            else:
                return discount.clause.price

        discounts = [i for i in discounts if matches(i)]
        discounts.sort(key=value)

        for candidate in reversed(discounts):
            if quantity == 0:
                break
            elif candidate.quantity == 0:
                # This discount clause has been exhausted by this cart
                continue

            # Get a provisional instance for this DiscountItem
            # with the quantity set to as much as we have in the cart
            discount_item = commerce.DiscountItem.objects.create(
                product=product,
                cart=self.cart,
                discount=candidate.discount,
                quantity=quantity,
            )

            # Truncate the quantity for this DiscountItem if we exceed quantity
            ours = discount_item.quantity
            allowed = candidate.quantity
            if ours > allowed:
                discount_item.quantity = allowed
                discount_item.save()
                # Update the remaining quantity.
                quantity = ours - allowed
            else:
                quantity = 0

            candidate.quantity -= discount_item.quantity

Response: Adds a discount clause to the given product from the given discounts.


Instruction:
Can you generate the documentation for the following Python 3 function
def rows(self, content_type):
        ''' Returns the data rows for the table. '''

        for row in self._data:
            yield [
                self.cell_text(content_type, i, cell)
                for i, cell in enumerate(row)
            ]

Response: Returns the data rows for the table.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_form(self, request):

        ''' Creates an instance of self.form_type using request.GET '''

        # Create a form instance
        if self.form_type is not None:
            form = self.form_type(request.GET)

            # Pre-validate it
            form.is_valid()
        else:
            form = None

        return form

Response: Creates an instance of self. form_type using request. GET


Instruction:
Create a Python 3 function to
wrap the reports in a _ReportTemplateWrapper for the given content_type.

Response:
def wrap_reports(cls, reports, content_type):
        ''' Wraps the reports in a _ReportTemplateWrapper for the given
        content_type -- this allows data to be returned as HTML links, for
        instance. '''

        reports = [
            _ReportTemplateWrapper(content_type, report)
            for report in reports
        ]

        return reports


Instruction:
Make a summary of the following Python 3 code
def render(self, data):
        ''' Renders the reports based on data.content_type's value.

        Arguments:
            data (ReportViewRequestData): The report data. data.content_type
                is used to determine how the reports are rendered.

        Returns:
            HTTPResponse: The rendered version of the report.

        '''
        renderers = {
            "text/csv": self._render_as_csv,
            "text/html": self._render_as_html,
            None: self._render_as_html,
        }
        render = renderers[data.content_type]
        return render(data)

Response: Renders the reports based on data. content_type.


Instruction:
Can you generate the documentation for the following Python 3 function
def reports_list(request):
    ''' Lists all of the reports currently available. '''

    reports = []

    for report in get_all_reports():
        reports.append({
            "name": report.__name__,
            "url": reverse(report),
            "description": report.__doc__,
        })

    reports.sort(key=lambda report: report["name"])

    ctx = {
        "reports": reports,
    }

    return render(request, "registrasion/reports_list.html", ctx)

Response: Lists all of the reports currently available.


Instruction:
Given the following Python 3 function, write the documentation
def items_sold():
    ''' Summarises the items sold and discounts granted for a given set of
    products, or products from categories. '''

    data = None
    headings = None

    line_items = commerce.LineItem.objects.filter(
        invoice__status=commerce.Invoice.STATUS_PAID,
    ).select_related("invoice")

    line_items = line_items.order_by(
        # sqlite requires an order_by for .values() to work
        "-price", "description",
    ).values(
        "price", "description",
    ).annotate(
        total_quantity=Sum("quantity"),
    )

    headings = ["Description", "Quantity", "Price", "Total"]

    data = []
    total_income = 0
    for line in line_items:
        cost = line["total_quantity"] * line["price"]
        data.append([
            line["description"], line["total_quantity"],
            line["price"], cost,
        ])
        total_income += cost

    data.append([
        "(TOTAL)", "--", "--", total_income,
    ])

    return ListReport("Items sold", headings, data)

Response:
Summarises the items sold and discounts granted for a given set of
    products or products from categories.


Instruction:
Can you implement a function in Python 3 that
summarises paid items and payments.

Response:
def sales_payment_summary():
    ''' Summarises paid items and payments. '''

    def value_or_zero(aggregate, key):
        return aggregate[key] or 0

    def sum_amount(payment_set):
        a = payment_set.values("amount").aggregate(total=Sum("amount"))
        return value_or_zero(a, "total")

    headings = ["Category", "Total"]
    data = []

    # Summarise all sales made (= income.)
    sales = commerce.LineItem.objects.filter(
        invoice__status=commerce.Invoice.STATUS_PAID,
    ).values(
        "price", "quantity"
    ).aggregate(
        total=Sum(F("price") * F("quantity"), output_field=CURRENCY()),
    )
    sales = value_or_zero(sales, "total")

    all_payments = sum_amount(commerce.PaymentBase.objects.all())

    # Manual payments
    # Credit notes generated (total)
    # Payments made by credit note
    # Claimed credit notes

    all_credit_notes = 0 - sum_amount(commerce.CreditNote.objects.all())
    unclaimed_credit_notes = 0 - sum_amount(commerce.CreditNote.unclaimed())
    claimed_credit_notes = sum_amount(
        commerce.CreditNoteApplication.objects.all()
    )
    refunded_credit_notes = 0 - sum_amount(commerce.CreditNote.refunded())

    data.append(["Items on paid invoices", sales])
    data.append(["All payments", all_payments])
    data.append(["Sales - Payments ", sales - all_payments])
    data.append(["All credit notes", all_credit_notes])
    data.append(["Credit notes paid on invoices", claimed_credit_notes])
    data.append(["Credit notes refunded", refunded_credit_notes])
    data.append(["Unclaimed credit notes", unclaimed_credit_notes])
    data.append([
        "Credit notes - (claimed credit notes + unclaimed credit notes)",
        all_credit_notes - claimed_credit_notes -
        refunded_credit_notes - unclaimed_credit_notes
        ])

    return ListReport("Sales and Payments Summary", headings, data)


Instruction:
Implement a Python 3 function for
showing the history of payments into the system

Response:
def payments():
    ''' Shows the history of payments into the system '''

    payments = commerce.PaymentBase.objects.all()
    return QuerysetReport(
        "Payments",
        ["invoice__id", "id", "reference", "amount"],
        payments,
        link_view=views.invoice,
    )


Instruction:
Given the following Python 3 function, write the documentation
def credit_note_refunds():
    ''' Shows all of the credit notes that have been generated. '''
    notes_refunded = commerce.CreditNote.refunded()
    return QuerysetReport(
        "Credit note refunds",
        ["id", "creditnoterefund__reference", "amount"],
        notes_refunded,
        link_view=views.credit_note,
    )

Response: Displays all of the credit notes that have been generated.


Instruction:
Make a summary of the following Python 3 code
def product_status(request, form):
    ''' Summarises the inventory status of the given items, grouping by
    invoice status. '''

    products = form.cleaned_data["product"]
    categories = form.cleaned_data["category"]

    items = commerce.ProductItem.objects.filter(
        Q(product__in=products) | Q(product__category__in=categories),
    ).select_related("cart", "product")

    items = group_by_cart_status(
        items,
        ["product__category__order", "product__order"],
        ["product", "product__category__name", "product__name"],
    )

    headings = [
        "Product", "Paid", "Reserved", "Unreserved", "Refunded",
    ]
    data = []

    for item in items:
        data.append([
            "%s - %s" % (
                item["product__category__name"], item["product__name"]
            ),
            item["total_paid"],
            item["total_reserved"],
            item["total_unreserved"],
            item["total_refunded"],
        ])

    return ListReport("Inventory", headings, data)

Response: Summarises the inventory status of the given items grouping by product status.


Instruction:
Explain what the following Python 3 code does
def discount_status(request, form):
    ''' Summarises the usage of a given discount. '''

    discounts = form.cleaned_data["discount"]

    items = commerce.DiscountItem.objects.filter(
        Q(discount__in=discounts),
    ).select_related("cart", "product", "product__category")

    items = group_by_cart_status(
        items,
        ["discount"],
        ["discount", "discount__description"],
    )

    headings = [
        "Discount", "Paid", "Reserved", "Unreserved", "Refunded",
    ]
    data = []

    for item in items:
        data.append([
            item["discount__description"],
            item["total_paid"],
            item["total_reserved"],
            item["total_unreserved"],
            item["total_refunded"],
        ])

    return ListReport("Usage by item", headings, data)

Response: Summarises the usage of a given discount.


Instruction:
How would you code a function in Python 3 to
show each product line item from invoices including their date and purchashing customer.

Response:
def product_line_items(request, form):
    ''' Shows each product line item from invoices, including their date and
    purchashing customer. '''

    products = form.cleaned_data["product"]
    categories = form.cleaned_data["category"]

    invoices = commerce.Invoice.objects.filter(
        (
            Q(lineitem__product__in=products) |
            Q(lineitem__product__category__in=categories)
        ),
        status=commerce.Invoice.STATUS_PAID,
    ).select_related(
        "cart",
        "user",
        "user__attendee",
        "user__attendee__attendeeprofilebase"
    ).order_by("issue_time")

    headings = [
        'Invoice', 'Invoice Date', 'Attendee', 'Qty', 'Product', 'Status'
    ]

    data = []
    for invoice in invoices:
        for item in invoice.cart.productitem_set.all():
            if item.product in products or item.product.category in categories:
                output = []
                output.append(invoice.id)
                output.append(invoice.issue_time.strftime('%Y-%m-%d %H:%M:%S'))
                output.append(
                    invoice.user.attendee.attendeeprofilebase.attendee_name()
                )
                output.append(item.quantity)
                output.append(item.product)
                cart = invoice.cart
                if cart.status == commerce.Cart.STATUS_PAID:
                    output.append('PAID')
                elif cart.status == commerce.Cart.STATUS_ACTIVE:
                    output.append('UNPAID')
                elif cart.status == commerce.Cart.STATUS_RELEASED:
                    output.append('REFUNDED')
                data.append(output)

    return ListReport("Line Items", headings, data)


Instruction:
Can you tell what is the following Python 3 function doing
def paid_invoices_by_date(request, form):
    ''' Shows the number of paid invoices containing given products or
    categories per day. '''

    products = form.cleaned_data["product"]
    categories = form.cleaned_data["category"]

    invoices = commerce.Invoice.objects.filter(
        (
            Q(lineitem__product__in=products) |
            Q(lineitem__product__category__in=categories)
        ),
        status=commerce.Invoice.STATUS_PAID,
    )

    # Invoices with payments will be paid at the time of their latest payment
    payments = commerce.PaymentBase.objects.all()
    payments = payments.filter(
        invoice__in=invoices,
    )
    payments = payments.order_by("invoice")
    invoice_max_time = payments.values("invoice").annotate(
        max_time=Max("time")
    )

    # Zero-value invoices will have no payments, so they're paid at issue time
    zero_value_invoices = invoices.filter(value=0)

    times = itertools.chain(
        (line["max_time"] for line in invoice_max_time),
        (invoice.issue_time for invoice in zero_value_invoices),
    )

    by_date = collections.defaultdict(int)
    for time in times:
        date = datetime.datetime(
            year=time.year, month=time.month, day=time.day
        )
        by_date[date] += 1

    data = [(date_, count) for date_, count in sorted(by_date.items())]
    data = [(date_.strftime("%Y-%m-%d"), count) for date_, count in data]

    return ListReport(
        "Paid Invoices By Date",
        ["date", "count"],
        data,
    )

Response: Displays the number of paid invoices containing given products or categories per day.


Instruction:
Explain what the following Python 3 code does
def credit_notes(request, form):
    ''' Shows all of the credit notes in the system. '''

    notes = commerce.CreditNote.objects.all().select_related(
        "creditnoterefund",
        "creditnoteapplication",
        "invoice",
        "invoice__user__attendee__attendeeprofilebase",
    )

    return QuerysetReport(
        "Credit Notes",
        ["id",
         "invoice__user__attendee__attendeeprofilebase__invoice_recipient",
         "status", "value"],
        notes,
        headings=["id", "Owner", "Status", "Value"],
        link_view=views.credit_note,
    )

Response: Displays all credit notes in the system.


Instruction:
Write a Python 3 function for
showing all of the invoices in the system.

Response:
def invoices(request, form):
    ''' Shows all of the invoices in the system. '''

    invoices = commerce.Invoice.objects.all().order_by("status", "id")

    return QuerysetReport(
        "Invoices",
        ["id", "recipient", "value", "get_status_display"],
        invoices,
        headings=["id", "Recipient", "Value", "Status"],
        link_view=views.invoice,
    )


Instruction:
Can you write a function in Python 3 where it
returns a list of all manifested attendees if no user_id is specified else displays the attendee manifest.

Response:
def attendee(request, form, user_id=None):
    ''' Returns a list of all manifested attendees if no attendee is specified,
    else displays the attendee manifest. '''

    if user_id is None and form.cleaned_data["user"] is not None:
        user_id = form.cleaned_data["user"]

    if user_id is None:
        return attendee_list(request)

    attendee = people.Attendee.objects.get(user__id=user_id)
    name = attendee.attendeeprofilebase.attendee_name()

    reports = []

    profile_data = []
    try:
        profile = people.AttendeeProfileBase.objects.get_subclass(
            attendee=attendee
        )
        fields = profile._meta.get_fields()
    except people.AttendeeProfileBase.DoesNotExist:
        fields = []

    exclude = set(["attendeeprofilebase_ptr", "id"])
    for field in fields:
        if field.name in exclude:
            # Not actually important
            continue
        if not hasattr(field, "verbose_name"):
            continue  # Not a publicly visible field
        value = getattr(profile, field.name)

        if isinstance(field, models.ManyToManyField):
            value = ", ".join(str(i) for i in value.all())

        profile_data.append((field.verbose_name, value))

    cart = CartController.for_user(attendee.user)
    reservation = cart.cart.reservation_duration + cart.cart.time_last_updated
    profile_data.append(("Current cart reserved until", reservation))

    reports.append(ListReport("Profile", ["", ""], profile_data))

    links = []
    links.append((
        reverse(views.badge, args=[user_id]),
        "View badge",
    ))
    links.append((
        reverse(views.amend_registration, args=[user_id]),
        "Amend current cart",
    ))
    links.append((
        reverse(views.extend_reservation, args=[user_id]),
        "Extend reservation",
    ))

    reports.append(Links("Actions for " + name, links))

    # Paid and pending  products
    ic = ItemController(attendee.user)
    reports.append(ListReport(
        "Paid Products",
        ["Product", "Quantity"],
        [(pq.product, pq.quantity) for pq in ic.items_purchased()],
    ))
    reports.append(ListReport(
        "Unpaid Products",
        ["Product", "Quantity"],
        [(pq.product, pq.quantity) for pq in ic.items_pending()],
    ))

    # Invoices
    invoices = commerce.Invoice.objects.filter(
        user=attendee.user,
    )
    reports.append(QuerysetReport(
        "Invoices",
        ["id", "get_status_display", "value"],
        invoices,
        headings=["Invoice ID", "Status", "Value"],
        link_view=views.invoice,
    ))

    # Credit Notes
    credit_notes = commerce.CreditNote.objects.filter(
        invoice__user=attendee.user,
    ).select_related("invoice", "creditnoteapplication", "creditnoterefund")

    reports.append(QuerysetReport(
        "Credit Notes",
        ["id", "status", "value"],
        credit_notes,
        link_view=views.credit_note,
    ))

    # All payments
    payments = commerce.PaymentBase.objects.filter(
        invoice__user=attendee.user,
    ).select_related("invoice")

    reports.append(QuerysetReport(
        "Payments",
        ["invoice__id", "id", "reference", "amount"],
        payments,
        link_view=views.invoice,
    ))

    return reports


Instruction:
Explain what the following Python 3 code does
def attendee_list(request):
    ''' Returns a list of all attendees. '''

    attendees = people.Attendee.objects.select_related(
        "attendeeprofilebase",
        "user",
    )

    profiles = AttendeeProfile.objects.filter(
        attendee__in=attendees
    ).select_related(
        "attendee", "attendee__user",
    )
    profiles_by_attendee = dict((i.attendee, i) for i in profiles)

    attendees = attendees.annotate(
        has_registered=Count(
            Q(user__invoice__status=commerce.Invoice.STATUS_PAID)
        ),
    )

    headings = [
        "User ID", "Name", "Email", "Has registered",
    ]

    data = []

    for a in attendees:
        data.append([
            a.user.id,
            (profiles_by_attendee[a].attendee_name()
                if a in profiles_by_attendee else ""),
            a.user.email,
            a.has_registered > 0,
        ])

    # Sort by whether they've registered, then ID.
    data.sort(key=lambda a: (-a[3], a[0]))

    return AttendeeListReport("Attendees", headings, data, link_view=attendee)

Response: Returns a list of all attendees.


Instruction:
Create a Python 3 function to
list attendees for a given product category selection along with profile data.

Response:
def attendee_data(request, form, user_id=None):
    ''' Lists attendees for a given product/category selection along with
    profile data.'''

    status_display = {
        commerce.Cart.STATUS_ACTIVE: "Unpaid",
        commerce.Cart.STATUS_PAID: "Paid",
        commerce.Cart.STATUS_RELEASED: "Refunded",
    }

    output = []

    by_category = (
        form.cleaned_data["group_by"] == forms.GroupByForm.GROUP_BY_CATEGORY)

    products = form.cleaned_data["product"]
    categories = form.cleaned_data["category"]
    fields = form.cleaned_data["fields"]
    name_field = AttendeeProfile.name_field()

    items = commerce.ProductItem.objects.filter(
        Q(product__in=products) | Q(product__category__in=categories),
    ).exclude(
        cart__status=commerce.Cart.STATUS_RELEASED
    ).select_related(
        "cart", "cart__user", "product", "product__category",
    ).order_by("cart__status")

    # Add invoice nag link
    links = []
    invoice_mailout = reverse(views.invoice_mailout, args=[])
    invoice_mailout += "?" + request.META["QUERY_STRING"]
    links += [
        (invoice_mailout + "&status=1", "Send invoice reminders",),
        (invoice_mailout + "&status=2", "Send mail for paid invoices",),
    ]

    if items.count() > 0:
        output.append(Links("Actions", links))

    # Make sure we select all of the related fields
    related_fields = set(
        field for field in fields
        if isinstance(AttendeeProfile._meta.get_field(field), RelatedField)
    )

    # Get all of the relevant attendee profiles in one hit.
    profiles = AttendeeProfile.objects.filter(
        attendee__user__cart__productitem__in=items
    ).select_related("attendee__user").prefetch_related(*related_fields)
    by_user = {}
    for profile in profiles:
        by_user[profile.attendee.user] = profile

    cart = "attendee__user__cart"
    cart_status = cart + "__status"  # noqa
    product = cart + "__productitem__product"
    product_name = product + "__name"
    category = product + "__category"
    category_name = category + "__name"

    if by_category:
        grouping_fields = (category, category_name)
        order_by = (category, )
        first_column = "Category"
        group_name = lambda i: "%s" % (i[category_name], )  # noqa
    else:
        grouping_fields = (product, product_name, category_name)
        order_by = (category, )
        first_column = "Product"
        group_name = lambda i: "%s - %s" % (i[category_name], i[product_name])  # noqa

    # Group the responses per-field.
    for field in fields:
        concrete_field = AttendeeProfile._meta.get_field(field)
        field_verbose = concrete_field.verbose_name

        # Render the correct values for related fields
        if field in related_fields:
            # Get all of the IDs that will appear
            all_ids = profiles.order_by(field).values(field)
            all_ids = [i[field] for i in all_ids if i[field] is not None]
            # Get all of the concrete objects for those IDs
            model = concrete_field.related_model
            all_objects = model.objects.filter(id__in=all_ids)
            all_objects_by_id = dict((i.id, i) for i in all_objects)

            # Define a function to render those IDs.
            def display_field(value):
                if value in all_objects_by_id:
                    return all_objects_by_id[value]
                else:
                    return None
        else:
            def display_field(value):
                return value

        status_count = lambda status: Case(When(  # noqa
                attendee__user__cart__status=status,
                then=Value(1),
            ),
            default=Value(0),
            output_field=models.fields.IntegerField(),
        )
        paid_count = status_count(commerce.Cart.STATUS_PAID)
        unpaid_count = status_count(commerce.Cart.STATUS_ACTIVE)

        groups = profiles.order_by(
            *(order_by + (field, ))
        ).values(
            *(grouping_fields + (field, ))
        ).annotate(
            paid_count=Sum(paid_count),
            unpaid_count=Sum(unpaid_count),
        )
        output.append(ListReport(
            "Grouped by %s" % field_verbose,
            [first_column, field_verbose, "paid", "unpaid"],
            [
                (
                    group_name(group),
                    display_field(group[field]),
                    group["paid_count"] or 0,
                    group["unpaid_count"] or 0,
                )
                for group in groups
            ],
        ))

    # DO the report for individual attendees

    field_names = [
        AttendeeProfile._meta.get_field(field).verbose_name for field in fields
    ]

    def display_field(profile, field):
        field_type = AttendeeProfile._meta.get_field(field)
        attr = getattr(profile, field)

        if isinstance(field_type, models.ManyToManyField):
            return [str(i) for i in attr.all()] or ""
        else:
            return attr

    headings = ["User ID", "Name", "Email", "Product", "Item Status"]
    headings.extend(field_names)
    data = []
    for item in items:
        profile = by_user[item.cart.user]
        line = [
            item.cart.user.id,
            getattr(profile, name_field),
            profile.attendee.user.email,
            item.product,
            status_display[item.cart.status],
        ] + [
            display_field(profile, field) for field in fields
        ]
        data.append(line)

    output.append(AttendeeListReport(
        "Attendees by item with profile data", headings, data,
        link_view=attendee
    ))
    return output


Instruction:
How would you code a function in Python 3 to
show registration status for speakers with a given proposal kind.

Response:
def speaker_registrations(request, form):
    ''' Shows registration status for speakers with a given proposal kind. '''

    kinds = form.cleaned_data["kind"]

    presentations = schedule_models.Presentation.objects.filter(
        proposal_base__kind__in=kinds,
    ).exclude(
        cancelled=True,
    )

    users = User.objects.filter(
        Q(speaker_profile__presentations__in=presentations) |
        Q(speaker_profile__copresentations__in=presentations)
    )

    paid_carts = commerce.Cart.objects.filter(status=commerce.Cart.STATUS_PAID)

    paid_carts = Case(
        When(cart__in=paid_carts, then=Value(1)),
        default=Value(0),
        output_field=models.IntegerField(),
    )
    users = users.annotate(paid_carts=Sum(paid_carts))
    users = users.order_by("paid_carts")

    return QuerysetReport(
        "Speaker Registration Status",
        ["id", "speaker_profile__name", "email", "paid_carts"],
        users,
        link_view=attendee,
    )

    return []


Instruction:
Here you have a function in Python 3, explain what it does
def manifest(request, form):
    '''
    Produces the registration manifest for people with the given product
    type.
    '''

    products = form.cleaned_data["product"]
    categories = form.cleaned_data["category"]

    line_items = (
        Q(lineitem__product__in=products) |
        Q(lineitem__product__category__in=categories)
    )

    invoices = commerce.Invoice.objects.filter(
        line_items,
        status=commerce.Invoice.STATUS_PAID,
    ).select_related(
        "cart",
        "user",
        "user__attendee",
        "user__attendee__attendeeprofilebase"
    )

    users = set(i.user for i in invoices)

    carts = commerce.Cart.objects.filter(
        user__in=users
    )

    items = commerce.ProductItem.objects.filter(
        cart__in=carts
    ).select_related(
        "product",
        "product__category",
        "cart",
        "cart__user",
        "cart__user__attendee",
        "cart__user__attendee__attendeeprofilebase"
    ).order_by("product__category__order", "product__order")

    users = {}

    for item in items:
        cart = item.cart
        if cart.user not in users:
            users[cart.user] = {"unpaid": [], "paid": [], "refunded": []}
        items = users[cart.user]
        if cart.status == commerce.Cart.STATUS_ACTIVE:
            items["unpaid"].append(item)
        elif cart.status == commerce.Cart.STATUS_PAID:
            items["paid"].append(item)
        elif cart.status == commerce.Cart.STATUS_RELEASED:
            items["refunded"].append(item)

    users_by_name = list(users.keys())
    users_by_name.sort(key=(
        lambda i: i.attendee.attendeeprofilebase.attendee_name().lower()
    ))

    headings = ["User ID", "Name", "Paid", "Unpaid", "Refunded"]

    def format_items(item_list):
        strings = [
            '%d x %s' % (item.quantity, str(item.product))
            for item in item_list
        ]
        return ", \n".join(strings)

    output = []
    for user in users_by_name:
        items = users[user]
        output.append([
            user.id,
            user.attendee.attendeeprofilebase.attendee_name(),
            format_items(items["paid"]),
            format_items(items["unpaid"]),
            format_items(items["refunded"]),
        ])

    return ListReport("Manifest", headings, output)

Response:
Generates the registration manifest for people with the given product
    type.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def missing_categories(context):
    ''' Adds the categories that the user does not currently have. '''
    user = user_for_context(context)
    categories_available = set(CategoryController.available_categories(user))
    items = ItemController(user).items_pending_or_purchased()

    categories_held = set()

    for product, quantity in items:
        categories_held.add(product.category)

    return categories_available - categories_held

Response: Adds the categories that the user does not currently have.


Instruction:
Given the following Python 3 function, write the documentation
def available_credit(context):
    ''' Calculates the sum of unclaimed credit from this user's credit notes.

    Returns:
        Decimal: the sum of the values of unclaimed credit notes for the
            current user.

    '''

    notes = commerce.CreditNote.unclaimed().filter(
        invoice__user=user_for_context(context),
    )
    ret = notes.values("amount").aggregate(Sum("amount"))["amount__sum"] or 0
    return 0 - ret

Response: Calculates the sum of unclaimed credit from this user s credit notes.


Instruction:
Write a Python 3 function that can
return the total number of items purchased for this user.

Response:
def total_items_purchased(context, category=None):
    ''' Returns the number of items purchased for this user (sum of quantities).

    The user will be either `context.user`, and `context.request.user` if
    the former is not defined.
    '''

    return sum(i.quantity for i in items_purchased(context, category))


Instruction:
Create a Python 3 function for
returning True if the current user s sold out and unregistered products.

Response:
def sold_out_and_unregistered(context):
    ''' If the current user is unregistered, returns True if there are no
    products in the TICKET_PRODUCT_CATEGORY that are available to that user.

    If there *are* products available, the return False.

    If the current user *is* registered, then return None (it's not a
    pertinent question for people who already have a ticket).

    '''

    user = user_for_context(context)
    if hasattr(user, "attendee") and user.attendee.completed_registration:
        # This user has completed registration, and so we don't need to answer
        # whether they have sold out yet.

        # TODO: what if a user has got to the review phase?
        # currently that user will hit the review page, click "Check out and
        # pay", and that will fail. Probably good enough for now.

        return None

    ticket_category = settings.TICKET_PRODUCT_CATEGORY
    categories = available_categories(context)

    return ticket_category not in [cat.id for cat in categories]


Instruction:
Can you generate a brief explanation for the following Python 3 code
def include_if_exists(parser, token):
    try:
        tag_name, template_name = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError, \
            "%r tag requires a single argument" % token.contents.split()[0]

    return IncludeNode(template_name)

Response: Include the current page if it exists.


Instruction:
Can you write a function in Python 3 where it
goes through the registration process in order, making sure user sees all valid categories. The user must be logged in to see this view. Parameter: page_number: 1) Profile form (and e-mail address?) 2) Ticket type 3) Remaining products 4) Mark registration as complete Returns: render: Renders ``registrasion/guided_registration.html``, with the following data:: { "current_step": int(), # The current step in the # registration "sections": sections, # A list of # GuidedRegistrationSections "title": str(), # The title of the page "total_steps": int(), # The total number of steps }

Response:
def guided_registration(request, page_number=None):
    ''' Goes through the registration process in order, making sure user sees
    all valid categories.

    The user must be logged in to see this view.

    Parameter:
        page_number:
            1) Profile form (and e-mail address?)
            2) Ticket type
            3) Remaining products
            4) Mark registration as complete

    Returns:
        render: Renders ``registrasion/guided_registration.html``,
            with the following data::

                {
                    "current_step": int(),  # The current step in the
                                            # registration
                    "sections": sections,   # A list of
                                            # GuidedRegistrationSections
                    "title": str(),         # The title of the page
                    "total_steps": int(),   # The total number of steps
                }

    '''

    PAGE_PROFILE = 1
    PAGE_TICKET = 2
    PAGE_PRODUCTS = 3
    PAGE_PRODUCTS_MAX = 4
    TOTAL_PAGES = 4

    ticket_category = inventory.Category.objects.get(
        id=settings.TICKET_PRODUCT_CATEGORY
    )
    cart = CartController.for_user(request.user)

    attendee = people.Attendee.get_instance(request.user)

    # This guided registration process is only for people who have
    # not completed registration (and has confusing behaviour if you go
    # back to it.)
    if attendee.completed_registration:
        return redirect(review)

    # Calculate the current maximum page number for this user.
    has_profile = hasattr(attendee, "attendeeprofilebase")
    if not has_profile:
        # If there's no profile, they have to go to the profile page.
        max_page = PAGE_PROFILE
        redirect_page = PAGE_PROFILE
    else:
        # We have a profile.
        # Do they have a ticket?
        products = inventory.Product.objects.filter(
            productitem__cart=cart.cart
        )
        products = products.filter(category=ticket_category)

        if products.count() == 0:
            # If no ticket, they can only see the profile or ticket page.
            max_page = PAGE_TICKET
            redirect_page = PAGE_TICKET
        else:
            # If there's a ticket, they should *see* the general products page#
            # but be able to go to the overflow page if needs be.
            max_page = PAGE_PRODUCTS_MAX
            redirect_page = PAGE_PRODUCTS

    if page_number is None or int(page_number) > max_page:
        return redirect("guided_registration", redirect_page)

    page_number = int(page_number)

    next_step = redirect("guided_registration", page_number + 1)

    with BatchController.batch(request.user):

        # This view doesn't work if the conference has sold out.
        available = ProductController.available_products(
            request.user, category=ticket_category
        )
        if not available:
            messages.error(request, "There are no more tickets available.")
            return redirect("dashboard")

        sections = []

        # Build up the list of sections
        if page_number == PAGE_PROFILE:
            # Profile bit
            title = "Attendee information"
            sections = _guided_registration_profile_and_voucher(request)
        elif page_number == PAGE_TICKET:
            # Select ticket
            title = "Select ticket type"
            sections = _guided_registration_products(
                request, GUIDED_MODE_TICKETS_ONLY
            )
        elif page_number == PAGE_PRODUCTS:
            # Select additional items
            title = "Additional items"
            sections = _guided_registration_products(
                request, GUIDED_MODE_ALL_ADDITIONAL
            )
        elif page_number == PAGE_PRODUCTS_MAX:
            # Items enabled by things on page 3 -- only shows things
            # that have not been marked as complete.
            title = "More additional items"
            sections = _guided_registration_products(
                request, GUIDED_MODE_EXCLUDE_COMPLETE
            )

        if not sections:
            # We've filled in every category
            attendee.completed_registration = True
            attendee.save()
            return redirect("review")

        if sections and request.method == "POST":
            for section in sections:
                if section.form.errors:
                    break
            else:
                # We've successfully processed everything
                return next_step

    data = {
        "current_step": page_number,
        "sections": sections,
        "title": title,
        "total_steps": TOTAL_PAGES,
    }
    return render(request, "registrasion/guided_registration.html", data)


Instruction:
How would you code a function in Python 3 to
view for editing an attendee s profile.

Response:
def edit_profile(request):
    ''' View for editing an attendee's profile

    The user must be logged in to edit their profile.

    Returns:
        redirect or render:
            In the case of a ``POST`` request, it'll redirect to ``dashboard``,
            or otherwise, it will render ``registrasion/profile_form.html``
            with data::

                {
                    "form": form,  # Instance of ATTENDEE_PROFILE_FORM.
                }

    '''

    form, handled = _handle_profile(request, "profile")

    if handled and not form.errors:
        messages.success(
            request,
            "Your attendee profile was updated.",
        )
        return redirect("dashboard")

    data = {
        "form": form,
    }
    return render(request, "registrasion/profile_form.html", data)


Instruction:
How would you explain what the following Python 3 function does
def _handle_profile(request, prefix):
    ''' Returns a profile form instance, and a boolean which is true if the
    form was handled. '''
    attendee = people.Attendee.get_instance(request.user)

    try:
        profile = attendee.attendeeprofilebase
        profile = people.AttendeeProfileBase.objects.get_subclass(
            pk=profile.id,
        )
    except ObjectDoesNotExist:
        profile = None

    # Load a pre-entered name from the speaker's profile,
    # if they have one.
    try:
        speaker_profile = request.user.speaker_profile
        speaker_name = speaker_profile.name
    except ObjectDoesNotExist:
        speaker_name = None

    name_field = ProfileForm.Meta.model.name_field()
    initial = {}
    if profile is None and name_field is not None:
        initial[name_field] = speaker_name

    form = ProfileForm(
        request.POST or None,
        initial=initial,
        instance=profile,
        prefix=prefix
    )

    handled = True if request.POST else False

    if request.POST and form.is_valid():
        form.instance.attendee = attendee
        form.save()

    return form, handled

Response: Returns a profile form instance and a boolean which is true if the profile form was handled.