identifier
stringlengths 0
89
| parameters
stringlengths 0
399
| return_statement
stringlengths 0
982
⌀ | docstring
stringlengths 10
3.04k
| docstring_summary
stringlengths 0
3.04k
| function
stringlengths 13
25.8k
| function_tokens
sequence | start_point
sequence | end_point
sequence | argument_list
null | language
stringclasses 3
values | docstring_language
stringclasses 4
values | docstring_language_predictions
stringclasses 4
values | is_langid_reliable
stringclasses 2
values | is_langid_extra_reliable
bool 1
class | type
stringclasses 9
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
makeDBnomes | (PATH, save_to_disk = False) | return df, dfRuim | Lê todos os XML indicados no caminho e extrai informações mínimas. Nome do Arquivo, CPF, ID_CNself e NOME. Se arquivo não tiver informações corretas, produz outro dataframe.
Args:
PATH (type): caminho (pode usar glob) `PATH`.
save_to_disk (type): Grava ou não o resultado na pasta /data/external/ `save_to_disk`. Defaults to False.
Returns:
type:Um dataframe com sucessos e um dataframe com fracassos.
| Lê todos os XML indicados no caminho e extrai informações mínimas. Nome do Arquivo, CPF, ID_CNself e NOME. Se arquivo não tiver informações corretas, produz outro dataframe. | def makeDBnomes(PATH, save_to_disk = False):
"""Lê todos os XML indicados no caminho e extrai informações mínimas. Nome do Arquivo, CPF, ID_CNself e NOME. Se arquivo não tiver informações corretas, produz outro dataframe.
Args:
PATH (type): caminho (pode usar glob) `PATH`.
save_to_disk (type): Grava ou não o resultado na pasta /data/external/ `save_to_disk`. Defaults to False.
Returns:
type:Um dataframe com sucessos e um dataframe com fracassos.
"""
#----Le todas as pastas e subpastas indicadas para busca de XML
files = readFolder(PATH)
nomes = []
problemas = []
for file in files:
NOME = []
CPF = []
ID = []
try:
#----XML funciona?
tree = etree.parse(file)
except etree.XMLSyntaxError:
#LOG.error("XML inválido: %s", file)
problemas.append([file, ID, CPF, NOME])
except (ParserError, ParseError) as error:
#LOG.error("XML inválido: %s", file)
problemas.append([file, ID, CPF, NOME])
else:
root = tree.getroot()
try:
CPF = root.find('DADOS-GERAIS').attrib['CPF']
except (KeyError, AttributeError) as error:
CPF = np.nan
try:
NOME = root.find('DADOS-GERAIS').attrib['NOME-COMPLETO']
except (KeyError, AttributeError) as error:
NOME = np.nan
try:
ID = root.attrib['NUMERO-IDENTIFICADOR']
except (KeyError, AttributeError) as error:
#LOG.error("XML inválido: %s", file)
problemas.append([file, ID, CPF, NOME])
ID = np.nan
nomes.append([file, ID, CPF, NOME])
if len(nomes) != 0:
df = pd.DataFrame(nomes)
df.columns = ['FILE','ID', 'CPF','NOME']
if len(problemas) !=0:
dfProblema = pd.DataFrame(problemas)
dfProblema.columns = ['FILE','ID', 'CPF','NOME']
else:
df = pd.DataFrame()
#----Apenas nome do arquivo dentro do pacote
df['FILE']= df['FILE'].apply( lambda val: '../../' + '/'.join(val.split('/')[-5:]))
#----Nome completo, tudo em maíusculas e sem acentos, normalizado para comparações.
dfRuim = df[ ( (df['NOME'].isna()) | (df['CPF'].isna()) | (df['ID'].isna()) )]
dfRuim = pd.concat([dfRuim, dfProblema], axis = 0)
df = df.dropna()
df = df.groupby(['NOME']).first().reset_index()
df['NOME']=df['NOME'].apply(lambda val: unidecode(val.upper()))
#----Salva arquivo XLSX
if save_to_disk:
PATH = pathHandler('../../data/external/DBnomes.xlsx')
PATHRuim = pathHandler('../../data/external/XMLruim.xlsx')
df.to_excel(PATH, index=False)
dfRuim.to_excel(PATHRuim, index=False)
return df, dfRuim | [
"def",
"makeDBnomes",
"(",
"PATH",
",",
"save_to_disk",
"=",
"False",
")",
":",
"#----Le todas as pastas e subpastas indicadas para busca de XML",
"files",
"=",
"readFolder",
"(",
"PATH",
")",
"nomes",
"=",
"[",
"]",
"problemas",
"=",
"[",
"]",
"for",
"file",
"in",
"files",
":",
"NOME",
"=",
"[",
"]",
"CPF",
"=",
"[",
"]",
"ID",
"=",
"[",
"]",
"try",
":",
"#----XML funciona?",
"tree",
"=",
"etree",
".",
"parse",
"(",
"file",
")",
"except",
"etree",
".",
"XMLSyntaxError",
":",
"#LOG.error(\"XML inválido: %s\", file)",
"problemas",
".",
"append",
"(",
"[",
"file",
",",
"ID",
",",
"CPF",
",",
"NOME",
"]",
")",
"except",
"(",
"ParserError",
",",
"ParseError",
")",
"as",
"error",
":",
"#LOG.error(\"XML inválido: %s\", file)",
"problemas",
".",
"append",
"(",
"[",
"file",
",",
"ID",
",",
"CPF",
",",
"NOME",
"]",
")",
"else",
":",
"root",
"=",
"tree",
".",
"getroot",
"(",
")",
"try",
":",
"CPF",
"=",
"root",
".",
"find",
"(",
"'DADOS-GERAIS'",
")",
".",
"attrib",
"[",
"'CPF'",
"]",
"except",
"(",
"KeyError",
",",
"AttributeError",
")",
"as",
"error",
":",
"CPF",
"=",
"np",
".",
"nan",
"try",
":",
"NOME",
"=",
"root",
".",
"find",
"(",
"'DADOS-GERAIS'",
")",
".",
"attrib",
"[",
"'NOME-COMPLETO'",
"]",
"except",
"(",
"KeyError",
",",
"AttributeError",
")",
"as",
"error",
":",
"NOME",
"=",
"np",
".",
"nan",
"try",
":",
"ID",
"=",
"root",
".",
"attrib",
"[",
"'NUMERO-IDENTIFICADOR'",
"]",
"except",
"(",
"KeyError",
",",
"AttributeError",
")",
"as",
"error",
":",
"#LOG.error(\"XML inválido: %s\", file)",
"problemas",
".",
"append",
"(",
"[",
"file",
",",
"ID",
",",
"CPF",
",",
"NOME",
"]",
")",
"ID",
"=",
"np",
".",
"nan",
"nomes",
".",
"append",
"(",
"[",
"file",
",",
"ID",
",",
"CPF",
",",
"NOME",
"]",
")",
"if",
"len",
"(",
"nomes",
")",
"!=",
"0",
":",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"nomes",
")",
"df",
".",
"columns",
"=",
"[",
"'FILE'",
",",
"'ID'",
",",
"'CPF'",
",",
"'NOME'",
"]",
"if",
"len",
"(",
"problemas",
")",
"!=",
"0",
":",
"dfProblema",
"=",
"pd",
".",
"DataFrame",
"(",
"problemas",
")",
"dfProblema",
".",
"columns",
"=",
"[",
"'FILE'",
",",
"'ID'",
",",
"'CPF'",
",",
"'NOME'",
"]",
"else",
":",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
")",
"#----Apenas nome do arquivo dentro do pacote",
"df",
"[",
"'FILE'",
"]",
"=",
"df",
"[",
"'FILE'",
"]",
".",
"apply",
"(",
"lambda",
"val",
":",
"'../../'",
"+",
"'/'",
".",
"join",
"(",
"val",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"5",
":",
"]",
")",
")",
"#----Nome completo, tudo em maíusculas e sem acentos, normalizado para comparações.",
"dfRuim",
"=",
"df",
"[",
"(",
"(",
"df",
"[",
"'NOME'",
"]",
".",
"isna",
"(",
")",
")",
"|",
"(",
"df",
"[",
"'CPF'",
"]",
".",
"isna",
"(",
")",
")",
"|",
"(",
"df",
"[",
"'ID'",
"]",
".",
"isna",
"(",
")",
")",
")",
"]",
"dfRuim",
"=",
"pd",
".",
"concat",
"(",
"[",
"dfRuim",
",",
"dfProblema",
"]",
",",
"axis",
"=",
"0",
")",
"df",
"=",
"df",
".",
"dropna",
"(",
")",
"df",
"=",
"df",
".",
"groupby",
"(",
"[",
"'NOME'",
"]",
")",
".",
"first",
"(",
")",
".",
"reset_index",
"(",
")",
"df",
"[",
"'NOME'",
"]",
"=",
"df",
"[",
"'NOME'",
"]",
".",
"apply",
"(",
"lambda",
"val",
":",
"unidecode",
"(",
"val",
".",
"upper",
"(",
")",
")",
")",
"#----Salva arquivo XLSX",
"if",
"save_to_disk",
":",
"PATH",
"=",
"pathHandler",
"(",
"'../../data/external/DBnomes.xlsx'",
")",
"PATHRuim",
"=",
"pathHandler",
"(",
"'../../data/external/XMLruim.xlsx'",
")",
"df",
".",
"to_excel",
"(",
"PATH",
",",
"index",
"=",
"False",
")",
"dfRuim",
".",
"to_excel",
"(",
"PATHRuim",
",",
"index",
"=",
"False",
")",
"return",
"df",
",",
"dfRuim"
] | [
113,
0
] | [
183,
21
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
quick_sort | (values) | Ordena uma lista, em ordem crescente, usando o Quick Sort.
O Quick Sort possui uma boa eficiência, no entanto, em
seu pior caso tem complexidade O(n^2).Ele funciona fazendo
sucessivos particionamentos com uso de recursão. O
particionamento basicamente pega um valor pivô e move todos
valores menores para trás dele e todos os maiores para depois,
dessa forma o pivô ficará posicionado corretamente. Já a recursão
atua fazendo sucessivos particionamentos nas sublistas antes e
depois de cada pivô particionado até chegar em sublistas com
menos que 2 elementos.
Parameters
----------
values : list
A lista que deve ser ordenada
| Ordena uma lista, em ordem crescente, usando o Quick Sort. | def quick_sort(values):
""" Ordena uma lista, em ordem crescente, usando o Quick Sort.
O Quick Sort possui uma boa eficiência, no entanto, em
seu pior caso tem complexidade O(n^2).Ele funciona fazendo
sucessivos particionamentos com uso de recursão. O
particionamento basicamente pega um valor pivô e move todos
valores menores para trás dele e todos os maiores para depois,
dessa forma o pivô ficará posicionado corretamente. Já a recursão
atua fazendo sucessivos particionamentos nas sublistas antes e
depois de cada pivô particionado até chegar em sublistas com
menos que 2 elementos.
Parameters
----------
values : list
A lista que deve ser ordenada
"""
quick_sort_recursion(values,0,len(values)-1) | [
"def",
"quick_sort",
"(",
"values",
")",
":",
"quick_sort_recursion",
"(",
"values",
",",
"0",
",",
"len",
"(",
"values",
")",
"-",
"1",
")"
] | [
75,
0
] | [
93,
48
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
remover_usuario_sessions_flow | (whatsapp) | esta função remove o usuário da database de sessions | esta função remove o usuário da database de sessions | def remover_usuario_sessions_flow(whatsapp):
"""esta função remove o usuário da database de sessions"""
id_documento = db.collection(u'sessions_flow').where(u'usuario', u'==', whatsapp).stream()
for documento in id_documento:
id = documento.id
return db.collection(u'sessions_flow').document(id).delete() | [
"def",
"remover_usuario_sessions_flow",
"(",
"whatsapp",
")",
":",
"id_documento",
"=",
"db",
".",
"collection",
"(",
"u'sessions_flow'",
")",
".",
"where",
"(",
"u'usuario'",
",",
"u'=='",
",",
"whatsapp",
")",
".",
"stream",
"(",
")",
"for",
"documento",
"in",
"id_documento",
":",
"id",
"=",
"documento",
".",
"id",
"return",
"db",
".",
"collection",
"(",
"u'sessions_flow'",
")",
".",
"document",
"(",
"id",
")",
".",
"delete",
"(",
")"
] | [
49,
0
] | [
54,
68
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
index_map | () | return dumps({"artistas": "url/artistas",
"albuns": "url/albuns"}) | Retornar um mapa completo da API. | Retornar um mapa completo da API. | def index_map():
"""Retornar um mapa completo da API."""
return dumps({"artistas": "url/artistas",
"albuns": "url/albuns"}) | [
"def",
"index_map",
"(",
")",
":",
"return",
"dumps",
"(",
"{",
"\"artistas\"",
":",
"\"url/artistas\"",
",",
"\"albuns\"",
":",
"\"url/albuns\"",
"}",
")"
] | [
13,
0
] | [
16,
42
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Restaurant.read_number | (self) | return parcial_number | Retorna o número de clientes atendidos. | Retorna o número de clientes atendidos. | def read_number(self):
"""Retorna o número de clientes atendidos."""
parcial_number = 'Estão sendo atendidos ' + str(self.number_served) + ' clientes.'
return parcial_number | [
"def",
"read_number",
"(",
"self",
")",
":",
"parcial_number",
"=",
"'Estão sendo atendidos ' ",
" ",
"tr(",
"s",
"elf.",
"n",
"umber_served)",
" ",
" ",
" clientes.'",
"return",
"parcial_number"
] | [
44,
4
] | [
47,
29
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
User.__init__ | (self, first_name, last_name, login_attempts) | Inicia os atributos do usuário. | Inicia os atributos do usuário. | def __init__(self, first_name, last_name, login_attempts):
"""Inicia os atributos do usuário."""
self.first_name = first_name
self.last_name = last_name
self.login_attempts = login_attempts | [
"def",
"__init__",
"(",
"self",
",",
"first_name",
",",
"last_name",
",",
"login_attempts",
")",
":",
"self",
".",
"first_name",
"=",
"first_name",
"self",
".",
"last_name",
"=",
"last_name",
"self",
".",
"login_attempts",
"=",
"login_attempts"
] | [
25,
4
] | [
29,
44
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Problem.actions | (self, state) | Retornar as ações que podem ser executadas no dado
estado. O resultado normalmente seria uma lista, mas se houver
muitas ações, considere levá-las de uma em uma
iteração, ao invés de construí-los todos de uma vez. | Retornar as ações que podem ser executadas no dado
estado. O resultado normalmente seria uma lista, mas se houver
muitas ações, considere levá-las de uma em uma
iteração, ao invés de construí-los todos de uma vez. | def actions(self, state):
"""Retornar as ações que podem ser executadas no dado
estado. O resultado normalmente seria uma lista, mas se houver
muitas ações, considere levá-las de uma em uma
iteração, ao invés de construí-los todos de uma vez."""
raise NotImplementedError | [
"def",
"actions",
"(",
"self",
",",
"state",
")",
":",
"raise",
"NotImplementedError"
] | [
32,
4
] | [
37,
33
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
conferir_ambiente | (whatsapp) | esta função verifica em qual ambiente o nosso usuário se encontra no momento,
podendo ser: 1) chatbot: falando com o watson,
2) atendimento humanizado: na sala de bate papo,
3) fila de espera: no aguardo para que alguma sala seja liberada | esta função verifica em qual ambiente o nosso usuário se encontra no momento,
podendo ser: 1) chatbot: falando com o watson,
2) atendimento humanizado: na sala de bate papo,
3) fila de espera: no aguardo para que alguma sala seja liberada | def conferir_ambiente(whatsapp):
"""esta função verifica em qual ambiente o nosso usuário se encontra no momento,
podendo ser: 1) chatbot: falando com o watson,
2) atendimento humanizado: na sala de bate papo,
3) fila de espera: no aguardo para que alguma sala seja liberada"""
ambiente_usuario = db.collection(u'ambiente_usuario')
consulta = ambiente_usuario.where(u'usuario', u'==', whatsapp).stream()
for query in consulta:
if bool(query.to_dict().get(u'chatbot')) == True:
return 'chatbot'
if bool(query.to_dict().get(u'atendimento_humanizado')) == True:
return 'atendimento_humanizado'
if bool(query.to_dict().get(u'fila_espera')) == True:
return 'fila_espera' | [
"def",
"conferir_ambiente",
"(",
"whatsapp",
")",
":",
"ambiente_usuario",
"=",
"db",
".",
"collection",
"(",
"u'ambiente_usuario'",
")",
"consulta",
"=",
"ambiente_usuario",
".",
"where",
"(",
"u'usuario'",
",",
"u'=='",
",",
"whatsapp",
")",
".",
"stream",
"(",
")",
"for",
"query",
"in",
"consulta",
":",
"if",
"bool",
"(",
"query",
".",
"to_dict",
"(",
")",
".",
"get",
"(",
"u'chatbot'",
")",
")",
"==",
"True",
":",
"return",
"'chatbot'",
"if",
"bool",
"(",
"query",
".",
"to_dict",
"(",
")",
".",
"get",
"(",
"u'atendimento_humanizado'",
")",
")",
"==",
"True",
":",
"return",
"'atendimento_humanizado'",
"if",
"bool",
"(",
"query",
".",
"to_dict",
"(",
")",
".",
"get",
"(",
"u'fila_espera'",
")",
")",
"==",
"True",
":",
"return",
"'fila_espera'"
] | [
59,
0
] | [
74,
32
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
datetime_utcnow_aware | () | return datetime.utcnow().replace(tzinfo=timezone.utc) | Data e hora UTC com informação de timezone. | Data e hora UTC com informação de timezone. | def datetime_utcnow_aware() -> datetime:
"""Data e hora UTC com informação de timezone."""
return datetime.utcnow().replace(tzinfo=timezone.utc) | [
"def",
"datetime_utcnow_aware",
"(",
")",
"->",
"datetime",
":",
"return",
"datetime",
".",
"utcnow",
"(",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"timezone",
".",
"utc",
")"
] | [
114,
0
] | [
116,
57
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
check_files | (file_paths) | Verifica todos os arquivos da lista de caminhos de arquivo.
Args:
file_paths (List[str]): Lista com caminho para os arquivos.
| Verifica todos os arquivos da lista de caminhos de arquivo. | def check_files(file_paths):
"""Verifica todos os arquivos da lista de caminhos de arquivo.
Args:
file_paths (List[str]): Lista com caminho para os arquivos.
"""
for file_path in file_paths:
logging.info(f'Verificando o arquivo {file_path}')
with open(os.path.join(DIR, file_path), encoding='utf-8-sig', mode='r') as f:
if file_path.endswith('.json'):
check_dict(json.loads(f.read()))
elif file_path.endswith('.csv'):
check_dict(csv.DictReader(f))
logging.info(f"Tudo certo com o arquivo {file_path}") | [
"def",
"check_files",
"(",
"file_paths",
")",
":",
"for",
"file_path",
"in",
"file_paths",
":",
"logging",
".",
"info",
"(",
"f'Verificando o arquivo {file_path}'",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"DIR",
",",
"file_path",
")",
",",
"encoding",
"=",
"'utf-8-sig'",
",",
"mode",
"=",
"'r'",
")",
"as",
"f",
":",
"if",
"file_path",
".",
"endswith",
"(",
"'.json'",
")",
":",
"check_dict",
"(",
"json",
".",
"loads",
"(",
"f",
".",
"read",
"(",
")",
")",
")",
"elif",
"file_path",
".",
"endswith",
"(",
"'.csv'",
")",
":",
"check_dict",
"(",
"csv",
".",
"DictReader",
"(",
"f",
")",
")",
"logging",
".",
"info",
"(",
"f\"Tudo certo com o arquivo {file_path}\"",
")"
] | [
42,
0
] | [
55,
65
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
GroupVirtualResource.handle_delete | (self, request, user, *args, **kwargs) | Trata as requisições de PUT para remover um grupo virtual.
URL: /grupovirtual/
| Trata as requisições de PUT para remover um grupo virtual. | def handle_delete(self, request, user, *args, **kwargs):
"""Trata as requisições de PUT para remover um grupo virtual.
URL: /grupovirtual/
"""
try:
xml_map, attrs_map = loads(
request.raw_post_data, ['vip', 'equipamento', 'id_equipamento'])
except XMLError, x:
self.log.error(u'Erro ao ler o XML da requisição.')
return self.response_error(3, x)
networkapi_map = xml_map.get('networkapi')
if networkapi_map is None:
return self.response_error(3, u'Não existe valor para a tag networkapi do XML de requisição.')
vips_map = networkapi_map.get('vips')
try:
equipments_map = networkapi_map['equipamentos']
except KeyError:
return self.response_error(3, u'XML de requisição inválido.')
try:
with distributedlock(LOCK_GROUP_VIRTUAL):
# Vips
if vips_map is not None:
try:
vip_maps = vips_map['vip']
for vip_map in vip_maps:
balanceadores_map = vip_map['balanceadores']
if balanceadores_map is None:
return self.response_error(3, u'Valor da tag balanceadores do XML de requisição inválido.')
ip_id = vip_map['id_ip']
try:
ip_id = int(ip_id)
except (TypeError, ValueError), e:
self.log.error(
u'Valor do id_ip inválido: %s.', ip_id)
raise IpNotFoundError(
e, u'Valor do id_ip inválido: %s.' % ip_id)
vip_s = RequisicaoVips.get_by_ipv4_id(ip_id)
# Run scripts to remove vips
for vip in vip_s:
# Make command
command = VIP_REMOVE % (vip.id)
# Execute command
code, stdout, stderr = exec_script(command)
if code == 0:
vip.vip_criado = 0
vip.save()
# SYNC_VIP
old_to_new(vip)
else:
return self.response_error(2, stdout + stderr)
equipment_ids = balanceadores_map['id_equipamento']
for equip_id in equipment_ids:
try:
equip_id = int(equip_id)
except (TypeError, ValueError), e:
self.log.error(
u'Valor do id_equipamento inválido: %s.', equip_id)
raise EquipamentoNotFoundError(
e, u'Valor do id_equipamento inválido: %s.' % equip_id)
remove_ip_equipment(ip_id, equip_id, user)
except KeyError:
return self.response_error(3, u'Valor das tags vips/vip do XML de requisição inválido.')
# Equipamentos
if equipments_map is not None:
try:
equipment_maps = equipments_map['equipamento']
for equipment_map in equipment_maps:
equip_id = equipment_map['id']
try:
equip_id = int(equip_id)
except (TypeError, ValueError), e:
self.log.error(
u'Valor do id do equipamento inválido: %s.', equip_id)
raise EquipamentoNotFoundError(
e, u'Valor do id do equipamento inválido: %s.' % equip_id)
remove_equipment(equip_id, user)
except KeyError:
return self.response_error(3, u'Valor das tags equipamentos/equipamento do XML de requisição inválido.')
return self.response(dumps_networkapi({}))
except IpNotFoundError:
return self.response_error(119)
except IpEquipmentNotFoundError:
return self.response_error(118, ip_id, equip_id)
except EquipamentoNotFoundError:
return self.response_error(117, equip_id)
except UserNotAuthorizedError:
return self.not_authorized()
except ScriptError, s:
return self.response_error(2, s)
except (IpError, EquipamentoError, GrupoError, RequisicaoVipsError) as e:
self.log.error(e)
return self.response_error(1) | [
"def",
"handle_delete",
"(",
"self",
",",
"request",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"xml_map",
",",
"attrs_map",
"=",
"loads",
"(",
"request",
".",
"raw_post_data",
",",
"[",
"'vip'",
",",
"'equipamento'",
",",
"'id_equipamento'",
"]",
")",
"except",
"XMLError",
",",
"x",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Erro ao ler o XML da requisição.')",
"",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"x",
")",
"networkapi_map",
"=",
"xml_map",
".",
"get",
"(",
"'networkapi'",
")",
"if",
"networkapi_map",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"u'Não existe valor para a tag networkapi do XML de requisição.')",
"",
"vips_map",
"=",
"networkapi_map",
".",
"get",
"(",
"'vips'",
")",
"try",
":",
"equipments_map",
"=",
"networkapi_map",
"[",
"'equipamentos'",
"]",
"except",
"KeyError",
":",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"u'XML de requisição inválido.')",
"",
"try",
":",
"with",
"distributedlock",
"(",
"LOCK_GROUP_VIRTUAL",
")",
":",
"# Vips",
"if",
"vips_map",
"is",
"not",
"None",
":",
"try",
":",
"vip_maps",
"=",
"vips_map",
"[",
"'vip'",
"]",
"for",
"vip_map",
"in",
"vip_maps",
":",
"balanceadores_map",
"=",
"vip_map",
"[",
"'balanceadores'",
"]",
"if",
"balanceadores_map",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"u'Valor da tag balanceadores do XML de requisição inválido.')",
"",
"ip_id",
"=",
"vip_map",
"[",
"'id_ip'",
"]",
"try",
":",
"ip_id",
"=",
"int",
"(",
"ip_id",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
",",
"e",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Valor do id_ip inválido: %s.',",
" ",
"p_id)",
"",
"raise",
"IpNotFoundError",
"(",
"e",
",",
"u'Valor do id_ip inválido: %s.' ",
" ",
"p_id)",
"",
"vip_s",
"=",
"RequisicaoVips",
".",
"get_by_ipv4_id",
"(",
"ip_id",
")",
"# Run scripts to remove vips",
"for",
"vip",
"in",
"vip_s",
":",
"# Make command",
"command",
"=",
"VIP_REMOVE",
"%",
"(",
"vip",
".",
"id",
")",
"# Execute command",
"code",
",",
"stdout",
",",
"stderr",
"=",
"exec_script",
"(",
"command",
")",
"if",
"code",
"==",
"0",
":",
"vip",
".",
"vip_criado",
"=",
"0",
"vip",
".",
"save",
"(",
")",
"# SYNC_VIP",
"old_to_new",
"(",
"vip",
")",
"else",
":",
"return",
"self",
".",
"response_error",
"(",
"2",
",",
"stdout",
"+",
"stderr",
")",
"equipment_ids",
"=",
"balanceadores_map",
"[",
"'id_equipamento'",
"]",
"for",
"equip_id",
"in",
"equipment_ids",
":",
"try",
":",
"equip_id",
"=",
"int",
"(",
"equip_id",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
",",
"e",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Valor do id_equipamento inválido: %s.',",
" ",
"quip_id)",
"",
"raise",
"EquipamentoNotFoundError",
"(",
"e",
",",
"u'Valor do id_equipamento inválido: %s.' ",
" ",
"quip_id)",
"",
"remove_ip_equipment",
"(",
"ip_id",
",",
"equip_id",
",",
"user",
")",
"except",
"KeyError",
":",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"u'Valor das tags vips/vip do XML de requisição inválido.')",
"",
"# Equipamentos",
"if",
"equipments_map",
"is",
"not",
"None",
":",
"try",
":",
"equipment_maps",
"=",
"equipments_map",
"[",
"'equipamento'",
"]",
"for",
"equipment_map",
"in",
"equipment_maps",
":",
"equip_id",
"=",
"equipment_map",
"[",
"'id'",
"]",
"try",
":",
"equip_id",
"=",
"int",
"(",
"equip_id",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
",",
"e",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Valor do id do equipamento inválido: %s.',",
" ",
"quip_id)",
"",
"raise",
"EquipamentoNotFoundError",
"(",
"e",
",",
"u'Valor do id do equipamento inválido: %s.' ",
" ",
"quip_id)",
"",
"remove_equipment",
"(",
"equip_id",
",",
"user",
")",
"except",
"KeyError",
":",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"u'Valor das tags equipamentos/equipamento do XML de requisição inválido.')",
"",
"return",
"self",
".",
"response",
"(",
"dumps_networkapi",
"(",
"{",
"}",
")",
")",
"except",
"IpNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"119",
")",
"except",
"IpEquipmentNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"118",
",",
"ip_id",
",",
"equip_id",
")",
"except",
"EquipamentoNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"117",
",",
"equip_id",
")",
"except",
"UserNotAuthorizedError",
":",
"return",
"self",
".",
"not_authorized",
"(",
")",
"except",
"ScriptError",
",",
"s",
":",
"return",
"self",
".",
"response_error",
"(",
"2",
",",
"s",
")",
"except",
"(",
"IpError",
",",
"EquipamentoError",
",",
"GrupoError",
",",
"RequisicaoVipsError",
")",
"as",
"e",
":",
"self",
".",
"log",
".",
"error",
"(",
"e",
")",
"return",
"self",
".",
"response_error",
"(",
"1",
")"
] | [
84,
4
] | [
193,
41
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
RestClient.delete | (self, url, request_data=None, content_type=None, auth_map=None) | Envia uma requisição DELETE para a url informada.
Retorna uma tupla contendo:
(<código de resposta http>, <corpo da resposta>).
| Envia uma requisição DELETE para a url informada.
Retorna uma tupla contendo:
(<código de resposta http>, <corpo da resposta>).
| def delete(self, url, request_data=None, content_type=None, auth_map=None):
"""Envia uma requisição DELETE para a url informada.
Retorna uma tupla contendo:
(<código de resposta http>, <corpo da resposta>).
"""
try:
parsed_url = urlparse(url)
connection = HTTPConnection(parsed_url.hostname, parsed_url.port)
headers_map = dict()
if auth_map is None:
headers_map['NETWORKAPI_USERNAME'] = 'ORQUESTRACAO'
headers_map[
'NETWORKAPI_PASSWORD'] = '93522a36bf2a18e0cc25857e06bbfe8b'
else:
headers_map.update(auth_map)
if content_type is not None:
headers_map['Content-Type'] = content_type
connection.request(
"DELETE", parsed_url.path, request_data, headers_map)
response = connection.getresponse()
return response.status, response.read()
except Exception, e:
raise RestError(e, e.message)
finally:
connection.close() | [
"def",
"delete",
"(",
"self",
",",
"url",
",",
"request_data",
"=",
"None",
",",
"content_type",
"=",
"None",
",",
"auth_map",
"=",
"None",
")",
":",
"try",
":",
"parsed_url",
"=",
"urlparse",
"(",
"url",
")",
"connection",
"=",
"HTTPConnection",
"(",
"parsed_url",
".",
"hostname",
",",
"parsed_url",
".",
"port",
")",
"headers_map",
"=",
"dict",
"(",
")",
"if",
"auth_map",
"is",
"None",
":",
"headers_map",
"[",
"'NETWORKAPI_USERNAME'",
"]",
"=",
"'ORQUESTRACAO'",
"headers_map",
"[",
"'NETWORKAPI_PASSWORD'",
"]",
"=",
"'93522a36bf2a18e0cc25857e06bbfe8b'",
"else",
":",
"headers_map",
".",
"update",
"(",
"auth_map",
")",
"if",
"content_type",
"is",
"not",
"None",
":",
"headers_map",
"[",
"'Content-Type'",
"]",
"=",
"content_type",
"connection",
".",
"request",
"(",
"\"DELETE\"",
",",
"parsed_url",
".",
"path",
",",
"request_data",
",",
"headers_map",
")",
"response",
"=",
"connection",
".",
"getresponse",
"(",
")",
"return",
"response",
".",
"status",
",",
"response",
".",
"read",
"(",
")",
"except",
"Exception",
",",
"e",
":",
"raise",
"RestError",
"(",
"e",
",",
"e",
".",
"message",
")",
"finally",
":",
"connection",
".",
"close",
"(",
")"
] | [
106,
4
] | [
134,
30
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Admin.show_privileges | (self) | Exibe os privilégios do administrador | Exibe os privilégios do administrador | def show_privileges(self):
"""Exibe os privilégios do administrador"""
print(self.privileges) | [
"def",
"show_privileges",
"(",
"self",
")",
":",
"print",
"(",
"self",
".",
"privileges",
")"
] | [
57,
4
] | [
59,
30
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Settings.initialize_dynamic_settings | (self) | Inicializa as configuracoes que mudam no decorrer do jogo. | Inicializa as configuracoes que mudam no decorrer do jogo. | def initialize_dynamic_settings(self):
"""Inicializa as configuracoes que mudam no decorrer do jogo."""
self.ship_speed_factor = 3
self.bullet_speed_factor = 3
self.alien_speed_factor = 1
# fleet_direction igual a 1 representa a direita;
# -1 representa a esquerda
self.fleet_direction = 1
# Pontuacao
self.alien_points = 50 | [
"def",
"initialize_dynamic_settings",
"(",
"self",
")",
":",
"self",
".",
"ship_speed_factor",
"=",
"3",
"self",
".",
"bullet_speed_factor",
"=",
"3",
"self",
".",
"alien_speed_factor",
"=",
"1",
"# fleet_direction igual a 1 representa a direita;",
"# -1 representa a esquerda",
"self",
".",
"fleet_direction",
"=",
"1",
"# Pontuacao",
"self",
".",
"alien_points",
"=",
"50"
] | [
32,
4
] | [
42,
30
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
get_files_in_path | (path: str, extension) | return files | Retorna uma lista com os arquivos encontrados em um determinado path | Retorna uma lista com os arquivos encontrados em um determinado path | def get_files_in_path(path: str, extension) -> List[str]:
"""Retorna uma lista com os arquivos encontrados em um determinado path"""
if os.path.isfile(path):
return [path]
files = []
for root, _, folder_files in os.walk(path):
files.extend(
[
os.path.realpath(os.path.join(root, file))
for file in folder_files
if file.endswith(extension)
]
)
return files | [
"def",
"get_files_in_path",
"(",
"path",
":",
"str",
",",
"extension",
")",
"->",
"List",
"[",
"str",
"]",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"return",
"[",
"path",
"]",
"files",
"=",
"[",
"]",
"for",
"root",
",",
"_",
",",
"folder_files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"files",
".",
"extend",
"(",
"[",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"file",
")",
")",
"for",
"file",
"in",
"folder_files",
"if",
"file",
".",
"endswith",
"(",
"extension",
")",
"]",
")",
"return",
"files"
] | [
172,
0
] | [
187,
16
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
is_subnetwork | (network_address_01, network_address_02) | return network_address_02[0:4] == _applyNetmask(network_address_01, network_mask_02) | Verifica se o endereço network_address_01 é sub-rede do endereço network_address_02.
@param network_address_01: Uma tuple com os octetos do endereço, formato: (oct1, oct2, oct3, oct5)
@param network_address_02: Uma tuple com os octetos do endereço e o bloco, formato: (oct1, oct2, oct3, oct5, bloco)
@return: True se network_address_01 é sub-rede de network_address_02. False caso contrário.
| Verifica se o endereço network_address_01 é sub-rede do endereço network_address_02. | def is_subnetwork(network_address_01, network_address_02):
"""Verifica se o endereço network_address_01 é sub-rede do endereço network_address_02.
@param network_address_01: Uma tuple com os octetos do endereço, formato: (oct1, oct2, oct3, oct5)
@param network_address_02: Uma tuple com os octetos do endereço e o bloco, formato: (oct1, oct2, oct3, oct5, bloco)
@return: True se network_address_01 é sub-rede de network_address_02. False caso contrário.
"""
if network_address_01 is None or network_address_02 is None:
return False
if len(network_address_01) < 4 or len(network_address_02) != 5:
return False
network_mask_02 = network_mask_from_cidr_mask(network_address_02[4])
return network_address_02[0:4] == _applyNetmask(network_address_01, network_mask_02) | [
"def",
"is_subnetwork",
"(",
"network_address_01",
",",
"network_address_02",
")",
":",
"if",
"network_address_01",
"is",
"None",
"or",
"network_address_02",
"is",
"None",
":",
"return",
"False",
"if",
"len",
"(",
"network_address_01",
")",
"<",
"4",
"or",
"len",
"(",
"network_address_02",
")",
"!=",
"5",
":",
"return",
"False",
"network_mask_02",
"=",
"network_mask_from_cidr_mask",
"(",
"network_address_02",
"[",
"4",
"]",
")",
"return",
"network_address_02",
"[",
"0",
":",
"4",
"]",
"==",
"_applyNetmask",
"(",
"network_address_01",
",",
"network_mask_02",
")"
] | [
36,
0
] | [
53,
88
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Battery.get_range | (self) | Exibe uma frase acerca da distância que o carro é capaz de percorrer com essa bateria. | Exibe uma frase acerca da distância que o carro é capaz de percorrer com essa bateria. | def get_range(self):
"""Exibe uma frase acerca da distância que o carro é capaz de percorrer com essa bateria."""
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = 'This car can go approximately ' + str(range) + ' miles on a full charge.'
print('\t' + message) | [
"def",
"get_range",
"(",
"self",
")",
":",
"if",
"self",
".",
"battery_size",
"==",
"70",
":",
"range",
"=",
"240",
"elif",
"self",
".",
"battery_size",
"==",
"85",
":",
"range",
"=",
"270",
"message",
"=",
"'This car can go approximately '",
"+",
"str",
"(",
"range",
")",
"+",
"' miles on a full charge.'",
"print",
"(",
"'\\t'",
"+",
"message",
")"
] | [
51,
4
] | [
58,
29
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
save_gazette | (item) | return gazette | Salva diários oficiais do executivo a partir de 2015. | Salva diários oficiais do executivo a partir de 2015. | def save_gazette(item):
"""Salva diários oficiais do executivo a partir de 2015."""
gazette, created = Gazette.objects.update_or_create(
date=item["date"],
power=item["power"],
year_and_edition=item["year_and_edition"],
defaults={
"crawled_at": item["crawled_at"],
"crawled_from": item["crawled_from"],
},
)
if created and item.get("files"):
content_type = get_content_type_for_model(gazette)
for file_ in item["files"]:
save_file(file_, content_type, gazette.pk)
for event in item["events"]:
GazetteEvent.objects.get_or_create(
gazette=gazette,
title=event["title"],
secretariat=event["secretariat"],
crawled_from=item["crawled_from"],
summary=event["summary"],
defaults={"crawled_at": item["crawled_at"]},
)
return gazette | [
"def",
"save_gazette",
"(",
"item",
")",
":",
"gazette",
",",
"created",
"=",
"Gazette",
".",
"objects",
".",
"update_or_create",
"(",
"date",
"=",
"item",
"[",
"\"date\"",
"]",
",",
"power",
"=",
"item",
"[",
"\"power\"",
"]",
",",
"year_and_edition",
"=",
"item",
"[",
"\"year_and_edition\"",
"]",
",",
"defaults",
"=",
"{",
"\"crawled_at\"",
":",
"item",
"[",
"\"crawled_at\"",
"]",
",",
"\"crawled_from\"",
":",
"item",
"[",
"\"crawled_from\"",
"]",
",",
"}",
",",
")",
"if",
"created",
"and",
"item",
".",
"get",
"(",
"\"files\"",
")",
":",
"content_type",
"=",
"get_content_type_for_model",
"(",
"gazette",
")",
"for",
"file_",
"in",
"item",
"[",
"\"files\"",
"]",
":",
"save_file",
"(",
"file_",
",",
"content_type",
",",
"gazette",
".",
"pk",
")",
"for",
"event",
"in",
"item",
"[",
"\"events\"",
"]",
":",
"GazetteEvent",
".",
"objects",
".",
"get_or_create",
"(",
"gazette",
"=",
"gazette",
",",
"title",
"=",
"event",
"[",
"\"title\"",
"]",
",",
"secretariat",
"=",
"event",
"[",
"\"secretariat\"",
"]",
",",
"crawled_from",
"=",
"item",
"[",
"\"crawled_from\"",
"]",
",",
"summary",
"=",
"event",
"[",
"\"summary\"",
"]",
",",
"defaults",
"=",
"{",
"\"crawled_at\"",
":",
"item",
"[",
"\"crawled_at\"",
"]",
"}",
",",
")",
"return",
"gazette"
] | [
9,
0
] | [
35,
18
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
find_by_text | (browser, tag, text) | Encontrar o elemento com o texto `text`.
Argumentos:
- browser = Instancia do browser [firefox, chrome, ...]
- texto = conteúdo que deve estar na tag
- tag = tag onde o texto será procurado
| Encontrar o elemento com o texto `text`. | def find_by_text(browser, tag, text):
"""Encontrar o elemento com o texto `text`.
Argumentos:
- browser = Instancia do browser [firefox, chrome, ...]
- texto = conteúdo que deve estar na tag
- tag = tag onde o texto será procurado
"""
elementos = browser.find_elements_by_tag_name(tag) # lista
for elemento in elementos:
if elemento.text == text:
return elemento | [
"def",
"find_by_text",
"(",
"browser",
",",
"tag",
",",
"text",
")",
":",
"elementos",
"=",
"browser",
".",
"find_elements_by_tag_name",
"(",
"tag",
")",
"# lista",
"for",
"elemento",
"in",
"elementos",
":",
"if",
"elemento",
".",
"text",
"==",
"text",
":",
"return",
"elemento"
] | [
3,
0
] | [
15,
27
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
buscaVizinhos | (matrizCapacidades) | return vizinhos | Função para buscar os vizihos de cada vertice | Função para buscar os vizihos de cada vertice | def buscaVizinhos(matrizCapacidades):
"""Função para buscar os vizihos de cada vertice"""
vizinhos = {}
for v in range(len(matrizCapacidades)):
vizinhos[v] = []
for v, fluxos in enumerate(matrizCapacidades):
for vizinho, fluxo in enumerate(fluxos):
if fluxo > 0:
vizinhos[v].append(vizinho)
vizinhos[vizinho].append(v)
return vizinhos | [
"def",
"buscaVizinhos",
"(",
"matrizCapacidades",
")",
":",
"vizinhos",
"=",
"{",
"}",
"for",
"v",
"in",
"range",
"(",
"len",
"(",
"matrizCapacidades",
")",
")",
":",
"vizinhos",
"[",
"v",
"]",
"=",
"[",
"]",
"for",
"v",
",",
"fluxos",
"in",
"enumerate",
"(",
"matrizCapacidades",
")",
":",
"for",
"vizinho",
",",
"fluxo",
"in",
"enumerate",
"(",
"fluxos",
")",
":",
"if",
"fluxo",
">",
"0",
":",
"vizinhos",
"[",
"v",
"]",
".",
"append",
"(",
"vizinho",
")",
"vizinhos",
"[",
"vizinho",
"]",
".",
"append",
"(",
"v",
")",
"return",
"vizinhos"
] | [
111,
0
] | [
122,
19
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
TesteFuncionario.test_receber_aumento_personalizado | (self) | Testa se o funcionário pode receber um valor maior ou menor
que 5000. | Testa se o funcionário pode receber um valor maior ou menor
que 5000. | def test_receber_aumento_personalizado(self):
"""Testa se o funcionário pode receber um valor maior ou menor
que 5000."""
self.alberto.receber_aumento(
aumento=10000
)
self.assertEqual(self.alberto.salario, 60000) | [
"def",
"test_receber_aumento_personalizado",
"(",
"self",
")",
":",
"self",
".",
"alberto",
".",
"receber_aumento",
"(",
"aumento",
"=",
"10000",
")",
"self",
".",
"assertEqual",
"(",
"self",
".",
"alberto",
".",
"salario",
",",
"60000",
")"
] | [
24,
4
] | [
30,
53
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Configuration.parse_settings | (self, defaults: Dict) | Analisa e retorna as configurações da app com base no env.
O argumento `defaults` deve receber uma lista associativa na forma:
[
(<diretiva de config>, <variável de ambiente>, <função de conversão>, <valor padrão>),
]
| Analisa e retorna as configurações da app com base no env.
O argumento `defaults` deve receber uma lista associativa na forma:
[
(<diretiva de config>, <variável de ambiente>, <função de conversão>, <valor padrão>),
]
| def parse_settings(self, defaults: Dict) -> None:
"""Analisa e retorna as configurações da app com base no env.
O argumento `defaults` deve receber uma lista associativa na forma:
[
(<diretiva de config>, <variável de ambiente>, <função de conversão>, <valor padrão>),
]
"""
parsed = {}
cfg = list(defaults)
for name, envkey, convert, default in cfg:
value = os.environ.get(envkey, default)
if convert is not None:
value = convert(value)
setattr(self, name, value) | [
"def",
"parse_settings",
"(",
"self",
",",
"defaults",
":",
"Dict",
")",
"->",
"None",
":",
"parsed",
"=",
"{",
"}",
"cfg",
"=",
"list",
"(",
"defaults",
")",
"for",
"name",
",",
"envkey",
",",
"convert",
",",
"default",
"in",
"cfg",
":",
"value",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"envkey",
",",
"default",
")",
"if",
"convert",
"is",
"not",
"None",
":",
"value",
"=",
"convert",
"(",
"value",
")",
"setattr",
"(",
"self",
",",
"name",
",",
"value",
")"
] | [
36,
4
] | [
52,
38
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Pesquisador.BlocoLattes | (root, lista ) | return lista | Método estático para parse de uma raiz XML com profundidade específica comum a várias seções do Lattes
Args:
root (type): raiz do XML `root`.
lista (type): Contem uma TAG principal e tags na outra hierarquia `lista`.
Returns:
type: Description of returned object.
| Método estático para parse de uma raiz XML com profundidade específica comum a várias seções do Lattes | def BlocoLattes(root, lista ):
"""Método estático para parse de uma raiz XML com profundidade específica comum a várias seções do Lattes
Args:
root (type): raiz do XML `root`.
lista (type): Contem uma TAG principal e tags na outra hierarquia `lista`.
Returns:
type: Description of returned object.
"""
raiz = root
TAG = lista[0]
bloco = lista[1]
lista = [ {'PRODUCAO':el3.tag, **el3.attrib, **el4.attrib}
for el1 in raiz.iterchildren(tag=TAG)
for el2 in el1.iterchildren()
for el3 in el2.iterchildren()
for el4 in el3.iterchildren() if any(tag in el4.tag for tag in [bloco]) ]
return lista | [
"def",
"BlocoLattes",
"(",
"root",
",",
"lista",
")",
":",
"raiz",
"=",
"root",
"TAG",
"=",
"lista",
"[",
"0",
"]",
"bloco",
"=",
"lista",
"[",
"1",
"]",
"lista",
"=",
"[",
"{",
"'PRODUCAO'",
":",
"el3",
".",
"tag",
",",
"*",
"*",
"el3",
".",
"attrib",
",",
"*",
"*",
"el4",
".",
"attrib",
"}",
"for",
"el1",
"in",
"raiz",
".",
"iterchildren",
"(",
"tag",
"=",
"TAG",
")",
"for",
"el2",
"in",
"el1",
".",
"iterchildren",
"(",
")",
"for",
"el3",
"in",
"el2",
".",
"iterchildren",
"(",
")",
"for",
"el4",
"in",
"el3",
".",
"iterchildren",
"(",
")",
"if",
"any",
"(",
"tag",
"in",
"el4",
".",
"tag",
"for",
"tag",
"in",
"[",
"bloco",
"]",
")",
"]",
"return",
"lista"
] | [
538,
4
] | [
558,
20
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
p_se | (p) | se : SE expressao ENTAO corpo FIM
| SE expressao ENTAO corpo SENAO corpo FIM
| se : SE expressao ENTAO corpo FIM
| SE expressao ENTAO corpo SENAO corpo FIM
| def p_se(p):
"""se : SE expressao ENTAO corpo FIM
| SE expressao ENTAO corpo SENAO corpo FIM
"""
pai = MyNode(name='se', type='SE')
p[0] = pai
filho1 = MyNode(name='SE', type='SE', parent=pai)
filho_se = MyNode(name=p[1], type='SE', parent=filho1)
p[1] = filho1
p[2].parent = pai
filho3 = MyNode(name='ENTAO', type='ENTAO', parent=pai)
filho_entao = MyNode(name=p[3], type='ENTAO', parent=filho3)
p[3] = filho3
p[4].parent = pai
if len(p) == 8:
filho5 = MyNode(name='SENAO', type='SENAO', parent=pai)
filho_senao = MyNode(name=p[5], type='SENAO', parent=filho5)
p[5] = filho5
p[6].parent = pai
filho7 = MyNode(name='FIM', type='FIM', parent=pai)
filho_fim = MyNode(name=p[7], type='FIM', parent=filho7)
p[7] = filho7
else:
filho5 = MyNode(name='fim', type='FIM', parent=pai)
filho_fim = MyNode(name=p[5], type='FIM', parent=filho5)
p[5] = filho5 | [
"def",
"p_se",
"(",
"p",
")",
":",
"pai",
"=",
"MyNode",
"(",
"name",
"=",
"'se'",
",",
"type",
"=",
"'SE'",
")",
"p",
"[",
"0",
"]",
"=",
"pai",
"filho1",
"=",
"MyNode",
"(",
"name",
"=",
"'SE'",
",",
"type",
"=",
"'SE'",
",",
"parent",
"=",
"pai",
")",
"filho_se",
"=",
"MyNode",
"(",
"name",
"=",
"p",
"[",
"1",
"]",
",",
"type",
"=",
"'SE'",
",",
"parent",
"=",
"filho1",
")",
"p",
"[",
"1",
"]",
"=",
"filho1",
"p",
"[",
"2",
"]",
".",
"parent",
"=",
"pai",
"filho3",
"=",
"MyNode",
"(",
"name",
"=",
"'ENTAO'",
",",
"type",
"=",
"'ENTAO'",
",",
"parent",
"=",
"pai",
")",
"filho_entao",
"=",
"MyNode",
"(",
"name",
"=",
"p",
"[",
"3",
"]",
",",
"type",
"=",
"'ENTAO'",
",",
"parent",
"=",
"filho3",
")",
"p",
"[",
"3",
"]",
"=",
"filho3",
"p",
"[",
"4",
"]",
".",
"parent",
"=",
"pai",
"if",
"len",
"(",
"p",
")",
"==",
"8",
":",
"filho5",
"=",
"MyNode",
"(",
"name",
"=",
"'SENAO'",
",",
"type",
"=",
"'SENAO'",
",",
"parent",
"=",
"pai",
")",
"filho_senao",
"=",
"MyNode",
"(",
"name",
"=",
"p",
"[",
"5",
"]",
",",
"type",
"=",
"'SENAO'",
",",
"parent",
"=",
"filho5",
")",
"p",
"[",
"5",
"]",
"=",
"filho5",
"p",
"[",
"6",
"]",
".",
"parent",
"=",
"pai",
"filho7",
"=",
"MyNode",
"(",
"name",
"=",
"'FIM'",
",",
"type",
"=",
"'FIM'",
",",
"parent",
"=",
"pai",
")",
"filho_fim",
"=",
"MyNode",
"(",
"name",
"=",
"p",
"[",
"7",
"]",
",",
"type",
"=",
"'FIM'",
",",
"parent",
"=",
"filho7",
")",
"p",
"[",
"7",
"]",
"=",
"filho7",
"else",
":",
"filho5",
"=",
"MyNode",
"(",
"name",
"=",
"'fim'",
",",
"type",
"=",
"'FIM'",
",",
"parent",
"=",
"pai",
")",
"filho_fim",
"=",
"MyNode",
"(",
"name",
"=",
"p",
"[",
"5",
"]",
",",
"type",
"=",
"'FIM'",
",",
"parent",
"=",
"filho5",
")",
"p",
"[",
"5",
"]",
"=",
"filho5"
] | [
567,
0
] | [
600,
21
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Ip.delete | (self) | Sobrescreve o método do Django para remover um IP.
Antes de remover o IP remove todas as suas requisições de VIP e os relacionamentos com equipamentos.
| Sobrescreve o método do Django para remover um IP.
Antes de remover o IP remove todas as suas requisições de VIP e os relacionamentos com equipamentos.
| def delete(self):
"""Sobrescreve o método do Django para remover um IP.
Antes de remover o IP remove todas as suas requisições de VIP e os relacionamentos com equipamentos.
"""
try:
for r in self.requisicaovips_set.all():
r_alter = False
# Assures VIP request is not being changed - issue #48
with distributedlock(LOCK_VIP % r.id):
# updates query after lock for object
r = self.requisicaovips_set.get(id=r.id)
id_vip = r.id
if r.vip_criado:
raise IpCantBeRemovedFromVip(
r.id, 'Ipv4 não pode ser removido, porque está em uso por Requisição Vip %s' % (r.id))
else:
if r.ipv6 is not None:
r.ip = None
r.validado = 0
r.save()
r_alter = True
# SYNC_VIP
syncs.old_to_new(r)
if not r_alter:
r.delete()
# SYNC_VIP
syncs.delete_new(id_vip)
for ie in self.ipequipamento_set.all():
# Codigo removido, pois não devemos remover o ambiente do equipamento mesmo que não tenha IP
# para o ambiente solicidado pelo Henrique
# ambienteequip = EquipamentoAmbiente()
# ambienteequip = ambienteequip.get_by_equipment_environment(
# ie.equipamento.id, self.networkipv4.vlan.ambiente_id)
#
# ips = Ip.list_by_environment_and_equipment(
# ambienteequip.ambiente_id, ie.equipamento.id)
# ips6 = Ipv6.list_by_environment_and_equipment(
# ambienteequip.ambiente_id, ie.equipamento.id)
#
# if len(ips) <= 1 and len(ips6) <= 0:
#
# ambienteequip.delete()
ie.delete()
ip_slz = get_app('api_ip', module_label='serializers')
serializer = ip_slz.Ipv4V3Serializer(self)
data_to_queue = serializer.data
# Deletes Obj IP
super(Ip, self).delete()
# Sends to Queue
queue_manager = QueueManager(broker_vhost='tasks',
queue_name='tasks.aclapi',
exchange_name='tasks.aclapi',
routing_key='tasks.aclapi')
data_to_queue.update({'description': queue_keys.IPv4_REMOVE})
queue_manager.append({
'action': queue_keys.IPv4_REMOVE,
'kind': queue_keys.IPv4_KEY,
'data': data_to_queue
})
except EquipamentoAmbienteNotFoundError, e:
raise EquipamentoAmbienteNotFoundError(None, e.message)
except IpCantBeRemovedFromVip, e:
raise IpCantBeRemovedFromVip(e.cause, e.message)
except IpEquipmentNotFoundError, e:
raise IpEquipmentNotFoundError(None, e.message) | [
"def",
"delete",
"(",
"self",
")",
":",
"try",
":",
"for",
"r",
"in",
"self",
".",
"requisicaovips_set",
".",
"all",
"(",
")",
":",
"r_alter",
"=",
"False",
"# Assures VIP request is not being changed - issue #48",
"with",
"distributedlock",
"(",
"LOCK_VIP",
"%",
"r",
".",
"id",
")",
":",
"# updates query after lock for object",
"r",
"=",
"self",
".",
"requisicaovips_set",
".",
"get",
"(",
"id",
"=",
"r",
".",
"id",
")",
"id_vip",
"=",
"r",
".",
"id",
"if",
"r",
".",
"vip_criado",
":",
"raise",
"IpCantBeRemovedFromVip",
"(",
"r",
".",
"id",
",",
"'Ipv4 não pode ser removido, porque está em uso por Requisição Vip %s' % (",
".",
"d",
")",
")",
"",
"",
"",
"else",
":",
"if",
"r",
".",
"ipv6",
"is",
"not",
"None",
":",
"r",
".",
"ip",
"=",
"None",
"r",
".",
"validado",
"=",
"0",
"r",
".",
"save",
"(",
")",
"r_alter",
"=",
"True",
"# SYNC_VIP",
"syncs",
".",
"old_to_new",
"(",
"r",
")",
"if",
"not",
"r_alter",
":",
"r",
".",
"delete",
"(",
")",
"# SYNC_VIP",
"syncs",
".",
"delete_new",
"(",
"id_vip",
")",
"for",
"ie",
"in",
"self",
".",
"ipequipamento_set",
".",
"all",
"(",
")",
":",
"# Codigo removido, pois não devemos remover o ambiente do equipamento mesmo que não tenha IP",
"# para o ambiente solicidado pelo Henrique",
"# ambienteequip = EquipamentoAmbiente()",
"# ambienteequip = ambienteequip.get_by_equipment_environment(",
"# ie.equipamento.id, self.networkipv4.vlan.ambiente_id)",
"#",
"# ips = Ip.list_by_environment_and_equipment(",
"# ambienteequip.ambiente_id, ie.equipamento.id)",
"# ips6 = Ipv6.list_by_environment_and_equipment(",
"# ambienteequip.ambiente_id, ie.equipamento.id)",
"#",
"# if len(ips) <= 1 and len(ips6) <= 0:",
"#",
"# ambienteequip.delete()",
"ie",
".",
"delete",
"(",
")",
"ip_slz",
"=",
"get_app",
"(",
"'api_ip'",
",",
"module_label",
"=",
"'serializers'",
")",
"serializer",
"=",
"ip_slz",
".",
"Ipv4V3Serializer",
"(",
"self",
")",
"data_to_queue",
"=",
"serializer",
".",
"data",
"# Deletes Obj IP",
"super",
"(",
"Ip",
",",
"self",
")",
".",
"delete",
"(",
")",
"# Sends to Queue",
"queue_manager",
"=",
"QueueManager",
"(",
"broker_vhost",
"=",
"'tasks'",
",",
"queue_name",
"=",
"'tasks.aclapi'",
",",
"exchange_name",
"=",
"'tasks.aclapi'",
",",
"routing_key",
"=",
"'tasks.aclapi'",
")",
"data_to_queue",
".",
"update",
"(",
"{",
"'description'",
":",
"queue_keys",
".",
"IPv4_REMOVE",
"}",
")",
"queue_manager",
".",
"append",
"(",
"{",
"'action'",
":",
"queue_keys",
".",
"IPv4_REMOVE",
",",
"'kind'",
":",
"queue_keys",
".",
"IPv4_KEY",
",",
"'data'",
":",
"data_to_queue",
"}",
")",
"except",
"EquipamentoAmbienteNotFoundError",
",",
"e",
":",
"raise",
"EquipamentoAmbienteNotFoundError",
"(",
"None",
",",
"e",
".",
"message",
")",
"except",
"IpCantBeRemovedFromVip",
",",
"e",
":",
"raise",
"IpCantBeRemovedFromVip",
"(",
"e",
".",
"cause",
",",
"e",
".",
"message",
")",
"except",
"IpEquipmentNotFoundError",
",",
"e",
":",
"raise",
"IpEquipmentNotFoundError",
"(",
"None",
",",
"e",
".",
"message",
")"
] | [
1796,
4
] | [
1869,
59
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Pesquisador.validaPath | (self) | return dicio | Verifica se todos os caminhos informados são válidos e define os booleanos __UFCG, __SAAP e __PONTUA.
Returns:
type: Dicionário com caminhos validados.
| Verifica se todos os caminhos informados são válidos e define os booleanos __UFCG, __SAAP e __PONTUA. | def validaPath(self):
"""Verifica se todos os caminhos informados são válidos e define os booleanos __UFCG, __SAAP e __PONTUA.
Returns:
type: Dicionário com caminhos validados.
"""
kwargs = self.defaultValues()
kwargs = {**kwargs, **self.kwargs}
dicio = {k: v for k, v in kwargs.items() if k.startswith('path')}
for key in list(dicio.keys()):
try:
valueP = pathHandler(dicio[key])
#----É um arquivo e ele pode ser lido?
assert isfile(valueP) and access(valueP, R_OK), \
"Arquivo {} não encontrado ou ilegível".format(valueP)
except AssertionError as error:
#LOG.error("Arquivo não encontrado %s",valueP )
dicio.pop(key, None)
else:
pass
#LOG.info("Arquivo encontrado: %s", valueP)
finally:
if ('pathSAAP' in dicio and dicio['pathSAAP']!=""):
self.__SAAP = True
else:
self.__SAAP = False
if ('pathUFCG' in dicio and dicio['pathUFCG']!=""):
self.__UFCG = True
else:
self.__UFCG = False
if ('pathPontos' in dicio and dicio['pathPontos']!=""):
self.__PONTUA = True
else:
self.__PONTUA = False
return dicio | [
"def",
"validaPath",
"(",
"self",
")",
":",
"kwargs",
"=",
"self",
".",
"defaultValues",
"(",
")",
"kwargs",
"=",
"{",
"*",
"*",
"kwargs",
",",
"*",
"*",
"self",
".",
"kwargs",
"}",
"dicio",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"if",
"k",
".",
"startswith",
"(",
"'path'",
")",
"}",
"for",
"key",
"in",
"list",
"(",
"dicio",
".",
"keys",
"(",
")",
")",
":",
"try",
":",
"valueP",
"=",
"pathHandler",
"(",
"dicio",
"[",
"key",
"]",
")",
"#----É um arquivo e ele pode ser lido?",
"assert",
"isfile",
"(",
"valueP",
")",
"and",
"access",
"(",
"valueP",
",",
"R_OK",
")",
",",
"\"Arquivo {} não encontrado ou ilegível\".f",
"o",
"rmat(v",
"a",
"lueP)",
"",
"except",
"AssertionError",
"as",
"error",
":",
"#LOG.error(\"Arquivo não encontrado %s\",valueP )",
"dicio",
".",
"pop",
"(",
"key",
",",
"None",
")",
"else",
":",
"pass",
"#LOG.info(\"Arquivo encontrado: %s\", valueP)",
"finally",
":",
"if",
"(",
"'pathSAAP'",
"in",
"dicio",
"and",
"dicio",
"[",
"'pathSAAP'",
"]",
"!=",
"\"\"",
")",
":",
"self",
".",
"__SAAP",
"=",
"True",
"else",
":",
"self",
".",
"__SAAP",
"=",
"False",
"if",
"(",
"'pathUFCG'",
"in",
"dicio",
"and",
"dicio",
"[",
"'pathUFCG'",
"]",
"!=",
"\"\"",
")",
":",
"self",
".",
"__UFCG",
"=",
"True",
"else",
":",
"self",
".",
"__UFCG",
"=",
"False",
"if",
"(",
"'pathPontos'",
"in",
"dicio",
"and",
"dicio",
"[",
"'pathPontos'",
"]",
"!=",
"\"\"",
")",
":",
"self",
".",
"__PONTUA",
"=",
"True",
"else",
":",
"self",
".",
"__PONTUA",
"=",
"False",
"return",
"dicio"
] | [
261,
4
] | [
298,
20
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Grafo.verticeDegree | (self, rotulo) | Implementa o grau dos vértices | Implementa o grau dos vértices | def verticeDegree(self, rotulo):
"""Implementa o grau dos vértices"""
for i in range(self.numVertices):
if rotulo == self.listaVertices[i]:
break
for j in range(self.numVertices):
if self.matrizAdj[j][i] != 0:
if j == i:
# diagonal
self.listaVertices[i].degree += 2
else:
# não diagonal
self.listaVertices[i].degree += 1
print("Grau do vertice"+str(rotulo) + "é " +
str(self.listaVertices[i].degree)) | [
"def",
"verticeDegree",
"(",
"self",
",",
"rotulo",
")",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"numVertices",
")",
":",
"if",
"rotulo",
"==",
"self",
".",
"listaVertices",
"[",
"i",
"]",
":",
"break",
"for",
"j",
"in",
"range",
"(",
"self",
".",
"numVertices",
")",
":",
"if",
"self",
".",
"matrizAdj",
"[",
"j",
"]",
"[",
"i",
"]",
"!=",
"0",
":",
"if",
"j",
"==",
"i",
":",
"# diagonal",
"self",
".",
"listaVertices",
"[",
"i",
"]",
".",
"degree",
"+=",
"2",
"else",
":",
"# não diagonal",
"self",
".",
"listaVertices",
"[",
"i",
"]",
".",
"degree",
"+=",
"1",
"print",
"(",
"\"Grau do vertice\"",
"+",
"str",
"(",
"rotulo",
")",
"+",
"\"é \" ",
"",
"str",
"(",
"self",
".",
"listaVertices",
"[",
"i",
"]",
".",
"degree",
")",
")"
] | [
62,
4
] | [
78,
48
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
download_file | (name, url, *, path='downloads', type='png') | return f'{path}/{name}' | Executa o download de um arquivo. | Executa o download de um arquivo. | def download_file(name, url, *, path='downloads', type='png'):
"""Executa o download de um arquivo."""
xpto = get(url, stream=True)
with open(f'{path}/{name}.{type}', 'wb') as f:
copyfileobj(xpto.raw, f)
return f'{path}/{name}' | [
"def",
"download_file",
"(",
"name",
",",
"url",
",",
"*",
",",
"path",
"=",
"'downloads'",
",",
"type",
"=",
"'png'",
")",
":",
"xpto",
"=",
"get",
"(",
"url",
",",
"stream",
"=",
"True",
")",
"with",
"open",
"(",
"f'{path}/{name}.{type}'",
",",
"'wb'",
")",
"as",
"f",
":",
"copyfileobj",
"(",
"xpto",
".",
"raw",
",",
"f",
")",
"return",
"f'{path}/{name}'"
] | [
21,
0
] | [
26,
27
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Grafo._peso_entre_u_e_v | (self, u: int, v: int) | Retorna o peso entre os vértices u e v
Args:
u (int): vértice u
v (int): vértice v
Returns:
float: peso entre u e v
| Retorna o peso entre os vértices u e v
Args:
u (int): vértice u
v (int): vértice v
Returns:
float: peso entre u e v
| def _peso_entre_u_e_v(self, u: int, v: int) -> float:
"""Retorna o peso entre os vértices u e v
Args:
u (int): vértice u
v (int): vértice v
Returns:
float: peso entre u e v
"""
for vertice in self.adj[v[1]]:
if vertice[1] == u:
return vertice[0] | [
"def",
"_peso_entre_u_e_v",
"(",
"self",
",",
"u",
":",
"int",
",",
"v",
":",
"int",
")",
"->",
"float",
":",
"for",
"vertice",
"in",
"self",
".",
"adj",
"[",
"v",
"[",
"1",
"]",
"]",
":",
"if",
"vertice",
"[",
"1",
"]",
"==",
"u",
":",
"return",
"vertice",
"[",
"0",
"]"
] | [
40,
4
] | [
52,
33
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Restaurante.__init__ | (self, nome_restaurante, tipo_cozinha) | Inicializa os atributos restaurante e cozinha. | Inicializa os atributos restaurante e cozinha. | def __init__(self, nome_restaurante, tipo_cozinha):
"""Inicializa os atributos restaurante e cozinha."""
self.nome_restaurante = nome_restaurante
self.tipo_cozinha = tipo_cozinha | [
"def",
"__init__",
"(",
"self",
",",
"nome_restaurante",
",",
"tipo_cozinha",
")",
":",
"self",
".",
"nome_restaurante",
"=",
"nome_restaurante",
"self",
".",
"tipo_cozinha",
"=",
"tipo_cozinha"
] | [
4,
4
] | [
7,
40
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
TestRenavam.test_special_case | (self) | Verifica os casos especiais de RENAVAM | Verifica os casos especiais de RENAVAM | def test_special_case(self):
""" Verifica os casos especiais de RENAVAM """
cases = [
('3467875434578764345789654', False),
('', False),
('AAAAAAAAAAA', False),
('38872054170', False),
('40999838209', False),
('31789431480', False),
('38919643060', False),
('13824652268', True),
('08543317523', True),
('09769017014', True),
('01993520012', True),
('04598137389', True),
('05204907510', True),
]
for renavam, is_valid in cases:
self.assertEqual(self.renavam.validate(renavam), is_valid) | [
"def",
"test_special_case",
"(",
"self",
")",
":",
"cases",
"=",
"[",
"(",
"'3467875434578764345789654'",
",",
"False",
")",
",",
"(",
"''",
",",
"False",
")",
",",
"(",
"'AAAAAAAAAAA'",
",",
"False",
")",
",",
"(",
"'38872054170'",
",",
"False",
")",
",",
"(",
"'40999838209'",
",",
"False",
")",
",",
"(",
"'31789431480'",
",",
"False",
")",
",",
"(",
"'38919643060'",
",",
"False",
")",
",",
"(",
"'13824652268'",
",",
"True",
")",
",",
"(",
"'08543317523'",
",",
"True",
")",
",",
"(",
"'09769017014'",
",",
"True",
")",
",",
"(",
"'01993520012'",
",",
"True",
")",
",",
"(",
"'04598137389'",
",",
"True",
")",
",",
"(",
"'05204907510'",
",",
"True",
")",
",",
"]",
"for",
"renavam",
",",
"is_valid",
"in",
"cases",
":",
"self",
".",
"assertEqual",
"(",
"self",
".",
"renavam",
".",
"validate",
"(",
"renavam",
")",
",",
"is_valid",
")"
] | [
31,
4
] | [
49,
70
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Carro_El.abastecer_gasolina | (self) | Carro elétricos não tem tanques de gasolina para abastecer. | Carro elétricos não tem tanques de gasolina para abastecer. | def abastecer_gasolina(self):
"""Carro elétricos não tem tanques de gasolina para abastecer."""
print("Esse carro não é movido a gosolina!") | [
"def",
"abastecer_gasolina",
"(",
"self",
")",
":",
"print",
"(",
"\"Esse carro não é movido a gosolina!\")",
""
] | [
68,
4
] | [
70,
54
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
hailstone_iterative_sequence | (a_0) | Calcula (iterativamente) a sequência conhecida como "números de granizo" (hailstone sequence) ou "números maravilhosos". A Conjectura de Collatz afirma que, independentemente do valor de a[0], a sequência sempre atingirá um valor k tal que a[k]=1.
Args:
a_0 (int): Valor inicial, a partir de onde a sequêcia de números maravilhosos se iniciará.
Returns:
list: Lista com números maravilhosos a partir de 'a_0'.
| Calcula (iterativamente) a sequência conhecida como "números de granizo" (hailstone sequence) ou "números maravilhosos". A Conjectura de Collatz afirma que, independentemente do valor de a[0], a sequência sempre atingirá um valor k tal que a[k]=1. | def hailstone_iterative_sequence(a_0):
"""Calcula (iterativamente) a sequência conhecida como "números de granizo" (hailstone sequence) ou "números maravilhosos". A Conjectura de Collatz afirma que, independentemente do valor de a[0], a sequência sempre atingirá um valor k tal que a[k]=1.
Args:
a_0 (int): Valor inicial, a partir de onde a sequêcia de números maravilhosos se iniciará.
Returns:
list: Lista com números maravilhosos a partir de 'a_0'.
"""
a = [a_0]
k = 0
while True:
# Condição de parada -> a[k] == 1
if a[k] == 1:
return a
# Decisão para próximo passo da sequência (par ou ímpar)
elif a[k] % 2 == 0:
a.append(a[k] // 2)
else:
a.append(3 * a[k] + 1)
k += 1 | [
"def",
"hailstone_iterative_sequence",
"(",
"a_0",
")",
":",
"a",
"=",
"[",
"a_0",
"]",
"k",
"=",
"0",
"while",
"True",
":",
"# Condição de parada -> a[k] == 1",
"if",
"a",
"[",
"k",
"]",
"==",
"1",
":",
"return",
"a",
"# Decisão para próximo passo da sequência (par ou ímpar)",
"elif",
"a",
"[",
"k",
"]",
"%",
"2",
"==",
"0",
":",
"a",
".",
"append",
"(",
"a",
"[",
"k",
"]",
"//",
"2",
")",
"else",
":",
"a",
".",
"append",
"(",
"3",
"*",
"a",
"[",
"k",
"]",
"+",
"1",
")",
"k",
"+=",
"1"
] | [
6,
0
] | [
28,
14
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
CNS._validate_first_case | (self, doc: list) | return cns == doc | Validar CNSs que comecem com 1 ou 2. | Validar CNSs que comecem com 1 ou 2. | def _validate_first_case(self, doc: list) -> bool:
"""Validar CNSs que comecem com 1 ou 2."""
cns = self._generate_first_case(doc)
return cns == doc | [
"def",
"_validate_first_case",
"(",
"self",
",",
"doc",
":",
"list",
")",
"->",
"bool",
":",
"cns",
"=",
"self",
".",
"_generate_first_case",
"(",
"doc",
")",
"return",
"cns",
"==",
"doc"
] | [
23,
4
] | [
27,
25
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
GridSearch.getBestModel | (self, X, y) | return best_model | Função para realizar o Grid Search dos classificadores
Parâmetros:
X:dataframe['tweets']
y:target
return: melhor modelo (Classificador com hyperparametros)
| Função para realizar o Grid Search dos classificadores
Parâmetros:
X:dataframe['tweets']
y:target | def getBestModel(self, X, y):
'''Função para realizar o Grid Search dos classificadores
Parâmetros:
X:dataframe['tweets']
y:target
return: melhor modelo (Classificador com hyperparametros)
'''
# Create grid search using 5-fold cross validation
clf = GridSearchCV(self.classificador,
self.hyperParams,
cv= 5, verbose= 0, n_jobs= -1,
scoring= ['accuracy', 'precision', 'recall', 'f1_micro', 'f1_macro'],
refit= 'f1_macro')
# Fit grid search and return best model
best_model = clf.fit(X, y)
print(best_model.best_estimator_.get_params())
for score in best_model.scoring:
values = best_model.cv_results_['mean_test_%s' % (score)][~np.isnan(best_model.cv_results_['mean_test_%s' % (score)])]
print("{0}: {1}".format(score,round(np.max(values)*100,3)))
return best_model | [
"def",
"getBestModel",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"# Create grid search using 5-fold cross validation",
"clf",
"=",
"GridSearchCV",
"(",
"self",
".",
"classificador",
",",
"self",
".",
"hyperParams",
",",
"cv",
"=",
"5",
",",
"verbose",
"=",
"0",
",",
"n_jobs",
"=",
"-",
"1",
",",
"scoring",
"=",
"[",
"'accuracy'",
",",
"'precision'",
",",
"'recall'",
",",
"'f1_micro'",
",",
"'f1_macro'",
"]",
",",
"refit",
"=",
"'f1_macro'",
")",
"# Fit grid search and return best model",
"best_model",
"=",
"clf",
".",
"fit",
"(",
"X",
",",
"y",
")",
"print",
"(",
"best_model",
".",
"best_estimator_",
".",
"get_params",
"(",
")",
")",
"for",
"score",
"in",
"best_model",
".",
"scoring",
":",
"values",
"=",
"best_model",
".",
"cv_results_",
"[",
"'mean_test_%s'",
"%",
"(",
"score",
")",
"]",
"[",
"~",
"np",
".",
"isnan",
"(",
"best_model",
".",
"cv_results_",
"[",
"'mean_test_%s'",
"%",
"(",
"score",
")",
"]",
")",
"]",
"print",
"(",
"\"{0}: {1}\"",
".",
"format",
"(",
"score",
",",
"round",
"(",
"np",
".",
"max",
"(",
"values",
")",
"*",
"100",
",",
"3",
")",
")",
")",
"return",
"best_model"
] | [
9,
4
] | [
30,
25
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Grafo.__adiciona_aresta | (self, u: int, v: int) | Adiciona a aresta na matriz de adjacência
Args:
u (int): vértice u
v (int): vértice v
| Adiciona a aresta na matriz de adjacência
Args:
u (int): vértice u
v (int): vértice v
| def __adiciona_aresta(self, u: int, v: int) -> None:
"""Adiciona a aresta na matriz de adjacência
Args:
u (int): vértice u
v (int): vértice v
"""
if v[0] not in self.adj[u]:
self.adj[u].append([v[1], v[0]]) | [
"def",
"__adiciona_aresta",
"(",
"self",
",",
"u",
":",
"int",
",",
"v",
":",
"int",
")",
"->",
"None",
":",
"if",
"v",
"[",
"0",
"]",
"not",
"in",
"self",
".",
"adj",
"[",
"u",
"]",
":",
"self",
".",
"adj",
"[",
"u",
"]",
".",
"append",
"(",
"[",
"v",
"[",
"1",
"]",
",",
"v",
"[",
"0",
"]",
"]",
")"
] | [
30,
4
] | [
38,
44
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Environment.list_things_at | (self, location, tclass=Thing) | return [thing for thing in self.things
if thing.location == location and isinstance(thing, tclass)] | Devolva todas as coisas exatamente em um determinado local. | Devolva todas as coisas exatamente em um determinado local. | def list_things_at(self, location, tclass=Thing):
"Devolva todas as coisas exatamente em um determinado local."
return [thing for thing in self.things
if thing.location == location and isinstance(thing, tclass)] | [
"def",
"list_things_at",
"(",
"self",
",",
"location",
",",
"tclass",
"=",
"Thing",
")",
":",
"return",
"[",
"thing",
"for",
"thing",
"in",
"self",
".",
"things",
"if",
"thing",
".",
"location",
"==",
"location",
"and",
"isinstance",
"(",
"thing",
",",
"tclass",
")",
"]"
] | [
188,
4
] | [
191,
76
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Settings.increase_speed | (self) | Aumenta as configuracos da velocidade e os pontos para
cada alienigena | Aumenta as configuracos da velocidade e os pontos para
cada alienigena | def increase_speed(self):
"""Aumenta as configuracos da velocidade e os pontos para
cada alienigena"""
self.ship_speed_factor *= self.speedup_scale
self.bullet_speed_factor *= self.speedup_scale
self.alien_speed_factor *= self.speedup_scale
self.alien_points = int(self.alien_points * self.score_scale) | [
"def",
"increase_speed",
"(",
"self",
")",
":",
"self",
".",
"ship_speed_factor",
"*=",
"self",
".",
"speedup_scale",
"self",
".",
"bullet_speed_factor",
"*=",
"self",
".",
"speedup_scale",
"self",
".",
"alien_speed_factor",
"*=",
"self",
".",
"speedup_scale",
"self",
".",
"alien_points",
"=",
"int",
"(",
"self",
".",
"alien_points",
"*",
"self",
".",
"score_scale",
")"
] | [
44,
4
] | [
50,
69
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
UsuarioChangePassResource.handle_post | (self, request, user, *args, **kwargs) | Trata as requisições de POST para alterar a senha de um Usuario.
URL: user-change-pass/
| Trata as requisições de POST para alterar a senha de um Usuario. | def handle_post(self, request, user, *args, **kwargs):
"""Trata as requisições de POST para alterar a senha de um Usuario.
URL: user-change-pass/
"""
try:
xml_map, attrs_map = loads(request.raw_post_data)
self.log.info('Change user password')
# User permission
if not has_perm(user, AdminPermission.AUTHENTICATE, AdminPermission.WRITE_OPERATION):
self.log.error(
u'User does not have permission to perform the operation.')
raise UserNotAuthorizedError(None)
networkapi_map = xml_map.get('networkapi')
if networkapi_map is None:
return self.response_error(3, u'Não existe valor para a tag networkapi do XML de requisição.')
user_map = networkapi_map.get('user')
if user_map is None:
return self.response_error(3, u'Não existe valor para a tag usuario do XML de requisição.')
# Get XML data
id_user = user_map.get('user_id')
password = user_map.get('password')
# Valid ID User
if not is_valid_int_greater_zero_param(id_user):
self.log.error(
u'The id_user parameter is not a valid value: %s.', id_user)
raise InvalidValueError(None, 'id_user', id_user)
# Valid pwd
if not is_valid_string_minsize(password, 3) or not is_valid_string_maxsize(password, 45):
self.log.error(u'Parameter password is invalid. Value: ****')
raise InvalidValueError(None, 'password', '****')
# Find User by ID to check if it exist
usr = Usuario.get_by_pk(id_user)
with distributedlock(LOCK_USER % id_user):
# set variable
usr.pwd = Usuario.encode_password(password)
try:
# update User
usr.save()
except Exception, e:
self.log.error(u'Failed to update the user.')
raise UsuarioError(e, u'Failed to update the user.')
return self.response(dumps_networkapi({}))
except InvalidValueError, e:
return self.response_error(269, e.param, e.value)
except UserNotAuthorizedError:
return self.not_authorized()
except UsuarioNotFoundError:
return self.response_error(177, id_user)
except XMLError, x:
self.log.error(u'Erro ao ler o XML da requisicao.')
return self.response_error(3, x)
except (UsuarioError, GrupoError):
return self.response_error(1) | [
"def",
"handle_post",
"(",
"self",
",",
"request",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"xml_map",
",",
"attrs_map",
"=",
"loads",
"(",
"request",
".",
"raw_post_data",
")",
"self",
".",
"log",
".",
"info",
"(",
"'Change user password'",
")",
"# User permission",
"if",
"not",
"has_perm",
"(",
"user",
",",
"AdminPermission",
".",
"AUTHENTICATE",
",",
"AdminPermission",
".",
"WRITE_OPERATION",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'User does not have permission to perform the operation.'",
")",
"raise",
"UserNotAuthorizedError",
"(",
"None",
")",
"networkapi_map",
"=",
"xml_map",
".",
"get",
"(",
"'networkapi'",
")",
"if",
"networkapi_map",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"u'Não existe valor para a tag networkapi do XML de requisição.')",
"",
"user_map",
"=",
"networkapi_map",
".",
"get",
"(",
"'user'",
")",
"if",
"user_map",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"u'Não existe valor para a tag usuario do XML de requisição.')",
"",
"# Get XML data",
"id_user",
"=",
"user_map",
".",
"get",
"(",
"'user_id'",
")",
"password",
"=",
"user_map",
".",
"get",
"(",
"'password'",
")",
"# Valid ID User",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"id_user",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'The id_user parameter is not a valid value: %s.'",
",",
"id_user",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'id_user'",
",",
"id_user",
")",
"# Valid pwd",
"if",
"not",
"is_valid_string_minsize",
"(",
"password",
",",
"3",
")",
"or",
"not",
"is_valid_string_maxsize",
"(",
"password",
",",
"45",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameter password is invalid. Value: ****'",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'password'",
",",
"'****'",
")",
"# Find User by ID to check if it exist",
"usr",
"=",
"Usuario",
".",
"get_by_pk",
"(",
"id_user",
")",
"with",
"distributedlock",
"(",
"LOCK_USER",
"%",
"id_user",
")",
":",
"# set variable",
"usr",
".",
"pwd",
"=",
"Usuario",
".",
"encode_password",
"(",
"password",
")",
"try",
":",
"# update User",
"usr",
".",
"save",
"(",
")",
"except",
"Exception",
",",
"e",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Failed to update the user.'",
")",
"raise",
"UsuarioError",
"(",
"e",
",",
"u'Failed to update the user.'",
")",
"return",
"self",
".",
"response",
"(",
"dumps_networkapi",
"(",
"{",
"}",
")",
")",
"except",
"InvalidValueError",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"269",
",",
"e",
".",
"param",
",",
"e",
".",
"value",
")",
"except",
"UserNotAuthorizedError",
":",
"return",
"self",
".",
"not_authorized",
"(",
")",
"except",
"UsuarioNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"177",
",",
"id_user",
")",
"except",
"XMLError",
",",
"x",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Erro ao ler o XML da requisicao.'",
")",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"x",
")",
"except",
"(",
"UsuarioError",
",",
"GrupoError",
")",
":",
"return",
"self",
".",
"response_error",
"(",
"1",
")"
] | [
42,
4
] | [
111,
41
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
find_words | (word) | return w.strip() | Função para filtrar por apenas letras dentro de iteráveis
Retornará todas as letras dentro do input 'word'
Se não encontrar nenhuma letra, retornará ''(vazio). | Função para filtrar por apenas letras dentro de iteráveis
Retornará todas as letras dentro do input 'word'
Se não encontrar nenhuma letra, retornará ''(vazio). | def find_words(word):
"""Função para filtrar por apenas letras dentro de iteráveis
Retornará todas as letras dentro do input 'word'
Se não encontrar nenhuma letra, retornará ''(vazio)."""
word = str(word)
w = "".join([char
if char.isalpha()
else ""
for char in word
])
return w.strip() | [
"def",
"find_words",
"(",
"word",
")",
":",
"word",
"=",
"str",
"(",
"word",
")",
"w",
"=",
"\"\"",
".",
"join",
"(",
"[",
"char",
"if",
"char",
".",
"isalpha",
"(",
")",
"else",
"\"\"",
"for",
"char",
"in",
"word",
"]",
")",
"return",
"w",
".",
"strip",
"(",
")"
] | [
3,
0
] | [
13,
20
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
p_acao | (p) | acao : expressao
| declaracao_variaveis
| se
| repita
| leia
| escreva
| retorna
| acao : expressao
| declaracao_variaveis
| se
| repita
| leia
| escreva
| retorna
| def p_acao(p):
"""acao : expressao
| declaracao_variaveis
| se
| repita
| leia
| escreva
| retorna
"""
pai = MyNode(name='acao', type='ACAO')
p[0] = pai
p[1].parent = pai | [
"def",
"p_acao",
"(",
"p",
")",
":",
"pai",
"=",
"MyNode",
"(",
"name",
"=",
"'acao'",
",",
"type",
"=",
"'ACAO'",
")",
"p",
"[",
"0",
"]",
"=",
"pai",
"p",
"[",
"1",
"]",
".",
"parent",
"=",
"pai"
] | [
337,
0
] | [
348,
19
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
lista | (ctx, threshold:str = '100') | lista os players que vão pra guerra com fila de espera e lista de PA | lista os players que vão pra guerra com fila de espera e lista de PA | async def lista(ctx, threshold:str = '100'):
'''lista os players que vão pra guerra com fila de espera e lista de PA'''
separator_go = '\n+'
separator = '\n!'
if len(attend) <= int(threshold):
await ctx.send("```diff\nCONFIRMADOS (" + str(len(attend)) + "): \n+"+separator_go.join(attend)+"```")
else:
wait = '\n-'
await ctx.send("```diff\nCONFIRMADOS (" + threshold + "): \n+"+separator_go.join(attend[:int(threshold)])+"```")
await ctx.send("```diff\nLISTA DE ESPERA (" + str((len(attend) - int(threshold))) + "): \n-"+wait.join(attend[int(threshold):])+"```")
await ctx.send("```diff\nPA (" + str(len(pa_list)) + "): \n!"+separator.join(pa_list)+"```") | [
"async",
"def",
"lista",
"(",
"ctx",
",",
"threshold",
":",
"str",
"=",
"'100'",
")",
":",
"separator_go",
"=",
"'\\n+'",
"separator",
"=",
"'\\n!'",
"if",
"len",
"(",
"attend",
")",
"<=",
"int",
"(",
"threshold",
")",
":",
"await",
"ctx",
".",
"send",
"(",
"\"```diff\\nCONFIRMADOS (\"",
"+",
"str",
"(",
"len",
"(",
"attend",
")",
")",
"+",
"\"): \\n+\"",
"+",
"separator_go",
".",
"join",
"(",
"attend",
")",
"+",
"\"```\"",
")",
"else",
":",
"wait",
"=",
"'\\n-'",
"await",
"ctx",
".",
"send",
"(",
"\"```diff\\nCONFIRMADOS (\"",
"+",
"threshold",
"+",
"\"): \\n+\"",
"+",
"separator_go",
".",
"join",
"(",
"attend",
"[",
":",
"int",
"(",
"threshold",
")",
"]",
")",
"+",
"\"```\"",
")",
"await",
"ctx",
".",
"send",
"(",
"\"```diff\\nLISTA DE ESPERA (\"",
"+",
"str",
"(",
"(",
"len",
"(",
"attend",
")",
"-",
"int",
"(",
"threshold",
")",
")",
")",
"+",
"\"): \\n-\"",
"+",
"wait",
".",
"join",
"(",
"attend",
"[",
"int",
"(",
"threshold",
")",
":",
"]",
")",
"+",
"\"```\"",
")",
"await",
"ctx",
".",
"send",
"(",
"\"```diff\\nPA (\"",
"+",
"str",
"(",
"len",
"(",
"pa_list",
")",
")",
"+",
"\"): \\n!\"",
"+",
"separator",
".",
"join",
"(",
"pa_list",
")",
"+",
"\"```\"",
")"
] | [
99,
0
] | [
111,
93
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
DType21._text2_len | (self) | return bin2int(self.data[20 + self._text1_len : 24 + self._text1_len]) | Retorna o tamanho do campo TEXT2 que contém o ‘unit_info’ no arquivo cfg. | Retorna o tamanho do campo TEXT2 que contém o ‘unit_info’ no arquivo cfg. | def _text2_len(self) -> int:
"""Retorna o tamanho do campo TEXT2 que contém o ‘unit_info’ no arquivo cfg."""
return bin2int(self.data[20 + self._text1_len : 24 + self._text1_len]) | [
"def",
"_text2_len",
"(",
"self",
")",
"->",
"int",
":",
"return",
"bin2int",
"(",
"self",
".",
"data",
"[",
"20",
"+",
"self",
".",
"_text1_len",
":",
"24",
"+",
"self",
".",
"_text1_len",
"]",
")"
] | [
471,
4
] | [
473,
78
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
link_documents_bundles_with_documents | (
documents_bundle: DocumentsBundle, documents: List[str], session: Session
) | Função responsável por atualizar o relacionamento entre
documents bundles e documents no nível de banco de dados | Função responsável por atualizar o relacionamento entre
documents bundles e documents no nível de banco de dados | def link_documents_bundles_with_documents(
documents_bundle: DocumentsBundle, documents: List[str], session: Session
):
"""Função responsável por atualizar o relacionamento entre
documents bundles e documents no nível de banco de dados"""
for document in documents:
try:
documents_bundle.add_document(document)
except AlreadyExists:
logger.info(
"Document %s already exists in documents bundle %s"
% (document, documents_bundle)
)
update_bundle(session, documents_bundle) | [
"def",
"link_documents_bundles_with_documents",
"(",
"documents_bundle",
":",
"DocumentsBundle",
",",
"documents",
":",
"List",
"[",
"str",
"]",
",",
"session",
":",
"Session",
")",
":",
"for",
"document",
"in",
"documents",
":",
"try",
":",
"documents_bundle",
".",
"add_document",
"(",
"document",
")",
"except",
"AlreadyExists",
":",
"logger",
".",
"info",
"(",
"\"Document %s already exists in documents bundle %s\"",
"%",
"(",
"document",
",",
"documents_bundle",
")",
")",
"update_bundle",
"(",
"session",
",",
"documents_bundle",
")"
] | [
326,
0
] | [
340,
44
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
ndoors | (n: int) | return only_open | Define quais portas estarão abertas após 'n' passagens. Todas iniciam trancadas.
Args:
n (int): Número de portas.
Returns:
list: Portas ques estarão aberta apos 'n' passagens.
>>> 100
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> 10
[1, 4, 9]
| Define quais portas estarão abertas após 'n' passagens. Todas iniciam trancadas. | def ndoors(n: int):
"""Define quais portas estarão abertas após 'n' passagens. Todas iniciam trancadas.
Args:
n (int): Número de portas.
Returns:
list: Portas ques estarão aberta apos 'n' passagens.
>>> 100
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> 10
[1, 4, 9]
"""
# Criar lista para portas (1 - 100)
doors = [i for i in range(1, n + 1)]
# Criar lista para status (1: aberta | 0: fechada)
status = [0 for i in doors]
# Apenas portas abertas
only_open = []
# Percorer todas portas alterando valores
for m in doors:
for index, k in enumerate(doors):
# Alterar os valores das portas cujo resto da divisao k e m seja zero
if k % m == 0:
# Se aberta, feche
if status[index]:
status[index] = 0
# Se fechada, abra
else:
status[index] = 1
# Representação visual de todas portas
# for d, s in zip(doors, status):
# print(f"{d:^10} | {s:^3} --")
# Retornar somente portas abertas
for d, s in zip(doors, status):
if s == 1:
only_open.append(d)
return only_open | [
"def",
"ndoors",
"(",
"n",
":",
"int",
")",
":",
"# Criar lista para portas (1 - 100)",
"doors",
"=",
"[",
"i",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"n",
"+",
"1",
")",
"]",
"# Criar lista para status (1: aberta | 0: fechada)",
"status",
"=",
"[",
"0",
"for",
"i",
"in",
"doors",
"]",
"# Apenas portas abertas",
"only_open",
"=",
"[",
"]",
"# Percorer todas portas alterando valores",
"for",
"m",
"in",
"doors",
":",
"for",
"index",
",",
"k",
"in",
"enumerate",
"(",
"doors",
")",
":",
"# Alterar os valores das portas cujo resto da divisao k e m seja zero",
"if",
"k",
"%",
"m",
"==",
"0",
":",
"# Se aberta, feche",
"if",
"status",
"[",
"index",
"]",
":",
"status",
"[",
"index",
"]",
"=",
"0",
"# Se fechada, abra",
"else",
":",
"status",
"[",
"index",
"]",
"=",
"1",
"# Representação visual de todas portas",
"# for d, s in zip(doors, status):",
"# print(f\"{d:^10} | {s:^3} --\")",
"# Retornar somente portas abertas",
"for",
"d",
",",
"s",
"in",
"zip",
"(",
"doors",
",",
"status",
")",
":",
"if",
"s",
"==",
"1",
":",
"only_open",
".",
"append",
"(",
"d",
")",
"return",
"only_open"
] | [
7,
0
] | [
51,
20
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
get_document_assets_path | (
xml: lxml.etree, folder_files: list, folder: str, prefered_types=[".tif"]
) | return (static_assets, static_additionals) | Retorna a lista de assets e seus respectivos paths no
filesystem. Também retorna um dicionário com `arquivos adicionais`
que por ventura existam no pacote SPS. Os arquivos adicionais podem
existir se o XML referênciar um arquivo estático que possua mais de
uma extensão dentro do pacote SPS.
Para os assets do tipo `graphic` existe uma ordem de preferência para os
tipos de arquivos onde arquivos `.tif` são preferênciais em comparação
com arquivos `.jp*g` ou `.png`. Exemplo:
1) Referência para arquivo `1518-8787-rsp-40-01-92-98-gseta`
2) Pacote com arquivos `1518-8787-rsp-40-01-92-98-gseta.jpeg` e
`1518-8787-rsp-40-01-92-98-gseta.tif`
3) Resultado de asset `{'1518-8787-rsp-40-01-92-98-gseta': '1518-8787-rsp-40-01-92-98-gseta.tif'}
4) Resultado para arquivo adicional: `[1518-8787-rsp-40-01-92-98-gseta.jpeg]`
| Retorna a lista de assets e seus respectivos paths no
filesystem. Também retorna um dicionário com `arquivos adicionais`
que por ventura existam no pacote SPS. Os arquivos adicionais podem
existir se o XML referênciar um arquivo estático que possua mais de
uma extensão dentro do pacote SPS. | def get_document_assets_path(
xml: lxml.etree, folder_files: list, folder: str, prefered_types=[".tif"]
) -> Tuple[dict, dict]:
"""Retorna a lista de assets e seus respectivos paths no
filesystem. Também retorna um dicionário com `arquivos adicionais`
que por ventura existam no pacote SPS. Os arquivos adicionais podem
existir se o XML referênciar um arquivo estático que possua mais de
uma extensão dentro do pacote SPS.
Para os assets do tipo `graphic` existe uma ordem de preferência para os
tipos de arquivos onde arquivos `.tif` são preferênciais em comparação
com arquivos `.jp*g` ou `.png`. Exemplo:
1) Referência para arquivo `1518-8787-rsp-40-01-92-98-gseta`
2) Pacote com arquivos `1518-8787-rsp-40-01-92-98-gseta.jpeg` e
`1518-8787-rsp-40-01-92-98-gseta.tif`
3) Resultado de asset `{'1518-8787-rsp-40-01-92-98-gseta': '1518-8787-rsp-40-01-92-98-gseta.tif'}
4) Resultado para arquivo adicional: `[1518-8787-rsp-40-01-92-98-gseta.jpeg]`
"""
# TODO: é preciso que o get_static_assets conheça todos os tipos de assets
static_assets = dict([(asset[0], None) for asset in get_static_assets(xml)])
static_additionals = {}
for folder_file in folder_files:
file_name, extension = os.path.splitext(folder_file)
for key in static_assets.keys():
path = os.path.join(folder, folder_file)
if key == folder_file:
static_assets[key] = path
elif key in folder_file and extension in prefered_types:
static_assets[key] = path
elif key in folder_file and static_assets[key] is None:
static_assets[key] = path
elif file_name == key:
static_additionals[key] = path
elif file_name == os.path.splitext(key)[0]:
static_additionals[file_name] = path
return (static_assets, static_additionals) | [
"def",
"get_document_assets_path",
"(",
"xml",
":",
"lxml",
".",
"etree",
",",
"folder_files",
":",
"list",
",",
"folder",
":",
"str",
",",
"prefered_types",
"=",
"[",
"\".tif\"",
"]",
")",
"->",
"Tuple",
"[",
"dict",
",",
"dict",
"]",
":",
"# TODO: é preciso que o get_static_assets conheça todos os tipos de assets",
"static_assets",
"=",
"dict",
"(",
"[",
"(",
"asset",
"[",
"0",
"]",
",",
"None",
")",
"for",
"asset",
"in",
"get_static_assets",
"(",
"xml",
")",
"]",
")",
"static_additionals",
"=",
"{",
"}",
"for",
"folder_file",
"in",
"folder_files",
":",
"file_name",
",",
"extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"folder_file",
")",
"for",
"key",
"in",
"static_assets",
".",
"keys",
"(",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"folder_file",
")",
"if",
"key",
"==",
"folder_file",
":",
"static_assets",
"[",
"key",
"]",
"=",
"path",
"elif",
"key",
"in",
"folder_file",
"and",
"extension",
"in",
"prefered_types",
":",
"static_assets",
"[",
"key",
"]",
"=",
"path",
"elif",
"key",
"in",
"folder_file",
"and",
"static_assets",
"[",
"key",
"]",
"is",
"None",
":",
"static_assets",
"[",
"key",
"]",
"=",
"path",
"elif",
"file_name",
"==",
"key",
":",
"static_additionals",
"[",
"key",
"]",
"=",
"path",
"elif",
"file_name",
"==",
"os",
".",
"path",
".",
"splitext",
"(",
"key",
")",
"[",
"0",
"]",
":",
"static_additionals",
"[",
"file_name",
"]",
"=",
"path",
"return",
"(",
"static_assets",
",",
"static_additionals",
")"
] | [
84,
0
] | [
125,
46
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
convert_date | (date) | Traduz datas em formato YYYYMMDD ou ano-mes-dia, ano-mes para
o formato usado no banco de dados | Traduz datas em formato YYYYMMDD ou ano-mes-dia, ano-mes para
o formato usado no banco de dados | def convert_date(date):
"""Traduz datas em formato YYYYMMDD ou ano-mes-dia, ano-mes para
o formato usado no banco de dados"""
_date = None
if "-" not in date:
date = "-".join((date[:4], date[4:6], date[6:]))
def limit_month_range(date):
"""Remove o segundo mês da data limitando o intervalo de criaçã
>>> limit_month_range("2018-Oct-Dec")
>>> "2018-Dec"
"""
parts = [part for part in date.split("-") if len(part.strip()) > 0]
return "-".join([parts[0], parts[-1]])
def remove_invalid_date_parts(date):
"""Remove partes inválidas de datas e retorna uma data válida
>>> remove_invalid_date_parts("2019-12-100")
>>> "2019-12"
>>> remove_invalid_date_parts("2019-20-01")
>>> "2019" # Não faz sentido utilizar o dia válido após um mês inválido
"""
date = date.split("-")
_date = []
for index, part in enumerate(date):
if len(part) == 0 or part == "00" or part == "0":
break
elif index == 1 and part.isnumeric() and int(part) > 12:
break
elif index == 2 and part.isnumeric() and int(part) > 31:
break
elif part.isdigit():
part = str(int(part))
_date.append(part)
return "-".join(_date)
formats = [
("%Y-%m-%d", lambda x: x),
("%Y-%m", lambda x: x),
("%Y", lambda x: x),
("%Y-%b-%d", lambda x: x),
("%Y-%b", lambda x: x),
("%Y-%B", lambda x: x),
("%Y-%B-%d", lambda x: x),
("%Y-%B", remove_invalid_date_parts),
("%Y-%b", limit_month_range),
("%Y-%m-%d", remove_invalid_date_parts),
("%Y-%m", remove_invalid_date_parts),
("%Y", remove_invalid_date_parts),
]
for template, func in formats:
try:
_date = (
datetime.strptime(func(date.strip()), template).isoformat(
timespec="microseconds"
)
+ "Z"
)
except ValueError:
continue
else:
return _date
raise ValueError("Could not transform date '%s' to ISO format" % date) from None | [
"def",
"convert_date",
"(",
"date",
")",
":",
"_date",
"=",
"None",
"if",
"\"-\"",
"not",
"in",
"date",
":",
"date",
"=",
"\"-\"",
".",
"join",
"(",
"(",
"date",
"[",
":",
"4",
"]",
",",
"date",
"[",
"4",
":",
"6",
"]",
",",
"date",
"[",
"6",
":",
"]",
")",
")",
"def",
"limit_month_range",
"(",
"date",
")",
":",
"\"\"\"Remove o segundo mês da data limitando o intervalo de criaçã\n >>> limit_month_range(\"2018-Oct-Dec\")\n >>> \"2018-Dec\"\n \"\"\"",
"parts",
"=",
"[",
"part",
"for",
"part",
"in",
"date",
".",
"split",
"(",
"\"-\"",
")",
"if",
"len",
"(",
"part",
".",
"strip",
"(",
")",
")",
">",
"0",
"]",
"return",
"\"-\"",
".",
"join",
"(",
"[",
"parts",
"[",
"0",
"]",
",",
"parts",
"[",
"-",
"1",
"]",
"]",
")",
"def",
"remove_invalid_date_parts",
"(",
"date",
")",
":",
"\"\"\"Remove partes inválidas de datas e retorna uma data válida\n >>> remove_invalid_date_parts(\"2019-12-100\")\n >>> \"2019-12\"\n >>> remove_invalid_date_parts(\"2019-20-01\")\n >>> \"2019\" # Não faz sentido utilizar o dia válido após um mês inválido\n \"\"\"",
"date",
"=",
"date",
".",
"split",
"(",
"\"-\"",
")",
"_date",
"=",
"[",
"]",
"for",
"index",
",",
"part",
"in",
"enumerate",
"(",
"date",
")",
":",
"if",
"len",
"(",
"part",
")",
"==",
"0",
"or",
"part",
"==",
"\"00\"",
"or",
"part",
"==",
"\"0\"",
":",
"break",
"elif",
"index",
"==",
"1",
"and",
"part",
".",
"isnumeric",
"(",
")",
"and",
"int",
"(",
"part",
")",
">",
"12",
":",
"break",
"elif",
"index",
"==",
"2",
"and",
"part",
".",
"isnumeric",
"(",
")",
"and",
"int",
"(",
"part",
")",
">",
"31",
":",
"break",
"elif",
"part",
".",
"isdigit",
"(",
")",
":",
"part",
"=",
"str",
"(",
"int",
"(",
"part",
")",
")",
"_date",
".",
"append",
"(",
"part",
")",
"return",
"\"-\"",
".",
"join",
"(",
"_date",
")",
"formats",
"=",
"[",
"(",
"\"%Y-%m-%d\"",
",",
"lambda",
"x",
":",
"x",
")",
",",
"(",
"\"%Y-%m\"",
",",
"lambda",
"x",
":",
"x",
")",
",",
"(",
"\"%Y\"",
",",
"lambda",
"x",
":",
"x",
")",
",",
"(",
"\"%Y-%b-%d\"",
",",
"lambda",
"x",
":",
"x",
")",
",",
"(",
"\"%Y-%b\"",
",",
"lambda",
"x",
":",
"x",
")",
",",
"(",
"\"%Y-%B\"",
",",
"lambda",
"x",
":",
"x",
")",
",",
"(",
"\"%Y-%B-%d\"",
",",
"lambda",
"x",
":",
"x",
")",
",",
"(",
"\"%Y-%B\"",
",",
"remove_invalid_date_parts",
")",
",",
"(",
"\"%Y-%b\"",
",",
"limit_month_range",
")",
",",
"(",
"\"%Y-%m-%d\"",
",",
"remove_invalid_date_parts",
")",
",",
"(",
"\"%Y-%m\"",
",",
"remove_invalid_date_parts",
")",
",",
"(",
"\"%Y\"",
",",
"remove_invalid_date_parts",
")",
",",
"]",
"for",
"template",
",",
"func",
"in",
"formats",
":",
"try",
":",
"_date",
"=",
"(",
"datetime",
".",
"strptime",
"(",
"func",
"(",
"date",
".",
"strip",
"(",
")",
")",
",",
"template",
")",
".",
"isoformat",
"(",
"timespec",
"=",
"\"microseconds\"",
")",
"+",
"\"Z\"",
")",
"except",
"ValueError",
":",
"continue",
"else",
":",
"return",
"_date",
"raise",
"ValueError",
"(",
"\"Could not transform date '%s' to ISO format\"",
"%",
"date",
")",
"from",
"None"
] | [
12,
0
] | [
79,
84
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Callback.__init__ | (self, fileobj=None, timeout=0) | Cria um objeto Callback.
fileobj: objeto tipo arquivo, podendo ser inclusive
um descritor de arquivo numérico.
timeout: valor de timeout em segundos, podendo ter parte
decimal para expressar fração de segundo | Cria um objeto Callback.
fileobj: objeto tipo arquivo, podendo ser inclusive
um descritor de arquivo numérico.
timeout: valor de timeout em segundos, podendo ter parte
decimal para expressar fração de segundo | def __init__(self, fileobj=None, timeout=0):
'''Cria um objeto Callback.
fileobj: objeto tipo arquivo, podendo ser inclusive
um descritor de arquivo numérico.
timeout: valor de timeout em segundos, podendo ter parte
decimal para expressar fração de segundo'''
if timeout < 0: raise ValueError('timeout negativo')
self.fd = fileobj
self._timeout = timeout
self.base_timeout = timeout
self._enabled = True
self._enabled_to = True
self._reloaded = False | [
"def",
"__init__",
"(",
"self",
",",
"fileobj",
"=",
"None",
",",
"timeout",
"=",
"0",
")",
":",
"if",
"timeout",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'timeout negativo'",
")",
"self",
".",
"fd",
"=",
"fileobj",
"self",
".",
"_timeout",
"=",
"timeout",
"self",
".",
"base_timeout",
"=",
"timeout",
"self",
".",
"_enabled",
"=",
"True",
"self",
".",
"_enabled_to",
"=",
"True",
"self",
".",
"_reloaded",
"=",
"False"
] | [
17,
4
] | [
29,
30
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Restaurante.__init__ | (self, nome_restaurante, tipo_cozinha) | Inicializa os atributos do método. | Inicializa os atributos do método. | def __init__(self, nome_restaurante, tipo_cozinha):
"""Inicializa os atributos do método."""
self.nome_restaurante = nome_restaurante
self.tipo_cozinha = tipo_cozinha
self.pessoas_atendidas = 0 | [
"def",
"__init__",
"(",
"self",
",",
"nome_restaurante",
",",
"tipo_cozinha",
")",
":",
"self",
".",
"nome_restaurante",
"=",
"nome_restaurante",
"self",
".",
"tipo_cozinha",
"=",
"tipo_cozinha",
"self",
".",
"pessoas_atendidas",
"=",
"0"
] | [
4,
4
] | [
8,
34
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
MyFunctor.__mul__ | (self, functor) | ver em oslash ou pymonad. | ver em oslash ou pymonad. | def __mul__(self, functor):
"""ver em oslash ou pymonad."""
# if isinstance(functor, Functor):
# return list(map(lambda value: [func(value) for func in functor],
# self._d))
pass | [
"def",
"__mul__",
"(",
"self",
",",
"functor",
")",
":",
"# if isinstance(functor, Functor):",
"# return list(map(lambda value: [func(value) for func in functor],",
"# self._d))",
"pass"
] | [
19,
4
] | [
24,
12
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
min_max_dc | (vetor, inicio, fim) | return min(vetor_min1, vetor_min2), max(vetor_max1, vetor_max2) | Encontra o valor mínimo e máximo em um vetor usando D&C. | Encontra o valor mínimo e máximo em um vetor usando D&C. | def min_max_dc(vetor, inicio, fim):
"""Encontra o valor mínimo e máximo em um vetor usando D&C."""
if inicio == fim:
return vetor[inicio], vetor[inicio]
meio = (inicio + fim) // 2
vetor_min1, vetor_max1 = min_max_dc(vetor, inicio, meio)
vetor_min2, vetor_max2 = min_max_dc(vetor, meio + 1, fim)
return min(vetor_min1, vetor_min2), max(vetor_max1, vetor_max2) | [
"def",
"min_max_dc",
"(",
"vetor",
",",
"inicio",
",",
"fim",
")",
":",
"if",
"inicio",
"==",
"fim",
":",
"return",
"vetor",
"[",
"inicio",
"]",
",",
"vetor",
"[",
"inicio",
"]",
"meio",
"=",
"(",
"inicio",
"+",
"fim",
")",
"//",
"2",
"vetor_min1",
",",
"vetor_max1",
"=",
"min_max_dc",
"(",
"vetor",
",",
"inicio",
",",
"meio",
")",
"vetor_min2",
",",
"vetor_max2",
"=",
"min_max_dc",
"(",
"vetor",
",",
"meio",
"+",
"1",
",",
"fim",
")",
"return",
"min",
"(",
"vetor_min1",
",",
"vetor_min2",
")",
",",
"max",
"(",
"vetor_max1",
",",
"vetor_max2",
")"
] | [
7,
0
] | [
15,
67
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Certificado.cert_chave | (self) | return self._cert.decode(), self._chave.decode() | Retorna o certificado e a chave | Retorna o certificado e a chave | def cert_chave(self):
"""Retorna o certificado e a chave"""
return self._cert.decode(), self._chave.decode() | [
"def",
"cert_chave",
"(",
"self",
")",
":",
"return",
"self",
".",
"_cert",
".",
"decode",
"(",
")",
",",
"self",
".",
"_chave",
".",
"decode",
"(",
")"
] | [
107,
4
] | [
109,
56
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
remove_ip_equipment | (ip_id, equipment_id, user) | return | Remove o relacionamento entre um ip e um equipamento.
@param ip_id: Identificador do IP.
@param equipment_id: Identificador do equipamento.
@param user: Usuário autenticado.
@return: Nothing.
@raise IpEquipmentNotFoundError: Relacionamento não cadastrado.
@raise IpEquipCantDissociateFromVip: Equip is the last balancer in a created Vip Request, the relationship cannot be removed.
@raise EquipamentoNotFoundError: Equipamento não cadastrado.
@raise IpError, GrupoError: Falha na pesquisa dos dados ou na operação de remover.
@raise UserNotAuthorizedError: Usuário sem autorização para executar a operação.
| Remove o relacionamento entre um ip e um equipamento. | def remove_ip_equipment(ip_id, equipment_id, user):
""" Remove o relacionamento entre um ip e um equipamento.
@param ip_id: Identificador do IP.
@param equipment_id: Identificador do equipamento.
@param user: Usuário autenticado.
@return: Nothing.
@raise IpEquipmentNotFoundError: Relacionamento não cadastrado.
@raise IpEquipCantDissociateFromVip: Equip is the last balancer in a created Vip Request, the relationship cannot be removed.
@raise EquipamentoNotFoundError: Equipamento não cadastrado.
@raise IpError, GrupoError: Falha na pesquisa dos dados ou na operação de remover.
@raise UserNotAuthorizedError: Usuário sem autorização para executar a operação.
"""
if not has_perm(user,
AdminPermission.IPS,
AdminPermission.WRITE_OPERATION,
None,
equipment_id,
AdminPermission.EQUIP_WRITE_OPERATION):
raise UserNotAuthorizedError(
None, u'Usuário não tem permissão para executar a operação.')
IpEquipamento().remove(user, ip_id, equipment_id)
return | [
"def",
"remove_ip_equipment",
"(",
"ip_id",
",",
"equipment_id",
",",
"user",
")",
":",
"if",
"not",
"has_perm",
"(",
"user",
",",
"AdminPermission",
".",
"IPS",
",",
"AdminPermission",
".",
"WRITE_OPERATION",
",",
"None",
",",
"equipment_id",
",",
"AdminPermission",
".",
"EQUIP_WRITE_OPERATION",
")",
":",
"raise",
"UserNotAuthorizedError",
"(",
"None",
",",
"u'Usuário não tem permissão para executar a operação.')",
"",
"IpEquipamento",
"(",
")",
".",
"remove",
"(",
"user",
",",
"ip_id",
",",
"equipment_id",
")",
"return"
] | [
158,
0
] | [
183,
10
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
TestTradeCalculator.test_is_base_experience_approximated_passing_wrong_type | (self) | Teste passando argumentos diferentes de inteiro
>>> _is_base_experience_approximated(42, 42)
bool
>>> _is_base_experience_approximated([...])
Error
| Teste passando argumentos diferentes de inteiro
>>> _is_base_experience_approximated(42, 42)
bool | def test_is_base_experience_approximated_passing_wrong_type(self):
"""Teste passando argumentos diferentes de inteiro
>>> _is_base_experience_approximated(42, 42)
bool
>>> _is_base_experience_approximated([...])
Error
"""
p1 = Player([Pokemon("Pichu", 42), Pokemon("Pikachu", 145)])
p2 = Player([Pokemon("Dito", 30), Pokemon("Charizard", 260)])
tc = TradeCalculator(p1, p2)
self.assertRaises(TypeError, lambda: tc._is_base_experience_approximated({'n1': 42}, {'n2': 13})) | [
"def",
"test_is_base_experience_approximated_passing_wrong_type",
"(",
"self",
")",
":",
"p1",
"=",
"Player",
"(",
"[",
"Pokemon",
"(",
"\"Pichu\"",
",",
"42",
")",
",",
"Pokemon",
"(",
"\"Pikachu\"",
",",
"145",
")",
"]",
")",
"p2",
"=",
"Player",
"(",
"[",
"Pokemon",
"(",
"\"Dito\"",
",",
"30",
")",
",",
"Pokemon",
"(",
"\"Charizard\"",
",",
"260",
")",
"]",
")",
"tc",
"=",
"TradeCalculator",
"(",
"p1",
",",
"p2",
")",
"self",
".",
"assertRaises",
"(",
"TypeError",
",",
"lambda",
":",
"tc",
".",
"_is_base_experience_approximated",
"(",
"{",
"'n1'",
":",
"42",
"}",
",",
"{",
"'n2'",
":",
"13",
"}",
")",
")"
] | [
52,
4
] | [
65,
105
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
test_post_patient | (client) | Teste post /patient/admission - Compara dados enviados com dados salvos no banco e valida status_code 200 | Teste post /patient/admission - Compara dados enviados com dados salvos no banco e valida status_code 200 | def test_post_patient(client):
"""Teste post /patient/admission - Compara dados enviados com dados salvos no banco e valida status_code 200"""
access_token = get_access(client, 'noadmin', 'noadmin')
admission = '5'
data = {
"height": "15.0"
}
url = 'patient/' + admission
response = client.post(url, data=json.dumps(data), headers=make_headers(access_token))
responseData = json.loads(response.data)['data']
patient = session.query(Patient).get(admission)
assert response.status_code == 200
assert data['height'] == str(patient.height)
assert admission == str(responseData) | [
"def",
"test_post_patient",
"(",
"client",
")",
":",
"access_token",
"=",
"get_access",
"(",
"client",
",",
"'noadmin'",
",",
"'noadmin'",
")",
"admission",
"=",
"'5'",
"data",
"=",
"{",
"\"height\"",
":",
"\"15.0\"",
"}",
"url",
"=",
"'patient/'",
"+",
"admission",
"response",
"=",
"client",
".",
"post",
"(",
"url",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
",",
"headers",
"=",
"make_headers",
"(",
"access_token",
")",
")",
"responseData",
"=",
"json",
".",
"loads",
"(",
"response",
".",
"data",
")",
"[",
"'data'",
"]",
"patient",
"=",
"session",
".",
"query",
"(",
"Patient",
")",
".",
"get",
"(",
"admission",
")",
"assert",
"response",
".",
"status_code",
"==",
"200",
"assert",
"data",
"[",
"'height'",
"]",
"==",
"str",
"(",
"patient",
".",
"height",
")",
"assert",
"admission",
"==",
"str",
"(",
"responseData",
")"
] | [
17,
0
] | [
34,
41
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
enumerate_joint | (variables, e, P) | return sum([enumerate_joint(rest, extend(e, Y, y), P) for y in P.values(Y)]) | Retornar a soma dessas entradas em P consistente com e,
As variáveis fornecidas são as variáveis restantes de P (aquelas não em e). | Retornar a soma dessas entradas em P consistente com e,
As variáveis fornecidas são as variáveis restantes de P (aquelas não em e). | def enumerate_joint(variables, e, P):
"""Retornar a soma dessas entradas em P consistente com e,
As variáveis fornecidas são as variáveis restantes de P (aquelas não em e)."""
if not variables:
return P[e]
Y, rest = variables[0], variables[1:]
return sum([enumerate_joint(rest, extend(e, Y, y), P) for y in P.values(Y)]) | [
"def",
"enumerate_joint",
"(",
"variables",
",",
"e",
",",
"P",
")",
":",
"if",
"not",
"variables",
":",
"return",
"P",
"[",
"e",
"]",
"Y",
",",
"rest",
"=",
"variables",
"[",
"0",
"]",
",",
"variables",
"[",
"1",
":",
"]",
"return",
"sum",
"(",
"[",
"enumerate_joint",
"(",
"rest",
",",
"extend",
"(",
"e",
",",
"Y",
",",
"y",
")",
",",
"P",
")",
"for",
"y",
"in",
"P",
".",
"values",
"(",
"Y",
")",
"]",
")"
] | [
145,
0
] | [
151,
80
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
csv_file | (final_list) | Exporta CSV com informações gerais dos papers. | Exporta CSV com informações gerais dos papers. | def csv_file(final_list):
"""Exporta CSV com informações gerais dos papers."""
print('Salvando arquivo .csv com todas as informações: autores/instituições, título, tipo, evento, ano, link do pdf')
df = pd.DataFrame(final_list, columns=['Autor(es)/Instituições', 'Título', 'Tipo', 'Evento', 'Ano', 'Link do Arquivo'])
df.to_csv('anais-anpuh-infos.csv')
print('Raspagem completa.') | [
"def",
"csv_file",
"(",
"final_list",
")",
":",
"print",
"(",
"'Salvando arquivo .csv com todas as informações: autores/instituições, título, tipo, evento, ano, link do pdf')",
"",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"final_list",
",",
"columns",
"=",
"[",
"'Autor(es)/Instituições', ",
"'",
"ítulo', '",
"T",
"po', '",
"E",
"ento', '",
"A",
"o', '",
"L",
"nk do Arquivo'])",
"",
"",
"df",
".",
"to_csv",
"(",
"'anais-anpuh-infos.csv'",
")",
"print",
"(",
"'Raspagem completa.'",
")"
] | [
13,
0
] | [
18,
31
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
pl_resolution | (KB, alpha) | Resolução Propositional-lógica | Resolução Propositional-lógica | def pl_resolution(KB, alpha):
"Resolução Propositional-lógica"
clauses = KB.clauses + conjuncts(to_cnf(~alpha))
new = set()
while True:
n = len(clauses)
pairs = [(clauses[i], clauses[j])
for i in range(n) for j in range(i+1, n)]
for (ci, cj) in pairs:
resolvents = pl_resolve(ci, cj)
if False in resolvents:
return True
new = new.union(set(resolvents))
if new.issubset(set(clauses)):
return False
for c in new:
if c not in clauses:
clauses.append(c) | [
"def",
"pl_resolution",
"(",
"KB",
",",
"alpha",
")",
":",
"clauses",
"=",
"KB",
".",
"clauses",
"+",
"conjuncts",
"(",
"to_cnf",
"(",
"~",
"alpha",
")",
")",
"new",
"=",
"set",
"(",
")",
"while",
"True",
":",
"n",
"=",
"len",
"(",
"clauses",
")",
"pairs",
"=",
"[",
"(",
"clauses",
"[",
"i",
"]",
",",
"clauses",
"[",
"j",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"n",
")",
"for",
"j",
"in",
"range",
"(",
"i",
"+",
"1",
",",
"n",
")",
"]",
"for",
"(",
"ci",
",",
"cj",
")",
"in",
"pairs",
":",
"resolvents",
"=",
"pl_resolve",
"(",
"ci",
",",
"cj",
")",
"if",
"False",
"in",
"resolvents",
":",
"return",
"True",
"new",
"=",
"new",
".",
"union",
"(",
"set",
"(",
"resolvents",
")",
")",
"if",
"new",
".",
"issubset",
"(",
"set",
"(",
"clauses",
")",
")",
":",
"return",
"False",
"for",
"c",
"in",
"new",
":",
"if",
"c",
"not",
"in",
"clauses",
":",
"clauses",
".",
"append",
"(",
"c",
")"
] | [
403,
0
] | [
420,
33
] | null | python | pt | ['pt', 'pt', 'pt'] | False | true | null |
|
texto_ou_api | (response_dict) | analizar se devemos coletar api do watson ou resposta para o usuário | analizar se devemos coletar api do watson ou resposta para o usuário | def texto_ou_api(response_dict):
"""analizar se devemos coletar api do watson ou resposta para o usuário"""
if response_dict['output']['generic'][0].get('text') == '--API':
return True
else:
return False | [
"def",
"texto_ou_api",
"(",
"response_dict",
")",
":",
"if",
"response_dict",
"[",
"'output'",
"]",
"[",
"'generic'",
"]",
"[",
"0",
"]",
".",
"get",
"(",
"'text'",
")",
"==",
"'--API'",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | [
62,
0
] | [
67,
20
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
InterfaceResource.get_interface_map | (self, interface) | return map | Gera o mapa para renderização do XML com os atributos de uma interface | Gera o mapa para renderização do XML com os atributos de uma interface | def get_interface_map(self, interface):
"""Gera o mapa para renderização do XML com os atributos de uma interface"""
map = dict()
map['id'] = interface.id
map['nome'] = interface.interface
map['protegida'] = interface.protegida
map['descricao'] = interface.descricao
map['tipo'] = interface.tipo.tipo
map['id_equipamento'] = interface.equipamento_id
map['equipamento_nome'] = interface.equipamento.nome
map['vlan'] = interface.vlan_nativa
map['sw_router'] = None
if interface.channel is not None:
map['channel'] = interface.channel.nome
map['lacp'] = interface.channel.lacp
map['id_channel'] = interface.channel.id
map['sw_router'] = True
elif interface.ligacao_front is not None:
try:
sw_router = interface.get_switch_and_router_interface_from_host_interface(
None)
if sw_router.channel is not None:
map['channel'] = sw_router.channel.nome
map['lacp'] = sw_router.channel.lacp
map['id_channel'] = sw_router.channel.id
except:
pass
if interface.ligacao_front is None:
map['id_ligacao_front'] = ''
else:
map['id_ligacao_front'] = interface.ligacao_front_id
if interface.ligacao_back is None:
map['id_ligacao_back'] = ''
else:
map['id_ligacao_back'] = interface.ligacao_back_id
return map | [
"def",
"get_interface_map",
"(",
"self",
",",
"interface",
")",
":",
"map",
"=",
"dict",
"(",
")",
"map",
"[",
"'id'",
"]",
"=",
"interface",
".",
"id",
"map",
"[",
"'nome'",
"]",
"=",
"interface",
".",
"interface",
"map",
"[",
"'protegida'",
"]",
"=",
"interface",
".",
"protegida",
"map",
"[",
"'descricao'",
"]",
"=",
"interface",
".",
"descricao",
"map",
"[",
"'tipo'",
"]",
"=",
"interface",
".",
"tipo",
".",
"tipo",
"map",
"[",
"'id_equipamento'",
"]",
"=",
"interface",
".",
"equipamento_id",
"map",
"[",
"'equipamento_nome'",
"]",
"=",
"interface",
".",
"equipamento",
".",
"nome",
"map",
"[",
"'vlan'",
"]",
"=",
"interface",
".",
"vlan_nativa",
"map",
"[",
"'sw_router'",
"]",
"=",
"None",
"if",
"interface",
".",
"channel",
"is",
"not",
"None",
":",
"map",
"[",
"'channel'",
"]",
"=",
"interface",
".",
"channel",
".",
"nome",
"map",
"[",
"'lacp'",
"]",
"=",
"interface",
".",
"channel",
".",
"lacp",
"map",
"[",
"'id_channel'",
"]",
"=",
"interface",
".",
"channel",
".",
"id",
"map",
"[",
"'sw_router'",
"]",
"=",
"True",
"elif",
"interface",
".",
"ligacao_front",
"is",
"not",
"None",
":",
"try",
":",
"sw_router",
"=",
"interface",
".",
"get_switch_and_router_interface_from_host_interface",
"(",
"None",
")",
"if",
"sw_router",
".",
"channel",
"is",
"not",
"None",
":",
"map",
"[",
"'channel'",
"]",
"=",
"sw_router",
".",
"channel",
".",
"nome",
"map",
"[",
"'lacp'",
"]",
"=",
"sw_router",
".",
"channel",
".",
"lacp",
"map",
"[",
"'id_channel'",
"]",
"=",
"sw_router",
".",
"channel",
".",
"id",
"except",
":",
"pass",
"if",
"interface",
".",
"ligacao_front",
"is",
"None",
":",
"map",
"[",
"'id_ligacao_front'",
"]",
"=",
"''",
"else",
":",
"map",
"[",
"'id_ligacao_front'",
"]",
"=",
"interface",
".",
"ligacao_front_id",
"if",
"interface",
".",
"ligacao_back",
"is",
"None",
":",
"map",
"[",
"'id_ligacao_back'",
"]",
"=",
"''",
"else",
":",
"map",
"[",
"'id_ligacao_back'",
"]",
"=",
"interface",
".",
"ligacao_back_id",
"return",
"map"
] | [
453,
4
] | [
488,
18
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Settings.__init__ | (self) | Inicializa as configurações do jogo | Inicializa as configurações do jogo | def __init__(self):
"""Inicializa as configurações do jogo"""
#configuração da tela
self.screen_width = 1200
self.screen_height = 600
self.bg_color = (230,230,230)
#configurações da espaçonave
self.ship_speed_factor = 1.5
# Configurações dos projéteis
self.bullet_speed_factor = 1
self.bullet_width = 3
self.bullet_height = 15
self.bullet_color = 60,60,60
self.bullets_alowed = 3 | [
"def",
"__init__",
"(",
"self",
")",
":",
"#configuração da tela",
"self",
".",
"screen_width",
"=",
"1200",
"self",
".",
"screen_height",
"=",
"600",
"self",
".",
"bg_color",
"=",
"(",
"230",
",",
"230",
",",
"230",
")",
"#configurações da espaçonave",
"self",
".",
"ship_speed_factor",
"=",
"1.5",
"# Configurações dos projéteis",
"self",
".",
"bullet_speed_factor",
"=",
"1",
"self",
".",
"bullet_width",
"=",
"3",
"self",
".",
"bullet_height",
"=",
"15",
"self",
".",
"bullet_color",
"=",
"60",
",",
"60",
",",
"60",
"self",
".",
"bullets_alowed",
"=",
"3"
] | [
4,
4
] | [
19,
31
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
DireitosGrupoEquipamento.remove | (cls, authenticated_user, pk) | Remove os direitos de um grupo de usuário em um grupo de equipamento.
@raise GrupoError: Falha ao alterar os direitos.
@raise DireitosGrupoEquipamento.DoesNotExist: DireitoGrupoEquipamento não cadastrado.
| Remove os direitos de um grupo de usuário em um grupo de equipamento. | def remove(cls, authenticated_user, pk):
"""Remove os direitos de um grupo de usuário em um grupo de equipamento.
@raise GrupoError: Falha ao alterar os direitos.
@raise DireitosGrupoEquipamento.DoesNotExist: DireitoGrupoEquipamento não cadastrado.
"""
direito = DireitosGrupoEquipamento.get_by_pk(pk)
try:
direito.delete()
except Exception, e:
cls.log.error(
u'Falha ao remover os direitos de um grupo de usuário em um grupo de equipamento.')
raise GrupoError(
e, u'Falha ao remover os direitos de um grupo de usuário em um grupo de equipamento.') | [
"def",
"remove",
"(",
"cls",
",",
"authenticated_user",
",",
"pk",
")",
":",
"direito",
"=",
"DireitosGrupoEquipamento",
".",
"get_by_pk",
"(",
"pk",
")",
"try",
":",
"direito",
".",
"delete",
"(",
")",
"except",
"Exception",
",",
"e",
":",
"cls",
".",
"log",
".",
"error",
"(",
"u'Falha ao remover os direitos de um grupo de usuário em um grupo de equipamento.')",
"",
"raise",
"GrupoError",
"(",
"e",
",",
"u'Falha ao remover os direitos de um grupo de usuário em um grupo de equipamento.')",
""
] | [
528,
4
] | [
542,
103
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
update | (id) | Faz o update do sócio informado pelo id | Faz o update do sócio informado pelo id | def update(id):
"""Faz o update do sócio informado pelo id"""
try:
socio = get_socio(id)
if request.method == 'POST':
f = ""
if request.files['image']:
file = request.files['image']
f = upload_file(file)
name_image = f.filename if f else socio['caminho_imagem']
request_parsed = parse_request(request)
sql = 'UPDATE socio set nome = "%s", rg = "%s", nasc = "%s", email = "%s", nome_pai = "%s", nome_mae = "%s", cidade = "%s", bairro = "%s", logradouro = "%s", num = "%s", tel_res = "%s", cel_1 = "%s", cel_2 = "%s", caminho_imagem = "%s" where id = %d' % (request_parsed['nome'], request_parsed['rg'], request_parsed['nasc'], request_parsed['email'], request_parsed['nome_pai'], request_parsed['nome_mae'], request_parsed['cidade'], request_parsed['bairro'], request_parsed['logradouro'], request_parsed['num'], request_parsed['tel_res'], request_parsed['cel_1'], request_parsed['cel_2'], name_image, id)
db.insert_bd(sql)
return redirect(url_for('socio.index'))
return render_template('socio/update.html', socio=socio)
except Exception as e:
print(e)
return render_template('404.html') | [
"def",
"update",
"(",
"id",
")",
":",
"try",
":",
"socio",
"=",
"get_socio",
"(",
"id",
")",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"f",
"=",
"\"\"",
"if",
"request",
".",
"files",
"[",
"'image'",
"]",
":",
"file",
"=",
"request",
".",
"files",
"[",
"'image'",
"]",
"f",
"=",
"upload_file",
"(",
"file",
")",
"name_image",
"=",
"f",
".",
"filename",
"if",
"f",
"else",
"socio",
"[",
"'caminho_imagem'",
"]",
"request_parsed",
"=",
"parse_request",
"(",
"request",
")",
"sql",
"=",
"'UPDATE socio set nome = \"%s\", rg = \"%s\", nasc = \"%s\", email = \"%s\", nome_pai = \"%s\", nome_mae = \"%s\", cidade = \"%s\", bairro = \"%s\", logradouro = \"%s\", num = \"%s\", tel_res = \"%s\", cel_1 = \"%s\", cel_2 = \"%s\", caminho_imagem = \"%s\" where id = %d'",
"%",
"(",
"request_parsed",
"[",
"'nome'",
"]",
",",
"request_parsed",
"[",
"'rg'",
"]",
",",
"request_parsed",
"[",
"'nasc'",
"]",
",",
"request_parsed",
"[",
"'email'",
"]",
",",
"request_parsed",
"[",
"'nome_pai'",
"]",
",",
"request_parsed",
"[",
"'nome_mae'",
"]",
",",
"request_parsed",
"[",
"'cidade'",
"]",
",",
"request_parsed",
"[",
"'bairro'",
"]",
",",
"request_parsed",
"[",
"'logradouro'",
"]",
",",
"request_parsed",
"[",
"'num'",
"]",
",",
"request_parsed",
"[",
"'tel_res'",
"]",
",",
"request_parsed",
"[",
"'cel_1'",
"]",
",",
"request_parsed",
"[",
"'cel_2'",
"]",
",",
"name_image",
",",
"id",
")",
"db",
".",
"insert_bd",
"(",
"sql",
")",
"return",
"redirect",
"(",
"url_for",
"(",
"'socio.index'",
")",
")",
"return",
"render_template",
"(",
"'socio/update.html'",
",",
"socio",
"=",
"socio",
")",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"e",
")",
"return",
"render_template",
"(",
"'404.html'",
")"
] | [
182,
0
] | [
202,
42
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
convert_token_to_relation | (sentence,token) | return Relation(sentence,token) | Converte um objeto do tipo token da biblioteca conllu em um objeto
do tipo Relation criado aqui
| Converte um objeto do tipo token da biblioteca conllu em um objeto
do tipo Relation criado aqui
| def convert_token_to_relation(sentence,token):
""" Converte um objeto do tipo token da biblioteca conllu em um objeto
do tipo Relation criado aqui
"""
return Relation(sentence,token) | [
"def",
"convert_token_to_relation",
"(",
"sentence",
",",
"token",
")",
":",
"return",
"Relation",
"(",
"sentence",
",",
"token",
")"
] | [
26,
0
] | [
30,
35
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
CNS._generate_first_case | (self, cns: list, generate_random=False) | return cns | Gera um CNS válido para os casos que se inicia com 1 ou 2. | Gera um CNS válido para os casos que se inicia com 1 ou 2. | def _generate_first_case(self, cns: list, generate_random=False) -> list:
"""Gera um CNS válido para os casos que se inicia com 1 ou 2."""
if generate_random:
# Adiciona os próximos 10 dígitos
cns = cns + [str(sample(self.digits, 1)[0]) for i in range(10)]
else:
# Pega apenas a parte que precisamos do CNS
cns = cns[:11]
# Processo de soma
sum = self._sum_algorithm(cns, 11)
dv = 11 - (sum % 11)
if dv == 11:
dv = 0
if dv == 10:
sum += 2
dv = 11 - (sum % 11)
cns = cns + ['0', '0', '1', str(dv)]
else:
cns = cns + ['0', '0', '0', str(dv)]
return cns | [
"def",
"_generate_first_case",
"(",
"self",
",",
"cns",
":",
"list",
",",
"generate_random",
"=",
"False",
")",
"->",
"list",
":",
"if",
"generate_random",
":",
"# Adiciona os próximos 10 dígitos",
"cns",
"=",
"cns",
"+",
"[",
"str",
"(",
"sample",
"(",
"self",
".",
"digits",
",",
"1",
")",
"[",
"0",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"10",
")",
"]",
"else",
":",
"# Pega apenas a parte que precisamos do CNS",
"cns",
"=",
"cns",
"[",
":",
"11",
"]",
"# Processo de soma",
"sum",
"=",
"self",
".",
"_sum_algorithm",
"(",
"cns",
",",
"11",
")",
"dv",
"=",
"11",
"-",
"(",
"sum",
"%",
"11",
")",
"if",
"dv",
"==",
"11",
":",
"dv",
"=",
"0",
"if",
"dv",
"==",
"10",
":",
"sum",
"+=",
"2",
"dv",
"=",
"11",
"-",
"(",
"sum",
"%",
"11",
")",
"cns",
"=",
"cns",
"+",
"[",
"'0'",
",",
"'0'",
",",
"'1'",
",",
"str",
"(",
"dv",
")",
"]",
"else",
":",
"cns",
"=",
"cns",
"+",
"[",
"'0'",
",",
"'0'",
",",
"'0'",
",",
"str",
"(",
"dv",
")",
"]",
"return",
"cns"
] | [
54,
4
] | [
78,
18
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
RestResource.not_implemented | (self) | return http_res | Cria um HttpResponse com o código HTTP 501 - Not implemented. | Cria um HttpResponse com o código HTTP 501 - Not implemented. | def not_implemented(self):
"""Cria um HttpResponse com o código HTTP 501 - Not implemented."""
http_res = HttpResponse(
u'501 - Chamada não implementada.',
status=501,
content_type='text/plain')
http_res['X-Request-Id'] = local.request_id
http_res['X-Request-Context'] = local.request_context
return http_res | [
"def",
"not_implemented",
"(",
"self",
")",
":",
"http_res",
"=",
"HttpResponse",
"(",
"u'501 - Chamada não implementada.',",
"",
"status",
"=",
"501",
",",
"content_type",
"=",
"'text/plain'",
")",
"http_res",
"[",
"'X-Request-Id'",
"]",
"=",
"local",
".",
"request_id",
"http_res",
"[",
"'X-Request-Context'",
"]",
"=",
"local",
".",
"request_context",
"return",
"http_res"
] | [
182,
4
] | [
192,
23
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
try_register_documents | (
documents: Iterable,
get_relation_data: callable,
fetch_document_front: callable,
article_factory: callable,
) | return list(set(orphans)) | Registra documentos do Kernel na base de dados do `OPAC`.
Os documentos que não puderem ser registrados serão considerados como
órfãos. Documentos que não possuam identificação a qual fascículo tem
relação serão considerados órfãos.
Args:
documents (Iterable): iterável com os identicadores dos documentos
a serem registrados.
get_relation_data (callable): função que identifica o fasículo
e o item de relacionamento que está sendo registrado.
fetch_document_front (callable): função que recupera os dados de
`front` do documento a partir da API do Kernel.
article_factory (callable): função que cria uma instância do modelo
de dados do Artigo na base do OPAC.
Returns:
List[str] orphans: Lista contendo todos os identificadores dos
documentos que não puderam ser registrados na base de dados do
OPAC.
| Registra documentos do Kernel na base de dados do `OPAC`. | def try_register_documents(
documents: Iterable,
get_relation_data: callable,
fetch_document_front: callable,
article_factory: callable,
) -> List[str]:
"""Registra documentos do Kernel na base de dados do `OPAC`.
Os documentos que não puderem ser registrados serão considerados como
órfãos. Documentos que não possuam identificação a qual fascículo tem
relação serão considerados órfãos.
Args:
documents (Iterable): iterável com os identicadores dos documentos
a serem registrados.
get_relation_data (callable): função que identifica o fasículo
e o item de relacionamento que está sendo registrado.
fetch_document_front (callable): função que recupera os dados de
`front` do documento a partir da API do Kernel.
article_factory (callable): função que cria uma instância do modelo
de dados do Artigo na base do OPAC.
Returns:
List[str] orphans: Lista contendo todos os identificadores dos
documentos que não puderam ser registrados na base de dados do
OPAC.
"""
orphans = []
# Para capturarmos a URL base é necessário que o hook tenha sido utilizado
# ao menos uma vez.
BASE_URL = hooks.KERNEL_HOOK_BASE.run(
endpoint="", extra_options={"timeout": 1, "check_response": False}
).url
for document_id in documents:
try:
issue_id, item = get_relation_data(document_id)
document_front = fetch_document_front(document_id)
document_xml_url = "{base_url}documents/{document_id}".format(
base_url=BASE_URL, document_id=document_id
)
document = article_factory(
document_id,
document_front,
issue_id,
item.get("order"),
document_xml_url,
)
document.save()
except (models.Issue.DoesNotExist, ValueError):
orphans.append(document_id)
logging.info(
"Could not possible to register the document %s. "
"Probably the issue that is related to it does not exist." % document_id
)
return list(set(orphans)) | [
"def",
"try_register_documents",
"(",
"documents",
":",
"Iterable",
",",
"get_relation_data",
":",
"callable",
",",
"fetch_document_front",
":",
"callable",
",",
"article_factory",
":",
"callable",
",",
")",
"->",
"List",
"[",
"str",
"]",
":",
"orphans",
"=",
"[",
"]",
"# Para capturarmos a URL base é necessário que o hook tenha sido utilizado",
"# ao menos uma vez.",
"BASE_URL",
"=",
"hooks",
".",
"KERNEL_HOOK_BASE",
".",
"run",
"(",
"endpoint",
"=",
"\"\"",
",",
"extra_options",
"=",
"{",
"\"timeout\"",
":",
"1",
",",
"\"check_response\"",
":",
"False",
"}",
")",
".",
"url",
"for",
"document_id",
"in",
"documents",
":",
"try",
":",
"issue_id",
",",
"item",
"=",
"get_relation_data",
"(",
"document_id",
")",
"document_front",
"=",
"fetch_document_front",
"(",
"document_id",
")",
"document_xml_url",
"=",
"\"{base_url}documents/{document_id}\"",
".",
"format",
"(",
"base_url",
"=",
"BASE_URL",
",",
"document_id",
"=",
"document_id",
")",
"document",
"=",
"article_factory",
"(",
"document_id",
",",
"document_front",
",",
"issue_id",
",",
"item",
".",
"get",
"(",
"\"order\"",
")",
",",
"document_xml_url",
",",
")",
"document",
".",
"save",
"(",
")",
"except",
"(",
"models",
".",
"Issue",
".",
"DoesNotExist",
",",
"ValueError",
")",
":",
"orphans",
".",
"append",
"(",
"document_id",
")",
"logging",
".",
"info",
"(",
"\"Could not possible to register the document %s. \"",
"\"Probably the issue that is related to it does not exist.\"",
"%",
"document_id",
")",
"return",
"list",
"(",
"set",
"(",
"orphans",
")",
")"
] | [
233,
0
] | [
291,
29
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
MinhaUFOP.listar_boletos | (self, **kwargs) | Retorna uma lista de boletos emitidos pelo usuário
Kwargs:
url (str): URL para fazer a requisição ao servidor
headers (dict): Headers da requisição ao servidor
Raises:
MinhaUFOPHTTPError: O servidor retornou o código {código HTTP}
| Retorna uma lista de boletos emitidos pelo usuário | def listar_boletos(self, **kwargs) -> list:
"""Retorna uma lista de boletos emitidos pelo usuário
Kwargs:
url (str): URL para fazer a requisição ao servidor
headers (dict): Headers da requisição ao servidor
Raises:
MinhaUFOPHTTPError: O servidor retornou o código {código HTTP}
"""
url = kwargs.get('url', "https://zeppelin10.ufop.br/api/v1/ru/boleto/")
headers = kwargs.get('headers', {'Authorization': f'Bearer {self.token}'})
response = requests.request("GET", url, headers=headers)
if response.ok:
return response.json()
else:
raise MinhaUFOPHTTPError(response) | [
"def",
"listar_boletos",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"->",
"list",
":",
"url",
"=",
"kwargs",
".",
"get",
"(",
"'url'",
",",
"\"https://zeppelin10.ufop.br/api/v1/ru/boleto/\"",
")",
"headers",
"=",
"kwargs",
".",
"get",
"(",
"'headers'",
",",
"{",
"'Authorization'",
":",
"f'Bearer {self.token}'",
"}",
")",
"response",
"=",
"requests",
".",
"request",
"(",
"\"GET\"",
",",
"url",
",",
"headers",
"=",
"headers",
")",
"if",
"response",
".",
"ok",
":",
"return",
"response",
".",
"json",
"(",
")",
"else",
":",
"raise",
"MinhaUFOPHTTPError",
"(",
"response",
")"
] | [
224,
4
] | [
243,
46
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Stack.__len__ | (self) | return self._size | Retorna o tamanho da lista | Retorna o tamanho da lista | def __len__(self):
"""Retorna o tamanho da lista"""
return self._size | [
"def",
"__len__",
"(",
"self",
")",
":",
"return",
"self",
".",
"_size"
] | [
36,
4
] | [
38,
25
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
tell | (kb, perceptions, loc) | Atualizar o conhecimento de acordo com a percepção e localização. | Atualizar o conhecimento de acordo com a percepção e localização. | def tell(kb, perceptions, loc):
"""Atualizar o conhecimento de acordo com a percepção e localização."""
# O agente está vivo e percebeu algo assim:
# Não há poços nem o Wumpus neste quarto
kb[loc].wumpus = kb[loc].pit = Status.Absent
wumpus, pit, gold = perceptions
near = [kb[l] for l in neighbors(loc)]
# Iterar sobre salas vizinhas não seguras
for room in (r for r in near if not r.is_safe()):
# Analisar a percepção Wumpus
if room.wumpus != Status.Absent:
if wumpus == Status.Absent:
room.wumpus = Status.Absent
elif wumpus == Status.LikelyPresent:
# Verificar se este é o único local onde o Wumpus pode estar
if len([r for r in near if r.is_dangerous(Entity.Wumpus)]) == 1:
room.wumpus = Status.Present
elif room.wumpus == Status.Unknown:
if any(r.is_deadly(Entity.Wumpus) for r in near):
# O agente sabe o local Wumpus -> ele não pode estar nesta sala
room.wumpus = Status.Absent
elif all(r.is_safe(Entity.Wumpus) for r in near if r != room):
# Todos os outros vizinhos são seguros -> o Wumpus deve estar nesta sala
room.wumpus = Status.Present
else:
room.wumpus = Status.LikelyPresent
# Analisar a percepção dos poços
if room.pit != Status.Absent:
if pit == Status.Absent:
room.pit = Status.Absent
elif pit == Status.LikelyPresent:
# Verifique se este é o único lugar onde o poço pode estar
if len([r for r in near if r.is_dangerous(Entity.Pit)]) == 1:
room.pit = Status.Present
elif room.pit == Status.Unknown:
if all(r.is_safe(Entity.Pit) for r in near if r != room):
# Todos os outros vizinhos estão seguros -> o poço deve estar nesta sala
room.pit = Status.Present
else:
room.pit = Status.LikelyPresent
# Analisa a percepção do ouro
kb[loc].gold = gold | [
"def",
"tell",
"(",
"kb",
",",
"perceptions",
",",
"loc",
")",
":",
"# O agente está vivo e percebeu algo assim:",
"# Não há poços nem o Wumpus neste quarto",
"kb",
"[",
"loc",
"]",
".",
"wumpus",
"=",
"kb",
"[",
"loc",
"]",
".",
"pit",
"=",
"Status",
".",
"Absent",
"wumpus",
",",
"pit",
",",
"gold",
"=",
"perceptions",
"near",
"=",
"[",
"kb",
"[",
"l",
"]",
"for",
"l",
"in",
"neighbors",
"(",
"loc",
")",
"]",
"# Iterar sobre salas vizinhas não seguras",
"for",
"room",
"in",
"(",
"r",
"for",
"r",
"in",
"near",
"if",
"not",
"r",
".",
"is_safe",
"(",
")",
")",
":",
"# Analisar a percepção Wumpus",
"if",
"room",
".",
"wumpus",
"!=",
"Status",
".",
"Absent",
":",
"if",
"wumpus",
"==",
"Status",
".",
"Absent",
":",
"room",
".",
"wumpus",
"=",
"Status",
".",
"Absent",
"elif",
"wumpus",
"==",
"Status",
".",
"LikelyPresent",
":",
"# Verificar se este é o único local onde o Wumpus pode estar",
"if",
"len",
"(",
"[",
"r",
"for",
"r",
"in",
"near",
"if",
"r",
".",
"is_dangerous",
"(",
"Entity",
".",
"Wumpus",
")",
"]",
")",
"==",
"1",
":",
"room",
".",
"wumpus",
"=",
"Status",
".",
"Present",
"elif",
"room",
".",
"wumpus",
"==",
"Status",
".",
"Unknown",
":",
"if",
"any",
"(",
"r",
".",
"is_deadly",
"(",
"Entity",
".",
"Wumpus",
")",
"for",
"r",
"in",
"near",
")",
":",
"# O agente sabe o local Wumpus -> ele não pode estar nesta sala",
"room",
".",
"wumpus",
"=",
"Status",
".",
"Absent",
"elif",
"all",
"(",
"r",
".",
"is_safe",
"(",
"Entity",
".",
"Wumpus",
")",
"for",
"r",
"in",
"near",
"if",
"r",
"!=",
"room",
")",
":",
"# Todos os outros vizinhos são seguros -> o Wumpus deve estar nesta sala",
"room",
".",
"wumpus",
"=",
"Status",
".",
"Present",
"else",
":",
"room",
".",
"wumpus",
"=",
"Status",
".",
"LikelyPresent",
"# Analisar a percepção dos poços",
"if",
"room",
".",
"pit",
"!=",
"Status",
".",
"Absent",
":",
"if",
"pit",
"==",
"Status",
".",
"Absent",
":",
"room",
".",
"pit",
"=",
"Status",
".",
"Absent",
"elif",
"pit",
"==",
"Status",
".",
"LikelyPresent",
":",
"# Verifique se este é o único lugar onde o poço pode estar",
"if",
"len",
"(",
"[",
"r",
"for",
"r",
"in",
"near",
"if",
"r",
".",
"is_dangerous",
"(",
"Entity",
".",
"Pit",
")",
"]",
")",
"==",
"1",
":",
"room",
".",
"pit",
"=",
"Status",
".",
"Present",
"elif",
"room",
".",
"pit",
"==",
"Status",
".",
"Unknown",
":",
"if",
"all",
"(",
"r",
".",
"is_safe",
"(",
"Entity",
".",
"Pit",
")",
"for",
"r",
"in",
"near",
"if",
"r",
"!=",
"room",
")",
":",
"# Todos os outros vizinhos estão seguros -> o poço deve estar nesta sala",
"room",
".",
"pit",
"=",
"Status",
".",
"Present",
"else",
":",
"room",
".",
"pit",
"=",
"Status",
".",
"LikelyPresent",
"# Analisa a percepção do ouro",
"kb",
"[",
"loc",
"]",
".",
"gold",
"=",
"gold"
] | [
48,
0
] | [
100,
21
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
AtorTestes.teste_ator_posicao | (self) | Teste que verifica que o ator comum não deve se mover independente do tempo do jogo | Teste que verifica que o ator comum não deve se mover independente do tempo do jogo | def teste_ator_posicao(self):
'Teste que verifica que o ator comum não deve se mover independente do tempo do jogo'
ator = Ator()
x, y = ator.calcular_posicao(0)
self.assertEqual(0, x)
self.assertEqual(0, y)
ator = Ator(0.3, 0.5)
x, y = ator.calcular_posicao(10)
self.assertEqual(0.3, x)
self.assertEqual(0.5, y) | [
"def",
"teste_ator_posicao",
"(",
"self",
")",
":",
"ator",
"=",
"Ator",
"(",
")",
"x",
",",
"y",
"=",
"ator",
".",
"calcular_posicao",
"(",
"0",
")",
"self",
".",
"assertEqual",
"(",
"0",
",",
"x",
")",
"self",
".",
"assertEqual",
"(",
"0",
",",
"y",
")",
"ator",
"=",
"Ator",
"(",
"0.3",
",",
"0.5",
")",
"x",
",",
"y",
"=",
"ator",
".",
"calcular_posicao",
"(",
"10",
")",
"self",
".",
"assertEqual",
"(",
"0.3",
",",
"x",
")",
"self",
".",
"assertEqual",
"(",
"0.5",
",",
"y",
")"
] | [
32,
4
] | [
42,
32
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
contarecuo | (p, r = 0, valores = recuo) | return r | Retorna o recuo da linha p somada à tabulação inicial r conforme o dicionário dos valores dos caracteres,
se p já não tiver recuo calculado. | Retorna o recuo da linha p somada à tabulação inicial r conforme o dicionário dos valores dos caracteres,
se p já não tiver recuo calculado. | def contarecuo (p, r = 0, valores = recuo):
'''Retorna o recuo da linha p somada à tabulação inicial r conforme o dicionário dos valores dos caracteres,
se p já não tiver recuo calculado.'''
try:
if type(p) != str:
return p.recuo
for c in p:
r += valores[c]
except AttributeError:
if p != None:
return contarecuo(p[0],r,valores)
except KeyError:
pass
return r | [
"def",
"contarecuo",
"(",
"p",
",",
"r",
"=",
"0",
",",
"valores",
"=",
"recuo",
")",
":",
"try",
":",
"if",
"type",
"(",
"p",
")",
"!=",
"str",
":",
"return",
"p",
".",
"recuo",
"for",
"c",
"in",
"p",
":",
"r",
"+=",
"valores",
"[",
"c",
"]",
"except",
"AttributeError",
":",
"if",
"p",
"!=",
"None",
":",
"return",
"contarecuo",
"(",
"p",
"[",
"0",
"]",
",",
"r",
",",
"valores",
")",
"except",
"KeyError",
":",
"pass",
"return",
"r"
] | [
31,
0
] | [
46,
9
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Bullet.__init__ | (self,ai_settings,screen,ship) | Cria um objeto para o projétil na posição atual da espaçonave | Cria um objeto para o projétil na posição atual da espaçonave | def __init__(self,ai_settings,screen,ship):
"""Cria um objeto para o projétil na posição atual da espaçonave"""
super(Bullet,self).__init__()
self.screen = screen
#Cria um retagulo para o projétil em (0,0) e em seguida define
#posição correta
self.rect = pygame.Rect(0,0,ai_settings.bullet_width,ai_settings.bullet_height)
self.rect.centerx = ship.rect.centerx
self.rect.top = ship.rect.top
#Armazena a posição do projetil como um valor decimal
self.y = float(self.rect.y)
self.color = ai_settings.bullet_color
self.speed_factor = ai_settings.bullet_speed_factor | [
"def",
"__init__",
"(",
"self",
",",
"ai_settings",
",",
"screen",
",",
"ship",
")",
":",
"super",
"(",
"Bullet",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"screen",
"=",
"screen",
"#Cria um retagulo para o projétil em (0,0) e em seguida define",
"#posição correta",
"self",
".",
"rect",
"=",
"pygame",
".",
"Rect",
"(",
"0",
",",
"0",
",",
"ai_settings",
".",
"bullet_width",
",",
"ai_settings",
".",
"bullet_height",
")",
"self",
".",
"rect",
".",
"centerx",
"=",
"ship",
".",
"rect",
".",
"centerx",
"self",
".",
"rect",
".",
"top",
"=",
"ship",
".",
"rect",
".",
"top",
"#Armazena a posição do projetil como um valor decimal",
"self",
".",
"y",
"=",
"float",
"(",
"self",
".",
"rect",
".",
"y",
")",
"self",
".",
"color",
"=",
"ai_settings",
".",
"bullet_color",
"self",
".",
"speed_factor",
"=",
"ai_settings",
".",
"bullet_speed_factor"
] | [
5,
4
] | [
20,
59
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
LinkedList._getnode | (self, index) | return pointer | Retorna o i-esimo nó indicado pelo index | Retorna o i-esimo nó indicado pelo index | def _getnode(self, index):
""" Retorna o i-esimo nó indicado pelo index """
pointer = self.head
for i in range(index):
if pointer is not None:
pointer = pointer.next
else:
raise IndexError('list index out of range')
return pointer | [
"def",
"_getnode",
"(",
"self",
",",
"index",
")",
":",
"pointer",
"=",
"self",
".",
"head",
"for",
"i",
"in",
"range",
"(",
"index",
")",
":",
"if",
"pointer",
"is",
"not",
"None",
":",
"pointer",
"=",
"pointer",
".",
"next",
"else",
":",
"raise",
"IndexError",
"(",
"'list index out of range'",
")",
"return",
"pointer"
] | [
100,
4
] | [
111,
22
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
update_menu | (screen, background_menu, play_button) | Apresenta o menu na tela com o botão de play | Apresenta o menu na tela com o botão de play | def update_menu(screen, background_menu, play_button):
"""Apresenta o menu na tela com o botão de play"""
# Tempo de transição de tela
sleep(3)
screen.blit(background_menu, (0, 0))
play_button.draw_button()
# Atualiza a tela
pygame.display.flip() | [
"def",
"update_menu",
"(",
"screen",
",",
"background_menu",
",",
"play_button",
")",
":",
"# Tempo de transição de tela",
"sleep",
"(",
"3",
")",
"screen",
".",
"blit",
"(",
"background_menu",
",",
"(",
"0",
",",
"0",
")",
")",
"play_button",
".",
"draw_button",
"(",
")",
"# Atualiza a tela",
"pygame",
".",
"display",
".",
"flip",
"(",
")"
] | [
113,
0
] | [
120,
25
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
TestQuery.test_query_expand_complex_type | (self) | Teste de expansão com expansão interna, select interno e select externo | Teste de expansão com expansão interna, select interno e select externo | def test_query_expand_complex_type(self):
"""Teste de expansão com expansão interna, select interno e select externo"""
expected = self.tickets.api.base_url + "&$expand=customFieldValues"
result = self.tickets.query.expand(
self.properties["customFieldValues"],
).as_url()
self.assertEqual(result, expected) | [
"def",
"test_query_expand_complex_type",
"(",
"self",
")",
":",
"expected",
"=",
"self",
".",
"tickets",
".",
"api",
".",
"base_url",
"+",
"\"&$expand=customFieldValues\"",
"result",
"=",
"self",
".",
"tickets",
".",
"query",
".",
"expand",
"(",
"self",
".",
"properties",
"[",
"\"customFieldValues\"",
"]",
",",
")",
".",
"as_url",
"(",
")",
"self",
".",
"assertEqual",
"(",
"result",
",",
"expected",
")"
] | [
176,
4
] | [
182,
42
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
dashboard | (request) | Abre o dashboard do usuário logado | Abre o dashboard do usuário logado | def dashboard(request):
"""Abre o dashboard do usuário logado"""
if request.user.is_authenticated:
id = request.user.id
# mostrando apenas as receitas do autor(user) filtradas pelo id
receitas = Receita.objects.order_by('-data_receita').filter(autor=id)
# passando as informações(dados) para o template
dados = {'receitas': receitas}
return render(request, 'usuarios/dashboard.html', dados)
else:
return redirect('index') | [
"def",
"dashboard",
"(",
"request",
")",
":",
"if",
"request",
".",
"user",
".",
"is_authenticated",
":",
"id",
"=",
"request",
".",
"user",
".",
"id",
"# mostrando apenas as receitas do autor(user) filtradas pelo id",
"receitas",
"=",
"Receita",
".",
"objects",
".",
"order_by",
"(",
"'-data_receita'",
")",
".",
"filter",
"(",
"autor",
"=",
"id",
")",
"# passando as informações(dados) para o template",
"dados",
"=",
"{",
"'receitas'",
":",
"receitas",
"}",
"return",
"render",
"(",
"request",
",",
"'usuarios/dashboard.html'",
",",
"dados",
")",
"else",
":",
"return",
"redirect",
"(",
"'index'",
")"
] | [
63,
0
] | [
73,
32
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
DriverInterface.sendCommand | (self, commandNumber, parameters, skipStatusErrors) | Envia comando a impresora | Envia comando a impresora | def sendCommand(self, commandNumber, parameters, skipStatusErrors):
"""Envia comando a impresora"""
raise NotImplementedError | [
"def",
"sendCommand",
"(",
"self",
",",
"commandNumber",
",",
"parameters",
",",
"skipStatusErrors",
")",
":",
"raise",
"NotImplementedError"
] | [
12,
4
] | [
14,
33
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Conta.__div__ | (self, outro) | Habilita obj/obj. Divisão de saldo | Habilita obj/obj. Divisão de saldo | def __div__(self, outro):
"""Habilita obj/obj. Divisão de saldo"""
self.saldo /= outro.saldo | [
"def",
"__div__",
"(",
"self",
",",
"outro",
")",
":",
"self",
".",
"saldo",
"/=",
"outro",
".",
"saldo"
] | [
23,
4
] | [
25,
33
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
CPF._check_repeated_digits | (self, doc: List[str]) | return len(set(doc)) == 1 | Verifica se é um CPF com números repetidos.
Exemplo: 111.111.111-11 | Verifica se é um CPF com números repetidos.
Exemplo: 111.111.111-11 | def _check_repeated_digits(self, doc: List[str]) -> bool:
"""Verifica se é um CPF com números repetidos.
Exemplo: 111.111.111-11"""
return len(set(doc)) == 1 | [
"def",
"_check_repeated_digits",
"(",
"self",
",",
"doc",
":",
"List",
"[",
"str",
"]",
")",
"->",
"bool",
":",
"return",
"len",
"(",
"set",
"(",
"doc",
")",
")",
"==",
"1"
] | [
73,
4
] | [
76,
33
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Agent.__init__ | (self) | Inicializa o agente com parâmetros default. | Inicializa o agente com parâmetros default. | def __init__(self):
"""Inicializa o agente com parâmetros default."""
self.location = (0, 0)
self.direction = 1
self.has_gold = False
self.has_arrow = True | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"location",
"=",
"(",
"0",
",",
"0",
")",
"self",
".",
"direction",
"=",
"1",
"self",
".",
"has_gold",
"=",
"False",
"self",
".",
"has_arrow",
"=",
"True"
] | [
101,
2
] | [
108,
25
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Bau.brinquedosort | (self) | return brinquedos | Retorna uma lista de brinquedos ordenados por felicidade. | Retorna uma lista de brinquedos ordenados por felicidade. | def brinquedosort(self):
"""Retorna uma lista de brinquedos ordenados por felicidade."""
brinquedos = [valor[0] for valor in self.brinquedos.values()]
for brinquedo in range(len(brinquedos) - 1, 0, -1):
for i in range(brinquedo):
if brinquedos[i].lt(brinquedos[i + 1]):
brinquedos[i], brinquedos[i + 1] = brinquedos[i + 1], brinquedos[i]
return brinquedos | [
"def",
"brinquedosort",
"(",
"self",
")",
":",
"brinquedos",
"=",
"[",
"valor",
"[",
"0",
"]",
"for",
"valor",
"in",
"self",
".",
"brinquedos",
".",
"values",
"(",
")",
"]",
"for",
"brinquedo",
"in",
"range",
"(",
"len",
"(",
"brinquedos",
")",
"-",
"1",
",",
"0",
",",
"-",
"1",
")",
":",
"for",
"i",
"in",
"range",
"(",
"brinquedo",
")",
":",
"if",
"brinquedos",
"[",
"i",
"]",
".",
"lt",
"(",
"brinquedos",
"[",
"i",
"+",
"1",
"]",
")",
":",
"brinquedos",
"[",
"i",
"]",
",",
"brinquedos",
"[",
"i",
"+",
"1",
"]",
"=",
"brinquedos",
"[",
"i",
"+",
"1",
"]",
",",
"brinquedos",
"[",
"i",
"]",
"return",
"brinquedos"
] | [
47,
4
] | [
57,
25
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Sorvete.__str__ | (self) | return exibicao | Deve ser retornado todos os sabores e o valor de venda. | Deve ser retornado todos os sabores e o valor de venda. | def __str__(self):
"""Deve ser retornado todos os sabores e o valor de venda."""
sabores = ''.join(str(sabor) for sabor in self.sabores.all())
exibicao = f'{sabores} {str(self.preco_de_venda).replace(".", ",")}'
return exibicao | [
"def",
"__str__",
"(",
"self",
")",
":",
"sabores",
"=",
"''",
".",
"join",
"(",
"str",
"(",
"sabor",
")",
"for",
"sabor",
"in",
"self",
".",
"sabores",
".",
"all",
"(",
")",
")",
"exibicao",
"=",
"f'{sabores} {str(self.preco_de_venda).replace(\".\", \",\")}'",
"return",
"exibicao"
] | [
29,
4
] | [
34,
23
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
check_aliens_bottom | (ai_settings, screen, stats, sb, ship, aliens, bullets) | Verifica se algum alienígena alcançou a parte inferior da tela | Verifica se algum alienígena alcançou a parte inferior da tela | def check_aliens_bottom(ai_settings, screen, stats, sb, ship, aliens, bullets):
"""Verifica se algum alienígena alcançou a parte inferior da tela"""
screen_rect = screen.get_rect()
for alien in aliens.sprites():
if alien.rect.bottom >= screen_rect.bottom:
# Trata esse caso do mesmo modo que é feito quando a espaçonave é atingida
ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets)
break | [
"def",
"check_aliens_bottom",
"(",
"ai_settings",
",",
"screen",
",",
"stats",
",",
"sb",
",",
"ship",
",",
"aliens",
",",
"bullets",
")",
":",
"screen_rect",
"=",
"screen",
".",
"get_rect",
"(",
")",
"for",
"alien",
"in",
"aliens",
".",
"sprites",
"(",
")",
":",
"if",
"alien",
".",
"rect",
".",
"bottom",
">=",
"screen_rect",
".",
"bottom",
":",
"# Trata esse caso do mesmo modo que é feito quando a espaçonave é atingida",
"ship_hit",
"(",
"ai_settings",
",",
"screen",
",",
"stats",
",",
"sb",
",",
"ship",
",",
"aliens",
",",
"bullets",
")",
"break"
] | [
294,
0
] | [
301,
17
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
TestCertidao.test_special_case | (self) | Verifica os casos especiais de Certidão | Verifica os casos especiais de Certidão | def test_special_case(self):
""" Verifica os casos especiais de Certidão """
cases = [
('3467875434578764345789654', False),
('AAAAAAAAAAA', False),
('', False),
('27610201552018226521370659786633', True),
('27610201552018226521370659786630', False),
]
for certidao, is_valid in cases:
self.assertEqual(self.certidao.validate(certidao), is_valid) | [
"def",
"test_special_case",
"(",
"self",
")",
":",
"cases",
"=",
"[",
"(",
"'3467875434578764345789654'",
",",
"False",
")",
",",
"(",
"'AAAAAAAAAAA'",
",",
"False",
")",
",",
"(",
"''",
",",
"False",
")",
",",
"(",
"'27610201552018226521370659786633'",
",",
"True",
")",
",",
"(",
"'27610201552018226521370659786630'",
",",
"False",
")",
",",
"]",
"for",
"certidao",
",",
"is_valid",
"in",
"cases",
":",
"self",
".",
"assertEqual",
"(",
"self",
".",
"certidao",
".",
"validate",
"(",
"certidao",
")",
",",
"is_valid",
")"
] | [
31,
4
] | [
41,
72
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
ajustaDadosSolar | () | ajusta dados solar | ajusta dados solar | def ajustaDadosSolar():
''' ajusta dados solar '''
global gDadosSolar
realPower = dl.float2number(gDadosSolar['real_power'],0)
capacidade = dl.float2number(gDadosSolar['capacitor'])
plant_tree = dl.float2number(gDadosSolar['plant_tree'], 0)
month_eq = dl.float2number(gDadosSolar['month_eq']) / 1000
month_eq = round(month_eq, 2)
total_eq = dl.float2number(gDadosSolar['total_eq']) / 1000000
total_eq = round(total_eq, 2)
co2 = dl.float2number(gDadosSolar['co2_emission_reduction']) / 1000000
co2 = round(co2,2)
# corrige escala e digitos
if capacidade > 0 and capacidade < 100:
capacidade = capacidade * 1000
capacidade = round(capacidade)
power = (realPower / capacidade) * 100
power = round(power,1)
if realPower == 0:
printC (Color.F_Magenta, "realPower = 0")
printC (Color.B_LightMagenta, dl.hoje() )
if DEVELOPERS_MODE:
#printC ('parada 1/0', str(1/0))
printC(Color.B_Red,'parada')
gDadosSolar['real_power'] = str( realPower )
gDadosSolar['power_ratio'] = str( power )
gDadosSolar['capacitor'] = str( capacidade )
gDadosSolar['co2_emission_reduction'] = str( co2 )
gDadosSolar['plant_tree'] = str( plant_tree )
gDadosSolar['total_eq'] = str( total_eq )
gDadosSolar['month_eq'] = str( month_eq ) | [
"def",
"ajustaDadosSolar",
"(",
")",
":",
"global",
"gDadosSolar",
"realPower",
"=",
"dl",
".",
"float2number",
"(",
"gDadosSolar",
"[",
"'real_power'",
"]",
",",
"0",
")",
"capacidade",
"=",
"dl",
".",
"float2number",
"(",
"gDadosSolar",
"[",
"'capacitor'",
"]",
")",
"plant_tree",
"=",
"dl",
".",
"float2number",
"(",
"gDadosSolar",
"[",
"'plant_tree'",
"]",
",",
"0",
")",
"month_eq",
"=",
"dl",
".",
"float2number",
"(",
"gDadosSolar",
"[",
"'month_eq'",
"]",
")",
"/",
"1000",
"month_eq",
"=",
"round",
"(",
"month_eq",
",",
"2",
")",
"total_eq",
"=",
"dl",
".",
"float2number",
"(",
"gDadosSolar",
"[",
"'total_eq'",
"]",
")",
"/",
"1000000",
"total_eq",
"=",
"round",
"(",
"total_eq",
",",
"2",
")",
"co2",
"=",
"dl",
".",
"float2number",
"(",
"gDadosSolar",
"[",
"'co2_emission_reduction'",
"]",
")",
"/",
"1000000",
"co2",
"=",
"round",
"(",
"co2",
",",
"2",
")",
"# corrige escala e digitos",
"if",
"capacidade",
">",
"0",
"and",
"capacidade",
"<",
"100",
":",
"capacidade",
"=",
"capacidade",
"*",
"1000",
"capacidade",
"=",
"round",
"(",
"capacidade",
")",
"power",
"=",
"(",
"realPower",
"/",
"capacidade",
")",
"*",
"100",
"power",
"=",
"round",
"(",
"power",
",",
"1",
")",
"if",
"realPower",
"==",
"0",
":",
"printC",
"(",
"Color",
".",
"F_Magenta",
",",
"\"realPower = 0\"",
")",
"printC",
"(",
"Color",
".",
"B_LightMagenta",
",",
"dl",
".",
"hoje",
"(",
")",
")",
"if",
"DEVELOPERS_MODE",
":",
"#printC ('parada 1/0', str(1/0))",
"printC",
"(",
"Color",
".",
"B_Red",
",",
"'parada'",
")",
"gDadosSolar",
"[",
"'real_power'",
"]",
"=",
"str",
"(",
"realPower",
")",
"gDadosSolar",
"[",
"'power_ratio'",
"]",
"=",
"str",
"(",
"power",
")",
"gDadosSolar",
"[",
"'capacitor'",
"]",
"=",
"str",
"(",
"capacidade",
")",
"gDadosSolar",
"[",
"'co2_emission_reduction'",
"]",
"=",
"str",
"(",
"co2",
")",
"gDadosSolar",
"[",
"'plant_tree'",
"]",
"=",
"str",
"(",
"plant_tree",
")",
"gDadosSolar",
"[",
"'total_eq'",
"]",
"=",
"str",
"(",
"total_eq",
")",
"gDadosSolar",
"[",
"'month_eq'",
"]",
"=",
"str",
"(",
"month_eq",
")"
] | [
508,
0
] | [
538,
45
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
largest_number | (input_list) | return best_so_far | Encontrar maior número da lista fornecida pelo usuário
Args:
input_list (list): Lista de números (floats, ints) fornecida pelo usuário.
Returns:
int, float: Maior número presente na lista.
| Encontrar maior número da lista fornecida pelo usuário | def largest_number(input_list):
"""Encontrar maior número da lista fornecida pelo usuário
Args:
input_list (list): Lista de números (floats, ints) fornecida pelo usuário.
Returns:
int, float: Maior número presente na lista.
"""
if len(input_list) in (0, 1):
return None
best_so_far = input_list[0]
for value in input_list:
if value > best_so_far:
best_so_far = value
return best_so_far | [
"def",
"largest_number",
"(",
"input_list",
")",
":",
"if",
"len",
"(",
"input_list",
")",
"in",
"(",
"0",
",",
"1",
")",
":",
"return",
"None",
"best_so_far",
"=",
"input_list",
"[",
"0",
"]",
"for",
"value",
"in",
"input_list",
":",
"if",
"value",
">",
"best_so_far",
":",
"best_so_far",
"=",
"value",
"return",
"best_so_far"
] | [
6,
0
] | [
23,
22
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
bubble_sort | (values) | Ordena uma lista, em ordem crescente, usando o Bubble Sort.
O Bubble Sort é, dentre os algoritmos de ordenação tradicionais, o
mais simples e o menos eficiente. Ele compara cada elemento ao seu
vizinho, trocando suas posições sempre que o elemento à direita for
menor que o elemento à esquerda. Desse modo, a cada iteração do
loop externo, o N-ésimo maior elemento será movido para a posição
correta.
Parameters
----------
values : list
A lista que deve ser ordenada
| Ordena uma lista, em ordem crescente, usando o Bubble Sort. | def bubble_sort(values):
""" Ordena uma lista, em ordem crescente, usando o Bubble Sort.
O Bubble Sort é, dentre os algoritmos de ordenação tradicionais, o
mais simples e o menos eficiente. Ele compara cada elemento ao seu
vizinho, trocando suas posições sempre que o elemento à direita for
menor que o elemento à esquerda. Desse modo, a cada iteração do
loop externo, o N-ésimo maior elemento será movido para a posição
correta.
Parameters
----------
values : list
A lista que deve ser ordenada
"""
for i in range(len(values)):
for j in range(len(values) -1):
if (values[j] > values[j + 1]):
values[j], values[j + 1] = values[j + 1], values[j] | [
"def",
"bubble_sort",
"(",
"values",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"values",
")",
")",
":",
"for",
"j",
"in",
"range",
"(",
"len",
"(",
"values",
")",
"-",
"1",
")",
":",
"if",
"(",
"values",
"[",
"j",
"]",
">",
"values",
"[",
"j",
"+",
"1",
"]",
")",
":",
"values",
"[",
"j",
"]",
",",
"values",
"[",
"j",
"+",
"1",
"]",
"=",
"values",
"[",
"j",
"+",
"1",
"]",
",",
"values",
"[",
"j",
"]"
] | [
10,
0
] | [
28,
67
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
all_events | (variables, bn, e) | Rendimento cada maneira de estender e com valores para todas as variáveis. | Rendimento cada maneira de estender e com valores para todas as variáveis. | def all_events(variables, bn, e):
"Rendimento cada maneira de estender e com valores para todas as variáveis."
if not variables:
yield e
else:
X, rest = variables[0], variables[1:]
for e1 in all_events(rest, bn, e):
for x in bn.variable_values(X):
yield extend(e1, X, x) | [
"def",
"all_events",
"(",
"variables",
",",
"bn",
",",
"e",
")",
":",
"if",
"not",
"variables",
":",
"yield",
"e",
"else",
":",
"X",
",",
"rest",
"=",
"variables",
"[",
"0",
"]",
",",
"variables",
"[",
"1",
":",
"]",
"for",
"e1",
"in",
"all_events",
"(",
"rest",
",",
"bn",
",",
"e",
")",
":",
"for",
"x",
"in",
"bn",
".",
"variable_values",
"(",
"X",
")",
":",
"yield",
"extend",
"(",
"e1",
",",
"X",
",",
"x",
")"
] | [
390,
0
] | [
398,
38
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
DoublyLinkedList.remove | (self, element) | Remove um elemento da lista (se ele existir) | Remove um elemento da lista (se ele existir) | def remove(self, element):
""" Remove um elemento da lista (se ele existir) """
# verifica se o rabo da lista é o elemento (remoção em O(1))
if self.tail.data == element:
# colocando o elemento anterior ao rabo como rabo da lista.
self.tail = self.tail.previous
self.tail.next = None
self._size -= 1
return None
# verifica se a cabeça da lista é o elemento (remoção em O(1))
elif self.head.data == element:
# colocando o segundo elemento como a cabeça da lista.
self.head = self.head.next
self.head.previous = None
self._size -= 1
return None
else:
pointer = self.head.next # começa a partir do segundo elemento
while pointer is not None:
if pointer.data == element:
# Ligando o nó anterior ao elemento com o nó posterior ao elemento
pointer.previous.next = pointer.next
pointer.next.previous = pointer.previous
pointer = None
self._size -= 1
return pointer # retornando None
pointer = pointer.next
# caso o elemento não esteja na lista
raise ValueError(f'{element} is not in list') | [
"def",
"remove",
"(",
"self",
",",
"element",
")",
":",
"# verifica se o rabo da lista é o elemento (remoção em O(1))\r",
"if",
"self",
".",
"tail",
".",
"data",
"==",
"element",
":",
"# colocando o elemento anterior ao rabo como rabo da lista.\r",
"self",
".",
"tail",
"=",
"self",
".",
"tail",
".",
"previous",
"self",
".",
"tail",
".",
"next",
"=",
"None",
"self",
".",
"_size",
"-=",
"1",
"return",
"None",
"# verifica se a cabeça da lista é o elemento (remoção em O(1))\r",
"elif",
"self",
".",
"head",
".",
"data",
"==",
"element",
":",
"# colocando o segundo elemento como a cabeça da lista.\r",
"self",
".",
"head",
"=",
"self",
".",
"head",
".",
"next",
"self",
".",
"head",
".",
"previous",
"=",
"None",
"self",
".",
"_size",
"-=",
"1",
"return",
"None",
"else",
":",
"pointer",
"=",
"self",
".",
"head",
".",
"next",
"# começa a partir do segundo elemento\r",
"while",
"pointer",
"is",
"not",
"None",
":",
"if",
"pointer",
".",
"data",
"==",
"element",
":",
"# Ligando o nó anterior ao elemento com o nó posterior ao elemento\r",
"pointer",
".",
"previous",
".",
"next",
"=",
"pointer",
".",
"next",
"pointer",
".",
"next",
".",
"previous",
"=",
"pointer",
".",
"previous",
"pointer",
"=",
"None",
"self",
".",
"_size",
"-=",
"1",
"return",
"pointer",
"# retornando None\r",
"pointer",
"=",
"pointer",
".",
"next",
"# caso o elemento não esteja na lista\r",
"raise",
"ValueError",
"(",
"f'{element} is not in list'",
")"
] | [
74,
4
] | [
111,
53
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
MainVendas.FormVendas | (self) | Chamanda de funções localizadas no arquivo comercial.py na pasta
Funcoes | Chamanda de funções localizadas no arquivo comercial.py na pasta
Funcoes | def FormVendas(self):
self.DesativaBotaoVendas()
self.LimpaFrame(self.ct_containerVendas)
super(MainVendas, self).setFormVendas(self.ct_containerVendas)
self.fr_FormVenda.show()
""" Chamanda de funções localizadas no arquivo comercial.py na pasta
Funcoes """
# Setando Datas
self.setDatas()
# Setando Validação
self.validaCampos()
# Definindo acao de calculo de frete e desconto
self.acaoCalculo()
# Setando Icones dos Botoes
self.setIcones()
# Setando tamanho das tabelas
self.tamanhoTabelas()
# Setando autocomplete
self.setAutocomplete()
# Botao Gerar Parcela
self.bt_GerarParcela.clicked.connect(
partial(self.gerarParcela, "Receber"))
# Autocomplete Produto
self.tx_BuscaItem.textEdited.connect(self.autocompleteProduto)
# Add Item Tabela
self.tx_ObsItem.returnPressed.connect(self.ValidaFormAdd)
self.bt_IncluirItem.clicked.connect(self.ValidaFormAdd)
""" Fim chamandas comercial.py """
""" Chamanda de funções localizadas no arquivo clientes.py na
pasta Funcoes """
# Campo Busca por nome e Autocompletar Cliente
self.tx_NomeFantasia.textEdited.connect(self.autocompleCliente)
self.tx_NomeFantasia.returnPressed.connect(
partial(self.BuscaClienteNome, self.tx_IdBuscaItem))
# Return Press Busca Id Cliente
self.tx_Id.returnPressed.connect(
partial(self.BuscaClienteId, self.tx_IdBuscaItem))
""" Fim Chamadas clientes.py"""
""" Chamanda de funções localizadas no arquivo FormaPagamento.py na pasta Funcoes """
# Populando combobox Forma de Pagamento
self.CboxFPagamento(self.cb_FormaPagamento)
""" Fim Chamanda FormaPagamento.py """
# Setando Foco no Cliente id TX
self.tx_Id.setFocus()
# Checando se existe ID válido
self.IdCheckPedido()
""" Definindo funcões widgets"""
# Adicionando numero parcelas
self.cboxParcelas(self.cb_QtdeParcela)
# Return Press Busca Id Produto
self.tx_IdBuscaItem.returnPressed.connect(self.BuscaProdutoId)
# Busca Produto por Nome
self.tx_BuscaItem.returnPressed.connect(self.BuscaProdutoNome)
# Calculo total produto por qtde item
self.tx_QntdItem.returnPressed.connect(self.TotalItem)
# Entregar
self.bt_Entregar.clicked.connect(self.Entregar)
# Botao Salvar
self.bt_Salvar.clicked.connect(self.CadVenda)
# Botao Cancelar
self.bt_Voltar.clicked.connect(self.janelaVendas)
# Botao Imprimir
self.bt_Imprimir.clicked.connect(self.imprimirVenda) | [
"def",
"FormVendas",
"(",
"self",
")",
":",
"self",
".",
"DesativaBotaoVendas",
"(",
")",
"self",
".",
"LimpaFrame",
"(",
"self",
".",
"ct_containerVendas",
")",
"super",
"(",
"MainVendas",
",",
"self",
")",
".",
"setFormVendas",
"(",
"self",
".",
"ct_containerVendas",
")",
"self",
".",
"fr_FormVenda",
".",
"show",
"(",
")",
"# Setando Datas",
"self",
".",
"setDatas",
"(",
")",
"# Setando Validação",
"self",
".",
"validaCampos",
"(",
")",
"# Definindo acao de calculo de frete e desconto",
"self",
".",
"acaoCalculo",
"(",
")",
"# Setando Icones dos Botoes",
"self",
".",
"setIcones",
"(",
")",
"# Setando tamanho das tabelas",
"self",
".",
"tamanhoTabelas",
"(",
")",
"# Setando autocomplete",
"self",
".",
"setAutocomplete",
"(",
")",
"# Botao Gerar Parcela",
"self",
".",
"bt_GerarParcela",
".",
"clicked",
".",
"connect",
"(",
"partial",
"(",
"self",
".",
"gerarParcela",
",",
"\"Receber\"",
")",
")",
"# Autocomplete Produto",
"self",
".",
"tx_BuscaItem",
".",
"textEdited",
".",
"connect",
"(",
"self",
".",
"autocompleteProduto",
")",
"# Add Item Tabela",
"self",
".",
"tx_ObsItem",
".",
"returnPressed",
".",
"connect",
"(",
"self",
".",
"ValidaFormAdd",
")",
"self",
".",
"bt_IncluirItem",
".",
"clicked",
".",
"connect",
"(",
"self",
".",
"ValidaFormAdd",
")",
"\"\"\" Fim chamandas comercial.py \"\"\"",
"\"\"\" Chamanda de funções localizadas no arquivo clientes.py na \n pasta Funcoes \"\"\"",
"# Campo Busca por nome e Autocompletar Cliente",
"self",
".",
"tx_NomeFantasia",
".",
"textEdited",
".",
"connect",
"(",
"self",
".",
"autocompleCliente",
")",
"self",
".",
"tx_NomeFantasia",
".",
"returnPressed",
".",
"connect",
"(",
"partial",
"(",
"self",
".",
"BuscaClienteNome",
",",
"self",
".",
"tx_IdBuscaItem",
")",
")",
"# Return Press Busca Id Cliente",
"self",
".",
"tx_Id",
".",
"returnPressed",
".",
"connect",
"(",
"partial",
"(",
"self",
".",
"BuscaClienteId",
",",
"self",
".",
"tx_IdBuscaItem",
")",
")",
"\"\"\" Fim Chamadas clientes.py\"\"\"",
"\"\"\" Chamanda de funções localizadas no arquivo FormaPagamento.py na pasta Funcoes \"\"\"",
"# Populando combobox Forma de Pagamento",
"self",
".",
"CboxFPagamento",
"(",
"self",
".",
"cb_FormaPagamento",
")",
"\"\"\" Fim Chamanda FormaPagamento.py \"\"\"",
"# Setando Foco no Cliente id TX",
"self",
".",
"tx_Id",
".",
"setFocus",
"(",
")",
"# Checando se existe ID válido",
"self",
".",
"IdCheckPedido",
"(",
")",
"\"\"\" Definindo funcões widgets\"\"\"",
"# Adicionando numero parcelas",
"self",
".",
"cboxParcelas",
"(",
"self",
".",
"cb_QtdeParcela",
")",
"# Return Press Busca Id Produto",
"self",
".",
"tx_IdBuscaItem",
".",
"returnPressed",
".",
"connect",
"(",
"self",
".",
"BuscaProdutoId",
")",
"# Busca Produto por Nome",
"self",
".",
"tx_BuscaItem",
".",
"returnPressed",
".",
"connect",
"(",
"self",
".",
"BuscaProdutoNome",
")",
"# Calculo total produto por qtde item",
"self",
".",
"tx_QntdItem",
".",
"returnPressed",
".",
"connect",
"(",
"self",
".",
"TotalItem",
")",
"# Entregar",
"self",
".",
"bt_Entregar",
".",
"clicked",
".",
"connect",
"(",
"self",
".",
"Entregar",
")",
"# Botao Salvar",
"self",
".",
"bt_Salvar",
".",
"clicked",
".",
"connect",
"(",
"self",
".",
"CadVenda",
")",
"# Botao Cancelar",
"self",
".",
"bt_Voltar",
".",
"clicked",
".",
"connect",
"(",
"self",
".",
"janelaVendas",
")",
"# Botao Imprimir",
"self",
".",
"bt_Imprimir",
".",
"clicked",
".",
"connect",
"(",
"self",
".",
"imprimirVenda",
")"
] | [
131,
4
] | [
216,
60
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
cloud_lda | (lista_tweets, n_repeticoes=1000) | Gera a nuvem de tags a partir de uma lista de tuplas LDA. | Gera a nuvem de tags a partir de uma lista de tuplas LDA. | def cloud_lda(lista_tweets, n_repeticoes=1000):
"""Gera a nuvem de tags a partir de uma lista de tuplas LDA."""
print("REP", n_repeticoes)
texto = _unpack(lista_tweets, n_repeticoes)
# texto="casarao_casa casa_casinha"
make_cloud(texto, "lda")
print("Cloud Lda Gerada.!!") | [
"def",
"cloud_lda",
"(",
"lista_tweets",
",",
"n_repeticoes",
"=",
"1000",
")",
":",
"print",
"(",
"\"REP\"",
",",
"n_repeticoes",
")",
"texto",
"=",
"_unpack",
"(",
"lista_tweets",
",",
"n_repeticoes",
")",
"# texto=\"casarao_casa casa_casinha\"",
"make_cloud",
"(",
"texto",
",",
"\"lda\"",
")",
"print",
"(",
"\"Cloud Lda Gerada.!!\"",
")"
] | [
71,
0
] | [
77,
32
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
GnomeSort.__validateParams | (self,array,leftIndex,rightIndex) | Verificação da validade dos parametros de limite passados
Este método busca evitar entradas inválidas para o algoritmo de ordenação, tais como: índices negativos,
índice direito menor que o esquerdo, índice direito superior ao tamanho do array.
Parametros:
array: Lista a ser ordenada
leftIndex(Opcional): Índice limítrofe a esquerda do array para ordenação parcial
rightIndex(Opcional): Índice limítrofe a direita do array para ordenação parcial
Retorna:
Boolean: Indicando se os parâmetros são ou não válidos
| Verificação da validade dos parametros de limite passados
Este método busca evitar entradas inválidas para o algoritmo de ordenação, tais como: índices negativos,
índice direito menor que o esquerdo, índice direito superior ao tamanho do array. | def __validateParams(self,array,leftIndex,rightIndex):
"""Verificação da validade dos parametros de limite passados
Este método busca evitar entradas inválidas para o algoritmo de ordenação, tais como: índices negativos,
índice direito menor que o esquerdo, índice direito superior ao tamanho do array.
Parametros:
array: Lista a ser ordenada
leftIndex(Opcional): Índice limítrofe a esquerda do array para ordenação parcial
rightIndex(Opcional): Índice limítrofe a direita do array para ordenação parcial
Retorna:
Boolean: Indicando se os parâmetros são ou não válidos
"""
if(array == None or leftIndex < 0 or rightIndex > len(array) - 1 or leftIndex > rightIndex):
return False
else:
return True | [
"def",
"__validateParams",
"(",
"self",
",",
"array",
",",
"leftIndex",
",",
"rightIndex",
")",
":",
"if",
"(",
"array",
"==",
"None",
"or",
"leftIndex",
"<",
"0",
"or",
"rightIndex",
">",
"len",
"(",
"array",
")",
"-",
"1",
"or",
"leftIndex",
">",
"rightIndex",
")",
":",
"return",
"False",
"else",
":",
"return",
"True"
] | [
77,
1
] | [
94,
14
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
UndirectedWeightedGraph.degree | (self, v) | return len(self.get(v).keys()) | Retorna o grau de conexões de um vértice | Retorna o grau de conexões de um vértice | def degree(self, v):
''' Retorna o grau de conexões de um vértice '''
return len(self.get(v).keys()) | [
"def",
"degree",
"(",
"self",
",",
"v",
")",
":",
"return",
"len",
"(",
"self",
".",
"get",
"(",
"v",
")",
".",
"keys",
"(",
")",
")"
] | [
214,
4
] | [
216,
38
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Restaurant.describe_restaurant | (self) | Exibe a descrição do restaurante. | Exibe a descrição do restaurante. | def describe_restaurant(self):
"""Exibe a descrição do restaurante."""
print("O restaurante " + self.name.title() + " é especialista na culinária " + self.cuisine.title() + ".") | [
"def",
"describe_restaurant",
"(",
"self",
")",
":",
"print",
"(",
"\"O restaurante \"",
"+",
"self",
".",
"name",
".",
"title",
"(",
")",
"+",
"\" é especialista na culinária \" +",
"s",
"lf.c",
"u",
"isine.t",
"i",
"tle()",
" ",
"+",
"\"",
"\")",
""
] | [
17,
4
] | [
19,
116
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
p_atribuicao | (p) | atribuicao : var ATRIBUICAO expressao | atribuicao : var ATRIBUICAO expressao | def p_atribuicao(p):
"""atribuicao : var ATRIBUICAO expressao"""
pai = MyNode(name='atribuicao', type='ATRIBUICAO')
p[0] = pai
p[1].parent = pai
filho2 = MyNode(name='ATRIBUICAO', type='ATRIBUICAO', parent=pai)
filho_sym2 = MyNode(name=':=', type='SIMBOLO', parent=filho2)
p[2] = filho2
p[3].parent = pai | [
"def",
"p_atribuicao",
"(",
"p",
")",
":",
"pai",
"=",
"MyNode",
"(",
"name",
"=",
"'atribuicao'",
",",
"type",
"=",
"'ATRIBUICAO'",
")",
"p",
"[",
"0",
"]",
"=",
"pai",
"p",
"[",
"1",
"]",
".",
"parent",
"=",
"pai",
"filho2",
"=",
"MyNode",
"(",
"name",
"=",
"'ATRIBUICAO'",
",",
"type",
"=",
"'ATRIBUICAO'",
",",
"parent",
"=",
"pai",
")",
"filho_sym2",
"=",
"MyNode",
"(",
"name",
"=",
"':='",
",",
"type",
"=",
"'SIMBOLO'",
",",
"parent",
"=",
"filho2",
")",
"p",
"[",
"2",
"]",
"=",
"filho2",
"p",
"[",
"3",
"]",
".",
"parent",
"=",
"pai"
] | [
432,
0
] | [
444,
19
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
validate_docs | (documents: List[Tuple[BaseDoc, str]] = list) | return validations | Recebe uma lista de tuplas (classe, valor) e a valida | Recebe uma lista de tuplas (classe, valor) e a valida | def validate_docs(documents: List[Tuple[BaseDoc, str]] = list):
"""Recebe uma lista de tuplas (classe, valor) e a valida"""
validations = []
for doc in documents:
if not inspect.isclass(doc[0]) or not issubclass(doc[0], BaseDoc):
raise TypeError(
"O primeiro índice da tupla deve ser uma classe de documento!"
)
validations.append(doc[0]().validate(doc[1]))
return validations | [
"def",
"validate_docs",
"(",
"documents",
":",
"List",
"[",
"Tuple",
"[",
"BaseDoc",
",",
"str",
"]",
"]",
"=",
"list",
")",
":",
"validations",
"=",
"[",
"]",
"for",
"doc",
"in",
"documents",
":",
"if",
"not",
"inspect",
".",
"isclass",
"(",
"doc",
"[",
"0",
"]",
")",
"or",
"not",
"issubclass",
"(",
"doc",
"[",
"0",
"]",
",",
"BaseDoc",
")",
":",
"raise",
"TypeError",
"(",
"\"O primeiro índice da tupla deve ser uma classe de documento!\"",
")",
"validations",
".",
"append",
"(",
"doc",
"[",
"0",
"]",
"(",
")",
".",
"validate",
"(",
"doc",
"[",
"1",
"]",
")",
")",
"return",
"validations"
] | [
5,
0
] | [
17,
22
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
PropDefiniteKB.tell | (self, sentence) | Adicione uma cláusula definitiva a esta KB. | Adicione uma cláusula definitiva a esta KB. | def tell(self, sentence):
"Adicione uma cláusula definitiva a esta KB."
assert is_definite_clause(sentence), "Deve ser cláusula definitiva"
self.clauses.append(sentence) | [
"def",
"tell",
"(",
"self",
",",
"sentence",
")",
":",
"assert",
"is_definite_clause",
"(",
"sentence",
")",
",",
"\"Deve ser cláusula definitiva\"",
"self",
".",
"clauses",
".",
"append",
"(",
"sentence",
")"
] | [
440,
4
] | [
443,
37
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Certidao.generate | (self, mask: bool = False) | return self.mask(certidao) if mask else certidao | Método para gerar a Certidão de Nascimento/Casamento/Óbito. | Método para gerar a Certidão de Nascimento/Casamento/Óbito. | def generate(self, mask: bool = False) -> str:
"""Método para gerar a Certidão de Nascimento/Casamento/Óbito."""
# Os trinta primeiros dígitos
certidao = [str(sample(self.digits, 1)[0]) for i in range(30)]
# Gerar os dígitos verificadores
certidao.append(self._generate_verifying_digit(certidao))
certidao = "".join(certidao)
return self.mask(certidao) if mask else certidao | [
"def",
"generate",
"(",
"self",
",",
"mask",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"# Os trinta primeiros dígitos",
"certidao",
"=",
"[",
"str",
"(",
"sample",
"(",
"self",
".",
"digits",
",",
"1",
")",
"[",
"0",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"30",
")",
"]",
"# Gerar os dígitos verificadores",
"certidao",
".",
"append",
"(",
"self",
".",
"_generate_verifying_digit",
"(",
"certidao",
")",
")",
"certidao",
"=",
"\"\"",
".",
"join",
"(",
"certidao",
")",
"return",
"self",
".",
"mask",
"(",
"certidao",
")",
"if",
"mask",
"else",
"certidao"
] | [
42,
4
] | [
52,
56
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Room.is_unexplored | (self) | return not self.is_explored | Retorna True é a sala não foi explorada. | Retorna True é a sala não foi explorada. | def is_unexplored(self):
"""Retorna True é a sala não foi explorada."""
return not self.is_explored | [
"def",
"is_unexplored",
"(",
"self",
")",
":",
"return",
"not",
"self",
".",
"is_explored"
] | [
89,
2
] | [
93,
31
] | null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.