Instruction:
Can you tell what is the following Python 3 function doing
def delete_organization(self, organization_id):
        log.warning('Deleting organization...')
        url = 'rest/servicedeskapi/organization/{}'.format(organization_id)

        return self.delete(url, headers=self.experimental_headers)

Response: Delete an organization for a given organization ID


Instruction:
Write a Python 3 script to
add users to an organization

Response:
def add_users_to_organization(self, organization_id, users_list):
        """
        Adds users to an organization
        users_list is a list of strings

        :param organization_id: str
        :param users_list: list
        :return:
        """
        log.warning('Adding users...')
        url = 'rest/servicedeskapi/organization/{}/user'.format(organization_id)
        data = {'usernames': users_list}

        return self.post(url, headers=self.experimental_headers, data=data)


Instruction:
Here you have a function in Python 3, explain what it does
def remove_users_from_organization(self, organization_id, users_list):
        log.warning('Removing users...')
        url = 'rest/servicedeskapi/organization/{}/user'.format(organization_id)
        data = {'usernames': users_list}

        return self.delete(url, headers=self.experimental_headers, data=data)

Response: Removes users from an organization


Instruction:
Here you have a function in Python 3, explain what it does
def create_attachment(self, service_desk_id, issue_id_or_key, filename, public=True, comment=None):
        log.warning('Creating attachment...')

        # Create temporary attachment
        temp_attachment_id = self.attach_temporary_file(service_desk_id, filename)

        # Add attachments
        return self.add_attachment(issue_id_or_key, temp_attachment_id, public, comment)

Response: Create a temporary attachment and add it to the cache.


Instruction:
How would you explain what the following Python 3 function does
def attach_temporary_file(self, service_desk_id, filename):
        headers = {'X-Atlassian-Token': 'no-check', 'X-ExperimentalApi': 'opt-in'}
        url = 'rest/servicedeskapi/servicedesk/{}/attachTemporaryFile'.format(service_desk_id)

        with open(filename, 'rb') as file:
            result = self.post(url, headers=headers, files={'file': file}).get('temporaryAttachments')
            temp_attachment_id = result[0].get('temporaryAttachmentId')

            return temp_attachment_id

Response: Create temporary attachment which can later be converted into permanent attachment


Instruction:
Can you generate the documentation for the following Python 3 function
def add_attachment(self, issue_id_or_key, temp_attachment_id, public=True, comment=None):
        log.warning('Adding attachment')
        data = {
            'temporaryAttachmentIds': [temp_attachment_id],
            'public': public,
            'additionalComment': {'body': comment}
        }
        url = 'rest/servicedeskapi/request/{}/attachment'.format(issue_id_or_key)

        return self.post(url, headers=self.experimental_headers, data=data)

Response: Adds temporary attachment to customer request


Instruction:
Write a Python 3 script for
getting the SLA information for a given request ID or key and SLA metric ID

Response:
def get_sla_by_id(self, issue_id_or_key, sla_id):
        """
        Get the SLA information for a customer request for a given request ID or key and SLA metric ID
        IMPORTANT: The calling user must be an agent

        :param issue_id_or_key: str
        :param sla_id: str
        :return: SLA information
        """
        url = 'rest/servicedeskapi/request/{0}/sla/{1}'.format(issue_id_or_key, sla_id)

        return self.get(url)


Instruction:
Can you generate the documentation for the following Python 3 function
def get_approvals(self, issue_id_or_key, start=0, limit=50):
        url = 'rest/servicedeskapi/request/{}/approval'.format(issue_id_or_key)
        params = {}
        if start is not None:
            params['start'] = int(start)
        if limit is not None:
            params['limit'] = int(limit)

        return self.get(url, headers=self.experimental_headers, params=params).get('values')

Response: Get all approvals on a given request ID or Key.


Instruction:
Explain what the following Python 3 code does
def get_approval_by_id(self, issue_id_or_key, approval_id):
        url = 'rest/servicedeskapi/request/{0}/approval/{1}'.format(issue_id_or_key, approval_id)

        return self.get(url, headers=self.experimental_headers)

Response: Get an approval for a given approval ID


Instruction:
How would you explain what the following Python 3 function does
def answer_approval(self, issue_id_or_key, approval_id, decision):
        url = 'rest/servicedeskapi/request/{0}/approval/{1}'.format(issue_id_or_key, approval_id)
        data = {'decision': decision}

        return self.post(url, headers=self.experimental_headers, data=data)

Response: Answer a pending approval


Instruction:
Can you write a function in Python 3 where it
gets queue settings on project

Response:
def get_queue_settings(self, project_key):
        """
        Get queue settings on project

        :param project_key: str
        :return:
        """
        url = 'rest/servicedeskapi/queues/{}'.format(project_key)

        return self.get(url, headers=self.experimental_headers)


Instruction:
How would you code a function in Python 3 to
add one or more customers to the given service desk.

Response:
def add_customers(self, service_desk_id, list_of_usernames):
        """
        Adds one or more existing customers to the given service desk.
        If you need to create a customer, see Create customer method.

        Administer project permission is required, or agents if public signups
        and invites are enabled for the Service Desk project.

        :param service_desk_id: str
        :param list_of_usernames: list
        :return: the customers added to the service desk
        """
        url = 'rest/servicedeskapi/servicedesk/{}/customer'.format(service_desk_id)
        data = {'usernames': list_of_usernames}

        return self.post(url, headers=self.experimental_headers, data=data)


Instruction:
Write a Python 3 script for
getting the queues defined inside a service desk.

Response:
def get_queues(self, service_desk_id, include_count=False, start=0, limit=50):
        """
        Returns a page of queues defined inside a service desk, for a given service desk ID.
        The returned queues will include an issue count for each queue (represented in issueCount field)
        if the query param includeCount is set to true (defaults to false).

        Permissions: The calling user must be an agent of the given service desk.

        :param service_desk_id: str
        :param include_count: bool
        :param start: int
        :param limit: int
        :return: a page of queues
        """
        url = 'rest/servicedeskapi/servicedesk/{}/queue'.format(service_desk_id)
        params = {}

        if include_count is not None:
            params['includeCount'] = bool(include_count)
        if start is not None:
            params['start'] = int(start)
        if limit is not None:
            params['limit'] = int(limit)

        return self.get(url, headers=self.experimental_headers, params=params)


Instruction:
How would you explain what the following Python 3 function does
def get_issues_in_queue(self, service_desk_id, queue_id, start=0, limit=50):
        url = 'rest/servicedeskapi/servicedesk/{0}/queue/{1}/issue'.format(service_desk_id, queue_id)
        params = {}

        if start is not None:
            params['start'] = int(start)
        if limit is not None:
            params['limit'] = int(limit)

        return self.get(url, headers=self.experimental_headers, params=params)

Response: Get a page of issues inside a queue for a given service desk ID and queue ID.


Instruction:
Here you have a function in Python 3, explain what it does
def project_plans(self, project_key):
        resource = 'project/{}'.format(project_key, max_results=25)
        return self.base_list_call(resource, expand='plans', favourite=False, clover_enabled=False, max_results=25,
                                   elements_key='plans', element_key='plan')

Response: Returns a generator with the plans in a given project


Instruction:
Here you have a function in Python 3, explain what it does
def results(self, project_key=None, plan_key=None, job_key=None, build_number=None, expand=None, favourite=False,
                clover_enabled=False, issue_key=None, start_index=0, max_results=25):
        """
        Get results as generic method
        :param project_key:
        :param plan_key:
        :param job_key:
        :param build_number:
        :param expand:
        :param favourite:
        :param clover_enabled:
        :param issue_key:
        :param start_index:
        :param max_results:
        :return:
        """
        resource = "result"
        if project_key and plan_key and job_key and build_number:
            resource += "/{}-{}-{}/{}".format(project_key, plan_key, job_key, build_number)
        elif project_key and plan_key and build_number:
            resource += "/{}-{}/{}".format(project_key, plan_key, build_number)
        elif project_key and plan_key:
            resource += "/{}-{}".format(project_key, plan_key)
        elif project_key:
            resource += '/' + project_key

        params = {}
        if issue_key:
            params['issueKey'] = issue_key
        return self.base_list_call(resource, expand=expand, favourite=favourite, clover_enabled=clover_enabled,
                                   start_index=start_index, max_results=max_results,
                                   elements_key='results', element_key='result', **params)

Response: Get results as generic method


Instruction:
Can you create a Python 3 function that
gets the results for a specific plan.

Response:
def plan_results(self, project_key, plan_key, expand=None, favourite=False, clover_enabled=False, label=None,
                     issue_key=None, start_index=0, max_results=25):
        """
        Get Plan results
        :param project_key:
        :param plan_key:
        :param expand:
        :param favourite:
        :param clover_enabled:
        :param label:
        :param issue_key:
        :param start_index:
        :param max_results:
        :return:
        """
        return self.results(project_key, plan_key, expand=expand, favourite=favourite, clover_enabled=clover_enabled,
                            label=label, issue_key=issue_key, start_index=start_index, max_results=max_results)


Instruction:
Create a Python 3 function for
returning details of a specific build result

Response:
def build_result(self, build_key, expand=None):
        """
        Returns details of a specific build result
        :param expand: expands build result details on request. Possible values are: artifacts, comments, labels,
        Jira Issues, stages. stages expand is available only for top level plans. It allows to drill down to job results
        using stages.stage.results.result. All expand parameters should contain results.result prefix.
        :param build_key: Should be in the form XX-YY[-ZZ]-99, that is, the last token should be an integer representing
        the build number
        """
        try:
            int(build_key.split('-')[-1])
            resource = "result/{}".format(build_key)
            return self.base_list_call(resource, expand, favourite=False, clover_enabled=False,
                                       start_index=0, max_results=25)
        except ValueError:
            raise ValueError('The key "{}" does not correspond to a build result'.format(build_key))


Instruction:
Explain what the following Python 3 code does
def deployment_dashboard(self, project_id=None):
        resource = 'deploy/dashboard/{}'.format(project_id) if project_id else 'deploy/dashboard'
        return self.get(self.resource_url(resource))

Response: Returns the current status of each deployment environment.


Instruction:
Can you tell what is the following Python 3 function doing
def plan_branches(self, plan_key, expand=None, favourite=False, clover_enabled=False, max_results=25):
        resource = 'plan/{}/branch'.format(plan_key)
        return self.base_list_call(resource, expand, favourite, clover_enabled, max_results,
                                   elements_key='branches', element_key='branch')

Response: Get branch information for a given plan.


Instruction:
Make a summary of the following Python 3 code
def is_email(string):
    email_regex = r'^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*$'

    if isinstance(string, str) and not re.match(email_regex, string):
        return False
    else:
        return True

Response: Check if a string is an email address.


Instruction:
Write a Python 3 script to
return a list of html elements for the given data.

Response:
def html_list(data):
    """
    >>> html_list(['example.com', 'admin1@example.com', 'admin2@example.com'])
    '

example.com

admin1@example.com

admin2@example.com

'
    """
    html = '
'

    for item in data:

        if isinstance(item, dict):
            if item.get('email'):
                item = html_email(item.get('email'), item.get('name', None))
            elif item.get('name'):
                item = item.get('name')

        if is_email(item):
            item = html_email(item, item)

        html += '
{}
'.format(item)

    return html + '
'


Instruction:
Can you generate a brief explanation for the following Python 3 code
def html_table_header_row(data):
    html = '\n\t
'

    for th in data:
        title = th.replace('_', ' ').title()
        html += '{}	'.format(title)

    return html + '
'

Response: Return a table header row.


Instruction:
Can you generate the documentation for the following Python 3 function
def html_row_with_ordered_headers(data, headers):
    html = '\n\t
'

    for header in headers:
        element = data[header]

        if isinstance(element, list):
            element = html_list(element)

        if is_email(element):
            element = html_email(element)

        html += '{}	'.format(element)

    return html + '
'

Response: Returns an HTML row with ordered headers.


Instruction:
Explain what the following Python 3 code does
def html_table_from_dict(data, ordering):
    html = '

'
    html += html_table_header_row(ordering)

    for row in data:
        html += html_row_with_ordered_headers(row, ordering)

    return html + '\n

'

Response: This function will convert the dictionary into an HTML table.


Instruction:
Given the following Python 3 function, write the documentation
def get_plugins_info(self, limit=10, offset=10):
        params = {}
        if offset:
            params['offset'] = offset
        if limit:
            params['limit'] = limit
        url = 'rest/1.0/plugins'
        return (self.get(url, params=params) or {}).get('plugins')

Response: Get the plugins info for a specific user.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_vendors_info(self, limit=10, offset=10):
        params = {}
        if offset:
            params['offset'] = offset
        if limit:
            params['limit'] = limit
        url = 'rest/1.0/vendors'
        return (self.get(url, params=params) or {}).get('vendors')

Response: Get vendors info for a specific user.


Instruction:
Make a summary of the following Python 3 code
def get_application_info(self, limit=10, offset=10):
        params = {}
        if offset:
            params['offset'] = offset
        if limit:
            params['limit'] = limit
        url = 'rest/2/applications'
        return self.get(url, params=params)

Response: Get information about applications.


Instruction:
Write a Python 3 function for
providing the project list

Response:
def project_list(self, limit=None):
        """
        Provide the project list
        :param limit: OPTIONAL 25 is default
        :return:
        """
        params = {}
        if limit:
            params['limit'] = limit
        return (self.get('rest/api/1.0/projects', params=params) or {}).get('values')


Instruction:
Write a Python 3 script to
get the project info for a given key

Response:
def project(self, key):
        """
        Provide project info
        :param key:
        :return:
        """
        url = 'rest/api/1.0/projects/{0}'.format(key)
        return (self.get(url) or {}).get('values')


Instruction:
Can you tell what is the following Python 3 function doing
def create_project(self, key, name, description=""):
        url = 'rest/api/1.0/projects'
        data = {"key": key,
                "name": name,
                "description": description
                }
        return self.post(url, data=data)

Response: Create a new project in the nacore store


Instruction:
Can you create a Python 3 function that
gets project administrators for project key

Response:
def project_users_with_administrator_permissions(self, key):
        """
        Get project administrators for project
        :param key: project key
        :return: project administrators
        """
        project_administrators = [user['user'] for user in self.project_users(key)
                                  if user['permission'] == 'PROJECT_ADMIN']
        for group in self.project_groups_with_administrator_permissions(key):
            for user in self.group_members(group):
                project_administrators.append(user)
        return project_administrators


Instruction:
Here you have a function in Python 3, explain what it does
def project_groups(self, key, limit=99999, filter_str=None):
        url = 'rest/api/1.0/projects/{key}/permissions/groups'.format(key=key)
        params = {}
        if limit:
            params['limit'] = limit
        if filter_str:
            params['filter'] = filter_str
        return (self.get(url, params=params) or {}).get('values')

Response:
Get Project Groups
        :param key:
        :param limit: OPTIONAL: The limit of the number of groups to return, this may be restricted by
                            fixed system limits. Default by built-in method: 99999
        :param filter_str: OPTIONAL: group filter string
        :return:


Instruction:
Make a summary of the following Python 3 code
def repo_groups(self, project_key, repo_key, limit=99999, filter_str=None):
        url = 'rest/api/1.0/projects/{project_key}/repos/{repo_key}/permissions/groups'.format(
            project_key=project_key,
            repo_key=repo_key)
        params = {}
        if limit:
            params['limit'] = limit
        if filter_str:
            params['filter'] = filter_str
        return (self.get(url, params=params) or {}).get('values')

Response:
Get repository Groups
        :param project_key:
        :param repo_key:
        :param limit: OPTIONAL: The limit of the number of groups to return, this may be restricted by
                            fixed system limits. Default by built-in method: 99999
        :param filter_str: OPTIONAL: group filter string
        :return:


Instruction:
How would you code a function in Python 3 to
get the members of a group.

Response:
def group_members(self, group, limit=99999):
        """
        Get group of members
        :param group:
        :param limit: OPTIONAL: The limit of the number of users to return, this may be restricted by
                        fixed system limits. Default by built-in method: 99999
        :return:
        """
        url = 'rest/api/1.0/admin/groups/more-members'
        params = {}
        if limit:
            params['limit'] = limit
        if group:
            params['context'] = group
        return (self.get(url, params=params) or {}).get('values')


Instruction:
Given the following Python 3 function, write the documentation
def all_project_administrators(self):
        for project in self.project_list():
            log.info('Processing project: {0} - {1}'.format(project.get('key'), project.get('name')))
            yield {
                'project_key': project.get('key'),
                'project_name': project.get('name'),
                'project_administrators': [{'email': x['emailAddress'], 'name': x['displayName']}
                                           for x in self.project_users_with_administrator_permissions(project['key'])]}

Response: Get the list of project administrators that are in the system.


Instruction:
Create a Python 3 function for
getting repositories list from project

Response:
def repo_list(self, project_key, start=None, limit=25):
        """
        Get repositories list from project
        :param project_key:
        :param start: OPTIONAL: The start of the
        :param limit: OPTIONAL: The limit of the number of repositories to return, this may be restricted by
                        fixed system limits. Default by built-in method: 25
        :return:
        """
        url = 'rest/api/1.0/projects/{projectKey}/repos'.format(projectKey=project_key)
        params = {}
        if limit:
            params['limit'] = limit
        if start:
            params['start'] = start
        response = self.get(url, params=params)
        if response.get('isLastPage'):
            log.info('This is a last page of the result')
        else:
            log.info('Next page start at {}'.format(response.get('nextPageStart')))
        return (response or {}).get('values')


Instruction:
Can you create a Python 3 function that
creates a new repository.

Response:
def create_repo(self, project_key, repository, forkable=False, is_private=True):
        """Create a new repository.

        Requires an existing project in which this repository will be created. The only parameters which will be used
        are name and scmId.

        The authenticated user must have PROJECT_ADMIN permission for the context project to call this resource.

        :param project_key: The project matching the projectKey supplied in the resource path as shown in URL.
        :type project_key: str
        :param repository: Name of repository to create (i.e. "My repo").
        :type repository: str
        :param forkable: Set the repository to be forkable or not.
        :type forkable: bool
        :param is_private: Set the repository to be private or not.
        :type is_private: bool
        :return:
            201 - application/json (repository)
            400 - application/json (errors)
            401 - application/json (errors)
            409 - application/json (errors)
        :rtype: requests.Response
        """

        url = 'rest/api/1.0/projects/{projectKey}/repos'.format(projectKey=project_key)
        data = {
            "name": repository,
            "scmId": "git",
            "forkable": forkable,
            "is_private": is_private
        }
        return self.post(url, data=data)


Instruction:
Given the following Python 3 function, write the documentation
def repo_all_list(self, project_key):
        url = 'rest/api/1.0/projects/{projectKey}/repos'.format(projectKey=project_key)
        params = {}
        start = 0
        params['start'] = start
        response = self.get(url, params=params)
        if 'values' not in response:
            return []
        repo_list = (response or {}).get('values')
        while not response.get('isLastPage'):
            start = response.get('nextPageStart')
            params['start'] = start
            response = self.get(url, params=params)
            repo_list += (response or {}).get('values')
        return repo_list

Response: Get all repositories list from project


Instruction:
Can you tell what is the following Python 3 function doing
def get_branches(self, project, repository, base=None, filter=None, start=0, limit=99999, details=True,
                     order_by='MODIFICATION'):
        """
        Retrieve the branches matching the supplied filterText param.
        The authenticated user must have REPO_READ permission for the specified repository to call this resource.
        :param start:
        :param project:
        :param repository:
        :param base: base branch/tag to compare each branch to (for the metadata providers that uses that information)
        :param filter:
        :param limit: OPTIONAL: The limit of the number of branches to return, this may be restricted by
                    fixed system limits. Default by built-in method: 99999
        :param details: whether to retrieve plugin-provided metadata about each branch
        :param order_by: OPTIONAL: ordering of refs either ALPHABETICAL (by name) or MODIFICATION (last updated)
        :return:
        """
        url = 'rest/api/1.0/projects/{project}/repos/{repository}/branches'.format(project=project,
                                                                                repository=repository)
        params = {}
        if start:
            params['start'] = start
        if limit:
            params['limit'] = limit
        if filter:
            params['filterText'] = filter
        if base:
            params['base'] = base
        if order_by:
            params['orderBy'] = order_by
        params['details'] = details

        return (self.get(url, params=params) or {}).get('values')

Response: Retrieve the branches for the specified filterText param.


Instruction:
How would you explain what the following Python 3 function does
def create_branch(self, project_key, repository, name, start_point, message=""):

        url = 'rest/api/1.0/projects/{projectKey}/repos/{repository}/branches'.format(projectKey=project_key,
                                                                                repository=repository)
        data = {
            "name": name,
            "startPoint": start_point,
            "message": message
        }
        return self.post(url, data=data)

Response: Creates a branch using the information provided in the request.


Instruction:
Can you generate the documentation for the following Python 3 function
def delete_branch(self, project, repository, name, end_point):

        url = 'rest/branch-utils/1.0/projects/{project}/repos/{repository}/branches'.format(project=project,
                                                                                repository=repository)

        data = {"name": str(name), "endPoint": str(end_point)}
        return self.delete(url, data=data)

Response: Delete branch from related repo


Instruction:
Write a Python 3 function for
getting pull requests in a repository.

Response:
def get_pull_requests(self, project, repository, state='OPEN', order='newest', limit=100, start=0):
        """
        Get pull requests
        :param project:
        :param repository:
        :param state:
        :param order: OPTIONAL: defaults to NEWEST) the order to return pull requests in, either OLDEST
                                (as in: "oldest first") or NEWEST.
        :param limit:
        :param start:
        :return:
        """
        url = 'rest/api/1.0/projects/{project}/repos/{repository}/pull-requests'.format(project=project,
                                                                                repository=repository)
        params = {}
        if state:
            params['state'] = state
        if limit:
            params['limit'] = limit
        if start:
            params['start'] = start
        if order:
            params['order'] = order
        response = self.get(url, params=params)
        if 'values' not in response:
            return []
        pr_list = (response or {}).get('values')
        while not response.get('isLastPage'):
            start = response.get('nextPageStart')
            params['start'] = start
            response = self.get(url, params=params)
            pr_list += (response or {}).get('values')
        return pr_list


Instruction:
Explain what the following Python 3 code does
def get_pull_requests_activities(self, project, repository, pull_request_id):
        url = 'rest/api/1.0/projects/{project}/repos/{repository}/pull-requests/{pullRequestId}/activities'.format(
            project=project,
            repository=repository,
            pullRequestId=pull_request_id)
        params = {'start': 0}
        response = self.get(url, params=params)
        if 'values' not in response:
            return []
        activities_list = (response or {}).get('values')
        while not response.get('isLastPage'):
            params['start'] = response.get('nextPageStart')
            response = self.get(url, params=params)
            activities_list += (response or {}).get('values')
        return activities_list

Response: Get the list of pull requests activities within a pull request.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_pull_requests_changes(self, project, repository, pull_request_id):
        url = 'rest/api/1.0/projects/{project}/repos/{repository}/pull-requests/{pullRequestId}/changes'.format(
            project=project,
            repository=repository,
            pullRequestId=pull_request_id)
        params = {'start': 0}
        response = self.get(url, params=params)
        if 'values' not in response:
            return []
        changes_list = (response or {}).get('values')
        while not response.get('isLastPage'):
            params['start'] = response.get('nextPageStart')
            if params['start'] is None:
                log.warning('Too many changes in pull request. Changes list is incomplete.')
                break
            response = self.get(url, params=params)
            changes_list += (response or {}).get('values')
        return changes_list

Response: Get the list of all changes in a pull request.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_pull_requests_commits(self, project, repository, pull_request_id):
        url = 'rest/api/1.0/projects/{project}/repos/{repository}/pull-requests/{pullRequestId}/commits'.format(
            project=project,
            repository=repository,
            pullRequestId=pull_request_id)
        params = {'start': 0}
        response = self.get(url, params=params)
        if 'values' not in response:
            return []
        commits_list = (response or {}).get('values')
        while not response.get('isLastPage'):
            params['start'] = response.get('nextPageStart')
            response = self.get(url, params=params)
            commits_list += (response or {}).get('values')
        return commits_list

Response: Get the commits for a pull request.


Instruction:
Can you implement a function in Python 3 that
adds a comment into a pull request

Response:
def add_pull_request_comment(self, project, repository, pull_request_id, text):
        """
        Add comment into pull request
        :param project:
        :param repository:
        :param pull_request_id: the ID of the pull request within the repository
        :param text comment text
        :return:
        """
        url = 'rest/api/1.0/projects/{project}/repos/{repository}/pull-requests/{pullRequestId}/comments'.format(
            project=project,
            repository=repository,
            pullRequestId=pull_request_id)
        body = {'text': text}
        return self.post(url, data=body)


Instruction:
Write a Python 3 script to
get a pull request.

Response:
def get_pullrequest(self, project, repository, pull_request_id):
        """
        Retrieve a pull request.
        The authenticated user must have REPO_READ permission
        for the repository that this pull request targets to call this resource.
        :param project:
        :param repository:
        :param pull_request_id: the ID of the pull request within the repository
        :return:
        """
        url = 'rest/api/1.0/projects/{project}/repos/{repository}/pull-requests/{pullRequestId}'.format(project=project,
                                                                                repository=repository,
                                                                                pullRequestId=pull_request_id)
        return self.get(url)


Instruction:
Given the following Python 3 function, write the documentation
def get_tags(self, project, repository, filter='', limit=1000, order_by=None, start=0):
        url = 'rest/api/1.0/projects/{project}/repos/{repository}/tags'.format(project=project,
                                                                               repository=repository)
        params = {}
        if start:
            params['start'] = start
        if limit:
            params['limit'] = limit
        if filter:
            params['filter'] = filter
        if order_by:
            params['orderBy'] = order_by
        result = self.get(url, params=params)
        if result.get('isLastPage'):
            log.info('This is a last page of the result')
        else:
            log.info('Next page start at {}'.format(result.get('nextPageStart')))
        return (result or {}).get('values')

Response: Retrieve the tags for a given context repository.


Instruction:
Explain what the following Python 3 code does
def get_project_tags(self, project, repository, tag_name):
        url = 'rest/api/1.0/projects/{project}/repos/{repository}/tags/{tag}'.format(project=project,
                                                                                repository=repository,
                                                                                tag=tag_name)
        return self.get(url)

Response: Get a specific tag in the specified repository.


Instruction:
Write a Python 3 script for
setting the tag name and revision of the current context.

Response:
def set_tag(self, project, repository, tag_name, commit_revision, description=None):
        """
        Creates a tag using the information provided in the {@link RestCreateTagRequest request}
        The authenticated user must have REPO_WRITE permission for the context repository to call this resource.
        :param project:
        :param repository:
        :param tag_name:
        :param commit_revision: commit hash
        :param description: OPTIONAL:
        :return:
        """
        url = 'rest/api/1.0/projects/{project}/repos/{repository}/tags'.format(project=project,
                                                                               repository=repository)
        body = {}
        if tag_name is not None:
            body['name'] = tag_name
        if tag_name is not None:
            body['startPoint'] = commit_revision
        if tag_name is not None:
            body['message'] = description
        return self.post(url, data=body)


Instruction:
Can you tell what is the following Python 3 function doing
def delete_tag(self, project, repository, tag_name):
        url = 'rest/git/1.0/projects/{project}/repos/{repository}/tags/{tag}'.format(project=project,
                                                                                repository=repository,
                                                                                tag=tag_name)
        return self.delete(url)

Response: Delete a tag from a context repository


Instruction:
Explain what the following Python 3 code does
def get_commits(self, project, repository, hash_oldest, hash_newest, limit=99999):
        url = 'rest/api/1.0/projects/{project}/repos/{repository}/commits'.format(project=project,
                                                                                repository=repository)
        params = {}
        if hash_oldest:
            params['since'] = hash_oldest
        if hash_newest:
            params['until'] = hash_newest
        if limit:
            params['limit'] = limit
        return (self.get(url, params=params) or {}).get('values')

Response: Get the list of commits from a repository.


Instruction:
Can you tell what is the following Python 3 function doing
def get_commit_info(self, project, repository, commit, path=None):
        url = 'rest/api/1.0/projects/{project}/repos/{repository}/commits/{commitId}'.format(project=project,
                                                                                repository=repository,
                                                                                commitId=commit)
        params = {}
        if path:
            params['path'] = path
        return self.get(url, params=params)

Response: Retrieve a single commit identified by its ID.


Instruction:
How would you explain what the following Python 3 function does
def get_changelog(self, project, repository, ref_from, ref_to, limit=99999):
        url = 'rest/api/1.0/projects/{project}/repos/{repository}/compare/commits'.format(project=project,
                                                                                repository=repository)
        params = {}
        if ref_from:
            params['from'] = ref_from
        if ref_to:
            params['to'] = ref_to
        if limit:
            params['limit'] = limit
        return (self.get(url, params=params) or {}).get('values')

Response: Get the change log between two refs.


Instruction:
Implement a Python 3 function for
retrieving a page of files from particular directory of a repository.

Response:
def get_file_list(self, project, repository, query, limit=100000):
        """
        Retrieve a page of files from particular directory of a repository.
        The search is done recursively, so all files from any sub-directory of the specified directory will be returned.
        The authenticated user must have REPO_READ permission for the specified repository to call this resource.
        :param project:
        :param repository:
        :param query: the commit ID or ref (e.g. a branch or tag) to list the files at.
                      If not specified the default branch will be used instead.
        :param limit: OPTIONAL
        :return:
        """
        url = 'rest/api/1.0/projects/{project}/repos/{repository}/files'.format(project=project,
                                                                                repository=repository)
        params = {}
        if query:
            params['at'] = query
        if limit:
            params['limit'] = limit
        return (self.get(url, params=params) or {}).get('values')


Instruction:
Can you tell what is the following Python 3 function doing
def get_content_of_file(self, project, repository, filename, at=None, markup=None):
        headers = self.form_token_headers
        url = 'projects/{project}/repos/{repository}/raw/{filename}/'.format(project=project,
                                                                             repository=repository,
                                                                             filename=filename)
        params = {}
        if at is not None:
            params['at'] = at
        if markup is not None:
            params['markup'] = markup
        return self.get(url, params=params, not_json_response=True, headers=headers)

Response: Retrieve the raw content of a file at a specified revision.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_branches_permissions(self, project, repository, limit=25):
        url = 'rest/branch-permissions/2.0/projects/{project}/repos/{repository}/restrictions'.format(project=project,
                                                                                repository=repository)
        params = {}
        if limit:
            params['limit'] = limit
        return self.get(url, params=params)

Response: Get branches permissions from a given repository


Instruction:
How would you explain what the following Python 3 function does
def reindex_repo_dev_panel(self, project, repository):
        url = 'rest/jira-dev/1.0/projects/{projectKey}/repos/{repositorySlug}/reindex'.format(projectKey=project,
                                                                                repositorySlug=repository)
        return self.post(url)

Response: Reindex all of the Jira issues related to this repository.


Instruction:
Write a Python 3 script for
forking a repository within the same project.

Response:
def fork_repository(self, project, repository, new_repository):
        """
        Forks a repository within the same project.
        :param project:
        :param repository:
        :param new_repository:
        :return:
        """
        url = 'rest/api/1.0/projects/{project}/repos/{repository}'.format(project=project,
                                                                          repository=repository)
        body = {}
        if new_repository is not None:
            body['name'] = new_repository
        if new_repository is not None:
            body['project'] = {'key': project}
        return self.post(url, data=body)


Instruction:
Can you tell what is the following Python 3 function doing
def get_branching_model(self, project, repository):
        url = 'rest/branch-utils/1.0/projects/{project}/repos/{repository}/branchmodel/configuration'.format(
            project=project,
            repository=repository)
        return self.get(url)

Response:
Get branching model
        :param project:
        :param repository:
        :return:


Instruction:
Can you tell what is the following Python 3 function doing
def set_branching_model(self, project, repository, data):
        url = 'rest/branch-utils/1.0/projects/{project}/repos/{repository}/branchmodel/configuration'.format(
            project=project,
            repository=repository)
        return self.put(url, data=data)

Response: Set branching model for a specific resource.


Instruction:
Make a summary of the following Python 3 code
def enable_branching_model(self, project, repository):
        default_model_data = {'development': {'refId': None, 'useDefault': True},
                              'types': [{'displayName': 'Bugfix',
                                         'enabled': True,
                                         'id': 'BUGFIX',
                                         'prefix': 'bugfix/'},
                                        {'displayName': 'Feature',
                                         'enabled': True,
                                         'id': 'FEATURE',
                                         'prefix': 'feature/'},
                                        {'displayName': 'Hotfix',
                                         'enabled': True,
                                         'id': 'HOTFIX',
                                         'prefix': 'hotfix/'},
                                        {'displayName': 'Release',
                                         'enabled': True,
                                         'id': 'RELEASE',
                                         'prefix': 'release/'}]}
        return self.set_branching_model(project,
                                        repository,
                                        default_model_data)

Response: Enable branching model by setting it with default configuration


Instruction:
Implement a function in Python 3 to
disable branching model for a specific language.

Response:
def disable_branching_model(self, project, repository):
        """
        Disable branching model
        :param project:
        :param repository:
        :return:
        """
        url = 'rest/branch-utils/1.0/projects/{project}/repos/{repository}/branchmodel/configuration'.format(
            project=project,
            repository=repository)
        return self.delete(url)


Instruction:
Create a Python 3 function for
getting the content of a resource from the server

Response:
def get(self, path, data=None, flags=None, params=None, headers=None, not_json_response=None):
        """
        Get request based on the python-requests module. You can override headers, and also, get not json response
        :param path:
        :param data:
        :param flags:
        :param params:
        :param headers:
        :param not_json_response: OPTIONAL: For get content from raw requests packet
        :return:
        """
        answer = self.request('GET', path=path, flags=flags, params=params, data=data, headers=headers)
        if not_json_response:
            return answer.content
        else:
            try:
                return answer.json()
            except Exception as e:
                log.error(e)
                return


Instruction:
Create a Python 3 function for
deleting resources at given paths. :rtype: dict :return: Empty dictionary to have consistent interface. Some of Atlassian REST resources don't return any content.

Response:
def delete(self, path, data=None, headers=None, params=None):
        """
        Deletes resources at given paths.
        :rtype: dict
        :return: Empty dictionary to have consistent interface.
        Some of Atlassian REST resources don't return any content.
        """
        self.request('DELETE', path=path, data=data, headers=headers, params=params)


Instruction:
Implement a function in Python 3 to
detect errors in a given space.

Response:
def check_unknown_attachment_in_space(confluence, space_key):
    """
    Detect errors in space
    :param confluence:
    :param space_key:
    :return:
    """
    page_ids = get_all_pages_ids(confluence, space_key)
    print("Start review pages {} in {}".format(len(page_ids), space_key))
    for page_id in page_ids:
        link = confluence.has_unknown_attachment_error(page_id)
        if len(link) > 0:
            print(link)


Instruction:
Given the following Python 3 function, write the documentation
def search_word(confluence, word):
    cql = "siteSearch ~ {} order by created".format(word)
    answers = confluence.cql(cql)
    for answer in answers.get('results'):
        print(answer)

Response: Search for all pages with the given word


Instruction:
Can you generate the documentation for the following Python 3 function
def search_word_in_space(confluence, space, word):
    cql = "space.key={} and (text ~ {})".format(space, word)
    answers = confluence.cql(cql, expand='space,body.view')
    for answer in answers.get('results'):
        print(answer)

Response: Search for a word in a given space


Instruction:
Write a Python 3 script for
removing all pages from trash for related space

Response:
def clean_pages_from_space(confluence, space_key, limit=500):
    """
    Remove all pages from trash for related space
    :param limit:
    :param confluence:
    :param space_key:
    :return:
    """
    flag = True
    while flag:
        values = confluence.get_all_pages_from_space_trash(space=space_key, start=0, limit=limit)
        if len(values) == 0:
            flag = False
            print("For space {} trash is empty".format(space_key))
        else:
            print("Found in space {} pages as trashed {}".format(space_key, len(values)))
            for value in values:
                print("Removing page with title: " + value['title'])
                confluence.remove_page_from_trash(value['id'])


Instruction:
Given the following Python 3 function, write the documentation
def clean_all_trash_pages_from_all_spaces(confluence):
    limit = 50
    flag = True
    i = 0
    while flag:
        space_lists = confluence.get_all_spaces(start=i * limit, limit=limit)
        if space_lists and len(space_lists) != 0:
            i += 1
            for space_list in space_lists:
                print("Start review the space with key = " + space_list['key'])
                clean_pages_from_space(confluence=confluence, space_key=space_list['key'])
        else:
            flag = False
    return 0

Response: This function will retrieve all space keys and provide space for cleaner


Instruction:
Can you write a function in Python 3 where it
gets all page ids from a given space.

Response:
def get_all_page_ids_from_space(confluence, space_key):
    """
    :param confluence:
    :param space_key:
    :return:
    """
    limit = 500
    flag = True
    step = 0
    page_ids = []

    while flag:
        values = confluence.get_all_pages_from_space(space=space_key, start=limit * step, limit=limit)
        step += 1
        if len(values) == 0:
            flag = False
            print("Did not find any pages, please, check permissions")
        else:
            for value in values:
                print("Retrieve page with title: " + value['title'])
                page_ids.append((value['id']))
    print("Found in space {} pages {}".format(space_key, len(page_ids)))
    return page_ids


Instruction:
Implement a function in Python 3 to
set the threshold of the content.

Response:
def threshold(self, value):
        """Threshold used to determine if your content qualifies as spam.
        On a scale from 1 to 10, with 10 being most strict, or most likely to
        be considered as spam.

        :param value: Threshold used to determine if your content qualifies as
                      spam.
                      On a scale from 1 to 10, with 10 being most strict, or
                      most likely to be considered as spam.
        :type value: int
        """
        if isinstance(value, SpamThreshold):
            self._threshold = value
        else:
            self._threshold = SpamThreshold(value)


Instruction:
Create a Python 3 function for
setting the post_to_url of the Inbound Parse URL.

Response:
def post_to_url(self, value):
        """An Inbound Parse URL to send a copy of your email.
        If defined, a copy of your email and its spam report will be sent here.

        :param value: An Inbound Parse URL to send a copy of your email.
        If defined, a copy of your email and its spam report will be sent here.
        :type value: string
        """
        if isinstance(value, SpamUrl):
            self._post_to_url = value
        else:
            self._post_to_url = SpamUrl(value)


Instruction:
Can you create a Python 3 function that
gets a JSON - ready representation of this SpamCheck.

Response:
def get(self):
        """
        Get a JSON-ready representation of this SpamCheck.

        :returns: This SpamCheck, ready for use in a request body.
        :rtype: dict
        """
        spam_check = {}
        if self.enable is not None:
            spam_check["enable"] = self.enable

        if self.threshold is not None:
            spam_check["threshold"] = self.threshold.get()

        if self.post_to_url is not None:
            spam_check["post_to_url"] = self.post_to_url.get()
        return spam_check


Instruction:
Can you generate the documentation for the following Python 3 function
def get(self):
        content = {}
        if self.mime_type is not None:
            content["type"] = self.mime_type

        if self.content is not None:
            content["value"] = self.content
        return content

Response: Returns a JSON - ready representation of this HtmlContent.


Instruction:
Write a Python 3 script for
getting a JSON - ready representation of this BCCSettings.

Response:
def get(self):
        """
        Get a JSON-ready representation of this BCCSettings.

        :returns: This BCCSettings, ready for use in a request body.
        :rtype: dict
        """
        bcc_settings = {}
        if self.enable is not None:
            bcc_settings["enable"] = self.enable

        if self.email is not None:
            bcc_settings["email"] = self.email.get()
        return bcc_settings


Instruction:
How would you explain what the following Python 3 function does
def _default_headers(self):
        headers = {
            "Authorization": 'Bearer {}'.format(self.api_key),
            "User-agent": self.useragent,
            "Accept": 'application/json'
        }
        if self.impersonate_subuser:
            headers['On-Behalf-Of'] = self.impersonate_subuser

        return headers

Response: Set the default header for a Twilio SendGrid v3 API call


Instruction:
Can you generate the documentation for the following Python 3 function
def send(self, message):
        if isinstance(message, dict):
            response = self.client.mail.send.post(request_body=message)
        else:
            response = self.client.mail.send.post(request_body=message.get())
        return response

Response:
Make a Twilio SendGrid v3 API request with the request body generated by the Mail object
           the Mail object


Instruction:
Can you create a Python 3 function that
ensures an item is appended to a list or create a new empty list

Response:
def _ensure_append(self, new_items, append_to, index=0):
        """Ensure an item is appended to a list or create a new empty list

        :param new_items: the item(s) to append
        :type new_items: list(obj)
        :param append_to: the list on which to append the items
        :type append_to: list()
        :param index: index of the list on which to append the items
        :type index: int
        """
        append_to = append_to or []
        append_to.insert(index, new_items)
        return append_to


Instruction:
Can you tell what is the following Python 3 function doing
def _ensure_insert(self, new_items, insert_to):
        insert_to = insert_to or []
        insert_to.insert(0, new_items)
        return insert_to

Response: Ensure an item is inserted to a list or create a new empty list


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _flatten_dicts(self, dicts):
        d = dict()
        list_of_dicts = [d.get() for d in dicts or []]
        return {k: v for d in list_of_dicts for k, v in d.items()}

Response: Flatten a list of dicts into a single dict.


Instruction:
Implement a Python 3 function for
adding emails to the Personalization object.

Response:
def _set_emails(
            self, emails, global_substitutions=None, is_multiple=False, p=0):
        """Adds emails to the Personalization object

        :param emails: An Email or list of Email objects
        :type emails: Email, list(Email)
        :param global_substitutions: A dict of substitutions for all recipients
        :type global_substitutions: dict
        :param is_multiple: Create a new personilization for each recipient
        :type is_multiple: bool
        :param p: p is the Personalization object or Personalization object
                  index
        :type p: Personalization, integer, optional
        """
        # Send multiple emails to multiple recipients
        if is_multiple is True:
            if isinstance(emails, list):
                for email in emails:
                    personalization = Personalization()
                    personalization.add_email(email)
                    self.add_personalization(personalization)
            else:
                personalization = Personalization()
                personalization.add_email(emails)
                self.add_personalization(personalization)
            if global_substitutions is not None:
                if isinstance(global_substitutions, list):
                    for substitution in global_substitutions:
                        for p in self.personalizations:
                            p.add_substitution(substitution)
                else:
                    for p in self.personalizations:
                        p.add_substitution(global_substitutions)
        else:
            try:
                personalization = self._personalizations[p]
                has_internal_personalization = True
            except IndexError:
                personalization = Personalization()
                has_internal_personalization = False

            if isinstance(emails, list):
                for email in emails:
                    personalization.add_email(email)
            else:
                personalization.add_email(emails)

            if global_substitutions is not None:
                if isinstance(global_substitutions, list):
                    for substitution in global_substitutions:
                        personalization.add_substitution(substitution)
                else:
                    personalization.add_substitution(global_substitutions)

            if not has_internal_personalization:
                self.add_personalization(personalization, index=p)


Instruction:
Can you create a Python 3 function that
adds a Personaliztion object to the internal list of personalizations.

Response:
def add_personalization(self, personalization, index=0):
        """Add a Personaliztion object

        :param personalizations: Add a Personalization object
        :type personalizations: Personalization
        :param index: The index where to add the Personalization
        :type index: int
        """
        self._personalizations = self._ensure_append(
            personalization, self._personalizations, index)


Instruction:
How would you explain what the following Python 3 function does
def to(self, to_emails, global_substitutions=None, is_multiple=False, p=0):
        if isinstance(to_emails, list):
            for email in to_emails:
                if isinstance(email, str):
                    email = To(email, None)
                if isinstance(email, tuple):
                    email = To(email[0], email[1])
                self.add_to(email, global_substitutions, is_multiple, p)
        else:
            if isinstance(to_emails, str):
                to_emails = To(to_emails, None)
            if isinstance(to_emails, tuple):
                to_emails = To(to_emails[0], to_emails[1])
            self.add_to(to_emails, global_substitutions, is_multiple, p)

Response: Adds To objects to the Personalization object.


Instruction:
Make a summary of the following Python 3 code
def add_to(
            self, to_email, global_substitutions=None, is_multiple=False, p=0):
        """Adds a To object to the Personalization object

        :param to_emails: A To object
        :type to_emails: To, str, tuple
        :param global_substitutions: A dict of substitutions for all recipients
        :type global_substitutions: dict
        :param is_multiple: Create a new personilization for each recipient
        :type is_multiple: bool
        :param p: p is the Personalization object or Personalization object
                  index
        :type p: Personalization, integer, optional
        """

        if isinstance(to_email, list):
            for email in to_email:
                if isinstance(email, str):
                    email = To(email, None)
                if isinstance(email, tuple):
                    email = To(email[0], email[1])
                self._set_emails(email, global_substitutions, is_multiple, p)
        else:
            if isinstance(to_email, str):
                to_email = To(to_email, None)
            if isinstance(to_email, tuple):
                to_email = To(to_email[0], to_email[1])
            if isinstance(to_email, Email):
                p = to_email.personalization
            self._set_emails(to_email, global_substitutions, is_multiple, p)

Response: Adds a To object to the Personalization object.


Instruction:
Can you tell what is the following Python 3 function doing
def cc(self, cc_emails, global_substitutions=None, is_multiple=False, p=0):
        if isinstance(cc_emails, list):
            for email in cc_emails:
                if isinstance(email, str):
                    email = Cc(email, None)
                if isinstance(email, tuple):
                    email = Cc(email[0], email[1])
                self.add_cc(email, global_substitutions, is_multiple, p)
        else:
            if isinstance(cc_emails, str):
                cc_emails = Cc(cc_emails, None)
            if isinstance(cc_emails, tuple):
                cc_emails = To(cc_emails[0], cc_emails[1])
            self.add_cc(cc_emails, global_substitutions, is_multiple, p)

Response: Adds Cc objects to the Personalization object.


Instruction:
Explain what the following Python 3 code does
def add_cc(
            self, cc_email, global_substitutions=None, is_multiple=False, p=0):
        """Adds a Cc object to the Personalization object

        :param to_emails: An Cc object
        :type to_emails: Cc
        :param global_substitutions: A dict of substitutions for all recipients
        :type global_substitutions: dict
        :param is_multiple: Create a new personilization for each recipient
        :type is_multiple: bool
        :param p: p is the Personalization object or Personalization object
                  index
        :type p: Personalization, integer, optional
        """
        if isinstance(cc_email, str):
            cc_email = Cc(cc_email, None)
        if isinstance(cc_email, tuple):
            cc_email = Cc(cc_email[0], cc_email[1])
        if isinstance(cc_email, Email):
            p = cc_email.personalization
        self._set_emails(
            cc_email, global_substitutions, is_multiple=is_multiple, p=p)

Response: Adds a Cc object to the Personalization object.


Instruction:
Create a Python 3 function for
adding Bcc objects to the Personalization object.

Response:
def bcc(
            self,
            bcc_emails,
            global_substitutions=None,
            is_multiple=False,
            p=0):
        """Adds Bcc objects to the Personalization object

        :param bcc_emails: An Bcc or list of Bcc objects
        :type bcc_emails: Bcc, list(Bcc), tuple
        :param global_substitutions: A dict of substitutions for all recipients
        :type global_substitutions: dict
        :param is_multiple: Create a new personilization for each recipient
        :type is_multiple: bool
        :param p: p is the Personalization object or Personalization object
                  index
        :type p: Personalization, integer, optional
        """
        if isinstance(bcc_emails, list):
            for email in bcc_emails:
                if isinstance(email, str):
                    email = Bcc(email, None)
                if isinstance(email, tuple):
                    email = Bcc(email[0], email[1])
                self.add_bcc(email, global_substitutions, is_multiple, p)
        else:
            if isinstance(bcc_emails, str):
                bcc_emails = Bcc(bcc_emails, None)
            if isinstance(bcc_emails, tuple):
                bcc_emails = Bcc(bcc_emails[0], bcc_emails[1])
            self.add_bcc(bcc_emails, global_substitutions, is_multiple, p)


Instruction:
How would you code a function in Python 3 to
add a Bcc object to the Personalization object.

Response:
def add_bcc(
            self,
            bcc_email,
            global_substitutions=None,
            is_multiple=False,
            p=0):
        """Adds a Bcc object to the Personalization object

        :param to_emails: An Bcc object
        :type to_emails: Bcc
        :param global_substitutions: A dict of substitutions for all recipients
        :type global_substitutions: dict
        :param is_multiple: Create a new personilization for each recipient
        :type is_multiple: bool
        :param p: p is the Personalization object or Personalization object
                  index
        :type p: Personalization, integer, optional
        """
        if isinstance(bcc_email, str):
            bcc_email = Bcc(bcc_email, None)
        if isinstance(bcc_email, tuple):
            bcc_email = Bcc(bcc_email[0], bcc_email[1])
        if isinstance(bcc_email, Email):
            p = bcc_email.personalization
        self._set_emails(
            bcc_email,
            global_substitutions,
            is_multiple=is_multiple,
            p=p)


Instruction:
Explain what the following Python 3 code does
def subject(self, value):
        if isinstance(value, Subject):
            if value.personalization is not None:
                try:
                    personalization = \
                        self._personalizations[value.personalization]
                    has_internal_personalization = True
                except IndexError:
                    personalization = Personalization()
                    has_internal_personalization = False
                personalization.subject = value.subject

                if not has_internal_personalization:
                    self.add_personalization(
                        personalization,
                        index=value.personalization)
            else:
                self._subject = value
        else:
            self._subject = Subject(value)

Response: Sets the subject of the message.


Instruction:
Explain what the following Python 3 code does
def header(self, headers):
        if isinstance(headers, list):
            for h in headers:
                self.add_header(h)
        else:
            self.add_header(headers)

Response: Add headers to the email


Instruction:
Explain what the following Python 3 code does
def add_header(self, header):
        if header.personalization is not None:
            try:
                personalization = \
                    self._personalizations[header.personalization]
                has_internal_personalization = True
            except IndexError:
                personalization = Personalization()
                has_internal_personalization = False
            if isinstance(header, dict):
                (k, v) = list(header.items())[0]
                personalization.add_header(Header(k, v))
            else:
                personalization.add_header(header)

            if not has_internal_personalization:
                self.add_personalization(
                    personalization,
                    index=header.personalization)
        else:
            if isinstance(header, dict):
                (k, v) = list(header.items())[0]
                self._headers = self._ensure_append(
                                    Header(k, v), self._headers)
            else:
                self._headers = self._ensure_append(header, self._headers)

Response: Add headers to the email globaly or to a specific Personalization


Instruction:
How would you explain what the following Python 3 function does
def substitution(self, substitution):
        if isinstance(substitution, list):
            for s in substitution:
                self.add_substitution(s)
        else:
            self.add_substitution(substitution)

Response:
Add substitutions to the email
Taxonomy


Instruction:
Implement a function in Python 3 to
add a substitution to the email.

Response:
def add_substitution(self, substitution):
        """Add a substitution to the email

        :param value: Add a substitution to the email
        :type value: Substitution
        """
        if substitution.personalization:
            try:
                personalization = \
                    self._personalizations[substitution.personalization]
                has_internal_personalization = True
            except IndexError:
                personalization = Personalization()
                has_internal_personalization = False
            personalization.add_substitution(substitution)

            if not has_internal_personalization:
                self.add_personalization(
                    personalization, index=substitution.personalization)
        else:
            if isinstance(substitution, list):
                for s in substitution:
                    for p in self.personalizations:
                        p.add_substitution(s)
            else:
                for p in self.personalizations:
                    p.add_substitution(substitution)


Instruction:
Can you write a function in Python 3 where it
adds custom args to the email key - value pairs.

Response:
def custom_arg(self, custom_arg):
        """Add custom args to the email

        :param value: A list of CustomArg objects or a dict of custom arg
                      key/values
        :type value: CustomArg, list(CustomArg), dict
        """
        if isinstance(custom_arg, list):
            for c in custom_arg:
                self.add_custom_arg(c)
        else:
            self.add_custom_arg(custom_arg)


Instruction:
How would you explain what the following Python 3 function does
def add_custom_arg(self, custom_arg):
        if custom_arg.personalization is not None:
            try:
                personalization = \
                    self._personalizations[custom_arg.personalization]
                has_internal_personalization = True
            except IndexError:
                personalization = Personalization()
                has_internal_personalization = False
            if isinstance(custom_arg, dict):
                (k, v) = list(custom_arg.items())[0]
                personalization.add_custom_arg(CustomArg(k, v))
            else:
                personalization.add_custom_arg(custom_arg)

            if not has_internal_personalization:
                self.add_personalization(
                    personalization, index=custom_arg.personalization)
        else:
            if isinstance(custom_arg, dict):
                (k, v) = list(custom_arg.items())[0]
                self._custom_args = self._ensure_append(
                    CustomArg(k, v), self._custom_args)
            else:
                self._custom_args = self._ensure_append(
                    custom_arg, self._custom_args)

Response: Adds custom args to the email globaly or to a specific Personalization


Instruction:
Can you tell what is the following Python 3 function doing
def send_at(self, value):
        if isinstance(value, SendAt):
            if value.personalization is not None:
                try:
                    personalization = \
                        self._personalizations[value.personalization]
                    has_internal_personalization = True
                except IndexError:
                    personalization = Personalization()
                    has_internal_personalization = False
                personalization.send_at = value.send_at

                if not has_internal_personalization:
                    self.add_personalization(
                        personalization, index=value.personalization)
            else:
                self._send_at = value
        else:
            self._send_at = SendAt(value)

Response: Set the send_at of the related object.


Instruction:
Write a Python 3 function that can
set the dynamic template data for a transactional template.

Response:
def dynamic_template_data(self, value):
        """Data for a transactional template

        :param value: Data for a transactional template
        :type value: DynamicTemplateData, a JSON-serializeable structure
        """
        if not isinstance(value, DynamicTemplateData):
            value = DynamicTemplateData(value)
        try:
            personalization = self._personalizations[value.personalization]
            has_internal_personalization = True
        except IndexError:
            personalization = Personalization()
            has_internal_personalization = False
        personalization.dynamic_template_data = value.dynamic_template_data

        if not has_internal_personalization:
            self.add_personalization(
                personalization, index=value.personalization)


Instruction:
Can you create a Python 3 function that
sets the From field of the object

Response:
def from_email(self, value):
        """The email address of the sender

        :param value: The email address of the sender
        :type value: From, str, tuple
        """
        if isinstance(value, str):
            value = From(value, None)
        if isinstance(value, tuple):
            value = From(value[0], value[1])
        self._from_email = value


Instruction:
Explain what the following Python 3 code does
def reply_to(self, value):
        if isinstance(value, str):
            value = ReplyTo(value, None)
        if isinstance(value, tuple):
            value = ReplyTo(value[0], value[1])
        self._reply_to = value

Response: Sets the ReplyTo value


Instruction:
Given the following Python 3 function, write the documentation
def content(self, contents):
        if isinstance(contents, list):
            for c in contents:
                self.add_content(c)
        else:
            self.add_content(contents)

Response:
The content of the email
        is a list of Content objects.


Instruction:
Here you have a function in Python 3, explain what it does
def add_content(self, content, mime_type=None):
        if isinstance(content, str):
            content = Content(mime_type, content)
        # Content of mime type text/plain must always come first
        if content.mime_type == "text/plain":
            self._contents = self._ensure_insert(content, self._contents)
        else:
            if self._contents:
                index = len(self._contents)
            else:
                index = 0
            self._contents = self._ensure_append(
                content, self._contents, index=index)

Response: Add a content to the email.


Instruction:
Can you tell what is the following Python 3 function doing
def attachment(self, attachment):
        if isinstance(attachment, list):
            for a in attachment:
                self.add_attachment(a)
        else:
            self.add_attachment(attachment)

Response: Adds an attachment to this email.


Instruction:
Can you generate the documentation for the following Python 3 function
def add_attachment(self, attachment):
        self._attachments = self._ensure_append(attachment, self._attachments)

Response: Add an attachment to this email


Instruction:
Can you generate the documentation for the following Python 3 function
def template_id(self, value):
        if isinstance(value, TemplateId):
            self._template_id = value
        else:
            self._template_id = TemplateId(value)

Response: Sets the transactional template id for this email.


Instruction:
Write a Python 3 script for
adding a section to the set of block sections of code to be used as substitutions

Response:
def section(self, section):
        """The block sections of code to be used as substitutions

        :rtype: Section, list(Section)
        """
        if isinstance(section, list):
            for h in section:
                self.add_section(h)
        else:
            self.add_section(section)


Instruction:
Can you implement a function in Python 3 that
adds a section to the set of section names to be used as substitutions .

Response:
def add_section(self, section):
        """A block section of code to be used as substitutions

        :param section: A block section of code to be used as substitutions
        :type section: Section
        """
        self._sections = self._ensure_append(section, self._sections)


Instruction:
Write a Python 3 function that can
add categories assigned to this message.

Response:
def category(self, categories):
        """Add categories assigned to this message

        :rtype: list(Category)
        """
        if isinstance(categories, list):
            for c in categories:
                self.add_category(c)
        else:
            self.add_category(categories)


Instruction:
Can you tell what is the following Python 3 function doing
def add_category(self, category):
        self._categories = self._ensure_append(category, self._categories)

Response: Add a category assigned to this message


Instruction:
Explain what the following Python 3 code does
def get(self):
        mail = {
            'from': self._get_or_none(self.from_email),
            'subject': self._get_or_none(self.subject),
            'personalizations': [p.get() for p in self.personalizations or []],
            'content': [c.get() for c in self.contents or []],
            'attachments': [a.get() for a in self.attachments or []],
            'template_id': self._get_or_none(self.template_id),
            'sections': self._flatten_dicts(self.sections),
            'headers': self._flatten_dicts(self.headers),
            'categories': [c.get() for c in self.categories or []],
            'custom_args': self._flatten_dicts(self.custom_args),
            'send_at':  self._get_or_none(self.send_at),
            'batch_id': self._get_or_none(self.batch_id),
            'asm': self._get_or_none(self.asm),
            'ip_pool_name': self._get_or_none(self.ip_pool_name),
            'mail_settings': self._get_or_none(self.mail_settings),
            'tracking_settings': self._get_or_none(self.tracking_settings),
            'reply_to': self._get_or_none(self.reply_to),
        }

        return {key: value for key, value in mail.items()
                if value is not None and value != [] and value != {}}

Response: Get a JSON - ready representation of this Mail object.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def from_EmailMessage(cls, message):
        mail = cls(
            from_email=Email(message.get('From')),
            subject=message.get('Subject'),
            to_emails=Email(message.get('To')),
        )
        try:
            body = message.get_content()
        except AttributeError:
            # Python2
            body = message.get_payload()
        mail.add_content(Content(
            message.get_content_type(),
            body.strip()
        ))
        for k, v in message.items():
            mail.add_header(Header(k, v))
        return mail

Response: Create an instance of Mail from an email. message. EmailMessage object.


Instruction:
How would you implement a function in Python 3 that
gets a JSON - ready representation of this Ganalytics.

Response:
def get(self):
        """
        Get a JSON-ready representation of this Ganalytics.

        :returns: This Ganalytics, ready for use in a request body.
        :rtype: dict
        """
        keys = ["enable", "utm_source", "utm_medium", "utm_term",
                "utm_content", "utm_campaign"]

        ganalytics = {}

        for key in keys:
            value = getattr(self, key, None)
            if value is not None:
                if isinstance(value, bool):
                    ganalytics[key] = value
                else:
                    ganalytics[key] = value.get()

        return ganalytics


Instruction:
Implement a function in Python 3 to
get a JSON - ready representation of this FooterSettings.

Response:
def get(self):
        """
        Get a JSON-ready representation of this FooterSettings.

        :returns: This FooterSettings, ready for use in a request body.
        :rtype: dict
        """
        footer_settings = {}
        if self.enable is not None:
            footer_settings["enable"] = self.enable

        if self.text is not None:
            footer_settings["text"] = self.text.get()

        if self.html is not None:
            footer_settings["html"] = self.html.get()
        return footer_settings


Instruction:
How would you implement a function in Python 3 that
sets the name associated with this email.

Response:
def name(self, value):
        """Name associated with this email.

        :param value: Name associated with this email.
        :type value: string
        """
        if not (value is None or isinstance(value, str)):
            raise TypeError('name must be of type string.')

        # Escape common CSV delimiters as workaround for
        # https://github.com/sendgrid/sendgrid-python/issues/578
        if value is not None and (',' in value or ';' in value):
            value = html_entity_decode(value)
            value = '"' + value + '"'
        self._name = value


Instruction:
Write a Python 3 function for
parsing an email address and returns the name and email.

Response:
def parse_email(self, email_info):
        """Allows passing emails as "Example Name <example@example.com>"

        :param email_info: Allows passing emails as
                           "Example Name <example@example.com>"
        :type email_info: string
        """
        name, email = rfc822.parseaddr(email_info)

        # more than likely a string was passed here instead of an email address
        if "@" not in email:
            name = email
            email = None

        if not name:
            name = None

        if not email:
            email = None

        self.name = name
        self.email = email
        return name, email


Instruction:
Implement a function in Python 3 to
return a JSON - ready representation of this Email.

Response:
def get(self):
        """
        Get a JSON-ready representation of this Email.

        :returns: This Email, ready for use in a request body.
        :rtype: dict
        """
        email = {}
        if self.name is not None:
            email["name"] = self.name

        if self.email is not None:
            email["email"] = self.email
        return email


Instruction:
Make a summary of the following Python 3 code
def groups_to_display(self, value):
        if value is not None and len(value) > 25:
            raise ValueError("New groups_to_display exceeds max length of 25.")
        self._groups_to_display = value

Response: Sets the value for the groups_to_display property.


Instruction:
Can you generate the documentation for the following Python 3 function
def group_id(self, value):
        if isinstance(value, GroupId):
            self._group_id = value
        else:
            self._group_id = GroupId(value)

Response: The group ID of an unsubscribe group.


Instruction:
Given the following Python 3 function, write the documentation
def groups_to_display(self, value):
        if isinstance(value, GroupsToDisplay):
            self._groups_to_display = value
        else:
            self._groups_to_display = GroupsToDisplay(value)

Response: Set the array containing the unsubscribe groups that you would like to display on the preferences page. Max of 25 groups.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get(self):
        asm = {}
        if self.group_id is not None:
            asm["group_id"] = self.group_id.get()

        if self.groups_to_display is not None:
            asm["groups_to_display"] = self.groups_to_display.get()
        return asm

Response: Get a JSON - ready representation of this ASM object.


Instruction:
Can you implement a function in Python 3 that
validates the JSON dict that will be sent to SendGrid s API.

Response:
def validate_message_dict(self, request_body):
        """With the JSON dict that will be sent to SendGrid's API,
            check the content for SendGrid API keys - throw exception if found.

           :param request_body: The JSON dict that will be sent to SendGrid's
                                API.
           :type request_body: JSON serializable structure
           :raise ApiKeyIncludedException: If any content in request_body
                                           matches regex
        """

        # Handle string in edge-case
        if isinstance(request_body, str):
            self.validate_message_text(request_body)

        # Default param
        elif isinstance(request_body, dict):

            contents = request_body.get("content", list())

            for content in contents:
                if content is not None:
                    if (content.get("type") == "text/html" or
                            isinstance(content.get("value"), str)):
                        message_text = content.get("value", "")
                        self.validate_message_text(message_text)


Instruction:
Write a Python 3 function that can
validate that a message string contains a SendGrid API KeyAcquire.

Response:
def validate_message_text(self, message_string):
        """With a message string, check to see if it contains a SendGrid API Key
            If a key is found, throw an exception

           :param message_string: message that will be sent
           :type message_string: string
           :raises ApiKeyIncludedException: If message_string matches a regex
                                            string
        """
        if isinstance(message_string, str):
            for regex in self.regexes:
                if regex.match(message_string) is not None:
                    raise ApiKeyIncludedException()


Instruction:
Can you generate the documentation for the following Python 3 function
def get_mock_personalization_dict():
    mock_pers = dict()

    mock_pers['to_list'] = [To("test1@example.com",
                                  "Example User"),
                            To("test2@example.com",
                                  "Example User")]

    mock_pers['cc_list'] = [To("test3@example.com",
                                  "Example User"),
                            To("test4@example.com",
                                  "Example User")]

    mock_pers['bcc_list'] = [To("test5@example.com"),
                             To("test6@example.com")]

    mock_pers['subject'] = ("Hello World from the Personalized "
                            "SendGrid Python Library")

    mock_pers['headers'] = [Header("X-Test", "test"),
                            Header("X-Mock", "true")]

    mock_pers['substitutions'] = [Substitution("%name%", "Example User"),
                                  Substitution("%city%", "Denver")]

    mock_pers['custom_args'] = [CustomArg("user_id", "343"),
                                CustomArg("type", "marketing")]

    mock_pers['send_at'] = 1443636843
    return mock_pers

Response: Get a dict of personalization mock.


Instruction:
Here you have a function in Python 3, explain what it does
def build_attachment1():
    attachment = Attachment()
    attachment.content = ("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNl"
                          "Y3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12")
    attachment.type = "application/pdf"
    attachment.filename = "balance_001.pdf"
    attachment.disposition = "attachment"
    attachment.content_id = "Balance Sheet"
    return attachment

Response:
Build attachment mock. Make sure your content is base64 encoded before passing into attachment.content.
    Another example: https://github.com/sendgrid/sendgrid-python/blob/master/use_cases/attachment.md


Instruction:
Make a summary of the following Python 3 code
def build_kitchen_sink():
    from sendgrid.helpers.mail import (
        Mail, From, To, Cc, Bcc, Subject, PlainTextContent,
        HtmlContent, SendGridException, Substitution,
        Header, CustomArg, SendAt, Content, MimeType, Attachment,
        FileName, FileContent, FileType, Disposition, ContentId,
        TemplateId, Section, ReplyTo, Category, BatchId, Asm,
        GroupId, GroupsToDisplay, IpPoolName, MailSettings,
        BccSettings, BccSettingsEmail, BypassListManagement,
        FooterSettings, FooterText, FooterHtml, SandBoxMode,
        SpamCheck, SpamThreshold, SpamUrl, TrackingSettings,
        ClickTracking, SubscriptionTracking, SubscriptionText,
        SubscriptionHtml, SubscriptionSubstitutionTag,
        OpenTracking, OpenTrackingSubstitutionTag, Ganalytics,
        UtmSource, UtmMedium, UtmTerm, UtmContent, UtmCampaign)
    import time
    import datetime

    message = Mail()

    # Define Personalizations

    message.to = To('test1@sendgrid.com', 'Example User1', p=0)
    message.to = [
        To('test2@sendgrid.com', 'Example User2', p=0),
        To('test3@sendgrid.com', 'Example User3', p=0)
    ]

    message.cc = Cc('test4@example.com', 'Example User4', p=0)
    message.cc = [
        Cc('test5@example.com', 'Example User5', p=0),
        Cc('test6@example.com', 'Example User6', p=0)
    ]

    message.bcc = Bcc('test7@example.com', 'Example User7', p=0)
    message.bcc = [
        Bcc('test8@example.com', 'Example User8', p=0),
        Bcc('test9@example.com', 'Example User9', p=0)
    ]

    message.subject = Subject('Sending with SendGrid is Fun 0', p=0)

    message.header = Header('X-Test1', 'Test1', p=0)
    message.header = Header('X-Test2', 'Test2', p=0)
    message.header = [
        Header('X-Test3', 'Test3', p=0),
        Header('X-Test4', 'Test4', p=0)
    ]

    message.substitution = Substitution('%name1%', 'Example Name 1', p=0)
    message.substitution = Substitution('%city1%', 'Example City 1', p=0)
    message.substitution = [
        Substitution('%name2%', 'Example Name 2', p=0),
        Substitution('%city2%', 'Example City 2', p=0)
    ]

    message.custom_arg = CustomArg('marketing1', 'true', p=0)
    message.custom_arg = CustomArg('transactional1', 'false', p=0)
    message.custom_arg = [
        CustomArg('marketing2', 'false', p=0),
        CustomArg('transactional2', 'true', p=0)
    ]

    message.send_at = SendAt(1461775051, p=0)

    message.to = To('test10@example.com', 'Example User10', p=1)
    message.to = [
        To('test11@example.com', 'Example User11', p=1),
        To('test12@example.com', 'Example User12', p=1)
    ]

    message.cc = Cc('test13@example.com', 'Example User13', p=1)
    message.cc = [
        Cc('test14@example.com', 'Example User14', p=1),
        Cc('test15@example.com', 'Example User15', p=1)
    ]

    message.bcc = Bcc('test16@example.com', 'Example User16', p=1)
    message.bcc = [
        Bcc('test17@example.com', 'Example User17', p=1),
        Bcc('test18@example.com', 'Example User18', p=1)
    ]

    message.header = Header('X-Test5', 'Test5', p=1)
    message.header = Header('X-Test6', 'Test6', p=1)
    message.header = [
        Header('X-Test7', 'Test7', p=1),
        Header('X-Test8', 'Test8', p=1)
    ]

    message.substitution = Substitution('%name3%', 'Example Name 3', p=1)
    message.substitution = Substitution('%city3%', 'Example City 3', p=1)
    message.substitution = [
        Substitution('%name4%', 'Example Name 4', p=1),
        Substitution('%city4%', 'Example City 4', p=1)
    ]

    message.custom_arg = CustomArg('marketing3', 'true', p=1)
    message.custom_arg = CustomArg('transactional3', 'false', p=1)
    message.custom_arg = [
        CustomArg('marketing4', 'false', p=1),
        CustomArg('transactional4', 'true', p=1)
    ]

    message.send_at = SendAt(1461775052, p=1)

    message.subject = Subject('Sending with SendGrid is Fun 1', p=1)

    # The values below this comment are global to entire message

    message.from_email = From('dx@sendgrid.com', 'DX')

    message.reply_to = ReplyTo('dx_reply@sendgrid.com', 'DX Reply')

    message.subject = Subject('Sending with SendGrid is Fun 2')

    message.content = Content(MimeType.text, 'and easy to do anywhere, even with Python')
    message.content = Content(MimeType.html, 'and easy to do anywhere, even with Python')
    message.content = [
        Content('text/calendar', 'Party Time!!'),
        Content('text/custom', 'Party Time 2!!')
    ]

    message.attachment = Attachment(FileContent('base64 encoded content 1'),
                                    FileType('application/pdf'),
                                    FileName('balance_001.pdf'),
                                    Disposition('attachment'),
                                    ContentId('Content ID 1'))
    message.attachment = [
        Attachment(FileContent('base64 encoded content 2'),
                FileType('image/png'),
                FileName('banner.png'),
                Disposition('inline'),
                ContentId('Content ID 2')),
        Attachment(FileContent('base64 encoded content 3'),
                FileType('image/png'),
                FileName('banner2.png'),
                Disposition('inline'),
                ContentId('Content ID 3'))
    ]

    message.template_id = TemplateId('13b8f94f-bcae-4ec6-b752-70d6cb59f932')

    message.section = Section('%section1%', 'Substitution for Section 1 Tag')
    message.section = [
        Section('%section2%', 'Substitution for Section 2 Tag'),
        Section('%section3%', 'Substitution for Section 3 Tag')
    ]

    message.header = Header('X-Test9', 'Test9')
    message.header = Header('X-Test10', 'Test10')
    message.header = [
        Header('X-Test11', 'Test11'),
        Header('X-Test12', 'Test12')
    ]

    message.category = Category('Category 1')
    message.category = Category('Category 2')
    message.category = [
        Category('Category 1'),
        Category('Category 2')
    ]

    message.custom_arg = CustomArg('marketing5', 'false')
    message.custom_arg = CustomArg('transactional5', 'true')
    message.custom_arg = [
        CustomArg('marketing6', 'true'),
        CustomArg('transactional6', 'false')
    ]

    message.send_at = SendAt(1461775053)

    message.batch_id = BatchId("HkJ5yLYULb7Rj8GKSx7u025ouWVlMgAi")

    message.asm = Asm(GroupId(1), GroupsToDisplay([1,2,3,4]))

    message.ip_pool_name = IpPoolName("IP Pool Name")

    mail_settings = MailSettings()
    mail_settings.bcc_settings = BccSettings(False, BccSettingsTo("bcc@twilio.com"))
    mail_settings.bypass_list_management = BypassListManagement(False)
    mail_settings.footer_settings = FooterSettings(True, FooterText("w00t"), FooterHtml("<string>w00t!"))
    mail_settings.sandbox_mode = SandBoxMode(True)
    mail_settings.spam_check = SpamCheck(True, SpamThreshold(5), SpamUrl("https://example.com"))
    message.mail_settings = mail_settings

    tracking_settings = TrackingSettings()
    tracking_settings.click_tracking = ClickTracking(True, False)
    tracking_settings.open_tracking = OpenTracking(True, OpenTrackingSubstitutionTag("open_tracking"))
    tracking_settings.subscription_tracking = SubscriptionTracking(
        True,
        SubscriptionText("Goodbye"),
        SubscriptionHtml("Goodbye!"),
        SubscriptionSubstitutionTag("unsubscribe"))
    tracking_settings.ganalytics = Ganalytics(
        True,
        UtmSource("utm_source"),
        UtmMedium("utm_medium"),
        UtmTerm("utm_term"),
        UtmContent("utm_content"),
        UtmCampaign("utm_campaign"))
    message.tracking_settings = tracking_settings

    return message.get()

Response: Build a Kitchen Sink


Instruction:
Write a Python 3 function for
initializing the environment variables for the current object.

Response:
def init_environment():
        """Allow variables assigned in .env available using
           os.environ.get('VAR_NAME')"""
        base_path = os.path.abspath(os.path.dirname(__file__))
        env_path = '{0}/.env'.format(base_path)
        if os.path.exists(env_path):
            with open(env_path) as f:
                lines = f.readlines()
                for line in lines:
                    var = line.strip().split('=')
                    if len(var) == 2:
                        os.environ[var[0]] = var[1]


Instruction:
Write a Python 3 function that can
get a JSON - ready representation of this MailSettings.

Response:
def get(self):
        """
        Get a JSON-ready representation of this MailSettings.

        :returns: This MailSettings, ready for use in a request body.
        :rtype: dict
        """
        mail_settings = {}
        if self.bcc_settings is not None:
            mail_settings["bcc"] = self.bcc_settings.get()

        if self.bypass_list_management is not None:
            mail_settings[
                "bypass_list_management"] = self.bypass_list_management.get()

        if self.footer_settings is not None:
            mail_settings["footer"] = self.footer_settings.get()

        if self.sandbox_mode is not None:
            mail_settings["sandbox_mode"] = self.sandbox_mode.get()

        if self.spam_check is not None:
            mail_settings["spam_check"] = self.spam_check.get()
        return mail_settings


Instruction:
Make a summary of the following Python 3 code
def get(self):
        substitution = {}
        if self.key is not None and self.value is not None:
            substitution[self.key] = self.value
        return substitution

Response: Returns a JSON - ready representation of this Substitution.


Instruction:
Write a Python 3 script to
return a JSON - ready representation of this Header.

Response:
def get(self):
        """
        Get a JSON-ready representation of this Header.

        :returns: This Header, ready for use in a request body.
        :rtype: dict
        """
        header = {}
        if self.key is not None and self.value is not None:
            header[self.key] = self.value
        return header


Instruction:
Create a Python 3 function to
return a dictionary of key - value pairs in the payload received from the webhook

Response:
def key_values(self):
        """
        Return a dictionary of key/values in the payload received from
        the webhook
        """
        key_values = {}
        for key in self.keys:
            if key in self.payload:
                key_values[key] = self.payload[key]
        return key_values


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_raw_email(self):
        if 'email' in self.payload:
            raw_email = email.message_from_string(self.payload['email'])
            return raw_email
        else:
            return None

Response: Returns the raw email for the current classroom.


Instruction:
How would you code a function in Python 3 to
return an object with the name of the file content type file_name contents of the file contents

Response:
def attachments(self):
        """Returns an object with:
        type = file content type
        file_name = the name of the file
        contents = base64 encoded file contents"""
        attachments = None
        if 'attachment-info' in self.payload:
            attachments = self._get_attachments(self.request)
        # Check if we have a raw message
        raw_email = self.get_raw_email()
        if raw_email is not None:
            attachments = self._get_attachments_raw(raw_email)
        return attachments


Instruction:
Can you generate the documentation for the following Python 3 function
def unassigned(data, as_json=False):

    no_subusers = set()

    if not isinstance(data, list):
        return format_ret(no_subusers, as_json=as_json)

    for current in data:
        num_subusers = len(current["subusers"])
        if num_subusers == 0:
            current_ip = current["ip"]
            no_subusers.add(current_ip)

    ret_val = format_ret(no_subusers, as_json=as_json)
    return ret_val

Response: The unassigned API endpoint returns information about the IP addresses and usernames assigned to an IP - level object.


Instruction:
Make a summary of the following Python 3 code
def add_to(self, email):
        if email.substitutions:
            if isinstance(email.substitutions, list):
                for substitution in email.substitutions:
                    self.add_substitution(substitution)
            else:
                self.add_substitution(email.substitutions)
        if email.subject:
            if isinstance(email.subject, str):
                self.subject = email.subject
            else:
                self.subject = email.subject.get()
        self._tos.append(email.get())

Response: Adds a single recipient to this Personalization.


Instruction:
Make a summary of the following Python 3 code
def add_substitution(self, substitution):
        if isinstance(substitution, dict):
            self._substitutions.append(substitution)
        else:
            self._substitutions.append(substitution.get())

Response: Add a new Substitution to this Personalization.