Instruction:
Can you tell what is the following Python 3 function doing
def search(self, id_perm):

        if not is_valid_int_param(id_perm):
            raise InvalidParameterError(
                u'The identifier of Administrative Permission is invalid or was not informed.')

        url = 'aperms/get/' + str(id_perm) + '/'

        code, xml = self.submit(None, 'GET', url)

        return self.response(code, xml)

Response: Search Administrative Permission from by the identifier.


Instruction:
Can you tell what is the following Python 3 function doing
def inserir(self, id_permission, read, write, id_group):
        perms_map = dict()
        perms_map['id_permission'] = id_permission
        perms_map['read'] = read
        perms_map['write'] = write
        perms_map['id_group'] = id_group

        code, xml = self.submit(
            {'administrative_permission': perms_map}, 'POST', 'aperms/')

        return self.response(code, xml)

Response: Inserts a new Administrative Permission and returns its identifier.


Instruction:
Can you write a function in Python 3 where it
changes Administrative Permission from by the identifier.

Response:
def alterar(self, id_perm, id_permission, read, write, id_group):
        """Change Administrative Permission from by the identifier.

        :param id_perm: Identifier of the Administrative Permission. Integer value and greater than zero.
        :param id_permission: Identifier of the Permission. Integer value and greater than zero.
        :param read: Read. 0 or 1
        :param write: Write. 0 or 1
        :param id_group: Identifier of the Group of User. Integer value and greater than zero.

        :return: None

        :raise InvalidParameterError: The identifier of Administrative Permission, identifier of Permission, identifier of Group of User, read or  write is null and invalid.
        :raise ValorIndicacaoPermissaoInvalidoError: The value of read or write is null and invalid.
        :raise PermissaoAdministrativaNaoExisteError: Administrative Permission not registered.
        :raise GrupoUsuarioNaoExisteError: Group of User not registered.
        :raise DataBaseError: Networkapi failed to access the database.
        :raise XMLError: Networkapi failed to generate the XML response.
        """
        if not is_valid_int_param(id_perm):
            raise InvalidParameterError(
                u'The identifier of Administrative Permission is invalid or was not informed.')

        url = 'aperms/' + str(id_perm) + '/'

        perms_map = dict()
        perms_map['id_perm'] = id_perm
        perms_map['id_permission'] = id_permission
        perms_map['read'] = read
        perms_map['write'] = write
        perms_map['id_group'] = id_group

        code, xml = self.submit(
            {'administrative_permission': perms_map}, 'PUT', url)

        return self.response(code, xml)


Instruction:
Can you create a Python 3 function that
removes Administrative Permission from by the identifier.

Response:
def remover(self, id_perms):
        """Remove Administrative Permission from by the identifier.

        :param id_perms: Identifier of the Administrative Permission. Integer value and greater than zero.

        :return: None

        :raise InvalidParameterError: The identifier of Administrative Permission is null and invalid.
        :raise PermissaoAdministrativaNaoExisteError: Administrative Permission not registered.
        :raise DataBaseError: Networkapi failed to access the database.
        :raise XMLError: Networkapi failed to generate the XML response.
        """
        if not is_valid_int_param(id_perms):
            raise InvalidParameterError(
                u'The identifier of Administrative Permission is invalid or was not informed.')

        url = 'aperms/' + str(id_perms) + '/'

        code, xml = self.submit(None, 'DELETE', url)

        return self.response(code, xml)


Instruction:
Implement a Python 3 function for
getting an instance of ambiente services facade.

Response:
def create_ambiente(self):
        """Get an instance of ambiente services facade."""
        return Ambiente(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Can you generate the documentation for the following Python 3 function
def create_ambiente_logico(self):
        return AmbienteLogico(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of ambiente_logico services facade.


Instruction:
Can you implement a function in Python 3 that
gets an instance of Api Environment Vip services facade.

Response:
def create_api_environment_vip(self):
        """Get an instance of Api Environment Vip services facade."""
        return ApiEnvironmentVip(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Create a Python 3 function to
get an instance of Api Environment services facade.

Response:
def create_api_environment(self):
        """Get an instance of Api Environment services facade."""
        return ApiEnvironment(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def create_api_equipment(self):
        return ApiEquipment(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of Api Equipment services facade.


Instruction:
Explain what the following Python 3 code does
def create_api_v4_equipment(self):
        return ApiV4Equipment(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of Api V4 Equipment services facade.


Instruction:
Can you write a function in Python 3 where it
gets an instance of Api V4 As services facade.

Response:
def create_api_v4_as(self):
        """Get an instance of Api As services facade."""
        return ApiV4As(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Can you generate the documentation for the following Python 3 function
def create_api_v4_virtual_interface(self):
        return ApiV4VirtualInterface(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of Api Virtual Interface services facade.


Instruction:
How would you code a function in Python 3 to
get an instance of Api Neighbor services facade.

Response:
def create_api_v4_neighbor(self):
        """Get an instance of Api Neighbor services facade."""
        return ApiV4Neighbor(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Create a Python 3 function for
getting an instance of Api Interface Request services facade.

Response:
def create_api_interface_request(self):
        """Get an instance of Api Vip Requests services facade."""

        return ApiInterfaceRequest(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Given the following Python 3 function, write the documentation
def create_api_ipv4(self):

        return ApiIPv4(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of Api IPv4 services facade.


Instruction:
Implement a function in Python 3 to
get an instance of Api IPv6 services facade.

Response:
def create_api_ipv6(self):
        """Get an instance of Api IPv6 services facade."""

        return ApiIPv6(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Given the following Python 3 function, write the documentation
def create_api_v4_ipv4(self):

        return ApiV4IPv4(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of Api V4 IPv4 services facade.


Instruction:
Implement a Python 3 function for
getting an instance of Api V4 IPv6 services facade.

Response:
def create_api_v4_ipv6(self):
        """Get an instance of Api V4 IPv6 services facade."""

        return ApiV4IPv6(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Here you have a function in Python 3, explain what it does
def create_api_network_ipv4(self):

        return ApiNetworkIPv4(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of Api Networkv4 services facade.


Instruction:
Write a Python 3 function that can
get an instance of Api Networkv6 services facade.

Response:
def create_api_network_ipv6(self):
        """Get an instance of Api Networkv6 services facade."""

        return ApiNetworkIPv6(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Here you have a function in Python 3, explain what it does
def create_api_option_vip(self):
        return ApiOptionVip(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of Api Option Vip services facade.


Instruction:
Write a Python 3 script to
get an instance of Api Pool services facade.

Response:
def create_api_pool(self):
        """Get an instance of Api Pool services facade."""
        return ApiPool(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Here you have a function in Python 3, explain what it does
def create_api_pool_deploy(self):
        return ApiPoolDeploy(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of Api Pool Deploy services facade.


Instruction:
Can you implement a function in Python 3 that
gets an instance of Api Rack Variables services facade.

Response:
def create_apirack(self):
        """Get an instance of Api Rack Variables services facade."""
        return ApiRack(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


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

        return ApiVipRequest(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap,
            self.log_level)

Response: Create an instance of Api Vip Requests services facade.


Instruction:
Explain what the following Python 3 code does
def create_api_object_type(self):

        return ApiObjectType(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of Api Object Type services facade.


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

        return ApiObjectGroupPermission(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of Api Object Group Permission services facade.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def create_api_object_group_permission_general(self):

        return ApiObjectGroupPermissionGeneral(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of Api Object Group Permission General services facade.


Instruction:
Can you create a Python 3 function that
gets an instance of Api Vlan services facade.

Response:
def create_api_vlan(self):
        """Get an instance of Api Vlan services facade."""
        return ApiVlan(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Write a Python 3 function that can
get an instance of Api Vrf services facade.

Response:
def create_api_vrf(self):
        """Get an instance of Api Vrf services facade."""
        return ApiVrf(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
How would you implement a function in Python 3 that
gets an instance of block rule services facade.

Response:
def create_rule(self):
        """Get an instance of block rule services facade."""
        return BlockRule(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Implement a Python 3 function for
getting an instance of direito_grupo_equipamento services facade.

Response:
def create_direito_grupo_equipamento(self):
        """Get an instance of direito_grupo_equipamento services facade."""
        return DireitoGrupoEquipamento(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Write a Python 3 script to
get an instance of divisao_dc services facade.

Response:
def create_divisao_dc(self):
        """Get an instance of divisao_dc services facade."""
        return DivisaoDc(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Create a Python 3 function to
get an instance of environment_vip services facade.

Response:
def create_environment_vip(self):
        """Get an instance of environment_vip services facade."""
        return EnvironmentVIP(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Can you generate the documentation for the following Python 3 function
def create_equipamento(self):
        return Equipamento(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of equipamento services facade.


Instruction:
Given the following Python 3 function, write the documentation
def create_equipamento_acesso(self):
        return EquipamentoAcesso(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of equipamento_acesso services facade.


Instruction:
How would you implement a function in Python 3 that
gets an instance of equipamento_ambiente services facade.

Response:
def create_equipamento_ambiente(self):
        """Get an instance of equipamento_ambiente services facade."""
        return EquipamentoAmbiente(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Given the following Python 3 function, write the documentation
def create_equipamento_roteiro(self):
        return EquipamentoRoteiro(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of equipamento_roteiro services facade.


Instruction:
Make a summary of the following Python 3 code
def create_log(self):
        return EventLog(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of log services facade.


Instruction:
Explain what the following Python 3 code does
def create_filter(self):
        return Filter(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of filter services facade.


Instruction:
Can you create a Python 3 function that
gets an instance of grupo_equipamento services facade.

Response:
def create_grupo_equipamento(self):
        """Get an instance of grupo_equipamento services facade."""
        return GrupoEquipamento(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Create a Python 3 function to
get an instance of grupo_l3 services facade.

Response:
def create_grupo_l3(self):
        """Get an instance of grupo_l3 services facade."""
        return GrupoL3(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
How would you implement a function in Python 3 that
gets an instance of grupo_usuario services facade.

Response:
def create_grupo_usuario(self):
        """Get an instance of grupo_usuario services facade."""
        return GrupoUsuario(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def create_grupo_virtual(self):
        return GrupoVirtual(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of grupo_virtual services facade.


Instruction:
How would you explain what the following Python 3 function does
def create_healthcheck(self):

        return Healthcheck(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of Healthcheck services facade.


Instruction:
How would you code a function in Python 3 to
get an instance of interface services facade.

Response:
def create_interface(self):
        """Get an instance of interface services facade."""
        return Interface(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Can you generate the documentation for the following Python 3 function
def create_ip(self):
        return Ip(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of ip services facade.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def create_marca(self):
        return Marca(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of marca services facade.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def create_modelo(self):
        return Modelo(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of modelo services facade.


Instruction:
How would you code a function in Python 3 to
get an instance of DHCPRelayIPv4 services facade.

Response:
def create_dhcprelay_ipv4(self):
        """Get an instance of DHCPRelayIPv4 services facade."""
        return DHCPRelayIPv4(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Write a Python 3 function for
getting an instance of DHCPRelayIPv6 services facade.

Response:
def create_dhcprelay_ipv6(self):
        """Get an instance of DHCPRelayIPv6 services facade."""
        return DHCPRelayIPv6(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Implement a Python 3 function for
getting an instance of vlan services facade.

Response:
def create_network(self):
        """Get an instance of vlan services facade."""
        return Network(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Write a Python 3 script for
getting an instance of option_pool services facade.

Response:
def create_option_pool(self):
        """Get an instance of option_pool services facade."""
        return OptionPool(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Here you have a function in Python 3, explain what it does
def create_option_vip(self):
        return OptionVIP(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of option_vip services facade.


Instruction:
Here you have a function in Python 3, explain what it does
def create_permissao_administrativa(self):
        return PermissaoAdministrativa(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of permissao_administrativa services facade.


Instruction:
Given the following Python 3 function, write the documentation
def create_permission(self):
        return Permission(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of permission services facade.


Instruction:
Create a Python 3 function to
get an instance of Poll services facade.

Response:
def create_pool(self):
        """Get an instance of Poll services facade."""

        return Pool(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Can you implement a function in Python 3 that
gets an instance of rack services facade.

Response:
def create_rack(self):
        """Get an instance of rack services facade."""
        return Rack(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Write a Python 3 function that can
get an instance of rackservers services facade.

Response:
def create_rackservers(self):
        """Get an instance of rackservers services facade."""
        return RackServers(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Here you have a function in Python 3, explain what it does
def create_roteiro(self):
        return Roteiro(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of roteiro services facade.


Instruction:
Explain what the following Python 3 code does
def create_system(self):
        return System(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of Api System Variables services facade.


Instruction:
Write a Python 3 script to
get an instance of tipo_acesso services facade.

Response:
def create_tipo_acesso(self):
        """Get an instance of tipo_acesso services facade."""
        return TipoAcesso(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Can you generate the documentation for the following Python 3 function
def create_tipo_equipamento(self):
        return TipoEquipamento(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of tipo_equipamento services facade.


Instruction:
Can you tell what is the following Python 3 function doing
def create_tipo_rede(self):
        return TipoRede(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of tipo_rede services facade.


Instruction:
How would you explain what the following Python 3 function does
def create_tipo_roteiro(self):
        return TipoRoteiro(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of tipo_roteiro services facade.


Instruction:
Given the following Python 3 function, write the documentation
def create_usuario(self):
        return Usuario(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of usuario services facade.


Instruction:
Write a Python 3 function that can
get an instance of usuario_grupo services facade.

Response:
def create_usuario_grupo(self):
        """Get an instance of usuario_grupo services facade."""
        return UsuarioGrupo(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
How would you explain what the following Python 3 function does
def create_vip(self):
        return Vip(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

Response: Get an instance of vip services facade.


Instruction:
Create a Python 3 function to
get an instance of vlan services facade.

Response:
def create_vlan(self):
        """Get an instance of vlan services facade."""
        return Vlan(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)


Instruction:
Write a Python 3 script to
deploy network in equipments and set column active = 1 in tables redeipv6

Response:
def deploy(self, id_networkv6):
        """Deploy network in equipments and set column 'active = 1' in tables redeipv6 ]

        :param id_networkv6: ID for NetworkIPv6

        :return: Equipments configuration output
        """

        data = dict()
        uri = 'api/networkv6/%s/equipments/' % id_networkv6

        return super(ApiNetworkIPv6, self).post(uri, data=data)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_by_id(self, id_networkv6):

        uri = 'api/networkv4/%s/' % id_networkv6
        return super(ApiNetworkIPv6, self).get(uri)

Response:
Get IPv6 network

        by ID


Instruction:
Write a Python 3 script for
listing networks in redeipv6

Response:
def list(self, environment_vip=None):
        """List networks redeipv6 ]

        :param environment_vip: environment vip to filter

        :return: IPv6 Networks
        """

        uri = 'api/networkv6/?'
        if environment_vip:
            uri += 'environment_vip=%s' % environment_vip

        return super(ApiNetworkIPv6, self).get(uri)


Instruction:
Explain what the following Python 3 code does
def undeploy(self, id_networkv6):

        uri = 'api/networkv6/%s/equipments/' % id_networkv6
        return super(ApiNetworkIPv6, self).delete(uri)

Response: Remove deployment of network in equipments and set active = 0 in tables redeipv6


Instruction:
Write a Python 3 script to
check available ipv6 in environment vip

Response:
def check_vip_ip(self, ip, environment_vip):
        """
        Check available ipv6 in environment vip
        """
        uri = 'api/ipv6/ip/%s/environment-vip/%s/' % (ip, environment_vip)

        return super(ApiNetworkIPv6, self).get(uri)


Instruction:
Given the following Python 3 function, write the documentation
def delete_ipv6(self, ipv6_id):
        uri = 'api/ipv6/%s/' % (ipv6_id)

        return super(ApiNetworkIPv6, self).delete(uri)

Response: Delete IPv6 related information


Instruction:
Explain what the following Python 3 code does
def search(self, **kwargs):

        return super(ApiNetworkIPv6, self).get(self.prepare_url('api/v3/networkv6/',
                                                                kwargs))

Response: Method to search ipv6 s based on extends search.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def update(self, networkipv6s):

        data = {'networks': networkipv6s}
        networkipv6s_ids = [str(networkipv6.get('id'))
                            for networkipv6 in networkipv6s]

        return super(ApiNetworkIPv6, self).put('api/v3/networkv6/%s/' %
                                               ';'.join(networkipv6s_ids), data)

Response: Method to update network - ipv6 s


Instruction:
Explain what the following Python 3 code does
def list_all(self):
        url = 'environmentvip/all/'

        code, xml = self.submit(None, 'GET', url)

        key = 'environment_vip'

        return get_list_map(self.response(code, xml, [key]), key)

Response: List all environment vips


Instruction:
Given the following Python 3 function, write the documentation
def list_all_available(self, id_vlan):

        url = 'environmentvip/search/' + str(id_vlan)

        code, xml = self.submit(None, 'GET', url)

        key = 'environment_vip'

        return get_list_map(self.response(code, xml, [key]), key)

Response: List all available environments vip


Instruction:
Given the following Python 3 function, write the documentation
def add(self, finalidade_txt, cliente_txt, ambiente_p44_txt, description):
        environmentvip_map = dict()
        environmentvip_map['finalidade_txt'] = finalidade_txt
        environmentvip_map['cliente_txt'] = cliente_txt
        environmentvip_map['ambiente_p44_txt'] = ambiente_p44_txt
        environmentvip_map['description'] = description

        code, xml = self.submit(
            {'environment_vip': environmentvip_map}, 'POST', 'environmentvip/')

        return self.response(code, xml)

Response: Inserts a new Environment VIP and returns its identifier.


Instruction:
How would you explain what the following Python 3 function does
def alter(
            self,
            id_environment_vip,
            finalidade_txt,
            cliente_txt,
            ambiente_p44_txt,
            description):
        """Change Environment VIP from by the identifier.

        :param id_environment_vip: Identifier of the Environment VIP. Integer value and greater than zero.
        :param finalidade_txt: Finality. String with a maximum of 50 characters and respect [a-zA-Z\_-]
        :param cliente_txt: ID  Client. String with a maximum of 50 characters and respect [a-zA-Z\_-]
        :param ambiente_p44_txt: Environment P44. String with a maximum of 50 characters and respect [a-zA-Z\_-]

        :return: None

        :raise InvalidParameterError: Environment VIP identifier is null and invalid.
        :raise InvalidParameterError: The value of finalidade_txt, cliente_txt or ambiente_p44_txt is invalid.
        :raise EnvironmentVipNotFoundError: Environment VIP not registered.
        :raise DataBaseError: Networkapi failed to access the database.
        :raise XMLError: Networkapi failed to generate the XML response.
        """

        if not is_valid_int_param(id_environment_vip):
            raise InvalidParameterError(
                u'The identifier of Environment VIP is invalid or was not informed.')

        environmentvip_map = dict()
        environmentvip_map['finalidade_txt'] = finalidade_txt
        environmentvip_map['cliente_txt'] = cliente_txt
        environmentvip_map['ambiente_p44_txt'] = ambiente_p44_txt
        environmentvip_map['description'] = description

        url = 'environmentvip/' + str(id_environment_vip) + '/'

        code, xml = self.submit(
            {'environment_vip': environmentvip_map}, 'PUT', url)

        return self.response(code, xml)

Response: Change the Environment VIP from by the identifier.


Instruction:
Create a Python 3 function for
removing Environment VIP from by the identifier.

Response:
def remove(self, id_environment_vip):
        """Remove Environment VIP from by the identifier.

        :param id_environment_vip: Identifier of the Environment VIP. Integer value and greater than zero.

        :return: None

        :raise InvalidParameterError: Environment VIP identifier is null and invalid.
        :raise EnvironmentVipNotFoundError: Environment VIP not registered.
        :raise EnvironmentVipError: There networkIPv4 or networkIPv6 associated with environment vip.
        :raise DataBaseError: Networkapi failed to access the database.
        :raise XMLError: Networkapi failed to generate the XML response.
        """

        if not is_valid_int_param(id_environment_vip):
            raise InvalidParameterError(
                u'The identifier of Environment VIP is invalid or was not informed.')

        url = 'environmentvip/' + str(id_environment_vip) + '/'

        code, xml = self.submit(None, 'DELETE', url)

        return self.response(code, xml)


Instruction:
Create a Python 3 function for
searching Environment VIP from by parameters.

Response:
def search(
            self,
            id_environment_vip=None,
            finalidade_txt=None,
            cliente_txt=None,
            ambiente_p44_txt=None):
        """Search Environment VIP from by parameters.

        Case the id parameter has been passed, the same it has priority over the other parameters.

        :param id_environment_vip: Identifier of the Environment VIP. Integer value and greater than zero.
        :param finalidade_txt: Finality. String with a maximum of 50 characters and respect [a-zA-Z\_-]
        :param cliente_txt: ID  Client. String with a maximum of 50 characters and respect [a-zA-Z\_-]
        :param ambiente_p44_txt: Environment P44. String with a maximum of 50 characters and respect [a-zA-Z\_-]

        :return: Following dictionary:

        ::

            {‘environment_vip’:
            {‘id’: < id >,
            ‘finalidade_txt’: < finalidade_txt >,
            ‘finalidade’: < finalidade >,
            ‘cliente_txt’: < cliente_txt >,
            ‘ambiente_p44_txt’: < ambiente_p44_txt >}}

        :raise InvalidParameterError: The value of id_environment_vip, finalidade_txt, cliente_txt or ambiente_p44_txt is invalid.
        :raise EnvironmentVipNotFoundError: Environment VIP not registered.
        :raise DataBaseError: Networkapi failed to access the database.
        :raise XMLError: Networkapi failed to generate the XML response.
        """
        environmentvip_map = dict()
        environmentvip_map['id_environment_vip'] = id_environment_vip
        environmentvip_map['finalidade_txt'] = finalidade_txt
        environmentvip_map['cliente_txt'] = cliente_txt
        environmentvip_map['ambiente_p44_txt'] = ambiente_p44_txt

        code, xml = self.submit(
            {'environment_vip': environmentvip_map}, 'POST', 'environmentvip/search/')

        return self.response(code, xml)


Instruction:
Given the following Python 3 function, write the documentation
def buscar_finalidade(self):

        url = 'environment-vip/get/finality'

        code, xml = self.submit(None, 'GET', url)

        return self.response(code, xml)

Response: Search finalidade_txt environment vip


Instruction:
Can you write a function in Python 3 where it
searches cliente_txt environment vip

Response:
def buscar_cliente_por_finalidade(self, finalidade_txt):
        """Search cliente_txt environment vip

        :return: Dictionary with the following structure:

        ::

            {‘cliente_txt’:
            ‘finalidade’: <'finalidade_txt'>,
            'cliente_txt: <'cliente_txt'>'}

        :raise InvalidParameterError: finalidade_txt is null and invalid.
        :raise DataBaseError: Networkapi failed to access the database.
        :raise XMLError: Networkapi failed to generate the XML response.
        """

        vip_map = dict()
        vip_map['finalidade_txt'] = finalidade_txt

        url = 'environment-vip/get/cliente_txt/'

        code, xml = self.submit({'vip': vip_map}, 'POST', url)

        return self.response(code, xml)


Instruction:
Can you tell what is the following Python 3 function doing
def buscar_ambientep44_por_finalidade_cliente(
            self,
            finalidade_txt,
            cliente_txt):
        """Search ambiente_p44_txt environment vip

        :return: Dictionary with the following structure:

        ::

            {‘ambiente_p44_txt’:
            'id':<'id_ambientevip'>,
            ‘finalidade’: <'finalidade_txt'>,
            'cliente_txt: <'cliente_txt'>',
            'ambiente_p44: <'ambiente_p44'>',}

        :raise InvalidParameterError: finalidade_txt and cliente_txt is null and invalid.
        :raise DataBaseError: Networkapi failed to access the database.
        :raise XMLError: Networkapi failed to generate the XML response.
        """

        vip_map = dict()
        vip_map['finalidade_txt'] = finalidade_txt
        vip_map['cliente_txt'] = cliente_txt

        url = 'environment-vip/get/ambiente_p44_txt/'

        code, xml = self.submit({'vip': vip_map}, 'POST', url)

        return self.response(code, xml)

Response: Search ambiente_p44_txt environment vip


Instruction:
Create a Python 3 function to
list finality, client or environment vip list. Param finality: finality of environment(optional) Param client: client of environment(optional) Param environmentp44: environmentp44(optional) Return finality list: when request has no finality and client. Return client list: when request has only finality. Return list environment vip: when request has finality and client. Return environment vip: when request has finality, client and environmentvip

Response:
def environmentvip_step(self, finality='', client='', environmentp44=''):
        """
        List finality, client or environment vip list.
        Param finality: finality of environment(optional)
        Param client: client of environment(optional)
        Param environmentp44: environmentp44(optional)
        Return finality list: when request has no finality and client.
        Return client list: when request has only finality.
        Return list environment vip: when request has finality and client.
        Return environment vip: when request has finality, client and environmentvip
        """

        uri = 'api/v3/environment-vip/step/?finality=%s&client=%s&environmentp44=%s' % (
            finality, client, environmentp44)

        return super(ApiEnvironmentVip, self).get(
            uri)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def search(self, **kwargs):

        return super(ApiEnvironmentVip, self).get(
            self.prepare_url('api/v3/environment-vip/', kwargs))

Response: Method to search environments vip based on extends search.


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

        data = {'environments_vip': environments}
        uri = 'api/v3/environment-vip/'
        return super(ApiEnvironmentVip, self).post(uri, data)

Response: Method to create environments vip


Instruction:
Here you have a function in Python 3, explain what it does
def get_ipv4(self, id_ip):

        if not is_valid_int_param(id_ip):
            raise InvalidParameterError(
                u'The IPv4 identifier is invalid or was not informed.')

        url = 'ip/get-ipv4/' + str(id_ip) + '/'

        code, xml = self.submit(None, 'GET', url)

        key = 'ipv4'
        return get_list_map(self.response(code, xml, ["equipamentos"]), key)

Response: Get IPv4 by id.


Instruction:
How would you code a function in Python 3 to
get IPv6 by id.

Response:
def get_ipv6(self, id_ip):
        """Get IPv6 by id.

        :param id_ip: ID of IPv6.

        :return: Dictionary with the following structure:

        ::

            {'ip': {'id': < id >,
            'networkipv6': < networkipv6 >,
            'block1': < block1 >,
            'block2': < block2 >,
            'block3': < block3 >,
            'block4': < block4 >,
            'block5': < block5 >,
            'block6': < block6 >,
            'block7': < block7 >,
            'block8': < block8 >,
            'description': < description >,
            'equipamentos': [ { all name of equipments related } ] , }}

        :raise IpNaoExisteError: IP is not registered.
        :raise InvalidParameterError: IP identifier is null or invalid.
        :raise DataBaseError: Networkapi failed to access the database.
        :raise XMLError: Networkapi failed to generate the XML response.
        """

        if not is_valid_int_param(id_ip):
            raise InvalidParameterError(
                u'The IPv6 identifier is invalid or was not informed.')

        url = 'ip/get-ipv6/' + str(id_ip) + '/'

        code, xml = self.submit(None, 'GET', url)

        key = 'ipv6'
        return get_list_map(self.response(code, xml, ["equipamentos"]), key)


Instruction:
How would you explain what the following Python 3 function does
def buscar_por_ip_ambiente(self, ip, id_environment):

        if not is_valid_int_param(id_environment):
            raise InvalidParameterError(
                u'Environment identifier is invalid or was not informed.')

        if not is_valid_ip(ip):
            raise InvalidParameterError(u'IP is invalid or was not informed.')

        url = 'ip/' + str(ip) + '/ambiente/' + str(id_environment) + '/'

        code, xml = self.submit(None, 'GET', url)

        return self.response(code, xml)

Response: Get an IP with an associated environment.


Instruction:
Given the following Python 3 function, write the documentation
def get_available_ip4(self, id_network):

        if not is_valid_int_param(id_network):
            raise InvalidParameterError(
                u'Network identifier is invalid or was not informed.')

        url = 'ip/availableip4/' + str(id_network) + "/"

        code, xml = self.submit(None, 'GET', url)

        return self.response(code, xml)

Response: Get a available IP in the network ipv4


Instruction:
How would you implement a function in Python 3 that
gets a available IP in the Equipment related Environment VIP and return the result as a dictionary.

Response:
def get_ip_by_equip_and_vip(self, equip_name, id_evip):
        """
        Get a available IP in the Equipment related Environment VIP

        :param equip_name: Equipment Name.
        :param id_evip: Vip environment identifier. Integer value and greater than zero.

        :return: Dictionary with the following structure:

        ::

            { 'ipv4': [ {'id': < id >, 'ip': < ip >, 'network': { 'id': < id >, 'network': < network >, 'mask': < mask >, }} ... ],
            'ipv6': [ {'id': < id >, 'ip': < ip >, 'network': { 'id': < id >, 'network': < network >, 'mask': < mask >, }} ... ] }

        :raise InvalidParameterError: Vip environment identifier or equipment name is none or invalid.
        :raise EquipamentoNotFoundError: Equipment not registered.
        :raise EnvironmentVipNotFoundError: Vip environment not registered.
        :raise UserNotAuthorizedError: User dont have permission to perform operation.
        :raise XMLError: Networkapi failed to generate the XML response.
        :raise DataBaseError: Networkapi failed to access the database.
        """

        if not is_valid_int_param(id_evip):
            raise InvalidParameterError(
                u'Vip environment is invalid or was not informed.')

        ip_map = dict()
        ip_map['equip_name'] = equip_name
        ip_map['id_evip'] = id_evip

        url = "ip/getbyequipandevip/"

        code, xml = self.submit({'ip_map': ip_map}, 'POST', url)

        return self.response(code, xml)


Instruction:
Can you tell what is the following Python 3 function doing
def get_ipv4_or_ipv6(self, ip):

        ip_map = dict()
        ip_map['ip'] = ip

        url = "ip/getbyoctblock/"

        code, xml = self.submit({'ip_map': ip_map}, 'POST', url)

        return self.response(code, xml)

Response: Get a Ipv4 or Ipv6 by ip


Instruction:
How would you implement a function in Python 3 that
gets a Ipv4 or Ipv6 for a vip

Response:
def check_vip_ip(self, ip, id_evip):
        """
        Get a Ipv4 or Ipv6 for Vip request

        :param ip: IPv4 or Ipv6. 'xxx.xxx.xxx.xxx or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx'

        :return: Dictionary with the following structure:

        ::

            {'ip': {'ip': < ip - octs for ipv4, blocks for ipv6 - >,
            'id': <id>,
            'network4 or network6'}}.

        :raise IpNaoExisteError: Ipv4 or Ipv6 not found.
        :raise EnvironemntVipNotFoundError: Vip environment not found.
        :raise IPNaoDisponivelError: Ip not available for Vip Environment.
        :raise UserNotAuthorizedError: User dont have permission to perform operation.
        :raise InvalidParameterError: Ip string or vip environment is none or invalid.
        :raise XMLError: Networkapi failed to generate the XML response.
        :raise DataBaseError: Networkapi failed to access the database.

        """

        ip_map = dict()
        ip_map['ip'] = ip
        ip_map['id_evip'] = id_evip

        url = "ip/checkvipip/"

        code, xml = self.submit({'ip_map': ip_map}, 'POST', url)

        return self.response(code, xml)


Instruction:
Can you implement a function in Python 3 that
gets a available IP in Network ipv6.

Response:
def get_available_ip6(self, id_network6):
        """
        Get a available IP in Network ipv6

        :param id_network6: Network ipv6 identifier. Integer value and greater than zero.

        :return: Dictionary with the following structure:

        ::

            {'ip6': {'ip6': < available_ip6 >}}

        :raise IpNotAvailableError: Network dont have available IP.
        :raise NetworkIPv4NotFoundError: Network was not found.
        :raise UserNotAuthorizedError: User dont have permission to get a available IP.
        :raise InvalidParameterError: Network ipv6 identifier is none or invalid.
        :raise XMLError: Networkapi failed to generate the XML response.
        :raise DataBaseError: Networkapi failed to access the database.

        """

        if not is_valid_int_param(id_network6):
            raise InvalidParameterError(
                u'Network ipv6 identifier is invalid or was not informed.')

        url = 'ip/availableip6/' + str(id_network6) + "/"

        code, xml = self.submit(None, 'GET', url)

        return self.response(code, xml)


Instruction:
Write a Python 3 script for
getting and save a available IP in the network ipv6 for vip environment.

Response:
def get_available_ip6_for_vip(self, id_evip, name):
        """
        Get and save a available IP in the network ipv6 for vip request

        :param id_evip: Vip environment identifier. Integer value and greater than zero.
        :param name: Ip description

        :return: Dictionary with the following structure:

        ::

            {'ip': {'bloco1':<bloco1>,
            'bloco2':<bloco2>,
            'bloco3':<bloco3>,
            'bloco4':<bloco4>,
            'bloco5':<bloco5>,
            'bloco6':<bloco6>,
            'bloco7':<bloco7>,
            'bloco8':<bloco8>,
            'id':<id>,
            'networkipv6':<networkipv6>,
            'description':<description>}}

        :raise IpNotAvailableError: Network dont have available IP for vip environment.
        :raise EnvironmentVipNotFoundError: Vip environment not registered.
        :raise UserNotAuthorizedError: User dont have permission to perform operation.
        :raise InvalidParameterError: Vip environment identifier is none or invalid.
        :raise XMLError: Networkapi failed to generate the XML response.
        :raise DataBaseError: Networkapi failed to access the database.

        """

        if not is_valid_int_param(id_evip):
            raise InvalidParameterError(
                u'Vip environment identifier is invalid or was not informed.')

        url = 'ip/availableip6/vip/' + str(id_evip) + "/"

        ip_map = dict()
        ip_map['id_evip'] = id_evip
        ip_map['name'] = name

        code, xml = self.submit({'ip_map': ip_map}, 'POST', url)

        return self.response(code, xml)


Instruction:
Write a Python 3 function that can
edit an IP4 in a resource.

Response:
def edit_ipv4(self, ip4, descricao, id_ip):
        """
        Edit a IP4

        :param ip4: An IP4 available to save in format x.x.x.x.
        :param id_ip: IP identifier. Integer value and greater than zero.
        :param descricao: IP description.

        :return: None
        """

        if not is_valid_int_param(id_ip):
            raise InvalidParameterError(
                u'Ip identifier is invalid or was not informed.')

        if ip4 is None or ip4 == "":
            raise InvalidParameterError(
                u'The IP4 is invalid or was not informed.')

        ip_map = dict()
        ip_map['descricao'] = descricao
        ip_map['ip4'] = ip4
        ip_map['id_ip'] = id_ip

        url = "ip4/edit/"

        code, xml = self.submit({'ip_map': ip_map}, 'POST', url)

        return self.response(code, xml)


Instruction:
Make a summary of the following Python 3 code
def save_ipv4(self, ip4, id_equip, descricao, id_net):
        if not is_valid_int_param(id_net):
            raise InvalidParameterError(
                u'Network identifier is invalid or was not informed.')

        if not is_valid_int_param(id_equip):
            raise InvalidParameterError(
                u'Equipment identifier is invalid or was not informed.')

        if ip4 is None or ip4 == "":
            raise InvalidParameterError(u'IP4 is invalid or was not informed.')

        ip_map = dict()
        ip_map['id_net'] = id_net
        ip_map['descricao'] = descricao
        ip_map['ip4'] = ip4
        ip_map['id_equip'] = id_equip

        url = "ipv4/save/"

        code, xml = self.submit({'ip_map': ip_map}, 'POST', url)

        return self.response(code, xml)

Response: Save a IP4 and associate with equipment and network.


Instruction:
Make a summary of the following Python 3 code
def edit_ipv6(self, ip6, descricao, id_ip):

        if not is_valid_int_param(id_ip):
            raise InvalidParameterError(
                u'Ipv6 identifier is invalid or was not informed.')

        if ip6 is None or ip6 == "":
            raise InvalidParameterError(u'IP6 is invalid or was not informed.')

        ip_map = dict()
        ip_map['descricao'] = descricao
        ip_map['ip6'] = ip6
        ip_map['id_ip'] = id_ip

        url = "ipv6/edit/"

        code, xml = self.submit({'ip_map': ip_map}, 'POST', url)

        return self.response(code, xml)

Response: Edit an IP6 in a cache.


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

        if not is_valid_int_param(id_ip):
            raise InvalidParameterError(
                u'Ip identifier is invalid or was not informed.')

        url = 'ip/get/' + str(id_ip) + "/"

        code, xml = self.submit(None, 'GET', url)

        return self.response(code, xml)

Response: Get an IP by ID.


Instruction:
Can you write a function in Python 3 where it
gets Ips related to an equipment by its identifier.

Response:
def find_ips_by_equip(self, id_equip):
        """
        Get Ips related to equipment by its identifier

        :param id_equip: Equipment identifier. Integer value and greater than zero.

        :return: Dictionary with the following structure:

            { ips: { ipv4:[
            id: <id_ip4>,
            oct1: <oct1>,
            oct2: <oct2>,
            oct3: <oct3>,
            oct4: <oct4>,
            descricao: <descricao> ]
            ipv6:[
            id: <id_ip6>,
            block1: <block1>,
            block2: <block2>,
            block3: <block3>,
            block4: <block4>,
            block5: <block5>,
            block6: <block6>,
            block7: <block7>,
            block8: <block8>,
            descricao: <descricao> ] } }

        :raise UserNotAuthorizedError: User dont have permission to list ips.
        :raise InvalidParameterError: Equipment identifier is none or invalid.
        :raise XMLError: Networkapi failed to generate the XML response.
        :raise DataBaseError: Networkapi failed to access the database.

        """
        url = 'ip/getbyequip/' + str(id_equip) + "/"

        code, xml = self.submit(None, 'GET', url)

        return self.response(code, xml, ['ipv4', 'ipv6'])


Instruction:
Can you implement a function in Python 3 that
gets an IP6 by ID.

Response:
def find_ip6_by_id(self, id_ip):
        """
        Get an IP6 by ID

        :param id_ip: IP6 identifier. Integer value and greater than zero.

        :return: Dictionary with the following structure:

        ::

            {'ip': {'id': < id >,
            'block1': <block1>,
            'block2': <block2>,
            'block3': <block3>,
            'block4': <block4>,
            'block5': <block5>,
            'block6': <block6>,
            'block7': <block7>,
            'block8': <block8>,
            'descricao': < description >,
            'equipamento': [ { all name equipamentos related} ], }}

        :raise IpNotAvailableError: Network dont have available IPv6.
        :raise NetworkIPv4NotFoundError: Network was not found.
        :raise UserNotAuthorizedError: User dont have permission to perform operation.
        :raise InvalidParameterError: IPv6 identifier is none or invalid.
        :raise XMLError: Networkapi failed to generate the XML response.
        :raise DataBaseError: Networkapi failed to access the database.

        """

        if not is_valid_int_param(id_ip):
            raise InvalidParameterError(
                u'Ipv6 identifier is invalid or was not informed.')

        url = 'ipv6/get/' + str(id_ip) + "/"

        code, xml = self.submit(None, 'GET', url)

        return self.response(code, xml)


Instruction:
Here you have a function in Python 3, explain what it does
def save_ipv6(self, ip6, id_equip, descricao, id_net):
        if not is_valid_int_param(id_net):
            raise InvalidParameterError(
                u'Network identifier is invalid or was not informed.')

        if not is_valid_int_param(id_equip):
            raise InvalidParameterError(
                u'Equipment identifier is invalid or was not informed.')

        if ip6 is None or ip6 == "":
            raise InvalidParameterError(
                u'IPv6 is invalid or was not informed.')

        ip_map = dict()
        ip_map['id_net'] = id_net
        ip_map['descricao'] = descricao
        ip_map['ip6'] = ip6
        ip_map['id_equip'] = id_equip

        url = "ipv6/save/"

        code, xml = self.submit({'ip_map': ip_map}, 'POST', url)

        return self.response(code, xml)

Response: Save an IP6 and associate with equipment.


Instruction:
Given the following Python 3 function, write the documentation
def delete_ip4(self, id_ip):

        if not is_valid_int_param(id_ip):
            raise InvalidParameterError(u'Ipv4 identifier is invalid or was not informed.')

        url = 'ip4/delete/' + str(id_ip) + "/"
        code, xml = self.submit(None, 'DELETE', url)

        return self.response(code, xml)

Response: Delete an IP4 from the database.


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

        if not is_valid_int_param(id_network):
            raise InvalidParameterError(
                u'Network identifier is invalid or was not informed.')

        url = 'ip/id_network_ipv6/' + str(id_network) + "/"

        code, xml = self.submit(None, 'GET', url)

        key = "ips"
        return get_list_map(self.response(code, xml, [key]), key)

Response: List IPv6 from network.


Instruction:
Can you tell what is the following Python 3 function doing
def search_ipv6_environment(self, ipv6, id_environment):

        if not is_valid_int_param(id_environment):
            raise InvalidParameterError(
                u'Environment identifier is invalid or was not informed.')

        ipv6_map = dict()
        ipv6_map['ipv6'] = ipv6
        ipv6_map['id_environment'] = id_environment

        code, xml = self.submit(
            {'ipv6_map': ipv6_map}, 'POST', 'ipv6/environment/')

        return self.response(code, xml)

Response: Search IPv6 with an associated environment.


Instruction:
Explain what the following Python 3 code does
def assoc_ipv4(self, id_ip, id_equip, id_net):

        if not is_valid_int_param(id_ip):
            raise InvalidParameterError(
                u'Ip identifier is invalid or was not informed.')

        if not is_valid_int_param(id_net):
            raise InvalidParameterError(
                u'Network identifier is invalid or was not informed.')

        if not is_valid_int_param(id_equip):
            raise InvalidParameterError(
                u'Equipment identifier is invalid or was not informed.')

        ip_map = dict()
        ip_map['id_ip'] = id_ip
        ip_map['id_net'] = id_net
        ip_map['id_equip'] = id_equip

        url = "ipv4/assoc/"

        code, xml = self.submit({'ip_map': ip_map}, 'POST', url)

        return self.response(code, xml)

Response: Associate an IP4 with an equipment.


Instruction:
How would you explain what the following Python 3 function does
def assoc_ipv6(self, id_ip, id_equip, id_net):

        if not is_valid_int_param(id_ip):
            raise InvalidParameterError(
                u'Ipv6 identifier is invalid or was not informed.')

        if not is_valid_int_param(id_net):
            raise InvalidParameterError(
                u'Network identifier is invalid or was not informed.')

        if not is_valid_int_param(id_equip):
            raise InvalidParameterError(
                u'Equipment identifier is invalid or was not informed.')

        ip_map = dict()
        ip_map['id_ip'] = id_ip
        ip_map['id_net'] = id_net
        ip_map['id_equip'] = id_equip

        url = "ipv6/assoc/"

        code, xml = self.submit({'ip_map': ip_map}, 'POST', url)

        return self.response(code, xml)

Response: Associate an IPv6 with an equipment.


Instruction:
Explain what the following Python 3 code does
def listar(self):

        code, xml = self.submit(None, 'GET', 'net_type/')

        key = 'net_type'
        return get_list_map(self.response(code, xml, [key]), key)

Response: List all network types.


Instruction:
Given the following Python 3 function, write the documentation
def inserir(self, name):

        net_type_map = dict()
        net_type_map['name'] = name

        code, xml = self.submit(
            {'net_type': net_type_map}, 'POST', 'net_type/')

        return self.response(code, xml)

Response: Insert a new network type and return its identifier.


Instruction:
Given the following Python 3 function, write the documentation
def alterar(self, id_net_type, name):

        if not is_valid_int_param(id_net_type):
            raise InvalidParameterError(
                u'Network type is invalid or was not informed.')

        url = 'net_type/' + str(id_net_type) + '/'

        net_type_map = dict()
        net_type_map['name'] = name

        code, xml = self.submit({'net_type': net_type_map}, 'PUT', url)

        return self.response(code, xml)

Response: Edit network type by its identifier.


Instruction:
Can you generate the documentation for the following Python 3 function
def remover(self, id_net_type):
        if not is_valid_int_param(id_net_type):
            raise InvalidParameterError(
                u'Network type is invalid or was not informed.')

        url = 'net_type/' + str(id_net_type) + '/'

        code, xml = self.submit(None, 'DELETE', url)

        return self.response(code, xml)

Response: Remove network type by its identifier.


Instruction:
Write a Python 3 function that can
compile rbnf source code file

Response:
def cc(filename: 'input source file',
       output:
       'output file name. default to be replacing input file\'s suffix with ".py"' = None,
       name: 'name of language' = 'unname'):
    """
    rbnf source code compiler.
    """

    lang = Language(name)

    with Path(filename).open('r') as fr:
        build_language(fr.read(), lang, filename)

    if not output:
        base, _ = os.path.splitext(filename)

        output = base + '.py'
    lang.dump(output)


Instruction:
Write a Python 3 function for
running the parser and returns a tree of all the modules that are parsed.

Response:
def run(filename: 'python file generated by `rbnf` command, or rbnf sour file',
        opt: 'optimize switch' = False):
    """
    You can apply immediate tests on your parser.
    P.S: use `--opt` option takes longer starting time.
    """
    from rbnf.easy import build_parser
    import importlib.util
    import traceback
    full_path = Path(filename)
    base, ext = os.path.splitext(str(full_path))
    full_path_str = str(full_path)

    if not ext:
        if full_path.into('.py').exists():
            full_path_str = base + '.py'
        elif Path(base).into('.rbnf'):
            full_path_str = base + '.rbnf'

    if full_path_str[-3:].lower() != '.py':
        with Path(full_path_str).open('r') as fr:
            ze_exp = ze.compile(fr.read(), filename=full_path_str)
            lang = ze_exp.lang

    else:
        spec = importlib.util.spec_from_file_location("runbnf", full_path_str)

        mod = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(mod)
        try:
            lang = next(each for each in mod.__dict__.values()
                        if isinstance(each, Language))
        except StopIteration:
            raise NameError("Found no language in {}".format(full_path_str))

    parse = build_parser(lang, opt=bool(opt))
    namespace = {}

    print(Purple('type `:i` to switch between python mode and parsing mode.'))
    print(Purple('The last result of parsing is stored as symbol `res`.'))
    while True:

        inp = input('runbnf> ')
        if not inp.strip():
            continue
        elif inp.strip() == 'exit':
            break

        if inp.strip() == ':i':
            while True:
                inp = input('python> ')

                if inp.strip() == ':i':
                    break
                try:
                    try:
                        res = eval(inp, namespace)
                        if res is not None:
                            print(res)

                        namespace['_'] = res
                    except SyntaxError:
                        exec(inp, namespace)
                except Exception:
                    traceback.print_exc()
        else:
            res = namespace['res'] = parse(inp)
            print(
                LightBlue(
                    'parsed result = res: ResultDescription{result, tokens, state}'
                ))
            print(res.result)


Instruction:
Can you tell what is the following Python 3 function doing
def rbnf_lexing(text: str):

    cast_map: const    = _cast_map
    lexer_table: const = _lexer_table
    keyword: const     = _keyword
    drop_table: const  = _DropTable
    end: const         = _END
    unknown: const     = _UNKNOWN

    text_length = len(text)
    colno       = 0
    lineno      = 0
    position    = 0

    cast_const  = ConstStrPool.cast_to_const

    while True:
        if text_length <= position:
            break

        for case_name, text_match_case in lexer_table:
            matched_text = text_match_case(text, position)
            if not matched_text:
                continue

            case_mem_addr = id(case_name)  # memory address of case_name

            if case_mem_addr not in drop_table:

                if matched_text in cast_map:
                    yield Tokenizer(keyword, cast_const(matched_text), lineno, colno)

                else:
                    yield Tokenizer(cast_const(case_name), matched_text, lineno, colno)

            n = len(matched_text)
            line_inc = matched_text.count('\n')

            if line_inc:

                latest_newline_idx = matched_text.rindex('\n')
                colno = n - latest_newline_idx
                lineno += line_inc

                if case_name is _Space and matched_text[-1] == '\n':

                    yield Tokenizer(end, '', lineno, colno)

            else:
                colno += n
            position += n
            break

        else:

            char = text[position]
            yield Tokenizer(unknown, char, lineno, colno)

            position += 1

            if char == '\n':
                lineno += 1
                colno = 0

            else:
                colno += 1

Response: Read loudly for documentation.


Instruction:
Can you implement a function in Python 3 that
recovers the code string from a series of tokenizers to a series of code strings.

Response:
def recover_codes(tokens: Iterator[Tokenizer]) -> str:
    """
    from a series of tokenizers to code string. (preserve the indentation)
    """

    tokens = iter(tokens)

    s = []

    try:
        head = next(tokens)

    except StopIteration:
        return s

    append = s.append
    lineno = head.lineno

    start_indent = colno = head.colno

    append(head.value)

    colno += len(s[-1])

    for each in tokens:
        n = each.lineno - lineno

        if n:
            append('\n' * n)
            lineno = each.lineno
            colno = each.colno

            if colno - start_indent > 0:
                append(' ' * colno)

        else:
            c = each.colno - colno
            if c:
                colno = each.colno
                if c > 0:
                    append(' ' * c)

        append(each.value)

        colno += len(s[-1])

    return s


Instruction:
Make a summary of the following Python 3 code
def str_lexer(mode):
    cast_to_const = ConstStrPool.cast_to_const

    def f_raw(inp_str, pos):
        return cast_to_const(mode) if inp_str.startswith(mode, pos) else None

    def f_collection(inp_str, pos):
        for each in mode:
            if inp_str.startswith(each, pos):
                return cast_to_const(each)
        return None

    if isinstance(mode, str):
        return f_raw

    if len(mode) is 1:
        mode = mode[0]
        return f_raw

    return f_collection

Response: generate token strings cache


Instruction:
Here you have a function in Python 3, explain what it does
def dispatch(self, tree):
        "Dispatcher function, dispatching tree type T to method _T."
        if isinstance(tree, list):
            for t in tree:
                self.dispatch(t)
            return
        meth = getattr(self, "_" + tree.__class__.__name__)
        meth(tree)

Response: Dispatcher function dispatching tree type T to method _T.


Instruction:
Implement a function in Python 3 to
process a function and its ast.

Response:
def process(fn, bound_names):
    """
    process automatic context variable capturing.
    return the transformed function and its ast.
    """
    if isinstance(fn, _AutoContext):
        fn = fn.fn

    # noinspection PyArgumentList,PyArgumentList
    if isinstance(fn, _FnCodeStr):

        if bound_names:
            assign_code_str = '{syms} = map(state.ctx.get, {names})'.format(
                syms=', '.join(bound_names) + ',', names=repr(bound_names))
        else:
             assign_code_str = ''

        code = "def {0}({1}):\n{2}".format(
            fn.fn_name, ", ".join(fn.fn_args),
            textwrap.indent(assign_code_str + '\n' + fn.code, "    "))

        module_ast = ast.parse(code, fn.filename)

        bound_name_line_inc = int(bool(bound_names)) + 1

        module_ast: ast.Module = ast.increment_lineno(
            module_ast, fn.lineno - bound_name_line_inc)

        fn_ast = module_ast.body[0]

        if isinstance(fn_ast.body[-1], ast.Expr):
            # auto addition of tail expr return
            # in rbnf you don't need to write return if the last statement in the end is an expression.
            it: ast.Expr = fn_ast.body[-1]

            fn_ast.body[-1] = ast.Return(
                lineno=it.lineno, col_offset=it.col_offset, value=it.value)

        filename = fn.filename
        name = fn.fn_name

        code_object = compile(module_ast, filename, "exec")

        local = {}
        # TODO: using types.MethodType here to create the function object leads to various problems.
        # Actually I don't really known why util now.
        exec(code_object, fn.namespace, local)
        ret = local[name]

    else:
        if not bound_names:
            return fn, get_ast(fn)

        code = fn.__code__
        assigns = ast.parse("ctx = state.ctx\n" + "\n".join(
            "{0} = ctx.get({0!r})".format(name) for name in bound_names))

        module_ast = get_ast(fn)
        fn_ast: ast.FunctionDef = module_ast.body[0]
        fn_ast.body = assigns.body + fn_ast.body
        module_ast = ast.Module([fn_ast])

        filename = code.co_filename
        name = code.co_name
        __defaults__ = fn.__defaults__
        __closure__ = fn.__closure__
        __globals__ = fn.__globals__

        code_object = compile(module_ast, filename, "exec")

        code_object = next(
            each for each in code_object.co_consts
            if isinstance(each, types.CodeType) and each.co_name == name)

        # noinspection PyArgumentList,PyUnboundLocalVariable
        ret = types.FunctionType(code_object, __globals__, name, __defaults__,
                                 __closure__)
    return ret, module_ast


Instruction:
Explain what the following Python 3 code does
def ignore(self, *ignore_lst: str):

        def stream():
            for each in ignore_lst:
                each = ConstStrPool.cast_to_const(each)
                yield id(each), each

        self.ignore_lst.update(stream())

Response: ignore a set of tokens with specific names


Instruction:
Create a Python 3 function to
build a language from a source code.

Response:
def build_language(source_code: str, lang: Language, filename: str):
    """
    lang:      language object represents your language.
    """
    state = MetaState(rbnf.implementation, requires=_Wild(), filename=filename)
    state.data = lang
    _build_language(source_code, state)
    lang.build()


Instruction:
Can you generate the documentation for the following Python 3 function
def _decode_POST_value(request, field_name, default=None):
    if default is None:
        value = request.POST[field_name]
    else:
        value = request.POST.get(field_name, default)

    # it's inefficient to load this each time it gets called, but we're
    # not anticipating incoming email being a performance bottleneck right now!
    charsets = json.loads(request.POST.get('charsets', "{}"))
    charset = charsets.get(field_name, 'utf-8')

    if charset.lower() != 'utf-8':
        logger.debug("Incoming email field '%s' has %s encoding.", field_name, charset)

    return smart_text(value, encoding=charset)

Response: Helper function to decode a request field into unicode based on charsets encoding.


Instruction:
Can you write a function in Python 3 where it
takes a list of RFC - compliant email addresses and returns a list of strings each containing the name and email addresses.

Response:
def _get_addresses(self, address_data, retain_name=False):
        """
        Takes RFC-compliant email addresses in both terse (email only)
        and verbose (name + email) forms and returns a list of
        email address strings

        (TODO: breaking change that returns a tuple of (name, email) per string)
        """
        if retain_name:
            raise NotImplementedError(
                "Not yet implemented, but will need client-code changes too"
            )

        # We trust than an email address contains an "@" after
        # email.utils.getaddresses has done the hard work. If we wanted
        # to we could use a regex to check for greater email validity

        # NB: getaddresses expects a list, so ensure we feed it appropriately
        if isinstance(address_data, str):
            if "[" not in address_data:
                # Definitely turn these into a list
                # NB: this is pretty assumptive, but still prob OK
                address_data = [address_data]

        output = [x[1] for x in getaddresses(address_data) if "@" in x[1]]
        return output


Instruction:
Can you generate the documentation for the following Python 3 function
def parse(self, request):
        assert isinstance(request, HttpRequest), "Invalid request type: %s" % type(request)

        try:
            # from_email should never be a list (unless we change our API)
            from_email = self._get_addresses([_decode_POST_value(request, 'from')])[0]

            # ...but all these can and will be a list
            to_email = self._get_addresses([_decode_POST_value(request, 'to')])
            cc = self._get_addresses([_decode_POST_value(request, 'cc', default='')])
            bcc = self._get_addresses([_decode_POST_value(request, 'bcc', default='')])

            subject = _decode_POST_value(request, 'subject')
            text = _decode_POST_value(request, 'text', default='')
            html = _decode_POST_value(request, 'html', default='')

        except IndexError as ex:
            raise RequestParseError(
                "Inbound request lacks a valid from address: %s." % request.get('from')
            )

        except MultiValueDictKeyError as ex:
            raise RequestParseError("Inbound request is missing required value: %s." % ex)

        if "@" not in from_email:
            # Light sanity check for potential issues related to taking just the
            # first element of the 'from' address list
            raise RequestParseError("Could not get a valid from address out of: %s." % request)

        email = EmailMultiAlternatives(
            subject=subject,
            body=text,
            from_email=from_email,
            to=to_email,
            cc=cc,
            bcc=bcc,
        )
        if html is not None and len(html) > 0:
            email.attach_alternative(html, "text/html")

        # TODO: this won't cope with big files - should really read in in chunks
        for n, f in list(request.FILES.items()):
            if f.size > self.max_file_size:
                logger.debug(
                    "File attachment %s is too large to process (%sB)",
                    f.name,
                    f.size
                )
                raise AttachmentTooLargeError(
                    email=email,
                    filename=f.name,
                    size=f.size
                )
            else:
                email.attach(f.name, f.read(), f.content_type)
        return email

Response: Parse an incoming request and return an EmailMultiAlternatives instance.


Instruction:
Write a Python 3 function for
parsing an incoming request and return an EmailMultiAlternatives instance.

Response:
def parse(self, request):
        """Parse incoming request and return an email instance.

        Mailgun does a lot of the heavy lifting at their end - requests
        come in from them UTF-8 encoded, and with the message reply and
        signature stripped out for you.

        Args:
            request: an HttpRequest object, containing the forwarded email, as
                per the SendGrid specification for inbound emails.

        Returns:
            an EmailMultiAlternatives instance, containing the parsed contents
                of the inbound email.
        """
        assert isinstance(request, HttpRequest), "Invalid request type: %s" % type(request)

        try:
            subject = request.POST.get('subject', '')
            text = "%s\n\n%s" % (
                request.POST.get('stripped-text', ''),
                request.POST.get('stripped-signature', '')
            )
            html = request.POST.get('stripped-html')
            from_email = request.POST.get('sender')
            to_email = request.POST.get('recipient').split(',')
            cc = request.POST.get('cc', '').split(',')
            bcc = request.POST.get('bcc', '').split(',')

        except MultiValueDictKeyError as ex:
            raise RequestParseError(
                "Inbound request is missing required value: %s." % ex
            )

        except AttributeError as ex:
            raise RequestParseError(
                "Inbound request is missing required value: %s." % ex
            )

        email = EmailMultiAlternatives(
            subject=subject,
            body=text,
            from_email=from_email,
            to=to_email,
            cc=cc,
            bcc=bcc,
        )
        if html is not None and len(html) > 0:
            email.attach_alternative(html, "text/html")

        # TODO: this won't cope with big files - should really read in in chunks
        for n, f in list(request.FILES.items()):
            if f.size > self.max_file_size:
                logger.debug(
                    "File attachment %s is too large to process (%sB)",
                    f.name,
                    f.size
                )
                raise AttachmentTooLargeError(
                    email=email,
                    filename=f.name,
                    size=f.size
                )
            else:
                email.attach(n, f.read(), f.content_type)

        return email


Instruction:
Create a Python 3 function to
return an iterator of objects from the array

Response:
def _get_recipients(self, array):
        """Returns an iterator of objects
           in the form ["Name <address@example.com", ...]
           from the array [["address@example.com", "Name"]]
        """
        for address, name in array:
            if not name:
                yield address
            else:
                yield "\"%s\" <%s>" % (name, address)


Instruction:
Make a summary of the following Python 3 code
def parse(self, request):
        assert isinstance(request, HttpRequest), "Invalid request type: %s" % type(request)

        if settings.INBOUND_MANDRILL_AUTHENTICATION_KEY:
            _check_mandrill_signature(
                request=request,
                key=settings.INBOUND_MANDRILL_AUTHENTICATION_KEY,
            )

        try:
            messages = json.loads(request.POST['mandrill_events'])
        except (ValueError, KeyError) as ex:
            raise RequestParseError("Request is not a valid json: %s" % ex)

        if not messages:
            logger.debug("No messages found in mandrill request: %s", request.body)
            return []

        emails = []
        for message in messages:
            if message.get('event') != 'inbound':
                logger.debug("Discarding non-inbound message")
                continue

            msg = message.get('msg')
            try:
                from_email = msg['from_email']
                to = list(self._get_recipients(msg['to']))
                cc = list(self._get_recipients(msg['cc'])) if 'cc' in msg else []
                bcc = list(self._get_recipients(msg['bcc'])) if 'bcc' in msg else []

                subject = msg.get('subject', "")

                attachments = msg.get('attachments', {})
                attachments.update(msg.get('images', {}))

                text = msg.get('text', "")
                html = msg.get('html', "")
            except (KeyError, ValueError) as ex:
                raise RequestParseError(
                    "Inbound request is missing or got an invalid value.: %s." % ex
                )

            email = EmailMultiAlternatives(
                subject=subject,
                body=text,
                from_email=self._get_sender(
                    from_email=from_email,
                    from_name=msg.get('from_name'),
                ),
                to=to,
                cc=cc,
                bcc=bcc,
            )
            if html is not None and len(html) > 0:
                email.attach_alternative(html, "text/html")

            email = self._process_attachments(email, attachments)
            emails.append(email)

        return emails

Response: Parse an incoming request and return an EmailMultiAlternatives instance.


Instruction:
Can you generate the documentation for the following Python 3 function
def receive_inbound_email(request):
    # log the request.POST and request.FILES contents
    if log_requests is True:
        _log_request(request)

    # HEAD requests are used by some backends to validate the route
    if request.method == 'HEAD':
        return HttpResponse('OK')

    try:
        # clean up encodings and extract relevant fields from request.POST
        backend = get_backend_instance()
        emails = backend.parse(request)

        # backend.parse can return either an EmailMultiAlternatives
        # or a list of those
        if emails:
            if isinstance(emails, EmailMultiAlternatives):
                emails = [emails]
            for email in emails:
                # fire the signal for each email
                email_received.send(sender=backend.__class__, email=email, request=request)

    except AttachmentTooLargeError as ex:
        logger.exception(ex)
        email_received_unacceptable.send(
            sender=backend.__class__,
            email=ex.email,
            request=request,
            exception=ex
        )
    except AuthenticationError as ex:
        logger.exception(ex)
        email_received_unacceptable.send(
            sender=backend.__class__,
            email=None,
            request=request,
            exception=ex
        )

    except RequestParseError as ex:
        logger.exception(ex)
        if getattr(settings, 'INBOUND_EMAIL_RESPONSE_200', True):
            # NB even if we have a problem, always use HTTP_STATUS=200, as
            # otherwise the email service will continue polling us with the email.
            # This is the default behaviour.
            status_code = 200
        else:
            status_code = 400

        return HttpResponse(
            "Unable to parse inbound email: %s" % ex,
            status=status_code
        )

    return HttpResponse("Successfully parsed inbound email.", status=200)

Response: Receives the inbound email from SendGrid.


Instruction:
Can you tell what is the following Python 3 function doing
def get_backend_class():
    # this will (intentionally) blow up if the setting does not exist
    assert hasattr(settings, 'INBOUND_EMAIL_PARSER')
    assert getattr(settings, 'INBOUND_EMAIL_PARSER') is not None

    package, klass = settings.INBOUND_EMAIL_PARSER.rsplit('.', 1)
    module = import_module(package)
    return getattr(module, klass)

Response: Return reference to the configured backed class.


Instruction:
Can you tell what is the following Python 3 function doing
def sorted_exists(values, x):
    i = bisect_left(values, x)
    j = bisect_right(values, x)
    exists = x in values[i:j]
    return exists, i

Response: Returns the insert position for item x and whether the item already exists in the list.


Instruction:
Write a Python 3 function that can
sort a list but returns the order of the index values of the list.

Response:
def sorted_list_indexes(list_to_sort, key=None, reverse=False):
    """
    Sorts a list but returns the order of the index values of the list for the sort and not the values themselves.
    For example is the list provided is ['b', 'a', 'c'] then the result will be [2, 1, 3]

    :param list_to_sort: list to sort
    :param key: if not None then a function of one argument that is used to extract a comparison key from each
                list element
    :param reverse: if True then the list elements are sorted as if each comparison were reversed.
    :return: list of sorted index values
    """
    if key is not None:
        def key_func(i):
            return key(list_to_sort.__getitem__(i))
    else:
        key_func = list_to_sort.__getitem__
    return sorted(range(len(list_to_sort)), key=key_func, reverse=reverse)


Instruction:
Here you have a function in Python 3, explain what it does
def runDia(diagram):
    ifname = '{}.dia'.format(diagram)
    ofname = '{}.png'.format(diagram)
    cmd = 'dia -t png-libart -e {} {}'.format(ofname, ifname)
    print('  {}'.format(cmd))
    subprocess.call(cmd, shell=True)
    return True

Response: Generate the diagrams using Dia.


Instruction:
Write a Python 3 script for
initializing the ordered worker.

Response:
def init2(
        self,
        input_tube,      # Read task from the input tube.
        output_tubes,    # Send result on all the output tubes.
        num_workers,     # Total number of workers in the stage.
        disable_result,  # Whether to override any result with None.
        do_stop_task,    # Whether to call doTask() on "stop" request.
        ):
        """Create *num_workers* worker objects with *input_tube* and
        an iterable of *output_tubes*. The worker reads a task from *input_tube*
        and writes the result to *output_tubes*."""

        super(OrderedWorker, self).__init__()
        self._tube_task_input = input_tube
        self._tubes_result_output = output_tubes
        self._num_workers = num_workers

        # Serializes reading from input tube.
        self._lock_prev_input = None
        self._lock_next_input = None

        # Serializes writing to output tube.
        self._lock_prev_output = None
        self._lock_next_output = None

        self._disable_result = disable_result
        self._do_stop_task = do_stop_task


Instruction:
Make a summary of the following Python 3 code
def assemble(
        cls,
        args,
        input_tube,
        output_tubes,
        size,
        disable_result=False,
        do_stop_task=False,
        ):
        """Create, assemble and start workers.
        Workers are created of class *cls*, initialized with *args*, and given
        task/result communication channels *input_tube* and *output_tubes*.
        The number of workers created is according to *size* parameter.
        *do_stop_task* indicates whether doTask() will be called for "stop" request.
        """

        # Create the workers.
        workers = []
        for ii in range(size):
            worker = cls(**args)
            worker.init2(
                input_tube,
                output_tubes,
                size,
                disable_result,
                do_stop_task,
                )
            workers.append(worker)

        # Connect the workers.
        for ii in range(size):
            worker_this = workers[ii]
            worker_prev = workers[ii-1]
            worker_prev._link(
                worker_this,
                next_is_first=(ii==0),  # Designate 0th worker as the first.
                )

        # Start the workers.
        for worker in workers:
            worker.start()

Response: Assemble and start workers.


Instruction:
Can you create a Python 3 function that
links the worker to the given next worker object.

Response:
def _link(self, next_worker, next_is_first=False):
        """Link the worker to the given next worker object,
        connecting the two workers with communication tubes."""

        lock = multiprocessing.Lock()
        next_worker._lock_prev_input = lock
        self._lock_next_input = lock
        lock.acquire()

        lock = multiprocessing.Lock()
        next_worker._lock_prev_output = lock
        self._lock_next_output = lock
        lock.acquire()

        # If the next worker is the first one, trigger it now.
        if next_is_first:
            self._lock_next_input.release()
            self._lock_next_output.release()


Instruction:
Create a Python 3 function for
registering the result by putting it on all the output tubes.

Response:
def putResult(self, result):
        """Register the *result* by putting it on all the output tubes."""
        self._lock_prev_output.acquire()
        for tube in self._tubes_result_output:
            tube.put((result, 0))
        self._lock_next_output.release()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def init2(
        self,
        input_tube,      # Read task from the input tube.
        output_tubes,    # Send result on all the output tubes.
        num_workers,     # Total number of workers in the stage.
        disable_result,  # Whether to override any result with None.
        do_stop_task,    # Whether to call doTask() on "stop" request.
        ):
        """Create *num_workers* worker objects with *input_tube* and
        an iterable of *output_tubes*. The worker reads a task from *input_tube*
        and writes the result to *output_tubes*."""

        super(UnorderedWorker, self).__init__()
        self._tube_task_input = input_tube
        self._tubes_result_output = output_tubes
        self._num_workers = num_workers
        self._disable_result = disable_result
        self._do_stop_task = do_stop_task

Response: Initialize the unordered worker.


Instruction:
Implement a function in Python 3 to
assemble and start workers.

Response:
def assemble(
        cls,
        args,
        input_tube,
        output_tubes,
        size,
        disable_result,
        do_stop_task,
        ):
        """Create, assemble and start workers.
        Workers are created of class *cls*, initialized with *args*, and given
        task/result communication channels *input_tube* and *output_tubes*.
        The number of workers created is according to *size* parameter.
        *do_stop_task* indicates whether doTask() will be called for "stop" request.
        """

        # Create the workers.
        workers = []
        for ii in range(size):
            worker = cls(**args)
            worker.init2(
                input_tube,
                output_tubes,
                size,
                disable_result,
                do_stop_task,
                )
            workers.append(worker)

        # Start the workers.
        for worker in workers:
            worker.start()


Instruction:
Can you implement a function in Python 3 that
prints the contents of the Series.

Response:
def show(self, index=True, **kwargs):
        """
        Print the contents of the Series. This method uses the tabulate function from the tabulate package. Use the
        kwargs to pass along any arguments to the tabulate function.

        :param index: If True then include the indexes as a column in the output, if False ignore the index
        :param kwargs: Parameters to pass along to the tabulate function
        :return: output of the tabulate function
        """
        print(self._make_table(index=index, **kwargs))


Instruction:
Write a Python 3 script for
giving indexes will return a sub-set of the Series. This method will direct to the specific methods based on what types are passed in for the indexes. The type of the return is determined by the types of the parameters. :param indexes: index value, list of index values, or a list of booleans. :param as_list: if True then return the values as a list, if False return a Series. :return: either Series, list, or single value. The return is a shallow copy

Response:
def get(self, indexes, as_list=False):
        """
        Given indexes will return a sub-set of the Series. This method will direct to the specific methods
        based on what types are passed in for the indexes. The type of the return is determined by the
        types of the parameters.

        :param indexes: index value, list of index values, or a list of booleans.
        :param as_list: if True then return the values as a list, if False return a Series.
        :return: either Series, list, or single value. The return is a shallow copy
        """
        if isinstance(indexes, (list, blist)):
            return self.get_rows(indexes, as_list)
        else:
            return self.get_cell(indexes)


Instruction:
How would you code a function in Python 3 to
return the value of the key - value pair for a single index and return the value

Response:
def get_cell(self, index):
        """
        For a single index and return the value

        :param index: index value
        :return: value
        """
        i = sorted_index(self._index, index) if self._sort else self._index.index(index)
        return self._data[i]


Instruction:
Write a Python 3 script for
returning the rows of the table.

Response:
def get_rows(self, indexes, as_list=False):
        """
        For a list of indexes return the values of the indexes in that column.

        :param indexes: either a list of index values or a list of booleans with same length as all indexes
        :param as_list: if True return a list, if False return Series
        :return: Series if as_list if False, a list if as_list is True
        """
        if all([isinstance(i, bool) for i in indexes]):  # boolean list
            if len(indexes) != len(self._index):
                raise ValueError('boolean index list must be same size of existing index')
            if all(indexes):  # the entire column
                data = self._data
                index = self._index
            else:
                data = list(compress(self._data, indexes))
                index = list(compress(self._index, indexes))
        else:  # index values list
            locations = [sorted_index(self._index, x) for x in indexes] if self._sort \
                else [self._index.index(x) for x in indexes]
            data = [self._data[i] for i in locations]
            index = [self._index[i] for i in locations]
        return data if as_list else Series(data=data, index=index, data_name=self._data_name,
                                           index_name=self._index_name, sort=self._sort)


Instruction:
How would you explain what the following Python 3 function does
def get_location(self, location):
        return {self.index_name: self._index[location], self.data_name: self._data[location]}

Response: Returns a dictionary of the index and value for the specified index location


Instruction:
Make a summary of the following Python 3 code
def get_locations(self, locations, as_list=False):

        indexes = [self._index[x] for x in locations]
        return self.get(indexes, as_list)

Response: Get the values for a list of locations.


Instruction:
Implement a function in Python 3 to
return a slice of the data from the index.

Response:
def get_slice(self, start_index=None, stop_index=None, as_list=False):
        """
        For sorted Series will return either a Series or list of all of the rows where the index is greater than
        or equal to the start_index if provided and less than or equal to the stop_index if provided. If either the
        start or stop index is None then will include from the first or last element, similar to standard python
        slide of [:5] or [:5]. Both end points are considered inclusive.

        :param start_index: lowest index value to include, or None to start from the first row
        :param stop_index: highest index value to include, or None to end at the last row
        :param as_list: if True then return a list of the indexes and values
        :return: Series or tuple of (index list, values list)
        """
        if not self._sort:
            raise RuntimeError('Can only use get_slice on sorted Series')

        start_location = bisect_left(self._index, start_index) if start_index is not None else None
        stop_location = bisect_right(self._index, stop_index) if stop_index is not None else None

        index = self._index[start_location:stop_location]
        data = self._data[start_location:stop_location]

        if as_list:
            return index, data
        else:
            return Series(data=data, index=index, data_name=self._data_name, index_name=self._index_name,
                          sort=self._sort)


Instruction:
Can you create a Python 3 function that
returns a dict containing the data and index names and the values are the data and index names.

Response:
def to_dict(self, index=True, ordered=False):
        """
        Returns a dict where the keys are the data and index names and the values are list of the data and index.

        :param index: If True then include the index in the dict with the index_name as the key
        :param ordered: If True then return an OrderedDict() to preserve the order of the columns in the Series
        :return: dict or OrderedDict()
        """
        result = OrderedDict() if ordered else dict()
        if index:
            result.update({self._index_name: self._index})
        if ordered:
            data_dict = [(self._data_name, self._data)]
        else:
            data_dict = {self._data_name: self._data}
        result.update(data_dict)
        return result


Instruction:
Write a Python 3 script for
returning a Series of the first N rows

Response:
def head(self, rows):
        """
        Return a Series of the first N rows

        :param rows: number of rows
        :return: Series
        """
        rows_bool = [True] * min(rows, len(self._index))
        rows_bool.extend([False] * max(0, len(self._index) - rows))
        return self.get(indexes=rows_bool)


Instruction:
Here you have a function in Python 3, explain what it does
def select_index(self, compare, result='boolean'):
        if isinstance(compare, tuple):
            # this crazy list comprehension will match all the tuples in the list with None being an * wildcard
            booleans = [all([(compare[i] == w if compare[i] is not None else True) for i, w in enumerate(v)])
                        for x, v in enumerate(self._index)]
        else:
            booleans = [False] * len(self._index)
            if self._sort:
                booleans[sorted_index(self._index, compare)] = True
            else:
                booleans[self._index.index(compare)] = True
        if result == 'boolean':
            return booleans
        elif result == 'value':
            return list(compress(self._index, booleans))
        else:
            raise ValueError('only valid values for result parameter are: boolean or value.')

Response: Select the elements in the index that match the compare parameter and returns either a list of booleans or values that match the compare parameter.


Instruction:
Write a Python 3 script for
returning a list of booleans on the equality of the value for the given indexes.

Response:
def equality(self, indexes=None, value=None):
        """
        Math helper method. Given a column and optional indexes will return a list of booleans on the equality of the
        value for that index in the DataFrame to the value parameter.

        :param indexes: list of index values or list of booleans. If a list of booleans then the list must be the same\
        length as the DataFrame
        :param value: value to compare
        :return: list of booleans
        """
        indexes = [True] * len(self._index) if indexes is None else indexes
        compare_list = self.get_rows(indexes, as_list=True)
        return [x == value for x in compare_list]


Instruction:
Here you have a function in Python 3, explain what it does
def _pad_data(self, index_len):
        self._data.extend([None] * (index_len - len(self._data)))

Response: Pad the data in Series with None to ensure that data is the same length as index


Instruction:
Make a summary of the following Python 3 code
def sort_index(self):
        sort = sorted_list_indexes(self._index)
        # sort index
        self._index = blist([self._index[x] for x in sort]) if self._blist else [self._index[x] for x in sort]
        # sort data
        self._data = blist([self._data[x] for x in sort]) if self._blist else [self._data[x] for x in sort]

Response: Sort the Series by the index. The sort modifies the Series inplace


Instruction:
Can you generate the documentation for the following Python 3 function
def set(self, indexes, values=None):
        if isinstance(indexes, (list, blist)):
            self.set_rows(indexes, values)
        else:
            self.set_cell(indexes, values)

Response: This method will set the values of the given indexes in the Series.