Instruction:
Create a Python 3 function to
handle the DELETE request for a single - course consent record.

Response:
def delete(self, request):
        """
        DELETE /consent/api/v1/data_sharing_consent

        Requires a JSON object of the following format:
        >>> {
        >>>     "username": "bob",
        >>>     "course_id": "course-v1:edX+DemoX+Demo_Course",
        >>>     "enterprise_customer_uuid": "enterprise-uuid-goes-right-here"
        >>> }

        Keys:
        *username*
            The edX username from whom to get consent.
        *course_id*
            The course for which consent is granted.
        *enterprise_customer_uuid*
            The UUID of the enterprise customer that requires consent.
        """
        try:
            consent_record = self.get_consent_record(request)
            if consent_record is None:
                return self.get_no_record_response(request)

            # We're fine with proactively refusing consent, even when there's no actual
            # requirement for consent yet.
            consent_record.granted = False

            # Models don't have return values when saving, but ProxyDataSharingConsent
            # objects do - they should return either a model instance, or another instance
            # of ProxyDataSharingConsent if representing a multi-course consent record.
            consent_record = consent_record.save() or consent_record

        except ConsentAPIRequestError as invalid_request:
            return Response({'error': str(invalid_request)}, status=HTTP_400_BAD_REQUEST)

        return Response(consent_record.serialize())


Instruction:
Here you have a function in Python 3, explain what it does
def ready(self):
        from enterprise.signals import handle_user_post_save
        from django.db.models.signals import pre_migrate, post_save

        post_save.connect(handle_user_post_save, sender=self.auth_user_model, dispatch_uid=USER_POST_SAVE_DISPATCH_UID)
        pre_migrate.connect(self._disconnect_user_post_save_for_migrations)

Response: Connect the user post - save signals to the user model.


Instruction:
Can you tell what is the following Python 3 function doing
def _disconnect_user_post_save_for_migrations(self, sender, **kwargs):  # pylint: disable=unused-argument
        from django.db.models.signals import post_save
        post_save.disconnect(sender=self.auth_user_model, dispatch_uid=USER_POST_SAVE_DISPATCH_UID)

Response: Disconnects user post save signal for migrations.


Instruction:
Make a summary of the following Python 3 code
def get_actor(self, username, email):
        return Agent(
            name=username,
            mbox='mailto:{email}'.format(email=email),
        )

Response: Get actor for the statement.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_object(self, name, description):
        return Activity(
            id=X_API_ACTIVITY_COURSE,
            definition=ActivityDefinition(
                name=LanguageMap({'en-US': (name or '').encode("ascii", "ignore").decode('ascii')}),
                description=LanguageMap({'en-US': (description or '').encode("ascii", "ignore").decode('ascii')}),
            ),
        )

Response: Get object for the statement.


Instruction:
Can you tell what is the following Python 3 function doing
def parse_csv(file_stream, expected_columns=None):
    reader = unicodecsv.DictReader(file_stream, encoding="utf-8")

    if expected_columns and set(expected_columns) - set(reader.fieldnames):
        raise ValidationError(ValidationMessages.MISSING_EXPECTED_COLUMNS.format(
            expected_columns=", ".join(expected_columns), actual_columns=", ".join(reader.fieldnames)
        ))

    # "yield from reader" would be nicer, but we're on python2.7 yet.
    for row in reader:
        yield row

Response: Parse a CSV file and return a stream of dictionaries representing each row.


Instruction:
Write a Python 3 script to
validate that the user email to be linked to the Enterprise Customer record.

Response:
def validate_email_to_link(email, raw_email=None, message_template=None, ignore_existing=False):
    """
    Validate email to be linked to Enterprise Customer.

    Performs two checks:
        * Checks that email is valid
        * Checks that it is not already linked to any Enterprise Customer

    Arguments:
        email (str): user email to link
        raw_email (str): raw value as it was passed by user - used in error message.
        message_template (str): Validation error template string.
        ignore_existing (bool): If True to skip the check for an existing Enterprise Customer

    Raises:
        ValidationError: if email is invalid or already linked to Enterprise Customer.

    Returns:
        bool: Whether or not there is an existing record with the same email address.
    """
    raw_email = raw_email if raw_email is not None else email
    message_template = message_template if message_template is not None else ValidationMessages.INVALID_EMAIL
    try:
        validate_email(email)
    except ValidationError:
        raise ValidationError(message_template.format(argument=raw_email))

    existing_record = EnterpriseCustomerUser.objects.get_link_by_email(email)
    if existing_record and not ignore_existing:
        raise ValidationError(ValidationMessages.USER_ALREADY_REGISTERED.format(
            email=email, ec_name=existing_record.enterprise_customer.name
        ))
    return existing_record or False


Instruction:
How would you explain what the following Python 3 function does
def get_course_runs_from_program(program):
    course_runs = set()
    for course in program.get("courses", []):
        for run in course.get("course_runs", []):
            if "key" in run and run["key"]:
                course_runs.add(run["key"])

    return course_runs

Response: Returns a set of all course runs in a given program


Instruction:
Given the following Python 3 function, write the documentation
def get_earliest_start_date_from_program(program):
    start_dates = []
    for course in program.get('courses', []):
        for run in course.get('course_runs', []):
            if run.get('start'):
                start_dates.append(parse_lms_api_datetime(run['start']))
    if not start_dates:
        return None
    return min(start_dates)

Response: Get the earliest start date from a program


Instruction:
Implement a Python 3 function for
returning a paginated list of the objects in the object_list.

Response:
def paginated_list(object_list, page, page_size=25):
    """
    Returns paginated list.

    Arguments:
        object_list (QuerySet): A list of records to be paginated.
        page (int): Current page number.
        page_size (int): Number of records displayed in each paginated set.
        show_all (bool): Whether to show all records.

    Adopted from django/contrib/admin/templatetags/admin_list.py
    https://github.com/django/django/blob/1.11.1/django/contrib/admin/templatetags/admin_list.py#L50
    """
    paginator = CustomPaginator(object_list, page_size)
    try:
        object_list = paginator.page(page)
    except PageNotAnInteger:
        object_list = paginator.page(1)
    except EmptyPage:
        object_list = paginator.page(paginator.num_pages)

    page_range = []
    page_num = object_list.number

    # If there are 10 or fewer pages, display links to every page.
    # Otherwise, do some fancy
    if paginator.num_pages <= 10:
        page_range = range(paginator.num_pages)
    else:
        # Insert "smart" pagination links, so that there are always ON_ENDS
        # links at either end of the list of pages, and there are always
        # ON_EACH_SIDE links at either end of the "current page" link.
        if page_num > (PAGES_ON_EACH_SIDE + PAGES_ON_ENDS + 1):
            page_range.extend(range(1, PAGES_ON_ENDS + 1))
            page_range.append(DOT)
            page_range.extend(range(page_num - PAGES_ON_EACH_SIDE, page_num + 1))
        else:
            page_range.extend(range(1, page_num + 1))
        if page_num < (paginator.num_pages - PAGES_ON_EACH_SIDE - PAGES_ON_ENDS):
            page_range.extend(range(page_num + 1, page_num + PAGES_ON_EACH_SIDE + 1))
            page_range.append(DOT)
            page_range.extend(range(paginator.num_pages + 1 - PAGES_ON_ENDS, paginator.num_pages + 1))
        else:
            page_range.extend(range(page_num + 1, paginator.num_pages + 1))

        # Override page range to implement custom smart links.
        object_list.paginator.page_range = page_range

    return object_list


Instruction:
Make a summary of the following Python 3 code
def clean_email_or_username(self):
        email_or_username = self.cleaned_data[self.Fields.EMAIL_OR_USERNAME].strip()

        if not email_or_username:
            # The field is blank; we just return the existing blank value.
            return email_or_username

        email = email_or_username__to__email(email_or_username)
        bulk_entry = len(split_usernames_and_emails(email)) > 1
        if bulk_entry:
            for email in split_usernames_and_emails(email):
                validate_email_to_link(
                    email,
                    None,
                    ValidationMessages.INVALID_EMAIL_OR_USERNAME,
                    ignore_existing=True
                )
            email = email_or_username
        else:
            validate_email_to_link(
                email,
                email_or_username,
                ValidationMessages.INVALID_EMAIL_OR_USERNAME,
                ignore_existing=True
            )

        return email

Response: Clean email form field


Instruction:
Write a Python 3 script for
verifying course ID and retrieve course details.

Response:
def clean_course(self):
        """
        Verify course ID and retrieve course details.
        """
        course_id = self.cleaned_data[self.Fields.COURSE].strip()
        if not course_id:
            return None
        try:
            client = EnrollmentApiClient()
            return client.get_course_details(course_id)
        except (HttpClientError, HttpServerError):
            raise ValidationError(ValidationMessages.INVALID_COURSE_ID.format(course_id=course_id))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def clean_program(self):
        program_id = self.cleaned_data[self.Fields.PROGRAM].strip()
        if not program_id:
            return None

        try:
            client = CourseCatalogApiClient(self._user, self._enterprise_customer.site)
            program = client.get_program_by_uuid(program_id) or client.get_program_by_title(program_id)
        except MultipleProgramMatchError as exc:
            raise ValidationError(ValidationMessages.MULTIPLE_PROGRAM_MATCH.format(program_count=exc.programs_matched))
        except (HttpClientError, HttpServerError):
            raise ValidationError(ValidationMessages.INVALID_PROGRAM_ID.format(program_id=program_id))

        if not program:
            raise ValidationError(ValidationMessages.INVALID_PROGRAM_ID.format(program_id=program_id))

        if program['status'] != ProgramStatuses.ACTIVE:
            raise ValidationError(
                ValidationMessages.PROGRAM_IS_INACTIVE.format(program_id=program_id, status=program['status'])
            )

        return program

Response: Try obtaining program from CourseCatalog API and return it.


Instruction:
Create a Python 3 function for
cleaning the notify_on_enrollment field.

Response:
def clean_notify(self):
        """
        Clean the notify_on_enrollment field.
        """
        return self.cleaned_data.get(self.Fields.NOTIFY, self.NotificationTypes.DEFAULT)


Instruction:
Can you write a function in Python 3 where it
cleans fields that depend on each other. In this case, the form can be used to link single user or bulk link multiple users. These are mutually exclusive modes, so this method checks that only one field is passed.

Response:
def clean(self):
        """
        Clean fields that depend on each other.

        In this case, the form can be used to link single user or bulk link multiple users. These are mutually
        exclusive modes, so this method checks that only one field is passed.
        """
        cleaned_data = super(ManageLearnersForm, self).clean()

        # Here we take values from `data` (and not `cleaned_data`) as we need raw values - field clean methods
        # might "invalidate" the value and set it to None, while all we care here is if it was provided at all or not
        email_or_username = self.data.get(self.Fields.EMAIL_OR_USERNAME, None)
        bulk_upload_csv = self.files.get(self.Fields.BULK_UPLOAD, None)

        if not email_or_username and not bulk_upload_csv:
            raise ValidationError(ValidationMessages.NO_FIELDS_SPECIFIED)

        if email_or_username and bulk_upload_csv:
            raise ValidationError(ValidationMessages.BOTH_FIELDS_SPECIFIED)

        if email_or_username:
            mode = self.Modes.MODE_SINGULAR
        else:
            mode = self.Modes.MODE_BULK

        cleaned_data[self.Fields.MODE] = mode
        cleaned_data[self.Fields.NOTIFY] = self.clean_notify()

        self._validate_course()
        self._validate_program()

        if self.data.get(self.Fields.PROGRAM, None) and self.data.get(self.Fields.COURSE, None):
            raise ValidationError(ValidationMessages.COURSE_AND_PROGRAM_ERROR)

        return cleaned_data


Instruction:
How would you explain what the following Python 3 function does
def _validate_course(self):
        # Verify that the selected mode is valid for the given course .
        course_details = self.cleaned_data.get(self.Fields.COURSE)
        if course_details:
            course_mode = self.cleaned_data.get(self.Fields.COURSE_MODE)
            if not course_mode:
                raise ValidationError(ValidationMessages.COURSE_WITHOUT_COURSE_MODE)
            valid_course_modes = course_details["course_modes"]
            if all(course_mode != mode["slug"] for mode in valid_course_modes):
                error = ValidationError(ValidationMessages.COURSE_MODE_INVALID_FOR_COURSE.format(
                    course_mode=course_mode,
                    course_id=course_details["course_id"],
                ))
                raise ValidationError({self.Fields.COURSE_MODE: error})

Response: Validate that the selected mode is valid for the given course.


Instruction:
Can you tell what is the following Python 3 function doing
def _validate_program(self):
        program = self.cleaned_data.get(self.Fields.PROGRAM)
        if not program:
            return

        course_runs = get_course_runs_from_program(program)
        try:
            client = CourseCatalogApiClient(self._user, self._enterprise_customer.site)
            available_modes = client.get_common_course_modes(course_runs)
            course_mode = self.cleaned_data.get(self.Fields.COURSE_MODE)
        except (HttpClientError, HttpServerError):
            raise ValidationError(
                ValidationMessages.FAILED_TO_OBTAIN_COURSE_MODES.format(program_title=program.get("title"))
            )

        if not course_mode:
            raise ValidationError(ValidationMessages.COURSE_WITHOUT_COURSE_MODE)
        if course_mode not in available_modes:
            raise ValidationError(ValidationMessages.COURSE_MODE_NOT_AVAILABLE.format(
                mode=course_mode, program_title=program.get("title"), modes=", ".join(available_modes)
            ))

Response: Validate that the selected mode is available for the program and all courses in the program.


Instruction:
Implement a Python 3 function for
retrieving a list of catalog ID and name pairs.

Response:
def get_catalog_options(self):
        """
        Retrieve a list of catalog ID and name pairs.

        Once retrieved, these name pairs can be used directly as a value
        for the `choices` argument to a ChoiceField.
        """
        # TODO: We will remove the discovery service catalog implementation
        # once we have fully migrated customer's to EnterpriseCustomerCatalogs.
        # For now, this code will prevent an admin from creating a new
        # EnterpriseCustomer with a discovery service catalog. They will have to first
        # save the EnterpriseCustomer admin form and then edit the EnterpriseCustomer
        # to add a discovery service catalog.
        if hasattr(self.instance, 'site'):
            catalog_api = CourseCatalogApiClient(self.user, self.instance.site)
        else:
            catalog_api = CourseCatalogApiClient(self.user)
        catalogs = catalog_api.get_all_catalogs()
        # order catalogs by name.
        catalogs = sorted(catalogs, key=lambda catalog: catalog.get('name', '').lower())

        return BLANK_CHOICE_DASH + [
            (catalog['id'], catalog['name'],)
            for catalog in catalogs
        ]


Instruction:
Can you tell what is the following Python 3 function doing
def clean(self):
        cleaned_data = super(EnterpriseCustomerAdminForm, self).clean()
        if 'catalog' in cleaned_data and not cleaned_data['catalog']:
            cleaned_data['catalog'] = None
        return cleaned_data

Response: Clean the data prior to database entry.


Instruction:
Here you have a function in Python 3, explain what it does
def clean(self):
        super(EnterpriseCustomerIdentityProviderAdminForm, self).clean()

        provider_id = self.cleaned_data.get('provider_id', None)
        enterprise_customer = self.cleaned_data.get('enterprise_customer', None)

        if provider_id is None or enterprise_customer is None:
            # field validation for either provider_id or enterprise_customer has already raised
            # a validation error.
            return

        identity_provider = utils.get_identity_provider(provider_id)
        if not identity_provider:
            # This should not happen, as identity providers displayed in drop down are fetched dynamically.
            message = _(
                "The specified Identity Provider does not exist. For more "
                "information, contact a system administrator.",
            )
            # Log message for debugging
            logger.exception(message)

            raise ValidationError(message)

        if identity_provider and identity_provider.site != enterprise_customer.site:
            raise ValidationError(
                _(
                    "The site for the selected identity provider "
                    "({identity_provider_site}) does not match the site for "
                    "this enterprise customer ({enterprise_customer_site}). "
                    "To correct this problem, select a site that has a domain "
                    "of '{identity_provider_site}', or update the identity "
                    "provider to '{enterprise_customer_site}'."
                ).format(
                    enterprise_customer_site=enterprise_customer.site,
                    identity_provider_site=identity_provider.site,
                ),
            )

Response: Validate that the selected site for this enterprise customer matches with the selected identity provider s site.


Instruction:
Write a Python 3 script for
checking that all selected catalogs for reporting are tied to the selected enterprise.

Response:
def clean(self):
        """
        Override of clean method to perform additional validation
        """
        cleaned_data = super(EnterpriseCustomerReportingConfigAdminForm, self).clean()
        report_customer = cleaned_data.get('enterprise_customer')

        # Check that any selected catalogs are tied to the selected enterprise.
        invalid_catalogs = [
            '{} ({})'.format(catalog.title, catalog.uuid)
            for catalog in cleaned_data.get('enterprise_customer_catalogs')
            if catalog.enterprise_customer != report_customer
        ]

        if invalid_catalogs:
            message = _(
                'These catalogs for reporting do not match enterprise'
                'customer {enterprise_customer}: {invalid_catalogs}',
            ).format(
                enterprise_customer=report_customer,
                invalid_catalogs=invalid_catalogs,
            )
            self.add_error('enterprise_customer_catalogs', message)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def clean_channel_worker_username(self):
        channel_worker_username = self.cleaned_data['channel_worker_username'].strip()

        try:
            User.objects.get(username=channel_worker_username)
        except User.DoesNotExist:
            raise ValidationError(
                ValidationMessages.INVALID_CHANNEL_WORKER.format(
                    channel_worker_username=channel_worker_username
                )
            )

        return channel_worker_username

Response: Clean enterprise channel worker user username form field


Instruction:
Can you generate a brief explanation for the following Python 3 code
def verify_edx_resources():
    required_methods = {
        'ProgramDataExtender': ProgramDataExtender,
    }

    for method in required_methods:
        if required_methods[method] is None:
            raise NotConnectedToOpenEdX(
                _("The following method from the Open edX platform is necessary for this view but isn't available.")
                + "\nUnavailable: {method}".format(method=method)
            )

Response: Ensures that all required resources to render the view are present.


Instruction:
Make a summary of the following Python 3 code
def get_global_context(request, enterprise_customer):
    platform_name = get_configuration_value("PLATFORM_NAME", settings.PLATFORM_NAME)
    # pylint: disable=no-member
    return {
        'enterprise_customer': enterprise_customer,
        'LMS_SEGMENT_KEY': settings.LMS_SEGMENT_KEY,
        'LANGUAGE_CODE': get_language_from_request(request),
        'tagline': get_configuration_value("ENTERPRISE_TAGLINE", settings.ENTERPRISE_TAGLINE),
        'platform_description': get_configuration_value(
            "PLATFORM_DESCRIPTION",
            settings.PLATFORM_DESCRIPTION,
        ),
        'LMS_ROOT_URL': settings.LMS_ROOT_URL,
        'platform_name': platform_name,
        'header_logo_alt_text': _('{platform_name} home page').format(platform_name=platform_name),
        'welcome_text': constants.WELCOME_TEXT.format(platform_name=platform_name),
        'enterprise_welcome_text': constants.ENTERPRISE_WELCOME_TEXT.format(
            enterprise_customer_name=enterprise_customer.name,
            platform_name=platform_name,
            strong_start='',
            strong_end='',
            line_break='
',
            privacy_policy_link_start="".format(
                pp_url=get_configuration_value('PRIVACY', 'https://www.edx.org/edx-privacy-policy', type='url'),
            ),
            privacy_policy_link_end="",
        ),
    }

Response: Get the set of variables that are needed by default across views.


Instruction:
Can you implement a function in Python 3 that
returns the localized converted price as string

Response:
def get_price_text(price, request):
    """
    Return the localized converted price as string (ex. '$150 USD').

    If the local_currency switch is enabled and the users location has been determined this will convert the
    given price based on conversion rate from the Catalog service and return a localized string
    """
    if waffle.switch_is_active('local_currency') and get_localized_price_text:
        return get_localized_price_text(price, request)

    return format_price(price)


Instruction:
Implement a Python 3 function for
rendering a page with specified error_code and log_message.

Response:
def render_page_with_error_code_message(request, context_data, error_code, log_message):
    """
    Return a 404 page with specified error_code after logging error and adding message to django messages.
    """
    LOGGER.error(log_message)
    messages.add_generic_error_message_with_code(request, error_code)
    return render(
        request,
        ENTERPRISE_GENERAL_ERROR_PAGE,
        context=context_data,
        status=404,
    )


Instruction:
Write a Python 3 function for
returning whether the input course or program exist.

Response:
def course_or_program_exist(self, course_id, program_uuid):
        """
        Return whether the input course or program exist.
        """
        course_exists = course_id and CourseApiClient().get_course_details(course_id)
        program_exists = program_uuid and CourseCatalogApiServiceClient().program_exists(program_uuid)
        return course_exists or program_exists


Instruction:
Can you write a function in Python 3 where it
gets the default set of variables that will be populated by default.

Response:
def get_default_context(self, enterprise_customer, platform_name):
        """
        Get the set of variables that will populate the template by default.
        """
        context_data = {
            'page_title': _('Data sharing consent required'),
            'consent_message_header': _('Consent to share your data'),
            'requested_permissions_header': _(
                'Per the {start_link}Data Sharing Policy{end_link}, '
                '{bold_start}{enterprise_customer_name}{bold_end} would like to know about:'
            ).format(
                enterprise_customer_name=enterprise_customer.name,
                bold_start='<b>',
                bold_end='</b>',
                start_link='<a href="#consent-policy-dropdown-bar" '
                           'class="policy-dropdown-link background-input" id="policy-dropdown-link">',
                end_link='</a>',
            ),
            'agreement_text': _(
                'I agree to allow {platform_name} to share data about my enrollment, completion and performance in all '
                '{platform_name} courses and programs where my enrollment is sponsored by {enterprise_customer_name}.'
            ).format(
                enterprise_customer_name=enterprise_customer.name,
                platform_name=platform_name,
            ),
            'continue_text': _('Yes, continue'),
            'abort_text': _('No, take me back.'),
            'policy_dropdown_header': _('Data Sharing Policy'),
            'sharable_items_header': _(
                'Enrollment, completion, and performance data that may be shared with {enterprise_customer_name} '
                '(or its designee) for these courses and programs are limited to the following:'
            ).format(
                enterprise_customer_name=enterprise_customer.name
            ),
            'sharable_items': [
                _(
                    'My email address for my {platform_name} account, '
                    'and the date when I created my {platform_name} account'
                ).format(
                    platform_name=platform_name
                ),
                _(
                    'My {platform_name} ID, and if I log in via single sign-on, '
                    'my {enterprise_customer_name} SSO user-ID'
                ).format(
                    platform_name=platform_name,
                    enterprise_customer_name=enterprise_customer.name,
                ),
                _('My {platform_name} username').format(platform_name=platform_name),
                _('My country or region of residence'),
                _(
                    'What courses and/or programs I\'ve enrolled in or unenrolled from, what track I '
                    'enrolled in (audit or verified) and the date when I enrolled in each course or program'
                ),
                _(
                    'Information about each course or program I\'ve enrolled in, '
                    'including its duration and level of effort required'
                ),
                _(
                    'Whether I completed specific parts of each course or program (for example, whether '
                    'I watched a given video or completed a given homework assignment)'
                ),
                _(
                    'My overall percentage completion of each course or program on a periodic basis, '
                    'including the total time spent in each course or program and the date when I last '
                    'logged in to each course or program'
                ),
                _('My performance in each course or program'),
                _('My final grade in each course or program, and the date when I completed each course or program'),
                _('Whether I received a certificate in each course or program'),
            ],
            'sharable_items_footer': _(
                'My permission applies only to data from courses or programs that are sponsored by '
                '{enterprise_customer_name}, and not to data from any {platform_name} courses or programs that '
                'I take on my own. I understand that I may withdraw my permission only by fully unenrolling '
                'from any courses or programs that are sponsored by {enterprise_customer_name}.'
            ).format(
                enterprise_customer_name=enterprise_customer.name,
                platform_name=platform_name,
            ),
            'sharable_items_note_header': _('Please note'),
            'sharable_items_notes': [
                _('If you decline to consent, that fact may be shared with {enterprise_customer_name}.').format(
                    enterprise_customer_name=enterprise_customer.name
                ),
            ],
            'confirmation_modal_header': _('Are you aware...'),
            'confirmation_modal_affirm_decline_text': _('I decline'),
            'confirmation_modal_abort_decline_text': _('View the data sharing policy'),
            'policy_link_template': _('View the {start_link}data sharing policy{end_link}.').format(
                start_link='<a href="#consent-policy-dropdown-bar" class="policy-dropdown-link background-input" '
                           'id="policy-dropdown-link">',
                end_link='</a>',
            ),
            'policy_return_link_text': _('Return to Top'),
        }
        return context_data


Instruction:
Can you generate the documentation for the following Python 3 function
def get_context_from_db(self, consent_page, platform_name, item, context):
        enterprise_customer = consent_page.enterprise_customer
        course_title = context.get('course_title', None)
        course_start_date = context.get('course_start_date', None)
        context_data = {
            'text_override_available': True,
            'page_title': consent_page.page_title,
            'left_sidebar_text': consent_page.left_sidebar_text.format(
                enterprise_customer_name=enterprise_customer.name,
                platform_name=platform_name,
                item=item,
                course_title=course_title,
                course_start_date=course_start_date,
            ),
            'top_paragraph': consent_page.top_paragraph.format(
                enterprise_customer_name=enterprise_customer.name,
                platform_name=platform_name,
                item=item,
                course_title=course_title,
                course_start_date=course_start_date,
            ),
            'agreement_text': consent_page.agreement_text.format(
                enterprise_customer_name=enterprise_customer.name,
                platform_name=platform_name,
                item=item,
                course_title=course_title,
                course_start_date=course_start_date,
            ),
            'continue_text': consent_page.continue_text,
            'abort_text': consent_page.abort_text,
            'policy_dropdown_header': consent_page.policy_dropdown_header,
            'policy_paragraph': consent_page.policy_paragraph.format(
                enterprise_customer_name=enterprise_customer.name,
                platform_name=platform_name,
                item=item,
                course_title=course_title,
                course_start_date=course_start_date,
            ),
            'confirmation_modal_header': consent_page.confirmation_modal_header.format(
                enterprise_customer_name=enterprise_customer.name,
                platform_name=platform_name,
                item=item,
                course_title=course_title,
                course_start_date=course_start_date,
            ),
            'confirmation_alert_prompt': consent_page.confirmation_modal_text.format(
                enterprise_customer_name=enterprise_customer.name,
                platform_name=platform_name,
                item=item,
                course_title=course_title,
                course_start_date=course_start_date,
            ),
            'confirmation_modal_affirm_decline_text': consent_page.modal_affirm_decline_text,
            'confirmation_modal_abort_decline_text': consent_page.modal_abort_decline_text,
        }
        return context_data

Response: Get the context from the DB.


Instruction:
Given the following Python 3 function, write the documentation
def get_course_or_program_context(self, enterprise_customer, course_id=None, program_uuid=None):
        context_data = {}
        if course_id:
            context_data.update({'course_id': course_id, 'course_specific': True})
            if not self.preview_mode:
                try:
                    catalog_api_client = CourseCatalogApiServiceClient(enterprise_customer.site)
                except ImproperlyConfigured:
                    raise Http404

                course_run_details = catalog_api_client.get_course_run(course_id)
                course_start_date = ''
                if course_run_details['start']:
                    course_start_date = parse(course_run_details['start']).strftime('%B %d, %Y')

                context_data.update({
                    'course_title': course_run_details['title'],
                    'course_start_date': course_start_date,
                })
            else:
                context_data.update({
                    'course_title': 'Demo Course',
                    'course_start_date': datetime.datetime.now().strftime('%B %d, %Y'),
                })
        else:
            context_data.update({
                'program_uuid': program_uuid,
                'program_specific': True,
            })
        return context_data

Response: Returns a dict having course or program specific keys for data sharing consent page.


Instruction:
Given the following Python 3 function, write the documentation
def get(self, request):
        enterprise_customer_uuid = request.GET.get('enterprise_customer_uuid')
        success_url = request.GET.get('next')
        failure_url = request.GET.get('failure_url')
        course_id = request.GET.get('course_id', '')
        program_uuid = request.GET.get('program_uuid', '')
        self.preview_mode = bool(request.GET.get('preview_mode', False))

        # Get enterprise_customer to start in case we need to render a custom 404 page
        # Then go through other business logic to determine (and potentially overwrite) the enterprise customer
        enterprise_customer = get_enterprise_customer_or_404(enterprise_customer_uuid)
        context_data = get_global_context(request, enterprise_customer)

        if not self.preview_mode:
            if not self.course_or_program_exist(course_id, program_uuid):
                error_code = 'ENTGDS000'
                log_message = (
                    'Neither the course with course_id: {course_id} '
                    'or program with {program_uuid} exist for '
                    'enterprise customer {enterprise_customer_uuid}'
                    'Error code {error_code} presented to user {userid}'.format(
                        course_id=course_id,
                        program_uuid=program_uuid,
                        error_code=error_code,
                        userid=request.user.id,
                        enterprise_customer_uuid=enterprise_customer_uuid,
                    )
                )
                return render_page_with_error_code_message(request, context_data, error_code, log_message)

            try:
                consent_record = get_data_sharing_consent(
                    request.user.username,
                    enterprise_customer_uuid,
                    program_uuid=program_uuid,
                    course_id=course_id
                )
            except NotConnectedToOpenEdX as error:
                error_code = 'ENTGDS001'
                log_message = (
                    'The was a problem with getting the consent record of user {userid} with '
                    'uuid {enterprise_customer_uuid}. get_data_sharing_consent threw '
                    'the following NotConnectedToOpenEdX error: {error}'
                    'for course_id {course_id}.'
                    'Error code {error_code} presented to user'.format(
                        userid=request.user.id,
                        enterprise_customer_uuid=enterprise_customer_uuid,
                        error=error,
                        error_code=error_code,
                        course_id=course_id,
                    )
                )
                return render_page_with_error_code_message(request, context_data, error_code, log_message)

            try:
                consent_required = consent_record.consent_required()
            except AttributeError:
                consent_required = None

            if consent_record is None or not consent_required:
                error_code = 'ENTGDS002'
                log_message = (
                    'The was a problem with the consent record of user {userid} with '
                    'enterprise_customer_uuid {enterprise_customer_uuid}. consent_record has a value '
                    'of {consent_record} and consent_record.consent_required() a '
                    'value of {consent_required} for course_id {course_id}. '
                    'Error code {error_code} presented to user'.format(
                        userid=request.user.id,
                        enterprise_customer_uuid=enterprise_customer_uuid,
                        consent_record=consent_record,
                        consent_required=consent_required,
                        error_code=error_code,
                        course_id=course_id,
                    )
                )
                return render_page_with_error_code_message(request, context_data, error_code, log_message)
            else:
                enterprise_customer = consent_record.enterprise_customer
        elif not request.user.is_staff:
            raise PermissionDenied()

        # Retrieve context data again now that enterprise_customer logic has been run
        context_data = get_global_context(request, enterprise_customer)

        if not (enterprise_customer_uuid and success_url and failure_url):
            error_code = 'ENTGDS003'
            log_message = (
                'Error: one or more of the following values was falsy: '
                'enterprise_customer_uuid: {enterprise_customer_uuid}, '
                'success_url: {success_url}, '
                'failure_url: {failure_url} for course id {course_id}'
                'The following error code was reported to user {userid}: {error_code}'.format(
                    userid=request.user.id,
                    enterprise_customer_uuid=enterprise_customer_uuid,
                    success_url=success_url,
                    failure_url=failure_url,
                    error_code=error_code,
                    course_id=course_id,
                )
            )
            return render_page_with_error_code_message(request, context_data, error_code, log_message)

        try:
            updated_context_dict = self.get_course_or_program_context(
                enterprise_customer,
                course_id=course_id,
                program_uuid=program_uuid
            )
            context_data.update(updated_context_dict)
        except Http404:
            error_code = 'ENTGDS004'
            log_message = (
                'CourseCatalogApiServiceClient is improperly configured. '
                'Returned error code {error_code} to user {userid} '
                'and enterprise_customer {enterprise_customer} '
                'for course_id {course_id}'.format(
                    error_code=error_code,
                    userid=request.user.id,
                    enterprise_customer=enterprise_customer.uuid,
                    course_id=course_id,
                )
            )
            return render_page_with_error_code_message(request, context_data, error_code, log_message)

        item = 'course' if course_id else 'program'
        # Translators: bold_start and bold_end are HTML tags for specifying enterprise name in bold text.
        context_data.update({
            'consent_request_prompt': _(
                'To access this {item}, you must first consent to share your learning achievements '
                'with {bold_start}{enterprise_customer_name}{bold_end}.'
            ).format(
                enterprise_customer_name=enterprise_customer.name,
                bold_start='',
                bold_end='',
                item=item,
            ),
            'confirmation_alert_prompt': _(
                'In order to start this {item} and use your discount, {bold_start}you must{bold_end} consent '
                'to share your {item} data with {enterprise_customer_name}.'
            ).format(
                enterprise_customer_name=enterprise_customer.name,
                bold_start='',
                bold_end='',
                item=item,
            ),
            'redirect_url': success_url,
            'failure_url': failure_url,
            'defer_creation': request.GET.get('defer_creation') is not None,
            'requested_permissions': [
                _('your enrollment in this {item}').format(item=item),
                _('your learning progress'),
                _('course completion'),
            ],
            'policy_link_template': '',
        })
        platform_name = context_data['platform_name']
        published_only = False if self.preview_mode else True
        enterprise_consent_page = enterprise_customer.get_data_sharing_consent_text_overrides(
            published_only=published_only
        )
        if enterprise_consent_page:
            context_data.update(self.get_context_from_db(enterprise_consent_page, platform_name, item, context_data))
        else:
            context_data.update(self.get_default_context(enterprise_customer, platform_name))

        return render(request, 'enterprise/grant_data_sharing_permissions.html', context=context_data)

Response: Render a form to collect user input about data sharing consent.


Instruction:
Explain what the following Python 3 code does
def post(self, request):
        enterprise_uuid = request.POST.get('enterprise_customer_uuid')
        success_url = request.POST.get('redirect_url')
        failure_url = request.POST.get('failure_url')
        course_id = request.POST.get('course_id', '')
        program_uuid = request.POST.get('program_uuid', '')

        enterprise_customer = get_enterprise_customer_or_404(enterprise_uuid)
        context_data = get_global_context(request, enterprise_customer)

        if not (enterprise_uuid and success_url and failure_url):
            error_code = 'ENTGDS005'
            log_message = (
                'Error: one or more of the following values was falsy: '
                'enterprise_uuid: {enterprise_uuid}, '
                'success_url: {success_url}, '
                'failure_url: {failure_url} for course_id {course_id}. '
                'The following error code was reported to the user {userid}: {error_code}'.format(
                    userid=request.user.id,
                    enterprise_uuid=enterprise_uuid,
                    success_url=success_url,
                    failure_url=failure_url,
                    error_code=error_code,
                    course_id=course_id,
                )
            )
            return render_page_with_error_code_message(request, context_data, error_code, log_message)

        if not self.course_or_program_exist(course_id, program_uuid):
            error_code = 'ENTGDS006'
            log_message = (
                'Neither the course with course_id: {course_id} '
                'or program with {program_uuid} exist for '
                'enterprise customer {enterprise_uuid}'
                'Error code {error_code} presented to user {userid}'.format(
                    course_id=course_id,
                    program_uuid=program_uuid,
                    error_code=error_code,
                    userid=request.user.id,
                    enterprise_uuid=enterprise_uuid,
                )
            )
            return render_page_with_error_code_message(request, context_data, error_code, log_message)

        consent_record = get_data_sharing_consent(
            request.user.username,
            enterprise_uuid,
            program_uuid=program_uuid,
            course_id=course_id
        )
        if consent_record is None:
            error_code = 'ENTGDS007'
            log_message = (
                'The was a problem with the consent record of user {userid} with '
                'enterprise_uuid {enterprise_uuid}. consent_record has a value '
                'of {consent_record} and a '
                'value for course_id {course_id}. '
                'Error code {error_code} presented to user'.format(
                    userid=request.user.id,
                    enterprise_uuid=enterprise_uuid,
                    consent_record=consent_record,
                    error_code=error_code,
                    course_id=course_id,
                )
            )
            return render_page_with_error_code_message(request, context_data, error_code, log_message)

        defer_creation = request.POST.get('defer_creation')
        consent_provided = bool(request.POST.get('data_sharing_consent', False))
        if defer_creation is None and consent_record.consent_required():
            if course_id:
                enterprise_customer_user, __ = EnterpriseCustomerUser.objects.get_or_create(
                    enterprise_customer=consent_record.enterprise_customer,
                    user_id=request.user.id
                )
                enterprise_customer_user.update_session(request)
                __, created = EnterpriseCourseEnrollment.objects.get_or_create(
                    enterprise_customer_user=enterprise_customer_user,
                    course_id=course_id,
                )
                if created:
                    track_enrollment('data-consent-page-enrollment', request.user.id, course_id, request.path)

            consent_record.granted = consent_provided
            consent_record.save()

        return redirect(success_url if consent_provided else failure_url)

Response: Process the POST request.


Instruction:
How would you explain what the following Python 3 function does
def get(self, request, enterprise_uuid, course_id):
        enrollment_course_mode = request.GET.get('course_mode')
        enterprise_catalog_uuid = request.GET.get('catalog')

        # Redirect the learner to LMS dashboard in case no course mode is
        # provided as query parameter `course_mode`
        if not enrollment_course_mode:
            return redirect(LMS_DASHBOARD_URL)

        enrollment_api_client = EnrollmentApiClient()
        course_modes = enrollment_api_client.get_course_modes(course_id)

        # Verify that the request user belongs to the enterprise against the
        # provided `enterprise_uuid`.
        enterprise_customer = get_enterprise_customer_or_404(enterprise_uuid)
        enterprise_customer_user = get_enterprise_customer_user(request.user.id, enterprise_customer.uuid)

        if not course_modes:
            context_data = get_global_context(request, enterprise_customer)
            error_code = 'ENTHCE000'
            log_message = (
                'No course_modes for course_id {course_id} for enterprise_catalog_uuid '
                '{enterprise_catalog_uuid}.'
                'The following error was presented to '
                'user {userid}: {error_code}'.format(
                    userid=request.user.id,
                    enterprise_catalog_uuid=enterprise_catalog_uuid,
                    course_id=course_id,
                    error_code=error_code
                )
            )
            return render_page_with_error_code_message(request, context_data, error_code, log_message)

        selected_course_mode = None
        for course_mode in course_modes:
            if course_mode['slug'] == enrollment_course_mode:
                selected_course_mode = course_mode
                break

        if not selected_course_mode:
            return redirect(LMS_DASHBOARD_URL)

        # Create the Enterprise backend database records for this course
        # enrollment
        __, created = EnterpriseCourseEnrollment.objects.get_or_create(
            enterprise_customer_user=enterprise_customer_user,
            course_id=course_id,
        )
        if created:
            track_enrollment('course-landing-page-enrollment', request.user.id, course_id, request.get_full_path())

        DataSharingConsent.objects.update_or_create(
            username=enterprise_customer_user.username,
            course_id=course_id,
            enterprise_customer=enterprise_customer_user.enterprise_customer,
            defaults={
                'granted': True
            },
        )

        audit_modes = getattr(settings, 'ENTERPRISE_COURSE_ENROLLMENT_AUDIT_MODES', ['audit', 'honor'])
        if selected_course_mode['slug'] in audit_modes:
            # In case of Audit course modes enroll the learner directly through
            # enrollment API client and redirect the learner to dashboard.
            enrollment_api_client.enroll_user_in_course(
                request.user.username, course_id, selected_course_mode['slug']
            )

            return redirect(LMS_COURSEWARE_URL.format(course_id=course_id))

        # redirect the enterprise learner to the ecommerce flow in LMS
        # Note: LMS start flow automatically detects the paid mode
        premium_flow = LMS_START_PREMIUM_COURSE_FLOW_URL.format(course_id=course_id)
        if enterprise_catalog_uuid:
            premium_flow += '?catalog={catalog_uuid}'.format(
                catalog_uuid=enterprise_catalog_uuid
            )

        return redirect(premium_flow)

Response: This function handles the get action for the given enterprise learner in the provided course.


Instruction:
Can you create a Python 3 function that
sets the final discounted price on each premium mode.

Response:
def set_final_prices(self, modes, request):
        """
        Set the final discounted price on each premium mode.
        """
        result = []
        for mode in modes:
            if mode['premium']:
                mode['final_price'] = EcommerceApiClient(request.user).get_course_final_price(
                    mode=mode,
                    enterprise_catalog_uuid=request.GET.get(
                        'catalog'
                    ) if request.method == 'GET' else None,
                )
            result.append(mode)
        return result


Instruction:
Here you have a function in Python 3, explain what it does
def get_available_course_modes(self, request, course_run_id, enterprise_catalog):
        modes = EnrollmentApiClient().get_course_modes(course_run_id)
        if not modes:
            LOGGER.warning('Unable to get course modes for course run id {course_run_id}.'.format(
                course_run_id=course_run_id
            ))
            messages.add_generic_info_message_for_error(request)

        if enterprise_catalog:
            # filter and order course modes according to the enterprise catalog
            modes = [mode for mode in modes if mode['slug'] in enterprise_catalog.enabled_course_modes]
            modes.sort(key=lambda course_mode: enterprise_catalog.enabled_course_modes.index(course_mode['slug']))
            if not modes:
                LOGGER.info(
                    'No matching course modes found for course run {course_run_id} in '
                    'EnterpriseCustomerCatalog [{enterprise_catalog_uuid}]'.format(
                        course_run_id=course_run_id,
                        enterprise_catalog_uuid=enterprise_catalog,
                    )
                )
                messages.add_generic_info_message_for_error(request)

        return modes

Response: Get the available course modes for the given course run.


Instruction:
Can you create a Python 3 function that
retrieves the base details for the specified enterprise customer and course run.

Response:
def get_base_details(self, request, enterprise_uuid, course_run_id):
        """
        Retrieve fundamental details used by both POST and GET versions of this view.

        Specifically, take an EnterpriseCustomer UUID and a course run ID, and transform those
        into an actual EnterpriseCustomer, a set of details about the course, and a list
        of the available course modes for that course run.
        """
        enterprise_customer = get_enterprise_customer_or_404(enterprise_uuid)

        # If the catalog query parameter was provided, we need to scope
        # this request to the specified EnterpriseCustomerCatalog.
        enterprise_catalog_uuid = request.GET.get('catalog')
        enterprise_catalog = None
        if enterprise_catalog_uuid:
            try:
                enterprise_catalog_uuid = UUID(enterprise_catalog_uuid)
                enterprise_catalog = enterprise_customer.enterprise_customer_catalogs.get(
                    uuid=enterprise_catalog_uuid
                )
            except (ValueError, EnterpriseCustomerCatalog.DoesNotExist):
                LOGGER.warning(
                    'EnterpriseCustomerCatalog [{enterprise_catalog_uuid}] does not exist'.format(
                        enterprise_catalog_uuid=enterprise_catalog_uuid,
                    )
                )
                messages.add_generic_info_message_for_error(request)

        course = None
        course_run = None
        course_modes = []
        if enterprise_catalog:
            course, course_run = enterprise_catalog.get_course_and_course_run(course_run_id)
        else:
            try:
                course, course_run = CourseCatalogApiServiceClient(
                    enterprise_customer.site
                ).get_course_and_course_run(course_run_id)
            except ImproperlyConfigured:
                LOGGER.warning('CourseCatalogApiServiceClient is improperly configured.')
                messages.add_generic_info_message_for_error(request)
                return enterprise_customer, course, course_run, course_modes

        if not course or not course_run:
            course_id = course['key'] if course else "Not Found"
            course_title = course['title'] if course else "Not Found"
            course_run_title = course_run['title'] if course_run else "Not Found"
            enterprise_catalog_title = enterprise_catalog.title if enterprise_catalog else "Not Found"
            # The specified course either does not exist in the specified
            # EnterpriseCustomerCatalog, or does not exist at all in the
            # discovery service.
            LOGGER.warning(
                'Failed to fetch details for course "{course_title}" [{course_id}] '
                'or course run "{course_run_title}" [{course_run_id}] '
                'for enterprise "{enterprise_name}" [{enterprise_uuid}] '
                'with catalog "{enterprise_catalog_title}" [{enterprise_catalog_uuid}]'.format(
                    course_title=course_title,
                    course_id=course_id,
                    course_run_title=course_run_title,
                    course_run_id=course_run_id,
                    enterprise_name=enterprise_customer.name,
                    enterprise_uuid=enterprise_customer.uuid,
                    enterprise_catalog_title=enterprise_catalog_title,
                    enterprise_catalog_uuid=enterprise_catalog_uuid,
                )
            )
            messages.add_generic_info_message_for_error(request)
            return enterprise_customer, course, course_run, course_modes

        if enterprise_catalog_uuid and not enterprise_catalog:
            # A catalog query parameter was given, but the specified
            # EnterpriseCustomerCatalog does not exist, so just return and
            # display the generic error message.
            return enterprise_customer, course, course_run, course_modes

        modes = self.get_available_course_modes(request, course_run_id, enterprise_catalog)
        audit_modes = getattr(
            settings,
            'ENTERPRISE_COURSE_ENROLLMENT_AUDIT_MODES',
            ['audit', 'honor']
        )

        for mode in modes:
            if mode['min_price']:
                price_text = get_price_text(mode['min_price'], request)
            else:
                price_text = _('FREE')
            if mode['slug'] in audit_modes:
                description = _('Not eligible for a certificate.')
            else:
                description = _('Earn a verified certificate!')
            course_modes.append({
                'mode': mode['slug'],
                'min_price': mode['min_price'],
                'sku': mode['sku'],
                'title': mode['name'],
                'original_price': price_text,
                'final_price': price_text,
                'description': description,
                'premium': mode['slug'] not in audit_modes
            })

        return enterprise_customer, course, course_run, course_modes


Instruction:
Can you tell what is the following Python 3 function doing
def get_enterprise_course_enrollment_page(
            self,
            request,
            enterprise_customer,
            course,
            course_run,
            course_modes,
            enterprise_course_enrollment,
            data_sharing_consent
    ):
        """
        Render enterprise-specific course track selection page.
        """
        context_data = get_global_context(request, enterprise_customer)
        enterprise_catalog_uuid = request.GET.get(
            'catalog'
        ) if request.method == 'GET' else None
        html_template_for_rendering = ENTERPRISE_GENERAL_ERROR_PAGE
        if course and course_run:
            course_enrollable = True
            course_start_date = ''
            course_in_future = False
            organization_name = ''
            organization_logo = ''
            expected_learning_items = course['expected_learning_items']
            # Parse organization name and logo.
            if course['owners']:
                # The owners key contains the organizations associated with the course.
                # We pick the first one in the list here to meet UX requirements.
                organization = course['owners'][0]
                organization_name = organization['name']
                organization_logo = organization['logo_image_url']

            course_title = course_run['title']
            course_short_description = course_run['short_description'] or ''
            course_full_description = clean_html_for_template_rendering(course_run['full_description'] or '')
            course_pacing = self.PACING_FORMAT.get(course_run['pacing_type'], '')
            if course_run['start']:
                course_start_date = parse(course_run['start']).strftime('%B %d, %Y')
                now = datetime.datetime.now(pytz.UTC)
                course_in_future = parse(course_run['start']) > now

            course_level_type = course_run.get('level_type', '')
            staff = course_run['staff']
            # Format the course effort string using the min/max effort fields for the course run.
            course_effort = ungettext_min_max(
                '{} hour per week',
                '{} hours per week',
                '{}-{} hours per week',
                course_run['min_effort'] or None,
                course_run['max_effort'] or None,
            ) or ''

            # Parse course run image.
            course_run_image = course_run['image'] or {}
            course_image_uri = course_run_image.get('src', '')

            # Retrieve the enterprise-discounted price from ecommerce.
            course_modes = self.set_final_prices(course_modes, request)
            premium_modes = [mode for mode in course_modes if mode['premium']]

            # Filter audit course modes.
            course_modes = filter_audit_course_modes(enterprise_customer, course_modes)

            # Allows automatic assignment to a cohort upon enrollment.
            cohort = request.GET.get('cohort')
            # Add a message to the message display queue if the learner
            # has gone through the data sharing consent flow and declined
            # to give data sharing consent.
            if enterprise_course_enrollment and not data_sharing_consent.granted:
                messages.add_consent_declined_message(request, enterprise_customer, course_run.get('title', ''))

            if not is_course_run_enrollable(course_run):
                messages.add_unenrollable_item_message(request, 'course')
                course_enrollable = False
            context_data.update({
                'course_enrollable': course_enrollable,
                'course_title': course_title,
                'course_short_description': course_short_description,
                'course_pacing': course_pacing,
                'course_start_date': course_start_date,
                'course_in_future': course_in_future,
                'course_image_uri': course_image_uri,
                'course_modes': course_modes,
                'course_effort': course_effort,
                'course_full_description': course_full_description,
                'cohort': cohort,
                'organization_logo': organization_logo,
                'organization_name': organization_name,
                'course_level_type': course_level_type,
                'premium_modes': premium_modes,
                'expected_learning_items': expected_learning_items,
                'catalog': enterprise_catalog_uuid,
                'staff': staff,
                'discount_text': _('Discount provided by {strong_start}{enterprise_customer_name}{strong_end}').format(
                    enterprise_customer_name=enterprise_customer.name,
                    strong_start='<strong>',
                    strong_end='</strong>',
                ),
                'hide_course_original_price': enterprise_customer.hide_course_original_price
            })
            html_template_for_rendering = 'enterprise/enterprise_course_enrollment_page.html'

        context_data.update({
            'page_title': _('Confirm your course'),
            'confirmation_text': _('Confirm your course'),
            'starts_at_text': _('Starts'),
            'view_course_details_text': _('View Course Details'),
            'select_mode_text': _('Please select one:'),
            'price_text': _('Price'),
            'continue_link_text': _('Continue'),
            'level_text': _('Level'),
            'effort_text': _('Effort'),
            'close_modal_button_text': _('Close'),
            'expected_learning_items_text': _("What you'll learn"),
            'course_full_description_text': _('About This Course'),
            'staff_text': _('Course Staff'),
        })
        return render(request, html_template_for_rendering, context=context_data)

Response: Render enterprise - specific course enrollment page.


Instruction:
Here you have a function in Python 3, explain what it does
def post(self, request, enterprise_uuid, course_id):
        enterprise_customer, course, course_run, course_modes = self.get_base_details(
            request, enterprise_uuid, course_id
        )

        # Create a link between the user and the enterprise customer if it does not already exist.
        enterprise_customer_user, __ = EnterpriseCustomerUser.objects.get_or_create(
            enterprise_customer=enterprise_customer,
            user_id=request.user.id
        )
        enterprise_customer_user.update_session(request)

        data_sharing_consent = DataSharingConsent.objects.proxied_get(
            username=enterprise_customer_user.username,
            course_id=course_id,
            enterprise_customer=enterprise_customer
        )

        try:
            enterprise_course_enrollment = EnterpriseCourseEnrollment.objects.get(
                enterprise_customer_user__enterprise_customer=enterprise_customer,
                enterprise_customer_user__user_id=request.user.id,
                course_id=course_id
            )
        except EnterpriseCourseEnrollment.DoesNotExist:
            enterprise_course_enrollment = None

        enterprise_catalog_uuid = request.POST.get('catalog')
        selected_course_mode_name = request.POST.get('course_mode')
        cohort_name = request.POST.get('cohort')

        selected_course_mode = None
        for course_mode in course_modes:
            if course_mode['mode'] == selected_course_mode_name:
                selected_course_mode = course_mode
                break

        if not selected_course_mode:
            return self.get_enterprise_course_enrollment_page(
                request,
                enterprise_customer,
                course,
                course_run,
                course_modes,
                enterprise_course_enrollment,
                data_sharing_consent
            )

        user_consent_needed = get_data_sharing_consent(
            enterprise_customer_user.username,
            enterprise_customer.uuid,
            course_id=course_id
        ).consent_required()
        if not selected_course_mode.get('premium') and not user_consent_needed:
            # For the audit course modes (audit, honor), where DSC is not
            # required, enroll the learner directly through enrollment API
            # client and redirect the learner to LMS courseware page.
            if not enterprise_course_enrollment:
                # Create the Enterprise backend database records for this course enrollment.
                enterprise_course_enrollment = EnterpriseCourseEnrollment.objects.create(
                    enterprise_customer_user=enterprise_customer_user,
                    course_id=course_id,
                )
                track_enrollment('course-landing-page-enrollment', request.user.id, course_id, request.get_full_path())

            client = EnrollmentApiClient()
            client.enroll_user_in_course(
                request.user.username,
                course_id,
                selected_course_mode_name,
                cohort=cohort_name
            )

            return redirect(LMS_COURSEWARE_URL.format(course_id=course_id))

        if user_consent_needed:
            # For the audit course modes (audit, honor) or for the premium
            # course modes (Verified, Prof Ed) where DSC is required, redirect
            # the learner to course specific DSC with enterprise UUID from
            # there the learner will be directed to the ecommerce flow after
            # providing DSC.
            query_string_params = {
                'course_mode': selected_course_mode_name,
            }
            if enterprise_catalog_uuid:
                query_string_params.update({'catalog': enterprise_catalog_uuid})

            next_url = '{handle_consent_enrollment_url}?{query_string}'.format(
                handle_consent_enrollment_url=reverse(
                    'enterprise_handle_consent_enrollment', args=[enterprise_customer.uuid, course_id]
                ),
                query_string=urlencode(query_string_params)
            )

            failure_url = reverse('enterprise_course_run_enrollment_page', args=[enterprise_customer.uuid, course_id])
            if request.META['QUERY_STRING']:
                # Preserve all querystring parameters in the request to build
                # failure url, so that learner views the same enterprise course
                # enrollment page (after redirect) as for the first time.
                # Since this is a POST view so use `request.META` to get
                # querystring instead of `request.GET`.
                # https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.HttpRequest.META
                failure_url = '{course_enrollment_url}?{query_string}'.format(
                    course_enrollment_url=reverse(
                        'enterprise_course_run_enrollment_page', args=[enterprise_customer.uuid, course_id]
                    ),
                    query_string=request.META['QUERY_STRING']
                )

            return redirect(
                '{grant_data_sharing_url}?{params}'.format(
                    grant_data_sharing_url=reverse('grant_data_sharing_permissions'),
                    params=urlencode(
                        {
                            'next': next_url,
                            'failure_url': failure_url,
                            'enterprise_customer_uuid': enterprise_customer.uuid,
                            'course_id': course_id,
                        }
                    )
                )
            )

        # For the premium course modes (Verified, Prof Ed) where DSC is
        # not required, redirect the enterprise learner to the ecommerce
        # flow in LMS.
        # Note: LMS start flow automatically detects the paid mode
        premium_flow = LMS_START_PREMIUM_COURSE_FLOW_URL.format(course_id=course_id)
        if enterprise_catalog_uuid:
            premium_flow += '?catalog={catalog_uuid}'.format(
                catalog_uuid=enterprise_catalog_uuid
            )

        return redirect(premium_flow)

Response: Process a submitted track selection form for the enterprise.


Instruction:
Write a Python 3 script to
get the details of a specific course.

Response:
def get(self, request, enterprise_uuid, course_id):
        """
        Show course track selection page for the enterprise.

        Based on `enterprise_uuid` in URL, the view will decide which
        enterprise customer's course enrollment page is to use.

        Unauthenticated learners will be redirected to enterprise-linked SSO.

        A 404 will be raised if any of the following conditions are met:
            * No enterprise customer uuid kwarg `enterprise_uuid` in request.
            * No enterprise customer found against the enterprise customer
                uuid `enterprise_uuid` in the request kwargs.
            * No course is found in database against the provided `course_id`.

        """
        # Check to see if access to the course run is restricted for this user.
        embargo_url = EmbargoApiClient.redirect_if_blocked([course_id], request.user, get_ip(request), request.path)
        if embargo_url:
            return redirect(embargo_url)

        enterprise_customer, course, course_run, modes = self.get_base_details(
            request, enterprise_uuid, course_id
        )
        enterprise_customer_user = get_enterprise_customer_user(request.user.id, enterprise_uuid)
        data_sharing_consent = DataSharingConsent.objects.proxied_get(
            username=enterprise_customer_user.username,
            course_id=course_id,
            enterprise_customer=enterprise_customer
        )

        enrollment_client = EnrollmentApiClient()
        enrolled_course = enrollment_client.get_course_enrollment(request.user.username, course_id)
        try:
            enterprise_course_enrollment = EnterpriseCourseEnrollment.objects.get(
                enterprise_customer_user__enterprise_customer=enterprise_customer,
                enterprise_customer_user__user_id=request.user.id,
                course_id=course_id
            )
        except EnterpriseCourseEnrollment.DoesNotExist:
            enterprise_course_enrollment = None

        if enrolled_course and enterprise_course_enrollment:
            # The user is already enrolled in the course through the Enterprise Customer, so redirect to the course
            # info page.
            return redirect(LMS_COURSEWARE_URL.format(course_id=course_id))

        return self.get_enterprise_course_enrollment_page(
            request,
            enterprise_customer,
            course,
            course_run,
            modes,
            enterprise_course_enrollment,
            data_sharing_consent,
        )


Instruction:
Can you generate the documentation for the following Python 3 function
def extend_course(course, enterprise_customer, request):
        course_run_id = course['course_runs'][0]['key']
        try:
            catalog_api_client = CourseCatalogApiServiceClient(enterprise_customer.site)
        except ImproperlyConfigured:
            error_code = 'ENTPEV000'
            LOGGER.error(
                'CourseCatalogApiServiceClient is improperly configured. '
                'Returned error code {error_code} to user {userid} '
                'and enterprise_customer {enterprise_customer} '
                'for course_run_id {course_run_id}'.format(
                    error_code=error_code,
                    userid=request.user.id,
                    enterprise_customer=enterprise_customer.uuid,
                    course_run_id=course_run_id,
                )
            )
            messages.add_generic_error_message_with_code(request, error_code)
            return ({}, error_code)

        course_details, course_run_details = catalog_api_client.get_course_and_course_run(course_run_id)
        if not course_details or not course_run_details:
            error_code = 'ENTPEV001'
            LOGGER.error(
                'User {userid} of enterprise customer {enterprise_customer} encountered an error.'
                'No course_details or course_run_details found for '
                'course_run_id {course_run_id}. '
                'The following error code reported to the user: {error_code}'.format(
                    userid=request.user.id,
                    enterprise_customer=enterprise_customer.uuid,
                    course_run_id=course_run_id,
                    error_code=error_code,
                )
            )
            messages.add_generic_error_message_with_code(request, error_code)
            return ({}, error_code)

        weeks_to_complete = course_run_details['weeks_to_complete']
        course_run_image = course_run_details['image'] or {}
        course.update({
            'course_image_uri': course_run_image.get('src', ''),
            'course_title': course_run_details['title'],
            'course_level_type': course_run_details.get('level_type', ''),
            'course_short_description': course_run_details['short_description'] or '',
            'course_full_description': clean_html_for_template_rendering(course_run_details['full_description'] or ''),
            'expected_learning_items': course_details.get('expected_learning_items', []),
            'staff': course_run_details.get('staff', []),
            'course_effort': ungettext_min_max(
                '{} hour per week',
                '{} hours per week',
                '{}-{} hours per week',
                course_run_details['min_effort'] or None,
                course_run_details['max_effort'] or None,
            ) or '',
            'weeks_to_complete': ungettext(
                '{} week',
                '{} weeks',
                weeks_to_complete
            ).format(weeks_to_complete) if weeks_to_complete else '',
        })
        return course, None

Response: Extend a course with more details needed for the program landing page.


Instruction:
Make a summary of the following Python 3 code
def get_program_details(self, request, program_uuid, enterprise_customer):
        try:
            course_catalog_api_client = CourseCatalogApiServiceClient(enterprise_customer.site)
        except ImproperlyConfigured:
            error_code = 'ENTPEV002'
            LOGGER.error(
                'CourseCatalogApiServiceClient is improperly configured. '
                'Returned error code {error_code} to user {userid} '
                'and enterprise_customer {enterprise_customer} '
                'for program {program_uuid}'.format(
                    error_code=error_code,
                    userid=request.user.id,
                    enterprise_customer=enterprise_customer.uuid,
                    program_uuid=program_uuid,
                )
            )
            messages.add_generic_error_message_with_code(request, error_code)
            return ({}, error_code)

        program_details = course_catalog_api_client.get_program_by_uuid(program_uuid)
        if program_details is None:
            error_code = 'ENTPEV003'
            LOGGER.error(
                'User {userid} of enterprise customer {enterprise_customer} encountered an error. '
                'program_details is None for program_uuid {program_uuid}. '
                'Returned error code {error_code} to user'.format(
                    userid=request.user.id,
                    enterprise_customer=enterprise_customer.uuid,
                    program_uuid=program_uuid,
                    error_code=error_code,
                )
            )
            messages.add_generic_error_message_with_code(request, error_code)
            return ({}, error_code)

        program_type = course_catalog_api_client.get_program_type_by_slug(slugify(program_details['type']))
        if program_type is None:
            error_code = 'ENTPEV004'
            LOGGER.error(
                'User {userid} of enterprise customer {enterprise_customer} encountered an error. '
                'program_type is None for program_details of program_uuid {program_uuid}. '
                'Returned error code {error_code} to user'.format(
                    userid=request.user.id,
                    enterprise_customer=enterprise_customer.uuid,
                    program_uuid=program_uuid,
                    error_code=error_code,
                )
            )
            messages.add_generic_error_message_with_code(request, error_code)
            return ({}, error_code)

        # Extend our program details with context we'll need for display or for deciding redirects.
        program_details = ProgramDataExtender(program_details, request.user).extend()

        # TODO: Upstream this additional context to the platform's `ProgramDataExtender` so we can avoid this here.
        program_details['enrolled_in_program'] = False
        enrollment_count = 0
        for extended_course in program_details['courses']:
            # We need to extend our course data further for modals and other displays.
            extended_data, error_code = ProgramEnrollmentView.extend_course(
                extended_course,
                enterprise_customer,
                request
            )

            if error_code:
                return ({}, error_code)

            extended_course.update(extended_data)
            # We're enrolled in the program if we have certificate-eligible enrollment in even 1 of its courses.
            extended_course_run = extended_course['course_runs'][0]
            if extended_course_run['is_enrolled'] and extended_course_run['upgrade_url'] is None:
                program_details['enrolled_in_program'] = True
                enrollment_count += 1

        # We're certificate eligible for the program if we have certificate-eligible enrollment in all of its courses.
        program_details['certificate_eligible_for_program'] = (enrollment_count == len(program_details['courses']))
        program_details['type_details'] = program_type
        return program_details, None

Response: Get fundamental details for a program.


Instruction:
How would you implement a function in Python 3 that
renders the Enterprise - specific program enrollment page.

Response:
def get_enterprise_program_enrollment_page(self, request, enterprise_customer, program_details):
        """
        Render Enterprise-specific program enrollment page.
        """
        # Safely make the assumption that we can use the first authoring organization.
        organizations = program_details['authoring_organizations']
        organization = organizations[0] if organizations else {}
        platform_name = get_configuration_value('PLATFORM_NAME', settings.PLATFORM_NAME)
        program_title = program_details['title']
        program_type_details = program_details['type_details']
        program_type = program_type_details['name']

        # Make any modifications for singular/plural-dependent text.
        program_courses = program_details['courses']
        course_count = len(program_courses)
        course_count_text = ungettext(
            '{count} Course',
            '{count} Courses',
            course_count,
        ).format(count=course_count)
        effort_info_text = ungettext_min_max(
            '{} hour per week, per course',
            '{} hours per week, per course',
            _('{}-{} hours per week, per course'),
            program_details.get('min_hours_effort_per_week'),
            program_details.get('max_hours_effort_per_week'),
        )
        length_info_text = ungettext_min_max(
            '{} week per course',
            '{} weeks per course',
            _('{}-{} weeks per course'),
            program_details.get('weeks_to_complete_min'),
            program_details.get('weeks_to_complete_max'),
        )

        # Update some enrollment-related text requirements.
        if program_details['enrolled_in_program']:
            purchase_action = _('Purchase all unenrolled courses')
            item = _('enrollment')
        else:
            purchase_action = _('Pursue the program')
            item = _('program enrollment')

        # Add any DSC warning messages.
        program_data_sharing_consent = get_data_sharing_consent(
            request.user.username,
            enterprise_customer.uuid,
            program_uuid=program_details['uuid'],
        )
        if program_data_sharing_consent.exists and not program_data_sharing_consent.granted:
            messages.add_consent_declined_message(request, enterprise_customer, program_title)

        discount_data = program_details.get('discount_data', {})
        one_click_purchase_eligibility = program_details.get('is_learner_eligible_for_one_click_purchase', False)
        # The following messages shouldn't both appear at the same time, and we prefer the eligibility message.
        if not one_click_purchase_eligibility:
            messages.add_unenrollable_item_message(request, 'program')
        elif discount_data.get('total_incl_tax_excl_discounts') is None:
            messages.add_missing_price_information_message(request, program_title)

        context_data = get_global_context(request, enterprise_customer)
        context_data.update({
            'enrolled_in_course_and_paid_text': _('enrolled'),
            'enrolled_in_course_and_unpaid_text': _('already enrolled, must pay for certificate'),
            'expected_learning_items_text': _("What you'll learn"),
            'expected_learning_items_show_count': 2,
            'corporate_endorsements_text': _('Real Career Impact'),
            'corporate_endorsements_show_count': 1,
            'see_more_text': _('See More'),
            'see_less_text': _('See Less'),
            'confirm_button_text': _('Confirm Program'),
            'summary_header': _('Program Summary'),
            'price_text': _('Price'),
            'length_text': _('Length'),
            'effort_text': _('Effort'),
            'level_text': _('Level'),
            'course_full_description_text': _('About This Course'),
            'staff_text': _('Course Staff'),
            'close_modal_button_text': _('Close'),
            'program_not_eligible_for_one_click_purchase_text': _('Program not eligible for one-click purchase.'),
            'program_type_description_header': _('What is an {platform_name} {program_type}?').format(
                platform_name=platform_name,
                program_type=program_type,
            ),
            'platform_description_header': _('What is {platform_name}?').format(
                platform_name=platform_name
            ),
            'organization_name': organization.get('name'),
            'organization_logo': organization.get('logo_image_url'),
            'organization_text': _('Presented by {organization}').format(organization=organization.get('name')),
            'page_title': _('Confirm your {item}').format(item=item),
            'program_type_logo': program_type_details['logo_image'].get('medium', {}).get('url', ''),
            'program_type': program_type,
            'program_type_description': get_program_type_description(program_type),
            'program_title': program_title,
            'program_subtitle': program_details['subtitle'],
            'program_overview': program_details['overview'],
            'program_price': get_price_text(discount_data.get('total_incl_tax_excl_discounts', 0), request),
            'program_discounted_price': get_price_text(discount_data.get('total_incl_tax', 0), request),
            'is_discounted': discount_data.get('is_discounted', False),
            'courses': program_courses,
            'item_bullet_points': [
                _('Credit- and Certificate-eligible'),
                _('Self-paced; courses can be taken in any order'),
            ],
            'purchase_text': _('{purchase_action} for').format(purchase_action=purchase_action),
            'expected_learning_items': program_details['expected_learning_items'],
            'corporate_endorsements': program_details['corporate_endorsements'],
            'course_count_text': course_count_text,
            'length_info_text': length_info_text,
            'effort_info_text': effort_info_text,
            'is_learner_eligible_for_one_click_purchase': one_click_purchase_eligibility,
        })
        return render(request, 'enterprise/enterprise_program_enrollment_page.html', context=context_data)


Instruction:
Implement a Python 3 function for
getting the Enterprise s Program and its associated Entry Point.

Response:
def get(self, request, enterprise_uuid, program_uuid):
        """
        Show Program Landing page for the Enterprise's Program.

        Render the Enterprise's Program Enrollment page for a specific program.
        The Enterprise and Program are both selected by their respective UUIDs.

        Unauthenticated learners will be redirected to enterprise-linked SSO.

        A 404 will be raised if any of the following conditions are met:
            * No enterprise customer UUID query parameter ``enterprise_uuid`` found in request.
            * No enterprise customer found against the enterprise customer
                uuid ``enterprise_uuid`` in the request kwargs.
            * No Program can be found given ``program_uuid`` either at all or associated with
                the Enterprise..
        """
        verify_edx_resources()

        enterprise_customer = get_enterprise_customer_or_404(enterprise_uuid)
        context_data = get_global_context(request, enterprise_customer)
        program_details, error_code = self.get_program_details(request, program_uuid, enterprise_customer)
        if error_code:
            return render(
                request,
                ENTERPRISE_GENERAL_ERROR_PAGE,
                context=context_data,
                status=404,
            )
        if program_details['certificate_eligible_for_program']:
            # The user is already enrolled in the program, so redirect to the program's dashboard.
            return redirect(LMS_PROGRAMS_DASHBOARD_URL.format(uuid=program_uuid))

        # Check to see if access to any of the course runs in the program are restricted for this user.
        course_run_ids = []
        for course in program_details['courses']:
            for course_run in course['course_runs']:
                course_run_ids.append(course_run['key'])
        embargo_url = EmbargoApiClient.redirect_if_blocked(course_run_ids, request.user, get_ip(request), request.path)
        if embargo_url:
            return redirect(embargo_url)

        return self.get_enterprise_program_enrollment_page(request, enterprise_customer, program_details)


Instruction:
Create a Python 3 function to
process a submitted track selection form for the enterprise.

Response:
def post(self, request, enterprise_uuid, program_uuid):
        """
        Process a submitted track selection form for the enterprise.
        """
        verify_edx_resources()

        # Create a link between the user and the enterprise customer if it does not already exist.
        enterprise_customer = get_enterprise_customer_or_404(enterprise_uuid)
        with transaction.atomic():
            enterprise_customer_user, __ = EnterpriseCustomerUser.objects.get_or_create(
                enterprise_customer=enterprise_customer,
                user_id=request.user.id
            )
            enterprise_customer_user.update_session(request)

        context_data = get_global_context(request, enterprise_customer)
        program_details, error_code = self.get_program_details(request, program_uuid, enterprise_customer)
        if error_code:
            return render(
                request,
                ENTERPRISE_GENERAL_ERROR_PAGE,
                context=context_data,
                status=404,
            )
        if program_details['certificate_eligible_for_program']:
            # The user is already enrolled in the program, so redirect to the program's dashboard.
            return redirect(LMS_PROGRAMS_DASHBOARD_URL.format(uuid=program_uuid))

        basket_page = '{basket_url}?{params}'.format(
            basket_url=BASKET_URL,
            params=urlencode(
                [tuple(['sku', sku]) for sku in program_details['skus']] +
                [tuple(['bundle', program_uuid])]
            )
        )
        if get_data_sharing_consent(
                enterprise_customer_user.username,
                enterprise_customer.uuid,
                program_uuid=program_uuid,
        ).consent_required():
            return redirect(
                '{grant_data_sharing_url}?{params}'.format(
                    grant_data_sharing_url=reverse('grant_data_sharing_permissions'),
                    params=urlencode(
                        {
                            'next': basket_page,
                            'failure_url': reverse(
                                'enterprise_program_enrollment_page',
                                args=[enterprise_customer.uuid, program_uuid]
                            ),
                            'enterprise_customer_uuid': enterprise_customer.uuid,
                            'program_uuid': program_uuid,
                        }
                    )
                )
            )

        return redirect(basket_page)


Instruction:
Can you implement a function in Python 3 that
gets the base variables for any view to route to.

Response:
def get_path_variables(**kwargs):
        """
        Get the base variables for any view to route to.

        Currently gets:
        - `enterprise_uuid` - the UUID of the enterprise customer.
        - `course_run_id` - the ID of the course, if applicable.
        - `program_uuid` - the UUID of the program, if applicable.
        """
        enterprise_customer_uuid = kwargs.get('enterprise_uuid', '')
        course_run_id = kwargs.get('course_id', '')
        course_key = kwargs.get('course_key', '')
        program_uuid = kwargs.get('program_uuid', '')

        return enterprise_customer_uuid, course_run_id, course_key, program_uuid


Instruction:
How would you code a function in Python 3 to
get the course run ID for a user

Response:
def get_course_run_id(user, enterprise_customer, course_key):
        """
        User is requesting a course, we need to translate that into the current course run.

        :param user:
        :param enterprise_customer:
        :param course_key:
        :return: course_run_id
        """
        try:
            course = CourseCatalogApiServiceClient(enterprise_customer.site).get_course_details(course_key)
        except ImproperlyConfigured:
            raise Http404

        users_all_enrolled_courses = EnrollmentApiClient().get_enrolled_courses(user.username)
        users_active_course_runs = get_active_course_runs(
            course,
            users_all_enrolled_courses
        ) if users_all_enrolled_courses else []
        course_run = get_current_course_run(course, users_active_course_runs)
        if course_run:
            course_run_id = course_run['key']
            return course_run_id
        else:
            raise Http404


Instruction:
Can you generate a brief explanation for the following Python 3 code
def eligible_for_direct_audit_enrollment(self, request, enterprise_customer, resource_id, course_key=None):
        course_identifier = course_key if course_key else resource_id

        # Return it in one big statement to utilize short-circuiting behavior. Avoid the API call if possible.
        return request.GET.get('audit') and \
            request.path == self.COURSE_ENROLLMENT_VIEW_URL.format(enterprise_customer.uuid, course_identifier) and \
            enterprise_customer.catalog_contains_course(resource_id) and \
            EnrollmentApiClient().has_course_mode(resource_id, 'audit')

Response: Returns whether a request is eligible for direct audit enrollment for a particular enterprise customer.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def redirect(self, request, *args, **kwargs):
        enterprise_customer_uuid, course_run_id, course_key, program_uuid = RouterView.get_path_variables(**kwargs)
        resource_id = course_key or course_run_id or program_uuid
        # Replace enterprise UUID and resource ID with '{}', to easily match with a path in RouterView.VIEWS. Example:
        # /enterprise/fake-uuid/course/course-v1:cool+course+2017/enroll/ -> /enterprise/{}/course/{}/enroll/
        path = re.sub('{}|{}'.format(enterprise_customer_uuid, re.escape(resource_id)), '{}', request.path)

        # Remove course_key from kwargs if it exists because delegate views are not expecting it.
        kwargs.pop('course_key', None)

        return self.VIEWS[path].as_view()(request, *args, **kwargs)

Response: Redirects to the appropriate view depending on where the user came from.


Instruction:
Can you write a function in Python 3 where it
runs some custom GET logic for Enterprise workflows before routing the user through existing views. In particular, before routing to existing views: - If the requested resource is a course, find the current course run for that course, and make that course run the requested resource instead. - Look to see whether a request is eligible for direct audit enrollment, and if so, directly enroll the user.

Response:
def get(self, request, *args, **kwargs):
        """
        Run some custom GET logic for Enterprise workflows before routing the user through existing views.

        In particular, before routing to existing views:
        - If the requested resource is a course, find the current course run for that course,
          and make that course run the requested resource instead.
        - Look to see whether a request is eligible for direct audit enrollment, and if so, directly enroll the user.
        """
        enterprise_customer_uuid, course_run_id, course_key, program_uuid = RouterView.get_path_variables(**kwargs)
        enterprise_customer = get_enterprise_customer_or_404(enterprise_customer_uuid)
        if course_key:
            try:
                course_run_id = RouterView.get_course_run_id(request.user, enterprise_customer, course_key)
            except Http404:
                context_data = get_global_context(request, enterprise_customer)
                error_code = 'ENTRV000'
                log_message = (
                    'Could not find course run with id {course_run_id} '
                    'for course key {course_key} and program_uuid {program_uuid} '
                    'for enterprise_customer_uuid {enterprise_customer_uuid} '
                    'Returned error code {error_code} to user {userid}'.format(
                        course_key=course_key,
                        course_run_id=course_run_id,
                        enterprise_customer_uuid=enterprise_customer_uuid,
                        error_code=error_code,
                        userid=request.user.id,
                        program_uuid=program_uuid,
                    )
                )
                return render_page_with_error_code_message(request, context_data, error_code, log_message)
            kwargs['course_id'] = course_run_id

        # Ensure that the link is saved to the database prior to making some call in a downstream view
        # which may need to know that the user belongs to an enterprise customer.
        with transaction.atomic():
            enterprise_customer_user, __ = EnterpriseCustomerUser.objects.get_or_create(
                enterprise_customer=enterprise_customer,
                user_id=request.user.id
            )
            enterprise_customer_user.update_session(request)

        # Directly enroll in audit mode if the request in question has full direct audit enrollment eligibility.
        resource_id = course_run_id or program_uuid
        if self.eligible_for_direct_audit_enrollment(request, enterprise_customer, resource_id, course_key):
            try:
                enterprise_customer_user.enroll(resource_id, 'audit', cohort=request.GET.get('cohort', None))
                track_enrollment('direct-audit-enrollment', request.user.id, resource_id, request.get_full_path())
            except (CourseEnrollmentDowngradeError, CourseEnrollmentPermissionError):
                pass
            # The courseware view logic will check for DSC requirements, and route to the DSC page if necessary.
            return redirect(LMS_COURSEWARE_URL.format(course_id=resource_id))

        return self.redirect(request, *args, **kwargs)