text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(self, **kwargs): """ Method to search environments vip based on extends search. :param search: Dict containing QuerySets to find environments vip. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param fields: Array containing fields to override default fields. :param kind: Determine if result will be detailed ('detail') or basic ('basic'). :return: Dict containing environments vip """
return super(ApiEnvironmentVip, self).get( self.prepare_url('api/v3/environment-vip/', kwargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, ids, **kwargs): """ Method to get environments vip by their ids :param ids: List containing identifiers of environments vip :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param fields: Array containing fields to override default fields. :param kind: Determine if result will be detailed ('detail') or basic ('basic'). :return: Dict containing environments vip """
uri = build_uri_with_ids('api/v3/environment-vip/%s/', ids) return super(ApiEnvironmentVip, self).get( self.prepare_url(uri, kwargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, ids): """ Method to delete environments vip by their id's. :param ids: Identifiers of environments vip :return: None """
url = build_uri_with_ids('api/v3/environment-vip/%s/', ids) return super(ApiEnvironmentVip, self).delete(url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, environments): """ Method to update environments vip :param environments vip: List containing environments vip desired to updated :return: None """
data = {'environments_vip': environments} environments_ids = [str(env.get('id')) for env in environments] uri = 'api/v3/environment-vip/%s/' % ';'.join(environments_ids) return super(ApiEnvironmentVip, self).put(uri, data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, environments): """ Method to create environments vip :param environments vip: Dict containing environments vip desired to be created on database :return: None """
data = {'environments_vip': environments} uri = 'api/v3/environment-vip/' return super(ApiEnvironmentVip, self).post(uri, data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_ipv4(self, id_ip): """Get IPv4 by id. :param id_ip: ID of IPv4. :return: Dictionary with the following structure: :: {'ip': {'id': < id >, 'networkipv4': < networkipv4 >, 'oct4': < oct4 >, 'oct3': < oct3 >, 'oct2': < oct2 >, 'oct1': < oct1 >, 'descricao': < descricao >, '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 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def buscar_por_ip_ambiente(self, ip, id_environment): """Get IP with an associated environment. :param ip: IP address in the format x1.x2.x3.x4. :param id_environment: Identifier of the environment. Integer value and greater than zero. :return: Dictionary with the following structure: :: {'ip': {'id': < id >, 'id_vlan': < id_vlan >, 'oct4': < oct4 >, 'oct3': < oct3 >, 'oct2': < oct2 >, 'oct1': < oct1 >, 'descricao': < descricao > }} :raise IpNaoExisteError: IP is not registered or not associated with environment. :raise InvalidParameterError: The environment identifier and/or IP is/are null or invalid. :raise DataBaseError: Networkapi failed to access the database. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_available_ip4(self, id_network): """ Get a available IP in the network ipv4 :param id_network: Network identifier. Integer value and greater than zero. :return: Dictionary with the following structure: :: {'ip': {'ip': < available_ip >}} :raise IpNotAvailableError: Network dont have available IP for insert a new IP :raise NetworkIPv4NotFoundError: Network is not found :raise UserNotAuthorizedError: User dont have permission to get a available IP :raise InvalidParameterError: Network identifier is null 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_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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: :: :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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_ipv4_or_ipv6(self, ip): """ Get a Ipv4 or Ipv6 by IP :param ip: IPv4 or Ipv6. 'xxx.xxx.xxx.xxx or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx' :return: Dictionary with the following structure: :: {'ips': [{'oct4': < oct4 >, 'oct2': < oct2 >, 'oct3': < oct3 >, 'oct1': < oct1 >, 'version': < version >, or {'ips': [ {'block1': < block1 >, 'block2': < block2 >, 'block3': < block3 >, 'block4': < block4 >, 'block5': < block5 >, 'block6': < block6 >, 'block7': < block7 >, 'block8': < block8 >, :raise IpNaoExisteError: Ipv4 or Ipv6 not found. :raise UserNotAuthorizedError: User dont have permission to perform operation. :raise InvalidParameterError: Ip string 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 url = "ip/getbyoctblock/" code, xml = self.submit({'ip_map': ip_map}, 'POST', url) return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_ipv4(self, ip4, id_equip, descricao, id_net): """ Save a IP4 and associate with equipment :param ip4: An IP4 available to save in format x.x.x.x. :param id_equip: Equipment identifier. Integer value and greater than zero. :param descricao: IP description. :param id_net: Network identifier. Integer value and greater than zero. :return: Dictionary with the following structure: :: { ip: { id: <id_ip4>, oct1: <oct1>, oct2: <oct2>, oct3: <oct3>, oct4: <oct4>, equipamento: [ { all equipamentos related } ] , descricao: <descricao> } } """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def edit_ipv6(self, ip6, descricao, id_ip): """ Edit a IP6 :param ip6: An IP6 available to save in format xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx. :param descricao: IP description. :param id_ip: Ipv6 identifier. Integer value and greater than zero. :return: None """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_ip4_by_id(self, id_ip): """ Get an IP by ID :param id_ip: IP identifier. Integer value and greater than zero. :return: Dictionary with the following structure: :: { ips { id: <id_ip4>, oct1: <oct1>, oct2: <oct2>, oct3: <oct3>, oct4: <oct4>, equipamento: [ {all equipamentos related} ] , descricao: <descricao>} } :raise IpNotAvailableError: Network dont have available IP. :raise NetworkIPv4NotFoundError: Network was not found. :raise UserNotAuthorizedError: User dont have permission to perform operation. :raise InvalidParameterError: Ip 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'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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_ipv6(self, ip6, id_equip, descricao, id_net): """ Save an IP6 and associate with equipment :param ip6: An IP6 available to save in format xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx. :param id_equip: Equipment identifier. Integer value and greater than zero. :param descricao: IPv6 description. :param id_net: Network identifier. Integer value and greater than zero. :return: Dictionary with the following structure: :: {'ipv6': {'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 } ], }} """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_ip4(self, id_ip): """ Delete an IP4 :param id_ip: Ipv4 identifier. Integer value and greater than zero. :return: None :raise IpNotFoundError: IP is not registered. :raise DataBaseError: Networkapi failed to access the database. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_ip6_by_network(self, id_network): """List IPv6 from network. :param id_network: Network ipv6 identifier. Integer value and greater than zero. :return: Dictionary with the following structure: :: {'ip': {'id': < id >, 'id_vlan': < id_vlan >, 'block1': <block1>, 'block2': <block2>, 'block3': <block3>, 'block4': <block4>, 'block5': <block5>, 'block6': <block6>, 'block7': <block7>, 'block8': <block8>, 'descricao': < description > 'equipamento': [ { all name equipamentos related } ], }} :raise IpNaoExisteError: Network does not have any ips. :raise InvalidParameterError: Network identifier is none or invalid. :raise DataBaseError: Networkapi failed to access the database. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_ipv6_environment(self, ipv6, id_environment): """Get IPv6 with an associated environment. :param ipv6: IPv6 address in the format x1:x2:x3:x4:x5:x6:x7:x8. :param id_environment: Environment identifier. Integer value and greater than zero. :return: Dictionary with the following structure: :: {'ipv6': {'id': < id >, 'id_vlan': < id_vlan >, 'bloco1': < bloco1 >, 'bloco2': < bloco2 >, 'bloco3': < bloco3 >, 'bloco4': < bloco4 >, 'bloco5': < bloco5 >, 'bloco6': < bloco6 >, 'bloco7': < bloco7 >, 'bloco8': < bloco8 >, 'descricao': < descricao > }} :raise IpNaoExisteError: IPv6 is not registered or is not associated to the environment. :raise AmbienteNaoExisteError: Environment not found. :raise InvalidParameterError: Environment identifier and/or IPv6 string is/are none 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_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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assoc_ipv4(self, id_ip, id_equip, id_net): """ Associate an IP4 with equipment. :param id_ip: IPv4 identifier. :param id_equip: Equipment identifier. Integer value and greater than zero. :param id_net: Network identifier. Integer value and greater than zero. :return: None :raise InvalidParameterError: IPv4, Equipment or Network identifier is none 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'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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assoc_ipv6(self, id_ip, id_equip, id_net): """ Associate an IP6 with equipment. :param id_ip: IPv6 identifier. :param id_equip: Equipment identifier. Integer value and greater than zero. :param id_net: Network identifier. Integer value and greater than zero. :return: None :raise InvalidParameterError: IPv6, Equipment or Network identifier is none 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'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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listar(self): """List all network types. :return: Following dictionary: :: {'net_type': [{'id': < id_tipo_rede >, :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
code, xml = self.submit(None, 'GET', 'net_type/') key = 'net_type' return get_list_map(self.response(code, xml, [key]), key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inserir(self, name): """Insert new network type and return its identifier. :param name: Network type name. :return: Following dictionary: {'net_type': {'id': < id >}} :raise InvalidParameterError: Network type is none or invalid. :raise NomeTipoRedeDuplicadoError: A network type with this name already exists. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def alterar(self, id_net_type, name): """Edit network type by its identifier. :param id_net_type: Network type identifier. :param name: Network type name. :return: None :raise InvalidParameterError: Network type identifier and/or name is(are) none or invalid. :raise TipoRedeNaoExisteError: Network type does not exist. :raise NomeTipoRedeDuplicadoError: Network type name already exists. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remover(self, id_net_type): """Remove network type by its identifier. :param id_net_type: Network type identifier. :return: None :raise TipoRedeNaoExisteError: Network type does not exist. :raise TipoRedeError: Network type is associated with network. :raise InvalidParameterError: Network type is none 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_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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rbnf_lexing(text: str): """Read loudly for documentation."""
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def regex_lexer(regex_pat): """ generate token names' cache """
if isinstance(regex_pat, str): regex_pat = re.compile(regex_pat) def f(inp_str, pos): m = regex_pat.match(inp_str, pos) return m.group() if m else None elif hasattr(regex_pat, 'match'): def f(inp_str, pos): m = regex_pat.match(inp_str, pos) return m.group() if m else None else: regex_pats = tuple(re.compile(e) for e in regex_pat) def f(inp_str, pos): for each_pat in regex_pats: m = each_pat.match(inp_str, pos) if m: return m.group() return f
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ignore(self, *ignore_lst: str): """ ignore a set of tokens with specific names """
def stream(): for each in ignore_lst: each = ConstStrPool.cast_to_const(each) yield id(each), each self.ignore_lst.update(stream())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _decode_POST_value(request, field_name, default=None): """Helper to decode a request field into unicode based on charsets encoding. Args: request: the HttpRequest object. field_name: the field expected in the request.POST Kwargs: default: if passed in then field is optional and default is used if not found; if None, then assume field exists, which will raise an error if it does not. Returns: the contents of the string encoded using the related charset from the requests.POST['charsets'] dictionary (or 'utf-8' if none specified). """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_recipients(self, array): """Returns an iterator of objects from the array [["[email protected]", "Name"]] """
for address, name in array: if not name: yield address else: yield "\"%s\" <%s>" % (name, address)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _log_request(request): """Helper function to dump out debug info."""
logger.debug("Inbound email received") for k, v in list(request.POST.items()): logger.debug("- POST['%s']='%s'" % (k, v)) for n, f in list(request.FILES.items()): logger.debug("- FILES['%s']: '%s', %sB", n, f.content_type, f.size)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive_inbound_email(request): """Receives inbound email from SendGrid. This view receives the email from SendGrid, parses the contents, logs the message and the fires the inbound_email signal. """
# 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_backend_class(): """Return reference to the configured backed 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sorted_exists(values, x): """ For list, values, returns the insert position for item x and whether the item already exists in the list. This allows one function call to return either the index to overwrite an existing value in the list, or the index to insert a new item in the list and keep the list in sorted order. :param values: list :param x: item :return: (exists, index) tuple """
i = bisect_left(values, x) j = bisect_right(values, x) exists = x in values[i:j] return exists, i
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sorted_index(values, x): """ For list, values, returns the index location of element x. If x does not exist will raise an error. :param values: list :param x: item :return: integer index """
i = bisect_left(values, x) j = bisect_right(values, x) return values[i:j].index(x) + i
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def runDia(diagram): """Generate the diagrams using Dia."""
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_locations(self, locations, as_list=False): """ For list of locations return a Series or list of the values. :param locations: list of index locations :param as_list: True to return a list of values :return: Series or list """
indexes = [self._index[x] for x in locations] return self.get(indexes, as_list)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort_index(self): """ Sort the Series by the index. The sort modifies the Series inplace :return: nothing """
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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set(self, indexes, values=None): """ Given indexes will set a sub-set of the Series to the values provided. This method will direct to the below methods based on what types are passed in for the indexes. If the indexes contains values not in the Series then new rows or columns will be added. :param indexes: indexes value, list of indexes values, or a list of booleans. :param values: value or list of values to set. If a list then must be the same length as the indexes parameter. :return: nothing """
if isinstance(indexes, (list, blist)): self.set_rows(indexes, values) else: self.set_cell(indexes, values)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_row(self, index): """ Add a new row to the Series :param index: index of the new row :return: nothing """
self._index.append(index) self._data.append(None)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _insert_row(self, i, index): """ Insert a new row in the Series. :param i: index location to insert :param index: index value to insert into the index list :return: nothing """
if i == len(self._index): self._add_row(index) else: self._index.insert(i, index) self._data.insert(i, None)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_missing_rows(self, indexes): """ Given a list of indexes, find all the indexes that are not currently in the Series and make a new row for that index by appending to the Series. This does not maintain sorted order for the index. :param indexes: list of indexes :return: nothing """
new_indexes = [x for x in indexes if x not in self._index] for x in new_indexes: self._add_row(x)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _insert_missing_rows(self, indexes): """ Given a list of indexes, find all the indexes that are not currently in the Series and make a new row for that index, inserting into the index. This requires the Series to be sorted=True :param indexes: list of indexes :return: nothing """
new_indexes = [x for x in indexes if x not in self._index] for x in new_indexes: self._insert_row(bisect_left(self._index, x), x)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_cell(self, index, value): """ Sets the value of a single cell. If the index is not in the current index then a new index will be created. :param index: index value :param value: value to set :return: nothing """
if self._sort: exists, i = sorted_exists(self._index, index) if not exists: self._insert_row(i, index) else: try: i = self._index.index(index) except ValueError: i = len(self._index) self._add_row(index) self._data[i] = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_rows(self, index, values=None): """ Set rows to a single value or list of values. If any of the index values are not in the current indexes then a new row will be created. :param index: list of index values or list of booleans. If a list of booleans then the list must be the same\ length as the Series :param values: either a single value or a list. The list must be the same length as the index list if the index\ list is values, or the length of the True values in the index list if the index list is booleans :return: nothing """
if all([isinstance(i, bool) for i in index]): # boolean list if not isinstance(values, (list, blist)): # single value provided, not a list, so turn values into list values = [values for x in index if x] if len(index) != len(self._index): raise ValueError('boolean index list must be same size of existing index') if len(values) != index.count(True): raise ValueError('length of values list must equal number of True entries in index list') indexes = [i for i, x in enumerate(index) if x] for x, i in enumerate(indexes): self._data[i] = values[x] else: # list of index if not isinstance(values, (list, blist)): # single value provided, not a list, so turn values into list values = [values for _ in index] if len(values) != len(index): raise ValueError('length of values and index must be the same.') # insert or append indexes as needed if self._sort: exists_tuples = list(zip(*[sorted_exists(self._index, x) for x in index])) exists = exists_tuples[0] indexes = exists_tuples[1] if not all(exists): self._insert_missing_rows(index) indexes = [sorted_index(self._index, x) for x in index] else: try: # all index in current index indexes = [self._index.index(x) for x in index] except ValueError: # new rows need to be added self._add_missing_rows(index) indexes = [self._index.index(x) for x in index] for x, i in enumerate(indexes): self._data[i] = values[x]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_locations(self, locations, values): """ For a list of locations set the values. :param locations: list of index locations :param values: list of values or a single value :return: nothing """
indexes = [self._index[x] for x in locations] self.set(indexes, values)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_row(self, index, value): """ Appends a row of value to the end of the data. Be very careful with this function as for sorted Series it will not enforce sort order. Use this only for speed when needed, be careful. :param index: index :param value: value :return: nothing """
if index in self._index: raise IndexError('index already in Series') self._index.append(index) self._data.append(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_rows(self, indexes, values): """ Appends values to the end of the data. Be very careful with this function as for sort DataFrames it will not enforce sort order. Use this only for speed when needed, be careful. :param indexes: list of indexes to append :param values: list of values to append :return: nothing """
# check that the values data is less than or equal to the length of the indexes if len(values) != len(indexes): raise ValueError('length of values is not equal to length of indexes') # check the indexes are not duplicates combined_index = self._index + indexes if len(set(combined_index)) != len(combined_index): raise IndexError('duplicate indexes in Series') # append index value self._index.extend(indexes) self._data.extend(values)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, indexes): """ Delete rows from the DataFrame :param indexes: either a list of values or list of booleans for the rows to delete :return: nothing """
indexes = [indexes] if not isinstance(indexes, (list, blist)) else indexes if all([isinstance(i, bool) for i in indexes]): # boolean list if len(indexes) != len(self._index): raise ValueError('boolean indexes list must be same size of existing indexes') indexes = [i for i, x in enumerate(indexes) if x] else: indexes = [sorted_index(self._index, x) for x in indexes] if self._sort \ else [self._index.index(x) for x in indexes] indexes = sorted(indexes, reverse=True) # need to sort and reverse list so deleting works for i in indexes: del self._data[i] # now remove from index for i in indexes: del self._index[i]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset_index(self): """ Resets the index of the Series to simple integer list and the index name to 'index'. :return: nothing """
self.index = list(range(self.__len__())) self.index_name = 'index'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def value(self, indexes, int_as_index=False): """ Wrapper function for get. It will return a list, no index. If the indexes are integers it will be assumed that they are locations unless int_as_index = True. If the indexes are locations then they will be rotated to the left by offset number of locations. :param indexes: integer location, single index, list of indexes or list of boolean :param int_as_index: if True then will treat int index values as indexes and not locations :return: value or list of values """
# single integer value if isinstance(indexes, int): if int_as_index: return self.get(indexes, as_list=True) else: indexes = indexes - self._offset return self._data[indexes] # slice elif isinstance(indexes, slice): if isinstance(indexes.start, int) and not int_as_index: # treat as location start = indexes.start - self._offset stop = indexes.stop - self._offset + 1 # to capture the last value # check locations are valid and will not return empty if start > stop: raise IndexError('end of slice is before start of slice') if (start > 0 > stop) or (start < 0 < stop): raise IndexError('slide indexes invalid with given offset:%f' % self._offset) # where end is the last element if (start < 0) and stop == 0: return self._data[start:] return self._data[start:stop] else: # treat as index indexes = self._slice_index(indexes) return self.get(indexes, as_list=True) # list of booleans elif all([isinstance(x, bool) for x in indexes]): return self.get(indexes, as_list=True) # list of values elif isinstance(indexes, list): if int_as_index or not isinstance(indexes[0], int): return self.get(indexes, as_list=True) else: indexes = [x - self._offset for x in indexes] return self.get_locations(indexes, as_list=True) # just a single value else: return self.get(indexes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_dataframe(cls, dataframe, column, offset=0): """ Creates and return a Series from a DataFrame and specific column :param dataframe: raccoon DataFrame :param column: column name :param offset: offset value must be provided as there is no equivalent for a DataFrame :return: Series """
return cls(data=dataframe.get_entire_column(column, as_list=True), index=dataframe.index, data_name=column, index_name=dataframe.index_name, sort=dataframe.sort, offset=offset)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_series(cls, series, offset=0): """ Creates and return a Series from a Series :param series: raccoon Series :param offset: offset value must be provided as there is no equivalent for a DataFrame :return: Series """
return cls(data=series.data, index=series.index, data_name=series.data_name, index_name=series.index_name, sort=series.sort, offset=offset)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, timeout=None): """Retrieve results from all the output tubes."""
valid = False result = None for tube in self._output_tubes: if timeout: valid, result = tube.get(timeout) if valid: result = result[0] else: result = tube.get()[0] if timeout: return valid, result return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getLeaves(self): """Return the downstream leaf stages of this stage."""
result = list() if not self._next_stages: result.append(self) else: for stage in self._next_stages: leaves = stage.getLeaves() result += leaves return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build(self): """Create and start up the internal workers."""
# If there's no output tube, it means that this stage # is at the end of a fork (hasn't been linked to any stage downstream). # Therefore, create one output tube. if not self._output_tubes: self._output_tubes.append(self._worker_class.getTubeClass()()) self._worker_class.assemble( self._worker_args, self._input_tube, self._output_tubes, self._size, self._disable_result, self._do_stop_task, ) # Build all downstream stages. for stage in self._next_stages: stage.build()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sort_columns(self, columns_list): """ Given a list of column names will sort the DataFrame columns to match the given order :param columns_list: list of column names. Must include all column names :return: nothing """
if not (all([x in columns_list for x in self._columns]) and all([x in self._columns for x in columns_list])): raise ValueError( 'columns_list must be all in current columns, and all current columns must be in columns_list') new_sort = [self._columns.index(x) for x in columns_list] self._data = blist([self._data[x] for x in new_sort]) if self._blist else [self._data[x] for x in new_sort] self._columns = blist([self._columns[x] for x in new_sort]) if self._blist \ else [self._columns[x] for x in new_sort]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pad_data(self, max_len=None): """ Pad the data in DataFrame with [None} to ensure that all columns have the same length. :param max_len: If provided will extend all columns to this length, if not then will use the longest column :return: nothing """
if not max_len: max_len = max([len(x) for x in self._data]) for _, col in enumerate(self._data): col.extend([None] * (max_len - len(col)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, indexes=None, columns=None, as_list=False, as_dict=False): """ Given indexes and columns will return a sub-set of the DataFrame. This method will direct to the below methods based on what types are passed in for the indexes and columns. 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. If None then all indexes are used :param columns: column name or list of column names. If None then all columns are used :param as_list: if True then return the values as a list, if False return a DataFrame. This is only used if the get is for a single column :param as_dict: if True then return the values as a dictionary, if False return a DataFrame. This is only used if the get is for a single row :return: either DataFrame, list, dict or single value. The return is a shallow copy """
if (indexes is None) and (columns is not None) and (not isinstance(columns, (list, blist))): return self.get_entire_column(columns, as_list) if indexes is None: indexes = [True] * len(self._index) if columns is None: columns = [True] * len(self._columns) if isinstance(indexes, (list, blist)) and isinstance(columns, (list, blist)): return self.get_matrix(indexes, columns) elif isinstance(indexes, (list, blist)) and (not isinstance(columns, (list, blist))): return self.get_rows(indexes, columns, as_list) elif (not isinstance(indexes, (list, blist))) and isinstance(columns, (list, blist)): return self.get_columns(indexes, columns, as_dict) else: return self.get_cell(indexes, columns)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_cell(self, index, column): """ For a single index and column value return the value of the cell :param index: index value :param column: column name :return: value """
i = sorted_index(self._index, index) if self._sort else self._index.index(index) c = self._columns.index(column) return self._data[c][i]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_rows(self, indexes, column, as_list=False): """ For a list of indexes and a single column name 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 column: single column name :param as_list: if True return a list, if False return DataFrame :return: DataFrame is as_list if False, a list if as_list is True """
c = self._columns.index(column) 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[c] index = self._index else: data = list(compress(self._data[c], 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[c][i] for i in locations] index = [self._index[i] for i in locations] return data if as_list else DataFrame(data={column: data}, index=index, index_name=self._index_name, sort=self._sort)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_columns(self, index, columns=None, as_dict=False): """ For a single index and list of column names return a DataFrame of the values in that index as either a dict or a DataFrame :param index: single index value :param columns: list of column names :param as_dict: if True then return the result as a dictionary :return: DataFrame or dictionary """
i = sorted_index(self._index, index) if self._sort else self._index.index(index) return self.get_location(i, columns, as_dict)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_entire_column(self, column, as_list=False): """ Shortcut method to retrieve a single column all rows. Since this is a common use case this method will be faster than the more general method. :param column: single column name :param as_list: if True return a list, if False return DataFrame :return: DataFrame is as_list if False, a list if as_list is True """
c = self._columns.index(column) data = self._data[c] return data if as_list else DataFrame(data={column: data}, index=self._index, index_name=self._index_name, sort=self._sort)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_matrix(self, indexes, columns): """ For a list of indexes and list of columns return a DataFrame of the values. :param indexes: either a list of index values or a list of booleans with same length as all indexes :param columns: list of column names :return: DataFrame """
if all([isinstance(i, bool) for i in indexes]): # boolean list is_bool_indexes = True if len(indexes) != len(self._index): raise ValueError('boolean index list must be same size of existing index') bool_indexes = indexes indexes = list(compress(self._index, indexes)) else: is_bool_indexes = False locations = [sorted_index(self._index, x) for x in indexes] if self._sort \ else [self._index.index(x) for x in indexes] if all([isinstance(i, bool) for i in columns]): # boolean list if len(columns) != len(self._columns): raise ValueError('boolean column list must be same size of existing columns') columns = list(compress(self._columns, columns)) col_locations = [self._columns.index(x) for x in columns] data_dict = dict() for c in col_locations: data_dict[self._columns[c]] = list(compress(self._data[c], bool_indexes)) if is_bool_indexes \ else [self._data[c][i] for i in locations] return DataFrame(data=data_dict, index=indexes, columns=columns, index_name=self._index_name, sort=self._sort)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_locations(self, locations, columns=None, **kwargs): """ For list of locations and list of columns return a DataFrame of the values. :param locations: list of index locations :param columns: list of column names :param kwargs: will pass along these parameters to the get() method :return: DataFrame """
indexes = [self._index[x] for x in locations] return self.get(indexes, columns, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _insert_row(self, i, index): """ Insert a new row in the DataFrame. :param i: index location to insert :param index: index value to insert into the index list :return: nothing """
if i == len(self._index): self._add_row(index) else: self._index.insert(i, index) for c in range(len(self._columns)): self._data[c].insert(i, None)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_row(self, index): """ Add a new row to the DataFrame :param index: index of the new row :return: nothing """
self._index.append(index) for c, _ in enumerate(self._columns): self._data[c].append(None)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_column(self, column): """ Add a new column to the DataFrame :param column: column name :return: nothing """
self._columns.append(column) if self._blist: self._data.append(blist([None] * len(self._index))) else: self._data.append([None] * len(self._index))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set(self, indexes=None, columns=None, values=None): """ Given indexes and columns will set a sub-set of the DataFrame to the values provided. This method will direct to the below methods based on what types are passed in for the indexes and columns. If the indexes or columns contains values not in the DataFrame then new rows or columns will be added. :param indexes: indexes value, list of indexes values, or a list of booleans. If None then all indexes are used :param columns: columns name, if None then all columns are used. Currently can only handle a single column or\ all columns :param values: value or list of values to set (index, column) to. If setting just a single row, then must be a\ dict where the keys are the column names. If a list then must be the same length as the indexes parameter, if\ indexes=None, then must be the same and length of DataFrame :return: nothing """
if (indexes is not None) and (columns is not None): if isinstance(indexes, (list, blist)): self.set_column(indexes, columns, values) else: self.set_cell(indexes, columns, values) elif (indexes is not None) and (columns is None): self.set_row(indexes, values) elif (indexes is None) and (columns is not None): self.set_column(indexes, columns, values) else: raise ValueError('either or both of indexes or columns must be provided')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_row(self, index, values): """ Sets the values of the columns in a single row. :param index: index value :param values: dict with the keys as the column names and the values what to set that column to :return: nothing """
if self._sort: exists, i = sorted_exists(self._index, index) if not exists: self._insert_row(i, index) else: try: i = self._index.index(index) except ValueError: # new row i = len(self._index) self._add_row(index) if isinstance(values, dict): if not (set(values.keys()).issubset(self._columns)): raise ValueError('keys of values are not all in existing columns') for c, column in enumerate(self._columns): self._data[c][i] = values.get(column, self._data[c][i]) else: raise TypeError('cannot handle values of this type.')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_column(self, index=None, column=None, values=None): """ Set a column to a single value or list of values. If any of the index values are not in the current indexes then a new row will be created. :param index: 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 column: column name :param values: either a single value or a list. The list must be the same length as the index list if the index\ list is values, or the length of the True values in the index list if the index list is booleans :return: nothing """
try: c = self._columns.index(column) except ValueError: # new column c = len(self._columns) self._add_column(column) if index: # index was provided if all([isinstance(i, bool) for i in index]): # boolean list if not isinstance(values, (list, blist)): # single value provided, not a list, so turn values into list values = [values for x in index if x] if len(index) != len(self._index): raise ValueError('boolean index list must be same size of existing index') if len(values) != index.count(True): raise ValueError('length of values list must equal number of True entries in index list') indexes = [i for i, x in enumerate(index) if x] for x, i in enumerate(indexes): self._data[c][i] = values[x] else: # list of index if not isinstance(values, (list, blist)): # single value provided, not a list, so turn values into list values = [values for _ in index] if len(values) != len(index): raise ValueError('length of values and index must be the same.') # insert or append indexes as needed if self._sort: exists_tuples = list(zip(*[sorted_exists(self._index, x) for x in index])) exists = exists_tuples[0] indexes = exists_tuples[1] if not all(exists): self._insert_missing_rows(index) indexes = [sorted_index(self._index, x) for x in index] else: try: # all index in current index indexes = [self._index.index(x) for x in index] except ValueError: # new rows need to be added self._add_missing_rows(index) indexes = [self._index.index(x) for x in index] for x, i in enumerate(indexes): self._data[c][i] = values[x] else: # no index, only values if not isinstance(values, (list, blist)): # values not a list, turn into one of length same as index values = [values for _ in self._index] if len(values) != len(self._index): raise ValueError('values list must be at same length as current index length.') else: self._data[c] = blist(values) if self._blist else values
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_row(self, index, values, new_cols=True): """ Appends a row of values to the end of the data. If there are new columns in the values and new_cols is True they will be added. Be very careful with this function as for sort DataFrames it will not enforce sort order. Use this only for speed when needed, be careful. :param index: value of the index :param values: dictionary of values :param new_cols: if True add new columns in values, if False ignore :return: nothing """
if index in self._index: raise IndexError('index already in DataFrame') if new_cols: for col in values: if col not in self._columns: self._add_column(col) # append index value self._index.append(index) # add data values, if not in values then use None for c, col in enumerate(self._columns): self._data[c].append(values.get(col, None))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_rows(self, indexes, values, new_cols=True): """ Appends rows of values to the end of the data. If there are new columns in the values and new_cols is True they will be added. Be very careful with this function as for sort DataFrames it will not enforce sort order. Use this only for speed when needed, be careful. :param indexes: list of indexes :param values: dictionary of values where the key is the column name and the value is a list :param new_cols: if True add new columns in values, if False ignore :return: nothing """
# check that the values data is less than or equal to the length of the indexes for column in values: if len(values[column]) > len(indexes): raise ValueError('length of %s column in values is longer than indexes' % column) # check the indexes are not duplicates combined_index = self._index + indexes if len(set(combined_index)) != len(combined_index): raise IndexError('duplicate indexes in DataFrames') if new_cols: for col in values: if col not in self._columns: self._add_column(col) # append index value self._index.extend(indexes) # add data values, if not in values then use None for c, col in enumerate(self._columns): self._data[c].extend(values.get(col, [None] * len(indexes))) self._pad_data()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_dict(self, index=True, ordered=False): """ Returns a dict where the keys are the column names and the values are lists of the values for that column. :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 DataFrame :return: dict or OrderedDict() """
result = OrderedDict() if ordered else dict() if index: result.update({self._index_name: self._index}) if ordered: data_dict = [(column, self._data[i]) for i, column in enumerate(self._columns)] else: data_dict = {column: self._data[i] for i, column in enumerate(self._columns)} result.update(data_dict) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rename_columns(self, rename_dict): """ Renames the columns :param rename_dict: dict where the keys are the current column names and the values are the new names :return: nothing """
if not all([x in self._columns for x in rename_dict.keys()]): raise ValueError('all dictionary keys must be in current columns') for current in rename_dict.keys(): self._columns[self._columns.index(current)] = rename_dict[current]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_columns(self, columns): """ Delete columns from the DataFrame :param columns: list of columns to delete :return: nothing """
columns = [columns] if not isinstance(columns, (list, blist)) else columns if not all([x in self._columns for x in columns]): raise ValueError('all columns must be in current columns') for column in columns: c = self._columns.index(column) del self._data[c] del self._columns[c] if not len(self._data): # if all the columns have been deleted, remove index self.index = list()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort_index(self): """ Sort the DataFrame by the index. The sort modifies the DataFrame inplace :return: nothing """
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] # each column for c in range(len(self._data)): self._data[c] = blist([self._data[c][i] for i in sort]) if self._blist else [self._data[c][i] for i in sort]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_integrity(self): """ Validate the integrity of the DataFrame. This checks that the indexes, column names and internal data are not corrupted. Will raise an error if there is a problem. :return: nothing """
self._validate_columns(self._columns) self._validate_index(self._index) self._validate_data()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append(self, data_frame): """ Append another DataFrame to this DataFrame. If the new data_frame has columns that are not in the current DataFrame then new columns will be created. All of the indexes in the data_frame must be different from the current indexes or will raise an error. :param data_frame: DataFrame to append :return: nothing """
if len(data_frame) == 0: # empty DataFrame, do nothing return data_frame_index = data_frame.index combined_index = self._index + data_frame_index if len(set(combined_index)) != len(combined_index): raise ValueError('duplicate indexes in DataFrames') for c, column in enumerate(data_frame.columns): if PYTHON3: self.set(indexes=data_frame_index, columns=column, values=data_frame.data[c].copy()) else: self.set(indexes=data_frame_index, columns=column, values=data_frame.data[c][:])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, left_column, right_column, indexes=None): """ Math helper method that adds element-wise two columns. If indexes are not None then will only perform the math on that sub-set of the columns. :param left_column: first column name :param right_column: second column name :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 :return: list """
left_list, right_list = self._get_lists(left_column, right_column, indexes) return [l + r for l, r in zip(left_list, right_list)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isin(self, column, compare_list): """ Returns a boolean list where each elements is whether that element in the column is in the compare_list. :param column: single column name, does not work for multiple columns :param compare_list: list of items to compare to :return: list of booleans """
return [x in compare_list for x in self._data[self._columns.index(column)]]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iterrows(self, index=True): """ Iterates over DataFrame rows as dictionary of the values. The index will be included. :param index: if True include the index in the results :return: dictionary """
for i in range(len(self._index)): row = {self._index_name: self._index[i]} if index else dict() for c, col in enumerate(self._columns): row[col] = self._data[c][i] yield row
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def itertuples(self, index=True, name='Raccoon'): """ Iterates over DataFrame rows as tuple of the values. :param index: if True then include the index :param name: name of the namedtuple :return: namedtuple """
fields = [self._index_name] if index else list() fields.extend(self._columns) row_tuple = namedtuple(name, fields) for i in range(len(self._index)): row = {self._index_name: self._index[i]} if index else dict() for c, col in enumerate(self._columns): row[col] = self._data[c][i] yield row_tuple(**row)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_json(cls, json_string): """ Creates and return a DataFrame from a JSON of the type created by to_json :param json_string: JSON :return: DataFrame """
input_dict = json.loads(json_string) # convert index to tuple if required if input_dict['index'] and isinstance(input_dict['index'][0], list): input_dict['index'] = [tuple(x) for x in input_dict['index']] # convert index_name to tuple if required if isinstance(input_dict['meta_data']['index_name'], list): input_dict['meta_data']['index_name'] = tuple(input_dict['meta_data']['index_name']) data = input_dict['data'] if input_dict['data'] else None return cls(data=data, index=input_dict['index'], **input_dict['meta_data'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_frame_equal(left, right, data_function=None, data_args=None): """ For unit testing equality of two DataFrames. :param left: first DataFrame :param right: second DataFrame :param data_function: if provided will use this function to assert compare the df.data :param data_args: arguments to pass to the data_function :return: nothing """
if data_function: data_args = {} if not data_args else data_args data_function(left.data, right.data, **data_args) else: assert left.data == right.data assert left.index == right.index assert left.columns == right.columns assert left.index_name == right.index_name assert left.sort == right.sort assert left.blist == right.blist