Instruction:
Given the following Python 3 function, write the documentation
def network_security_group_present(name, resource_group, tags=None, security_rules=None, connection_auth=None,
                                   **kwargs):
    '''
    .. versionadded:: 2019.2.0

    Ensure a network security group exists.

    :param name:
        Name of the network security group.

    :param resource_group:
        The resource group assigned to the network security group.

    :param tags:
        A dictionary of strings can be passed as tag metadata to the network security group object.

    :param security_rules: An optional list of dictionaries representing valid SecurityRule objects. See the
        documentation for the security_rule_present state or security_rule_create_or_update execution module
        for more information on required and optional parameters for security rules. The rules are only
        managed if this parameter is present. When this parameter is absent, implemented rules will not be removed,
        and will merely become unmanaged.

    :param connection_auth:
        A dict with subscription and authentication parameters to be used in connecting to the
        Azure Resource Manager API.

    Example usage:

    .. code-block:: yaml

        Ensure network security group exists:
            azurearm_network.network_security_group_present:
                - name: nsg1
                - resource_group: group1
                - security_rules:
                  - name: nsg1_rule1
                    priority: 100
                    protocol: tcp
                    access: allow
                    direction: outbound
                    source_address_prefix: virtualnetwork
                    destination_address_prefix: internet
                    source_port_range: '*'
                    destination_port_range: '*'
                  - name: nsg1_rule2
                    priority: 101
                    protocol: tcp
                    access: allow
                    direction: inbound
                    source_address_prefix: internet
                    destination_address_prefix: virtualnetwork
                    source_port_range: '*'
                    destination_port_ranges:
                      - '80'
                      - '443'
                - tags:
                    contact_name: Elmer Fudd Gantry
                - connection_auth: {{ profile }}
                - require:
                  - azurearm_resource: Ensure resource group exists

    '''
    ret = {
        'name': name,
        'result': False,
        'comment': '',
        'changes': {}
    }

    if not isinstance(connection_auth, dict):
        ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
        return ret

    nsg = __salt__['azurearm_network.network_security_group_get'](
        name,
        resource_group,
        azurearm_log_level='info',
        **connection_auth
    )

    if 'error' not in nsg:
        tag_changes = __utils__['dictdiffer.deep_diff'](nsg.get('tags', {}), tags or {})
        if tag_changes:
            ret['changes']['tags'] = tag_changes

        if security_rules:
            comp_ret = __utils__['azurearm.compare_list_of_dicts'](nsg.get('security_rules', []), security_rules)

            if comp_ret.get('comment'):
                ret['comment'] = '"security_rules" {0}'.format(comp_ret['comment'])
                return ret

            if comp_ret.get('changes'):
                ret['changes']['security_rules'] = comp_ret['changes']

        if not ret['changes']:
            ret['result'] = True
            ret['comment'] = 'Network security group {0} is already present.'.format(name)
            return ret

        if __opts__['test']:
            ret['result'] = None
            ret['comment'] = 'Network security group {0} would be updated.'.format(name)
            return ret

    else:
        ret['changes'] = {
            'old': {},
            'new': {
                'name': name,
                'resource_group': resource_group,
                'tags': tags,
                'security_rules': security_rules,
            }
        }

    if __opts__['test']:
        ret['comment'] = 'Network security group {0} would be created.'.format(name)
        ret['result'] = None
        return ret

    nsg_kwargs = kwargs.copy()
    nsg_kwargs.update(connection_auth)

    nsg = __salt__['azurearm_network.network_security_group_create_or_update'](
        name=name,
        resource_group=resource_group,
        tags=tags,
        security_rules=security_rules,
        **nsg_kwargs
    )

    if 'error' not in nsg:
        ret['result'] = True
        ret['comment'] = 'Network security group {0} has been created.'.format(name)
        return ret

    ret['comment'] = 'Failed to create network security group {0}! ({1})'.format(name, nsg.get('error'))
    return ret

Response: Ensures a network security group exists.


Instruction:
How would you code a function in Python 3 to
ensure a network security group is absent in the resource group.

Response:
def network_security_group_absent(name, resource_group, connection_auth=None):
    '''
    .. versionadded:: 2019.2.0

    Ensure a network security group does not exist in the resource group.

    :param name:
        Name of the network security group.

    :param resource_group:
        The resource group assigned to the network security group.

    :param connection_auth:
        A dict with subscription and authentication parameters to be used in connecting to the
        Azure Resource Manager API.
    '''
    ret = {
        'name': name,
        'result': False,
        'comment': '',
        'changes': {}
    }

    if not isinstance(connection_auth, dict):
        ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
        return ret

    nsg = __salt__['azurearm_network.network_security_group_get'](
        name,
        resource_group,
        azurearm_log_level='info',
        **connection_auth
    )

    if 'error' in nsg:
        ret['result'] = True
        ret['comment'] = 'Network security group {0} was not found.'.format(name)
        return ret

    elif __opts__['test']:
        ret['comment'] = 'Network security group {0} would be deleted.'.format(name)
        ret['result'] = None
        ret['changes'] = {
            'old': nsg,
            'new': {},
        }
        return ret

    deleted = __salt__['azurearm_network.network_security_group_delete'](name, resource_group, **connection_auth)

    if deleted:
        ret['result'] = True
        ret['comment'] = 'Network security group {0} has been deleted.'.format(name)
        ret['changes'] = {
            'old': nsg,
            'new': {}
        }
        return ret

    ret['comment'] = 'Failed to delete network security group {0}!'.format(name)
    return ret


Instruction:
Can you tell what is the following Python 3 function doing
def security_rule_present(name, access, direction, priority, protocol, security_group, resource_group,
                          destination_address_prefix=None, destination_port_range=None, source_address_prefix=None,
                          source_port_range=None, description=None, destination_address_prefixes=None,
                          destination_port_ranges=None, source_address_prefixes=None, source_port_ranges=None,
                          connection_auth=None, **kwargs):
    '''
    .. versionadded:: 2019.2.0

    Ensure a security rule exists.

    :param name:
        Name of the security rule.

    :param access:
        'allow' or 'deny'

    :param direction:
        'inbound' or 'outbound'

    :param priority:
        Integer between 100 and 4096 used for ordering rule application.

    :param protocol:
        'tcp', 'udp', or '*'

    :param security_group:
        The name of the existing network security group to contain the security rule.

    :param resource_group:
        The resource group assigned to the network security group.

    :param description:
        Optional description of the security rule.

    :param destination_address_prefix:
        The CIDR or destination IP range. Asterix '*' can also be used to match all destination IPs.
        Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used.
        If this is an ingress rule, specifies where network traffic originates from.

    :param destination_port_range:
        The destination port or range. Integer or range between 0 and 65535. Asterix '*'
        can also be used to match all ports.

    :param source_address_prefix:
        The CIDR or source IP range. Asterix '*' can also be used to match all source IPs.
        Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used.
        If this is an ingress rule, specifies where network traffic originates from.

    :param source_port_range:
        The source port or range. Integer or range between 0 and 65535. Asterix '*'
        can also be used to match all ports.

    :param destination_address_prefixes:
        A list of destination_address_prefix values. This parameter overrides destination_address_prefix
        and will cause any value entered there to be ignored.

    :param destination_port_ranges:
        A list of destination_port_range values. This parameter overrides destination_port_range
        and will cause any value entered there to be ignored.

    :param source_address_prefixes:
        A list of source_address_prefix values. This parameter overrides source_address_prefix
        and will cause any value entered there to be ignored.

    :param source_port_ranges:
        A list of source_port_range values. This parameter overrides source_port_range
        and will cause any value entered there to be ignored.

    :param connection_auth:
        A dict with subscription and authentication parameters to be used in connecting to the
        Azure Resource Manager API.

    Example usage:

    .. code-block:: yaml

        Ensure security rule exists:
            azurearm_network.security_rule_present:
                - name: nsg1_rule2
                - security_group: nsg1
                - resource_group: group1
                - priority: 101
                - protocol: tcp
                - access: allow
                - direction: inbound
                - source_address_prefix: internet
                - destination_address_prefix: virtualnetwork
                - source_port_range: '*'
                - destination_port_ranges:
                  - '80'
                  - '443'
                - connection_auth: {{ profile }}
                - require:
                  - azurearm_network: Ensure network security group exists

    '''
    ret = {
        'name': name,
        'result': False,
        'comment': '',
        'changes': {}
    }

    if not isinstance(connection_auth, dict):
        ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
        return ret

    exclusive_params = [
        ('source_port_ranges', 'source_port_range'),
        ('source_address_prefixes', 'source_address_prefix'),
        ('destination_port_ranges', 'destination_port_range'),
        ('destination_address_prefixes', 'destination_address_prefix'),
    ]

    for params in exclusive_params:
        # pylint: disable=eval-used
        if not eval(params[0]) and not eval(params[1]):
            ret['comment'] = 'Either the {0} or {1} parameter must be provided!'.format(params[0], params[1])
            return ret
        # pylint: disable=eval-used
        if eval(params[0]):
            # pylint: disable=eval-used
            if not isinstance(eval(params[0]), list):
                ret['comment'] = 'The {0} parameter must be a list!'.format(params[0])
                return ret
            # pylint: disable=exec-used
            exec('{0} = None'.format(params[1]))

    rule = __salt__['azurearm_network.security_rule_get'](
        name,
        security_group,
        resource_group,
        azurearm_log_level='info',
        **connection_auth
    )

    if 'error' not in rule:
        # access changes
        if access.capitalize() != rule.get('access'):
            ret['changes']['access'] = {
                'old': rule.get('access'),
                'new': access
            }

        # description changes
        if description != rule.get('description'):
            ret['changes']['description'] = {
                'old': rule.get('description'),
                'new': description
            }

        # direction changes
        if direction.capitalize() != rule.get('direction'):
            ret['changes']['direction'] = {
                'old': rule.get('direction'),
                'new': direction
            }

        # priority changes
        if int(priority) != rule.get('priority'):
            ret['changes']['priority'] = {
                'old': rule.get('priority'),
                'new': priority
            }

        # protocol changes
        if protocol.lower() != rule.get('protocol', '').lower():
            ret['changes']['protocol'] = {
                'old': rule.get('protocol'),
                'new': protocol
            }

        # destination_port_range changes
        if destination_port_range != rule.get('destination_port_range'):
            ret['changes']['destination_port_range'] = {
                'old': rule.get('destination_port_range'),
                'new': destination_port_range
            }

        # source_port_range changes
        if source_port_range != rule.get('source_port_range'):
            ret['changes']['source_port_range'] = {
                'old': rule.get('source_port_range'),
                'new': source_port_range
            }

        # destination_port_ranges changes
        if sorted(destination_port_ranges or []) != sorted(rule.get('destination_port_ranges', [])):
            ret['changes']['destination_port_ranges'] = {
                'old': rule.get('destination_port_ranges'),
                'new': destination_port_ranges
            }

        # source_port_ranges changes
        if sorted(source_port_ranges or []) != sorted(rule.get('source_port_ranges', [])):
            ret['changes']['source_port_ranges'] = {
                'old': rule.get('source_port_ranges'),
                'new': source_port_ranges
            }

        # destination_address_prefix changes
        if (destination_address_prefix or '').lower() != rule.get('destination_address_prefix', '').lower():
            ret['changes']['destination_address_prefix'] = {
                'old': rule.get('destination_address_prefix'),
                'new': destination_address_prefix
            }

        # source_address_prefix changes
        if (source_address_prefix or '').lower() != rule.get('source_address_prefix', '').lower():
            ret['changes']['source_address_prefix'] = {
                'old': rule.get('source_address_prefix'),
                'new': source_address_prefix
            }

        # destination_address_prefixes changes
        if sorted(destination_address_prefixes or []) != sorted(rule.get('destination_address_prefixes', [])):
            if len(destination_address_prefixes or []) != len(rule.get('destination_address_prefixes', [])):
                ret['changes']['destination_address_prefixes'] = {
                    'old': rule.get('destination_address_prefixes'),
                    'new': destination_address_prefixes
                }
            else:
                local_dst_addrs, remote_dst_addrs = (sorted(destination_address_prefixes),
                                                     sorted(rule.get('destination_address_prefixes')))
                for idx in six_range(0, len(local_dst_addrs)):
                    if local_dst_addrs[idx].lower() != remote_dst_addrs[idx].lower():
                        ret['changes']['destination_address_prefixes'] = {
                            'old': rule.get('destination_address_prefixes'),
                            'new': destination_address_prefixes
                        }
                        break

        # source_address_prefixes changes
        if sorted(source_address_prefixes or []) != sorted(rule.get('source_address_prefixes', [])):
            if len(source_address_prefixes or []) != len(rule.get('source_address_prefixes', [])):
                ret['changes']['source_address_prefixes'] = {
                    'old': rule.get('source_address_prefixes'),
                    'new': source_address_prefixes
                }
            else:
                local_src_addrs, remote_src_addrs = (sorted(source_address_prefixes),
                                                     sorted(rule.get('source_address_prefixes')))
                for idx in six_range(0, len(local_src_addrs)):
                    if local_src_addrs[idx].lower() != remote_src_addrs[idx].lower():
                        ret['changes']['source_address_prefixes'] = {
                            'old': rule.get('source_address_prefixes'),
                            'new': source_address_prefixes
                        }
                        break

        if not ret['changes']:
            ret['result'] = True
            ret['comment'] = 'Security rule {0} is already present.'.format(name)
            return ret

        if __opts__['test']:
            ret['result'] = None
            ret['comment'] = 'Security rule {0} would be updated.'.format(name)
            return ret

    else:
        ret['changes'] = {
            'old': {},
            'new': {
                'name': name,
                'access': access,
                'description': description,
                'direction': direction,
                'priority': priority,
                'protocol': protocol,
                'destination_address_prefix': destination_address_prefix,
                'destination_address_prefixes': destination_address_prefixes,
                'destination_port_range': destination_port_range,
                'destination_port_ranges': destination_port_ranges,
                'source_address_prefix': source_address_prefix,
                'source_address_prefixes': source_address_prefixes,
                'source_port_range': source_port_range,
                'source_port_ranges': source_port_ranges,
            }
        }

    if __opts__['test']:
        ret['comment'] = 'Security rule {0} would be created.'.format(name)
        ret['result'] = None
        return ret

    rule_kwargs = kwargs.copy()
    rule_kwargs.update(connection_auth)

    rule = __salt__['azurearm_network.security_rule_create_or_update'](
        name=name,
        access=access,
        description=description,
        direction=direction,
        priority=priority,
        protocol=protocol,
        security_group=security_group,
        resource_group=resource_group,
        destination_address_prefix=destination_address_prefix,
        destination_address_prefixes=destination_address_prefixes,
        destination_port_range=destination_port_range,
        destination_port_ranges=destination_port_ranges,
        source_address_prefix=source_address_prefix,
        source_address_prefixes=source_address_prefixes,
        source_port_range=source_port_range,
        source_port_ranges=source_port_ranges,
        **rule_kwargs
    )

    if 'error' not in rule:
        ret['result'] = True
        ret['comment'] = 'Security rule {0} has been created.'.format(name)
        return ret

    ret['comment'] = 'Failed to create security rule {0}! ({1})'.format(name, rule.get('error'))
    return ret

Response: Ensures a security rule exists in the network.


Instruction:
Write a Python 3 function for
ensuring a security rule is absent in the network security group.

Response:
def security_rule_absent(name, security_group, resource_group, connection_auth=None):
    '''
    .. versionadded:: 2019.2.0

    Ensure a security rule does not exist in the network security group.

    :param name:
        Name of the security rule.

    :param security_group:
        The network security group containing the security rule.

    :param resource_group:
        The resource group assigned to the network security group.

    :param connection_auth:
        A dict with subscription and authentication parameters to be used in connecting to the
        Azure Resource Manager API.
    '''
    ret = {
        'name': name,
        'result': False,
        'comment': '',
        'changes': {}
    }

    if not isinstance(connection_auth, dict):
        ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
        return ret

    rule = __salt__['azurearm_network.security_rule_get'](
        name,
        security_group,
        resource_group,
        azurearm_log_level='info',
        **connection_auth
    )

    if 'error' in rule:
        ret['result'] = True
        ret['comment'] = 'Security rule {0} was not found.'.format(name)
        return ret

    elif __opts__['test']:
        ret['comment'] = 'Security rule {0} would be deleted.'.format(name)
        ret['result'] = None
        ret['changes'] = {
            'old': rule,
            'new': {},
        }
        return ret

    deleted = __salt__['azurearm_network.security_rule_delete'](name, security_group, resource_group, **connection_auth)

    if deleted:
        ret['result'] = True
        ret['comment'] = 'Security rule {0} has been deleted.'.format(name)
        ret['changes'] = {
            'old': rule,
            'new': {}
        }
        return ret

    ret['comment'] = 'Failed to delete security rule {0}!'.format(name)
    return ret


Instruction:
Can you implement a function in Python 3 that
ensures that a load balancer exists and is up - to - date.

Response:
def load_balancer_present(name, resource_group, sku=None, frontend_ip_configurations=None, backend_address_pools=None,
                          load_balancing_rules=None, probes=None, inbound_nat_rules=None, inbound_nat_pools=None,
                          outbound_nat_rules=None, tags=None, connection_auth=None, **kwargs):
    '''
    .. versionadded:: 2019.2.0

    Ensure a load balancer exists.

    :param name:
        Name of the load balancer.

    :param resource_group:
        The resource group assigned to the load balancer.

    :param sku:
        The load balancer SKU, which can be 'Basic' or 'Standard'.

    :param tags:
        A dictionary of strings can be passed as tag metadata to the load balancer object.

    :param frontend_ip_configurations:
        An optional list of dictionaries representing valid FrontendIPConfiguration objects. A frontend IP
        configuration can be either private (using private IP address and subnet parameters) or public (using a
        reference to a public IP address object). Valid parameters are:

        - ``name``: The name of the resource that is unique within a resource group.
        - ``private_ip_address``: The private IP address of the IP configuration. Required if
          'private_ip_allocation_method' is 'Static'.
        - ``private_ip_allocation_method``: The Private IP allocation method. Possible values are: 'Static' and
          'Dynamic'.
        - ``subnet``: Name of an existing subnet inside of which the frontend IP will reside.
        - ``public_ip_address``: Name of an existing public IP address which will be assigned to the frontend IP object.

    :param backend_address_pools:
        An optional list of dictionaries representing valid BackendAddressPool objects. Only the 'name' parameter is
        valid for a BackendAddressPool dictionary. All other parameters are read-only references from other objects
        linking to the backend address pool. Inbound traffic is randomly load balanced across IPs in the backend IPs.

    :param probes:
        An optional list of dictionaries representing valid Probe objects. Valid parameters are:

        - ``name``: The name of the resource that is unique within a resource group.
        - ``protocol``: The protocol of the endpoint. Possible values are 'Http' or 'Tcp'. If 'Tcp' is specified, a
          received ACK is required for the probe to be successful. If 'Http' is specified, a 200 OK response from the
          specified URI is required for the probe to be successful.
        - ``port``: The port for communicating the probe. Possible values range from 1 to 65535, inclusive.
        - ``interval_in_seconds``: The interval, in seconds, for how frequently to probe the endpoint for health status.
          Typically, the interval is slightly less than half the allocated timeout period (in seconds) which allows two
          full probes before taking the instance out of rotation. The default value is 15, the minimum value is 5.
        - ``number_of_probes``: The number of probes where if no response, will result in stopping further traffic from
          being delivered to the endpoint. This values allows endpoints to be taken out of rotation faster or slower
          than the typical times used in Azure.
        - ``request_path``: The URI used for requesting health status from the VM. Path is required if a protocol is
          set to 'Http'. Otherwise, it is not allowed. There is no default value.

    :param load_balancing_rules:
        An optional list of dictionaries representing valid LoadBalancingRule objects. Valid parameters are:

        - ``name``: The name of the resource that is unique within a resource group.
        - ``load_distribution``: The load distribution policy for this rule. Possible values are 'Default', 'SourceIP',
          and 'SourceIPProtocol'.
        - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the
          Load Balancer. Acceptable values are between 0 and 65534. Note that value 0 enables 'Any Port'.
        - ``backend_port``: The port used for internal connections on the endpoint. Acceptable values are between 0 and
          65535. Note that value 0 enables 'Any Port'.
        - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30
          minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP.
        - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required
          to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn
          Availability Groups in SQL server. This setting can't be changed after you create the endpoint.
        - ``disable_outbound_snat``: Configures SNAT for the VMs in the backend pool to use the public IP address
          specified in the frontend of the load balancing rule.
        - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the load balancing rule
          object.
        - ``backend_address_pool``: Name of the backend address pool object used by the load balancing rule object.
          Inbound traffic is randomly load balanced across IPs in the backend IPs.
        - ``probe``: Name of the probe object used by the load balancing rule object.

    :param inbound_nat_rules:
        An optional list of dictionaries representing valid InboundNatRule objects. Defining inbound NAT rules on your
        load balancer is mutually exclusive with defining an inbound NAT pool. Inbound NAT pools are referenced from
        virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an
        Inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are:

        - ``name``: The name of the resource that is unique within a resource group.
        - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT rule
          object.
        - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'.
        - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the
          Load Balancer. Acceptable values range from 1 to 65534.
        - ``backend_port``: The port used for the internal endpoint. Acceptable values range from 1 to 65535.
        - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30
          minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP.
        - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required
          to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn
          Availability Groups in SQL server. This setting can't be changed after you create the endpoint.

    :param inbound_nat_pools:
        An optional list of dictionaries representing valid InboundNatPool objects. They define an external port range
        for inbound NAT to a single backend port on NICs associated with a load balancer. Inbound NAT rules are created
        automatically for each NIC associated with the Load Balancer using an external port from this range. Defining an
        Inbound NAT pool on your Load Balancer is mutually exclusive with defining inbound NAT rules. Inbound NAT pools
        are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot
        reference an inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are:

        - ``name``: The name of the resource that is unique within a resource group.
        - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT pool
          object.
        - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'.
        - ``frontend_port_range_start``: The first port number in the range of external ports that will be used to
          provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65534.
        - ``frontend_port_range_end``: The last port number in the range of external ports that will be used to
          provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65535.
        - ``backend_port``: The port used for internal connections to the endpoint. Acceptable values are between 1 and
          65535.

    :param outbound_nat_rules:
        An optional list of dictionaries representing valid OutboundNatRule objects. Valid parameters are:

        - ``name``: The name of the resource that is unique within a resource group.
        - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the outbound NAT rule
          object.
        - ``backend_address_pool``: Name of the backend address pool object used by the outbound NAT rule object.
          Outbound traffic is randomly load balanced across IPs in the backend IPs.
        - ``allocated_outbound_ports``: The number of outbound ports to be used for NAT.

    :param connection_auth:
        A dict with subscription and authentication parameters to be used in connecting to the
        Azure Resource Manager API.

    Example usage:

    .. code-block:: yaml

        Ensure load balancer exists:
            azurearm_network.load_balancer_present:
                - name: lb1
                - resource_group: group1
                - location: eastus
                - frontend_ip_configurations:
                  - name: lb1_feip1
                    public_ip_address: pub_ip1
                - backend_address_pools:
                  - name: lb1_bepool1
                - probes:
                  - name: lb1_webprobe1
                    protocol: tcp
                    port: 80
                    interval_in_seconds: 5
                    number_of_probes: 2
                - load_balancing_rules:
                  - name: lb1_webprobe1
                    protocol: tcp
                    frontend_port: 80
                    backend_port: 80
                    idle_timeout_in_minutes: 4
                    frontend_ip_configuration: lb1_feip1
                    backend_address_pool: lb1_bepool1
                    probe: lb1_webprobe1
                - tags:
                    contact_name: Elmer Fudd Gantry
                - connection_auth: {{ profile }}
                - require:
                  - azurearm_resource: Ensure resource group exists
                  - azurearm_network: Ensure public IP exists

    '''
    ret = {
        'name': name,
        'result': False,
        'comment': '',
        'changes': {}
    }

    if not isinstance(connection_auth, dict):
        ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
        return ret

    if sku:
        sku = {'name': sku.capitalize()}

    load_bal = __salt__['azurearm_network.load_balancer_get'](
        name,
        resource_group,
        azurearm_log_level='info',
        **connection_auth
    )

    if 'error' not in load_bal:
        # tag changes
        tag_changes = __utils__['dictdiffer.deep_diff'](load_bal.get('tags', {}), tags or {})
        if tag_changes:
            ret['changes']['tags'] = tag_changes

        # sku changes
        if sku:
            sku_changes = __utils__['dictdiffer.deep_diff'](load_bal.get('sku', {}), sku)
            if sku_changes:
                ret['changes']['sku'] = sku_changes

        # frontend_ip_configurations changes
        if frontend_ip_configurations:
            comp_ret = __utils__['azurearm.compare_list_of_dicts'](
                load_bal.get('frontend_ip_configurations', []),
                frontend_ip_configurations,
                ['public_ip_address', 'subnet']
            )

            if comp_ret.get('comment'):
                ret['comment'] = '"frontend_ip_configurations" {0}'.format(comp_ret['comment'])
                return ret

            if comp_ret.get('changes'):
                ret['changes']['frontend_ip_configurations'] = comp_ret['changes']

        # backend_address_pools changes
        if backend_address_pools:
            comp_ret = __utils__['azurearm.compare_list_of_dicts'](
                load_bal.get('backend_address_pools', []),
                backend_address_pools
            )

            if comp_ret.get('comment'):
                ret['comment'] = '"backend_address_pools" {0}'.format(comp_ret['comment'])
                return ret

            if comp_ret.get('changes'):
                ret['changes']['backend_address_pools'] = comp_ret['changes']

        # probes changes
        if probes:
            comp_ret = __utils__['azurearm.compare_list_of_dicts'](load_bal.get('probes', []), probes)

            if comp_ret.get('comment'):
                ret['comment'] = '"probes" {0}'.format(comp_ret['comment'])
                return ret

            if comp_ret.get('changes'):
                ret['changes']['probes'] = comp_ret['changes']

        # load_balancing_rules changes
        if load_balancing_rules:
            comp_ret = __utils__['azurearm.compare_list_of_dicts'](
                load_bal.get('load_balancing_rules', []),
                load_balancing_rules,
                ['frontend_ip_configuration', 'backend_address_pool', 'probe']
            )

            if comp_ret.get('comment'):
                ret['comment'] = '"load_balancing_rules" {0}'.format(comp_ret['comment'])
                return ret

            if comp_ret.get('changes'):
                ret['changes']['load_balancing_rules'] = comp_ret['changes']

        # inbound_nat_rules changes
        if inbound_nat_rules:
            comp_ret = __utils__['azurearm.compare_list_of_dicts'](
                load_bal.get('inbound_nat_rules', []),
                inbound_nat_rules,
                ['frontend_ip_configuration']
            )

            if comp_ret.get('comment'):
                ret['comment'] = '"inbound_nat_rules" {0}'.format(comp_ret['comment'])
                return ret

            if comp_ret.get('changes'):
                ret['changes']['inbound_nat_rules'] = comp_ret['changes']

        # inbound_nat_pools changes
        if inbound_nat_pools:
            comp_ret = __utils__['azurearm.compare_list_of_dicts'](
                load_bal.get('inbound_nat_pools', []),
                inbound_nat_pools,
                ['frontend_ip_configuration']
            )

            if comp_ret.get('comment'):
                ret['comment'] = '"inbound_nat_pools" {0}'.format(comp_ret['comment'])
                return ret

            if comp_ret.get('changes'):
                ret['changes']['inbound_nat_pools'] = comp_ret['changes']

        # outbound_nat_rules changes
        if outbound_nat_rules:
            comp_ret = __utils__['azurearm.compare_list_of_dicts'](
                load_bal.get('outbound_nat_rules', []),
                outbound_nat_rules,
                ['frontend_ip_configuration']
            )

            if comp_ret.get('comment'):
                ret['comment'] = '"outbound_nat_rules" {0}'.format(comp_ret['comment'])
                return ret

            if comp_ret.get('changes'):
                ret['changes']['outbound_nat_rules'] = comp_ret['changes']

        if not ret['changes']:
            ret['result'] = True
            ret['comment'] = 'Load balancer {0} is already present.'.format(name)
            return ret

        if __opts__['test']:
            ret['result'] = None
            ret['comment'] = 'Load balancer {0} would be updated.'.format(name)
            return ret

    else:
        ret['changes'] = {
            'old': {},
            'new': {
                'name': name,
                'sku': sku,
                'tags': tags,
                'frontend_ip_configurations': frontend_ip_configurations,
                'backend_address_pools': backend_address_pools,
                'load_balancing_rules': load_balancing_rules,
                'probes': probes,
                'inbound_nat_rules': inbound_nat_rules,
                'inbound_nat_pools': inbound_nat_pools,
                'outbound_nat_rules': outbound_nat_rules,
            }
        }

    if __opts__['test']:
        ret['comment'] = 'Load balancer {0} would be created.'.format(name)
        ret['result'] = None
        return ret

    lb_kwargs = kwargs.copy()
    lb_kwargs.update(connection_auth)

    load_bal = __salt__['azurearm_network.load_balancer_create_or_update'](
        name=name,
        resource_group=resource_group,
        sku=sku,
        tags=tags,
        frontend_ip_configurations=frontend_ip_configurations,
        backend_address_pools=backend_address_pools,
        load_balancing_rules=load_balancing_rules,
        probes=probes,
        inbound_nat_rules=inbound_nat_rules,
        inbound_nat_pools=inbound_nat_pools,
        outbound_nat_rules=outbound_nat_rules,
        **lb_kwargs
    )

    if 'error' not in load_bal:
        ret['result'] = True
        ret['comment'] = 'Load balancer {0} has been created.'.format(name)
        return ret

    ret['comment'] = 'Failed to create load balancer {0}! ({1})'.format(name, load_bal.get('error'))
    return ret


Instruction:
How would you implement a function in Python 3 that
ensures a load balancer with the given name is absent in the given resource group.

Response:
def load_balancer_absent(name, resource_group, connection_auth=None):
    '''
    .. versionadded:: 2019.2.0

    Ensure a load balancer does not exist in the resource group.

    :param name:
        Name of the load balancer.

    :param resource_group:
        The resource group assigned to the load balancer.

    :param connection_auth:
        A dict with subscription and authentication parameters to be used in connecting to the
        Azure Resource Manager API.
    '''
    ret = {
        'name': name,
        'result': False,
        'comment': '',
        'changes': {}
    }

    if not isinstance(connection_auth, dict):
        ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
        return ret

    load_bal = __salt__['azurearm_network.load_balancer_get'](
        name,
        resource_group,
        azurearm_log_level='info',
        **connection_auth
    )

    if 'error' in load_bal:
        ret['result'] = True
        ret['comment'] = 'Load balancer {0} was not found.'.format(name)
        return ret

    elif __opts__['test']:
        ret['comment'] = 'Load balancer {0} would be deleted.'.format(name)
        ret['result'] = None
        ret['changes'] = {
            'old': load_bal,
            'new': {},
        }
        return ret

    deleted = __salt__['azurearm_network.load_balancer_delete'](name, resource_group, **connection_auth)

    if deleted:
        ret['result'] = True
        ret['comment'] = 'Load balancer {0} has been deleted.'.format(name)
        ret['changes'] = {
            'old': load_bal,
            'new': {}
        }
        return ret

    ret['comment'] = 'Failed to delete load balancer {0}!'.format(name)
    return ret


Instruction:
Write a Python 3 script for
ensuring that a public IP address exists in the resource group with the given name resource group and tags are passed as tag metadata.

Response:
def public_ip_address_present(name, resource_group, tags=None, sku=None, public_ip_allocation_method=None,
                              public_ip_address_version=None, dns_settings=None, idle_timeout_in_minutes=None,
                              connection_auth=None, **kwargs):
    '''
    .. versionadded:: 2019.2.0

    Ensure a public IP address exists.

    :param name:
        Name of the public IP address.

    :param resource_group:
        The resource group assigned to the public IP address.

    :param dns_settings:
        An optional dictionary representing a valid PublicIPAddressDnsSettings object. Parameters include
        'domain_name_label' and 'reverse_fqdn', which accept strings. The 'domain_name_label' parameter is concatenated
        with the regionalized DNS zone make up the fully qualified domain name associated with the public IP address.
        If a domain name label is specified, an A DNS record is created for the public IP in the Microsoft Azure DNS
        system. The 'reverse_fqdn' parameter is a user-visible, fully qualified domain name that resolves to this public
        IP address. If the reverse FQDN is specified, then a PTR DNS record is created pointing from the IP address in
        the in-addr.arpa domain to the reverse FQDN.

    :param sku:
        The public IP address SKU, which can be 'Basic' or 'Standard'.

    :param public_ip_allocation_method:
        The public IP allocation method. Possible values are: 'Static' and 'Dynamic'.

    :param public_ip_address_version:
        The public IP address version. Possible values are: 'IPv4' and 'IPv6'.

    :param idle_timeout_in_minutes:
        An integer representing the idle timeout of the public IP address.

    :param tags:
        A dictionary of strings can be passed as tag metadata to the public IP address object.

    :param connection_auth:
        A dict with subscription and authentication parameters to be used in connecting to the
        Azure Resource Manager API.

    Example usage:

    .. code-block:: yaml

        Ensure public IP exists:
            azurearm_network.public_ip_address_present:
                - name: pub_ip1
                - resource_group: group1
                - dns_settings:
                    domain_name_label: decisionlab-ext-test-label
                - sku: basic
                - public_ip_allocation_method: static
                - public_ip_address_version: ipv4
                - idle_timeout_in_minutes: 4
                - tags:
                    contact_name: Elmer Fudd Gantry
                - connection_auth: {{ profile }}
                - require:
                  - azurearm_resource: Ensure resource group exists

    '''
    ret = {
        'name': name,
        'result': False,
        'comment': '',
        'changes': {}
    }

    if not isinstance(connection_auth, dict):
        ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
        return ret

    if sku:
        sku = {'name': sku.capitalize()}

    pub_ip = __salt__['azurearm_network.public_ip_address_get'](
        name,
        resource_group,
        azurearm_log_level='info',
        **connection_auth
    )

    if 'error' not in pub_ip:
        # tag changes
        tag_changes = __utils__['dictdiffer.deep_diff'](pub_ip.get('tags', {}), tags or {})
        if tag_changes:
            ret['changes']['tags'] = tag_changes

        # dns_settings changes
        if dns_settings:
            if not isinstance(dns_settings, dict):
                ret['comment'] = 'DNS settings must be provided as a dictionary!'
                return ret

            for key in dns_settings:
                if dns_settings[key] != pub_ip.get('dns_settings', {}).get(key):
                    ret['changes']['dns_settings'] = {
                        'old': pub_ip.get('dns_settings'),
                        'new': dns_settings
                    }
                    break

        # sku changes
        if sku:
            sku_changes = __utils__['dictdiffer.deep_diff'](pub_ip.get('sku', {}), sku)
            if sku_changes:
                ret['changes']['sku'] = sku_changes

        # public_ip_allocation_method changes
        if public_ip_allocation_method:
            if public_ip_allocation_method.capitalize() != pub_ip.get('public_ip_allocation_method'):
                ret['changes']['public_ip_allocation_method'] = {
                    'old': pub_ip.get('public_ip_allocation_method'),
                    'new': public_ip_allocation_method
                }

        # public_ip_address_version changes
        if public_ip_address_version:
            if public_ip_address_version.lower() != pub_ip.get('public_ip_address_version', '').lower():
                ret['changes']['public_ip_address_version'] = {
                    'old': pub_ip.get('public_ip_address_version'),
                    'new': public_ip_address_version
                }

        # idle_timeout_in_minutes changes
        if idle_timeout_in_minutes and (int(idle_timeout_in_minutes) != pub_ip.get('idle_timeout_in_minutes')):
            ret['changes']['idle_timeout_in_minutes'] = {
                'old': pub_ip.get('idle_timeout_in_minutes'),
                'new': idle_timeout_in_minutes
            }

        if not ret['changes']:
            ret['result'] = True
            ret['comment'] = 'Public IP address {0} is already present.'.format(name)
            return ret

        if __opts__['test']:
            ret['result'] = None
            ret['comment'] = 'Public IP address {0} would be updated.'.format(name)
            return ret

    else:
        ret['changes'] = {
            'old': {},
            'new': {
                'name': name,
                'tags': tags,
                'dns_settings': dns_settings,
                'sku': sku,
                'public_ip_allocation_method': public_ip_allocation_method,
                'public_ip_address_version': public_ip_address_version,
                'idle_timeout_in_minutes': idle_timeout_in_minutes,
            }
        }

    if __opts__['test']:
        ret['comment'] = 'Public IP address {0} would be created.'.format(name)
        ret['result'] = None
        return ret

    pub_ip_kwargs = kwargs.copy()
    pub_ip_kwargs.update(connection_auth)

    pub_ip = __salt__['azurearm_network.public_ip_address_create_or_update'](
        name=name,
        resource_group=resource_group,
        sku=sku,
        tags=tags,
        dns_settings=dns_settings,
        public_ip_allocation_method=public_ip_allocation_method,
        public_ip_address_version=public_ip_address_version,
        idle_timeout_in_minutes=idle_timeout_in_minutes,
        **pub_ip_kwargs
    )

    if 'error' not in pub_ip:
        ret['result'] = True
        ret['comment'] = 'Public IP address {0} has been created.'.format(name)
        return ret

    ret['comment'] = 'Failed to create public IP address {0}! ({1})'.format(name, pub_ip.get('error'))
    return ret


Instruction:
Implement a function in Python 3 to
ensure that the public IP address is absent in the resource group.

Response:
def public_ip_address_absent(name, resource_group, connection_auth=None):
    '''
    .. versionadded:: 2019.2.0

    Ensure a public IP address does not exist in the resource group.

    :param name:
        Name of the public IP address.

    :param resource_group:
        The resource group assigned to the public IP address.

    :param connection_auth:
        A dict with subscription and authentication parameters to be used in connecting to the
        Azure Resource Manager API.
    '''
    ret = {
        'name': name,
        'result': False,
        'comment': '',
        'changes': {}
    }

    if not isinstance(connection_auth, dict):
        ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
        return ret

    pub_ip = __salt__['azurearm_network.public_ip_address_get'](
        name,
        resource_group,
        azurearm_log_level='info',
        **connection_auth
    )

    if 'error' in pub_ip:
        ret['result'] = True
        ret['comment'] = 'Public IP address {0} was not found.'.format(name)
        return ret

    elif __opts__['test']:
        ret['comment'] = 'Public IP address {0} would be deleted.'.format(name)
        ret['result'] = None
        ret['changes'] = {
            'old': pub_ip,
            'new': {},
        }
        return ret

    deleted = __salt__['azurearm_network.public_ip_address_delete'](name, resource_group, **connection_auth)

    if deleted:
        ret['result'] = True
        ret['comment'] = 'Public IP address {0} has been deleted.'.format(name)
        ret['changes'] = {
            'old': pub_ip,
            'new': {}
        }
        return ret

    ret['comment'] = 'Failed to delete public IP address {0}!'.format(name)
    return ret


Instruction:
Write a Python 3 script to
ensure that a network interface with the given parameters is present.

Response:
def network_interface_present(name, ip_configurations, subnet, virtual_network, resource_group, tags=None,
                              virtual_machine=None, network_security_group=None, dns_settings=None, mac_address=None,
                              primary=None, enable_accelerated_networking=None, enable_ip_forwarding=None,
                              connection_auth=None, **kwargs):
    '''
    .. versionadded:: 2019.2.0

    Ensure a network interface exists.

    :param name:
        Name of the network interface.

    :param ip_configurations:
        A list of dictionaries representing valid NetworkInterfaceIPConfiguration objects. The 'name' key is required at
        minimum. At least one IP Configuration must be present.

    :param subnet:
        Name of the existing subnet assigned to the network interface.

    :param virtual_network:
        Name of the existing virtual network containing the subnet.

    :param resource_group:
        The resource group assigned to the virtual network.

    :param tags:
        A dictionary of strings can be passed as tag metadata to the network interface object.

    :param network_security_group:
        The name of the existing network security group to assign to the network interface.

    :param virtual_machine:
        The name of the existing virtual machine to assign to the network interface.

    :param dns_settings:
        An optional dictionary representing a valid NetworkInterfaceDnsSettings object. Valid parameters are:

        - ``dns_servers``: List of DNS server IP addresses. Use 'AzureProvidedDNS' to switch to Azure provided DNS
          resolution. 'AzureProvidedDNS' value cannot be combined with other IPs, it must be the only value in
          dns_servers collection.
        - ``internal_dns_name_label``: Relative DNS name for this NIC used for internal communications between VMs in
          the same virtual network.
        - ``internal_fqdn``: Fully qualified DNS name supporting internal communications between VMs in the same virtual
          network.
        - ``internal_domain_name_suffix``: Even if internal_dns_name_label is not specified, a DNS entry is created for
          the primary NIC of the VM. This DNS name can be constructed by concatenating the VM name with the value of
          internal_domain_name_suffix.

    :param mac_address:
        Optional string containing the MAC address of the network interface.

    :param primary:
        Optional boolean allowing the interface to be set as the primary network interface on a virtual machine
        with multiple interfaces attached.

    :param enable_accelerated_networking:
        Optional boolean indicating whether accelerated networking should be enabled for the interface.

    :param enable_ip_forwarding:
        Optional boolean indicating whether IP forwarding should be enabled for the interface.

    :param connection_auth:
        A dict with subscription and authentication parameters to be used in connecting to the
        Azure Resource Manager API.

    Example usage:

    .. code-block:: yaml

        Ensure network interface exists:
            azurearm_network.network_interface_present:
                - name: iface1
                - subnet: vnet1_sn1
                - virtual_network: vnet1
                - resource_group: group1
                - ip_configurations:
                  - name: iface1_ipc1
                    public_ip_address: pub_ip2
                - dns_settings:
                    internal_dns_name_label: decisionlab-int-test-label
                - primary: True
                - enable_accelerated_networking: True
                - enable_ip_forwarding: False
                - network_security_group: nsg1
                - connection_auth: {{ profile }}
                - require:
                  - azurearm_network: Ensure subnet exists
                  - azurearm_network: Ensure network security group exists
                  - azurearm_network: Ensure another public IP exists

    '''
    ret = {
        'name': name,
        'result': False,
        'comment': '',
        'changes': {}
    }

    if not isinstance(connection_auth, dict):
        ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
        return ret

    iface = __salt__['azurearm_network.network_interface_get'](
        name,
        resource_group,
        azurearm_log_level='info',
        **connection_auth
    )

    if 'error' not in iface:
        # tag changes
        tag_changes = __utils__['dictdiffer.deep_diff'](iface.get('tags', {}), tags or {})
        if tag_changes:
            ret['changes']['tags'] = tag_changes

        # mac_address changes
        if mac_address and (mac_address != iface.get('mac_address')):
            ret['changes']['mac_address'] = {
                'old': iface.get('mac_address'),
                'new': mac_address
            }

        # primary changes
        if primary is not None:
            if primary != iface.get('primary', True):
                ret['changes']['primary'] = {
                    'old': iface.get('primary'),
                    'new': primary
                }

        # enable_accelerated_networking changes
        if enable_accelerated_networking is not None:
            if enable_accelerated_networking != iface.get('enable_accelerated_networking'):
                ret['changes']['enable_accelerated_networking'] = {
                    'old': iface.get('enable_accelerated_networking'),
                    'new': enable_accelerated_networking
                }

        # enable_ip_forwarding changes
        if enable_ip_forwarding is not None:
            if enable_ip_forwarding != iface.get('enable_ip_forwarding'):
                ret['changes']['enable_ip_forwarding'] = {
                    'old': iface.get('enable_ip_forwarding'),
                    'new': enable_ip_forwarding
                }

        # network_security_group changes
        nsg_name = None
        if iface.get('network_security_group'):
            nsg_name = iface['network_security_group']['id'].split('/')[-1]

        if network_security_group and (network_security_group != nsg_name):
            ret['changes']['network_security_group'] = {
                'old': nsg_name,
                'new': network_security_group
            }

        # virtual_machine changes
        vm_name = None
        if iface.get('virtual_machine'):
            vm_name = iface['virtual_machine']['id'].split('/')[-1]

        if virtual_machine and (virtual_machine != vm_name):
            ret['changes']['virtual_machine'] = {
                'old': vm_name,
                'new': virtual_machine
            }

        # dns_settings changes
        if dns_settings:
            if not isinstance(dns_settings, dict):
                ret['comment'] = 'DNS settings must be provided as a dictionary!'
                return ret

            for key in dns_settings:
                if dns_settings[key].lower() != iface.get('dns_settings', {}).get(key, '').lower():
                    ret['changes']['dns_settings'] = {
                        'old': iface.get('dns_settings'),
                        'new': dns_settings
                    }
                    break

        # ip_configurations changes
        comp_ret = __utils__['azurearm.compare_list_of_dicts'](
            iface.get('ip_configurations', []),
            ip_configurations,
            ['public_ip_address', 'subnet']
        )

        if comp_ret.get('comment'):
            ret['comment'] = '"ip_configurations" {0}'.format(comp_ret['comment'])
            return ret

        if comp_ret.get('changes'):
            ret['changes']['ip_configurations'] = comp_ret['changes']

        if not ret['changes']:
            ret['result'] = True
            ret['comment'] = 'Network interface {0} is already present.'.format(name)
            return ret

        if __opts__['test']:
            ret['result'] = None
            ret['comment'] = 'Network interface {0} would be updated.'.format(name)
            return ret

    else:
        ret['changes'] = {
            'old': {},
            'new': {
                'name': name,
                'ip_configurations': ip_configurations,
                'dns_settings': dns_settings,
                'network_security_group': network_security_group,
                'virtual_machine': virtual_machine,
                'enable_accelerated_networking': enable_accelerated_networking,
                'enable_ip_forwarding': enable_ip_forwarding,
                'mac_address': mac_address,
                'primary': primary,
                'tags': tags,
            }
        }

    if __opts__['test']:
        ret['comment'] = 'Network interface {0} would be created.'.format(name)
        ret['result'] = None
        return ret

    iface_kwargs = kwargs.copy()
    iface_kwargs.update(connection_auth)

    iface = __salt__['azurearm_network.network_interface_create_or_update'](
        name=name,
        subnet=subnet,
        virtual_network=virtual_network,
        resource_group=resource_group,
        ip_configurations=ip_configurations,
        dns_settings=dns_settings,
        enable_accelerated_networking=enable_accelerated_networking,
        enable_ip_forwarding=enable_ip_forwarding,
        mac_address=mac_address,
        primary=primary,
        network_security_group=network_security_group,
        virtual_machine=virtual_machine,
        tags=tags,
        **iface_kwargs
    )

    if 'error' not in iface:
        ret['result'] = True
        ret['comment'] = 'Network interface {0} has been created.'.format(name)
        return ret

    ret['comment'] = 'Failed to create network interface {0}! ({1})'.format(name, iface.get('error'))
    return ret


Instruction:
Can you generate a brief explanation for the following Python 3 code
def network_interface_absent(name, resource_group, connection_auth=None):
    '''
    .. versionadded:: 2019.2.0

    Ensure a network interface does not exist in the resource group.

    :param name:
        Name of the network interface.

    :param resource_group:
        The resource group assigned to the network interface.

    :param connection_auth:
        A dict with subscription and authentication parameters to be used in connecting to the
        Azure Resource Manager API.
    '''
    ret = {
        'name': name,
        'result': False,
        'comment': '',
        'changes': {}
    }

    if not isinstance(connection_auth, dict):
        ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
        return ret

    iface = __salt__['azurearm_network.network_interface_get'](
        name,
        resource_group,
        azurearm_log_level='info',
        **connection_auth
    )

    if 'error' in iface:
        ret['result'] = True
        ret['comment'] = 'Network interface {0} was not found.'.format(name)
        return ret

    elif __opts__['test']:
        ret['comment'] = 'Network interface {0} would be deleted.'.format(name)
        ret['result'] = None
        ret['changes'] = {
            'old': iface,
            'new': {},
        }
        return ret

    deleted = __salt__['azurearm_network.network_interface_delete'](name, resource_group, **connection_auth)

    if deleted:
        ret['result'] = True
        ret['comment'] = 'Network interface {0} has been deleted.'.format(name)
        ret['changes'] = {
            'old': iface,
            'new': {}
        }
        return ret

    ret['comment'] = 'Failed to delete network interface {0}!)'.format(name)
    return ret

Response: Ensure a network interface does not exist in the resource group.


Instruction:
How would you explain what the following Python 3 function does
def route_table_present(name, resource_group, tags=None, routes=None, disable_bgp_route_propagation=None,
                        connection_auth=None, **kwargs):
    '''
    .. versionadded:: 2019.2.0

    Ensure a route table exists.

    :param name:
        Name of the route table.

    :param resource_group:
        The resource group assigned to the route table.

    :param routes:
        An optional list of dictionaries representing valid Route objects contained within a route table. See the
        documentation for the route_present state or route_create_or_update execution module for more information on
        required and optional parameters for routes. The routes are only managed if this parameter is present. When this
        parameter is absent, implemented routes will not be removed, and will merely become unmanaged.

    :param disable_bgp_route_propagation:
        An optional boolean parameter setting whether to disable the routes learned by BGP on the route table.

    :param tags:
        A dictionary of strings can be passed as tag metadata to the route table object.

    :param connection_auth:
        A dict with subscription and authentication parameters to be used in connecting to the
        Azure Resource Manager API.

    Example usage:

    .. code-block:: yaml

        Ensure route table exists:
            azurearm_network.route_table_present:
                - name: rt1
                - resource_group: group1
                - routes:
                  - name: rt1_route1
                    address_prefix: '0.0.0.0/0'
                    next_hop_type: internet
                  - name: rt1_route2
                    address_prefix: '192.168.0.0/16'
                    next_hop_type: vnetlocal
                - tags:
                    contact_name: Elmer Fudd Gantry
                - connection_auth: {{ profile }}
                - require:
                  - azurearm_resource: Ensure resource group exists

    '''
    ret = {
        'name': name,
        'result': False,
        'comment': '',
        'changes': {}
    }

    if not isinstance(connection_auth, dict):
        ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
        return ret

    rt_tbl = __salt__['azurearm_network.route_table_get'](
        name,
        resource_group,
        azurearm_log_level='info',
        **connection_auth
    )

    if 'error' not in rt_tbl:
        # tag changes
        tag_changes = __utils__['dictdiffer.deep_diff'](rt_tbl.get('tags', {}), tags or {})
        if tag_changes:
            ret['changes']['tags'] = tag_changes

        # disable_bgp_route_propagation changes
        # pylint: disable=line-too-long
        if disable_bgp_route_propagation and (disable_bgp_route_propagation != rt_tbl.get('disable_bgp_route_propagation')):
            ret['changes']['disable_bgp_route_propagation'] = {
                'old': rt_tbl.get('disable_bgp_route_propagation'),
                'new': disable_bgp_route_propagation
            }

        # routes changes
        if routes:
            comp_ret = __utils__['azurearm.compare_list_of_dicts'](rt_tbl.get('routes', []), routes)

            if comp_ret.get('comment'):
                ret['comment'] = '"routes" {0}'.format(comp_ret['comment'])
                return ret

            if comp_ret.get('changes'):
                ret['changes']['routes'] = comp_ret['changes']

        if not ret['changes']:
            ret['result'] = True
            ret['comment'] = 'Route table {0} is already present.'.format(name)
            return ret

        if __opts__['test']:
            ret['result'] = None
            ret['comment'] = 'Route table {0} would be updated.'.format(name)
            return ret

    else:
        ret['changes'] = {
            'old': {},
            'new': {
                'name': name,
                'tags': tags,
                'routes': routes,
                'disable_bgp_route_propagation': disable_bgp_route_propagation,
            }
        }

    if __opts__['test']:
        ret['comment'] = 'Route table {0} would be created.'.format(name)
        ret['result'] = None
        return ret

    rt_tbl_kwargs = kwargs.copy()
    rt_tbl_kwargs.update(connection_auth)

    rt_tbl = __salt__['azurearm_network.route_table_create_or_update'](
        name=name,
        resource_group=resource_group,
        disable_bgp_route_propagation=disable_bgp_route_propagation,
        routes=routes,
        tags=tags,
        **rt_tbl_kwargs
    )

    if 'error' not in rt_tbl:
        ret['result'] = True
        ret['comment'] = 'Route table {0} has been created.'.format(name)
        return ret

    ret['comment'] = 'Failed to create route table {0}! ({1})'.format(name, rt_tbl.get('error'))
    return ret

Response: Ensures that a route table with the given name and resource group exists.


Instruction:
Create a Python 3 function for
ensuring a route table is absent in the resource group.

Response:
def route_table_absent(name, resource_group, connection_auth=None):
    '''
    .. versionadded:: 2019.2.0

    Ensure a route table does not exist in the resource group.

    :param name:
        Name of the route table.

    :param resource_group:
        The resource group assigned to the route table.

    :param connection_auth:
        A dict with subscription and authentication parameters to be used in connecting to the
        Azure Resource Manager API.
    '''
    ret = {
        'name': name,
        'result': False,
        'comment': '',
        'changes': {}
    }

    if not isinstance(connection_auth, dict):
        ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
        return ret

    rt_tbl = __salt__['azurearm_network.route_table_get'](
        name,
        resource_group,
        azurearm_log_level='info',
        **connection_auth
    )

    if 'error' in rt_tbl:
        ret['result'] = True
        ret['comment'] = 'Route table {0} was not found.'.format(name)
        return ret

    elif __opts__['test']:
        ret['comment'] = 'Route table {0} would be deleted.'.format(name)
        ret['result'] = None
        ret['changes'] = {
            'old': rt_tbl,
            'new': {},
        }
        return ret

    deleted = __salt__['azurearm_network.route_table_delete'](name, resource_group, **connection_auth)

    if deleted:
        ret['result'] = True
        ret['comment'] = 'Route table {0} has been deleted.'.format(name)
        ret['changes'] = {
            'old': rt_tbl,
            'new': {}
        }
        return ret

    ret['comment'] = 'Failed to delete route table {0}!'.format(name)
    return ret


Instruction:
Given the following Python 3 function, write the documentation
def route_present(name, address_prefix, next_hop_type, route_table, resource_group, next_hop_ip_address=None,
                  connection_auth=None, **kwargs):
    '''
    .. versionadded:: 2019.2.0

    Ensure a route exists within a route table.

    :param name:
        Name of the route.

    :param address_prefix:
        The destination CIDR to which the route applies.

    :param next_hop_type:
        The type of Azure hop the packet should be sent to. Possible values are: 'VirtualNetworkGateway', 'VnetLocal',
        'Internet', 'VirtualAppliance', and 'None'.

    :param next_hop_ip_address:
        The IP address packets should be forwarded to. Next hop values are only allowed in routes where the next hop
        type is 'VirtualAppliance'.

    :param route_table:
        The name of the existing route table which will contain the route.

    :param resource_group:
        The resource group assigned to the route table.

    :param connection_auth:
        A dict with subscription and authentication parameters to be used in connecting to the
        Azure Resource Manager API.

    Example usage:

    .. code-block:: yaml

        Ensure route exists:
            azurearm_network.route_present:
                - name: rt1_route2
                - route_table: rt1
                - resource_group: group1
                - address_prefix: '192.168.0.0/16'
                - next_hop_type: vnetlocal
                - connection_auth: {{ profile }}
                - require:
                  - azurearm_network: Ensure route table exists

    '''
    ret = {
        'name': name,
        'result': False,
        'comment': '',
        'changes': {}
    }

    if not isinstance(connection_auth, dict):
        ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
        return ret

    route = __salt__['azurearm_network.route_get'](
        name,
        route_table,
        resource_group,
        azurearm_log_level='info',
        **connection_auth
    )

    if 'error' not in route:
        if address_prefix != route.get('address_prefix'):
            ret['changes']['address_prefix'] = {
                'old': route.get('address_prefix'),
                'new': address_prefix
            }

        if next_hop_type.lower() != route.get('next_hop_type', '').lower():
            ret['changes']['next_hop_type'] = {
                'old': route.get('next_hop_type'),
                'new': next_hop_type
            }

        if next_hop_type.lower() == 'virtualappliance' and next_hop_ip_address != route.get('next_hop_ip_address'):
            ret['changes']['next_hop_ip_address'] = {
                'old': route.get('next_hop_ip_address'),
                'new': next_hop_ip_address
            }

        if not ret['changes']:
            ret['result'] = True
            ret['comment'] = 'Route {0} is already present.'.format(name)
            return ret

        if __opts__['test']:
            ret['result'] = None
            ret['comment'] = 'Route {0} would be updated.'.format(name)
            return ret

    else:
        ret['changes'] = {
            'old': {},
            'new': {
                'name': name,
                'address_prefix': address_prefix,
                'next_hop_type': next_hop_type,
                'next_hop_ip_address': next_hop_ip_address
            }
        }

    if __opts__['test']:
        ret['comment'] = 'Route {0} would be created.'.format(name)
        ret['result'] = None
        return ret

    route_kwargs = kwargs.copy()
    route_kwargs.update(connection_auth)

    route = __salt__['azurearm_network.route_create_or_update'](
        name=name,
        route_table=route_table,
        resource_group=resource_group,
        address_prefix=address_prefix,
        next_hop_type=next_hop_type,
        next_hop_ip_address=next_hop_ip_address,
        **route_kwargs
    )

    if 'error' not in route:
        ret['result'] = True
        ret['comment'] = 'Route {0} has been created.'.format(name)
        return ret

    ret['comment'] = 'Failed to create route {0}! ({1})'.format(name, route.get('error'))
    return ret

Response: Ensure a route exists within a route table.


Instruction:
Write a Python 3 script for
ensuring a route table is absent in the resource group.

Response:
def route_absent(name, route_table, resource_group, connection_auth=None):
    '''
    .. versionadded:: 2019.2.0

    Ensure a route table does not exist in the resource group.

    :param name:
        Name of the route table.

    :param route_table:
        The name of the existing route table containing the route.

    :param resource_group:
        The resource group assigned to the route table.

    :param connection_auth:
        A dict with subscription and authentication parameters to be used in connecting to the
        Azure Resource Manager API.
    '''
    ret = {
        'name': name,
        'result': False,
        'comment': '',
        'changes': {}
    }

    if not isinstance(connection_auth, dict):
        ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
        return ret

    route = __salt__['azurearm_network.route_get'](
        name,
        route_table,
        resource_group,
        azurearm_log_level='info',
        **connection_auth
    )

    if 'error' in route:
        ret['result'] = True
        ret['comment'] = 'Route {0} was not found.'.format(name)
        return ret

    elif __opts__['test']:
        ret['comment'] = 'Route {0} would be deleted.'.format(name)
        ret['result'] = None
        ret['changes'] = {
            'old': route,
            'new': {},
        }
        return ret

    deleted = __salt__['azurearm_network.route_delete'](name, route_table, resource_group, **connection_auth)

    if deleted:
        ret['result'] = True
        ret['comment'] = 'Route {0} has been deleted.'.format(name)
        ret['changes'] = {
            'old': route,
            'new': {}
        }
        return ret

    ret['comment'] = 'Failed to delete route {0}!'.format(name)
    return ret


Instruction:
Can you generate the documentation for the following Python 3 function
def is_jid(jid):
    '''
    Returns True if the passed in value is a job id
    '''
    if not isinstance(jid, six.string_types):
        return False
    if len(jid) != 20 and (len(jid) <= 21 or jid[20] != '_'):
        return False
    try:
        int(jid[:20])
        return True
    except ValueError:
        return False

Response:
Returns True if the passed in value is a job id
    Returns False otherwise


Instruction:
Here you have a function in Python 3, explain what it does
def jid_to_time(jid):
    '''
    Convert a salt job id into the time when the job was invoked
    '''
    jid = six.text_type(jid)
    if len(jid) != 20 and (len(jid) <= 21 or jid[20] != '_'):
        return ''
    year = jid[:4]
    month = jid[4:6]
    day = jid[6:8]
    hour = jid[8:10]
    minute = jid[10:12]
    second = jid[12:14]
    micro = jid[14:20]

    ret = '{0}, {1} {2} {3}:{4}:{5}.{6}'.format(year,
                                                months[int(month)],
                                                day,
                                                hour,
                                                minute,
                                                second,
                                                micro)
    return ret

Response: Convert a salt job id into a time when the job was invoked


Instruction:
Create a Python 3 function for
formatting the job instance correctly

Response:
def format_job_instance(job):
    '''
    Format the job instance correctly
    '''
    ret = {'Function': job.get('fun', 'unknown-function'),
           'Arguments': list(job.get('arg', [])),
           # unlikely but safeguard from invalid returns
           'Target': job.get('tgt', 'unknown-target'),
           'Target-type': job.get('tgt_type', 'list'),
           'User': job.get('user', 'root')}

    if 'metadata' in job:
        ret['Metadata'] = job.get('metadata', {})
    else:
        if 'kwargs' in job:
            if 'metadata' in job['kwargs']:
                ret['Metadata'] = job['kwargs'].get('metadata', {})
    return ret


Instruction:
How would you implement a function in Python 3 that
formats the jid correctly

Response:
def format_jid_instance(jid, job):
    '''
    Format the jid correctly
    '''
    ret = format_job_instance(job)
    ret.update({'StartTime': jid_to_time(jid)})
    return ret


Instruction:
Can you generate the documentation for the following Python 3 function
def format_jid_instance_ext(jid, job):
    '''
    Format the jid correctly with jid included
    '''
    ret = format_job_instance(job)
    ret.update({
        'JID': jid,
        'StartTime': jid_to_time(jid)})
    return ret

Response: Format the jid correctly with jid included


Instruction:
Can you generate the documentation for the following Python 3 function
def jid_dir(jid, job_dir=None, hash_type='sha256'):
    '''
    Return the jid_dir for the given job id
    '''
    if not isinstance(jid, six.string_types):
        jid = six.text_type(jid)
    jhash = getattr(hashlib, hash_type)(
        salt.utils.stringutils.to_bytes(jid)).hexdigest()

    parts = []
    if job_dir is not None:
        parts.append(job_dir)
    parts.extend([jhash[:2], jhash[2:]])
    return os.path.join(*parts)

Response: Return the jid_dir for the given job id


Instruction:
Can you create a Python 3 function that
changes the system runlevel on sysV compatible systems CLI Example: .. code-block:: bash salt '*' system.init 3

Response:
def init(runlevel):
    '''
    Change the system runlevel on sysV compatible systems

    CLI Example:

    .. code-block:: bash

        salt '*' system.init 3
    '''
    cmd = ['init', '{0}'.format(runlevel)]
    ret = __salt__['cmd.run'](cmd, python_shell=False)
    return ret


Instruction:
Make a summary of the following Python 3 code
def reboot(at_time=None):
    '''
    Reboot the system

    at_time
        The wait time in minutes before the system will be rebooted.

    CLI Example:

    .. code-block:: bash

        salt '*' system.reboot
    '''
    cmd = ['shutdown', '-r', ('{0}'.format(at_time) if at_time else 'now')]
    ret = __salt__['cmd.run'](cmd, python_shell=False)
    return ret

Response:
Reboot the system
    at_time


Instruction:
Make a summary of the following Python 3 code
def shutdown(at_time=None):
    '''
    Shutdown a running system

    at_time
        The wait time in minutes before the system will be shutdown.

    CLI Example:

    .. code-block:: bash

        salt '*' system.shutdown 5
    '''
    cmd = ['shutdown', '-h', ('{0}'.format(at_time) if at_time else 'now')]
    ret = __salt__['cmd.run'](cmd, python_shell=False)
    return ret

Response: Shut down a running system


Instruction:
How would you explain what the following Python 3 function does
def _date_bin_set_datetime(new_date):
    '''
    set the system date/time using the date command

    Note using a strictly posix-compliant date binary we can only set the date
    up to the minute.
    '''
    cmd = ['date']

    # if there is a timezone in the datetime object use that offset
    # This will modify the new_date to be the equivalent time in UTC
    if new_date.utcoffset() is not None:
        new_date = new_date - new_date.utcoffset()
        new_date = new_date.replace(tzinfo=_FixedOffset(0))
        cmd.append('-u')

    # the date can be set in the following format:
    # Note that setting the time with a resolution of seconds
    # is not a posix feature, so we will attempt it and if it
    # fails we will try again only using posix features

    # date MMDDhhmm[[CC]YY[.ss]]
    non_posix = ("{1:02}{2:02}{3:02}{4:02}{0:04}.{5:02}"
                 .format(*new_date.timetuple()))
    non_posix_cmd = cmd + [non_posix]

    ret_non_posix = __salt__['cmd.run_all'](non_posix_cmd, python_shell=False)
    if ret_non_posix['retcode'] != 0:
        # We will now try the command again following posix
        # date MMDDhhmm[[CC]YY]
        posix = " {1:02}{2:02}{3:02}{4:02}{0:04}".format(*new_date.timetuple())
        posix_cmd = cmd + [posix]

        ret_posix = __salt__['cmd.run_all'](posix_cmd, python_shell=False)
        if ret_posix['retcode'] != 0:
            # if both fail it's likely an invalid date string
            # so we will give back the error from the first attempt
            msg = 'date failed: {0}'.format(ret_non_posix['stderr'])
            raise CommandExecutionError(msg)
    return True

Response: Set the date of the system using the date command


Instruction:
Write a Python 3 function that can
return True if the system has a hardware clock capable of being set from software.

Response:
def has_settable_hwclock():
    '''
    Returns True if the system has a hardware clock capable of being
    set from software.

    CLI Example:

    salt '*' system.has_settable_hwclock
    '''
    if salt.utils.path.which_bin(['hwclock']) is not None:
        res = __salt__['cmd.run_all'](
            ['hwclock', '--test', '--systohc'], python_shell=False,
            output_loglevel='quiet', ignore_retcode=True
        )
        return res['retcode'] == 0
    return False


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _swclock_to_hwclock():
    '''
    Set hardware clock to value of software clock.
    '''
    res = __salt__['cmd.run_all'](['hwclock', '--systohc'], python_shell=False)
    if res['retcode'] != 0:
        msg = 'hwclock failed to set hardware clock from software clock: {0}'.format(res['stderr'])
        raise CommandExecutionError(msg)
    return True

Response: Set hardware clock to value of software clock.


Instruction:
Make a summary of the following Python 3 code
def _offset_to_min(utc_offset):
    '''
    Helper function that converts the utc offset string into number of minutes
    offset. Input is in form "[+-]?HHMM". Example valid inputs are "+0500"
    "-0300" and "0800". These would return -300, 180, 480 respectively.
    '''
    match = re.match(r"^([+-])?(\d\d)(\d\d)$", utc_offset)
    if not match:
        raise SaltInvocationError("Invalid UTC offset")

    sign = -1 if match.group(1) == '-' else 1
    hours_offset = int(match.group(2))
    minutes_offset = int(match.group(3))
    total_offset = sign * (hours_offset * 60 + minutes_offset)
    return total_offset

Response:
Helper function that converts the utc offset string into number of minutes
    offset. Input is in form HHMM - 0500 - 350 - 480.


Instruction:
Can you implement a function in Python 3 that
returns the current time adjusted using the input timezone offset.

Response:
def _get_offset_time(utc_offset):
    '''
    Will return the current time adjusted using the input timezone offset.

    :rtype datetime:
    '''
    if utc_offset is not None:
        minutes = _offset_to_min(utc_offset)
        offset = timedelta(minutes=minutes)
        offset_time = datetime.utcnow() + offset
        offset_time = offset_time.replace(tzinfo=_FixedOffset(minutes))
    else:
        offset_time = datetime.now()
    return offset_time


Instruction:
Write a Python 3 function that can
set the system time for the current node.

Response:
def set_system_time(newtime, utc_offset=None):
    '''
    Set the system time.

    :param str newtime:
        The time to set. Can be any of the following formats.
        - HH:MM:SS AM/PM
        - HH:MM AM/PM
        - HH:MM:SS (24 hour)
        - HH:MM (24 hour)

        Note that the salt command line parser parses the date/time
        before we obtain the argument (preventing us from doing utc)
        Therefore the argument must be passed in as a string.
        Meaning you may have to quote the text twice from the command line.

    :param str utc_offset: The utc offset in 4 digit (+0600) format with an
        optional sign (+/-).  Will default to None which will use the local
        timezone. To set the time based off of UTC use "'+0000'". Note: if
        being passed through the command line will need to be quoted twice to
        allow negative offsets.
    :return: Returns True if successful. Otherwise False.
    :rtype: bool

    CLI Example:

    .. code-block:: bash

        salt '*' system.set_system_time "'11:20'"
    '''
    fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M']
    dt_obj = _try_parse_datetime(newtime, fmts)
    if dt_obj is None:
        return False

    return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute,
                                seconds=dt_obj.second, utc_offset=utc_offset)


Instruction:
Write a Python 3 function that can
set the system date and time for the given set of values.

Response:
def set_system_date_time(years=None,
                         months=None,
                         days=None,
                         hours=None,
                         minutes=None,
                         seconds=None,
                         utc_offset=None):
    '''
    Set the system date and time. Each argument is an element of the date, but
    not required. If an element is not passed, the current system value for
    that element will be used. For example, if you don't pass the year, the
    current system year will be used. (Used by set_system_date and
    set_system_time)

    Updates hardware clock, if present, in addition to software
    (kernel) clock.

    :param int years: Years digit, ie: 2015
    :param int months: Months digit: 1 - 12
    :param int days: Days digit: 1 - 31
    :param int hours: Hours digit: 0 - 23
    :param int minutes: Minutes digit: 0 - 59
    :param int seconds: Seconds digit: 0 - 59
    :param str utc_offset: The utc offset in 4 digit (+0600) format with an
        optional sign (+/-).  Will default to None which will use the local
        timezone. To set the time based off of UTC use "'+0000'". Note: if
        being passed through the command line will need to be quoted twice to
        allow negative offsets.
    :return: True if successful. Otherwise False.
    :rtype: bool

    CLI Example:

    .. code-block:: bash

        salt '*' system.set_system_date_time 2015 5 12 11 37 53 "'-0500'"
    '''
    # Get the current date/time
    date_time = _get_offset_time(utc_offset)

    # Check for passed values. If not passed, use current values
    if years is None:
        years = date_time.year
    if months is None:
        months = date_time.month
    if days is None:
        days = date_time.day
    if hours is None:
        hours = date_time.hour
    if minutes is None:
        minutes = date_time.minute
    if seconds is None:
        seconds = date_time.second

    try:
        new_datetime = datetime(years, months, days, hours, minutes, seconds, 0,
                                date_time.tzinfo)
    except ValueError as err:
        raise SaltInvocationError(err.message)

    if not _date_bin_set_datetime(new_datetime):
        return False

    if has_settable_hwclock():
        # Now that we've successfully set the software clock, we should
        # update hardware clock for time to persist though reboot.
        return _swclock_to_hwclock()

    return True


Instruction:
Here you have a function in Python 3, explain what it does
def get_computer_desc():
    '''
    Get PRETTY_HOSTNAME value stored in /etc/machine-info
    If this file doesn't exist or the variable doesn't exist
    return False.

    :return: Value of PRETTY_HOSTNAME if this does not exist False.
    :rtype: str

    CLI Example:

    .. code-block:: bash

        salt '*' system.get_computer_desc
    '''
    hostname_cmd = salt.utils.path.which('hostnamectl')
    if hostname_cmd:
        desc = __salt__['cmd.run'](
            [hostname_cmd, 'status', '--pretty'],
            python_shell=False
        )
    else:
        desc = None
        pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$')
        try:
            with salt.utils.files.fopen('/etc/machine-info', 'r') as mach_info:
                for line in mach_info.readlines():
                    line = salt.utils.stringutils.to_unicode(line)
                    match = pattern.match(line)
                    if match:
                        # get rid of whitespace then strip off quotes
                        desc = _strip_quotes(match.group(1).strip())
                        # no break so we get the last occurance
        except IOError:
            pass

        if desc is None:
            return False

    return desc.replace(r'\"', r'"').replace(r'\n', '\n').replace(r'\t', '\t')

Response: Return the value stored in the NIC_NAME file


Instruction:
Create a Python 3 function for
setting the computer description in the neccesary way.

Response:
def set_computer_desc(desc):
    '''
    Set PRETTY_HOSTNAME value stored in /etc/machine-info
    This will create the file if it does not exist. If
    it is unable to create or modify this file returns False.

    :param str desc: The computer description
    :return: False on failure. True if successful.

    CLI Example:

    .. code-block:: bash

        salt '*' system.set_computer_desc "Michael's laptop"
    '''
    desc = salt.utils.stringutils.to_unicode(
        desc).replace('"', r'\"').replace('\n', r'\n').replace('\t', r'\t')

    hostname_cmd = salt.utils.path.which('hostnamectl')
    if hostname_cmd:
        result = __salt__['cmd.retcode'](
            [hostname_cmd, 'set-hostname', '--pretty', desc],
            python_shell=False
        )
        return True if result == 0 else False

    if not os.path.isfile('/etc/machine-info'):
        with salt.utils.files.fopen('/etc/machine-info', 'w'):
            pass

    pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$')
    new_line = salt.utils.stringutils.to_str('PRETTY_HOSTNAME="{0}"'.format(desc))
    try:
        with salt.utils.files.fopen('/etc/machine-info', 'r+') as mach_info:
            lines = mach_info.readlines()
            for i, line in enumerate(lines):
                if pattern.match(salt.utils.stringutils.to_unicode(line)):
                    lines[i] = new_line
                    break
            else:
                # PRETTY_HOSTNAME line was not found, add it to the end
                lines.append(new_line)
            # time to write our changes to the file
            mach_info.seek(0, 0)
            mach_info.truncate()
            mach_info.writelines(lines)
            return True
    except IOError:
        return False


Instruction:
How would you explain what the following Python 3 function does
def handle_stream(self, stream):
        '''
        Override this to handle the streams as they arrive

        :param IOStream stream: An IOStream for processing

        See https://tornado.readthedocs.io/en/latest/iostream.html#tornado.iostream.IOStream
        for additional details.
        '''
        @tornado.gen.coroutine
        def _null(msg):
            raise tornado.gen.Return(None)

        def write_callback(stream, header):
            if header.get('mid'):
                @tornado.gen.coroutine
                def return_message(msg):
                    pack = salt.transport.frame.frame_msg_ipc(
                        msg,
                        header={'mid': header['mid']},
                        raw_body=True,
                    )
                    yield stream.write(pack)
                return return_message
            else:
                return _null
        if six.PY2:
            encoding = None
        else:
            encoding = 'utf-8'
        unpacker = msgpack.Unpacker(encoding=encoding)
        while not stream.closed():
            try:
                wire_bytes = yield stream.read_bytes(4096, partial=True)
                unpacker.feed(wire_bytes)
                for framed_msg in unpacker:
                    body = framed_msg['body']
                    self.io_loop.spawn_callback(self.payload_handler, body, write_callback(stream, framed_msg['head']))
            except tornado.iostream.StreamClosedError:
                log.trace('Client disconnected from IPC %s', self.socket_path)
                break
            except socket.error as exc:
                # On occasion an exception will occur with
                # an error code of 0, it's a spurious exception.
                if exc.errno == 0:
                    log.trace('Exception occured with error number 0, '
                              'spurious exception: %s', exc)
                else:
                    log.error('Exception occurred while '
                              'handling stream: %s', exc)
            except Exception as exc:
                log.error('Exception occurred while '
                          'handling stream: %s', exc)

Response: Handle the given stream and yield the messages that are available to the user.


Instruction:
Write a Python 3 function that can
close the underlying socket and filehandles.

Response:
def close(self):
        '''
        Routines to handle any cleanup before the instance shuts down.
        Sockets and filehandles should be closed explicitly, to prevent
        leaks.
        '''
        if self._closing:
            return
        self._closing = True
        if hasattr(self.sock, 'close'):
            self.sock.close()


Instruction:
Can you generate the documentation for the following Python 3 function
def connect(self, callback=None, timeout=None):
        '''
        Connect to the IPC socket
        '''
        if hasattr(self, '_connecting_future') and not self._connecting_future.done():  # pylint: disable=E0203
            future = self._connecting_future  # pylint: disable=E0203
        else:
            if hasattr(self, '_connecting_future'):
                # read previous future result to prevent the "unhandled future exception" error
                self._connecting_future.exception()  # pylint: disable=E0203
            future = tornado.concurrent.Future()
            self._connecting_future = future
            self._connect(timeout=timeout)

        if callback is not None:
            def handle_future(future):
                response = future.result()
                self.io_loop.add_callback(callback, response)
            future.add_done_callback(handle_future)

        return future

Response: Connect to the IPC socket and return a future that will be returned when the socket is ready.


Instruction:
Given the following Python 3 function, write the documentation
def _connect(self, timeout=None):
        '''
        Connect to a running IPCServer
        '''
        if isinstance(self.socket_path, int):
            sock_type = socket.AF_INET
            sock_addr = ('127.0.0.1', self.socket_path)
        else:
            sock_type = socket.AF_UNIX
            sock_addr = self.socket_path

        self.stream = None
        if timeout is not None:
            timeout_at = time.time() + timeout

        while True:
            if self._closing:
                break

            if self.stream is None:
                with salt.utils.asynchronous.current_ioloop(self.io_loop):
                    self.stream = IOStream(
                        socket.socket(sock_type, socket.SOCK_STREAM),
                    )

            try:
                log.trace('IPCClient: Connecting to socket: %s', self.socket_path)
                yield self.stream.connect(sock_addr)
                self._connecting_future.set_result(True)
                break
            except Exception as e:
                if self.stream.closed():
                    self.stream = None

                if timeout is None or time.time() > timeout_at:
                    if self.stream is not None:
                        self.stream.close()
                        self.stream = None
                    self._connecting_future.set_exception(e)
                    break

                yield tornado.gen.sleep(1)

Response: Connect to a running IPCServer and return a tornado. Future that fires when the connection is complete.


Instruction:
Can you tell what is the following Python 3 function doing
def close(self):
        '''
        Routines to handle any cleanup before the instance shuts down.
        Sockets and filehandles should be closed explicitly, to prevent
        leaks.
        '''
        if self._closing:
            return

        if self._refcount > 1:
            # Decrease refcount
            with self._refcount_lock:
                self._refcount -= 1
            log.debug(
                'This is not the last %s instance. Not closing yet.',
                self.__class__.__name__
            )
            return

        self._closing = True

        log.debug('Closing %s instance', self.__class__.__name__)

        if self.stream is not None and not self.stream.closed():
            self.stream.close()

        # Remove the entry from the instance map so
        # that a closed entry may not be reused.
        # This forces this operation even if the reference
        # count of the entry has not yet gone to zero.
        if self.io_loop in self.__class__.instance_map:
            loop_instance_map = self.__class__.instance_map[self.io_loop]
            if self._instance_key in loop_instance_map:
                del loop_instance_map[self._instance_key]
            if not loop_instance_map:
                del self.__class__.instance_map[self.io_loop]

Response: Closes the current instance.


Instruction:
Can you write a function in Python 3 where it
sends a message to an IPC socket.

Response:
def send(self, msg, timeout=None, tries=None):
        '''
        Send a message to an IPC socket

        If the socket is not currently connected, a connection will be established.

        :param dict msg: The message to be sent
        :param int timeout: Timeout when sending message (Currently unimplemented)
        '''
        if not self.connected():
            yield self.connect()
        pack = salt.transport.frame.frame_msg_ipc(msg, raw_body=True)
        yield self.stream.write(pack)