repository_name
stringlengths 7
55
| func_path_in_repository
stringlengths 4
223
| func_name
stringlengths 1
134
| whole_func_string
stringlengths 75
104k
| language
stringclasses 1
value | func_code_string
stringlengths 75
104k
| func_code_tokens
sequencelengths 19
28.4k
| func_documentation_string
stringlengths 1
46.9k
| func_documentation_tokens
sequencelengths 1
1.97k
| split_name
stringclasses 1
value | func_code_url
stringlengths 87
315
|
---|---|---|---|---|---|---|---|---|---|---|
globocom/GloboNetworkAPI-client-python | networkapiclient/Ip.py | Ip.find_ips_by_equip | 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']) | python | 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']) | [
"def",
"find_ips_by_equip",
"(",
"self",
",",
"id_equip",
")",
":",
"url",
"=",
"'ip/getbyequip/'",
"+",
"str",
"(",
"id_equip",
")",
"+",
"\"/\"",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"None",
",",
"'GET'",
",",
"url",
")",
"return",
"self",
".",
"response",
"(",
"code",
",",
"xml",
",",
"[",
"'ipv4'",
",",
"'ipv6'",
"]",
")"
] | 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. | [
"Get",
"Ips",
"related",
"to",
"equipment",
"by",
"its",
"identifier"
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Ip.py#L535-L572 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Ip.py | Ip.find_ip6_by_id | 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) | python | 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) | [
"def",
"find_ip6_by_id",
"(",
"self",
",",
"id_ip",
")",
":",
"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",
")"
] | 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. | [
"Get",
"an",
"IP6",
"by",
"ID"
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Ip.py#L574-L614 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Ip.py | Ip.save_ipv6 | 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) | python | 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) | [
"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",
")"
] | 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 } ], }} | [
"Save",
"an",
"IP6",
"and",
"associate",
"with",
"equipment"
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Ip.py#L616-L663 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Ip.py | Ip.delete_ip4 | 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) | python | 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) | [
"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",
")"
] | 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. | [
"Delete",
"an",
"IP4"
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Ip.py#L665-L684 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Ip.py | Ip.find_ip6_by_network | 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) | python | 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) | [
"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",
")"
] | 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. | [
"List",
"IPv6",
"from",
"network",
"."
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Ip.py#L743-L779 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Ip.py | Ip.search_ipv6_environment | 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) | python | 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) | [
"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",
")"
] | 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. | [
"Get",
"IPv6",
"with",
"an",
"associated",
"environment",
"."
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Ip.py#L781-L822 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Ip.py | Ip.assoc_ipv4 | 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) | python | 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) | [
"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",
")"
] | 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. | [
"Associate",
"an",
"IP4",
"with",
"equipment",
"."
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Ip.py#L824-L860 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Ip.py | Ip.assoc_ipv6 | 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) | python | 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) | [
"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",
")"
] | 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. | [
"Associate",
"an",
"IP6",
"with",
"equipment",
"."
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Ip.py#L862-L898 |
globocom/GloboNetworkAPI-client-python | networkapiclient/TipoRede.py | TipoRede.listar | def listar(self):
"""List all network types.
:return: Following dictionary:
::
{'net_type': [{'id': < id_tipo_rede >,
'name': < nome_tipo_rede >}, ... other network types ...]}
: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) | python | def listar(self):
"""List all network types.
:return: Following dictionary:
::
{'net_type': [{'id': < id_tipo_rede >,
'name': < nome_tipo_rede >}, ... other network types ...]}
: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) | [
"def",
"listar",
"(",
"self",
")",
":",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"None",
",",
"'GET'",
",",
"'net_type/'",
")",
"key",
"=",
"'net_type'",
"return",
"get_list_map",
"(",
"self",
".",
"response",
"(",
"code",
",",
"xml",
",",
"[",
"key",
"]",
")",
",",
"key",
")"
] | List all network types.
:return: Following dictionary:
::
{'net_type': [{'id': < id_tipo_rede >,
'name': < nome_tipo_rede >}, ... other network types ...]}
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response. | [
"List",
"all",
"network",
"types",
"."
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/TipoRede.py#L38-L55 |
globocom/GloboNetworkAPI-client-python | networkapiclient/TipoRede.py | TipoRede.inserir | 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) | python | 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) | [
"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",
")"
] | 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. | [
"Insert",
"new",
"network",
"type",
"and",
"return",
"its",
"identifier",
"."
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/TipoRede.py#L57-L76 |
globocom/GloboNetworkAPI-client-python | networkapiclient/TipoRede.py | TipoRede.alterar | 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) | python | 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) | [
"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",
")"
] | 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. | [
"Edit",
"network",
"type",
"by",
"its",
"identifier",
"."
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/TipoRede.py#L78-L104 |
globocom/GloboNetworkAPI-client-python | networkapiclient/TipoRede.py | TipoRede.remover | 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) | python | 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) | [
"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",
")"
] | 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. | [
"Remove",
"network",
"type",
"by",
"its",
"identifier",
"."
] | train | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/TipoRede.py#L106-L127 |
thautwarm/RBNF | rbnf/cli.py | cc | 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) | python | 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) | [
"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'",
")",
":",
"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",
")"
] | rbnf source code compiler. | [
"rbnf",
"source",
"code",
"compiler",
"."
] | train | https://github.com/thautwarm/RBNF/blob/cceec88c90f7ec95c160cfda01bfc532610985e0/rbnf/cli.py#L11-L28 |
thautwarm/RBNF | rbnf/cli.py | run | 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) | python | 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) | [
"def",
"run",
"(",
"filename",
":",
"'python file generated by `rbnf` command, or rbnf sour file'",
",",
"opt",
":",
"'optimize switch'",
"=",
"False",
")",
":",
"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",
")"
] | You can apply immediate tests on your parser.
P.S: use `--opt` option takes longer starting time. | [
"You",
"can",
"apply",
"immediate",
"tests",
"on",
"your",
"parser",
".",
"P",
".",
"S",
":",
"use",
"--",
"opt",
"option",
"takes",
"longer",
"starting",
"time",
"."
] | train | https://github.com/thautwarm/RBNF/blob/cceec88c90f7ec95c160cfda01bfc532610985e0/rbnf/cli.py#L32-L103 |
thautwarm/RBNF | rbnf/auto_lexer/rbnf_lexer.py | rbnf_lexing | 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 | python | 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 | [
"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"
] | Read loudly for documentation. | [
"Read",
"loudly",
"for",
"documentation",
"."
] | train | https://github.com/thautwarm/RBNF/blob/cceec88c90f7ec95c160cfda01bfc532610985e0/rbnf/auto_lexer/rbnf_lexer.py#L30-L96 |
thautwarm/RBNF | rbnf/std/common.py | recover_codes | 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 | python | 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 | [
"def",
"recover_codes",
"(",
"tokens",
":",
"Iterator",
"[",
"Tokenizer",
"]",
")",
"->",
"str",
":",
"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"
] | from a series of tokenizers to code string. (preserve the indentation) | [
"from",
"a",
"series",
"of",
"tokenizers",
"to",
"code",
"string",
".",
"(",
"preserve",
"the",
"indentation",
")"
] | train | https://github.com/thautwarm/RBNF/blob/cceec88c90f7ec95c160cfda01bfc532610985e0/rbnf/std/common.py#L14-L60 |
thautwarm/RBNF | rbnf/auto_lexer/__init__.py | str_lexer | def str_lexer(mode):
"""
generate token strings' cache
"""
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 | python | def str_lexer(mode):
"""
generate token strings' cache
"""
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 | [
"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"
] | generate token strings' cache | [
"generate",
"token",
"strings",
"cache"
] | train | https://github.com/thautwarm/RBNF/blob/cceec88c90f7ec95c160cfda01bfc532610985e0/rbnf/auto_lexer/__init__.py#L221-L243 |
thautwarm/RBNF | rbnf/auto_lexer/__init__.py | regex_lexer | 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 | python | 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 | [
"def",
"regex_lexer",
"(",
"regex_pat",
")",
":",
"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"
] | generate token names' cache | [
"generate",
"token",
"names",
"cache"
] | train | https://github.com/thautwarm/RBNF/blob/cceec88c90f7ec95c160cfda01bfc532610985e0/rbnf/auto_lexer/__init__.py#L246-L270 |
thautwarm/RBNF | rbnf/py_tools/unparse.py | Unparser.dispatch | 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) | python | 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) | [
"def",
"dispatch",
"(",
"self",
",",
"tree",
")",
":",
"if",
"isinstance",
"(",
"tree",
",",
"list",
")",
":",
"for",
"t",
"in",
"tree",
":",
"self",
".",
"dispatch",
"(",
"t",
")",
"return",
"meth",
"=",
"getattr",
"(",
"self",
",",
"\"_\"",
"+",
"tree",
".",
"__class__",
".",
"__name__",
")",
"meth",
"(",
"tree",
")"
] | Dispatcher function, dispatching tree type T to method _T. | [
"Dispatcher",
"function",
"dispatching",
"tree",
"type",
"T",
"to",
"method",
"_T",
"."
] | train | https://github.com/thautwarm/RBNF/blob/cceec88c90f7ec95c160cfda01bfc532610985e0/rbnf/py_tools/unparse.py#L101-L108 |
thautwarm/RBNF | rbnf/edsl/core.py | process | 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 | python | 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 | [
"def",
"process",
"(",
"fn",
",",
"bound_names",
")",
":",
"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"
] | process automatic context variable capturing.
return the transformed function and its ast. | [
"process",
"automatic",
"context",
"variable",
"capturing",
".",
"return",
"the",
"transformed",
"function",
"and",
"its",
"ast",
"."
] | train | https://github.com/thautwarm/RBNF/blob/cceec88c90f7ec95c160cfda01bfc532610985e0/rbnf/edsl/core.py#L107-L184 |
thautwarm/RBNF | rbnf/edsl/core.py | Language.ignore | 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()) | python | 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()) | [
"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",
"(",
")",
")"
] | ignore a set of tokens with specific names | [
"ignore",
"a",
"set",
"of",
"tokens",
"with",
"specific",
"names"
] | train | https://github.com/thautwarm/RBNF/blob/cceec88c90f7ec95c160cfda01bfc532610985e0/rbnf/edsl/core.py#L324-L334 |
thautwarm/RBNF | rbnf/bootstrap/rbnf.py | build_language | 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() | python | 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() | [
"def",
"build_language",
"(",
"source_code",
":",
"str",
",",
"lang",
":",
"Language",
",",
"filename",
":",
"str",
")",
":",
"state",
"=",
"MetaState",
"(",
"rbnf",
".",
"implementation",
",",
"requires",
"=",
"_Wild",
"(",
")",
",",
"filename",
"=",
"filename",
")",
"state",
".",
"data",
"=",
"lang",
"_build_language",
"(",
"source_code",
",",
"state",
")",
"lang",
".",
"build",
"(",
")"
] | lang: language object represents your language. | [
"lang",
":",
"language",
"object",
"represents",
"your",
"language",
"."
] | train | https://github.com/thautwarm/RBNF/blob/cceec88c90f7ec95c160cfda01bfc532610985e0/rbnf/bootstrap/rbnf.py#L536-L543 |
yunojuno-archive/django-inbound-email | inbound_email/backends/sendgrid.py | _decode_POST_value | 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) | python | 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) | [
"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",
")"
] | 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). | [
"Helper",
"to",
"decode",
"a",
"request",
"field",
"into",
"unicode",
"based",
"on",
"charsets",
"encoding",
"."
] | train | https://github.com/yunojuno-archive/django-inbound-email/blob/c0c1186fc2ced56b43d6b223e73cd5e8700dfc48/inbound_email/backends/sendgrid.py#L17-L45 |
yunojuno-archive/django-inbound-email | inbound_email/backends/sendgrid.py | SendGridRequestParser._get_addresses | 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 | python | 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 | [
"def",
"_get_addresses",
"(",
"self",
",",
"address_data",
",",
"retain_name",
"=",
"False",
")",
":",
"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"
] | 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) | [
"Takes",
"RFC",
"-",
"compliant",
"email",
"addresses",
"in",
"both",
"terse",
"(",
"email",
"only",
")",
"and",
"verbose",
"(",
"name",
"+",
"email",
")",
"forms",
"and",
"returns",
"a",
"list",
"of",
"email",
"address",
"strings"
] | train | https://github.com/yunojuno-archive/django-inbound-email/blob/c0c1186fc2ced56b43d6b223e73cd5e8700dfc48/inbound_email/backends/sendgrid.py#L51-L76 |
yunojuno-archive/django-inbound-email | inbound_email/backends/sendgrid.py | SendGridRequestParser.parse | def parse(self, request):
"""Parse incoming request and return an email instance.
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.
TODO: non-UTF8 charset handling.
TODO: handler headers.
"""
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 | python | def parse(self, request):
"""Parse incoming request and return an email instance.
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.
TODO: non-UTF8 charset handling.
TODO: handler headers.
"""
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 | [
"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"
] | Parse incoming request and return an email instance.
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.
TODO: non-UTF8 charset handling.
TODO: handler headers. | [
"Parse",
"incoming",
"request",
"and",
"return",
"an",
"email",
"instance",
"."
] | train | https://github.com/yunojuno-archive/django-inbound-email/blob/c0c1186fc2ced56b43d6b223e73cd5e8700dfc48/inbound_email/backends/sendgrid.py#L78-L146 |
yunojuno-archive/django-inbound-email | inbound_email/backends/mailgun.py | MailgunRequestParser.parse | 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 | python | 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 | [
"def",
"parse",
"(",
"self",
",",
"request",
")",
":",
"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"
] | 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. | [
"Parse",
"incoming",
"request",
"and",
"return",
"an",
"email",
"instance",
"."
] | train | https://github.com/yunojuno-archive/django-inbound-email/blob/c0c1186fc2ced56b43d6b223e73cd5e8700dfc48/inbound_email/backends/mailgun.py#L16-L82 |
yunojuno-archive/django-inbound-email | inbound_email/backends/mandrill.py | MandrillRequestParser._get_recipients | def _get_recipients(self, array):
"""Returns an iterator of objects
in the form ["Name <[email protected]", ...]
from the array [["[email protected]", "Name"]]
"""
for address, name in array:
if not name:
yield address
else:
yield "\"%s\" <%s>" % (name, address) | python | def _get_recipients(self, array):
"""Returns an iterator of objects
in the form ["Name <[email protected]", ...]
from the array [["[email protected]", "Name"]]
"""
for address, name in array:
if not name:
yield address
else:
yield "\"%s\" <%s>" % (name, address) | [
"def",
"_get_recipients",
"(",
"self",
",",
"array",
")",
":",
"for",
"address",
",",
"name",
"in",
"array",
":",
"if",
"not",
"name",
":",
"yield",
"address",
"else",
":",
"yield",
"\"\\\"%s\\\" <%s>\"",
"%",
"(",
"name",
",",
"address",
")"
] | Returns an iterator of objects
in the form ["Name <[email protected]", ...]
from the array [["[email protected]", "Name"]] | [
"Returns",
"an",
"iterator",
"of",
"objects",
"in",
"the",
"form",
"[",
"Name",
"<address"
] | train | https://github.com/yunojuno-archive/django-inbound-email/blob/c0c1186fc2ced56b43d6b223e73cd5e8700dfc48/inbound_email/backends/mandrill.py#L90-L99 |
yunojuno-archive/django-inbound-email | inbound_email/backends/mandrill.py | MandrillRequestParser.parse | def parse(self, request):
"""Parse incoming request and return an email instance.
Args:
request: an HttpRequest object, containing a list of forwarded emails, as
per Mandrill specification for inbound emails.
Returns:
a list of EmailMultiAlternatives instances
"""
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 | python | def parse(self, request):
"""Parse incoming request and return an email instance.
Args:
request: an HttpRequest object, containing a list of forwarded emails, as
per Mandrill specification for inbound emails.
Returns:
a list of EmailMultiAlternatives instances
"""
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 | [
"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"
] | Parse incoming request and return an email instance.
Args:
request: an HttpRequest object, containing a list of forwarded emails, as
per Mandrill specification for inbound emails.
Returns:
a list of EmailMultiAlternatives instances | [
"Parse",
"incoming",
"request",
"and",
"return",
"an",
"email",
"instance",
"."
] | train | https://github.com/yunojuno-archive/django-inbound-email/blob/c0c1186fc2ced56b43d6b223e73cd5e8700dfc48/inbound_email/backends/mandrill.py#L107-L176 |
yunojuno-archive/django-inbound-email | inbound_email/views.py | _log_request | 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) | python | 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) | [
"def",
"_log_request",
"(",
"request",
")",
":",
"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",
")"
] | Helper function to dump out debug info. | [
"Helper",
"function",
"to",
"dump",
"out",
"debug",
"info",
"."
] | train | https://github.com/yunojuno-archive/django-inbound-email/blob/c0c1186fc2ced56b43d6b223e73cd5e8700dfc48/inbound_email/views.py#L23-L31 |
yunojuno-archive/django-inbound-email | inbound_email/views.py | receive_inbound_email | 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) | python | 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) | [
"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",
")"
] | 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. | [
"Receives",
"inbound",
"email",
"from",
"SendGrid",
"."
] | train | https://github.com/yunojuno-archive/django-inbound-email/blob/c0c1186fc2ced56b43d6b223e73cd5e8700dfc48/inbound_email/views.py#L36-L97 |
yunojuno-archive/django-inbound-email | inbound_email/backends/__init__.py | get_backend_class | 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) | python | 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) | [
"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",
")"
] | Return reference to the configured backed class. | [
"Return",
"reference",
"to",
"the",
"configured",
"backed",
"class",
"."
] | train | https://github.com/yunojuno-archive/django-inbound-email/blob/c0c1186fc2ced56b43d6b223e73cd5e8700dfc48/inbound_email/backends/__init__.py#L6-L14 |
rsheftel/raccoon | raccoon/sort_utils.py | sorted_exists | 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 | python | 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 | [
"def",
"sorted_exists",
"(",
"values",
",",
"x",
")",
":",
"i",
"=",
"bisect_left",
"(",
"values",
",",
"x",
")",
"j",
"=",
"bisect_right",
"(",
"values",
",",
"x",
")",
"exists",
"=",
"x",
"in",
"values",
"[",
"i",
":",
"j",
"]",
"return",
"exists",
",",
"i"
] | 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 | [
"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",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/sort_utils.py#L8-L21 |
rsheftel/raccoon | raccoon/sort_utils.py | sorted_index | 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 | python | 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 | [
"def",
"sorted_index",
"(",
"values",
",",
"x",
")",
":",
"i",
"=",
"bisect_left",
"(",
"values",
",",
"x",
")",
"j",
"=",
"bisect_right",
"(",
"values",
",",
"x",
")",
"return",
"values",
"[",
"i",
":",
"j",
"]",
".",
"index",
"(",
"x",
")",
"+",
"i"
] | 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 | [
"For",
"list",
"values",
"returns",
"the",
"index",
"location",
"of",
"element",
"x",
".",
"If",
"x",
"does",
"not",
"exist",
"will",
"raise",
"an",
"error",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/sort_utils.py#L24-L34 |
rsheftel/raccoon | raccoon/sort_utils.py | sorted_list_indexes | 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) | python | 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) | [
"def",
"sorted_list_indexes",
"(",
"list_to_sort",
",",
"key",
"=",
"None",
",",
"reverse",
"=",
"False",
")",
":",
"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",
")"
] | 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 | [
"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",
"]"
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/sort_utils.py#L37-L53 |
vmlaker/mpipe | doc/create.py | runDia | 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 | python | 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 | [
"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"
] | Generate the diagrams using Dia. | [
"Generate",
"the",
"diagrams",
"using",
"Dia",
"."
] | train | https://github.com/vmlaker/mpipe/blob/5a1804cf64271931f0cd3e4fff3e2b38291212dd/doc/create.py#L37-L44 |
vmlaker/mpipe | src/OrderedWorker.py | OrderedWorker.init2 | 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 | python | 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 | [
"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.",
")",
":",
"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"
] | 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*. | [
"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",
"*",
"."
] | train | https://github.com/vmlaker/mpipe/blob/5a1804cf64271931f0cd3e4fff3e2b38291212dd/src/OrderedWorker.py#L19-L45 |
vmlaker/mpipe | src/OrderedWorker.py | OrderedWorker.assemble | 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() | python | 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() | [
"def",
"assemble",
"(",
"cls",
",",
"args",
",",
"input_tube",
",",
"output_tubes",
",",
"size",
",",
"disable_result",
"=",
"False",
",",
"do_stop_task",
"=",
"False",
",",
")",
":",
"# 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",
"(",
")"
] | 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",
"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",
"."
] | train | https://github.com/vmlaker/mpipe/blob/5a1804cf64271931f0cd3e4fff3e2b38291212dd/src/OrderedWorker.py#L53-L93 |
vmlaker/mpipe | src/OrderedWorker.py | OrderedWorker._link | 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() | python | 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() | [
"def",
"_link",
"(",
"self",
",",
"next_worker",
",",
"next_is_first",
"=",
"False",
")",
":",
"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",
"(",
")"
] | Link the worker to the given next worker object,
connecting the two workers with communication tubes. | [
"Link",
"the",
"worker",
"to",
"the",
"given",
"next",
"worker",
"object",
"connecting",
"the",
"two",
"workers",
"with",
"communication",
"tubes",
"."
] | train | https://github.com/vmlaker/mpipe/blob/5a1804cf64271931f0cd3e4fff3e2b38291212dd/src/OrderedWorker.py#L95-L112 |
vmlaker/mpipe | src/OrderedWorker.py | OrderedWorker.putResult | 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() | python | 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() | [
"def",
"putResult",
"(",
"self",
",",
"result",
")",
":",
"self",
".",
"_lock_prev_output",
".",
"acquire",
"(",
")",
"for",
"tube",
"in",
"self",
".",
"_tubes_result_output",
":",
"tube",
".",
"put",
"(",
"(",
"result",
",",
"0",
")",
")",
"self",
".",
"_lock_next_output",
".",
"release",
"(",
")"
] | Register the *result* by putting it on all the output tubes. | [
"Register",
"the",
"*",
"result",
"*",
"by",
"putting",
"it",
"on",
"all",
"the",
"output",
"tubes",
"."
] | train | https://github.com/vmlaker/mpipe/blob/5a1804cf64271931f0cd3e4fff3e2b38291212dd/src/OrderedWorker.py#L114-L119 |
vmlaker/mpipe | src/UnorderedWorker.py | UnorderedWorker.init2 | 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 | python | 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 | [
"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.",
")",
":",
"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"
] | 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*. | [
"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",
"*",
"."
] | train | https://github.com/vmlaker/mpipe/blob/5a1804cf64271931f0cd3e4fff3e2b38291212dd/src/UnorderedWorker.py#L17-L34 |
vmlaker/mpipe | src/UnorderedWorker.py | UnorderedWorker.assemble | 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() | python | 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() | [
"def",
"assemble",
"(",
"cls",
",",
"args",
",",
"input_tube",
",",
"output_tubes",
",",
"size",
",",
"disable_result",
",",
"do_stop_task",
",",
")",
":",
"# 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",
"(",
")"
] | 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",
"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",
"."
] | train | https://github.com/vmlaker/mpipe/blob/5a1804cf64271931f0cd3e4fff3e2b38291212dd/src/UnorderedWorker.py#L42-L73 |
rsheftel/raccoon | raccoon/series.py | SeriesBase.show | 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)) | python | 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)) | [
"def",
"show",
"(",
"self",
",",
"index",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"print",
"(",
"self",
".",
"_make_table",
"(",
"index",
"=",
"index",
",",
"*",
"*",
"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",
"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",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L50-L59 |
rsheftel/raccoon | raccoon/series.py | SeriesBase.get | 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) | python | 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) | [
"def",
"get",
"(",
"self",
",",
"indexes",
",",
"as_list",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"indexes",
",",
"(",
"list",
",",
"blist",
")",
")",
":",
"return",
"self",
".",
"get_rows",
"(",
"indexes",
",",
"as_list",
")",
"else",
":",
"return",
"self",
".",
"get_cell",
"(",
"indexes",
")"
] | 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 | [
"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",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L97-L110 |
rsheftel/raccoon | raccoon/series.py | SeriesBase.get_cell | 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] | python | 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] | [
"def",
"get_cell",
"(",
"self",
",",
"index",
")",
":",
"i",
"=",
"sorted_index",
"(",
"self",
".",
"_index",
",",
"index",
")",
"if",
"self",
".",
"_sort",
"else",
"self",
".",
"_index",
".",
"index",
"(",
"index",
")",
"return",
"self",
".",
"_data",
"[",
"i",
"]"
] | For a single index and return the value
:param index: index value
:return: value | [
"For",
"a",
"single",
"index",
"and",
"return",
"the",
"value"
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L112-L120 |
rsheftel/raccoon | raccoon/series.py | SeriesBase.get_rows | 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) | python | 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) | [
"def",
"get_rows",
"(",
"self",
",",
"indexes",
",",
"as_list",
"=",
"False",
")",
":",
"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",
")"
] | 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 | [
"For",
"a",
"list",
"of",
"indexes",
"return",
"the",
"values",
"of",
"the",
"indexes",
"in",
"that",
"column",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L122-L145 |
rsheftel/raccoon | raccoon/series.py | SeriesBase.get_location | def get_location(self, location):
"""
For an index location return a dict of the index and value. This is optimized for speed because
it does not need to lookup the index location with a search. Also can accept relative indexing from the end of
the SEries in standard python notation [-3, -2, -1]
:param location: index location in standard python form of positive or negative number
:return: dictionary
"""
return {self.index_name: self._index[location], self.data_name: self._data[location]} | python | def get_location(self, location):
"""
For an index location return a dict of the index and value. This is optimized for speed because
it does not need to lookup the index location with a search. Also can accept relative indexing from the end of
the SEries in standard python notation [-3, -2, -1]
:param location: index location in standard python form of positive or negative number
:return: dictionary
"""
return {self.index_name: self._index[location], self.data_name: self._data[location]} | [
"def",
"get_location",
"(",
"self",
",",
"location",
")",
":",
"return",
"{",
"self",
".",
"index_name",
":",
"self",
".",
"_index",
"[",
"location",
"]",
",",
"self",
".",
"data_name",
":",
"self",
".",
"_data",
"[",
"location",
"]",
"}"
] | For an index location return a dict of the index and value. This is optimized for speed because
it does not need to lookup the index location with a search. Also can accept relative indexing from the end of
the SEries in standard python notation [-3, -2, -1]
:param location: index location in standard python form of positive or negative number
:return: dictionary | [
"For",
"an",
"index",
"location",
"return",
"a",
"dict",
"of",
"the",
"index",
"and",
"value",
".",
"This",
"is",
"optimized",
"for",
"speed",
"because",
"it",
"does",
"not",
"need",
"to",
"lookup",
"the",
"index",
"location",
"with",
"a",
"search",
".",
"Also",
"can",
"accept",
"relative",
"indexing",
"from",
"the",
"end",
"of",
"the",
"SEries",
"in",
"standard",
"python",
"notation",
"[",
"-",
"3",
"-",
"2",
"-",
"1",
"]"
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L147-L156 |
rsheftel/raccoon | raccoon/series.py | SeriesBase.get_locations | 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) | python | 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) | [
"def",
"get_locations",
"(",
"self",
",",
"locations",
",",
"as_list",
"=",
"False",
")",
":",
"indexes",
"=",
"[",
"self",
".",
"_index",
"[",
"x",
"]",
"for",
"x",
"in",
"locations",
"]",
"return",
"self",
".",
"get",
"(",
"indexes",
",",
"as_list",
")"
] | 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 | [
"For",
"list",
"of",
"locations",
"return",
"a",
"Series",
"or",
"list",
"of",
"the",
"values",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L158-L168 |
rsheftel/raccoon | raccoon/series.py | SeriesBase.get_slice | 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) | python | 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) | [
"def",
"get_slice",
"(",
"self",
",",
"start_index",
"=",
"None",
",",
"stop_index",
"=",
"None",
",",
"as_list",
"=",
"False",
")",
":",
"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",
")"
] | 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) | [
"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",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L170-L195 |
rsheftel/raccoon | raccoon/series.py | SeriesBase.to_dict | 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 | python | 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 | [
"def",
"to_dict",
"(",
"self",
",",
"index",
"=",
"True",
",",
"ordered",
"=",
"False",
")",
":",
"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"
] | 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() | [
"Returns",
"a",
"dict",
"where",
"the",
"keys",
"are",
"the",
"data",
"and",
"index",
"names",
"and",
"the",
"values",
"are",
"list",
"of",
"the",
"data",
"and",
"index",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L235-L251 |
rsheftel/raccoon | raccoon/series.py | SeriesBase.head | 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) | python | 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) | [
"def",
"head",
"(",
"self",
",",
"rows",
")",
":",
"rows_bool",
"=",
"[",
"True",
"]",
"*",
"min",
"(",
"rows",
",",
"len",
"(",
"self",
".",
"_index",
")",
")",
"rows_bool",
".",
"extend",
"(",
"[",
"False",
"]",
"*",
"max",
"(",
"0",
",",
"len",
"(",
"self",
".",
"_index",
")",
"-",
"rows",
")",
")",
"return",
"self",
".",
"get",
"(",
"indexes",
"=",
"rows_bool",
")"
] | Return a Series of the first N rows
:param rows: number of rows
:return: Series | [
"Return",
"a",
"Series",
"of",
"the",
"first",
"N",
"rows"
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L253-L262 |
rsheftel/raccoon | raccoon/series.py | SeriesBase.select_index | def select_index(self, compare, result='boolean'):
"""
Finds the elements in the index that match the compare parameter and returns either a list of the values that
match, of a boolean list the length of the index with True to each index that matches. If the indexes are
tuples then the compare is a tuple where None in any field of the tuple will be treated as "*" and match all
values.
:param compare: value to compare as a singleton or tuple
:param result: 'boolean' = returns a list of booleans, 'value' = returns a list of index values that match
:return: list of booleans or values
"""
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.') | python | def select_index(self, compare, result='boolean'):
"""
Finds the elements in the index that match the compare parameter and returns either a list of the values that
match, of a boolean list the length of the index with True to each index that matches. If the indexes are
tuples then the compare is a tuple where None in any field of the tuple will be treated as "*" and match all
values.
:param compare: value to compare as a singleton or tuple
:param result: 'boolean' = returns a list of booleans, 'value' = returns a list of index values that match
:return: list of booleans or values
"""
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.') | [
"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.'",
")"
] | Finds the elements in the index that match the compare parameter and returns either a list of the values that
match, of a boolean list the length of the index with True to each index that matches. If the indexes are
tuples then the compare is a tuple where None in any field of the tuple will be treated as "*" and match all
values.
:param compare: value to compare as a singleton or tuple
:param result: 'boolean' = returns a list of booleans, 'value' = returns a list of index values that match
:return: list of booleans or values | [
"Finds",
"the",
"elements",
"in",
"the",
"index",
"that",
"match",
"the",
"compare",
"parameter",
"and",
"returns",
"either",
"a",
"list",
"of",
"the",
"values",
"that",
"match",
"of",
"a",
"boolean",
"list",
"the",
"length",
"of",
"the",
"index",
"with",
"True",
"to",
"each",
"index",
"that",
"matches",
".",
"If",
"the",
"indexes",
"are",
"tuples",
"then",
"the",
"compare",
"is",
"a",
"tuple",
"where",
"None",
"in",
"any",
"field",
"of",
"the",
"tuple",
"will",
"be",
"treated",
"as",
"*",
"and",
"match",
"all",
"values",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L275-L301 |
rsheftel/raccoon | raccoon/series.py | SeriesBase.equality | 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] | python | 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] | [
"def",
"equality",
"(",
"self",
",",
"indexes",
"=",
"None",
",",
"value",
"=",
"None",
")",
":",
"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",
"]"
] | 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 | [
"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",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L312-L324 |
rsheftel/raccoon | raccoon/series.py | Series._pad_data | def _pad_data(self, index_len):
"""
Pad the data in Series with [None] to ensure that data is the same length as index
:param index_len: length of index to extend data to
:return: nothing
"""
self._data.extend([None] * (index_len - len(self._data))) | python | def _pad_data(self, index_len):
"""
Pad the data in Series with [None] to ensure that data is the same length as index
:param index_len: length of index to extend data to
:return: nothing
"""
self._data.extend([None] * (index_len - len(self._data))) | [
"def",
"_pad_data",
"(",
"self",
",",
"index_len",
")",
":",
"self",
".",
"_data",
".",
"extend",
"(",
"[",
"None",
"]",
"*",
"(",
"index_len",
"-",
"len",
"(",
"self",
".",
"_data",
")",
")",
")"
] | Pad the data in Series with [None] to ensure that data is the same length as index
:param index_len: length of index to extend data to
:return: nothing | [
"Pad",
"the",
"data",
"in",
"Series",
"with",
"[",
"None",
"]",
"to",
"ensure",
"that",
"data",
"is",
"the",
"same",
"length",
"as",
"index"
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L382-L389 |
rsheftel/raccoon | raccoon/series.py | Series.sort_index | 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] | python | 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] | [
"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",
"]"
] | Sort the Series by the index. The sort modifies the Series inplace
:return: nothing | [
"Sort",
"the",
"Series",
"by",
"the",
"index",
".",
"The",
"sort",
"modifies",
"the",
"Series",
"inplace"
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L418-L428 |
rsheftel/raccoon | raccoon/series.py | Series.set | 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) | python | 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) | [
"def",
"set",
"(",
"self",
",",
"indexes",
",",
"values",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"indexes",
",",
"(",
"list",
",",
"blist",
")",
")",
":",
"self",
".",
"set_rows",
"(",
"indexes",
",",
"values",
")",
"else",
":",
"self",
".",
"set_cell",
"(",
"indexes",
",",
"values",
")"
] | 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 | [
"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",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L430-L443 |
rsheftel/raccoon | raccoon/series.py | Series._add_row | 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) | python | 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) | [
"def",
"_add_row",
"(",
"self",
",",
"index",
")",
":",
"self",
".",
"_index",
".",
"append",
"(",
"index",
")",
"self",
".",
"_data",
".",
"append",
"(",
"None",
")"
] | Add a new row to the Series
:param index: index of the new row
:return: nothing | [
"Add",
"a",
"new",
"row",
"to",
"the",
"Series"
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L445-L453 |
rsheftel/raccoon | raccoon/series.py | Series._insert_row | 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) | python | 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) | [
"def",
"_insert_row",
"(",
"self",
",",
"i",
",",
"index",
")",
":",
"if",
"i",
"==",
"len",
"(",
"self",
".",
"_index",
")",
":",
"self",
".",
"_add_row",
"(",
"index",
")",
"else",
":",
"self",
".",
"_index",
".",
"insert",
"(",
"i",
",",
"index",
")",
"self",
".",
"_data",
".",
"insert",
"(",
"i",
",",
"None",
")"
] | 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 | [
"Insert",
"a",
"new",
"row",
"in",
"the",
"Series",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L455-L467 |
rsheftel/raccoon | raccoon/series.py | Series._add_missing_rows | 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) | python | 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) | [
"def",
"_add_missing_rows",
"(",
"self",
",",
"indexes",
")",
":",
"new_indexes",
"=",
"[",
"x",
"for",
"x",
"in",
"indexes",
"if",
"x",
"not",
"in",
"self",
".",
"_index",
"]",
"for",
"x",
"in",
"new_indexes",
":",
"self",
".",
"_add_row",
"(",
"x",
")"
] | 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 | [
"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",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L469-L479 |
rsheftel/raccoon | raccoon/series.py | Series._insert_missing_rows | 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) | python | 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) | [
"def",
"_insert_missing_rows",
"(",
"self",
",",
"indexes",
")",
":",
"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",
")"
] | 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 | [
"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"
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L481-L491 |
rsheftel/raccoon | raccoon/series.py | Series.set_cell | 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 | python | 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 | [
"def",
"set_cell",
"(",
"self",
",",
"index",
",",
"value",
")",
":",
"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"
] | 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 | [
"Sets",
"the",
"value",
"of",
"a",
"single",
"cell",
".",
"If",
"the",
"index",
"is",
"not",
"in",
"the",
"current",
"index",
"then",
"a",
"new",
"index",
"will",
"be",
"created",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L493-L511 |
rsheftel/raccoon | raccoon/series.py | Series.set_rows | 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] | python | 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] | [
"def",
"set_rows",
"(",
"self",
",",
"index",
",",
"values",
"=",
"None",
")",
":",
"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",
"]"
] | 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 | [
"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",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L513-L554 |
rsheftel/raccoon | raccoon/series.py | Series.set_locations | 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) | python | 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) | [
"def",
"set_locations",
"(",
"self",
",",
"locations",
",",
"values",
")",
":",
"indexes",
"=",
"[",
"self",
".",
"_index",
"[",
"x",
"]",
"for",
"x",
"in",
"locations",
"]",
"self",
".",
"set",
"(",
"indexes",
",",
"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 | [
"For",
"a",
"list",
"of",
"locations",
"set",
"the",
"values",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L566-L576 |
rsheftel/raccoon | raccoon/series.py | Series.append_row | 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) | python | 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) | [
"def",
"append_row",
"(",
"self",
",",
"index",
",",
"value",
")",
":",
"if",
"index",
"in",
"self",
".",
"_index",
":",
"raise",
"IndexError",
"(",
"'index already in Series'",
")",
"self",
".",
"_index",
".",
"append",
"(",
"index",
")",
"self",
".",
"_data",
".",
"append",
"(",
"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 | [
"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",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L614-L627 |
rsheftel/raccoon | raccoon/series.py | Series.append_rows | 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) | python | 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) | [
"def",
"append_rows",
"(",
"self",
",",
"indexes",
",",
"values",
")",
":",
"# 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",
")"
] | 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 | [
"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",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L629-L650 |
rsheftel/raccoon | raccoon/series.py | Series.delete | 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] | python | 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] | [
"def",
"delete",
"(",
"self",
",",
"indexes",
")",
":",
"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",
"]"
] | Delete rows from the DataFrame
:param indexes: either a list of values or list of booleans for the rows to delete
:return: nothing | [
"Delete",
"rows",
"from",
"the",
"DataFrame"
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L652-L672 |
rsheftel/raccoon | raccoon/series.py | Series.reset_index | 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' | python | 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' | [
"def",
"reset_index",
"(",
"self",
")",
":",
"self",
".",
"index",
"=",
"list",
"(",
"range",
"(",
"self",
".",
"__len__",
"(",
")",
")",
")",
"self",
".",
"index_name",
"=",
"'index'"
] | Resets the index of the Series to simple integer list and the index name to 'index'.
:return: nothing | [
"Resets",
"the",
"index",
"of",
"the",
"Series",
"to",
"simple",
"integer",
"list",
"and",
"the",
"index",
"name",
"to",
"index",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L674-L681 |
rsheftel/raccoon | raccoon/series.py | ViewSeries.value | 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) | python | 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) | [
"def",
"value",
"(",
"self",
",",
"indexes",
",",
"int_as_index",
"=",
"False",
")",
":",
"# 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",
")"
] | 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 | [
"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",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L738-L788 |
rsheftel/raccoon | raccoon/series.py | ViewSeries.from_dataframe | 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) | python | 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) | [
"def",
"from_dataframe",
"(",
"cls",
",",
"dataframe",
",",
"column",
",",
"offset",
"=",
"0",
")",
":",
"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",
")"
] | 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 | [
"Creates",
"and",
"return",
"a",
"Series",
"from",
"a",
"DataFrame",
"and",
"specific",
"column"
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L807-L817 |
rsheftel/raccoon | raccoon/series.py | ViewSeries.from_series | 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) | python | 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) | [
"def",
"from_series",
"(",
"cls",
",",
"series",
",",
"offset",
"=",
"0",
")",
":",
"return",
"cls",
"(",
"data",
"=",
"series",
".",
"data",
",",
"index",
"=",
"series",
".",
"index",
",",
"data_name",
"=",
"series",
".",
"data_name",
",",
"index_name",
"=",
"series",
".",
"index_name",
",",
"sort",
"=",
"series",
".",
"sort",
",",
"offset",
"=",
"offset",
")"
] | 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 | [
"Creates",
"and",
"return",
"a",
"Series",
"from",
"a",
"Series"
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/series.py#L820-L829 |
vmlaker/mpipe | src/TubeQ.py | TubeQ.get | def get(self, timeout=None):
"""Return the next available item from the tube.
Blocks if tube is empty, until a producer for the tube puts an item on it."""
if timeout:
try:
result = self._queue.get(True, timeout)
except multiprocessing.Queue.Empty:
return(False, None)
return(True, result)
return self._queue.get() | python | def get(self, timeout=None):
"""Return the next available item from the tube.
Blocks if tube is empty, until a producer for the tube puts an item on it."""
if timeout:
try:
result = self._queue.get(True, timeout)
except multiprocessing.Queue.Empty:
return(False, None)
return(True, result)
return self._queue.get() | [
"def",
"get",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
":",
"try",
":",
"result",
"=",
"self",
".",
"_queue",
".",
"get",
"(",
"True",
",",
"timeout",
")",
"except",
"multiprocessing",
".",
"Queue",
".",
"Empty",
":",
"return",
"(",
"False",
",",
"None",
")",
"return",
"(",
"True",
",",
"result",
")",
"return",
"self",
".",
"_queue",
".",
"get",
"(",
")"
] | Return the next available item from the tube.
Blocks if tube is empty, until a producer for the tube puts an item on it. | [
"Return",
"the",
"next",
"available",
"item",
"from",
"the",
"tube",
"."
] | train | https://github.com/vmlaker/mpipe/blob/5a1804cf64271931f0cd3e4fff3e2b38291212dd/src/TubeQ.py#L16-L26 |
vmlaker/mpipe | src/Stage.py | Stage.get | 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 | python | 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 | [
"def",
"get",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"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"
] | Retrieve results from all the output tubes. | [
"Retrieve",
"results",
"from",
"all",
"the",
"output",
"tubes",
"."
] | train | https://github.com/vmlaker/mpipe/blob/5a1804cf64271931f0cd3e4fff3e2b38291212dd/src/Stage.py#L42-L55 |
vmlaker/mpipe | src/Stage.py | Stage.link | def link(self, next_stage):
"""Link to the given downstream stage *next_stage*
by adding its input tube to the list of this stage's output tubes.
Return this stage."""
if next_stage is self: raise ValueError('cannot link stage to itself')
self._output_tubes.append(next_stage._input_tube)
self._next_stages.append(next_stage)
return self | python | def link(self, next_stage):
"""Link to the given downstream stage *next_stage*
by adding its input tube to the list of this stage's output tubes.
Return this stage."""
if next_stage is self: raise ValueError('cannot link stage to itself')
self._output_tubes.append(next_stage._input_tube)
self._next_stages.append(next_stage)
return self | [
"def",
"link",
"(",
"self",
",",
"next_stage",
")",
":",
"if",
"next_stage",
"is",
"self",
":",
"raise",
"ValueError",
"(",
"'cannot link stage to itself'",
")",
"self",
".",
"_output_tubes",
".",
"append",
"(",
"next_stage",
".",
"_input_tube",
")",
"self",
".",
"_next_stages",
".",
"append",
"(",
"next_stage",
")",
"return",
"self"
] | Link to the given downstream stage *next_stage*
by adding its input tube to the list of this stage's output tubes.
Return this stage. | [
"Link",
"to",
"the",
"given",
"downstream",
"stage",
"*",
"next_stage",
"*",
"by",
"adding",
"its",
"input",
"tube",
"to",
"the",
"list",
"of",
"this",
"stage",
"s",
"output",
"tubes",
".",
"Return",
"this",
"stage",
"."
] | train | https://github.com/vmlaker/mpipe/blob/5a1804cf64271931f0cd3e4fff3e2b38291212dd/src/Stage.py#L64-L71 |
vmlaker/mpipe | src/Stage.py | Stage.getLeaves | 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 | python | 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 | [
"def",
"getLeaves",
"(",
"self",
")",
":",
"result",
"=",
"list",
"(",
")",
"if",
"not",
"self",
".",
"_next_stages",
":",
"result",
".",
"append",
"(",
"self",
")",
"else",
":",
"for",
"stage",
"in",
"self",
".",
"_next_stages",
":",
"leaves",
"=",
"stage",
".",
"getLeaves",
"(",
")",
"result",
"+=",
"leaves",
"return",
"result"
] | Return the downstream leaf stages of this stage. | [
"Return",
"the",
"downstream",
"leaf",
"stages",
"of",
"this",
"stage",
"."
] | train | https://github.com/vmlaker/mpipe/blob/5a1804cf64271931f0cd3e4fff3e2b38291212dd/src/Stage.py#L73-L82 |
vmlaker/mpipe | src/Stage.py | Stage.build | 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() | python | 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() | [
"def",
"build",
"(",
"self",
")",
":",
"# 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",
"(",
")"
] | Create and start up the internal workers. | [
"Create",
"and",
"start",
"up",
"the",
"internal",
"workers",
"."
] | train | https://github.com/vmlaker/mpipe/blob/5a1804cf64271931f0cd3e4fff3e2b38291212dd/src/Stage.py#L84-L104 |
vmlaker/mpipe | src/TubeP.py | TubeP.get | def get(self, timeout=None):
"""Return the next available item from the tube.
Blocks if tube is empty, until a producer for the tube puts an item on it."""
if timeout:
# Todo: Consider locking the poll/recv block.
# Otherwise, this method is not thread safe.
if self._conn1.poll(timeout):
return (True, self._conn1.recv())
else:
return (False, None)
return self._conn1.recv() | python | def get(self, timeout=None):
"""Return the next available item from the tube.
Blocks if tube is empty, until a producer for the tube puts an item on it."""
if timeout:
# Todo: Consider locking the poll/recv block.
# Otherwise, this method is not thread safe.
if self._conn1.poll(timeout):
return (True, self._conn1.recv())
else:
return (False, None)
return self._conn1.recv() | [
"def",
"get",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
":",
"# Todo: Consider locking the poll/recv block.",
"# Otherwise, this method is not thread safe.",
"if",
"self",
".",
"_conn1",
".",
"poll",
"(",
"timeout",
")",
":",
"return",
"(",
"True",
",",
"self",
".",
"_conn1",
".",
"recv",
"(",
")",
")",
"else",
":",
"return",
"(",
"False",
",",
"None",
")",
"return",
"self",
".",
"_conn1",
".",
"recv",
"(",
")"
] | Return the next available item from the tube.
Blocks if tube is empty, until a producer for the tube puts an item on it. | [
"Return",
"the",
"next",
"available",
"item",
"from",
"the",
"tube",
"."
] | train | https://github.com/vmlaker/mpipe/blob/5a1804cf64271931f0cd3e4fff3e2b38291212dd/src/TubeP.py#L17-L28 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame._sort_columns | 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] | python | 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] | [
"def",
"_sort_columns",
"(",
"self",
",",
"columns_list",
")",
":",
"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",
"]"
] | 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 | [
"Given",
"a",
"list",
"of",
"column",
"names",
"will",
"sort",
"the",
"DataFrame",
"columns",
"to",
"match",
"the",
"given",
"order"
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L126-L139 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame._pad_data | 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))) | python | 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))) | [
"def",
"_pad_data",
"(",
"self",
",",
"max_len",
"=",
"None",
")",
":",
"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",
")",
")",
")"
] | 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 | [
"Pad",
"the",
"data",
"in",
"DataFrame",
"with",
"[",
"None",
"}",
"to",
"ensure",
"that",
"all",
"columns",
"have",
"the",
"same",
"length",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L141-L151 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.get | 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) | python | 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) | [
"def",
"get",
"(",
"self",
",",
"indexes",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"as_list",
"=",
"False",
",",
"as_dict",
"=",
"False",
")",
":",
"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",
")"
] | 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 | [
"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",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L240-L269 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.get_cell | 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] | python | 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] | [
"def",
"get_cell",
"(",
"self",
",",
"index",
",",
"column",
")",
":",
"i",
"=",
"sorted_index",
"(",
"self",
".",
"_index",
",",
"index",
")",
"if",
"self",
".",
"_sort",
"else",
"self",
".",
"_index",
".",
"index",
"(",
"index",
")",
"c",
"=",
"self",
".",
"_columns",
".",
"index",
"(",
"column",
")",
"return",
"self",
".",
"_data",
"[",
"c",
"]",
"[",
"i",
"]"
] | For a single index and column value return the value of the cell
:param index: index value
:param column: column name
:return: value | [
"For",
"a",
"single",
"index",
"and",
"column",
"value",
"return",
"the",
"value",
"of",
"the",
"cell"
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L271-L281 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.get_rows | 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) | python | 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) | [
"def",
"get_rows",
"(",
"self",
",",
"indexes",
",",
"column",
",",
"as_list",
"=",
"False",
")",
":",
"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",
")"
] | 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 | [
"For",
"a",
"list",
"of",
"indexes",
"and",
"a",
"single",
"column",
"name",
"return",
"the",
"values",
"of",
"the",
"indexes",
"in",
"that",
"column",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L283-L308 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.get_columns | 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) | python | 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) | [
"def",
"get_columns",
"(",
"self",
",",
"index",
",",
"columns",
"=",
"None",
",",
"as_dict",
"=",
"False",
")",
":",
"i",
"=",
"sorted_index",
"(",
"self",
".",
"_index",
",",
"index",
")",
"if",
"self",
".",
"_sort",
"else",
"self",
".",
"_index",
".",
"index",
"(",
"index",
")",
"return",
"self",
".",
"get_location",
"(",
"i",
",",
"columns",
",",
"as_dict",
")"
] | 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 | [
"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"
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L310-L321 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.get_entire_column | 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) | python | 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) | [
"def",
"get_entire_column",
"(",
"self",
",",
"column",
",",
"as_list",
"=",
"False",
")",
":",
"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",
")"
] | 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 | [
"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",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L323-L335 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.get_matrix | 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) | python | 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) | [
"def",
"get_matrix",
"(",
"self",
",",
"indexes",
",",
"columns",
")",
":",
"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",
")"
] | 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 | [
"For",
"a",
"list",
"of",
"indexes",
"and",
"list",
"of",
"columns",
"return",
"a",
"DataFrame",
"of",
"the",
"values",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L337-L369 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.get_location | def get_location(self, location, columns=None, as_dict=False, index=True):
"""
For an index location and either (1) list of columns return a DataFrame or dictionary of the values or
(2) single column name and return the value of that cell. This is optimized for speed because it does not need
to lookup the index location with a search. Also can accept relative indexing from the end of the DataFrame
in standard python notation [-3, -2, -1]
:param location: index location in standard python form of positive or negative number
:param columns: list of columns, single column name, or None to include all columns
:param as_dict: if True then return a dictionary
:param index: if True then include the index in the dictionary if as_dict=True
:return: DataFrame or dictionary if columns is a list or value if columns is a single column name
"""
if columns is None:
columns = self._columns
elif not isinstance(columns, list): # single value for columns
c = self._columns.index(columns)
return self._data[c][location]
elif all([isinstance(i, bool) for i in columns]):
if len(columns) != len(self._columns):
raise ValueError('boolean column list must be same size of existing columns')
columns = list(compress(self._columns, columns))
data = dict()
for column in columns:
c = self._columns.index(column)
data[column] = self._data[c][location]
index_value = self._index[location]
if as_dict:
if index:
data[self._index_name] = index_value
return data
else:
data = {k: [data[k]] for k in data} # this makes the dict items lists
return DataFrame(data=data, index=[index_value], columns=columns, index_name=self._index_name,
sort=self._sort) | python | def get_location(self, location, columns=None, as_dict=False, index=True):
"""
For an index location and either (1) list of columns return a DataFrame or dictionary of the values or
(2) single column name and return the value of that cell. This is optimized for speed because it does not need
to lookup the index location with a search. Also can accept relative indexing from the end of the DataFrame
in standard python notation [-3, -2, -1]
:param location: index location in standard python form of positive or negative number
:param columns: list of columns, single column name, or None to include all columns
:param as_dict: if True then return a dictionary
:param index: if True then include the index in the dictionary if as_dict=True
:return: DataFrame or dictionary if columns is a list or value if columns is a single column name
"""
if columns is None:
columns = self._columns
elif not isinstance(columns, list): # single value for columns
c = self._columns.index(columns)
return self._data[c][location]
elif all([isinstance(i, bool) for i in columns]):
if len(columns) != len(self._columns):
raise ValueError('boolean column list must be same size of existing columns')
columns = list(compress(self._columns, columns))
data = dict()
for column in columns:
c = self._columns.index(column)
data[column] = self._data[c][location]
index_value = self._index[location]
if as_dict:
if index:
data[self._index_name] = index_value
return data
else:
data = {k: [data[k]] for k in data} # this makes the dict items lists
return DataFrame(data=data, index=[index_value], columns=columns, index_name=self._index_name,
sort=self._sort) | [
"def",
"get_location",
"(",
"self",
",",
"location",
",",
"columns",
"=",
"None",
",",
"as_dict",
"=",
"False",
",",
"index",
"=",
"True",
")",
":",
"if",
"columns",
"is",
"None",
":",
"columns",
"=",
"self",
".",
"_columns",
"elif",
"not",
"isinstance",
"(",
"columns",
",",
"list",
")",
":",
"# single value for columns",
"c",
"=",
"self",
".",
"_columns",
".",
"index",
"(",
"columns",
")",
"return",
"self",
".",
"_data",
"[",
"c",
"]",
"[",
"location",
"]",
"elif",
"all",
"(",
"[",
"isinstance",
"(",
"i",
",",
"bool",
")",
"for",
"i",
"in",
"columns",
"]",
")",
":",
"if",
"len",
"(",
"columns",
")",
"!=",
"len",
"(",
"self",
".",
"_columns",
")",
":",
"raise",
"ValueError",
"(",
"'boolean column list must be same size of existing columns'",
")",
"columns",
"=",
"list",
"(",
"compress",
"(",
"self",
".",
"_columns",
",",
"columns",
")",
")",
"data",
"=",
"dict",
"(",
")",
"for",
"column",
"in",
"columns",
":",
"c",
"=",
"self",
".",
"_columns",
".",
"index",
"(",
"column",
")",
"data",
"[",
"column",
"]",
"=",
"self",
".",
"_data",
"[",
"c",
"]",
"[",
"location",
"]",
"index_value",
"=",
"self",
".",
"_index",
"[",
"location",
"]",
"if",
"as_dict",
":",
"if",
"index",
":",
"data",
"[",
"self",
".",
"_index_name",
"]",
"=",
"index_value",
"return",
"data",
"else",
":",
"data",
"=",
"{",
"k",
":",
"[",
"data",
"[",
"k",
"]",
"]",
"for",
"k",
"in",
"data",
"}",
"# this makes the dict items lists",
"return",
"DataFrame",
"(",
"data",
"=",
"data",
",",
"index",
"=",
"[",
"index_value",
"]",
",",
"columns",
"=",
"columns",
",",
"index_name",
"=",
"self",
".",
"_index_name",
",",
"sort",
"=",
"self",
".",
"_sort",
")"
] | For an index location and either (1) list of columns return a DataFrame or dictionary of the values or
(2) single column name and return the value of that cell. This is optimized for speed because it does not need
to lookup the index location with a search. Also can accept relative indexing from the end of the DataFrame
in standard python notation [-3, -2, -1]
:param location: index location in standard python form of positive or negative number
:param columns: list of columns, single column name, or None to include all columns
:param as_dict: if True then return a dictionary
:param index: if True then include the index in the dictionary if as_dict=True
:return: DataFrame or dictionary if columns is a list or value if columns is a single column name | [
"For",
"an",
"index",
"location",
"and",
"either",
"(",
"1",
")",
"list",
"of",
"columns",
"return",
"a",
"DataFrame",
"or",
"dictionary",
"of",
"the",
"values",
"or",
"(",
"2",
")",
"single",
"column",
"name",
"and",
"return",
"the",
"value",
"of",
"that",
"cell",
".",
"This",
"is",
"optimized",
"for",
"speed",
"because",
"it",
"does",
"not",
"need",
"to",
"lookup",
"the",
"index",
"location",
"with",
"a",
"search",
".",
"Also",
"can",
"accept",
"relative",
"indexing",
"from",
"the",
"end",
"of",
"the",
"DataFrame",
"in",
"standard",
"python",
"notation",
"[",
"-",
"3",
"-",
"2",
"-",
"1",
"]",
":",
"param",
"location",
":",
"index",
"location",
"in",
"standard",
"python",
"form",
"of",
"positive",
"or",
"negative",
"number",
":",
"param",
"columns",
":",
"list",
"of",
"columns",
"single",
"column",
"name",
"or",
"None",
"to",
"include",
"all",
"columns",
":",
"param",
"as_dict",
":",
"if",
"True",
"then",
"return",
"a",
"dictionary",
":",
"param",
"index",
":",
"if",
"True",
"then",
"include",
"the",
"index",
"in",
"the",
"dictionary",
"if",
"as_dict",
"=",
"True",
":",
"return",
":",
"DataFrame",
"or",
"dictionary",
"if",
"columns",
"is",
"a",
"list",
"or",
"value",
"if",
"columns",
"is",
"a",
"single",
"column",
"name"
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L371-L405 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.get_locations | 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) | python | 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) | [
"def",
"get_locations",
"(",
"self",
",",
"locations",
",",
"columns",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"indexes",
"=",
"[",
"self",
".",
"_index",
"[",
"x",
"]",
"for",
"x",
"in",
"locations",
"]",
"return",
"self",
".",
"get",
"(",
"indexes",
",",
"columns",
",",
"*",
"*",
"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 | [
"For",
"list",
"of",
"locations",
"and",
"list",
"of",
"columns",
"return",
"a",
"DataFrame",
"of",
"the",
"values",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L407-L418 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.get_slice | def get_slice(self, start_index=None, stop_index=None, columns=None, as_dict=False):
"""
For sorted DataFrames will return either a DataFrame or dict 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 columns: list of column names to include, or None for all columns
:param as_dict: if True then return a tuple of (list of index, dict of column names: list data values)
:return: DataFrame or tuple
"""
if not self._sort:
raise RuntimeError('Can only use get_slice on sorted DataFrames')
if columns is None:
columns = self._columns
elif all([isinstance(i, bool) for i in columns]):
if len(columns) != len(self._columns):
raise ValueError('boolean column list must be same size of existing columns')
columns = list(compress(self._columns, columns))
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 = dict()
for column in columns:
c = self._columns.index(column)
data[column] = self._data[c][start_location:stop_location]
if as_dict:
return index, data
else:
data = data if data else None # if the dict is empty, convert to None
return DataFrame(data=data, index=index, columns=columns, index_name=self._index_name, sort=self._sort,
use_blist=self._blist) | python | def get_slice(self, start_index=None, stop_index=None, columns=None, as_dict=False):
"""
For sorted DataFrames will return either a DataFrame or dict 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 columns: list of column names to include, or None for all columns
:param as_dict: if True then return a tuple of (list of index, dict of column names: list data values)
:return: DataFrame or tuple
"""
if not self._sort:
raise RuntimeError('Can only use get_slice on sorted DataFrames')
if columns is None:
columns = self._columns
elif all([isinstance(i, bool) for i in columns]):
if len(columns) != len(self._columns):
raise ValueError('boolean column list must be same size of existing columns')
columns = list(compress(self._columns, columns))
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 = dict()
for column in columns:
c = self._columns.index(column)
data[column] = self._data[c][start_location:stop_location]
if as_dict:
return index, data
else:
data = data if data else None # if the dict is empty, convert to None
return DataFrame(data=data, index=index, columns=columns, index_name=self._index_name, sort=self._sort,
use_blist=self._blist) | [
"def",
"get_slice",
"(",
"self",
",",
"start_index",
"=",
"None",
",",
"stop_index",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"as_dict",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"_sort",
":",
"raise",
"RuntimeError",
"(",
"'Can only use get_slice on sorted DataFrames'",
")",
"if",
"columns",
"is",
"None",
":",
"columns",
"=",
"self",
".",
"_columns",
"elif",
"all",
"(",
"[",
"isinstance",
"(",
"i",
",",
"bool",
")",
"for",
"i",
"in",
"columns",
"]",
")",
":",
"if",
"len",
"(",
"columns",
")",
"!=",
"len",
"(",
"self",
".",
"_columns",
")",
":",
"raise",
"ValueError",
"(",
"'boolean column list must be same size of existing columns'",
")",
"columns",
"=",
"list",
"(",
"compress",
"(",
"self",
".",
"_columns",
",",
"columns",
")",
")",
"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",
"=",
"dict",
"(",
")",
"for",
"column",
"in",
"columns",
":",
"c",
"=",
"self",
".",
"_columns",
".",
"index",
"(",
"column",
")",
"data",
"[",
"column",
"]",
"=",
"self",
".",
"_data",
"[",
"c",
"]",
"[",
"start_location",
":",
"stop_location",
"]",
"if",
"as_dict",
":",
"return",
"index",
",",
"data",
"else",
":",
"data",
"=",
"data",
"if",
"data",
"else",
"None",
"# if the dict is empty, convert to None",
"return",
"DataFrame",
"(",
"data",
"=",
"data",
",",
"index",
"=",
"index",
",",
"columns",
"=",
"columns",
",",
"index_name",
"=",
"self",
".",
"_index_name",
",",
"sort",
"=",
"self",
".",
"_sort",
",",
"use_blist",
"=",
"self",
".",
"_blist",
")"
] | For sorted DataFrames will return either a DataFrame or dict 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 columns: list of column names to include, or None for all columns
:param as_dict: if True then return a tuple of (list of index, dict of column names: list data values)
:return: DataFrame or tuple | [
"For",
"sorted",
"DataFrames",
"will",
"return",
"either",
"a",
"DataFrame",
"or",
"dict",
"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",
"columns",
":",
"list",
"of",
"column",
"names",
"to",
"include",
"or",
"None",
"for",
"all",
"columns",
":",
"param",
"as_dict",
":",
"if",
"True",
"then",
"return",
"a",
"tuple",
"of",
"(",
"list",
"of",
"index",
"dict",
"of",
"column",
"names",
":",
"list",
"data",
"values",
")",
":",
"return",
":",
"DataFrame",
"or",
"tuple"
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L420-L457 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame._insert_row | 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) | python | 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) | [
"def",
"_insert_row",
"(",
"self",
",",
"i",
",",
"index",
")",
":",
"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",
")"
] | 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 | [
"Insert",
"a",
"new",
"row",
"in",
"the",
"DataFrame",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L459-L472 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame._add_row | 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) | python | 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) | [
"def",
"_add_row",
"(",
"self",
",",
"index",
")",
":",
"self",
".",
"_index",
".",
"append",
"(",
"index",
")",
"for",
"c",
",",
"_",
"in",
"enumerate",
"(",
"self",
".",
"_columns",
")",
":",
"self",
".",
"_data",
"[",
"c",
"]",
".",
"append",
"(",
"None",
")"
] | Add a new row to the DataFrame
:param index: index of the new row
:return: nothing | [
"Add",
"a",
"new",
"row",
"to",
"the",
"DataFrame"
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L486-L495 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame._add_column | 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)) | python | 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)) | [
"def",
"_add_column",
"(",
"self",
",",
"column",
")",
":",
"self",
".",
"_columns",
".",
"append",
"(",
"column",
")",
"if",
"self",
".",
"_blist",
":",
"self",
".",
"_data",
".",
"append",
"(",
"blist",
"(",
"[",
"None",
"]",
"*",
"len",
"(",
"self",
".",
"_index",
")",
")",
")",
"else",
":",
"self",
".",
"_data",
".",
"append",
"(",
"[",
"None",
"]",
"*",
"len",
"(",
"self",
".",
"_index",
")",
")"
] | Add a new column to the DataFrame
:param column: column name
:return: nothing | [
"Add",
"a",
"new",
"column",
"to",
"the",
"DataFrame"
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L509-L520 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.set | 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') | python | 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') | [
"def",
"set",
"(",
"self",
",",
"indexes",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"values",
"=",
"None",
")",
":",
"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'",
")"
] | 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 | [
"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",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L522-L546 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.set_cell | def set_cell(self, index, column, value):
"""
Sets the value of a single cell. If the index and/or column is not in the current index/columns then a new
index and/or column will be created.
:param index: index value
:param column: column name
: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)
try:
c = self._columns.index(column)
except ValueError:
c = len(self._columns)
self._add_column(column)
self._data[c][i] = value | python | def set_cell(self, index, column, value):
"""
Sets the value of a single cell. If the index and/or column is not in the current index/columns then a new
index and/or column will be created.
:param index: index value
:param column: column name
: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)
try:
c = self._columns.index(column)
except ValueError:
c = len(self._columns)
self._add_column(column)
self._data[c][i] = value | [
"def",
"set_cell",
"(",
"self",
",",
"index",
",",
"column",
",",
"value",
")",
":",
"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",
")",
"try",
":",
"c",
"=",
"self",
".",
"_columns",
".",
"index",
"(",
"column",
")",
"except",
"ValueError",
":",
"c",
"=",
"len",
"(",
"self",
".",
"_columns",
")",
"self",
".",
"_add_column",
"(",
"column",
")",
"self",
".",
"_data",
"[",
"c",
"]",
"[",
"i",
"]",
"=",
"value"
] | Sets the value of a single cell. If the index and/or column is not in the current index/columns then a new
index and/or column will be created.
:param index: index value
:param column: column name
:param value: value to set
:return: nothing | [
"Sets",
"the",
"value",
"of",
"a",
"single",
"cell",
".",
"If",
"the",
"index",
"and",
"/",
"or",
"column",
"is",
"not",
"in",
"the",
"current",
"index",
"/",
"columns",
"then",
"a",
"new",
"index",
"and",
"/",
"or",
"column",
"will",
"be",
"created",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L548-L573 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.set_row | 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.') | python | 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.') | [
"def",
"set_row",
"(",
"self",
",",
"index",
",",
"values",
")",
":",
"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.'",
")"
] | 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 | [
"Sets",
"the",
"values",
"of",
"the",
"columns",
"in",
"a",
"single",
"row",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L575-L599 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.set_column | 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 | python | 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 | [
"def",
"set_column",
"(",
"self",
",",
"index",
"=",
"None",
",",
"column",
"=",
"None",
",",
"values",
"=",
"None",
")",
":",
"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"
] | 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 | [
"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",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L601-L656 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.set_location | def set_location(self, location, values, missing_to_none=False):
"""
Sets the column values, as given by the keys of the values dict, for the row at location to the values of the
values dict. If missing_to_none is False then columns not in the values dict will be left unchanged, if it is
True then they are set to None. This method does not add new columns and raises an error.
:param location: location
:param values: dict of column names as keys and the value as the value to set the row for that column to
:param missing_to_none: if True set any column missing in the values to None, otherwise leave unchanged
:return: nothing
"""
if missing_to_none:
# populate the dict with None in any column missing
for column in self._columns:
if column not in values:
values[column] = None
for column in values:
i = self._columns.index(column)
self._data[i][location] = values[column] | python | def set_location(self, location, values, missing_to_none=False):
"""
Sets the column values, as given by the keys of the values dict, for the row at location to the values of the
values dict. If missing_to_none is False then columns not in the values dict will be left unchanged, if it is
True then they are set to None. This method does not add new columns and raises an error.
:param location: location
:param values: dict of column names as keys and the value as the value to set the row for that column to
:param missing_to_none: if True set any column missing in the values to None, otherwise leave unchanged
:return: nothing
"""
if missing_to_none:
# populate the dict with None in any column missing
for column in self._columns:
if column not in values:
values[column] = None
for column in values:
i = self._columns.index(column)
self._data[i][location] = values[column] | [
"def",
"set_location",
"(",
"self",
",",
"location",
",",
"values",
",",
"missing_to_none",
"=",
"False",
")",
":",
"if",
"missing_to_none",
":",
"# populate the dict with None in any column missing",
"for",
"column",
"in",
"self",
".",
"_columns",
":",
"if",
"column",
"not",
"in",
"values",
":",
"values",
"[",
"column",
"]",
"=",
"None",
"for",
"column",
"in",
"values",
":",
"i",
"=",
"self",
".",
"_columns",
".",
"index",
"(",
"column",
")",
"self",
".",
"_data",
"[",
"i",
"]",
"[",
"location",
"]",
"=",
"values",
"[",
"column",
"]"
] | Sets the column values, as given by the keys of the values dict, for the row at location to the values of the
values dict. If missing_to_none is False then columns not in the values dict will be left unchanged, if it is
True then they are set to None. This method does not add new columns and raises an error.
:param location: location
:param values: dict of column names as keys and the value as the value to set the row for that column to
:param missing_to_none: if True set any column missing in the values to None, otherwise leave unchanged
:return: nothing | [
"Sets",
"the",
"column",
"values",
"as",
"given",
"by",
"the",
"keys",
"of",
"the",
"values",
"dict",
"for",
"the",
"row",
"at",
"location",
"to",
"the",
"values",
"of",
"the",
"values",
"dict",
".",
"If",
"missing_to_none",
"is",
"False",
"then",
"columns",
"not",
"in",
"the",
"values",
"dict",
"will",
"be",
"left",
"unchanged",
"if",
"it",
"is",
"True",
"then",
"they",
"are",
"set",
"to",
"None",
".",
"This",
"method",
"does",
"not",
"add",
"new",
"columns",
"and",
"raises",
"an",
"error",
".",
":",
"param",
"location",
":",
"location",
":",
"param",
"values",
":",
"dict",
"of",
"column",
"names",
"as",
"keys",
"and",
"the",
"value",
"as",
"the",
"value",
"to",
"set",
"the",
"row",
"for",
"that",
"column",
"to",
":",
"param",
"missing_to_none",
":",
"if",
"True",
"set",
"any",
"column",
"missing",
"in",
"the",
"values",
"to",
"None",
"otherwise",
"leave",
"unchanged",
":",
"return",
":",
"nothing"
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L658-L677 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.append_row | 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)) | python | 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)) | [
"def",
"append_row",
"(",
"self",
",",
"index",
",",
"values",
",",
"new_cols",
"=",
"True",
")",
":",
"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",
")",
")"
] | 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 | [
"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",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L691-L716 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.append_rows | 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() | python | 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() | [
"def",
"append_rows",
"(",
"self",
",",
"indexes",
",",
"values",
",",
"new_cols",
"=",
"True",
")",
":",
"# 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",
"(",
")"
] | 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 | [
"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",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L718-L751 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.to_dict | 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 | python | 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 | [
"def",
"to_dict",
"(",
"self",
",",
"index",
"=",
"True",
",",
"ordered",
"=",
"False",
")",
":",
"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"
] | 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() | [
"Returns",
"a",
"dict",
"where",
"the",
"keys",
"are",
"the",
"column",
"names",
"and",
"the",
"values",
"are",
"lists",
"of",
"the",
"values",
"for",
"that",
"column",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L833-L849 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.to_json | def to_json(self):
"""
Returns a JSON of the entire DataFrame that can be reconstructed back with raccoon.from_json(input). Any object
that cannot be serialized will be replaced with the representation of the object using repr(). In that instance
the DataFrame will have a string representation in place of the object and will not reconstruct exactly.
:return: json string
"""
input_dict = {'data': self.to_dict(index=False), 'index': list(self._index)}
# if blist, turn into lists
if self.blist:
input_dict['index'] = list(input_dict['index'])
for key in input_dict['data']:
input_dict['data'][key] = list(input_dict['data'][key])
meta_data = dict()
for key in self.__slots__:
if key not in ['_data', '_index']:
value = self.__getattribute__(key)
meta_data[key.lstrip('_')] = value if not isinstance(value, blist) else list(value)
meta_data['use_blist'] = meta_data.pop('blist')
input_dict['meta_data'] = meta_data
return json.dumps(input_dict, default=repr) | python | def to_json(self):
"""
Returns a JSON of the entire DataFrame that can be reconstructed back with raccoon.from_json(input). Any object
that cannot be serialized will be replaced with the representation of the object using repr(). In that instance
the DataFrame will have a string representation in place of the object and will not reconstruct exactly.
:return: json string
"""
input_dict = {'data': self.to_dict(index=False), 'index': list(self._index)}
# if blist, turn into lists
if self.blist:
input_dict['index'] = list(input_dict['index'])
for key in input_dict['data']:
input_dict['data'][key] = list(input_dict['data'][key])
meta_data = dict()
for key in self.__slots__:
if key not in ['_data', '_index']:
value = self.__getattribute__(key)
meta_data[key.lstrip('_')] = value if not isinstance(value, blist) else list(value)
meta_data['use_blist'] = meta_data.pop('blist')
input_dict['meta_data'] = meta_data
return json.dumps(input_dict, default=repr) | [
"def",
"to_json",
"(",
"self",
")",
":",
"input_dict",
"=",
"{",
"'data'",
":",
"self",
".",
"to_dict",
"(",
"index",
"=",
"False",
")",
",",
"'index'",
":",
"list",
"(",
"self",
".",
"_index",
")",
"}",
"# if blist, turn into lists",
"if",
"self",
".",
"blist",
":",
"input_dict",
"[",
"'index'",
"]",
"=",
"list",
"(",
"input_dict",
"[",
"'index'",
"]",
")",
"for",
"key",
"in",
"input_dict",
"[",
"'data'",
"]",
":",
"input_dict",
"[",
"'data'",
"]",
"[",
"key",
"]",
"=",
"list",
"(",
"input_dict",
"[",
"'data'",
"]",
"[",
"key",
"]",
")",
"meta_data",
"=",
"dict",
"(",
")",
"for",
"key",
"in",
"self",
".",
"__slots__",
":",
"if",
"key",
"not",
"in",
"[",
"'_data'",
",",
"'_index'",
"]",
":",
"value",
"=",
"self",
".",
"__getattribute__",
"(",
"key",
")",
"meta_data",
"[",
"key",
".",
"lstrip",
"(",
"'_'",
")",
"]",
"=",
"value",
"if",
"not",
"isinstance",
"(",
"value",
",",
"blist",
")",
"else",
"list",
"(",
"value",
")",
"meta_data",
"[",
"'use_blist'",
"]",
"=",
"meta_data",
".",
"pop",
"(",
"'blist'",
")",
"input_dict",
"[",
"'meta_data'",
"]",
"=",
"meta_data",
"return",
"json",
".",
"dumps",
"(",
"input_dict",
",",
"default",
"=",
"repr",
")"
] | Returns a JSON of the entire DataFrame that can be reconstructed back with raccoon.from_json(input). Any object
that cannot be serialized will be replaced with the representation of the object using repr(). In that instance
the DataFrame will have a string representation in place of the object and will not reconstruct exactly.
:return: json string | [
"Returns",
"a",
"JSON",
"of",
"the",
"entire",
"DataFrame",
"that",
"can",
"be",
"reconstructed",
"back",
"with",
"raccoon",
".",
"from_json",
"(",
"input",
")",
".",
"Any",
"object",
"that",
"cannot",
"be",
"serialized",
"will",
"be",
"replaced",
"with",
"the",
"representation",
"of",
"the",
"object",
"using",
"repr",
"()",
".",
"In",
"that",
"instance",
"the",
"DataFrame",
"will",
"have",
"a",
"string",
"representation",
"in",
"place",
"of",
"the",
"object",
"and",
"will",
"not",
"reconstruct",
"exactly",
"."
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L851-L874 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.rename_columns | 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] | python | 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] | [
"def",
"rename_columns",
"(",
"self",
",",
"rename_dict",
")",
":",
"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",
"]"
] | Renames the columns
:param rename_dict: dict where the keys are the current column names and the values are the new names
:return: nothing | [
"Renames",
"the",
"columns"
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L876-L886 |
rsheftel/raccoon | raccoon/dataframe.py | DataFrame.delete_all_rows | def delete_all_rows(self):
"""
Deletes the contents of all rows in the DataFrame. This function is faster than delete_rows() to remove all
information, and at the same time it keeps the container lists for the columns and index so if there is another
object that references this DataFrame, like a ViewSeries, the reference remains in tact.
:return: nothing
"""
del self._index[:]
for c in range(len(self._columns)):
del self._data[c][:] | python | def delete_all_rows(self):
"""
Deletes the contents of all rows in the DataFrame. This function is faster than delete_rows() to remove all
information, and at the same time it keeps the container lists for the columns and index so if there is another
object that references this DataFrame, like a ViewSeries, the reference remains in tact.
:return: nothing
"""
del self._index[:]
for c in range(len(self._columns)):
del self._data[c][:] | [
"def",
"delete_all_rows",
"(",
"self",
")",
":",
"del",
"self",
".",
"_index",
"[",
":",
"]",
"for",
"c",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"_columns",
")",
")",
":",
"del",
"self",
".",
"_data",
"[",
"c",
"]",
"[",
":",
"]"
] | Deletes the contents of all rows in the DataFrame. This function is faster than delete_rows() to remove all
information, and at the same time it keeps the container lists for the columns and index so if there is another
object that references this DataFrame, like a ViewSeries, the reference remains in tact.
:return: nothing | [
"Deletes",
"the",
"contents",
"of",
"all",
"rows",
"in",
"the",
"DataFrame",
".",
"This",
"function",
"is",
"faster",
"than",
"delete_rows",
"()",
"to",
"remove",
"all",
"information",
"and",
"at",
"the",
"same",
"time",
"it",
"keeps",
"the",
"container",
"lists",
"for",
"the",
"columns",
"and",
"index",
"so",
"if",
"there",
"is",
"another",
"object",
"that",
"references",
"this",
"DataFrame",
"like",
"a",
"ViewSeries",
"the",
"reference",
"remains",
"in",
"tact",
".",
":",
"return",
":",
"nothing"
] | train | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L933-L943 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.