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
list | start_point
list | end_point
list | 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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
AttendanceListSpider.get_status | (status) | return status_labels.get(status.upper().strip()) | Retorna label dos status. Consultado em 20/03/2020. | Retorna label dos status. Consultado em 20/03/2020. | def get_status(status):
""""Retorna label dos status. Consultado em 20/03/2020."""
status_labels = {
"P": "presente",
"FJ": "falta_justificada",
"LJ": "licenca_justificada",
"A": "ausente",
}
return status_labels.get(status.upper().strip()) | [
"def",
"get_status",
"(",
"status",
")",
":",
"status_labels",
"=",
"{",
"\"P\"",
":",
"\"presente\"",
",",
"\"FJ\"",
":",
"\"falta_justificada\"",
",",
"\"LJ\"",
":",
"\"licenca_justificada\"",
",",
"\"A\"",
":",
"\"ausente\"",
",",
"}",
"return",
"status_labels",
".",
"get",
"(",
"status",
".",
"upper",
"(",
")",
".",
"strip",
"(",
")",
")"
]
| [
79,
4
]
| [
88,
56
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
TestCnpj.test_special_case | (self) | Verifica os casos especiais de CNPJ | Verifica os casos especiais de CNPJ | def test_special_case(self):
""" Verifica os casos especiais de CNPJ """
cases = [
('00000-000/0000', False),
('AAAA0AAAAAAA2AAAAAA', False),
('74600269000145', True),
]
for cnpj, is_valid in cases:
self.assertEqual(self.cnpj.validate(cnpj), is_valid) | [
"def",
"test_special_case",
"(",
"self",
")",
":",
"cases",
"=",
"[",
"(",
"'00000-000/0000'",
",",
"False",
")",
",",
"(",
"'AAAA0AAAAAAA2AAAAAA'",
",",
"False",
")",
",",
"(",
"'74600269000145'",
",",
"True",
")",
",",
"]",
"for",
"cnpj",
",",
"is_valid",
"in",
"cases",
":",
"self",
".",
"assertEqual",
"(",
"self",
".",
"cnpj",
".",
"validate",
"(",
"cnpj",
")",
",",
"is_valid",
")"
]
| [
29,
4
]
| [
37,
64
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
ArticleRenditionFactory | (article_id: str, data: List[dict]) | return article | Recupera uma instância de artigo a partir de um article_id e popula seus
assets a partir dos dados de entrada.
A partir do article_id uma instância de Artigo é recuperada da base OPAC e
seus assets são populados. Se o Artigo não existir na base OPAC a exceção
models.ArticleDoesNotExists é lançada.
Args:
article_id (str): Identificador do artigo a ser recuperado
data (List[dict]): Lista de renditions do artigo
Returns:
models.Article: Artigo recuperado e atualizado com uma nova lista de assets. | Recupera uma instância de artigo a partir de um article_id e popula seus
assets a partir dos dados de entrada. | def ArticleRenditionFactory(article_id: str, data: List[dict]) -> models.Article:
"""Recupera uma instância de artigo a partir de um article_id e popula seus
assets a partir dos dados de entrada.
A partir do article_id uma instância de Artigo é recuperada da base OPAC e
seus assets são populados. Se o Artigo não existir na base OPAC a exceção
models.ArticleDoesNotExists é lançada.
Args:
article_id (str): Identificador do artigo a ser recuperado
data (List[dict]): Lista de renditions do artigo
Returns:
models.Article: Artigo recuperado e atualizado com uma nova lista de assets."""
article = models.Article.objects.get(_id=article_id)
def _get_pdfs(data: dict) -> List[dict]:
return [
{"lang": rendition["lang"], "url": rendition["url"], "type": "pdf"}
for rendition in data
if rendition["mimetype"] == "application/pdf"
]
article.pdfs = list(_get_pdfs(data))
return article | [
"def",
"ArticleRenditionFactory",
"(",
"article_id",
":",
"str",
",",
"data",
":",
"List",
"[",
"dict",
"]",
")",
"->",
"models",
".",
"Article",
":",
"article",
"=",
"models",
".",
"Article",
".",
"objects",
".",
"get",
"(",
"_id",
"=",
"article_id",
")",
"def",
"_get_pdfs",
"(",
"data",
":",
"dict",
")",
"->",
"List",
"[",
"dict",
"]",
":",
"return",
"[",
"{",
"\"lang\"",
":",
"rendition",
"[",
"\"lang\"",
"]",
",",
"\"url\"",
":",
"rendition",
"[",
"\"url\"",
"]",
",",
"\"type\"",
":",
"\"pdf\"",
"}",
"for",
"rendition",
"in",
"data",
"if",
"rendition",
"[",
"\"mimetype\"",
"]",
"==",
"\"application/pdf\"",
"]",
"article",
".",
"pdfs",
"=",
"list",
"(",
"_get_pdfs",
"(",
"data",
")",
")",
"return",
"article"
]
| [
294,
0
]
| [
320,
18
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
get_infos | (paper_boxes, base_url, final_list, event_folder, previous_link) | Raspa as informações de cada paper. | Raspa as informações de cada paper. | def get_infos(paper_boxes, base_url, final_list, event_folder, previous_link):
"""Raspa as informações de cada paper."""
for paper in paper_boxes:
title = paper.h2.text
title = title.strip().lower().replace('/','-')
infos = paper.find_all('dt')
tipo = ""
event = ""
year = ""
authors = ""
file_link = ""
for info in infos:
if info.text.strip() == "Tipo":
tipo = info.find_next_sibling().text.strip()
print (f"Tipo : {tipo}")
if info.text.strip() == "Evento":
event = info.find_next_sibling().text.strip()
print (f"Evento : {event}")
if info.text.strip() == "Ano":
year = info.find_next_sibling().text.strip()
print (f"Ano : {year}")
if info.text.strip() == "Arquivo":
file_tag = info.find_next_sibling().a['href']
file_link = base_url + file_tag
print (f"Arquivo : {file_link}")
if info.text.strip() == "PDF LINK":
file_tag = info.find_next_sibling().a['href']
if file_tag.startswith('https://') == True:
file_link = file_tag
print (f"Arquivo : {file_link}")
else:
file_link = base_url + file_tag
print (f"Arquivo : {file_link}")
if info.text.strip() == "Autor(es)":
authors = info.find_next_sibling().text.strip()
print (f"\nAutor(es) : {authors}")
info_list = [authors, title, tipo, event, year, file_link]
final_list.append(info_list)
print('Encontrando link do paper...')
get_links(paper, event_folder, title, previous_link) | [
"def",
"get_infos",
"(",
"paper_boxes",
",",
"base_url",
",",
"final_list",
",",
"event_folder",
",",
"previous_link",
")",
":",
"for",
"paper",
"in",
"paper_boxes",
":",
"title",
"=",
"paper",
".",
"h2",
".",
"text",
"title",
"=",
"title",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"'/'",
",",
"'-'",
")",
"infos",
"=",
"paper",
".",
"find_all",
"(",
"'dt'",
")",
"tipo",
"=",
"\"\"",
"event",
"=",
"\"\"",
"year",
"=",
"\"\"",
"authors",
"=",
"\"\"",
"file_link",
"=",
"\"\"",
"for",
"info",
"in",
"infos",
":",
"if",
"info",
".",
"text",
".",
"strip",
"(",
")",
"==",
"\"Tipo\"",
":",
"tipo",
"=",
"info",
".",
"find_next_sibling",
"(",
")",
".",
"text",
".",
"strip",
"(",
")",
"print",
"(",
"f\"Tipo : {tipo}\"",
")",
"if",
"info",
".",
"text",
".",
"strip",
"(",
")",
"==",
"\"Evento\"",
":",
"event",
"=",
"info",
".",
"find_next_sibling",
"(",
")",
".",
"text",
".",
"strip",
"(",
")",
"print",
"(",
"f\"Evento : {event}\"",
")",
"if",
"info",
".",
"text",
".",
"strip",
"(",
")",
"==",
"\"Ano\"",
":",
"year",
"=",
"info",
".",
"find_next_sibling",
"(",
")",
".",
"text",
".",
"strip",
"(",
")",
"print",
"(",
"f\"Ano : {year}\"",
")",
"if",
"info",
".",
"text",
".",
"strip",
"(",
")",
"==",
"\"Arquivo\"",
":",
"file_tag",
"=",
"info",
".",
"find_next_sibling",
"(",
")",
".",
"a",
"[",
"'href'",
"]",
"file_link",
"=",
"base_url",
"+",
"file_tag",
"print",
"(",
"f\"Arquivo : {file_link}\"",
")",
"if",
"info",
".",
"text",
".",
"strip",
"(",
")",
"==",
"\"PDF LINK\"",
":",
"file_tag",
"=",
"info",
".",
"find_next_sibling",
"(",
")",
".",
"a",
"[",
"'href'",
"]",
"if",
"file_tag",
".",
"startswith",
"(",
"'https://'",
")",
"==",
"True",
":",
"file_link",
"=",
"file_tag",
"print",
"(",
"f\"Arquivo : {file_link}\"",
")",
"else",
":",
"file_link",
"=",
"base_url",
"+",
"file_tag",
"print",
"(",
"f\"Arquivo : {file_link}\"",
")",
"if",
"info",
".",
"text",
".",
"strip",
"(",
")",
"==",
"\"Autor(es)\"",
":",
"authors",
"=",
"info",
".",
"find_next_sibling",
"(",
")",
".",
"text",
".",
"strip",
"(",
")",
"print",
"(",
"f\"\\nAutor(es) : {authors}\"",
")",
"info_list",
"=",
"[",
"authors",
",",
"title",
",",
"tipo",
",",
"event",
",",
"year",
",",
"file_link",
"]",
"final_list",
".",
"append",
"(",
"info_list",
")",
"print",
"(",
"'Encontrando link do paper...'",
")",
"get_links",
"(",
"paper",
",",
"event_folder",
",",
"title",
",",
"previous_link",
")"
]
| [
38,
0
]
| [
77,
60
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Initial.getset_folderspath | (cls, folder_path_only=True) | Seleciona onde estão as pastas e planihas
Returns:
[type]: [description]
| Seleciona onde estão as pastas e planihas | def getset_folderspath(cls, folder_path_only=True):
"""Seleciona onde estão as pastas e planihas
Returns:
[type]: [description]
"""
# filepath = os.path.realpath(__file__)
# os.path.dirname(filepath)
returned = False
try:
with open(cls.main_path) as f:
returned = f.read()
# except FileNotFoundError:
except (OSError, FileNotFoundError) as e:
e('WITH TITLE PATH NOT EXISTENTE ')
returned = cls.__select_path_if_not_exists()
finally:
if returned and folder_path_only:
returned = os.path.dirname(returned)
return returned | [
"def",
"getset_folderspath",
"(",
"cls",
",",
"folder_path_only",
"=",
"True",
")",
":",
"# filepath = os.path.realpath(__file__)",
"# os.path.dirname(filepath)",
"returned",
"=",
"False",
"try",
":",
"with",
"open",
"(",
"cls",
".",
"main_path",
")",
"as",
"f",
":",
"returned",
"=",
"f",
".",
"read",
"(",
")",
"# except FileNotFoundError:",
"except",
"(",
"OSError",
",",
"FileNotFoundError",
")",
"as",
"e",
":",
"e",
"(",
"'WITH TITLE PATH NOT EXISTENTE '",
")",
"returned",
"=",
"cls",
".",
"__select_path_if_not_exists",
"(",
")",
"finally",
":",
"if",
"returned",
"and",
"folder_path_only",
":",
"returned",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"returned",
")",
"return",
"returned"
]
| [
89,
4
]
| [
110,
27
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
uma_fun | Não faz nada, mas tem requisitos. :) | Não faz nada, mas tem requisitos. :) | def uma_função_fictícia():
"""Não faz nada, mas tem requisitos. :)"""
matriz1 = np.random.rand(5, 5)
print(stats.describe(matriz1)) | [
"def",
"uma_fun",
"ção_",
"fictíc",
"ia",
"():",
"",
"",
"",
"matriz1",
"=",
"np",
".",
"random",
".",
"rand",
"(",
"5",
",",
"5",
")",
"print",
"(",
"stats",
".",
"describe",
"(",
"matriz1",
")",
")"
]
| [
4,
0
]
| [
7,
34
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
||
LineSensor.__init__ | (self, topic_name) | Cria um novo objeto para fazer a leitura do sensor de linha
Args:
topic_name (string): Nome do tópico do sensor de linha
| Cria um novo objeto para fazer a leitura do sensor de linha | def __init__(self, topic_name):
"""Cria um novo objeto para fazer a leitura do sensor de linha
Args:
topic_name (string): Nome do tópico do sensor de linha
"""
self.brightness = 1023 # Inicializa como branco
self.topic_name = topic_name | [
"def",
"__init__",
"(",
"self",
",",
"topic_name",
")",
":",
"self",
".",
"brightness",
"=",
"1023",
"# Inicializa como branco",
"self",
".",
"topic_name",
"=",
"topic_name"
]
| [
4,
4
]
| [
11,
36
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
setchannel | (ctx, channel: Optional[discord.TextChannel]) | Define o canal padrão para as respostas principais (logs).
Você precisa da permissão `Gerenciar Canais`.
| Define o canal padrão para as respostas principais (logs).
Você precisa da permissão `Gerenciar Canais`.
| async def setchannel(ctx, channel: Optional[discord.TextChannel]):
"""Define o canal padrão para as respostas principais (logs).
Você precisa da permissão `Gerenciar Canais`.
"""
if channel is None:
channel = ctx.channel
async with create_async_database("main.db") as db:
fields = (
Field(name="guild", type="TEXT NOT NULL"),
Field(name="channel", type="TEXT NOT NULL")
)
await db.create_table_if_absent("default_channels", fields=fields)
db._cursor.execute("INSERT INTO default_channels(guild, channel) VALUES (?,?)", (ctx.guild.id, ctx.channel.id))
db._connection.commit()
await ctx.channel.send(embed=discord.Embed(
description='Canal {} adicionado como canal principal de respostas!'.format(channel.mention),
color=0xff0000)) | [
"async",
"def",
"setchannel",
"(",
"ctx",
",",
"channel",
":",
"Optional",
"[",
"discord",
".",
"TextChannel",
"]",
")",
":",
"if",
"channel",
"is",
"None",
":",
"channel",
"=",
"ctx",
".",
"channel",
"async",
"with",
"create_async_database",
"(",
"\"main.db\"",
")",
"as",
"db",
":",
"fields",
"=",
"(",
"Field",
"(",
"name",
"=",
"\"guild\"",
",",
"type",
"=",
"\"TEXT NOT NULL\"",
")",
",",
"Field",
"(",
"name",
"=",
"\"channel\"",
",",
"type",
"=",
"\"TEXT NOT NULL\"",
")",
")",
"await",
"db",
".",
"create_table_if_absent",
"(",
"\"default_channels\"",
",",
"fields",
"=",
"fields",
")",
"db",
".",
"_cursor",
".",
"execute",
"(",
"\"INSERT INTO default_channels(guild, channel) VALUES (?,?)\"",
",",
"(",
"ctx",
".",
"guild",
".",
"id",
",",
"ctx",
".",
"channel",
".",
"id",
")",
")",
"db",
".",
"_connection",
".",
"commit",
"(",
")",
"await",
"ctx",
".",
"channel",
".",
"send",
"(",
"embed",
"=",
"discord",
".",
"Embed",
"(",
"description",
"=",
"'Canal {} adicionado como canal principal de respostas!'",
".",
"format",
"(",
"channel",
".",
"mention",
")",
",",
"color",
"=",
"0xff0000",
")",
")"
]
| [
393,
0
]
| [
411,
24
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
DType63.nagc | (self) | return bin2int(self.data[BYTES_63[19]]) | F19 - 0 ou igual à quantidade de valores de "tunings" usados na amostra | F19 - 0 ou igual à quantidade de valores de "tunings" usados na amostra | def nagc(self) -> int:
"""F19 - 0 ou igual à quantidade de valores de "tunings" usados na amostra"""
return bin2int(self.data[BYTES_63[19]]) | [
"def",
"nagc",
"(",
"self",
")",
"->",
"int",
":",
"return",
"bin2int",
"(",
"self",
".",
"data",
"[",
"BYTES_63",
"[",
"19",
"]",
"]",
")"
]
| [
1112,
4
]
| [
1114,
47
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
AtorTestes.teste_valores_passados_por_parametro | (self) | Testa se valores passados no inicializador são armazenados no objeto | Testa se valores passados no inicializador são armazenados no objeto | def teste_valores_passados_por_parametro(self):
'Testa se valores passados no inicializador são armazenados no objeto'
ator = Ator(1, 2)
self.assertEqual(1, ator.x)
self.assertEqual(2, ator.y)
self.assertEqual(ATIVO, ator.status)
self.assertEqual('A', ator.caracter()) | [
"def",
"teste_valores_passados_por_parametro",
"(",
"self",
")",
":",
"ator",
"=",
"Ator",
"(",
"1",
",",
"2",
")",
"self",
".",
"assertEqual",
"(",
"1",
",",
"ator",
".",
"x",
")",
"self",
".",
"assertEqual",
"(",
"2",
",",
"ator",
".",
"y",
")",
"self",
".",
"assertEqual",
"(",
"ATIVO",
",",
"ator",
".",
"status",
")",
"self",
".",
"assertEqual",
"(",
"'A'",
",",
"ator",
".",
"caracter",
"(",
")",
")"
]
| [
24,
4
]
| [
30,
46
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
fetch_stages_info | (content: List[str], func_name: str) | return fetch_stages_to_do(path=stages_file_path, all_stages=content) | Fachada que executa os passos necessários para
criar o arquivo de cache que **contém** os estágios já realizados
por uma função.
Retorna uma tupla contendo informações sobre o arquivo de estágios:
stages_to_do :: Lista contendo os `estágios` a serem realizados
stages_already_done :: Quantidade de estágios finalizados
path :: Path para os arquivo contendo os estágios já
realizados
| Fachada que executa os passos necessários para
criar o arquivo de cache que **contém** os estágios já realizados
por uma função. | def fetch_stages_info(content: List[str], func_name: str) -> Tuple[Set[str], Set[str], str]:
"""Fachada que executa os passos necessários para
criar o arquivo de cache que **contém** os estágios já realizados
por uma função.
Retorna uma tupla contendo informações sobre o arquivo de estágios:
stages_to_do :: Lista contendo os `estágios` a serem realizados
stages_already_done :: Quantidade de estágios finalizados
path :: Path para os arquivo contendo os estágios já
realizados
"""
stages_file_path = fetch_stage_file_path(content=content, func_name=func_name)
create_stage_file(stage_file_path=stages_file_path)
return fetch_stages_to_do(path=stages_file_path, all_stages=content) | [
"def",
"fetch_stages_info",
"(",
"content",
":",
"List",
"[",
"str",
"]",
",",
"func_name",
":",
"str",
")",
"->",
"Tuple",
"[",
"Set",
"[",
"str",
"]",
",",
"Set",
"[",
"str",
"]",
",",
"str",
"]",
":",
"stages_file_path",
"=",
"fetch_stage_file_path",
"(",
"content",
"=",
"content",
",",
"func_name",
"=",
"func_name",
")",
"create_stage_file",
"(",
"stage_file_path",
"=",
"stages_file_path",
")",
"return",
"fetch_stages_to_do",
"(",
"path",
"=",
"stages_file_path",
",",
"all_stages",
"=",
"content",
")"
]
| [
154,
0
]
| [
169,
72
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
TestCns.test_special_case | (self) | Verifica os casos especiais de CNS | Verifica os casos especiais de CNS | def test_special_case(self):
""" Verifica os casos especiais de CNS """
cases = [
('AAAAAAAAAAA', False),
('', False),
]
for cns, is_valid in cases:
self.assertEqual(self.cns.validate(cns), is_valid) | [
"def",
"test_special_case",
"(",
"self",
")",
":",
"cases",
"=",
"[",
"(",
"'AAAAAAAAAAA'",
",",
"False",
")",
",",
"(",
"''",
",",
"False",
")",
",",
"]",
"for",
"cns",
",",
"is_valid",
"in",
"cases",
":",
"self",
".",
"assertEqual",
"(",
"self",
".",
"cns",
".",
"validate",
"(",
"cns",
")",
",",
"is_valid",
")"
]
| [
29,
4
]
| [
36,
62
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
DatabaseWrap.create_table_if_absent | (self, table_name, fields) | Cria uma tabela do SQLite se inexistente | Cria uma tabela do SQLite se inexistente | def create_table_if_absent(self, table_name, fields):
"""Cria uma tabela do SQLite se inexistente"""
cl = []
for field in fields:
cl.append(f"{field.name}\t{field.type}")
joined = ",\n".join(cl)
sql = f"""
CREATE TABLE IF NOT EXISTS "{table_name}"(
{joined}
);
"""
self.cursor.execute(sql)
self.database.commit() | [
"def",
"create_table_if_absent",
"(",
"self",
",",
"table_name",
",",
"fields",
")",
":",
"cl",
"=",
"[",
"]",
"for",
"field",
"in",
"fields",
":",
"cl",
".",
"append",
"(",
"f\"{field.name}\\t{field.type}\"",
")",
"joined",
"=",
"\",\\n\"",
".",
"join",
"(",
"cl",
")",
"sql",
"=",
"f\"\"\"\n CREATE TABLE IF NOT EXISTS \"{table_name}\"(\n {joined}\n );\n \"\"\"",
"self",
".",
"cursor",
".",
"execute",
"(",
"sql",
")",
"self",
".",
"database",
".",
"commit",
"(",
")"
]
| [
36,
4
]
| [
50,
30
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
get_number_rows | (ai_settings, ship_height, alien_height) | return number_rows | Determina o número de linhas com aliens que cabem na tela | Determina o número de linhas com aliens que cabem na tela | def get_number_rows(ai_settings, ship_height, alien_height):
"""Determina o número de linhas com aliens que cabem na tela"""
available_space_y = (ai_settings.screen_height - (3 * alien_height) - ship_height)
number_rows = int(available_space_y / (2 * alien_height))
return number_rows | [
"def",
"get_number_rows",
"(",
"ai_settings",
",",
"ship_height",
",",
"alien_height",
")",
":",
"available_space_y",
"=",
"(",
"ai_settings",
".",
"screen_height",
"-",
"(",
"3",
"*",
"alien_height",
")",
"-",
"ship_height",
")",
"number_rows",
"=",
"int",
"(",
"available_space_y",
"/",
"(",
"2",
"*",
"alien_height",
")",
")",
"return",
"number_rows"
]
| [
198,
0
]
| [
202,
22
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Conta.__str__ | (self) | return f"Id: {self.Id}\nSaldo: {self.saldo}" | Retorna uma string de descrição do objeto Conta | Retorna uma string de descrição do objeto Conta | def __str__(self):
"""Retorna uma string de descrição do objeto Conta"""
return f"Id: {self.Id}\nSaldo: {self.saldo}" | [
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"f\"Id: {self.Id}\\nSaldo: {self.saldo}\""
]
| [
7,
4
]
| [
9,
52
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
doPicsBackup | (picsDir, picsBackupFile) | Efetua o backup das figuras com chamada de sistema ao tar | Efetua o backup das figuras com chamada de sistema ao tar | def doPicsBackup(picsDir, picsBackupFile):
'Efetua o backup das figuras com chamada de sistema ao tar'
cmd = 'tar cjspf %s -C %s ./' % (picsBackupFile, picsDir)
res = commands.getstatusoutput(cmd)
if res[0] != 0:
print 'Erro ao gerar %s: %s' % (picsBackupFile, res[1]) | [
"def",
"doPicsBackup",
"(",
"picsDir",
",",
"picsBackupFile",
")",
":",
"cmd",
"=",
"'tar cjspf %s -C %s ./'",
"%",
"(",
"picsBackupFile",
",",
"picsDir",
")",
"res",
"=",
"commands",
".",
"getstatusoutput",
"(",
"cmd",
")",
"if",
"res",
"[",
"0",
"]",
"!=",
"0",
":",
"print",
"'Erro ao gerar %s: %s'",
"%",
"(",
"picsBackupFile",
",",
"res",
"[",
"1",
"]",
")"
]
| [
105,
0
]
| [
110,
63
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
User.serialize | (self) | return {
'id': self.id,
'username': self.username,
'email': self.email,
'picture': self.picture
} | Retorna os dados de um objeto serializado | Retorna os dados de um objeto serializado | def serialize(self):
'''Retorna os dados de um objeto serializado'''
return {
'id': self.id,
'username': self.username,
'email': self.email,
'picture': self.picture
} | [
"def",
"serialize",
"(",
"self",
")",
":",
"return",
"{",
"'id'",
":",
"self",
".",
"id",
",",
"'username'",
":",
"self",
".",
"username",
",",
"'email'",
":",
"self",
".",
"email",
",",
"'picture'",
":",
"self",
".",
"picture",
"}"
]
| [
34,
4
]
| [
41,
9
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Gatinho.atualizar_attr | (attr, valor, sinal=1, sup=100, inf=0) | Atualiza um atributo, não permitindo que ele exceda
seus limites superior ou inferior ao ser atualizado. | Atualiza um atributo, não permitindo que ele exceda
seus limites superior ou inferior ao ser atualizado. | def atualizar_attr(attr, valor, sinal=1, sup=100, inf=0):
"""Atualiza um atributo, não permitindo que ele exceda
seus limites superior ou inferior ao ser atualizado."""
attr += valor*sinal
if attr >= sup:
return sup
elif attr <= inf:
return inf
else:
return attr | [
"def",
"atualizar_attr",
"(",
"attr",
",",
"valor",
",",
"sinal",
"=",
"1",
",",
"sup",
"=",
"100",
",",
"inf",
"=",
"0",
")",
":",
"attr",
"+=",
"valor",
"*",
"sinal",
"if",
"attr",
">=",
"sup",
":",
"return",
"sup",
"elif",
"attr",
"<=",
"inf",
":",
"return",
"inf",
"else",
":",
"return",
"attr"
]
| [
77,
4
]
| [
88,
23
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
InsertionSort.__simpleInsertionSort | (self,array,leftIndex,rightIndex) | Implementação do método InsertionSort de forma iterativa
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
| Implementação do método InsertionSort de forma iterativa
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
| def __simpleInsertionSort(self,array,leftIndex,rightIndex):
"""Implementação do método InsertionSort de forma iterativa
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
"""
for i in range(leftIndex,rightIndex+1):
j = i
while(j > leftIndex and array[j] < array[j-1]):
array[j] , array[j -1] = array[j -1] , array[j]
j = j - 1 | [
"def",
"__simpleInsertionSort",
"(",
"self",
",",
"array",
",",
"leftIndex",
",",
"rightIndex",
")",
":",
"for",
"i",
"in",
"range",
"(",
"leftIndex",
",",
"rightIndex",
"+",
"1",
")",
":",
"j",
"=",
"i",
"while",
"(",
"j",
">",
"leftIndex",
"and",
"array",
"[",
"j",
"]",
"<",
"array",
"[",
"j",
"-",
"1",
"]",
")",
":",
"array",
"[",
"j",
"]",
",",
"array",
"[",
"j",
"-",
"1",
"]",
"=",
"array",
"[",
"j",
"-",
"1",
"]",
",",
"array",
"[",
"j",
"]",
"j",
"=",
"j",
"-",
"1"
]
| [
34,
1
]
| [
46,
13
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
test_get_prescriptions_drug_by_idPrescription_and_period | (client) | Teste get /prescriptions/drug/idPrescription/period - Compara response data com dados do banco e valida status_code 200 | Teste get /prescriptions/drug/idPrescription/period - Compara response data com dados do banco e valida status_code 200 | def test_get_prescriptions_drug_by_idPrescription_and_period(client):
"""Teste get /prescriptions/drug/idPrescription/period - Compara response data com dados do banco e valida status_code 200"""
access_token = get_access(client)
idPrescription = '20'
url = '/prescriptions/drug/{0}/period'.format(idPrescription)
response = client.get(url, headers=make_headers(access_token))
data = json.loads(response.data)['data']
# TODO: Add consulta ao banco de dados e comparar retorno (retornando status 200 porém data = [])
assert response.status_code == 200 | [
"def",
"test_get_prescriptions_drug_by_idPrescription_and_period",
"(",
"client",
")",
":",
"access_token",
"=",
"get_access",
"(",
"client",
")",
"idPrescription",
"=",
"'20'",
"url",
"=",
"'/prescriptions/drug/{0}/period'",
".",
"format",
"(",
"idPrescription",
")",
"response",
"=",
"client",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"make_headers",
"(",
"access_token",
")",
")",
"data",
"=",
"json",
".",
"loads",
"(",
"response",
".",
"data",
")",
"[",
"'data'",
"]",
"# TODO: Add consulta ao banco de dados e comparar retorno (retornando status 200 porém data = [])",
"assert",
"response",
".",
"status_code",
"==",
"200"
]
| [
43,
0
]
| [
57,
38
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
path_to_spins | (path, direction) | return tuple(rotations) | Obtém uma lista de rotações que um agente deve executar para seguir o caminho. | Obtém uma lista de rotações que um agente deve executar para seguir o caminho. | def path_to_spins(path, direction):
"""Obtém uma lista de rotações que um agente deve executar para seguir o caminho."""
# Verifica a presença de um caminho válido
assert path is not None
rotations = []
# Segue o caminho e calcula os passos necessários para girar e depois avançar
# até alcançar a última localização do caminho
i = 0
while i < len(path) - 1:
rot = spins(path[i], direction, path[i + 1])
rotations.append(rot)
direction = (direction + rot) % len(DELTA)
i += 1
return tuple(rotations) | [
"def",
"path_to_spins",
"(",
"path",
",",
"direction",
")",
":",
"# Verifica a presença de um caminho válido",
"assert",
"path",
"is",
"not",
"None",
"rotations",
"=",
"[",
"]",
"# Segue o caminho e calcula os passos necessários para girar e depois avançar",
"# até alcançar a última localização do caminho",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"path",
")",
"-",
"1",
":",
"rot",
"=",
"spins",
"(",
"path",
"[",
"i",
"]",
",",
"direction",
",",
"path",
"[",
"i",
"+",
"1",
"]",
")",
"rotations",
".",
"append",
"(",
"rot",
")",
"direction",
"=",
"(",
"direction",
"+",
"rot",
")",
"%",
"len",
"(",
"DELTA",
")",
"i",
"+=",
"1",
"return",
"tuple",
"(",
"rotations",
")"
]
| [
116,
0
]
| [
132,
25
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
RequisicaoVips.remove | (cls, authenticated_user, vip_id) | Pesquisa e remove uma Requisicao VIP.
@return: Nothing
@raise RequisicaoVipsNotFoundError: Requisao VIP não cadastrado.
@raise RequisicaoVipsError: Falha ao remover Requisao VIP.
| Pesquisa e remove uma Requisicao VIP. | def remove(cls, authenticated_user, vip_id):
"""Pesquisa e remove uma Requisicao VIP.
@return: Nothing
@raise RequisicaoVipsNotFoundError: Requisao VIP não cadastrado.
@raise RequisicaoVipsError: Falha ao remover Requisao VIP.
"""
try:
vip = RequisicaoVips.get_by_pk(vip_id)
try:
dsrl3 = DsrL3_to_Vip.get_by_vip_id(vip_id)
dsrl3.delete(authenticated_user)
except ObjectDoesNotExist, e:
pass
except RequisicaoVipsMissingDSRL3idError, e:
cls.log.error(
u'Requisao Vip nao possui id DSRL3 correspondente cadastrado no banco')
raise RequisicaoVipsMissingDSRL3idError(
e, 'Requisao Vip com id %s possui DSRl3 id não foi encontrado' % vip_id)
vip.delete()
except RequisicaoVipsNotFoundError, e:
cls.log.error(u'Requisao Vip nao encontrada')
raise RequisicaoVipsNotFoundError(
e, 'Requisao Vip com id %s nao encontrada' % vip_id)
except Exception, e:
cls.log.error(u'Falha ao remover requisicao VIP.')
raise RequisicaoVipsError(e, u'Falha ao remover requisicao VIP.') | [
"def",
"remove",
"(",
"cls",
",",
"authenticated_user",
",",
"vip_id",
")",
":",
"try",
":",
"vip",
"=",
"RequisicaoVips",
".",
"get_by_pk",
"(",
"vip_id",
")",
"try",
":",
"dsrl3",
"=",
"DsrL3_to_Vip",
".",
"get_by_vip_id",
"(",
"vip_id",
")",
"dsrl3",
".",
"delete",
"(",
"authenticated_user",
")",
"except",
"ObjectDoesNotExist",
",",
"e",
":",
"pass",
"except",
"RequisicaoVipsMissingDSRL3idError",
",",
"e",
":",
"cls",
".",
"log",
".",
"error",
"(",
"u'Requisao Vip nao possui id DSRL3 correspondente cadastrado no banco'",
")",
"raise",
"RequisicaoVipsMissingDSRL3idError",
"(",
"e",
",",
"'Requisao Vip com id %s possui DSRl3 id não foi encontrado' ",
" ",
"ip_id)",
"",
"vip",
".",
"delete",
"(",
")",
"except",
"RequisicaoVipsNotFoundError",
",",
"e",
":",
"cls",
".",
"log",
".",
"error",
"(",
"u'Requisao Vip nao encontrada'",
")",
"raise",
"RequisicaoVipsNotFoundError",
"(",
"e",
",",
"'Requisao Vip com id %s nao encontrada'",
"%",
"vip_id",
")",
"except",
"Exception",
",",
"e",
":",
"cls",
".",
"log",
".",
"error",
"(",
"u'Falha ao remover requisicao VIP.'",
")",
"raise",
"RequisicaoVipsError",
"(",
"e",
",",
"u'Falha ao remover requisicao VIP.'",
")"
]
| [
642,
4
]
| [
673,
77
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
mover_tabuleiro | (tabuleiro) | Recebe uma jogada do usuario e
move o tabuleiro de acordo com as regras do
jogo 2048 e retorna o tabuleiro movido
list -> list | Recebe uma jogada do usuario e
move o tabuleiro de acordo com as regras do
jogo 2048 e retorna o tabuleiro movido
list -> list | def mover_tabuleiro(tabuleiro):
""" Recebe uma jogada do usuario e
move o tabuleiro de acordo com as regras do
jogo 2048 e retorna o tabuleiro movido
list -> list """
""" Funcionamento base da função:
É usada a "somar_adjacentes" nas linhas
do tabuleiro dado como entrada caso as
jogadas sejam horizontais, se forem na
vertical, uso a função "transpor_matriz"
e faço a mesma coisa. """
jogada = receber_jogada()
aux = list()
if jogada == "d":
for linha in tabuleiro:
aux.append(somar_adjacentes(linha,jogada))
montar_tabuleiro(tabuleiro)
if tabuleiro == aux:
print("igual")
montar_tabuleiro(aux) | [
"def",
"mover_tabuleiro",
"(",
"tabuleiro",
")",
":",
"\"\"\" Funcionamento base da função:\n É usada a \"somar_adjacentes\" nas linhas\n do tabuleiro dado como entrada caso as\n jogadas sejam horizontais, se forem na\n vertical, uso a função \"transpor_matriz\"\n e faço a mesma coisa. \"\"\"",
"jogada",
"=",
"receber_jogada",
"(",
")",
"aux",
"=",
"list",
"(",
")",
"if",
"jogada",
"==",
"\"d\"",
":",
"for",
"linha",
"in",
"tabuleiro",
":",
"aux",
".",
"append",
"(",
"somar_adjacentes",
"(",
"linha",
",",
"jogada",
")",
")",
"montar_tabuleiro",
"(",
"tabuleiro",
")",
"if",
"tabuleiro",
"==",
"aux",
":",
"print",
"(",
"\"igual\"",
")",
"montar_tabuleiro",
"(",
"aux",
")"
]
| [
223,
0
]
| [
243,
25
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
CallbackEnquadramento.handle | (self) | Monitora a chegada de dados da Serial | Monitora a chegada de dados da Serial | def handle(self):
'''Monitora a chegada de dados da Serial'''
octeto = self.cnx.read(1)
self.desenquadra(octeto) | [
"def",
"handle",
"(",
"self",
")",
":",
"octeto",
"=",
"self",
".",
"cnx",
".",
"read",
"(",
"1",
")",
"self",
".",
"desenquadra",
"(",
"octeto",
")"
]
| [
30,
4
]
| [
33,
32
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
ModelSalaTestCase.setUp | (self) | Variaveis iniciais para o teste. | Variaveis iniciais para o teste. | def setUp(self):
"""Variaveis iniciais para o teste."""
"""Por padrão vou usar nomes de ruas."""
self.name = "Rua Augusta"
self.sala = Sala(name=self.name) | [
"def",
"setUp",
"(",
"self",
")",
":",
"\"\"\"Por padrão vou usar nomes de ruas.\"\"\"",
"self",
".",
"name",
"=",
"\"Rua Augusta\"",
"self",
".",
"sala",
"=",
"Sala",
"(",
"name",
"=",
"self",
".",
"name",
")"
]
| [
9,
4
]
| [
13,
40
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
avalia_textos | (textos, ass_cp) | IMPLEMENTAR. Essa funcao recebe uma lista de textos e uma assinatura ass_cp e deve devolver o numero (1 a n) do texto com maior probabilidade de ter sido infectado por COH-PIAH. | IMPLEMENTAR. Essa funcao recebe uma lista de textos e uma assinatura ass_cp e deve devolver o numero (1 a n) do texto com maior probabilidade de ter sido infectado por COH-PIAH. | def avalia_textos(textos, ass_cp):
'''IMPLEMENTAR. Essa funcao recebe uma lista de textos e uma assinatura ass_cp e deve devolver o numero (1 a n) do texto com maior probabilidade de ter sido infectado por COH-PIAH.'''
lista_g_similaridade=[]
total_ass=[]
for tex in textos:
total_ass.append(calcula_assinatura(tex))
#print("\ntotal_ass: ",total_ass)
for ass in total_ass:
lista_g_similaridade.append(compara_assinatura(ass,ass_cp))
#print("\nlista_g_similaridade: ",lista_g_similaridade)
menor=min(lista_g_similaridade)
#print("\nMenor",menor)
#for pos, ind in enumerate(lista_g_similaridade,start=1):
#print(f"\nNa posição: {pos}, encontrei o valor: {ind}")
pos=1
for graus in lista_g_similaridade:
if graus == menor:
return pos
else:
pos+=1 | [
"def",
"avalia_textos",
"(",
"textos",
",",
"ass_cp",
")",
":",
"lista_g_similaridade",
"=",
"[",
"]",
"total_ass",
"=",
"[",
"]",
"for",
"tex",
"in",
"textos",
":",
"total_ass",
".",
"append",
"(",
"calcula_assinatura",
"(",
"tex",
")",
")",
"#print(\"\\ntotal_ass: \",total_ass) ",
"for",
"ass",
"in",
"total_ass",
":",
"lista_g_similaridade",
".",
"append",
"(",
"compara_assinatura",
"(",
"ass",
",",
"ass_cp",
")",
")",
"#print(\"\\nlista_g_similaridade: \",lista_g_similaridade)",
"menor",
"=",
"min",
"(",
"lista_g_similaridade",
")",
"#print(\"\\nMenor\",menor)",
"#for pos, ind in enumerate(lista_g_similaridade,start=1):",
"#print(f\"\\nNa posição: {pos}, encontrei o valor: {ind}\")",
"pos",
"=",
"1",
"for",
"graus",
"in",
"lista_g_similaridade",
":",
"if",
"graus",
"==",
"menor",
":",
"return",
"pos",
"else",
":",
"pos",
"+=",
"1"
]
| [
168,
0
]
| [
192,
18
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
AmbienteResource.handle_get | (self, request, user, *args, **kwargs) | Trata as requisições de GET para consulta de ambientes.
Permite a consulta de todos os ambientes, ambientes filtrados por divisao_dc,
ambientes filtrados por divisão_dc e por ambiente_logico
URLs: /ambiente/,
/ambiente/divisao_dc/<id_divisao_dc>/,
/ambiente/divisao_dc/<id_divisao_dc>/ambiente_logico/<id_amb_logico>/,
| Trata as requisições de GET para consulta de ambientes. | def handle_get(self, request, user, *args, **kwargs):
"""Trata as requisições de GET para consulta de ambientes.
Permite a consulta de todos os ambientes, ambientes filtrados por divisao_dc,
ambientes filtrados por divisão_dc e por ambiente_logico
URLs: /ambiente/,
/ambiente/divisao_dc/<id_divisao_dc>/,
/ambiente/divisao_dc/<id_divisao_dc>/ambiente_logico/<id_amb_logico>/,
"""
try:
if not has_perm(user, AdminPermission.ENVIRONMENT_MANAGEMENT, AdminPermission.READ_OPERATION):
return self.not_authorized()
environment_list = []
division_id = kwargs.get('id_divisao_dc')
environment_logical_id = kwargs.get('id_amb_logico')
if division_id is not None:
if not is_valid_int_greater_zero_param(division_id):
self.log.error(
u'The division_id parameter is not a valid value: %s.', division_id)
raise InvalidValueError(None, 'division_id', division_id)
else:
division_dc = DivisaoDc.get_by_pk(division_id)
if environment_logical_id is not None:
if not is_valid_int_greater_zero_param(environment_logical_id):
self.log.error(
u'The environment_logical_id parameter is not a valid value: %s.', environment_logical_id)
raise InvalidValueError(
None, 'environment_logical_id', environment_logical_id)
else:
loc_env = AmbienteLogico.get_by_pk(environment_logical_id)
environments = Ambiente().search(
division_id, environment_logical_id).select_related('grupo_l3', 'ambiente_logico', 'divisao_dc', 'filter')
for environment in environments:
environment_list.append(get_environment_map(environment))
return self.response(dumps_networkapi({'ambiente': environment_list}))
except InvalidValueError, e:
return self.response_error(269, e.param, e.value)
except DivisaoDcNotFoundError:
return self.response_error(164, division_id)
except AmbienteLogicoNotFoundError:
return self.response_error(162, environment_logical_id)
except AmbienteNotFoundError:
return self.response_error(112)
except (AmbienteError, GrupoError):
return self.response_error(1) | [
"def",
"handle_get",
"(",
"self",
",",
"request",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"if",
"not",
"has_perm",
"(",
"user",
",",
"AdminPermission",
".",
"ENVIRONMENT_MANAGEMENT",
",",
"AdminPermission",
".",
"READ_OPERATION",
")",
":",
"return",
"self",
".",
"not_authorized",
"(",
")",
"environment_list",
"=",
"[",
"]",
"division_id",
"=",
"kwargs",
".",
"get",
"(",
"'id_divisao_dc'",
")",
"environment_logical_id",
"=",
"kwargs",
".",
"get",
"(",
"'id_amb_logico'",
")",
"if",
"division_id",
"is",
"not",
"None",
":",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"division_id",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'The division_id parameter is not a valid value: %s.'",
",",
"division_id",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'division_id'",
",",
"division_id",
")",
"else",
":",
"division_dc",
"=",
"DivisaoDc",
".",
"get_by_pk",
"(",
"division_id",
")",
"if",
"environment_logical_id",
"is",
"not",
"None",
":",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"environment_logical_id",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'The environment_logical_id parameter is not a valid value: %s.'",
",",
"environment_logical_id",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'environment_logical_id'",
",",
"environment_logical_id",
")",
"else",
":",
"loc_env",
"=",
"AmbienteLogico",
".",
"get_by_pk",
"(",
"environment_logical_id",
")",
"environments",
"=",
"Ambiente",
"(",
")",
".",
"search",
"(",
"division_id",
",",
"environment_logical_id",
")",
".",
"select_related",
"(",
"'grupo_l3'",
",",
"'ambiente_logico'",
",",
"'divisao_dc'",
",",
"'filter'",
")",
"for",
"environment",
"in",
"environments",
":",
"environment_list",
".",
"append",
"(",
"get_environment_map",
"(",
"environment",
")",
")",
"return",
"self",
".",
"response",
"(",
"dumps_networkapi",
"(",
"{",
"'ambiente'",
":",
"environment_list",
"}",
")",
")",
"except",
"InvalidValueError",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"269",
",",
"e",
".",
"param",
",",
"e",
".",
"value",
")",
"except",
"DivisaoDcNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"164",
",",
"division_id",
")",
"except",
"AmbienteLogicoNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"162",
",",
"environment_logical_id",
")",
"except",
"AmbienteNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"112",
")",
"except",
"(",
"AmbienteError",
",",
"GrupoError",
")",
":",
"return",
"self",
".",
"response_error",
"(",
"1",
")"
]
| [
92,
4
]
| [
143,
41
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
pack_article_ALLxml | () | Gera os pacotes SPS a partir de um lista de XML validos.
Args:
Não há argumentos
Retornos:
Sem retornos.
Persiste o XML no ``package_path``
Exemplo:
pack_article_ALLxml()
Exceções:
Não lança exceções.
| Gera os pacotes SPS a partir de um lista de XML validos. | def pack_article_ALLxml():
"""Gera os pacotes SPS a partir de um lista de XML validos.
Args:
Não há argumentos
Retornos:
Sem retornos.
Persiste o XML no ``package_path``
Exemplo:
pack_article_ALLxml()
Exceções:
Não lança exceções.
"""
xmls = [
os.path.join(config.get("VALID_XML_PATH"), xml)
for xml in files.xml_files_list(config.get("VALID_XML_PATH"))
]
jobs = [{"file_xml_path": xml} for xml in xmls]
with tqdm(total=len(xmls), initial=0) as pbar:
def update_bar(pbar=pbar):
pbar.update(1)
DoJobsConcurrently(
pack_article_xml,
jobs=jobs,
max_workers=int(config.get("THREADPOOL_MAX_WORKERS")),
update_bar=update_bar,
) | [
"def",
"pack_article_ALLxml",
"(",
")",
":",
"xmls",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"config",
".",
"get",
"(",
"\"VALID_XML_PATH\"",
")",
",",
"xml",
")",
"for",
"xml",
"in",
"files",
".",
"xml_files_list",
"(",
"config",
".",
"get",
"(",
"\"VALID_XML_PATH\"",
")",
")",
"]",
"jobs",
"=",
"[",
"{",
"\"file_xml_path\"",
":",
"xml",
"}",
"for",
"xml",
"in",
"xmls",
"]",
"with",
"tqdm",
"(",
"total",
"=",
"len",
"(",
"xmls",
")",
",",
"initial",
"=",
"0",
")",
"as",
"pbar",
":",
"def",
"update_bar",
"(",
"pbar",
"=",
"pbar",
")",
":",
"pbar",
".",
"update",
"(",
"1",
")",
"DoJobsConcurrently",
"(",
"pack_article_xml",
",",
"jobs",
"=",
"jobs",
",",
"max_workers",
"=",
"int",
"(",
"config",
".",
"get",
"(",
"\"THREADPOOL_MAX_WORKERS\"",
")",
")",
",",
"update_bar",
"=",
"update_bar",
",",
")"
]
| [
103,
0
]
| [
138,
9
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Funcionario.__init__ | (self, nome, sobrenome, salario) | Gerando atributos para cada parâmetro relacionado. | Gerando atributos para cada parâmetro relacionado. | def __init__(self, nome, sobrenome, salario):
"""Gerando atributos para cada parâmetro relacionado."""
self.nome = nome
self.sobrenome = sobrenome
self.salario = salario | [
"def",
"__init__",
"(",
"self",
",",
"nome",
",",
"sobrenome",
",",
"salario",
")",
":",
"self",
".",
"nome",
"=",
"nome",
"self",
".",
"sobrenome",
"=",
"sobrenome",
"self",
".",
"salario",
"=",
"salario"
]
| [
3,
4
]
| [
7,
30
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
checar | (cpf="",regiao=False) | Checa um CPF.
Se nenhum CPF for passado como parametro ``str``, um ``input()`` será pedido.
Retorna ``True`` quando um CPF é válido e ``False`` quando é inválido
``regiao`` é um parametro ``bool`` o qual checará ou não a região do CPF retornado em ``stdout``. ``False`` é o valor padrão e a região não será checada.
| Checa um CPF.
Se nenhum CPF for passado como parametro ``str``, um ``input()`` será pedido. | def checar(cpf="",regiao=False):
"""Checa um CPF.
Se nenhum CPF for passado como parametro ``str``, um ``input()`` será pedido.
Retorna ``True`` quando um CPF é válido e ``False`` quando é inválido
``regiao`` é um parametro ``bool`` o qual checará ou não a região do CPF retornado em ``stdout``. ``False`` é o valor padrão e a região não será checada.
"""
if not cpf:
cpf = input("Digite o CPF que deseja checar: ")
else:
cpf = cpf
num = 0
# 000.000.000-00
if "." in cpf and "-" in cpf:
cpf = cpf.replace(".", "").replace("-", "")
else:
pass
if len(cpf) == 11:
pass
else:
return False
for x in range(len(cpf)):
num += int(cpf[x])
if str(num)[0] == str(num)[1]:
if regiao:
reg = lambda regi: print("Regiões: " + regi)
ident=str(cpf[8])
if ident == "0":
print("Região: Rio Grande do Sul")
elif ident == "1":
reg("Distrito Federal – Goiás – Mato Grosso – Mato Grosso do Sul – Tocantins")
elif ident == "2":
reg("Pará – Amazonas – Acre – Amapá – Rondônia – Roraima")
elif ident == "3":
reg("Ceará – Maranhão – Piauí")
elif ident == "4":
reg("Pernambuco – Rio Grande do Norte – Paraíba – Alagoas")
elif ident == "5":
reg("Bahia – Sergipe")
elif ident == "6":
reg("Minas Gerais")
elif ident == "7":
reg("Rio de Janeiro – Espírito Santo")
elif ident == "8":
reg("São Paulo")
elif ident == "9":
reg("Paraná – Santa Catarina")
return True
else:
return False | [
"def",
"checar",
"(",
"cpf",
"=",
"\"\"",
",",
"regiao",
"=",
"False",
")",
":",
"if",
"not",
"cpf",
":",
"cpf",
"=",
"input",
"(",
"\"Digite o CPF que deseja checar: \"",
")",
"else",
":",
"cpf",
"=",
"cpf",
"num",
"=",
"0",
"# 000.000.000-00",
"if",
"\".\"",
"in",
"cpf",
"and",
"\"-\"",
"in",
"cpf",
":",
"cpf",
"=",
"cpf",
".",
"replace",
"(",
"\".\"",
",",
"\"\"",
")",
".",
"replace",
"(",
"\"-\"",
",",
"\"\"",
")",
"else",
":",
"pass",
"if",
"len",
"(",
"cpf",
")",
"==",
"11",
":",
"pass",
"else",
":",
"return",
"False",
"for",
"x",
"in",
"range",
"(",
"len",
"(",
"cpf",
")",
")",
":",
"num",
"+=",
"int",
"(",
"cpf",
"[",
"x",
"]",
")",
"if",
"str",
"(",
"num",
")",
"[",
"0",
"]",
"==",
"str",
"(",
"num",
")",
"[",
"1",
"]",
":",
"if",
"regiao",
":",
"reg",
"=",
"lambda",
"regi",
":",
"print",
"(",
"\"Regiões: \" ",
" ",
"egi)",
"",
"ident",
"=",
"str",
"(",
"cpf",
"[",
"8",
"]",
")",
"if",
"ident",
"==",
"\"0\"",
":",
"print",
"(",
"\"Região: Rio Grande do Sul\")",
"",
"elif",
"ident",
"==",
"\"1\"",
":",
"reg",
"(",
"\"Distrito Federal – Goiás – Mato Grosso – Mato Grosso do Sul – Tocantins\")",
"",
"elif",
"ident",
"==",
"\"2\"",
":",
"reg",
"(",
"\"Pará – Amazonas – Acre – Amapá – Rondônia – Roraima\")",
"",
"elif",
"ident",
"==",
"\"3\"",
":",
"reg",
"(",
"\"Ceará – Maranhão – Piauí\")",
"",
"elif",
"ident",
"==",
"\"4\"",
":",
"reg",
"(",
"\"Pernambuco – Rio Grande do Norte – Paraíba – Alagoas\")",
"",
"elif",
"ident",
"==",
"\"5\"",
":",
"reg",
"(",
"\"Bahia – Sergipe\")",
"",
"elif",
"ident",
"==",
"\"6\"",
":",
"reg",
"(",
"\"Minas Gerais\"",
")",
"elif",
"ident",
"==",
"\"7\"",
":",
"reg",
"(",
"\"Rio de Janeiro – Espírito Santo\")",
"",
"elif",
"ident",
"==",
"\"8\"",
":",
"reg",
"(",
"\"São Paulo\")",
"",
"elif",
"ident",
"==",
"\"9\"",
":",
"reg",
"(",
"\"Paraná – Santa Catarina\")",
"",
"return",
"True",
"else",
":",
"return",
"False"
]
| [
10,
0
]
| [
60,
20
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
LineSensor._callback | (self, data) | Função de callback necessária para receber informação do subscriber
Args:
data (std_msgs/UInt32): Dados da leitura do sensor
| Função de callback necessária para receber informação do subscriber | def _callback(self, data):
"""Função de callback necessária para receber informação do subscriber
Args:
data (std_msgs/UInt32): Dados da leitura do sensor
"""
self.brightness = data.data | [
"def",
"_callback",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"brightness",
"=",
"data",
".",
"data"
]
| [
19,
4
]
| [
25,
35
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
rollback_document | (
doc_info: dict, session: object, journals: dict, poison_pill=PoisonPill()
) | Desfaz documento de uma instância do Kernel como se não tivesse sido inserido,
removendo registros feitos durante o processo de importação. | Desfaz documento de uma instância do Kernel como se não tivesse sido inserido,
removendo registros feitos durante o processo de importação. | def rollback_document(
doc_info: dict, session: object, journals: dict, poison_pill=PoisonPill()
) -> None:
"""Desfaz documento de uma instância do Kernel como se não tivesse sido inserido,
removendo registros feitos durante o processo de importação."""
if poison_pill.poisoned:
return
try:
pid_v3 = doc_info["pid_v3"]
except KeyError:
raise exceptions.RollbackError("could not get PID V3 from doc info.")
else:
logger.debug("Starting the rollback step for document PID V3 '%s'...", pid_v3)
# Rollback Document changes
try:
session.changes.rollback(pid_v3)
except ds_exceptions.DoesNotExist as exc:
logger.info('Document "%s" changes not fount', pid_v3)
# Rollback Document
try:
session.documents.rollback(pid_v3)
except ds_exceptions.DoesNotExist as exc:
logger.info('Document "%s" not fount', pid_v3)
_rolledback_result = {
"pid_v3": doc_info["pid_v3"],
"status": "ROLLEDBACK",
"timestamp": datetime.utcnow().isoformat(),
}
# Rollback DocumentsBundle
try:
_rolledback_bundle_id = rollback_bundle(doc_info, session, journals)
except exceptions.RollbackError as exc:
logger.info(exc)
else:
if _rolledback_bundle_id:
_rolledback_result["bundle"] = _rolledback_bundle_id
return _rolledback_result | [
"def",
"rollback_document",
"(",
"doc_info",
":",
"dict",
",",
"session",
":",
"object",
",",
"journals",
":",
"dict",
",",
"poison_pill",
"=",
"PoisonPill",
"(",
")",
")",
"->",
"None",
":",
"if",
"poison_pill",
".",
"poisoned",
":",
"return",
"try",
":",
"pid_v3",
"=",
"doc_info",
"[",
"\"pid_v3\"",
"]",
"except",
"KeyError",
":",
"raise",
"exceptions",
".",
"RollbackError",
"(",
"\"could not get PID V3 from doc info.\"",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"\"Starting the rollback step for document PID V3 '%s'...\"",
",",
"pid_v3",
")",
"# Rollback Document changes",
"try",
":",
"session",
".",
"changes",
".",
"rollback",
"(",
"pid_v3",
")",
"except",
"ds_exceptions",
".",
"DoesNotExist",
"as",
"exc",
":",
"logger",
".",
"info",
"(",
"'Document \"%s\" changes not fount'",
",",
"pid_v3",
")",
"# Rollback Document",
"try",
":",
"session",
".",
"documents",
".",
"rollback",
"(",
"pid_v3",
")",
"except",
"ds_exceptions",
".",
"DoesNotExist",
"as",
"exc",
":",
"logger",
".",
"info",
"(",
"'Document \"%s\" not fount'",
",",
"pid_v3",
")",
"_rolledback_result",
"=",
"{",
"\"pid_v3\"",
":",
"doc_info",
"[",
"\"pid_v3\"",
"]",
",",
"\"status\"",
":",
"\"ROLLEDBACK\"",
",",
"\"timestamp\"",
":",
"datetime",
".",
"utcnow",
"(",
")",
".",
"isoformat",
"(",
")",
",",
"}",
"# Rollback DocumentsBundle",
"try",
":",
"_rolledback_bundle_id",
"=",
"rollback_bundle",
"(",
"doc_info",
",",
"session",
",",
"journals",
")",
"except",
"exceptions",
".",
"RollbackError",
"as",
"exc",
":",
"logger",
".",
"info",
"(",
"exc",
")",
"else",
":",
"if",
"_rolledback_bundle_id",
":",
"_rolledback_result",
"[",
"\"bundle\"",
"]",
"=",
"_rolledback_bundle_id",
"return",
"_rolledback_result"
]
| [
170,
0
]
| [
213,
33
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
RoteiroResource.handle_put | (self, request, user, *args, **kwargs) | Trata as requisições de PUT para alterar um Roteiro.
URL: roteiro/<id_roteiro>/
| Trata as requisições de PUT para alterar um Roteiro. | def handle_put(self, request, user, *args, **kwargs):
"""Trata as requisições de PUT para alterar um Roteiro.
URL: roteiro/<id_roteiro>/
"""
try:
script_id = kwargs.get('id_roteiro')
if script_id is None:
return self.response_error(233)
if not has_perm(user, AdminPermission.SCRIPT_MANAGEMENT, AdminPermission.WRITE_OPERATION):
return self.not_authorized()
xml_map, attrs_map = loads(request.raw_post_data)
self.log.debug('XML_MAP: %s', xml_map)
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.')
script_map = networkapi_map.get('roteiro')
if script_map is None:
return self.response_error(3, u'Não existe valor para a tag roteiro do XML de requisição.')
script_type_id = script_map.get('id_tipo_roteiro')
if script_type_id is None:
return self.response_error(194)
try:
script_type_id = int(script_type_id)
except (TypeError, ValueError):
self.log.error(
u'Valor do id_tipo_roteiro inválido: %s.', script_type_id)
return self.response_error(158, script_type_id)
script_name = script_map.get('nome')
if script_name is None:
return self.response_error(195)
Roteiro.update(user,
script_id,
tipo_roteiro_id=script_type_id,
roteiro=script_name,
descricao=script_map.get('descricao'))
return self.response(dumps_networkapi({}))
except RoteiroNotFoundError:
return self.response_error(165, script_id)
except TipoRoteiroNotFoundError:
return self.response_error(158, script_type_id)
except RoteiroNameDuplicatedError:
return self.response_error(250, script_name)
except XMLError, x:
self.log.error(u'Erro ao ler o XML da requisicao.')
return self.response_error(3, x)
except (RoteiroError, GrupoError):
return self.response_error(1) | [
"def",
"handle_put",
"(",
"self",
",",
"request",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"script_id",
"=",
"kwargs",
".",
"get",
"(",
"'id_roteiro'",
")",
"if",
"script_id",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"233",
")",
"if",
"not",
"has_perm",
"(",
"user",
",",
"AdminPermission",
".",
"SCRIPT_MANAGEMENT",
",",
"AdminPermission",
".",
"WRITE_OPERATION",
")",
":",
"return",
"self",
".",
"not_authorized",
"(",
")",
"xml_map",
",",
"attrs_map",
"=",
"loads",
"(",
"request",
".",
"raw_post_data",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'XML_MAP: %s'",
",",
"xml_map",
")",
"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.')",
"",
"script_map",
"=",
"networkapi_map",
".",
"get",
"(",
"'roteiro'",
")",
"if",
"script_map",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"u'Não existe valor para a tag roteiro do XML de requisição.')",
"",
"script_type_id",
"=",
"script_map",
".",
"get",
"(",
"'id_tipo_roteiro'",
")",
"if",
"script_type_id",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"194",
")",
"try",
":",
"script_type_id",
"=",
"int",
"(",
"script_type_id",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Valor do id_tipo_roteiro inválido: %s.',",
" ",
"cript_type_id)",
"",
"return",
"self",
".",
"response_error",
"(",
"158",
",",
"script_type_id",
")",
"script_name",
"=",
"script_map",
".",
"get",
"(",
"'nome'",
")",
"if",
"script_name",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"195",
")",
"Roteiro",
".",
"update",
"(",
"user",
",",
"script_id",
",",
"tipo_roteiro_id",
"=",
"script_type_id",
",",
"roteiro",
"=",
"script_name",
",",
"descricao",
"=",
"script_map",
".",
"get",
"(",
"'descricao'",
")",
")",
"return",
"self",
".",
"response",
"(",
"dumps_networkapi",
"(",
"{",
"}",
")",
")",
"except",
"RoteiroNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"165",
",",
"script_id",
")",
"except",
"TipoRoteiroNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"158",
",",
"script_type_id",
")",
"except",
"RoteiroNameDuplicatedError",
":",
"return",
"self",
".",
"response_error",
"(",
"250",
",",
"script_name",
")",
"except",
"XMLError",
",",
"x",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Erro ao ler o XML da requisicao.'",
")",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"x",
")",
"except",
"(",
"RoteiroError",
",",
"GrupoError",
")",
":",
"return",
"self",
".",
"response_error",
"(",
"1",
")"
]
| [
157,
4
]
| [
214,
41
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
test_put_prescriptions_by_id_permission | (client) | Teste put /prescriptions/id - Deve retornar erro [401 UNAUTHORIZED] devido ao usuário utilizado | Teste put /prescriptions/id - Deve retornar erro [401 UNAUTHORIZED] devido ao usuário utilizado | def test_put_prescriptions_by_id_permission(client):
"""Teste put /prescriptions/id - Deve retornar erro [401 UNAUTHORIZED] devido ao usuário utilizado"""
access_token = get_access(client)
idPrescription = '20'
mimetype = 'application/json'
authorization = 'Bearer {}'.format(access_token)
headers = {
'Content-Type': mimetype,
'Accept': mimetype,
'Authorization': authorization
}
data = {
"status": "s",
"notes": "note test",
"concilia": "s"
}
url = 'prescriptions/' + idPrescription
response = client.put(url, data=json.dumps(data), headers=headers)
assert response.status_code == 401 | [
"def",
"test_put_prescriptions_by_id_permission",
"(",
"client",
")",
":",
"access_token",
"=",
"get_access",
"(",
"client",
")",
"idPrescription",
"=",
"'20'",
"mimetype",
"=",
"'application/json'",
"authorization",
"=",
"'Bearer {}'",
".",
"format",
"(",
"access_token",
")",
"headers",
"=",
"{",
"'Content-Type'",
":",
"mimetype",
",",
"'Accept'",
":",
"mimetype",
",",
"'Authorization'",
":",
"authorization",
"}",
"data",
"=",
"{",
"\"status\"",
":",
"\"s\"",
",",
"\"notes\"",
":",
"\"note test\"",
",",
"\"concilia\"",
":",
"\"s\"",
"}",
"url",
"=",
"'prescriptions/'",
"+",
"idPrescription",
"response",
"=",
"client",
".",
"put",
"(",
"url",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
",",
"headers",
"=",
"headers",
")",
"assert",
"response",
".",
"status_code",
"==",
"401"
]
| [
74,
0
]
| [
97,
38
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
SelectionSort.__recursiveSimpleSelectionSort | (self,array,leftIndex,rightIndex) | Implementação do método SelectionSort de forma recursiva
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
| Implementação do método SelectionSort de forma recursiva
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
| def __recursiveSimpleSelectionSort(self,array,leftIndex,rightIndex):
"""Implementação do método SelectionSort de forma recursiva
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
"""
if(leftIndex < rightIndex):
self.__recursiveGetMin(array, leftIndex, rightIndex, leftIndex, leftIndex)
self.__recursiveSimpleSelectionSort(array,leftIndex + 1,rightIndex) | [
"def",
"__recursiveSimpleSelectionSort",
"(",
"self",
",",
"array",
",",
"leftIndex",
",",
"rightIndex",
")",
":",
"if",
"(",
"leftIndex",
"<",
"rightIndex",
")",
":",
"self",
".",
"__recursiveGetMin",
"(",
"array",
",",
"leftIndex",
",",
"rightIndex",
",",
"leftIndex",
",",
"leftIndex",
")",
"self",
".",
"__recursiveSimpleSelectionSort",
"(",
"array",
",",
"leftIndex",
"+",
"1",
",",
"rightIndex",
")"
]
| [
76,
1
]
| [
86,
70
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
blocos | (prog, novo = False, id = None, abre=bloco[0],fecha=bloco[1]) | return prog | Divide a lista de linhas prog (sendo essa lista copiada se novo for verdadeiro),
atribuindo, se possível, o id != None, abrindo os blocos e fechando de acordo com a presença das substrings fornecidas.
O id é composto pela tupla do valor dado precedido pelo índice da lista, se o referido valor não for None. | Divide a lista de linhas prog (sendo essa lista copiada se novo for verdadeiro),
atribuindo, se possível, o id != None, abrindo os blocos e fechando de acordo com a presença das substrings fornecidas.
O id é composto pela tupla do valor dado precedido pelo índice da lista, se o referido valor não for None. | def blocos (prog, novo = False, id = None, abre=bloco[0],fecha=bloco[1]):
'''Divide a lista de linhas prog (sendo essa lista copiada se novo for verdadeiro),
atribuindo, se possível, o id != None, abrindo os blocos e fechando de acordo com a presença das substrings fornecidas.
O id é composto pela tupla do valor dado precedido pelo índice da lista, se o referido valor não for None.'''
if novo or type(prog) != list:
prog = linhas(prog)
novo = True
b = c = 0
while c < len(prog):
ln = prog[c]
try:
ln = ln.upper()
if id != None:
prog[c].__id__((c,id))
except AttributeError:
pass
if abre in ln:
prog[c] = [prog[c]]
b = c
c += 1
novo = False
elif novo:
c += 1
else:
if fecha in ln:
novo = True
prog[b].append(prog.pop(c))
# c += novo
return prog | [
"def",
"blocos",
"(",
"prog",
",",
"novo",
"=",
"False",
",",
"id",
"=",
"None",
",",
"abre",
"=",
"bloco",
"[",
"0",
"]",
",",
"fecha",
"=",
"bloco",
"[",
"1",
"]",
")",
":",
"if",
"novo",
"or",
"type",
"(",
"prog",
")",
"!=",
"list",
":",
"prog",
"=",
"linhas",
"(",
"prog",
")",
"novo",
"=",
"True",
"b",
"=",
"c",
"=",
"0",
"while",
"c",
"<",
"len",
"(",
"prog",
")",
":",
"ln",
"=",
"prog",
"[",
"c",
"]",
"try",
":",
"ln",
"=",
"ln",
".",
"upper",
"(",
")",
"if",
"id",
"!=",
"None",
":",
"prog",
"[",
"c",
"]",
".",
"__id__",
"(",
"(",
"c",
",",
"id",
")",
")",
"except",
"AttributeError",
":",
"pass",
"if",
"abre",
"in",
"ln",
":",
"prog",
"[",
"c",
"]",
"=",
"[",
"prog",
"[",
"c",
"]",
"]",
"b",
"=",
"c",
"c",
"+=",
"1",
"novo",
"=",
"False",
"elif",
"novo",
":",
"c",
"+=",
"1",
"else",
":",
"if",
"fecha",
"in",
"ln",
":",
"novo",
"=",
"True",
"prog",
"[",
"b",
"]",
".",
"append",
"(",
"prog",
".",
"pop",
"(",
"c",
")",
")",
"#\tc += novo",
"return",
"prog"
]
| [
49,
0
]
| [
78,
12
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
TestLambdas.test_lambda_anyall | (self) | Teste usando dois operadores lambda: any e all | Teste usando dois operadores lambda: any e all | def test_lambda_anyall(self):
"""Teste usando dois operadores lambda: any e all"""
expected = "customFieldValues/any(x: x/items/all(y: y/customFieldItem eq 'MGSSUSTR6-06R'))"
result = AnyAll(
self.properties["customFieldValues"].items.customFieldItem
== "MGSSUSTR6-06R"
)
self.assertEqual(result, expected) | [
"def",
"test_lambda_anyall",
"(",
"self",
")",
":",
"expected",
"=",
"\"customFieldValues/any(x: x/items/all(y: y/customFieldItem eq 'MGSSUSTR6-06R'))\"",
"result",
"=",
"AnyAll",
"(",
"self",
".",
"properties",
"[",
"\"customFieldValues\"",
"]",
".",
"items",
".",
"customFieldItem",
"==",
"\"MGSSUSTR6-06R\"",
")",
"self",
".",
"assertEqual",
"(",
"result",
",",
"expected",
")"
]
| [
63,
4
]
| [
70,
42
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
testeAtividade.testCriacaoDiagrama | (self) | self.assertEqual(Atividade['nomeDiagrama'], 'Diagrama de Atividades', 'Nome do diagrama não criado')
self.assertEqual(Atividades['nomeAtividade'], 'Atividade de Monitoramento', 'Nome da atividade não criado')
self.assertEqual(len(nodoInicial['arrayAtividades']), 4, 'Atividades não foram criadas')
self.assertEqual(len(nodoInicial['arrayTransicoes']), 4, 'Transicoes não foram criadas')
if __name__ == "__main__":
unittest.main() | self.assertEqual(Atividade['nomeDiagrama'], 'Diagrama de Atividades', 'Nome do diagrama não criado')
self.assertEqual(Atividades['nomeAtividade'], 'Atividade de Monitoramento', 'Nome da atividade não criado')
self.assertEqual(len(nodoInicial['arrayAtividades']), 4, 'Atividades não foram criadas')
self.assertEqual(len(nodoInicial['arrayTransicoes']), 4, 'Transicoes não foram criadas') | def testCriacaoDiagrama(self):
nodoInicial = Nodo('Nodo Inicial', ['proximo'])
nodoDecisao = NodoDecisao('Nodo Decisao', ['Nodo Inicial'] ,['Nodo Fusao'])
nodoFusao = NodoFusao('Nodo Fusao', ['Nodo Decisao'] ,['Nodo Final'])
nodoFinal = NodoFinal('Nodo Final', ['Nodo Fusao'])
nodoInicial.addNodo(nodoDecisao)
nodoInicial.addNodo(nodoFusao)
nodoInicial.addNodo(nodoFinal)
self.assertEqual(len(nodoInicial.arrayNodo), 4, 'Nodos não criados')
atividade = Atividade('Diagrama de Atividades', 'Atividade de Monitoramento', nodoInicial.arrayNodo)
"""self.assertEqual(Atividade['nomeDiagrama'], 'Diagrama de Atividades', 'Nome do diagrama não criado')
self.assertEqual(Atividades['nomeAtividade'], 'Atividade de Monitoramento', 'Nome da atividade não criado')
self.assertEqual(len(nodoInicial['arrayAtividades']), 4, 'Atividades não foram criadas')
self.assertEqual(len(nodoInicial['arrayTransicoes']), 4, 'Transicoes não foram criadas')
if __name__ == "__main__":
unittest.main() """ | [
"def",
"testCriacaoDiagrama",
"(",
"self",
")",
":",
"nodoInicial",
"=",
"Nodo",
"(",
"'Nodo Inicial'",
",",
"[",
"'proximo'",
"]",
")",
"nodoDecisao",
"=",
"NodoDecisao",
"(",
"'Nodo Decisao'",
",",
"[",
"'Nodo Inicial'",
"]",
",",
"[",
"'Nodo Fusao'",
"]",
")",
"nodoFusao",
"=",
"NodoFusao",
"(",
"'Nodo Fusao'",
",",
"[",
"'Nodo Decisao'",
"]",
",",
"[",
"'Nodo Final'",
"]",
")",
"nodoFinal",
"=",
"NodoFinal",
"(",
"'Nodo Final'",
",",
"[",
"'Nodo Fusao'",
"]",
")",
"nodoInicial",
".",
"addNodo",
"(",
"nodoDecisao",
")",
"nodoInicial",
".",
"addNodo",
"(",
"nodoFusao",
")",
"nodoInicial",
".",
"addNodo",
"(",
"nodoFinal",
")",
"self",
".",
"assertEqual",
"(",
"len",
"(",
"nodoInicial",
".",
"arrayNodo",
")",
",",
"4",
",",
"'Nodos não criados')",
"",
"atividade",
"=",
"Atividade",
"(",
"'Diagrama de Atividades'",
",",
"'Atividade de Monitoramento'",
",",
"nodoInicial",
".",
"arrayNodo",
")"
]
| [
6,
2
]
| [
22,
22
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
register_latest_stage | (stages_file_path: str, stage_id: str) | Adiciona um `stage_id` na última linha de um
arquivo de controle | Adiciona um `stage_id` na última linha de um
arquivo de controle | def register_latest_stage(stages_file_path: str, stage_id: str) -> None:
"""Adiciona um `stage_id` na última linha de um
arquivo de controle"""
with open(stages_file_path, "a") as file:
file.write(f"{stage_id}\n") | [
"def",
"register_latest_stage",
"(",
"stages_file_path",
":",
"str",
",",
"stage_id",
":",
"str",
")",
"->",
"None",
":",
"with",
"open",
"(",
"stages_file_path",
",",
"\"a\"",
")",
"as",
"file",
":",
"file",
".",
"write",
"(",
"f\"{stage_id}\\n\"",
")"
]
| [
117,
0
]
| [
122,
35
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
GuessTest.test_assert_match | (self) | Cenário 1: Tentativa Acertada | Cenário 1: Tentativa Acertada | def test_assert_match(self):
""" Cenário 1: Tentativa Acertada """
self.assertEqual(guess.assert_match("++++"), True) | [
"def",
"test_assert_match",
"(",
"self",
")",
":",
"self",
".",
"assertEqual",
"(",
"guess",
".",
"assert_match",
"(",
"\"++++\"",
")",
",",
"True",
")"
]
| [
19,
4
]
| [
21,
58
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
greatest_common_divisor | (a, b) | return a | Retorna o maior divisor comum (MDC) entre a e b.
Args:
a (int): primeiro valor.
b (int): segundo valor.
Returns:
int: Maior divisor comum (MDC) entre a e b.
| Retorna o maior divisor comum (MDC) entre a e b. | def greatest_common_divisor(a, b):
"""Retorna o maior divisor comum (MDC) entre a e b.
Args:
a (int): primeiro valor.
b (int): segundo valor.
Returns:
int: Maior divisor comum (MDC) entre a e b.
"""
if 0 in (a, b):
return 1
if a < b:
return greatest_common_divisor(a, b - a)
elif b < a:
return greatest_common_divisor(a - b, a)
return a | [
"def",
"greatest_common_divisor",
"(",
"a",
",",
"b",
")",
":",
"if",
"0",
"in",
"(",
"a",
",",
"b",
")",
":",
"return",
"1",
"if",
"a",
"<",
"b",
":",
"return",
"greatest_common_divisor",
"(",
"a",
",",
"b",
"-",
"a",
")",
"elif",
"b",
"<",
"a",
":",
"return",
"greatest_common_divisor",
"(",
"a",
"-",
"b",
",",
"a",
")",
"return",
"a"
]
| [
6,
0
]
| [
22,
12
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Tun.start | (self) | Cria a interface tun, e configura-a com seu endereço IP | Cria a interface tun, e configura-a com seu endereço IP | def start(self):
'Cria a interface tun, e configura-a com seu endereço IP'
if self.fd >= 0: raise ValueError('already started')
self._alloc()
self._setIp() | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"fd",
">=",
"0",
":",
"raise",
"ValueError",
"(",
"'already started'",
")",
"self",
".",
"_alloc",
"(",
")",
"self",
".",
"_setIp",
"(",
")"
]
| [
66,
4
]
| [
70,
21
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
PassaroVermelhoTests.teste_posicao_antes_do_lancamento | (self) | Método que testa que o pássaro fica parado antes do tempo de lançamento | Método que testa que o pássaro fica parado antes do tempo de lançamento | def teste_posicao_antes_do_lancamento(self):
'Método que testa que o pássaro fica parado antes do tempo de lançamento'
passaro_vermelho = PassaroVermelho(1, 1)
passaro_vermelho.lancar(90, 2) # passaro lancado a 90 graus no tempo 2 segundos
#
for t in range(20):
t /= 10
self.assertEqual((1, 1), passaro_vermelho.calcular_posicao(t),
'Não deveria se mover no tempo %s < 2 segundtos' % t) | [
"def",
"teste_posicao_antes_do_lancamento",
"(",
"self",
")",
":",
"passaro_vermelho",
"=",
"PassaroVermelho",
"(",
"1",
",",
"1",
")",
"passaro_vermelho",
".",
"lancar",
"(",
"90",
",",
"2",
")",
"# passaro lancado a 90 graus no tempo 2 segundos",
"#",
"for",
"t",
"in",
"range",
"(",
"20",
")",
":",
"t",
"/=",
"10",
"self",
".",
"assertEqual",
"(",
"(",
"1",
",",
"1",
")",
",",
"passaro_vermelho",
".",
"calcular_posicao",
"(",
"t",
")",
",",
"'Não deveria se mover no tempo %s < 2 segundtos' ",
" ",
")",
""
]
| [
188,
4
]
| [
196,
83
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
topics | (request) | return render(request, 'learning_logs/topics.html', context) | Mostra todos os assuntos. | Mostra todos os assuntos. | def topics(request):
"""Mostra todos os assuntos."""
topics = Topic.objects.filter(owner=request.user).order_by('date_added')
context = {'topics': topics}
return render(request, 'learning_logs/topics.html', context) | [
"def",
"topics",
"(",
"request",
")",
":",
"topics",
"=",
"Topic",
".",
"objects",
".",
"filter",
"(",
"owner",
"=",
"request",
".",
"user",
")",
".",
"order_by",
"(",
"'date_added'",
")",
"context",
"=",
"{",
"'topics'",
":",
"topics",
"}",
"return",
"render",
"(",
"request",
",",
"'learning_logs/topics.html'",
",",
"context",
")"
]
| [
16,
0
]
| [
20,
64
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
update_status | () | return render_template('livro/update_status.html', livros=livros, erro=error) | Atualiza o status do livro. | Atualiza o status do livro. | def update_status():
"""Atualiza o status do livro."""
error = ''
if request.method == 'POST':
try:
status = request.form['status']
tombo = request.form['tombos']
sql = 'UPDATE livro SET status = "%s" WHERE tombo = "%s" ' % (status, tombo)
db.insert_bd(sql)
return redirect(url_for('livro.index'))
except Exception as e:
error = 'Não foi possível atualizar esse livro!'
sql = 'select tombo, status from livro'
livros = db.query_bd(sql)
return render_template('livro/update_status.html', livros=livros, erro=error) | [
"def",
"update_status",
"(",
")",
":",
"error",
"=",
"''",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"try",
":",
"status",
"=",
"request",
".",
"form",
"[",
"'status'",
"]",
"tombo",
"=",
"request",
".",
"form",
"[",
"'tombos'",
"]",
"sql",
"=",
"'UPDATE livro SET status = \"%s\" WHERE tombo = \"%s\" '",
"%",
"(",
"status",
",",
"tombo",
")",
"db",
".",
"insert_bd",
"(",
"sql",
")",
"return",
"redirect",
"(",
"url_for",
"(",
"'livro.index'",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"error",
"=",
"'Não foi possível atualizar esse livro!'",
"sql",
"=",
"'select tombo, status from livro'",
"livros",
"=",
"db",
".",
"query_bd",
"(",
"sql",
")",
"return",
"render_template",
"(",
"'livro/update_status.html'",
",",
"livros",
"=",
"livros",
",",
"erro",
"=",
"error",
")"
]
| [
172,
0
]
| [
188,
81
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
verificar_sudoku | (sv) | return correto | A função verificar_sudoku, tem como objetivo receber um sudoku que o próprio usuário preencheu e analisar se ele está correto e retorna o valor True caso esteja correto e False caso esteja errado
sv: sudoku a ser verificado
| A função verificar_sudoku, tem como objetivo receber um sudoku que o próprio usuário preencheu e analisar se ele está correto e retorna o valor True caso esteja correto e False caso esteja errado
sv: sudoku a ser verificado
| def verificar_sudoku(sv):
""" A função verificar_sudoku, tem como objetivo receber um sudoku que o próprio usuário preencheu e analisar se ele está correto e retorna o valor True caso esteja correto e False caso esteja errado
sv: sudoku a ser verificado
"""
#todas as linhas
l1 = sv[0]
l2 = sv[1]
l3 = sv[2]
l4 = sv[3]
l5 = sv[4]
l6 = sv[5]
l7 = sv[6]
l8 = sv[7]
l9 = sv[8]
#todos os blocos
b1 = [l1[0], l1[1], l1[2], l2[0], l2[1], l2[2], l3[0], l3[1], l3[2]]
b2 = [l1[3], l1[4], l1[5], l2[3], l2[4], l2[5], l3[3], l3[4], l3[5]]
b3 = [l1[6], l1[7], l1[8], l2[6], l2[7], l2[8], l3[6], l3[7], l3[8]]
b4 = [l4[0], l4[1], l4[2], l5[0], l5[1], l5[2], l6[0], l6[1], l6[2]]
b5 = [l4[3], l4[4], l4[5], l5[3], l5[4], l5[5], l6[3], l6[4], l6[5]]
b6 = [l4[6], l4[7], l4[8], l5[6], l5[7], l5[8], l6[6], l6[7], l6[8]]
b7 = [l7[0], l7[1], l7[2], l8[0], l8[1], l8[2], l9[0], l9[1], l9[2]]
b8 = [l7[3], l7[4], l7[5], l8[3], l8[4], l8[5], l9[3], l9[4], l9[5]]
b9 = [l7[6], l7[7], l7[8], l8[6], l8[7], l8[8], l9[6], l9[7], l9[8]]
#todas as colunas
c1 = [l1[0], l2[0], l3[0], l4[0], l5[0], l6[0], l7[0], l8[0], l9[0]]
c2 = [l1[1], l2[1], l3[1], l4[1], l5[1], l6[1], l7[1], l8[1], l9[1]]
c3 = [l1[2], l2[2], l3[2], l4[2], l5[2], l6[2], l7[2], l8[2], l9[2]]
c4 = [l1[3], l2[3], l3[3], l4[3], l5[3], l6[3], l7[3], l8[3], l9[3]]
c5 = [l1[4], l2[4], l3[4], l4[4], l5[4], l6[4], l7[4], l8[4], l9[4]]
c6 = [l1[5], l2[5], l3[5], l4[5], l5[5], l6[5], l7[5], l8[5], l9[5]]
c7 = [l1[6], l2[6], l3[6], l4[6], l5[6], l6[6], l7[6], l8[6], l9[6]]
c8 = [l1[7], l2[7], l3[7], l4[7], l5[7], l6[7], l7[7], l8[7], l9[7]]
c9 = [l1[8], l2[8], l3[8], l4[8], l5[8], l6[8], l7[8], l8[8], l9[8]]
#ll = lista com todas as linhas
lista_linhas = l1, l2, l3, l4, l5, l6, l7, l8, l9
#lc = lista com todas as colunas
lista_colunas = c1, c2, c3, c4, c5, c6, c7, c8, c9
#lb = lista com todos os blocos
lista_blocos = b1, b2, b3, b4, b5, b6, b7, b8, b9
ctd = 0
ctdb = 0
cb = 0
correto = True
for linha in lista_linhas:
for num in linha:
if lista_colunas[ctd].count(num) > 1 or lista_blocos[ctdb].count(num) > 1 or linha.count(num) > 1:
correto = False
ctd += 1
else:
ctd += 1
if ctd == 3:
ctdb += 1
if ctd == 6:
ctdb += 1
if ctd == 8:
cb += 1
ctd -= ctd
ctdb = 0
if cb > 3:
ctdb = 3
if cb > 5:
ctdb = 6
return correto | [
"def",
"verificar_sudoku",
"(",
"sv",
")",
":",
"#todas as linhas",
"l1",
"=",
"sv",
"[",
"0",
"]",
"l2",
"=",
"sv",
"[",
"1",
"]",
"l3",
"=",
"sv",
"[",
"2",
"]",
"l4",
"=",
"sv",
"[",
"3",
"]",
"l5",
"=",
"sv",
"[",
"4",
"]",
"l6",
"=",
"sv",
"[",
"5",
"]",
"l7",
"=",
"sv",
"[",
"6",
"]",
"l8",
"=",
"sv",
"[",
"7",
"]",
"l9",
"=",
"sv",
"[",
"8",
"]",
"#todos os blocos",
"b1",
"=",
"[",
"l1",
"[",
"0",
"]",
",",
"l1",
"[",
"1",
"]",
",",
"l1",
"[",
"2",
"]",
",",
"l2",
"[",
"0",
"]",
",",
"l2",
"[",
"1",
"]",
",",
"l2",
"[",
"2",
"]",
",",
"l3",
"[",
"0",
"]",
",",
"l3",
"[",
"1",
"]",
",",
"l3",
"[",
"2",
"]",
"]",
"b2",
"=",
"[",
"l1",
"[",
"3",
"]",
",",
"l1",
"[",
"4",
"]",
",",
"l1",
"[",
"5",
"]",
",",
"l2",
"[",
"3",
"]",
",",
"l2",
"[",
"4",
"]",
",",
"l2",
"[",
"5",
"]",
",",
"l3",
"[",
"3",
"]",
",",
"l3",
"[",
"4",
"]",
",",
"l3",
"[",
"5",
"]",
"]",
"b3",
"=",
"[",
"l1",
"[",
"6",
"]",
",",
"l1",
"[",
"7",
"]",
",",
"l1",
"[",
"8",
"]",
",",
"l2",
"[",
"6",
"]",
",",
"l2",
"[",
"7",
"]",
",",
"l2",
"[",
"8",
"]",
",",
"l3",
"[",
"6",
"]",
",",
"l3",
"[",
"7",
"]",
",",
"l3",
"[",
"8",
"]",
"]",
"b4",
"=",
"[",
"l4",
"[",
"0",
"]",
",",
"l4",
"[",
"1",
"]",
",",
"l4",
"[",
"2",
"]",
",",
"l5",
"[",
"0",
"]",
",",
"l5",
"[",
"1",
"]",
",",
"l5",
"[",
"2",
"]",
",",
"l6",
"[",
"0",
"]",
",",
"l6",
"[",
"1",
"]",
",",
"l6",
"[",
"2",
"]",
"]",
"b5",
"=",
"[",
"l4",
"[",
"3",
"]",
",",
"l4",
"[",
"4",
"]",
",",
"l4",
"[",
"5",
"]",
",",
"l5",
"[",
"3",
"]",
",",
"l5",
"[",
"4",
"]",
",",
"l5",
"[",
"5",
"]",
",",
"l6",
"[",
"3",
"]",
",",
"l6",
"[",
"4",
"]",
",",
"l6",
"[",
"5",
"]",
"]",
"b6",
"=",
"[",
"l4",
"[",
"6",
"]",
",",
"l4",
"[",
"7",
"]",
",",
"l4",
"[",
"8",
"]",
",",
"l5",
"[",
"6",
"]",
",",
"l5",
"[",
"7",
"]",
",",
"l5",
"[",
"8",
"]",
",",
"l6",
"[",
"6",
"]",
",",
"l6",
"[",
"7",
"]",
",",
"l6",
"[",
"8",
"]",
"]",
"b7",
"=",
"[",
"l7",
"[",
"0",
"]",
",",
"l7",
"[",
"1",
"]",
",",
"l7",
"[",
"2",
"]",
",",
"l8",
"[",
"0",
"]",
",",
"l8",
"[",
"1",
"]",
",",
"l8",
"[",
"2",
"]",
",",
"l9",
"[",
"0",
"]",
",",
"l9",
"[",
"1",
"]",
",",
"l9",
"[",
"2",
"]",
"]",
"b8",
"=",
"[",
"l7",
"[",
"3",
"]",
",",
"l7",
"[",
"4",
"]",
",",
"l7",
"[",
"5",
"]",
",",
"l8",
"[",
"3",
"]",
",",
"l8",
"[",
"4",
"]",
",",
"l8",
"[",
"5",
"]",
",",
"l9",
"[",
"3",
"]",
",",
"l9",
"[",
"4",
"]",
",",
"l9",
"[",
"5",
"]",
"]",
"b9",
"=",
"[",
"l7",
"[",
"6",
"]",
",",
"l7",
"[",
"7",
"]",
",",
"l7",
"[",
"8",
"]",
",",
"l8",
"[",
"6",
"]",
",",
"l8",
"[",
"7",
"]",
",",
"l8",
"[",
"8",
"]",
",",
"l9",
"[",
"6",
"]",
",",
"l9",
"[",
"7",
"]",
",",
"l9",
"[",
"8",
"]",
"]",
"#todas as colunas",
"c1",
"=",
"[",
"l1",
"[",
"0",
"]",
",",
"l2",
"[",
"0",
"]",
",",
"l3",
"[",
"0",
"]",
",",
"l4",
"[",
"0",
"]",
",",
"l5",
"[",
"0",
"]",
",",
"l6",
"[",
"0",
"]",
",",
"l7",
"[",
"0",
"]",
",",
"l8",
"[",
"0",
"]",
",",
"l9",
"[",
"0",
"]",
"]",
"c2",
"=",
"[",
"l1",
"[",
"1",
"]",
",",
"l2",
"[",
"1",
"]",
",",
"l3",
"[",
"1",
"]",
",",
"l4",
"[",
"1",
"]",
",",
"l5",
"[",
"1",
"]",
",",
"l6",
"[",
"1",
"]",
",",
"l7",
"[",
"1",
"]",
",",
"l8",
"[",
"1",
"]",
",",
"l9",
"[",
"1",
"]",
"]",
"c3",
"=",
"[",
"l1",
"[",
"2",
"]",
",",
"l2",
"[",
"2",
"]",
",",
"l3",
"[",
"2",
"]",
",",
"l4",
"[",
"2",
"]",
",",
"l5",
"[",
"2",
"]",
",",
"l6",
"[",
"2",
"]",
",",
"l7",
"[",
"2",
"]",
",",
"l8",
"[",
"2",
"]",
",",
"l9",
"[",
"2",
"]",
"]",
"c4",
"=",
"[",
"l1",
"[",
"3",
"]",
",",
"l2",
"[",
"3",
"]",
",",
"l3",
"[",
"3",
"]",
",",
"l4",
"[",
"3",
"]",
",",
"l5",
"[",
"3",
"]",
",",
"l6",
"[",
"3",
"]",
",",
"l7",
"[",
"3",
"]",
",",
"l8",
"[",
"3",
"]",
",",
"l9",
"[",
"3",
"]",
"]",
"c5",
"=",
"[",
"l1",
"[",
"4",
"]",
",",
"l2",
"[",
"4",
"]",
",",
"l3",
"[",
"4",
"]",
",",
"l4",
"[",
"4",
"]",
",",
"l5",
"[",
"4",
"]",
",",
"l6",
"[",
"4",
"]",
",",
"l7",
"[",
"4",
"]",
",",
"l8",
"[",
"4",
"]",
",",
"l9",
"[",
"4",
"]",
"]",
"c6",
"=",
"[",
"l1",
"[",
"5",
"]",
",",
"l2",
"[",
"5",
"]",
",",
"l3",
"[",
"5",
"]",
",",
"l4",
"[",
"5",
"]",
",",
"l5",
"[",
"5",
"]",
",",
"l6",
"[",
"5",
"]",
",",
"l7",
"[",
"5",
"]",
",",
"l8",
"[",
"5",
"]",
",",
"l9",
"[",
"5",
"]",
"]",
"c7",
"=",
"[",
"l1",
"[",
"6",
"]",
",",
"l2",
"[",
"6",
"]",
",",
"l3",
"[",
"6",
"]",
",",
"l4",
"[",
"6",
"]",
",",
"l5",
"[",
"6",
"]",
",",
"l6",
"[",
"6",
"]",
",",
"l7",
"[",
"6",
"]",
",",
"l8",
"[",
"6",
"]",
",",
"l9",
"[",
"6",
"]",
"]",
"c8",
"=",
"[",
"l1",
"[",
"7",
"]",
",",
"l2",
"[",
"7",
"]",
",",
"l3",
"[",
"7",
"]",
",",
"l4",
"[",
"7",
"]",
",",
"l5",
"[",
"7",
"]",
",",
"l6",
"[",
"7",
"]",
",",
"l7",
"[",
"7",
"]",
",",
"l8",
"[",
"7",
"]",
",",
"l9",
"[",
"7",
"]",
"]",
"c9",
"=",
"[",
"l1",
"[",
"8",
"]",
",",
"l2",
"[",
"8",
"]",
",",
"l3",
"[",
"8",
"]",
",",
"l4",
"[",
"8",
"]",
",",
"l5",
"[",
"8",
"]",
",",
"l6",
"[",
"8",
"]",
",",
"l7",
"[",
"8",
"]",
",",
"l8",
"[",
"8",
"]",
",",
"l9",
"[",
"8",
"]",
"]",
"#ll = lista com todas as linhas",
"lista_linhas",
"=",
"l1",
",",
"l2",
",",
"l3",
",",
"l4",
",",
"l5",
",",
"l6",
",",
"l7",
",",
"l8",
",",
"l9",
"#lc = lista com todas as colunas",
"lista_colunas",
"=",
"c1",
",",
"c2",
",",
"c3",
",",
"c4",
",",
"c5",
",",
"c6",
",",
"c7",
",",
"c8",
",",
"c9",
"#lb = lista com todos os blocos",
"lista_blocos",
"=",
"b1",
",",
"b2",
",",
"b3",
",",
"b4",
",",
"b5",
",",
"b6",
",",
"b7",
",",
"b8",
",",
"b9",
"ctd",
"=",
"0",
"ctdb",
"=",
"0",
"cb",
"=",
"0",
"correto",
"=",
"True",
"for",
"linha",
"in",
"lista_linhas",
":",
"for",
"num",
"in",
"linha",
":",
"if",
"lista_colunas",
"[",
"ctd",
"]",
".",
"count",
"(",
"num",
")",
">",
"1",
"or",
"lista_blocos",
"[",
"ctdb",
"]",
".",
"count",
"(",
"num",
")",
">",
"1",
"or",
"linha",
".",
"count",
"(",
"num",
")",
">",
"1",
":",
"correto",
"=",
"False",
"ctd",
"+=",
"1",
"else",
":",
"ctd",
"+=",
"1",
"if",
"ctd",
"==",
"3",
":",
"ctdb",
"+=",
"1",
"if",
"ctd",
"==",
"6",
":",
"ctdb",
"+=",
"1",
"if",
"ctd",
"==",
"8",
":",
"cb",
"+=",
"1",
"ctd",
"-=",
"ctd",
"ctdb",
"=",
"0",
"if",
"cb",
">",
"3",
":",
"ctdb",
"=",
"3",
"if",
"cb",
">",
"5",
":",
"ctdb",
"=",
"6",
"return",
"correto"
]
| [
539,
0
]
| [
610,
15
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
pega_salada_sobremesa_suco | (items) | return cardapio, items | Funcao auxiliar que popula os atributos salada, sobremesa e suco do cardapio da refeicao fornecida. | Funcao auxiliar que popula os atributos salada, sobremesa e suco do cardapio da refeicao fornecida. | def pega_salada_sobremesa_suco(items):
""" Funcao auxiliar que popula os atributos salada, sobremesa e suco do cardapio da refeicao fornecida."""
alimentos = ["salada", "suco", "sobremesa"]
cardapio = {}
for alim in alimentos:
tag = alim.upper() + ":" # tag para procurar o cardapio dos alimentos acima dentro do vetor items
valor = [s.replace(tag, "") for s in items if tag in s][0] # pega o valor do alimento e ja tira a tag (e.g. "SOBREMESA:")
cardapio[alim] = valor.capitalize() # lowercase eh melhor para exibir.
items = [s for s in items if tag not in s]
return cardapio, items | [
"def",
"pega_salada_sobremesa_suco",
"(",
"items",
")",
":",
"alimentos",
"=",
"[",
"\"salada\"",
",",
"\"suco\"",
",",
"\"sobremesa\"",
"]",
"cardapio",
"=",
"{",
"}",
"for",
"alim",
"in",
"alimentos",
":",
"tag",
"=",
"alim",
".",
"upper",
"(",
")",
"+",
"\":\"",
"# tag para procurar o cardapio dos alimentos acima dentro do vetor items",
"valor",
"=",
"[",
"s",
".",
"replace",
"(",
"tag",
",",
"\"\"",
")",
"for",
"s",
"in",
"items",
"if",
"tag",
"in",
"s",
"]",
"[",
"0",
"]",
"# pega o valor do alimento e ja tira a tag (e.g. \"SOBREMESA:\")",
"cardapio",
"[",
"alim",
"]",
"=",
"valor",
".",
"capitalize",
"(",
")",
"# lowercase eh melhor para exibir.",
"items",
"=",
"[",
"s",
"for",
"s",
"in",
"items",
"if",
"tag",
"not",
"in",
"s",
"]",
"return",
"cardapio",
",",
"items"
]
| [
20,
0
]
| [
32,
26
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
check_fleet_edges | (ai_settins, aliens) | Responde apropriadamente se algum alienigena alcancou uma
borda. | Responde apropriadamente se algum alienigena alcancou uma
borda. | def check_fleet_edges(ai_settins, aliens):
"""Responde apropriadamente se algum alienigena alcancou uma
borda."""
for alien in aliens.sprites():
if alien.check_edges():
change_fleet_direction(ai_settins, aliens)
break | [
"def",
"check_fleet_edges",
"(",
"ai_settins",
",",
"aliens",
")",
":",
"for",
"alien",
"in",
"aliens",
".",
"sprites",
"(",
")",
":",
"if",
"alien",
".",
"check_edges",
"(",
")",
":",
"change_fleet_direction",
"(",
"ai_settins",
",",
"aliens",
")",
"break"
]
| [
186,
0
]
| [
192,
17
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
PropKB.tell | (self, sentence) | Adicione as cláusulas da sentença ao KB. | Adicione as cláusulas da sentença ao KB. | def tell(self, sentence):
"Adicione as cláusulas da sentença ao KB."
self.clauses.extend(conjuncts(to_cnf(sentence))) | [
"def",
"tell",
"(",
"self",
",",
"sentence",
")",
":",
"self",
".",
"clauses",
".",
"extend",
"(",
"conjuncts",
"(",
"to_cnf",
"(",
"sentence",
")",
")",
")"
]
| [
79,
4
]
| [
81,
56
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
EGrupo.update | (cls, authenticated_user, pk, **kwargs) | Atualiza os dados de um grupo de equipamento.
@return: Nothing.
@raise GrupoError: Falha ao inserir o grupo.
@raise EGrupoNotFoundError: Grupo de equipamento não cadastrado.
@raise EGrupoNameDuplicatedError: Grupo de equipamento com o nome já cadastrado.
| Atualiza os dados de um grupo de equipamento. | def update(cls, authenticated_user, pk, **kwargs):
"""Atualiza os dados de um grupo de equipamento.
@return: Nothing.
@raise GrupoError: Falha ao inserir o grupo.
@raise EGrupoNotFoundError: Grupo de equipamento não cadastrado.
@raise EGrupoNameDuplicatedError: Grupo de equipamento com o nome já cadastrado.
"""
egrupo = EGrupo.get_by_pk(pk)
try:
try:
nome = kwargs['nome']
if (egrupo.nome.lower() != nome.lower()):
EGrupo.objects.get(nome__iexact=nome)
raise EGrupoNameDuplicatedError(
None, u'Grupo de equipamento com o nome %s já cadastrado' % nome)
except (EGrupo.DoesNotExist, KeyError):
pass
egrupo.__dict__.update(kwargs)
egrupo.save(authenticated_user)
except EGrupoNameDuplicatedError, e:
raise e
except Exception, e:
cls.log.error(u'Falha ao atualizar o grupo de equipamento.')
raise GrupoError(e, u'Falha ao atualizar o grupo de equipamento.') | [
"def",
"update",
"(",
"cls",
",",
"authenticated_user",
",",
"pk",
",",
"*",
"*",
"kwargs",
")",
":",
"egrupo",
"=",
"EGrupo",
".",
"get_by_pk",
"(",
"pk",
")",
"try",
":",
"try",
":",
"nome",
"=",
"kwargs",
"[",
"'nome'",
"]",
"if",
"(",
"egrupo",
".",
"nome",
".",
"lower",
"(",
")",
"!=",
"nome",
".",
"lower",
"(",
")",
")",
":",
"EGrupo",
".",
"objects",
".",
"get",
"(",
"nome__iexact",
"=",
"nome",
")",
"raise",
"EGrupoNameDuplicatedError",
"(",
"None",
",",
"u'Grupo de equipamento com o nome %s já cadastrado' ",
" ",
"ome)",
"",
"except",
"(",
"EGrupo",
".",
"DoesNotExist",
",",
"KeyError",
")",
":",
"pass",
"egrupo",
".",
"__dict__",
".",
"update",
"(",
"kwargs",
")",
"egrupo",
".",
"save",
"(",
"authenticated_user",
")",
"except",
"EGrupoNameDuplicatedError",
",",
"e",
":",
"raise",
"e",
"except",
"Exception",
",",
"e",
":",
"cls",
".",
"log",
".",
"error",
"(",
"u'Falha ao atualizar o grupo de equipamento.'",
")",
"raise",
"GrupoError",
"(",
"e",
",",
"u'Falha ao atualizar o grupo de equipamento.'",
")"
]
| [
368,
4
]
| [
398,
78
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
EquipamentoResource.handle_get | (self, request, user, *args, **kwargs) | Trata requisições GET para consulta de equipamentos.
Permite a consulta de equipamento filtrado por nome,
equipamentos filtrados por tipo de equipamento e ambiente
URLs: /equipamento/nome/<nome_equip>/
/equipamento/id/<id_equip>/
/equipamento/tipoequipamento/<id_tipo_equip>/ambiente/<id_ambiente>/
| Trata requisições GET para consulta de equipamentos. | def handle_get(self, request, user, *args, **kwargs):
"""Trata requisições GET para consulta de equipamentos.
Permite a consulta de equipamento filtrado por nome,
equipamentos filtrados por tipo de equipamento e ambiente
URLs: /equipamento/nome/<nome_equip>/
/equipamento/id/<id_equip>/
/equipamento/tipoequipamento/<id_tipo_equip>/ambiente/<id_ambiente>/
"""
try:
equipment_name = kwargs.get('nome_equip')
equipment_id = kwargs.get('id_equip')
equipment_type_id = kwargs.get('id_tipo_equip')
environment_id = kwargs.get('id_ambiente')
if (equipment_id is None) and (equipment_name is None) and (equipment_type_id is None or environment_id is None):
return super(EquipamentoResource, self).handle_get(request, user, *args, **kwargs)
equipments = []
if equipment_id is not None:
if not is_valid_int_greater_zero_param(equipment_id):
self.log.error(
u'The equipment_id parameter is not a valid value: %s.', equipment_id)
raise InvalidValueError(None, 'equipment_id', equipment_id)
equipment = Equipamento.get_by_pk(int(equipment_id))
if not has_perm(user,
AdminPermission.EQUIPMENT_MANAGEMENT,
AdminPermission.READ_OPERATION,
None,
equipment.id,
AdminPermission.EQUIP_READ_OPERATION):
return self.not_authorized()
equipments.append(equipment)
elif equipment_name is not None:
equipment = Equipamento.get_by_name(equipment_name)
if not has_perm(user,
AdminPermission.EQUIPMENT_MANAGEMENT,
AdminPermission.READ_OPERATION,
None,
equipment.id,
AdminPermission.EQUIP_READ_OPERATION):
return self.not_authorized()
equipments.append(equipment)
else:
if not has_perm(user,
AdminPermission.EQUIPMENT_MANAGEMENT,
AdminPermission.READ_OPERATION):
return self.not_authorized()
if not is_valid_int_greater_zero_param(environment_id):
self.log.error(
u'The environment_id parameter is not a valid value: %s.', environment_id)
raise InvalidValueError(
None, 'environment_id', environment_id)
if not is_valid_int_greater_zero_param(equipment_type_id):
self.log.error(
u'The equipment_type_id parameter is not a valid value: %s.', equipment_type_id)
raise InvalidValueError(
None, 'equipment_type_id', equipment_type_id)
Ambiente.get_by_pk(environment_id)
TipoEquipamento.get_by_pk(equipment_type_id)
equipments = Equipamento().search(
None, equipment_type_id, environment_id, user.grupos.all())
map_list = []
for equipment in equipments:
equip_map = dict()
equip_map['id'] = equipment.id
equip_map['nome'] = equipment.nome
equip_map[
'id_tipo_equipamento'] = equipment.tipo_equipamento.id
equip_map[
'nome_tipo_equipamento'] = equipment.tipo_equipamento.tipo_equipamento
equip_map['id_modelo'] = equipment.modelo.id
equip_map['nome_modelo'] = equipment.modelo.nome
equip_map['id_marca'] = equipment.modelo.marca.id
equip_map['nome_marca'] = equipment.modelo.marca.nome
equip_map['maintenance'] = equipment.maintenance
map_list.append(equip_map)
return self.response(dumps_networkapi({'equipamento': map_list}))
except InvalidValueError, e:
return self.response_error(269, e.param, e.value)
except EquipamentoNotFoundError:
return self.response_error(117, equipment_name)
except AmbienteNotFoundError:
return self.response_error(112)
except TipoEquipamentoNotFoundError:
return self.response_error(100)
except (EquipamentoError, GrupoError):
return self.response_error(1) | [
"def",
"handle_get",
"(",
"self",
",",
"request",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"equipment_name",
"=",
"kwargs",
".",
"get",
"(",
"'nome_equip'",
")",
"equipment_id",
"=",
"kwargs",
".",
"get",
"(",
"'id_equip'",
")",
"equipment_type_id",
"=",
"kwargs",
".",
"get",
"(",
"'id_tipo_equip'",
")",
"environment_id",
"=",
"kwargs",
".",
"get",
"(",
"'id_ambiente'",
")",
"if",
"(",
"equipment_id",
"is",
"None",
")",
"and",
"(",
"equipment_name",
"is",
"None",
")",
"and",
"(",
"equipment_type_id",
"is",
"None",
"or",
"environment_id",
"is",
"None",
")",
":",
"return",
"super",
"(",
"EquipamentoResource",
",",
"self",
")",
".",
"handle_get",
"(",
"request",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"equipments",
"=",
"[",
"]",
"if",
"equipment_id",
"is",
"not",
"None",
":",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"equipment_id",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'The equipment_id parameter is not a valid value: %s.'",
",",
"equipment_id",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'equipment_id'",
",",
"equipment_id",
")",
"equipment",
"=",
"Equipamento",
".",
"get_by_pk",
"(",
"int",
"(",
"equipment_id",
")",
")",
"if",
"not",
"has_perm",
"(",
"user",
",",
"AdminPermission",
".",
"EQUIPMENT_MANAGEMENT",
",",
"AdminPermission",
".",
"READ_OPERATION",
",",
"None",
",",
"equipment",
".",
"id",
",",
"AdminPermission",
".",
"EQUIP_READ_OPERATION",
")",
":",
"return",
"self",
".",
"not_authorized",
"(",
")",
"equipments",
".",
"append",
"(",
"equipment",
")",
"elif",
"equipment_name",
"is",
"not",
"None",
":",
"equipment",
"=",
"Equipamento",
".",
"get_by_name",
"(",
"equipment_name",
")",
"if",
"not",
"has_perm",
"(",
"user",
",",
"AdminPermission",
".",
"EQUIPMENT_MANAGEMENT",
",",
"AdminPermission",
".",
"READ_OPERATION",
",",
"None",
",",
"equipment",
".",
"id",
",",
"AdminPermission",
".",
"EQUIP_READ_OPERATION",
")",
":",
"return",
"self",
".",
"not_authorized",
"(",
")",
"equipments",
".",
"append",
"(",
"equipment",
")",
"else",
":",
"if",
"not",
"has_perm",
"(",
"user",
",",
"AdminPermission",
".",
"EQUIPMENT_MANAGEMENT",
",",
"AdminPermission",
".",
"READ_OPERATION",
")",
":",
"return",
"self",
".",
"not_authorized",
"(",
")",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"environment_id",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'The environment_id parameter is not a valid value: %s.'",
",",
"environment_id",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'environment_id'",
",",
"environment_id",
")",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"equipment_type_id",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'The equipment_type_id parameter is not a valid value: %s.'",
",",
"equipment_type_id",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'equipment_type_id'",
",",
"equipment_type_id",
")",
"Ambiente",
".",
"get_by_pk",
"(",
"environment_id",
")",
"TipoEquipamento",
".",
"get_by_pk",
"(",
"equipment_type_id",
")",
"equipments",
"=",
"Equipamento",
"(",
")",
".",
"search",
"(",
"None",
",",
"equipment_type_id",
",",
"environment_id",
",",
"user",
".",
"grupos",
".",
"all",
"(",
")",
")",
"map_list",
"=",
"[",
"]",
"for",
"equipment",
"in",
"equipments",
":",
"equip_map",
"=",
"dict",
"(",
")",
"equip_map",
"[",
"'id'",
"]",
"=",
"equipment",
".",
"id",
"equip_map",
"[",
"'nome'",
"]",
"=",
"equipment",
".",
"nome",
"equip_map",
"[",
"'id_tipo_equipamento'",
"]",
"=",
"equipment",
".",
"tipo_equipamento",
".",
"id",
"equip_map",
"[",
"'nome_tipo_equipamento'",
"]",
"=",
"equipment",
".",
"tipo_equipamento",
".",
"tipo_equipamento",
"equip_map",
"[",
"'id_modelo'",
"]",
"=",
"equipment",
".",
"modelo",
".",
"id",
"equip_map",
"[",
"'nome_modelo'",
"]",
"=",
"equipment",
".",
"modelo",
".",
"nome",
"equip_map",
"[",
"'id_marca'",
"]",
"=",
"equipment",
".",
"modelo",
".",
"marca",
".",
"id",
"equip_map",
"[",
"'nome_marca'",
"]",
"=",
"equipment",
".",
"modelo",
".",
"marca",
".",
"nome",
"equip_map",
"[",
"'maintenance'",
"]",
"=",
"equipment",
".",
"maintenance",
"map_list",
".",
"append",
"(",
"equip_map",
")",
"return",
"self",
".",
"response",
"(",
"dumps_networkapi",
"(",
"{",
"'equipamento'",
":",
"map_list",
"}",
")",
")",
"except",
"InvalidValueError",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"269",
",",
"e",
".",
"param",
",",
"e",
".",
"value",
")",
"except",
"EquipamentoNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"117",
",",
"equipment_name",
")",
"except",
"AmbienteNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"112",
")",
"except",
"TipoEquipamentoNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"100",
")",
"except",
"(",
"EquipamentoError",
",",
"GrupoError",
")",
":",
"return",
"self",
".",
"response_error",
"(",
"1",
")"
]
| [
245,
4
]
| [
348,
41
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
reverse_lookup | (d, v) | return out | Retorna uma lista com as chaves do dicionário 'd' que apontam para um determinado valor 'v'.
Args:
d (dict): dicionário no qual queremos encontrar todas as chaves para o valor 'v'.
v (any): valor pelo qual desejamos encontrar as chaves correspondentes no dicionário 'd'.
Returns:
list: Todas as chaves referentes ao valor 'v' presente no dicionário 'd'.
| Retorna uma lista com as chaves do dicionário 'd' que apontam para um determinado valor 'v'. | def reverse_lookup(d, v):
"""Retorna uma lista com as chaves do dicionário 'd' que apontam para um determinado valor 'v'.
Args:
d (dict): dicionário no qual queremos encontrar todas as chaves para o valor 'v'.
v (any): valor pelo qual desejamos encontrar as chaves correspondentes no dicionário 'd'.
Returns:
list: Todas as chaves referentes ao valor 'v' presente no dicionário 'd'.
"""
out = []
for key, value in d.items():
if value == v:
out.append(key)
return out | [
"def",
"reverse_lookup",
"(",
"d",
",",
"v",
")",
":",
"out",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"d",
".",
"items",
"(",
")",
":",
"if",
"value",
"==",
"v",
":",
"out",
".",
"append",
"(",
"key",
")",
"return",
"out"
]
| [
6,
0
]
| [
21,
14
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Scoreboard.prep_ships | (self) | Mostra quantas espaçonaves restam | Mostra quantas espaçonaves restam | def prep_ships(self):
"""Mostra quantas espaçonaves restam"""
self.ships = Group()
for ship_number in range(self.stats.ships_left):
ship = Ship(self.ai_settings, self.screen)
ship.rect.x = 10 + ship_number * ship.rect.width
ship.rect.y = 10
self.ships.add(ship) | [
"def",
"prep_ships",
"(",
"self",
")",
":",
"self",
".",
"ships",
"=",
"Group",
"(",
")",
"for",
"ship_number",
"in",
"range",
"(",
"self",
".",
"stats",
".",
"ships_left",
")",
":",
"ship",
"=",
"Ship",
"(",
"self",
".",
"ai_settings",
",",
"self",
".",
"screen",
")",
"ship",
".",
"rect",
".",
"x",
"=",
"10",
"+",
"ship_number",
"*",
"ship",
".",
"rect",
".",
"width",
"ship",
".",
"rect",
".",
"y",
"=",
"10",
"self",
".",
"ships",
".",
"add",
"(",
"ship",
")"
]
| [
58,
4
]
| [
65,
32
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
IpResource.handle_post | (self, request, user, *args, **kwargs) | Trata as requisições de POST para inserir um IP e associá-lo a um equipamento.
URL: ip/
| Trata as requisições de POST para inserir um IP e associá-lo a um equipamento. | def handle_post(self, request, user, *args, **kwargs):
"""Trata as requisições de POST para inserir um IP e associá-lo a um equipamento.
URL: ip/
"""
try:
xml_map, attrs_map = loads(request.raw_post_data)
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.')
ip_map = networkapi_map.get('ip')
if ip_map is None:
return self.response_error(3, u'Não existe valor para a tag ip do XML de requisição.')
try:
response = insert_ip(ip_map, user)
if response[0] == 0:
return self.response(dumps_networkapi({'ip': response[1]}))
else:
return self.response_error(response[0])
except InvalidValueError, e:
return self.response_error(269, e.param, e.value)
except VlanNotFoundError:
return self.response_error(116)
except NetworkIPv4NotFoundError, e:
return self.response_error(281)
except EquipamentoNotFoundError:
return self.response_error(117, ip_map.get('id_equipamento'))
except IpNotAvailableError, e:
return self.response_error(150, e.message)
except UserNotAuthorizedError:
return self.not_authorized()
except (IpError, VlanError, EquipamentoError, GrupoError), e:
return self.response_error(1, e)
except Exception, e:
return self.response_error(1, e) | [
"def",
"handle_post",
"(",
"self",
",",
"request",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"xml_map",
",",
"attrs_map",
"=",
"loads",
"(",
"request",
".",
"raw_post_data",
")",
"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.')",
"",
"ip_map",
"=",
"networkapi_map",
".",
"get",
"(",
"'ip'",
")",
"if",
"ip_map",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"u'Não existe valor para a tag ip do XML de requisição.')",
"",
"try",
":",
"response",
"=",
"insert_ip",
"(",
"ip_map",
",",
"user",
")",
"if",
"response",
"[",
"0",
"]",
"==",
"0",
":",
"return",
"self",
".",
"response",
"(",
"dumps_networkapi",
"(",
"{",
"'ip'",
":",
"response",
"[",
"1",
"]",
"}",
")",
")",
"else",
":",
"return",
"self",
".",
"response_error",
"(",
"response",
"[",
"0",
"]",
")",
"except",
"InvalidValueError",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"269",
",",
"e",
".",
"param",
",",
"e",
".",
"value",
")",
"except",
"VlanNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"116",
")",
"except",
"NetworkIPv4NotFoundError",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"281",
")",
"except",
"EquipamentoNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"117",
",",
"ip_map",
".",
"get",
"(",
"'id_equipamento'",
")",
")",
"except",
"IpNotAvailableError",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"150",
",",
"e",
".",
"message",
")",
"except",
"UserNotAuthorizedError",
":",
"return",
"self",
".",
"not_authorized",
"(",
")",
"except",
"(",
"IpError",
",",
"VlanError",
",",
"EquipamentoError",
",",
"GrupoError",
")",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"1",
",",
"e",
")",
"except",
"Exception",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"1",
",",
"e",
")"
]
| [
234,
4
]
| [
275,
44
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
process_issues | (**context) | Processa uma lista de issues carregadas a partir do resultado
de leitura da base MST | Processa uma lista de issues carregadas a partir do resultado
de leitura da base MST | def process_issues(**context):
"""Processa uma lista de issues carregadas a partir do resultado
de leitura da base MST"""
issue_json_path = context["ti"].xcom_pull(
task_ids="copy_mst_bases_to_work_folder_task", key="issue_json_path"
)
with open(issue_json_path, "r") as f:
issues = f.read()
logging.info("reading file from %s." % (issue_json_path))
issues = json.loads(issues)
issues = [Issue({"issue": data}) for data in issues]
issues = filter_issues(issues)
issues_as_kernel = [issue_as_kernel(issue) for issue in issues]
for issue in issues_as_kernel:
_id = issue.pop("_id")
register_or_update(_id, issue, KERNEL_API_BUNDLES_ENDPOINT) | [
"def",
"process_issues",
"(",
"*",
"*",
"context",
")",
":",
"issue_json_path",
"=",
"context",
"[",
"\"ti\"",
"]",
".",
"xcom_pull",
"(",
"task_ids",
"=",
"\"copy_mst_bases_to_work_folder_task\"",
",",
"key",
"=",
"\"issue_json_path\"",
")",
"with",
"open",
"(",
"issue_json_path",
",",
"\"r\"",
")",
"as",
"f",
":",
"issues",
"=",
"f",
".",
"read",
"(",
")",
"logging",
".",
"info",
"(",
"\"reading file from %s.\"",
"%",
"(",
"issue_json_path",
")",
")",
"issues",
"=",
"json",
".",
"loads",
"(",
"issues",
")",
"issues",
"=",
"[",
"Issue",
"(",
"{",
"\"issue\"",
":",
"data",
"}",
")",
"for",
"data",
"in",
"issues",
"]",
"issues",
"=",
"filter_issues",
"(",
"issues",
")",
"issues_as_kernel",
"=",
"[",
"issue_as_kernel",
"(",
"issue",
")",
"for",
"issue",
"in",
"issues",
"]",
"for",
"issue",
"in",
"issues_as_kernel",
":",
"_id",
"=",
"issue",
".",
"pop",
"(",
"\"_id\"",
")",
"register_or_update",
"(",
"_id",
",",
"issue",
",",
"KERNEL_API_BUNDLES_ENDPOINT",
")"
]
| [
303,
0
]
| [
322,
67
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Anuncio.compartilhamentos | (self) | return int(compartilhamentos) | Retorna a quantidade máxima de compartilhamentos do anúncio | Retorna a quantidade máxima de compartilhamentos do anúncio | def compartilhamentos(self) -> int:
"""Retorna a quantidade máxima de compartilhamentos do anúncio"""
compartilhamentos = converte_cliques_em_compartilhamentos(self.cliques)
return int(compartilhamentos) | [
"def",
"compartilhamentos",
"(",
"self",
")",
"->",
"int",
":",
"compartilhamentos",
"=",
"converte_cliques_em_compartilhamentos",
"(",
"self",
".",
"cliques",
")",
"return",
"int",
"(",
"compartilhamentos",
")"
]
| [
102,
4
]
| [
105,
37
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
update_aliens | (ai_settings, screen, stats, sb, ship, aliens, bullets) | Verifica se a frota está em uma das bordas
e então atualiza as posições de todos os alienigenas da frota | Verifica se a frota está em uma das bordas
e então atualiza as posições de todos os alienigenas da frota | def update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets):
"""Verifica se a frota está em uma das bordas
e então atualiza as posições de todos os alienigenas da frota"""
check_fleet_edges(ai_settings, aliens)
aliens.update()
# Verifica se houve colisões entre alienigenas e a espaçonave
if pygame.sprite.spritecollideany(ship, aliens):
ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets)
# Verifica se há algum alien que atingiu a parte inferior da tela
check_aliens_bottom(ai_settings, screen, stats, sb, ship, aliens, bullets) | [
"def",
"update_aliens",
"(",
"ai_settings",
",",
"screen",
",",
"stats",
",",
"sb",
",",
"ship",
",",
"aliens",
",",
"bullets",
")",
":",
"check_fleet_edges",
"(",
"ai_settings",
",",
"aliens",
")",
"aliens",
".",
"update",
"(",
")",
"# Verifica se houve colisões entre alienigenas e a espaçonave",
"if",
"pygame",
".",
"sprite",
".",
"spritecollideany",
"(",
"ship",
",",
"aliens",
")",
":",
"ship_hit",
"(",
"ai_settings",
",",
"screen",
",",
"stats",
",",
"sb",
",",
"ship",
",",
"aliens",
",",
"bullets",
")",
"# Verifica se há algum alien que atingiu a parte inferior da tela",
"check_aliens_bottom",
"(",
"ai_settings",
",",
"screen",
",",
"stats",
",",
"sb",
",",
"ship",
",",
"aliens",
",",
"bullets",
")"
]
| [
248,
0
]
| [
259,
78
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
create_stage_file | (stage_file_path) | Cria um arquivo para conter a lista de estágios
já realizados | Cria um arquivo para conter a lista de estágios
já realizados | def create_stage_file(stage_file_path):
"""Cria um arquivo para conter a lista de estágios
já realizados"""
directory = os.path.dirname(stage_file_path)
if not os.path.exists(directory):
os.makedirs(directory, exist_ok=True)
register_latest_stage(stage_file_path, "") | [
"def",
"create_stage_file",
"(",
"stage_file_path",
")",
":",
"directory",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"stage_file_path",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"directory",
")",
":",
"os",
".",
"makedirs",
"(",
"directory",
",",
"exist_ok",
"=",
"True",
")",
"register_latest_stage",
"(",
"stage_file_path",
",",
"\"\"",
")"
]
| [
133,
0
]
| [
141,
46
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
montar_tabuleiro | (matriz) | Monta um tabuleiro de 2048 a partir de
uma matriz. | Monta um tabuleiro de 2048 a partir de
uma matriz. | def montar_tabuleiro(matriz):
""" Monta um tabuleiro de 2048 a partir de
uma matriz."""
#dimensões da matriz
len_linha = len(matriz)
len_coluna = len(matriz[0])
print("-"*49)
for linha in range(len_linha):
for coluna in range(len_coluna):
if matriz[linha][coluna] != 0:
elemento = f"|{matriz[linha][coluna]:^15}"
else:
elemento = f"|{'-':^15}"
print(elemento,end="")
print("|")
print("-"*49) | [
"def",
"montar_tabuleiro",
"(",
"matriz",
")",
":",
"#dimensões da matriz",
"len_linha",
"=",
"len",
"(",
"matriz",
")",
"len_coluna",
"=",
"len",
"(",
"matriz",
"[",
"0",
"]",
")",
"print",
"(",
"\"-\"",
"*",
"49",
")",
"for",
"linha",
"in",
"range",
"(",
"len_linha",
")",
":",
"for",
"coluna",
"in",
"range",
"(",
"len_coluna",
")",
":",
"if",
"matriz",
"[",
"linha",
"]",
"[",
"coluna",
"]",
"!=",
"0",
":",
"elemento",
"=",
"f\"|{matriz[linha][coluna]:^15}\"",
"else",
":",
"elemento",
"=",
"f\"|{'-':^15}\"",
"print",
"(",
"elemento",
",",
"end",
"=",
"\"\"",
")",
"print",
"(",
"\"|\"",
")",
"print",
"(",
"\"-\"",
"*",
"49",
")"
]
| [
7,
0
]
| [
22,
21
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
AmbienteResource.handle_put | (self, request, user, *args, **kwargs) | Trata requisições PUT para alterar um Ambiente.
URL: ambiente/<id_ambiente>/
| Trata requisições PUT para alterar um Ambiente. | def handle_put(self, request, user, *args, **kwargs):
"""Trata requisições PUT para alterar um Ambiente.
URL: ambiente/<id_ambiente>/
"""
try:
environment_id = kwargs.get('id_ambiente')
if not is_valid_int_greater_zero_param(environment_id):
self.log.error(
u'The environment_id parameter is not a valid value: %s.', environment_id)
raise InvalidValueError(None, 'environment_id', environment_id)
if not has_perm(user,
AdminPermission.ENVIRONMENT_MANAGEMENT,
AdminPermission.WRITE_OPERATION):
return self.not_authorized()
xml_map, attrs_map = loads(request.raw_post_data)
self.log.debug('XML_MAP: %s', xml_map)
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.')
environment_map = networkapi_map.get('ambiente')
if environment_map is None:
return self.response_error(3, u'Não existe valor para a tag ambiente do XML de requisição.')
l3_group_id = environment_map.get('id_grupo_l3')
if not is_valid_int_greater_zero_param(l3_group_id):
self.log.error(
u'The l3_group_id parameter is not a valid value: %s.', l3_group_id)
raise InvalidValueError(None, 'l3_group_id', l3_group_id)
else:
l3_group_id = int(l3_group_id)
GrupoL3.get_by_pk(l3_group_id)
logic_environment_id = environment_map.get('id_ambiente_logico')
if not is_valid_int_greater_zero_param(logic_environment_id):
self.log.error(
u'The logic_environment_id parameter is not a valid value: %s.', logic_environment_id)
raise InvalidValueError(
None, 'logic_environment_id', logic_environment_id)
else:
logic_environment_id = int(logic_environment_id)
AmbienteLogico.get_by_pk(logic_environment_id)
dc_division_id = environment_map.get('id_divisao')
if not is_valid_int_greater_zero_param(dc_division_id):
self.log.error(
u'The dc_division_id parameter is not a valid value: %s.', dc_division_id)
raise InvalidValueError(None, 'dc_division_id', dc_division_id)
else:
dc_division_id = int(dc_division_id)
DivisaoDc.get_by_pk(dc_division_id)
link = environment_map.get('link')
if not is_valid_string_maxsize(link, 200, False):
self.log.error(u'Parameter link is invalid. Value: %s', link)
raise InvalidValueError(None, 'link', link)
vrf = environment_map.get('vrf')
if not is_valid_string_maxsize(link, 100, False):
self.log.error(u'Parameter vrf is invalid. Value: %s', vrf)
raise InvalidValueError(None, 'vrf', vrf)
filter_id = environment_map.get('id_filter')
if filter_id is not None:
if not is_valid_int_greater_zero_param(filter_id):
self.log.error(
u'Parameter filter_id is invalid. Value: %s.', filter_id)
raise InvalidValueError(None, 'filter_id', filter_id)
filter_id = int(filter_id)
# Filter must exist
Filter.get_by_pk(filter_id)
acl_path = environment_map.get('acl_path')
if not is_valid_string_maxsize(acl_path, 250, False):
self.log.error(
u'Parameter acl_path is invalid. Value: %s', acl_path)
raise InvalidValueError(None, 'acl_path', acl_path)
ipv4_template = environment_map.get('ipv4_template')
if not is_valid_string_maxsize(ipv4_template, 250, False):
self.log.error(
u'Parameter ipv4_template is invalid. Value: %s', ipv4_template)
raise InvalidValueError(None, 'ipv4_template', ipv4_template)
ipv6_template = environment_map.get('ipv6_template')
if not is_valid_string_maxsize(ipv6_template, 250, False):
self.log.error(
u'Parameter ipv6_template is invalid. Value: %s', ipv6_template)
raise InvalidValueError(None, 'ipv6_template', ipv6_template)
max_num_vlan_1 = environment_map.get('max_num_vlan_1')
min_num_vlan_1 = environment_map.get('min_num_vlan_1')
max_num_vlan_2 = environment_map.get('max_num_vlan_2')
min_num_vlan_2 = environment_map.get('min_num_vlan_2')
# validate max_num_vlan_1 and min_num_vlan_1
if (max_num_vlan_1 is not None and min_num_vlan_1 is None) or (min_num_vlan_1 is not None and max_num_vlan_1 is None):
self.log.error(
u'Parameters min_num_vlan_1, max_num_vlan_1 is invalid. Values: %s, %s', (min_num_vlan_1, max_num_vlan_1))
raise InvalidValueError(
None, 'min_num_vlan_1, max_num_vlan_1', min_num_vlan_1 + ',' + max_num_vlan_1)
if max_num_vlan_1 is not None and min_num_vlan_1 is not None:
max_num_vlan_1 = int(max_num_vlan_1)
min_num_vlan_1 = int(min_num_vlan_1)
if max_num_vlan_1 < 1 or min_num_vlan_1 < 1:
self.log.error(
u'Parameters min_num_vlan_1, max_num_vlan_1 is invalid. Values: %s, %s', (min_num_vlan_1, max_num_vlan_1))
raise InvalidValueError(
None, 'min_num_vlan_1, max_num_vlan_1', min_num_vlan_1 + ',' + max_num_vlan_1)
if max_num_vlan_1 <= min_num_vlan_1:
self.log.error(
u'Parameters min_num_vlan_1, max_num_vlan_1 is invalid. Values: %s, %s', (min_num_vlan_1, max_num_vlan_1))
raise InvalidValueError(
None, 'min_num_vlan_1, max_num_vlan_1', min_num_vlan_1 + ',' + max_num_vlan_1)
else:
max_num_vlan_1 = max_num_vlan_2
min_num_vlan_1 = min_num_vlan_2
# validate max_num_vlan_1 and min_num_vlan_1
# validate max_num_vlan_2 and min_num_vlan_2
if (max_num_vlan_2 is not None and min_num_vlan_2 is None) or (min_num_vlan_2 is not None and max_num_vlan_2 is None):
self.log.error(
u'Parameters min_num_vlan_2, max_num_vlan_2 is invalid. Values: %s, %s', (min_num_vlan_2, max_num_vlan_2))
raise InvalidValueError(
None, 'min_num_vlan_2, max_num_vlan_2', min_num_vlan_2 + ',' + max_num_vlan_1)
if max_num_vlan_2 is not None and min_num_vlan_2 is not None:
max_num_vlan_2 = int(max_num_vlan_2)
min_num_vlan_2 = int(min_num_vlan_2)
max_num_vlan_1 = int(max_num_vlan_1)
min_num_vlan_1 = int(min_num_vlan_1)
if max_num_vlan_2 < 1 or min_num_vlan_2 < 1:
self.log.error(
u'Parameters min_num_vlan_2, max_num_vlan_2 is invalid. Values: %s, %s', (min_num_vlan_2, max_num_vlan_2))
raise InvalidValueError(
None, 'min_num_vlan_2, max_num_vlan_2', min_num_vlan_2 + ',' + max_num_vlan_1)
if max_num_vlan_2 <= min_num_vlan_2:
self.log.error(
u'Parameters min_num_vlan_2, max_num_vlan_2 is invalid. Values: %s, %s', (min_num_vlan_2, max_num_vlan_2))
raise InvalidValueError(
None, 'min_num_vlan_2, max_num_vlan_2', min_num_vlan_2 + ',' + max_num_vlan_1)
else:
max_num_vlan_2 = max_num_vlan_1
min_num_vlan_2 = min_num_vlan_1
# validate max_num_vlan_2 and min_num_vlan_2
with distributedlock(LOCK_ENVIRONMENT % environment_id):
# Delete vlan's cache
key_list_db = Vlan.objects.filter(ambiente__pk=environment_id)
key_list = []
for key in key_list_db:
key_list.append(key.id)
destroy_cache_function(key_list)
# Destroy equipment's cache
equip_id_list = []
envr = Ambiente.get_by_pk(environment_id)
for equipment in envr.equipamentoambiente_set.all():
equip_id_list.append(equipment.equipamento_id)
destroy_cache_function(equip_id_list, True)
Ambiente.update(user,
environment_id,
grupo_l3_id=l3_group_id,
ambiente_logico_id=logic_environment_id,
divisao_dc_id=dc_division_id,
filter_id=filter_id,
link=link,
vrf=vrf,
acl_path=fix_acl_path(acl_path),
ipv4_template=ipv4_template,
ipv6_template=ipv6_template,
max_num_vlan_1=max_num_vlan_1,
min_num_vlan_1=min_num_vlan_1,
max_num_vlan_2=max_num_vlan_2,
min_num_vlan_2=min_num_vlan_2)
return self.response(dumps_networkapi({}))
except InvalidValueError, e:
return self.response_error(269, e.param, e.value)
except FilterNotFoundError, e:
return self.response_error(339)
except GroupL3NotFoundError:
return self.response_error(160, l3_group_id)
except AmbienteNotFoundError:
return self.response_error(112)
except AmbienteLogicoNotFoundError:
return self.response_error(162, logic_environment_id)
except AmbienteDuplicatedError:
return self.response_error(219)
except DivisaoDcNotFoundError:
return self.response_error(164, dc_division_id)
except CannotDissociateFilterError, e:
return self.response_error(349, e.cause)
except XMLError, x:
self.log.error(u'Erro ao ler o XML da requisicao.')
return self.response_error(3, x)
except (AmbienteError, GrupoError):
return self.response_error(1) | [
"def",
"handle_put",
"(",
"self",
",",
"request",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"environment_id",
"=",
"kwargs",
".",
"get",
"(",
"'id_ambiente'",
")",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"environment_id",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'The environment_id parameter is not a valid value: %s.'",
",",
"environment_id",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'environment_id'",
",",
"environment_id",
")",
"if",
"not",
"has_perm",
"(",
"user",
",",
"AdminPermission",
".",
"ENVIRONMENT_MANAGEMENT",
",",
"AdminPermission",
".",
"WRITE_OPERATION",
")",
":",
"return",
"self",
".",
"not_authorized",
"(",
")",
"xml_map",
",",
"attrs_map",
"=",
"loads",
"(",
"request",
".",
"raw_post_data",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'XML_MAP: %s'",
",",
"xml_map",
")",
"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.')",
"",
"environment_map",
"=",
"networkapi_map",
".",
"get",
"(",
"'ambiente'",
")",
"if",
"environment_map",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"u'Não existe valor para a tag ambiente do XML de requisição.')",
"",
"l3_group_id",
"=",
"environment_map",
".",
"get",
"(",
"'id_grupo_l3'",
")",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"l3_group_id",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'The l3_group_id parameter is not a valid value: %s.'",
",",
"l3_group_id",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'l3_group_id'",
",",
"l3_group_id",
")",
"else",
":",
"l3_group_id",
"=",
"int",
"(",
"l3_group_id",
")",
"GrupoL3",
".",
"get_by_pk",
"(",
"l3_group_id",
")",
"logic_environment_id",
"=",
"environment_map",
".",
"get",
"(",
"'id_ambiente_logico'",
")",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"logic_environment_id",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'The logic_environment_id parameter is not a valid value: %s.'",
",",
"logic_environment_id",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'logic_environment_id'",
",",
"logic_environment_id",
")",
"else",
":",
"logic_environment_id",
"=",
"int",
"(",
"logic_environment_id",
")",
"AmbienteLogico",
".",
"get_by_pk",
"(",
"logic_environment_id",
")",
"dc_division_id",
"=",
"environment_map",
".",
"get",
"(",
"'id_divisao'",
")",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"dc_division_id",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'The dc_division_id parameter is not a valid value: %s.'",
",",
"dc_division_id",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'dc_division_id'",
",",
"dc_division_id",
")",
"else",
":",
"dc_division_id",
"=",
"int",
"(",
"dc_division_id",
")",
"DivisaoDc",
".",
"get_by_pk",
"(",
"dc_division_id",
")",
"link",
"=",
"environment_map",
".",
"get",
"(",
"'link'",
")",
"if",
"not",
"is_valid_string_maxsize",
"(",
"link",
",",
"200",
",",
"False",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameter link is invalid. Value: %s'",
",",
"link",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'link'",
",",
"link",
")",
"vrf",
"=",
"environment_map",
".",
"get",
"(",
"'vrf'",
")",
"if",
"not",
"is_valid_string_maxsize",
"(",
"link",
",",
"100",
",",
"False",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameter vrf is invalid. Value: %s'",
",",
"vrf",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'vrf'",
",",
"vrf",
")",
"filter_id",
"=",
"environment_map",
".",
"get",
"(",
"'id_filter'",
")",
"if",
"filter_id",
"is",
"not",
"None",
":",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"filter_id",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameter filter_id is invalid. Value: %s.'",
",",
"filter_id",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'filter_id'",
",",
"filter_id",
")",
"filter_id",
"=",
"int",
"(",
"filter_id",
")",
"# Filter must exist",
"Filter",
".",
"get_by_pk",
"(",
"filter_id",
")",
"acl_path",
"=",
"environment_map",
".",
"get",
"(",
"'acl_path'",
")",
"if",
"not",
"is_valid_string_maxsize",
"(",
"acl_path",
",",
"250",
",",
"False",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameter acl_path is invalid. Value: %s'",
",",
"acl_path",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'acl_path'",
",",
"acl_path",
")",
"ipv4_template",
"=",
"environment_map",
".",
"get",
"(",
"'ipv4_template'",
")",
"if",
"not",
"is_valid_string_maxsize",
"(",
"ipv4_template",
",",
"250",
",",
"False",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameter ipv4_template is invalid. Value: %s'",
",",
"ipv4_template",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'ipv4_template'",
",",
"ipv4_template",
")",
"ipv6_template",
"=",
"environment_map",
".",
"get",
"(",
"'ipv6_template'",
")",
"if",
"not",
"is_valid_string_maxsize",
"(",
"ipv6_template",
",",
"250",
",",
"False",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameter ipv6_template is invalid. Value: %s'",
",",
"ipv6_template",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'ipv6_template'",
",",
"ipv6_template",
")",
"max_num_vlan_1",
"=",
"environment_map",
".",
"get",
"(",
"'max_num_vlan_1'",
")",
"min_num_vlan_1",
"=",
"environment_map",
".",
"get",
"(",
"'min_num_vlan_1'",
")",
"max_num_vlan_2",
"=",
"environment_map",
".",
"get",
"(",
"'max_num_vlan_2'",
")",
"min_num_vlan_2",
"=",
"environment_map",
".",
"get",
"(",
"'min_num_vlan_2'",
")",
"# validate max_num_vlan_1 and min_num_vlan_1",
"if",
"(",
"max_num_vlan_1",
"is",
"not",
"None",
"and",
"min_num_vlan_1",
"is",
"None",
")",
"or",
"(",
"min_num_vlan_1",
"is",
"not",
"None",
"and",
"max_num_vlan_1",
"is",
"None",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameters min_num_vlan_1, max_num_vlan_1 is invalid. Values: %s, %s'",
",",
"(",
"min_num_vlan_1",
",",
"max_num_vlan_1",
")",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'min_num_vlan_1, max_num_vlan_1'",
",",
"min_num_vlan_1",
"+",
"','",
"+",
"max_num_vlan_1",
")",
"if",
"max_num_vlan_1",
"is",
"not",
"None",
"and",
"min_num_vlan_1",
"is",
"not",
"None",
":",
"max_num_vlan_1",
"=",
"int",
"(",
"max_num_vlan_1",
")",
"min_num_vlan_1",
"=",
"int",
"(",
"min_num_vlan_1",
")",
"if",
"max_num_vlan_1",
"<",
"1",
"or",
"min_num_vlan_1",
"<",
"1",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameters min_num_vlan_1, max_num_vlan_1 is invalid. Values: %s, %s'",
",",
"(",
"min_num_vlan_1",
",",
"max_num_vlan_1",
")",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'min_num_vlan_1, max_num_vlan_1'",
",",
"min_num_vlan_1",
"+",
"','",
"+",
"max_num_vlan_1",
")",
"if",
"max_num_vlan_1",
"<=",
"min_num_vlan_1",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameters min_num_vlan_1, max_num_vlan_1 is invalid. Values: %s, %s'",
",",
"(",
"min_num_vlan_1",
",",
"max_num_vlan_1",
")",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'min_num_vlan_1, max_num_vlan_1'",
",",
"min_num_vlan_1",
"+",
"','",
"+",
"max_num_vlan_1",
")",
"else",
":",
"max_num_vlan_1",
"=",
"max_num_vlan_2",
"min_num_vlan_1",
"=",
"min_num_vlan_2",
"# validate max_num_vlan_1 and min_num_vlan_1",
"# validate max_num_vlan_2 and min_num_vlan_2",
"if",
"(",
"max_num_vlan_2",
"is",
"not",
"None",
"and",
"min_num_vlan_2",
"is",
"None",
")",
"or",
"(",
"min_num_vlan_2",
"is",
"not",
"None",
"and",
"max_num_vlan_2",
"is",
"None",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameters min_num_vlan_2, max_num_vlan_2 is invalid. Values: %s, %s'",
",",
"(",
"min_num_vlan_2",
",",
"max_num_vlan_2",
")",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'min_num_vlan_2, max_num_vlan_2'",
",",
"min_num_vlan_2",
"+",
"','",
"+",
"max_num_vlan_1",
")",
"if",
"max_num_vlan_2",
"is",
"not",
"None",
"and",
"min_num_vlan_2",
"is",
"not",
"None",
":",
"max_num_vlan_2",
"=",
"int",
"(",
"max_num_vlan_2",
")",
"min_num_vlan_2",
"=",
"int",
"(",
"min_num_vlan_2",
")",
"max_num_vlan_1",
"=",
"int",
"(",
"max_num_vlan_1",
")",
"min_num_vlan_1",
"=",
"int",
"(",
"min_num_vlan_1",
")",
"if",
"max_num_vlan_2",
"<",
"1",
"or",
"min_num_vlan_2",
"<",
"1",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameters min_num_vlan_2, max_num_vlan_2 is invalid. Values: %s, %s'",
",",
"(",
"min_num_vlan_2",
",",
"max_num_vlan_2",
")",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'min_num_vlan_2, max_num_vlan_2'",
",",
"min_num_vlan_2",
"+",
"','",
"+",
"max_num_vlan_1",
")",
"if",
"max_num_vlan_2",
"<=",
"min_num_vlan_2",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameters min_num_vlan_2, max_num_vlan_2 is invalid. Values: %s, %s'",
",",
"(",
"min_num_vlan_2",
",",
"max_num_vlan_2",
")",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'min_num_vlan_2, max_num_vlan_2'",
",",
"min_num_vlan_2",
"+",
"','",
"+",
"max_num_vlan_1",
")",
"else",
":",
"max_num_vlan_2",
"=",
"max_num_vlan_1",
"min_num_vlan_2",
"=",
"min_num_vlan_1",
"# validate max_num_vlan_2 and min_num_vlan_2",
"with",
"distributedlock",
"(",
"LOCK_ENVIRONMENT",
"%",
"environment_id",
")",
":",
"# Delete vlan's cache",
"key_list_db",
"=",
"Vlan",
".",
"objects",
".",
"filter",
"(",
"ambiente__pk",
"=",
"environment_id",
")",
"key_list",
"=",
"[",
"]",
"for",
"key",
"in",
"key_list_db",
":",
"key_list",
".",
"append",
"(",
"key",
".",
"id",
")",
"destroy_cache_function",
"(",
"key_list",
")",
"# Destroy equipment's cache",
"equip_id_list",
"=",
"[",
"]",
"envr",
"=",
"Ambiente",
".",
"get_by_pk",
"(",
"environment_id",
")",
"for",
"equipment",
"in",
"envr",
".",
"equipamentoambiente_set",
".",
"all",
"(",
")",
":",
"equip_id_list",
".",
"append",
"(",
"equipment",
".",
"equipamento_id",
")",
"destroy_cache_function",
"(",
"equip_id_list",
",",
"True",
")",
"Ambiente",
".",
"update",
"(",
"user",
",",
"environment_id",
",",
"grupo_l3_id",
"=",
"l3_group_id",
",",
"ambiente_logico_id",
"=",
"logic_environment_id",
",",
"divisao_dc_id",
"=",
"dc_division_id",
",",
"filter_id",
"=",
"filter_id",
",",
"link",
"=",
"link",
",",
"vrf",
"=",
"vrf",
",",
"acl_path",
"=",
"fix_acl_path",
"(",
"acl_path",
")",
",",
"ipv4_template",
"=",
"ipv4_template",
",",
"ipv6_template",
"=",
"ipv6_template",
",",
"max_num_vlan_1",
"=",
"max_num_vlan_1",
",",
"min_num_vlan_1",
"=",
"min_num_vlan_1",
",",
"max_num_vlan_2",
"=",
"max_num_vlan_2",
",",
"min_num_vlan_2",
"=",
"min_num_vlan_2",
")",
"return",
"self",
".",
"response",
"(",
"dumps_networkapi",
"(",
"{",
"}",
")",
")",
"except",
"InvalidValueError",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"269",
",",
"e",
".",
"param",
",",
"e",
".",
"value",
")",
"except",
"FilterNotFoundError",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"339",
")",
"except",
"GroupL3NotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"160",
",",
"l3_group_id",
")",
"except",
"AmbienteNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"112",
")",
"except",
"AmbienteLogicoNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"162",
",",
"logic_environment_id",
")",
"except",
"AmbienteDuplicatedError",
":",
"return",
"self",
".",
"response_error",
"(",
"219",
")",
"except",
"DivisaoDcNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"164",
",",
"dc_division_id",
")",
"except",
"CannotDissociateFilterError",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"349",
",",
"e",
".",
"cause",
")",
"except",
"XMLError",
",",
"x",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Erro ao ler o XML da requisicao.'",
")",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"x",
")",
"except",
"(",
"AmbienteError",
",",
"GrupoError",
")",
":",
"return",
"self",
".",
"response_error",
"(",
"1",
")"
]
| [
376,
4
]
| [
593,
41
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
FFP.read_input | (self, filename: str) | Função para carregar uma instância. | Função para carregar uma instância. | def read_input(self, filename: str):
''' Função para carregar uma instância.'''
self.B = []
self.G = Graph()
with open(filename, 'r') as f:
# Iterar sobre as linhas do arquivo
for (idx, line) in enumerate(f):
values = line.split()
# Adicionar vértices de B
if idx > 4 and len(values) == 1:
self.B.append(int(values[0]))
# Adicionar arestas
elif len(values) == 2:
self.G.add_edge(int(values[0]), int(values[1]))
# Número de vértices e arestas
n = self.G.number_of_nodes()
# Limite de iterações
self.max_T = ceil(n / self.D)
# Calcular caminho mínimo entre todos os pares
self.sp_len = dict(all_pairs_shortest_path_length(self.G)) | [
"def",
"read_input",
"(",
"self",
",",
"filename",
":",
"str",
")",
":",
"self",
".",
"B",
"=",
"[",
"]",
"self",
".",
"G",
"=",
"Graph",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"# Iterar sobre as linhas do arquivo",
"for",
"(",
"idx",
",",
"line",
")",
"in",
"enumerate",
"(",
"f",
")",
":",
"values",
"=",
"line",
".",
"split",
"(",
")",
"# Adicionar vértices de B",
"if",
"idx",
">",
"4",
"and",
"len",
"(",
"values",
")",
"==",
"1",
":",
"self",
".",
"B",
".",
"append",
"(",
"int",
"(",
"values",
"[",
"0",
"]",
")",
")",
"# Adicionar arestas",
"elif",
"len",
"(",
"values",
")",
"==",
"2",
":",
"self",
".",
"G",
".",
"add_edge",
"(",
"int",
"(",
"values",
"[",
"0",
"]",
")",
",",
"int",
"(",
"values",
"[",
"1",
"]",
")",
")",
"# Número de vértices e arestas",
"n",
"=",
"self",
".",
"G",
".",
"number_of_nodes",
"(",
")",
"# Limite de iterações",
"self",
".",
"max_T",
"=",
"ceil",
"(",
"n",
"/",
"self",
".",
"D",
")",
"# Calcular caminho mínimo entre todos os pares",
"self",
".",
"sp_len",
"=",
"dict",
"(",
"all_pairs_shortest_path_length",
"(",
"self",
".",
"G",
")",
")"
]
| [
33,
4
]
| [
59,
66
]
| 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, ...].
- text = 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, ...].
- text = conteúdo que deve estar na tag.
- tag = tag onde o texto será procurado.
"""
elements = browser.find_elements_by_tag_name(tag) # list
for element in elements:
if element.text == text:
return element | [
"def",
"find_by_text",
"(",
"browser",
",",
"tag",
",",
"text",
")",
":",
"elements",
"=",
"browser",
".",
"find_elements_by_tag_name",
"(",
"tag",
")",
"# list",
"for",
"element",
"in",
"elements",
":",
"if",
"element",
".",
"text",
"==",
"text",
":",
"return",
"element"
]
| [
4,
0
]
| [
16,
26
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Banco.fetchall | (self) | return self.cursor.fetchall() | Busca todas as linhas de um resultado de consulta e retorna uma lista com os resultados | Busca todas as linhas de um resultado de consulta e retorna uma lista com os resultados | def fetchall(self):
""" Busca todas as linhas de um resultado de consulta e retorna uma lista com os resultados """
return self.cursor.fetchall() | [
"def",
"fetchall",
"(",
"self",
")",
":",
"return",
"self",
".",
"cursor",
".",
"fetchall",
"(",
")"
]
| [
33,
4
]
| [
35,
37
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
vacinacao_paciente | () | Realiza a vacinacao de um paciente | Realiza a vacinacao de um paciente | def vacinacao_paciente():
'''Realiza a vacinacao de um paciente'''
# Vacina Geral
session['idVacinaGeral'] = request.args['idVacinaGeral']
# Vacinas da Vacina Geral
vacinas = db.session.query(Vacina).join(Vacina_Doenca).join(Vacina_Geral).filter(Vacina_Geral.id == request.args['idVacinaGeral'])
lista_vacinas_disponiveis = []
for v in vacinas:
e = db.session.query(Estoque).filter(Estoque.idVacina == v.id).first()
if e.dosesTotal > (e.vacAplicadas + e.vacDescartadas): # Essa vacina ainda está em estoque
lista_vacinas_disponiveis.append(v)
# Unidades de saude
unidades_saude = []
unidade = db.session.query(Unidade_Saude).all()
for u in unidade:
unidades_saude.append(u)
form = VacinarPaciente()
form.vacina.choices = [(v.id, v.nome) for v in lista_vacinas_disponiveis]
form.unidadeSaude.choices = [(u.id, u.nome) for u in unidades_saude]
if request.method == 'GET':
return render_template('vacinacao.html', title='VACINAÇÃO', form=form,)
if form.validate_on_submit():
vacina_aplicada = db.session.query(Vacina).filter(Vacina.id == request.form['vacina']).first()
doseAtual = int(request.form['doseAtual'])
# Buscando id do ano atual
now = datetime.now()
ano = db.session.query(Ano).filter(Ano.ano == str(now.year)).first()
intervalo = db.session.query(Intervalo).join(Vacina).filter(Vacina.id == vacina_aplicada.id).first()
periodo_dias = intervalo.periodo
# Próxima dose
if doseAtual < vacina_aplicada.nDose: # Não está na última dose da vacina
aux = datetime.now()
proximaDose = aux + timedelta(days=periodo_dias)
proximaDose = proximaDose.strftime('%Y-%m-%d')
session['proximaDose'] = proximaDose
else:
session['proximaDose'] = 'ultima'
hoje = date.today()
dataHoje = hoje.strftime("%Y-%m-%d")
h = Historico()
h.idVacinaGeral = session['idVacinaGeral']
h.idFaixaEtaria = session['idFaixaEtaria']
h.idAno = session['idAnoAtual']
h.idPessoa = session['idPaciente']
h.data = dataHoje
h.idUnidadeSaude = request.form['unidadeSaude']
h.doseAtual = doseAtual
h.idVacina = vacina_aplicada.id
db.session.add(h)
# Alterando estoque (incrementando vacina utilizada)
est = db.session.query(Estoque).filter(Estoque.idVacina == vacina_aplicada.id).first()
est.vacAplicadas = est.vacAplicadas + 1
# Povoando proxima dose
if session['proximaDose'] is not 'ultima':
pDose_max_id = db.session.query(func.max(Proxima_Dose.id)).scalar()
pDose = Proxima_Dose()
pDose.id = pDose_max_id+1
pDose.data = session['proximaDose']
pDose.idPessoa = session['idPaciente']
pDose.idVacinaGeral = session['idVacinaGeral']
db.session.add(pDose)
db.session.commit()
db.session.close()
return redirect(url_for('historico_paciente')) | [
"def",
"vacinacao_paciente",
"(",
")",
":",
"# Vacina Geral",
"session",
"[",
"'idVacinaGeral'",
"]",
"=",
"request",
".",
"args",
"[",
"'idVacinaGeral'",
"]",
"# Vacinas da Vacina Geral",
"vacinas",
"=",
"db",
".",
"session",
".",
"query",
"(",
"Vacina",
")",
".",
"join",
"(",
"Vacina_Doenca",
")",
".",
"join",
"(",
"Vacina_Geral",
")",
".",
"filter",
"(",
"Vacina_Geral",
".",
"id",
"==",
"request",
".",
"args",
"[",
"'idVacinaGeral'",
"]",
")",
"lista_vacinas_disponiveis",
"=",
"[",
"]",
"for",
"v",
"in",
"vacinas",
":",
"e",
"=",
"db",
".",
"session",
".",
"query",
"(",
"Estoque",
")",
".",
"filter",
"(",
"Estoque",
".",
"idVacina",
"==",
"v",
".",
"id",
")",
".",
"first",
"(",
")",
"if",
"e",
".",
"dosesTotal",
">",
"(",
"e",
".",
"vacAplicadas",
"+",
"e",
".",
"vacDescartadas",
")",
":",
"# Essa vacina ainda está em estoque",
"lista_vacinas_disponiveis",
".",
"append",
"(",
"v",
")",
"# Unidades de saude",
"unidades_saude",
"=",
"[",
"]",
"unidade",
"=",
"db",
".",
"session",
".",
"query",
"(",
"Unidade_Saude",
")",
".",
"all",
"(",
")",
"for",
"u",
"in",
"unidade",
":",
"unidades_saude",
".",
"append",
"(",
"u",
")",
"form",
"=",
"VacinarPaciente",
"(",
")",
"form",
".",
"vacina",
".",
"choices",
"=",
"[",
"(",
"v",
".",
"id",
",",
"v",
".",
"nome",
")",
"for",
"v",
"in",
"lista_vacinas_disponiveis",
"]",
"form",
".",
"unidadeSaude",
".",
"choices",
"=",
"[",
"(",
"u",
".",
"id",
",",
"u",
".",
"nome",
")",
"for",
"u",
"in",
"unidades_saude",
"]",
"if",
"request",
".",
"method",
"==",
"'GET'",
":",
"return",
"render_template",
"(",
"'vacinacao.html'",
",",
"title",
"=",
"'VACINAÇÃO', ",
"f",
"rm=f",
"o",
"rm,)",
"",
"",
"if",
"form",
".",
"validate_on_submit",
"(",
")",
":",
"vacina_aplicada",
"=",
"db",
".",
"session",
".",
"query",
"(",
"Vacina",
")",
".",
"filter",
"(",
"Vacina",
".",
"id",
"==",
"request",
".",
"form",
"[",
"'vacina'",
"]",
")",
".",
"first",
"(",
")",
"doseAtual",
"=",
"int",
"(",
"request",
".",
"form",
"[",
"'doseAtual'",
"]",
")",
"# Buscando id do ano atual",
"now",
"=",
"datetime",
".",
"now",
"(",
")",
"ano",
"=",
"db",
".",
"session",
".",
"query",
"(",
"Ano",
")",
".",
"filter",
"(",
"Ano",
".",
"ano",
"==",
"str",
"(",
"now",
".",
"year",
")",
")",
".",
"first",
"(",
")",
"intervalo",
"=",
"db",
".",
"session",
".",
"query",
"(",
"Intervalo",
")",
".",
"join",
"(",
"Vacina",
")",
".",
"filter",
"(",
"Vacina",
".",
"id",
"==",
"vacina_aplicada",
".",
"id",
")",
".",
"first",
"(",
")",
"periodo_dias",
"=",
"intervalo",
".",
"periodo",
"# Próxima dose",
"if",
"doseAtual",
"<",
"vacina_aplicada",
".",
"nDose",
":",
"# Não está na última dose da vacina",
"aux",
"=",
"datetime",
".",
"now",
"(",
")",
"proximaDose",
"=",
"aux",
"+",
"timedelta",
"(",
"days",
"=",
"periodo_dias",
")",
"proximaDose",
"=",
"proximaDose",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
"session",
"[",
"'proximaDose'",
"]",
"=",
"proximaDose",
"else",
":",
"session",
"[",
"'proximaDose'",
"]",
"=",
"'ultima'",
"hoje",
"=",
"date",
".",
"today",
"(",
")",
"dataHoje",
"=",
"hoje",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
"h",
"=",
"Historico",
"(",
")",
"h",
".",
"idVacinaGeral",
"=",
"session",
"[",
"'idVacinaGeral'",
"]",
"h",
".",
"idFaixaEtaria",
"=",
"session",
"[",
"'idFaixaEtaria'",
"]",
"h",
".",
"idAno",
"=",
"session",
"[",
"'idAnoAtual'",
"]",
"h",
".",
"idPessoa",
"=",
"session",
"[",
"'idPaciente'",
"]",
"h",
".",
"data",
"=",
"dataHoje",
"h",
".",
"idUnidadeSaude",
"=",
"request",
".",
"form",
"[",
"'unidadeSaude'",
"]",
"h",
".",
"doseAtual",
"=",
"doseAtual",
"h",
".",
"idVacina",
"=",
"vacina_aplicada",
".",
"id",
"db",
".",
"session",
".",
"add",
"(",
"h",
")",
"# Alterando estoque (incrementando vacina utilizada)",
"est",
"=",
"db",
".",
"session",
".",
"query",
"(",
"Estoque",
")",
".",
"filter",
"(",
"Estoque",
".",
"idVacina",
"==",
"vacina_aplicada",
".",
"id",
")",
".",
"first",
"(",
")",
"est",
".",
"vacAplicadas",
"=",
"est",
".",
"vacAplicadas",
"+",
"1",
"# Povoando proxima dose",
"if",
"session",
"[",
"'proximaDose'",
"]",
"is",
"not",
"'ultima'",
":",
"pDose_max_id",
"=",
"db",
".",
"session",
".",
"query",
"(",
"func",
".",
"max",
"(",
"Proxima_Dose",
".",
"id",
")",
")",
".",
"scalar",
"(",
")",
"pDose",
"=",
"Proxima_Dose",
"(",
")",
"pDose",
".",
"id",
"=",
"pDose_max_id",
"+",
"1",
"pDose",
".",
"data",
"=",
"session",
"[",
"'proximaDose'",
"]",
"pDose",
".",
"idPessoa",
"=",
"session",
"[",
"'idPaciente'",
"]",
"pDose",
".",
"idVacinaGeral",
"=",
"session",
"[",
"'idVacinaGeral'",
"]",
"db",
".",
"session",
".",
"add",
"(",
"pDose",
")",
"db",
".",
"session",
".",
"commit",
"(",
")",
"db",
".",
"session",
".",
"close",
"(",
")",
"return",
"redirect",
"(",
"url_for",
"(",
"'historico_paciente'",
")",
")"
]
| [
275,
0
]
| [
354,
54
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Thing.display | (self, canvas, x, y, width, height) | Mostre uma imagem desta 'coisa na tela. | Mostre uma imagem desta 'coisa na tela. | def display(self, canvas, x, y, width, height):
"Mostre uma imagem desta 'coisa na tela."
pass | [
"def",
"display",
"(",
"self",
",",
"canvas",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
")",
":",
"pass"
]
| [
29,
4
]
| [
31,
12
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
BaseDoc.validate | (self, doc: str = '') | Método para validar o documento desejado. | Método para validar o documento desejado. | def validate(self, doc: str = '') -> bool:
"""Método para validar o documento desejado."""
pass | [
"def",
"validate",
"(",
"self",
",",
"doc",
":",
"str",
"=",
"''",
")",
"->",
"bool",
":",
"pass"
]
| [
7,
4
]
| [
9,
12
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
build_person | (first_name, last_name, age = '') | return person | Devolve um dicionário com informações sobre uma pessoa. | Devolve um dicionário com informações sobre uma pessoa. | def build_person(first_name, last_name, age = ''):
"""Devolve um dicionário com informações sobre uma pessoa."""
person = {'first': first_name, 'last': last_name}
if age:
person['age'] = age
return person | [
"def",
"build_person",
"(",
"first_name",
",",
"last_name",
",",
"age",
"=",
"''",
")",
":",
"person",
"=",
"{",
"'first'",
":",
"first_name",
",",
"'last'",
":",
"last_name",
"}",
"if",
"age",
":",
"person",
"[",
"'age'",
"]",
"=",
"age",
"return",
"person"
]
| [
2,
0
]
| [
7,
17
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
GroupVirtualResource.handle_post | (self, request, user, *args, **kwargs) | Trata as requisições de POST para inserir um Grupo Virtual.
URL: /grupovirtual/
| Trata as requisições de POST para inserir um Grupo Virtual. | def handle_post(self, request, user, *args, **kwargs):
"""Trata as requisições de POST para inserir um Grupo Virtual.
URL: /grupovirtual/
"""
try:
xml_map, attrs_map = loads(request.raw_post_data, [
'vip', 'equipamento', 'id_equipamento', 'reals_weight', 'reals_priority', 'real', 'transbordo', 'porta'])
except XMLError, x:
self.log.error(u'Erro ao ler o XML da requisicao.')
return self.response_error(3, x)
self.log.debug('XML_MAP: %s', xml_map)
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.')
equipments_map = networkapi_map.get('equipamentos')
if equipments_map is None:
return self.response_error(3, u'Não existe valor para a tag equipamentos do XML de requisição.')
equipment_maps = equipments_map.get('equipamento')
if len(equipment_maps) == 0:
return self.response_error(3, u'Não existe valor para a tag equipamento do XML de requisição.')
vips_map = networkapi_map.get('vips')
if vips_map is not None:
vip_maps = vips_map.get('vip')
else:
vip_maps = []
try:
with distributedlock(LOCK_GROUP_VIRTUAL):
# for nos equipamentos
resp_equipment_maps = []
vip_equipment_ip_map = dict()
response = self.__post_virtual_group_equipment(
equipment_maps, vip_maps, user, resp_equipment_maps, vip_equipment_ip_map)
if response is not None:
return response
# for nos vips
resp_vip_maps = []
response = self.__post_virtual_group_vip(
vip_maps, user, vip_equipment_ip_map, resp_vip_maps)
if response is not None:
return response
# Mapa final
map = dict()
map['equipamentos'] = {'equipamento': resp_equipment_maps}
map['vips'] = {'vip': resp_vip_maps}
return self.response(dumps_networkapi(map))
except UserNotAuthorizedError:
return self.not_authorized()
except InvalidValueError, e:
return self.response_error(269, e.param, e.value)
except VlanNotFoundError:
return self.response_error(116)
except IpNotAvailableError, e:
return self.response_error(150, e)
except (IpError, VlanError, EquipamentoError, GrupoError, RequisicaoVipsError, HealthcheckExpectError):
return self.response_error(1) | [
"def",
"handle_post",
"(",
"self",
",",
"request",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"xml_map",
",",
"attrs_map",
"=",
"loads",
"(",
"request",
".",
"raw_post_data",
",",
"[",
"'vip'",
",",
"'equipamento'",
",",
"'id_equipamento'",
",",
"'reals_weight'",
",",
"'reals_priority'",
",",
"'real'",
",",
"'transbordo'",
",",
"'porta'",
"]",
")",
"except",
"XMLError",
",",
"x",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Erro ao ler o XML da requisicao.'",
")",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"x",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'XML_MAP: %s'",
",",
"xml_map",
")",
"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.')",
"",
"equipments_map",
"=",
"networkapi_map",
".",
"get",
"(",
"'equipamentos'",
")",
"if",
"equipments_map",
"is",
"None",
":",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"u'Não existe valor para a tag equipamentos do XML de requisição.')",
"",
"equipment_maps",
"=",
"equipments_map",
".",
"get",
"(",
"'equipamento'",
")",
"if",
"len",
"(",
"equipment_maps",
")",
"==",
"0",
":",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"u'Não existe valor para a tag equipamento do XML de requisição.')",
"",
"vips_map",
"=",
"networkapi_map",
".",
"get",
"(",
"'vips'",
")",
"if",
"vips_map",
"is",
"not",
"None",
":",
"vip_maps",
"=",
"vips_map",
".",
"get",
"(",
"'vip'",
")",
"else",
":",
"vip_maps",
"=",
"[",
"]",
"try",
":",
"with",
"distributedlock",
"(",
"LOCK_GROUP_VIRTUAL",
")",
":",
"# for nos equipamentos",
"resp_equipment_maps",
"=",
"[",
"]",
"vip_equipment_ip_map",
"=",
"dict",
"(",
")",
"response",
"=",
"self",
".",
"__post_virtual_group_equipment",
"(",
"equipment_maps",
",",
"vip_maps",
",",
"user",
",",
"resp_equipment_maps",
",",
"vip_equipment_ip_map",
")",
"if",
"response",
"is",
"not",
"None",
":",
"return",
"response",
"# for nos vips",
"resp_vip_maps",
"=",
"[",
"]",
"response",
"=",
"self",
".",
"__post_virtual_group_vip",
"(",
"vip_maps",
",",
"user",
",",
"vip_equipment_ip_map",
",",
"resp_vip_maps",
")",
"if",
"response",
"is",
"not",
"None",
":",
"return",
"response",
"# Mapa final",
"map",
"=",
"dict",
"(",
")",
"map",
"[",
"'equipamentos'",
"]",
"=",
"{",
"'equipamento'",
":",
"resp_equipment_maps",
"}",
"map",
"[",
"'vips'",
"]",
"=",
"{",
"'vip'",
":",
"resp_vip_maps",
"}",
"return",
"self",
".",
"response",
"(",
"dumps_networkapi",
"(",
"map",
")",
")",
"except",
"UserNotAuthorizedError",
":",
"return",
"self",
".",
"not_authorized",
"(",
")",
"except",
"InvalidValueError",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"269",
",",
"e",
".",
"param",
",",
"e",
".",
"value",
")",
"except",
"VlanNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"116",
")",
"except",
"IpNotAvailableError",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"150",
",",
"e",
")",
"except",
"(",
"IpError",
",",
"VlanError",
",",
"EquipamentoError",
",",
"GrupoError",
",",
"RequisicaoVipsError",
",",
"HealthcheckExpectError",
")",
":",
"return",
"self",
".",
"response_error",
"(",
"1",
")"
]
| [
506,
4
]
| [
573,
41
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Dado.__init__ | (self) | Inicializa o atributo que se refere aos lados de um dado. | Inicializa o atributo que se refere aos lados de um dado. | def __init__(self):
"""Inicializa o atributo que se refere aos lados de um dado."""
self.lados_dado = 6 | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"lados_dado",
"=",
"6"
]
| [
7,
4
]
| [
9,
27
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
EquipamentoEditResource.handle_post | (self, request, user, *args, **kwargs) | Trata uma requisicao POST para editar um equipamento.
URL: equipmento/edit/
| Trata uma requisicao POST para editar um equipamento. | def handle_post(self, request, user, *args, **kwargs):
"""Trata uma requisicao POST para editar um equipamento.
URL: equipmento/edit/
"""
try:
# Load XML data
xml_map, attrs_map = loads(request.raw_post_data)
# XML data format
networkapi_map = xml_map.get('networkapi')
if networkapi_map is None:
msg = u'There is no value to the networkapi tag of XML request.'
self.log.error(msg)
return self.response_error(3, msg)
equip_map = networkapi_map.get('equipamento')
if equip_map is None:
msg = u'There is no value to the ip tag of XML request.'
self.log.error(msg)
return self.response_error(3, msg)
# Get XML data
equip_id = equip_map.get('id_equip')
id_modelo = equip_map.get('id_modelo')
nome = equip_map.get('nome')
id_tipo_equipamento = equip_map.get('id_tipo_equipamento')
maintenance = equip_map.get('maintenance')
# Valid equip_id
if not is_valid_int_greater_zero_param(equip_id):
self.log.error(
u'Parameter equip_id is invalid. Value: %s.', equip_id)
raise InvalidValueError(None, 'equip_id', equip_id)
# Valid id_modelo
if not is_valid_int_greater_zero_param(id_modelo):
self.log.error(
u'Parameter id_modelo is invalid. Value: %s.', id_modelo)
raise InvalidValueError(None, 'id_modelo', id_modelo)
# Valid id_tipo_equipamento
if not is_valid_int_greater_zero_param(id_tipo_equipamento):
self.log.error(
u'Parameter id_tipo_equipamento is invalid. Value: %s.', id_tipo_equipamento)
raise InvalidValueError(
None, 'id_tipo_equipamento', id_tipo_equipamento)
# Valid nome
if not is_valid_string_minsize(nome, 3) or not is_valid_string_maxsize(nome, 80) or not is_valid_regex(nome, '^[A-Z0-9-_]+$'):
self.log.error(u'Parameter nome is invalid. Value: %s', nome)
raise InvalidValueError(None, 'nome', nome)
# Business Rules
# New equipment
equip = Equipamento()
equip = equip.get_by_pk(equip_id)
# maintenance is a new feature. Check existing value if not defined in request
# Old calls does not send this field
if maintenance is None:
maintenance = equip.maintenance
if not is_valid_boolean_param(maintenance):
self.log.error(
u'The maintenance parameter is not a valid value: %s.', maintenance)
raise InvalidValueError(None, 'maintenance', maintenance)
if maintenance in ['1', 'True', True]:
maintenance = True
else:
maintenance = False
# User permission
if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION, None, equip_id, AdminPermission.EQUIP_WRITE_OPERATION):
raise UserNotAuthorizedError(
None, u'User does not have permission to perform the operation.')
with distributedlock(LOCK_EQUIPMENT % equip_id):
tipo_equip = TipoEquipamento.get_by_pk(id_tipo_equipamento)
if equip.tipo_equipamento != tipo_equip:
# Environments with filters using current equip type, with
# equipment associated
envs = [eq_env.ambiente.id for eq_env in equip.equipamentoambiente_set.filter(
ambiente__filter__filterequiptype__equiptype=equip.tipo_equipamento)]
# Filters case 1 and 2
filters_ok = True
# Networks in environments with same ip range
nets_same_range = NetworkIPv4.objects.filter(vlan__ambiente__in=envs).values(
'oct1', 'oct2', 'oct3', 'oct4', 'block').annotate(count=Count('id')).filter(count__gt=1)
if len(nets_same_range) > 0:
for net_gp in nets_same_range:
nets_current_range = NetworkIPv4.objects.filter(vlan__ambiente__in=envs, oct1=net_gp[
'oct1'], oct2=net_gp['oct2'], oct3=net_gp['oct3'], oct4=net_gp['oct4'], block=net_gp['block'])
filters_of_envs = [
net.vlan.ambiente.filter.id for net in nets_current_range]
for fil_ in filters_of_envs:
if TipoEquipamento.objects.filter(id=id_tipo_equipamento, filterequiptype__filter=fil_).count() == 0:
filters_ok = False
break
if not filters_ok:
raise EquipTypeCantBeChangedError(
None, 'O tipo de equipamento não pode ser modificado pois existe um filtro em uso que não possui o novo tipo de equipamento informado.')
# Networks ipv6 in environments with same ipv6 range
nets_v6_same_range = NetworkIPv6.objects.filter(vlan__ambiente__in=envs).values(
'block1', 'block2', 'block3', 'block4', 'block5', 'block6', 'block7', 'block8', 'block').annotate(count=Count('id')).filter(count__gt=1)
if len(nets_v6_same_range) > 0:
for net_gp in nets_v6_same_range:
nets_current_range = NetworkIPv6.objects.filter(vlan__ambiente__in=envs, block1=net_gp['block1'], block2=net_gp['block2'], block3=net_gp[
'block3'], block4=net_gp['block4'], block5=net_gp['block5'], block6=net_gp['block6'], block7=net_gp['block7'], block8=net_gp['block8'], block=net_gp['block'])
filters_of_envs = [
net.vlan.ambiente.filter.id for net in nets_current_range]
for fil_ in filters_of_envs:
if TipoEquipamento.objects.filter(id=id_tipo_equipamento, filterequiptype__filter=fil_).count() == 0:
filters_ok = False
break
if not filters_ok:
raise EquipTypeCantBeChangedError(
None, 'O tipo de equipamento não pode ser modificado pois existe um filtro em uso que não possui o novo tipo de equipamento informado.')
# Filters case 1 and 2 end
# Filter case 3
# Get vlans with same number
vlans_same_number = Vlan.objects.filter(ambiente__in=envs).values(
'num_vlan').annotate(count=Count('id')).filter(count__gt=1)
if len(vlans_same_number) > 0:
for vlan_gp in vlans_same_number:
vlans_current_number = Vlan.objects.filter(
ambiente__in=envs, num_vlan=vlan_gp['num_vlan'])
filters_of_envs = [
vlan.ambiente.filter.id for vlan in vlans_current_number]
for fil_ in filters_of_envs:
if TipoEquipamento.objects.filter(id=id_tipo_equipamento, filterequiptype__filter=fil_).count() == 0:
filters_ok = False
break
if not filters_ok:
raise EquipTypeCantBeChangedError(
None, 'O tipo de equipamento não pode ser modificado pois existe um filtro em uso que não possui o novo tipo de equipamento informado.')
# Filter case 3 end
# Test all vip requests if equip.tipo_equipamento is
# balancing
if equip.tipo_equipamento == TipoEquipamento.get_tipo_balanceador():
vips = RequisicaoVips.objects.all()
vip_ips = []
vip_ipsv6 = []
for vip in vips:
if vip.vip_criado:
if vip.ip is not None:
if vip.ip.ipequipamento_set.filter(equipamento=equip.id).count() > 0:
raise EquipTypeCantBeChangedError(
None, 'O tipo de equipamento não pode ser modificado pois este equipamento é o balanceador associado com o vip criado %s.' % vip.id)
if vip.ipv6 is not None:
if vip.ipv6.ipv6equipament_set.filter(equipamento=equip.id).count() > 0:
raise EquipTypeCantBeChangedError(
None, 'O tipo de equipamento não pode ser modificado pois este equipamento é o balanceador associado com o vip criado %s.' % vip.id)
else:
if vip.ip is not None:
vip_ips.append(vip.ip.id)
if vip.ipv6 is not None:
vip_ipsv6.append(vip.ipv6.id)
nets_using_balancer_in_vips_ = [
ip_.networkipv4 for ip_ in Ip.objects.filter(id__in=vip_ips)]
nets_using_balancer_in_vips = [ip_.networkipv4 for ip_ in Ip.objects.filter(
networkipv4__in=nets_using_balancer_in_vips_, ipequipamento__equipamento=equip.id)]
nets_v6_using_balancer_in_vips_ = [
ip_.networkipv6 for ip_ in Ipv6.objects.filter(id__in=vip_ipsv6)]
nets_v6_using_balancer_in_vips = [ip_.networkipv6 for ip_ in Ipv6.objects.filter(
networkipv6__in=nets_v6_using_balancer_in_vips_, ipv6equipament__equipamento=equip.id)]
for net in nets_using_balancer_in_vips:
net_str = str(net.oct1) + '.' + str(net.oct2) + '.' + \
str(net.oct3) + '.' + str(net.oct4) + \
'/' + str(net.block)
if IpEquipamento.objects.filter(ip__networkipv4=net, equipamento__tipo_equipamento=TipoEquipamento.get_tipo_balanceador()).exclude(equipamento=equip).count() == 0:
raise EquipTypeCantBeChangedError(
None, 'O tipo de equipamento não pode ser modificado pois este equipamento é o único balanceador disponível na rede %s da vlan %s.' % (net_str, net.vlan.nome))
for net in nets_v6_using_balancer_in_vips:
net_str = str(net.block1) + ':' + str(net.block2) + ':' + str(net.block3) + ':' + str(net.block4) + ':' + str(
net.block5) + ':' + str(net.block6) + ':' + str(net.block7) + ':' + str(net.block8) + '/' + str(net.block)
if Ipv6Equipament.objects.filter(ip__networkipv6=net, equipamento__tipo_equipamento=TipoEquipamento.get_tipo_balanceador()).exclude(equipamento=equip).count() == 0:
raise EquipTypeCantBeChangedError(
None, 'O tipo de equipamento não pode ser modificado pois este equipamento é o único balanceador disponível na rede %s da vlan %s.' % (net_str, net.vlan.nome))
ip_equipamento_list = IpEquipamento.objects.filter(
equipamento=equip_id)
ip6_equipamento_list = Ipv6Equipament.objects.filter(
equipamento=equip_id)
# Delete vlan's cache
key_list = []
for eq in ip_equipamento_list:
vlan = eq.ip.networkipv4.vlan
vlan_id = vlan.id
key_list.append(vlan_id)
for eq in ip6_equipamento_list:
vlan = eq.ip.networkipv6.vlan
vlan_id = vlan.id
key_list.append(vlan_id)
destroy_cache_function(key_list)
# Delete equipment's cache
destroy_cache_function([equip_id], True)
modelo = Modelo.get_by_pk(id_modelo)
equip.edit(user, nome, tipo_equip, modelo, maintenance)
return self.response(dumps_networkapi({}))
except EquipTypeCantBeChangedError, e:
return self.response_error(150, e.message)
except InvalidValueError, e:
return self.response_error(269, e.param, e.value)
except TipoEquipamentoNotFoundError:
return self.response_error(100)
except ModeloNotFoundError:
return self.response_error(101)
except EquipamentoNotFoundError, e:
return self.response_error(117, equip_id)
except EquipamentoNameDuplicatedError, e:
return self.response_error(e.message)
except (EquipamentoError), e:
return self.responde_error(1)
except UserNotAuthorizedError:
return self.not_authorized()
except XMLError, x:
self.log.error(u'Error reading the XML request.')
return self.response_error(3, x) | [
"def",
"handle_post",
"(",
"self",
",",
"request",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"# Load XML data",
"xml_map",
",",
"attrs_map",
"=",
"loads",
"(",
"request",
".",
"raw_post_data",
")",
"# XML data format",
"networkapi_map",
"=",
"xml_map",
".",
"get",
"(",
"'networkapi'",
")",
"if",
"networkapi_map",
"is",
"None",
":",
"msg",
"=",
"u'There is no value to the networkapi tag of XML request.'",
"self",
".",
"log",
".",
"error",
"(",
"msg",
")",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"msg",
")",
"equip_map",
"=",
"networkapi_map",
".",
"get",
"(",
"'equipamento'",
")",
"if",
"equip_map",
"is",
"None",
":",
"msg",
"=",
"u'There is no value to the ip tag of XML request.'",
"self",
".",
"log",
".",
"error",
"(",
"msg",
")",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"msg",
")",
"# Get XML data",
"equip_id",
"=",
"equip_map",
".",
"get",
"(",
"'id_equip'",
")",
"id_modelo",
"=",
"equip_map",
".",
"get",
"(",
"'id_modelo'",
")",
"nome",
"=",
"equip_map",
".",
"get",
"(",
"'nome'",
")",
"id_tipo_equipamento",
"=",
"equip_map",
".",
"get",
"(",
"'id_tipo_equipamento'",
")",
"maintenance",
"=",
"equip_map",
".",
"get",
"(",
"'maintenance'",
")",
"# Valid equip_id",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"equip_id",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameter equip_id is invalid. Value: %s.'",
",",
"equip_id",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'equip_id'",
",",
"equip_id",
")",
"# Valid id_modelo",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"id_modelo",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameter id_modelo is invalid. Value: %s.'",
",",
"id_modelo",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'id_modelo'",
",",
"id_modelo",
")",
"# Valid id_tipo_equipamento",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"id_tipo_equipamento",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameter id_tipo_equipamento is invalid. Value: %s.'",
",",
"id_tipo_equipamento",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'id_tipo_equipamento'",
",",
"id_tipo_equipamento",
")",
"# Valid nome",
"if",
"not",
"is_valid_string_minsize",
"(",
"nome",
",",
"3",
")",
"or",
"not",
"is_valid_string_maxsize",
"(",
"nome",
",",
"80",
")",
"or",
"not",
"is_valid_regex",
"(",
"nome",
",",
"'^[A-Z0-9-_]+$'",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Parameter nome is invalid. Value: %s'",
",",
"nome",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'nome'",
",",
"nome",
")",
"# Business Rules",
"# New equipment",
"equip",
"=",
"Equipamento",
"(",
")",
"equip",
"=",
"equip",
".",
"get_by_pk",
"(",
"equip_id",
")",
"# maintenance is a new feature. Check existing value if not defined in request",
"# Old calls does not send this field",
"if",
"maintenance",
"is",
"None",
":",
"maintenance",
"=",
"equip",
".",
"maintenance",
"if",
"not",
"is_valid_boolean_param",
"(",
"maintenance",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'The maintenance parameter is not a valid value: %s.'",
",",
"maintenance",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'maintenance'",
",",
"maintenance",
")",
"if",
"maintenance",
"in",
"[",
"'1'",
",",
"'True'",
",",
"True",
"]",
":",
"maintenance",
"=",
"True",
"else",
":",
"maintenance",
"=",
"False",
"# User permission",
"if",
"not",
"has_perm",
"(",
"user",
",",
"AdminPermission",
".",
"EQUIPMENT_MANAGEMENT",
",",
"AdminPermission",
".",
"WRITE_OPERATION",
",",
"None",
",",
"equip_id",
",",
"AdminPermission",
".",
"EQUIP_WRITE_OPERATION",
")",
":",
"raise",
"UserNotAuthorizedError",
"(",
"None",
",",
"u'User does not have permission to perform the operation.'",
")",
"with",
"distributedlock",
"(",
"LOCK_EQUIPMENT",
"%",
"equip_id",
")",
":",
"tipo_equip",
"=",
"TipoEquipamento",
".",
"get_by_pk",
"(",
"id_tipo_equipamento",
")",
"if",
"equip",
".",
"tipo_equipamento",
"!=",
"tipo_equip",
":",
"# Environments with filters using current equip type, with",
"# equipment associated",
"envs",
"=",
"[",
"eq_env",
".",
"ambiente",
".",
"id",
"for",
"eq_env",
"in",
"equip",
".",
"equipamentoambiente_set",
".",
"filter",
"(",
"ambiente__filter__filterequiptype__equiptype",
"=",
"equip",
".",
"tipo_equipamento",
")",
"]",
"# Filters case 1 and 2",
"filters_ok",
"=",
"True",
"# Networks in environments with same ip range",
"nets_same_range",
"=",
"NetworkIPv4",
".",
"objects",
".",
"filter",
"(",
"vlan__ambiente__in",
"=",
"envs",
")",
".",
"values",
"(",
"'oct1'",
",",
"'oct2'",
",",
"'oct3'",
",",
"'oct4'",
",",
"'block'",
")",
".",
"annotate",
"(",
"count",
"=",
"Count",
"(",
"'id'",
")",
")",
".",
"filter",
"(",
"count__gt",
"=",
"1",
")",
"if",
"len",
"(",
"nets_same_range",
")",
">",
"0",
":",
"for",
"net_gp",
"in",
"nets_same_range",
":",
"nets_current_range",
"=",
"NetworkIPv4",
".",
"objects",
".",
"filter",
"(",
"vlan__ambiente__in",
"=",
"envs",
",",
"oct1",
"=",
"net_gp",
"[",
"'oct1'",
"]",
",",
"oct2",
"=",
"net_gp",
"[",
"'oct2'",
"]",
",",
"oct3",
"=",
"net_gp",
"[",
"'oct3'",
"]",
",",
"oct4",
"=",
"net_gp",
"[",
"'oct4'",
"]",
",",
"block",
"=",
"net_gp",
"[",
"'block'",
"]",
")",
"filters_of_envs",
"=",
"[",
"net",
".",
"vlan",
".",
"ambiente",
".",
"filter",
".",
"id",
"for",
"net",
"in",
"nets_current_range",
"]",
"for",
"fil_",
"in",
"filters_of_envs",
":",
"if",
"TipoEquipamento",
".",
"objects",
".",
"filter",
"(",
"id",
"=",
"id_tipo_equipamento",
",",
"filterequiptype__filter",
"=",
"fil_",
")",
".",
"count",
"(",
")",
"==",
"0",
":",
"filters_ok",
"=",
"False",
"break",
"if",
"not",
"filters_ok",
":",
"raise",
"EquipTypeCantBeChangedError",
"(",
"None",
",",
"'O tipo de equipamento não pode ser modificado pois existe um filtro em uso que não possui o novo tipo de equipamento informado.')",
"",
"# Networks ipv6 in environments with same ipv6 range",
"nets_v6_same_range",
"=",
"NetworkIPv6",
".",
"objects",
".",
"filter",
"(",
"vlan__ambiente__in",
"=",
"envs",
")",
".",
"values",
"(",
"'block1'",
",",
"'block2'",
",",
"'block3'",
",",
"'block4'",
",",
"'block5'",
",",
"'block6'",
",",
"'block7'",
",",
"'block8'",
",",
"'block'",
")",
".",
"annotate",
"(",
"count",
"=",
"Count",
"(",
"'id'",
")",
")",
".",
"filter",
"(",
"count__gt",
"=",
"1",
")",
"if",
"len",
"(",
"nets_v6_same_range",
")",
">",
"0",
":",
"for",
"net_gp",
"in",
"nets_v6_same_range",
":",
"nets_current_range",
"=",
"NetworkIPv6",
".",
"objects",
".",
"filter",
"(",
"vlan__ambiente__in",
"=",
"envs",
",",
"block1",
"=",
"net_gp",
"[",
"'block1'",
"]",
",",
"block2",
"=",
"net_gp",
"[",
"'block2'",
"]",
",",
"block3",
"=",
"net_gp",
"[",
"'block3'",
"]",
",",
"block4",
"=",
"net_gp",
"[",
"'block4'",
"]",
",",
"block5",
"=",
"net_gp",
"[",
"'block5'",
"]",
",",
"block6",
"=",
"net_gp",
"[",
"'block6'",
"]",
",",
"block7",
"=",
"net_gp",
"[",
"'block7'",
"]",
",",
"block8",
"=",
"net_gp",
"[",
"'block8'",
"]",
",",
"block",
"=",
"net_gp",
"[",
"'block'",
"]",
")",
"filters_of_envs",
"=",
"[",
"net",
".",
"vlan",
".",
"ambiente",
".",
"filter",
".",
"id",
"for",
"net",
"in",
"nets_current_range",
"]",
"for",
"fil_",
"in",
"filters_of_envs",
":",
"if",
"TipoEquipamento",
".",
"objects",
".",
"filter",
"(",
"id",
"=",
"id_tipo_equipamento",
",",
"filterequiptype__filter",
"=",
"fil_",
")",
".",
"count",
"(",
")",
"==",
"0",
":",
"filters_ok",
"=",
"False",
"break",
"if",
"not",
"filters_ok",
":",
"raise",
"EquipTypeCantBeChangedError",
"(",
"None",
",",
"'O tipo de equipamento não pode ser modificado pois existe um filtro em uso que não possui o novo tipo de equipamento informado.')",
"",
"# Filters case 1 and 2 end",
"# Filter case 3",
"# Get vlans with same number",
"vlans_same_number",
"=",
"Vlan",
".",
"objects",
".",
"filter",
"(",
"ambiente__in",
"=",
"envs",
")",
".",
"values",
"(",
"'num_vlan'",
")",
".",
"annotate",
"(",
"count",
"=",
"Count",
"(",
"'id'",
")",
")",
".",
"filter",
"(",
"count__gt",
"=",
"1",
")",
"if",
"len",
"(",
"vlans_same_number",
")",
">",
"0",
":",
"for",
"vlan_gp",
"in",
"vlans_same_number",
":",
"vlans_current_number",
"=",
"Vlan",
".",
"objects",
".",
"filter",
"(",
"ambiente__in",
"=",
"envs",
",",
"num_vlan",
"=",
"vlan_gp",
"[",
"'num_vlan'",
"]",
")",
"filters_of_envs",
"=",
"[",
"vlan",
".",
"ambiente",
".",
"filter",
".",
"id",
"for",
"vlan",
"in",
"vlans_current_number",
"]",
"for",
"fil_",
"in",
"filters_of_envs",
":",
"if",
"TipoEquipamento",
".",
"objects",
".",
"filter",
"(",
"id",
"=",
"id_tipo_equipamento",
",",
"filterequiptype__filter",
"=",
"fil_",
")",
".",
"count",
"(",
")",
"==",
"0",
":",
"filters_ok",
"=",
"False",
"break",
"if",
"not",
"filters_ok",
":",
"raise",
"EquipTypeCantBeChangedError",
"(",
"None",
",",
"'O tipo de equipamento não pode ser modificado pois existe um filtro em uso que não possui o novo tipo de equipamento informado.')",
"",
"# Filter case 3 end",
"# Test all vip requests if equip.tipo_equipamento is",
"# balancing",
"if",
"equip",
".",
"tipo_equipamento",
"==",
"TipoEquipamento",
".",
"get_tipo_balanceador",
"(",
")",
":",
"vips",
"=",
"RequisicaoVips",
".",
"objects",
".",
"all",
"(",
")",
"vip_ips",
"=",
"[",
"]",
"vip_ipsv6",
"=",
"[",
"]",
"for",
"vip",
"in",
"vips",
":",
"if",
"vip",
".",
"vip_criado",
":",
"if",
"vip",
".",
"ip",
"is",
"not",
"None",
":",
"if",
"vip",
".",
"ip",
".",
"ipequipamento_set",
".",
"filter",
"(",
"equipamento",
"=",
"equip",
".",
"id",
")",
".",
"count",
"(",
")",
">",
"0",
":",
"raise",
"EquipTypeCantBeChangedError",
"(",
"None",
",",
"'O tipo de equipamento não pode ser modificado pois este equipamento é o balanceador associado com o vip criado %s.' %",
"v",
"p.i",
"d",
")",
"",
"if",
"vip",
".",
"ipv6",
"is",
"not",
"None",
":",
"if",
"vip",
".",
"ipv6",
".",
"ipv6equipament_set",
".",
"filter",
"(",
"equipamento",
"=",
"equip",
".",
"id",
")",
".",
"count",
"(",
")",
">",
"0",
":",
"raise",
"EquipTypeCantBeChangedError",
"(",
"None",
",",
"'O tipo de equipamento não pode ser modificado pois este equipamento é o balanceador associado com o vip criado %s.' %",
"v",
"p.i",
"d",
")",
"",
"else",
":",
"if",
"vip",
".",
"ip",
"is",
"not",
"None",
":",
"vip_ips",
".",
"append",
"(",
"vip",
".",
"ip",
".",
"id",
")",
"if",
"vip",
".",
"ipv6",
"is",
"not",
"None",
":",
"vip_ipsv6",
".",
"append",
"(",
"vip",
".",
"ipv6",
".",
"id",
")",
"nets_using_balancer_in_vips_",
"=",
"[",
"ip_",
".",
"networkipv4",
"for",
"ip_",
"in",
"Ip",
".",
"objects",
".",
"filter",
"(",
"id__in",
"=",
"vip_ips",
")",
"]",
"nets_using_balancer_in_vips",
"=",
"[",
"ip_",
".",
"networkipv4",
"for",
"ip_",
"in",
"Ip",
".",
"objects",
".",
"filter",
"(",
"networkipv4__in",
"=",
"nets_using_balancer_in_vips_",
",",
"ipequipamento__equipamento",
"=",
"equip",
".",
"id",
")",
"]",
"nets_v6_using_balancer_in_vips_",
"=",
"[",
"ip_",
".",
"networkipv6",
"for",
"ip_",
"in",
"Ipv6",
".",
"objects",
".",
"filter",
"(",
"id__in",
"=",
"vip_ipsv6",
")",
"]",
"nets_v6_using_balancer_in_vips",
"=",
"[",
"ip_",
".",
"networkipv6",
"for",
"ip_",
"in",
"Ipv6",
".",
"objects",
".",
"filter",
"(",
"networkipv6__in",
"=",
"nets_v6_using_balancer_in_vips_",
",",
"ipv6equipament__equipamento",
"=",
"equip",
".",
"id",
")",
"]",
"for",
"net",
"in",
"nets_using_balancer_in_vips",
":",
"net_str",
"=",
"str",
"(",
"net",
".",
"oct1",
")",
"+",
"'.'",
"+",
"str",
"(",
"net",
".",
"oct2",
")",
"+",
"'.'",
"+",
"str",
"(",
"net",
".",
"oct3",
")",
"+",
"'.'",
"+",
"str",
"(",
"net",
".",
"oct4",
")",
"+",
"'/'",
"+",
"str",
"(",
"net",
".",
"block",
")",
"if",
"IpEquipamento",
".",
"objects",
".",
"filter",
"(",
"ip__networkipv4",
"=",
"net",
",",
"equipamento__tipo_equipamento",
"=",
"TipoEquipamento",
".",
"get_tipo_balanceador",
"(",
")",
")",
".",
"exclude",
"(",
"equipamento",
"=",
"equip",
")",
".",
"count",
"(",
")",
"==",
"0",
":",
"raise",
"EquipTypeCantBeChangedError",
"(",
"None",
",",
"'O tipo de equipamento não pode ser modificado pois este equipamento é o único balanceador disponível na rede %s da vlan %s.' % (",
"e",
"_",
"str, ne",
"t",
"vla",
"n",
".nom",
"e",
"))",
"",
"",
"for",
"net",
"in",
"nets_v6_using_balancer_in_vips",
":",
"net_str",
"=",
"str",
"(",
"net",
".",
"block1",
")",
"+",
"':'",
"+",
"str",
"(",
"net",
".",
"block2",
")",
"+",
"':'",
"+",
"str",
"(",
"net",
".",
"block3",
")",
"+",
"':'",
"+",
"str",
"(",
"net",
".",
"block4",
")",
"+",
"':'",
"+",
"str",
"(",
"net",
".",
"block5",
")",
"+",
"':'",
"+",
"str",
"(",
"net",
".",
"block6",
")",
"+",
"':'",
"+",
"str",
"(",
"net",
".",
"block7",
")",
"+",
"':'",
"+",
"str",
"(",
"net",
".",
"block8",
")",
"+",
"'/'",
"+",
"str",
"(",
"net",
".",
"block",
")",
"if",
"Ipv6Equipament",
".",
"objects",
".",
"filter",
"(",
"ip__networkipv6",
"=",
"net",
",",
"equipamento__tipo_equipamento",
"=",
"TipoEquipamento",
".",
"get_tipo_balanceador",
"(",
")",
")",
".",
"exclude",
"(",
"equipamento",
"=",
"equip",
")",
".",
"count",
"(",
")",
"==",
"0",
":",
"raise",
"EquipTypeCantBeChangedError",
"(",
"None",
",",
"'O tipo de equipamento não pode ser modificado pois este equipamento é o único balanceador disponível na rede %s da vlan %s.' % (",
"e",
"_",
"str, ne",
"t",
"vla",
"n",
".nom",
"e",
"))",
"",
"",
"ip_equipamento_list",
"=",
"IpEquipamento",
".",
"objects",
".",
"filter",
"(",
"equipamento",
"=",
"equip_id",
")",
"ip6_equipamento_list",
"=",
"Ipv6Equipament",
".",
"objects",
".",
"filter",
"(",
"equipamento",
"=",
"equip_id",
")",
"# Delete vlan's cache",
"key_list",
"=",
"[",
"]",
"for",
"eq",
"in",
"ip_equipamento_list",
":",
"vlan",
"=",
"eq",
".",
"ip",
".",
"networkipv4",
".",
"vlan",
"vlan_id",
"=",
"vlan",
".",
"id",
"key_list",
".",
"append",
"(",
"vlan_id",
")",
"for",
"eq",
"in",
"ip6_equipamento_list",
":",
"vlan",
"=",
"eq",
".",
"ip",
".",
"networkipv6",
".",
"vlan",
"vlan_id",
"=",
"vlan",
".",
"id",
"key_list",
".",
"append",
"(",
"vlan_id",
")",
"destroy_cache_function",
"(",
"key_list",
")",
"# Delete equipment's cache",
"destroy_cache_function",
"(",
"[",
"equip_id",
"]",
",",
"True",
")",
"modelo",
"=",
"Modelo",
".",
"get_by_pk",
"(",
"id_modelo",
")",
"equip",
".",
"edit",
"(",
"user",
",",
"nome",
",",
"tipo_equip",
",",
"modelo",
",",
"maintenance",
")",
"return",
"self",
".",
"response",
"(",
"dumps_networkapi",
"(",
"{",
"}",
")",
")",
"except",
"EquipTypeCantBeChangedError",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"150",
",",
"e",
".",
"message",
")",
"except",
"InvalidValueError",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"269",
",",
"e",
".",
"param",
",",
"e",
".",
"value",
")",
"except",
"TipoEquipamentoNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"100",
")",
"except",
"ModeloNotFoundError",
":",
"return",
"self",
".",
"response_error",
"(",
"101",
")",
"except",
"EquipamentoNotFoundError",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"117",
",",
"equip_id",
")",
"except",
"EquipamentoNameDuplicatedError",
",",
"e",
":",
"return",
"self",
".",
"response_error",
"(",
"e",
".",
"message",
")",
"except",
"(",
"EquipamentoError",
")",
",",
"e",
":",
"return",
"self",
".",
"responde_error",
"(",
"1",
")",
"except",
"UserNotAuthorizedError",
":",
"return",
"self",
".",
"not_authorized",
"(",
")",
"except",
"XMLError",
",",
"x",
":",
"self",
".",
"log",
".",
"error",
"(",
"u'Error reading the XML request.'",
")",
"return",
"self",
".",
"response_error",
"(",
"3",
",",
"x",
")"
]
| [
60,
4
]
| [
306,
44
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
convert_article_ALLxml | (spy=False) | Converte todos os arquivos HTML/XML que estão na pasta fonte. | Converte todos os arquivos HTML/XML que estão na pasta fonte. | def convert_article_ALLxml(spy=False):
"""Converte todos os arquivos HTML/XML que estão na pasta fonte."""
logger.debug("Starting XML conversion, it may take sometime.")
logger.warning(
"If you are facing problems with Python crashing during "
"conversion try to export this environment "
"variable: `OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES`"
)
xmls = [
os.path.join(config.get("SOURCE_PATH"), xml)
for xml in files.xml_files_list(config.get("SOURCE_PATH"))
]
jobs = [{"file_xml_path": xml, "spy": spy} for xml in xmls]
with tqdm(total=len(xmls)) as pbar:
def update_bar(pbar=pbar):
pbar.update(1)
def log_exceptions(exception, job, logger=logger):
logger.error(
"Could not convert file '%s'. The exception '%s' was raised.",
job["file_xml_path"],
exception,
)
DoJobsConcurrently(
convert_article_xml,
jobs=jobs,
executor=concurrent.futures.ProcessPoolExecutor,
max_workers=int(config.get("PROCESSPOOL_MAX_WORKERS")),
exception_callback=log_exceptions,
update_bar=update_bar,
) | [
"def",
"convert_article_ALLxml",
"(",
"spy",
"=",
"False",
")",
":",
"logger",
".",
"debug",
"(",
"\"Starting XML conversion, it may take sometime.\"",
")",
"logger",
".",
"warning",
"(",
"\"If you are facing problems with Python crashing during \"",
"\"conversion try to export this environment \"",
"\"variable: `OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES`\"",
")",
"xmls",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"config",
".",
"get",
"(",
"\"SOURCE_PATH\"",
")",
",",
"xml",
")",
"for",
"xml",
"in",
"files",
".",
"xml_files_list",
"(",
"config",
".",
"get",
"(",
"\"SOURCE_PATH\"",
")",
")",
"]",
"jobs",
"=",
"[",
"{",
"\"file_xml_path\"",
":",
"xml",
",",
"\"spy\"",
":",
"spy",
"}",
"for",
"xml",
"in",
"xmls",
"]",
"with",
"tqdm",
"(",
"total",
"=",
"len",
"(",
"xmls",
")",
")",
"as",
"pbar",
":",
"def",
"update_bar",
"(",
"pbar",
"=",
"pbar",
")",
":",
"pbar",
".",
"update",
"(",
"1",
")",
"def",
"log_exceptions",
"(",
"exception",
",",
"job",
",",
"logger",
"=",
"logger",
")",
":",
"logger",
".",
"error",
"(",
"\"Could not convert file '%s'. The exception '%s' was raised.\"",
",",
"job",
"[",
"\"file_xml_path\"",
"]",
",",
"exception",
",",
")",
"DoJobsConcurrently",
"(",
"convert_article_xml",
",",
"jobs",
"=",
"jobs",
",",
"executor",
"=",
"concurrent",
".",
"futures",
".",
"ProcessPoolExecutor",
",",
"max_workers",
"=",
"int",
"(",
"config",
".",
"get",
"(",
"\"PROCESSPOOL_MAX_WORKERS\"",
")",
")",
",",
"exception_callback",
"=",
"log_exceptions",
",",
"update_bar",
"=",
"update_bar",
",",
")"
]
| [
105,
0
]
| [
141,
9
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
DType21._text1_len | (self) | return bin2int(self.data[16:20]) | Retorna o tamanho do campo TEXT1 que contém o ‘unit_info’ no arquivo cfg. | Retorna o tamanho do campo TEXT1 que contém o ‘unit_info’ no arquivo cfg. | def _text1_len(self) -> int:
"""Retorna o tamanho do campo TEXT1 que contém o ‘unit_info’ no arquivo cfg."""
return bin2int(self.data[16:20]) | [
"def",
"_text1_len",
"(",
"self",
")",
"->",
"int",
":",
"return",
"bin2int",
"(",
"self",
".",
"data",
"[",
"16",
":",
"20",
"]",
")"
]
| [
461,
4
]
| [
463,
40
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Cachorro.__init__ | (self, nome, idade) | Inicializa os atributos nome e idade. | Inicializa os atributos nome e idade. | def __init__(self, nome, idade):
"""Inicializa os atributos nome e idade."""
self.nome = nome
self.idade = idade | [
"def",
"__init__",
"(",
"self",
",",
"nome",
",",
"idade",
")",
":",
"self",
".",
"nome",
"=",
"nome",
"self",
".",
"idade",
"=",
"idade"
]
| [
4,
4
]
| [
7,
26
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
CallbackARQ.recebe | (self, quadro) | Recebe dados de baixo e envia para cima | Recebe dados de baixo e envia para cima | def recebe(self, quadro):
''' Recebe dados de baixo e envia para cima '''
if quadro.tipo == 0:
e = Evento(TipoEvento.DATA, quadro)
else:
e = Evento(TipoEvento.ACK_TX, quadro)
self.mecanismoARQ(e) | [
"def",
"recebe",
"(",
"self",
",",
"quadro",
")",
":",
"if",
"quadro",
".",
"tipo",
"==",
"0",
":",
"e",
"=",
"Evento",
"(",
"TipoEvento",
".",
"DATA",
",",
"quadro",
")",
"else",
":",
"e",
"=",
"Evento",
"(",
"TipoEvento",
".",
"ACK_TX",
",",
"quadro",
")",
"self",
".",
"mecanismoARQ",
"(",
"e",
")"
]
| [
141,
4
]
| [
148,
28
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
name_changed | (streamers, header) | return streamers, streamers_modified | Função que verifica se o nome na base de dados está correto
ou se precisa alterar
| Função que verifica se o nome na base de dados está correto
ou se precisa alterar
| def name_changed(streamers, header):
"""Função que verifica se o nome na base de dados está correto
ou se precisa alterar
"""
# Booleano que guarda o estado de modificação do dataframe
streamers_modified = False
for streamer in streamers["Id"]:
# Obter o indice do streamer e o ID
index = streamers[streamers["Id"] == streamer].index
idt = streamers.loc[index, "Id"].values[0]
# Obter nome do streamer utilizando o ID
url = "https://api.twitch.tv/helix/channels"
param = {"broadcaster_id": str(idt)}
r = requests.get(url, params=param, headers=header).json()
# Obter nome real e o nome da DB do streamer
streamer_name = str(r["data"][0]["broadcaster_name"]).lower()
bd_name = str(streamers.loc[index, "Nome"].values[0]).lower()
# Verificar se são iguais
if streamer_name == bd_name:
pass
else:
# Se não temos de atualizar na DB e no dataframe
streamers_modified = True
name = streamer_name
twitch_link = "twitch.tv/" + name
# Atualizar o CSV/DataFrame
streamers.loc[index, "Nome"] = name
streamers.loc[index, "Twitch"] = twitch_link
# Apagar o velho valor da DB
delete_streamer(idt)
return streamers, streamers_modified | [
"def",
"name_changed",
"(",
"streamers",
",",
"header",
")",
":",
"# Booleano que guarda o estado de modificação do dataframe\r",
"streamers_modified",
"=",
"False",
"for",
"streamer",
"in",
"streamers",
"[",
"\"Id\"",
"]",
":",
"# Obter o indice do streamer e o ID\r",
"index",
"=",
"streamers",
"[",
"streamers",
"[",
"\"Id\"",
"]",
"==",
"streamer",
"]",
".",
"index",
"idt",
"=",
"streamers",
".",
"loc",
"[",
"index",
",",
"\"Id\"",
"]",
".",
"values",
"[",
"0",
"]",
"# Obter nome do streamer utilizando o ID\r",
"url",
"=",
"\"https://api.twitch.tv/helix/channels\"",
"param",
"=",
"{",
"\"broadcaster_id\"",
":",
"str",
"(",
"idt",
")",
"}",
"r",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"params",
"=",
"param",
",",
"headers",
"=",
"header",
")",
".",
"json",
"(",
")",
"# Obter nome real e o nome da DB do streamer\r",
"streamer_name",
"=",
"str",
"(",
"r",
"[",
"\"data\"",
"]",
"[",
"0",
"]",
"[",
"\"broadcaster_name\"",
"]",
")",
".",
"lower",
"(",
")",
"bd_name",
"=",
"str",
"(",
"streamers",
".",
"loc",
"[",
"index",
",",
"\"Nome\"",
"]",
".",
"values",
"[",
"0",
"]",
")",
".",
"lower",
"(",
")",
"# Verificar se são iguais\r",
"if",
"streamer_name",
"==",
"bd_name",
":",
"pass",
"else",
":",
"# Se não temos de atualizar na DB e no dataframe\r",
"streamers_modified",
"=",
"True",
"name",
"=",
"streamer_name",
"twitch_link",
"=",
"\"twitch.tv/\"",
"+",
"name",
"# Atualizar o CSV/DataFrame\r",
"streamers",
".",
"loc",
"[",
"index",
",",
"\"Nome\"",
"]",
"=",
"name",
"streamers",
".",
"loc",
"[",
"index",
",",
"\"Twitch\"",
"]",
"=",
"twitch_link",
"# Apagar o velho valor da DB\r",
"delete_streamer",
"(",
"idt",
")",
"return",
"streamers",
",",
"streamers_modified"
]
| [
90,
0
]
| [
132,
40
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Usu.apresentar | (self) | Exibe o nome do usuário de forma estilizada. | Exibe o nome do usuário de forma estilizada. | def apresentar(self):
"""Exibe o nome do usuário de forma estilizada."""
print("\nOlá, " + self.nome.title() + " " + self.sobrenome.title() +
". Bem vindo ao mundo da programação.") | [
"def",
"apresentar",
"(",
"self",
")",
":",
"print",
"(",
"\"\\nOlá, \" ",
" ",
"elf.",
"n",
"ome.",
"t",
"itle(",
")",
" ",
" ",
" \" ",
" ",
"elf.",
"s",
"obrenome.",
"t",
"itle(",
")",
" ",
"",
"\". Bem vindo ao mundo da programação.\")",
""
]
| [
17,
4
]
| [
20,
53
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Misc.oibot | (self, ctx) | Tá carente? Usa esse comando! | Tá carente? Usa esse comando! | async def oibot(self, ctx):
"""Tá carente? Usa esse comando!"""
await ctx.channel.send('Oieeeeee {}!'.format(ctx.message.author.name)) | [
"async",
"def",
"oibot",
"(",
"self",
",",
"ctx",
")",
":",
"await",
"ctx",
".",
"channel",
".",
"send",
"(",
"'Oieeeeee {}!'",
".",
"format",
"(",
"ctx",
".",
"message",
".",
"author",
".",
"name",
")",
")"
]
| [
300,
4
]
| [
302,
78
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
ResidenteForm.test_novo_residente_inativo | (self) | Testa se novos usaários tem como padrão is_active == False | Testa se novos usaários tem como padrão is_active == False | def test_novo_residente_inativo(self):
"""Testa se novos usaários tem como padrão is_active == False"""
self.assertFalse(self.user.is_active) | [
"def",
"test_novo_residente_inativo",
"(",
"self",
")",
":",
"self",
".",
"assertFalse",
"(",
"self",
".",
"user",
".",
"is_active",
")"
]
| [
92,
4
]
| [
94,
45
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Campanha.obter_tarefa | (self, usuario, gerar_novo_trabalho=False) | return tarefa | Obtem uma tarefa para uma campanha ativa.
Retorna nulo para campanhas com tarefas completas.
Cria um job de tarefa para um usuário caso ele não exista. | Obtem uma tarefa para uma campanha ativa.
Retorna nulo para campanhas com tarefas completas.
Cria um job de tarefa para um usuário caso ele não exista. | def obter_tarefa(self, usuario, gerar_novo_trabalho=False):
"""Obtem uma tarefa para uma campanha ativa.
Retorna nulo para campanhas com tarefas completas.
Cria um job de tarefa para um usuário caso ele não exista. """
trabalho_ativo = self.obter_trabalho(usuario)
# se a situacao do trabalho for inativa não retorna tarefa nenhuma
if (trabalho_ativo and
trabalho_ativo.situacao == 'F' and
not gerar_novo_trabalho):
return None
# se a situacao do trabalho for inativa e ousuário quiser
# alocar mais um grupo de trabalho, permite
if (trabalho_ativo and
trabalho_ativo.situacao == 'F' and
gerar_novo_trabalho):
trabalho_ativo = None
if not trabalho_ativo:
# Caso não tenha trabalho ativo,
# cria um set de trabalho automaticamente
ids_tarefas = [id for id in [self.tarefa_set.values_list(
'id', flat=True)]]
random.shuffle(ids_tarefas)
tarefas_trabalho = ids_tarefas[:self.tarefas_por_trabalho]
tarefas = Tarefa.objects.filter(id__in=tarefas_trabalho)
trabalho_ativo = Trabalho(
username=usuario,
situacao='A'
)
trabalho_ativo.save()
trabalho_ativo.tarefas.set(tarefas)
ids_tarefas_realizadas = trabalho_ativo.tarefas.filter(
resposta__username=usuario).values_list('id', flat=True)
tarefa = trabalho_ativo.tarefas.exclude(
id__in=ids_tarefas_realizadas).first()
if trabalho_ativo.situacao == 'A' and not tarefa:
trabalho_ativo.situacao = 'F'
trabalho_ativo.save()
return tarefa | [
"def",
"obter_tarefa",
"(",
"self",
",",
"usuario",
",",
"gerar_novo_trabalho",
"=",
"False",
")",
":",
"trabalho_ativo",
"=",
"self",
".",
"obter_trabalho",
"(",
"usuario",
")",
"# se a situacao do trabalho for inativa não retorna tarefa nenhuma",
"if",
"(",
"trabalho_ativo",
"and",
"trabalho_ativo",
".",
"situacao",
"==",
"'F'",
"and",
"not",
"gerar_novo_trabalho",
")",
":",
"return",
"None",
"# se a situacao do trabalho for inativa e ousuário quiser",
"# alocar mais um grupo de trabalho, permite",
"if",
"(",
"trabalho_ativo",
"and",
"trabalho_ativo",
".",
"situacao",
"==",
"'F'",
"and",
"gerar_novo_trabalho",
")",
":",
"trabalho_ativo",
"=",
"None",
"if",
"not",
"trabalho_ativo",
":",
"# Caso não tenha trabalho ativo,",
"# cria um set de trabalho automaticamente",
"ids_tarefas",
"=",
"[",
"id",
"for",
"id",
"in",
"[",
"self",
".",
"tarefa_set",
".",
"values_list",
"(",
"'id'",
",",
"flat",
"=",
"True",
")",
"]",
"]",
"random",
".",
"shuffle",
"(",
"ids_tarefas",
")",
"tarefas_trabalho",
"=",
"ids_tarefas",
"[",
":",
"self",
".",
"tarefas_por_trabalho",
"]",
"tarefas",
"=",
"Tarefa",
".",
"objects",
".",
"filter",
"(",
"id__in",
"=",
"tarefas_trabalho",
")",
"trabalho_ativo",
"=",
"Trabalho",
"(",
"username",
"=",
"usuario",
",",
"situacao",
"=",
"'A'",
")",
"trabalho_ativo",
".",
"save",
"(",
")",
"trabalho_ativo",
".",
"tarefas",
".",
"set",
"(",
"tarefas",
")",
"ids_tarefas_realizadas",
"=",
"trabalho_ativo",
".",
"tarefas",
".",
"filter",
"(",
"resposta__username",
"=",
"usuario",
")",
".",
"values_list",
"(",
"'id'",
",",
"flat",
"=",
"True",
")",
"tarefa",
"=",
"trabalho_ativo",
".",
"tarefas",
".",
"exclude",
"(",
"id__in",
"=",
"ids_tarefas_realizadas",
")",
".",
"first",
"(",
")",
"if",
"trabalho_ativo",
".",
"situacao",
"==",
"'A'",
"and",
"not",
"tarefa",
":",
"trabalho_ativo",
".",
"situacao",
"=",
"'F'",
"trabalho_ativo",
".",
"save",
"(",
")",
"return",
"tarefa"
]
| [
51,
4
]
| [
98,
21
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
RandomAgentProgram | (actions) | return lambda percept: random.choice(actions) | Um agente que escolhe uma ação aleatoriamente, ignorando todas as percepções. | Um agente que escolhe uma ação aleatoriamente, ignorando todas as percepções. | def RandomAgentProgram(actions):
"Um agente que escolhe uma ação aleatoriamente, ignorando todas as percepções."
return lambda percept: random.choice(actions) | [
"def",
"RandomAgentProgram",
"(",
"actions",
")",
":",
"return",
"lambda",
"percept",
":",
"random",
".",
"choice",
"(",
"actions",
")"
]
| [
90,
0
]
| [
92,
49
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Misc.enviar | (self, ctx, user: Union[discord.Member, discord.User], *, msg: str) | Envia uma mensagem para a dm da pessoa mencionada.
é necessário de que a DM dela esteja aberta. | Envia uma mensagem para a dm da pessoa mencionada.
é necessário de que a DM dela esteja aberta. | async def enviar(self, ctx, user: Union[discord.Member, discord.User], *, msg: str):
"""Envia uma mensagem para a dm da pessoa mencionada.
é necessário de que a DM dela esteja aberta."""
description = """
Lembre-se de responder a mensagem enviada usando o novo sistema, conforme o
exemplo abaixo.
"""
files = [await att.to_file() for att in ctx.message.attachments]
respmsg = await user.send(msg, files=files)
embed = discord.Embed(title="Responda seu amigo (ou inimigo) anônimo!",
description="Para responder use `,responder <mensagem>`\n" + description,
color=self._get_embed_color(ctx))
embed.set_image(url="https://i.ibb.co/sF6pVsn/enviar-example.png")
await user.send(embed=embed)
if ctx.guild is not None:
# não pode apagar mensagens do destinatário na DM
await ctx.message.delete()
def check(message: discord.Message):
msgcon = message.content.startswith(",responder") or \
message.content.startswith(",report") and message.reference is not None \
and message.reference.message_id == respmsg.id
return message.author.id == user.id and message.guild is None and msgcon
guild = self.client.get_guild(790744527450800139)
channel = guild.get_channel(790744527941009480)
enviar_embed = discord.Embed(title=",enviar usado.", description=ctx.message.content,
color=self._get_embed_color(ctx))
enviar_embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar_url)
await channel.send(embed=enviar_embed)
try:
message = await self.client.wait_for("message",
check=check,
timeout=300.0)
except asyncio.TimeoutError:
return
else:
con = " ".join(message.content.split(" ")[1:])
embed = discord.Embed(
title=f"E ele respondeu!",
color=discord.Color.red(),
description=con,
)
await message.add_reaction("👍")
embed.set_author(name=str(user), icon_url=message.author.avatar_url)
files = None
if message.attachments:
files = [await att.to_file() for att in message.attachments]
await ctx.author.send(embed=embed, files=files) | [
"async",
"def",
"enviar",
"(",
"self",
",",
"ctx",
",",
"user",
":",
"Union",
"[",
"discord",
".",
"Member",
",",
"discord",
".",
"User",
"]",
",",
"*",
",",
"msg",
":",
"str",
")",
":",
"description",
"=",
"\"\"\"\r\n Lembre-se de responder a mensagem enviada usando o novo sistema, conforme o\r\n exemplo abaixo.\r\n \"\"\"",
"files",
"=",
"[",
"await",
"att",
".",
"to_file",
"(",
")",
"for",
"att",
"in",
"ctx",
".",
"message",
".",
"attachments",
"]",
"respmsg",
"=",
"await",
"user",
".",
"send",
"(",
"msg",
",",
"files",
"=",
"files",
")",
"embed",
"=",
"discord",
".",
"Embed",
"(",
"title",
"=",
"\"Responda seu amigo (ou inimigo) anônimo!\",",
"\r",
"description",
"=",
"\"Para responder use `,responder <mensagem>`\\n\"",
"+",
"description",
",",
"color",
"=",
"self",
".",
"_get_embed_color",
"(",
"ctx",
")",
")",
"embed",
".",
"set_image",
"(",
"url",
"=",
"\"https://i.ibb.co/sF6pVsn/enviar-example.png\"",
")",
"await",
"user",
".",
"send",
"(",
"embed",
"=",
"embed",
")",
"if",
"ctx",
".",
"guild",
"is",
"not",
"None",
":",
"# não pode apagar mensagens do destinatário na DM\r",
"await",
"ctx",
".",
"message",
".",
"delete",
"(",
")",
"def",
"check",
"(",
"message",
":",
"discord",
".",
"Message",
")",
":",
"msgcon",
"=",
"message",
".",
"content",
".",
"startswith",
"(",
"\",responder\"",
")",
"or",
"message",
".",
"content",
".",
"startswith",
"(",
"\",report\"",
")",
"and",
"message",
".",
"reference",
"is",
"not",
"None",
"and",
"message",
".",
"reference",
".",
"message_id",
"==",
"respmsg",
".",
"id",
"return",
"message",
".",
"author",
".",
"id",
"==",
"user",
".",
"id",
"and",
"message",
".",
"guild",
"is",
"None",
"and",
"msgcon",
"guild",
"=",
"self",
".",
"client",
".",
"get_guild",
"(",
"790744527450800139",
")",
"channel",
"=",
"guild",
".",
"get_channel",
"(",
"790744527941009480",
")",
"enviar_embed",
"=",
"discord",
".",
"Embed",
"(",
"title",
"=",
"\",enviar usado.\"",
",",
"description",
"=",
"ctx",
".",
"message",
".",
"content",
",",
"color",
"=",
"self",
".",
"_get_embed_color",
"(",
"ctx",
")",
")",
"enviar_embed",
".",
"set_author",
"(",
"name",
"=",
"ctx",
".",
"author",
".",
"name",
",",
"icon_url",
"=",
"ctx",
".",
"author",
".",
"avatar_url",
")",
"await",
"channel",
".",
"send",
"(",
"embed",
"=",
"enviar_embed",
")",
"try",
":",
"message",
"=",
"await",
"self",
".",
"client",
".",
"wait_for",
"(",
"\"message\"",
",",
"check",
"=",
"check",
",",
"timeout",
"=",
"300.0",
")",
"except",
"asyncio",
".",
"TimeoutError",
":",
"return",
"else",
":",
"con",
"=",
"\" \"",
".",
"join",
"(",
"message",
".",
"content",
".",
"split",
"(",
"\" \"",
")",
"[",
"1",
":",
"]",
")",
"embed",
"=",
"discord",
".",
"Embed",
"(",
"title",
"=",
"f\"E ele respondeu!\"",
",",
"color",
"=",
"discord",
".",
"Color",
".",
"red",
"(",
")",
",",
"description",
"=",
"con",
",",
")",
"await",
"message",
".",
"add_reaction",
"(",
"\"👍\")\r",
"",
"embed",
".",
"set_author",
"(",
"name",
"=",
"str",
"(",
"user",
")",
",",
"icon_url",
"=",
"message",
".",
"author",
".",
"avatar_url",
")",
"files",
"=",
"None",
"if",
"message",
".",
"attachments",
":",
"files",
"=",
"[",
"await",
"att",
".",
"to_file",
"(",
")",
"for",
"att",
"in",
"message",
".",
"attachments",
"]",
"await",
"ctx",
".",
"author",
".",
"send",
"(",
"embed",
"=",
"embed",
",",
"files",
"=",
"files",
")"
]
| [
306,
4
]
| [
360,
59
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
SASM.referencia | (self, modo='curto') | return Ref | funcao que retorna a referência da funcao
modo: como a funcao vai retornar a funcao:
'longo': referencia completa
'curto' (padrão): referencia por citação
| funcao que retorna a referência da funcao
modo: como a funcao vai retornar a funcao:
'longo': referencia completa
'curto' (padrão): referencia por citação
| def referencia(self, modo='curto'):
""" funcao que retorna a referência da funcao
modo: como a funcao vai retornar a funcao:
'longo': referencia completa
'curto' (padrão): referencia por citação
"""
if modo == 'curto':
Ref = 'Dorji et al. 2016'
else:
Ref = 'Ref: Dorji P, Fearns P, Broomhall M. A Semi-Analytic Model for Estimating Total Suspended Sediment Con- centration in Turbid Coastal Waters of Northern Western Australia Using MODIS-Aqua 250mData. Remote Sensing. 2016; 8(7):556'
return Ref | [
"def",
"referencia",
"(",
"self",
",",
"modo",
"=",
"'curto'",
")",
":",
"if",
"modo",
"==",
"'curto'",
":",
"Ref",
"=",
"'Dorji et al. 2016'",
"else",
":",
"Ref",
"=",
"'Ref: Dorji P, Fearns P, Broomhall M. A Semi-Analytic Model for Estimating Total Suspended Sediment Con- centration in Turbid Coastal Waters of Northern Western Australia Using MODIS-Aqua 250mData. Remote Sensing. 2016; 8(7):556'",
"return",
"Ref"
]
| [
40,
4
]
| [
54,
18
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Room.is_deadly | (self, danger=None) | Retorna True se a sala contiver o Wumpus ou um poço. | Retorna True se a sala contiver o Wumpus ou um poço. | def is_deadly(self, danger=None):
"""Retorna True se a sala contiver o Wumpus ou um poço."""
if danger is None:
return self.wumpus == Status.Present or self.pit == Status.Present
if danger == Entity.Wumpus:
return self.wumpus == Status.Present
if danger == Entity.Pit:
return self.pit == Status.Present
raise ValueError | [
"def",
"is_deadly",
"(",
"self",
",",
"danger",
"=",
"None",
")",
":",
"if",
"danger",
"is",
"None",
":",
"return",
"self",
".",
"wumpus",
"==",
"Status",
".",
"Present",
"or",
"self",
".",
"pit",
"==",
"Status",
".",
"Present",
"if",
"danger",
"==",
"Entity",
".",
"Wumpus",
":",
"return",
"self",
".",
"wumpus",
"==",
"Status",
".",
"Present",
"if",
"danger",
"==",
"Entity",
".",
"Pit",
":",
"return",
"self",
".",
"pit",
"==",
"Status",
".",
"Present",
"raise",
"ValueError"
]
| [
66,
2
]
| [
76,
20
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
create | () | return render_template('emprestimo/create.html', data=data, success=success, socios_id=socios_id, livros_tombo=livros_tombo, datadevolucao=datadevolucao) | Cria um novo emprestimo. | Cria um novo emprestimo. | def create():
"""Cria um novo emprestimo."""
data = {
'error': '',
'livro': '',
'socio': ''
}
datadevolucao = ''
success = False
try:
socios_id = db.query_bd('select id from socio order by id')
livros_tombo = db.query_bd('select tombo from livro order by tombo')
except Exception as e:
print(e)
return render_template('404.html')
if request.method == 'POST':
try:
idsocio = request.form['idsocio']
tombo = request.form['tombo']
retirada = request.form['retirada']
datadevolucao = datetime.strptime(retirada, '%Y-%m-%d') + timedelta(days=5)
devolucao = str(datadevolucao).split(" ")[0]
data['livro'] = livro = db.query_one('select * from livro where tombo = %s' % tombo)
data['socio'] = socio = db.query_one('select * from socio where id = %s' % idsocio)
qtdlivro = livro['qtd']
if qtdlivro <= 0:
data['error'] = 'Este livro não está disponível!'
elif data['socio']['status'] == 'SUSPENSO':
data['error'] = 'Não é possível criar empréstimo pois o sócio está suspenso!'
elif livro['status'] == 'ESTANTE':
qtdlivro -= 1
sql = "insert into emprestimo values(default, '%s', '%s', '%s', '%s')" % (retirada, devolucao, tombo, idsocio)
db.insert_bd(sql)
db.insert_bd('UPDATE livro SET qtd = "%s" WHERE tombo = "%s" ' % (qtdlivro, tombo))
success = True
if qtdlivro == 0:
db.insert_bd('UPDATE livro SET status = "EMPRESTADO" WHERE tombo = "%s" ' % tombo)
elif livro['status'] == 'EMPRESTADO':
data['error'] = 'Este livro não pode ser emprestado! ' \
'Pois já está emprestado.'
elif livro['status'] == 'PERDIDO':
data['error'] = 'Este livro não pode ser emprestado! ' \
'Pois está perdido.'
elif livro['status'] == 'EXTRAVIADO':
data['error'] = 'Este livro não pode ser emprestado! ' \
'Pois está extraviado.'
elif livro['status'] == 'RESERVADO':
reserva = db.query_one('select * from reserva where tombo = %s and id_socio = %s' % (tombo, idsocio))
if reserva:
qtdlivro -= 1
db.insert_bd("insert into emprestimo values(default, '%s', '%s', '%s', '%s')" % (retirada, devolucao, tombo, idsocio))
db.insert_bd("delete from reserva where id = %s" % reserva['id'])
db.insert_bd('UPDATE livro SET qtd = "%s" WHERE tombo = "%s" ' % (qtdlivro, tombo))
success = True
if qtdlivro == 0:
db.insert_bd('UPDATE livro SET status = "EMPRESTADO" WHERE tombo = "%s" ' % tombo)
data['error'] = 'Este livro não pode ser emprestado! ' \
'Pois está reservado.'
except Exception as e:
print(e)
return render_template('404.html')
return render_template('emprestimo/create.html', data=data, success=success, socios_id=socios_id, livros_tombo=livros_tombo, datadevolucao=datadevolucao) | [
"def",
"create",
"(",
")",
":",
"data",
"=",
"{",
"'error'",
":",
"''",
",",
"'livro'",
":",
"''",
",",
"'socio'",
":",
"''",
"}",
"datadevolucao",
"=",
"''",
"success",
"=",
"False",
"try",
":",
"socios_id",
"=",
"db",
".",
"query_bd",
"(",
"'select id from socio order by id'",
")",
"livros_tombo",
"=",
"db",
".",
"query_bd",
"(",
"'select tombo from livro order by tombo'",
")",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"e",
")",
"return",
"render_template",
"(",
"'404.html'",
")",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"try",
":",
"idsocio",
"=",
"request",
".",
"form",
"[",
"'idsocio'",
"]",
"tombo",
"=",
"request",
".",
"form",
"[",
"'tombo'",
"]",
"retirada",
"=",
"request",
".",
"form",
"[",
"'retirada'",
"]",
"datadevolucao",
"=",
"datetime",
".",
"strptime",
"(",
"retirada",
",",
"'%Y-%m-%d'",
")",
"+",
"timedelta",
"(",
"days",
"=",
"5",
")",
"devolucao",
"=",
"str",
"(",
"datadevolucao",
")",
".",
"split",
"(",
"\" \"",
")",
"[",
"0",
"]",
"data",
"[",
"'livro'",
"]",
"=",
"livro",
"=",
"db",
".",
"query_one",
"(",
"'select * from livro where tombo = %s'",
"%",
"tombo",
")",
"data",
"[",
"'socio'",
"]",
"=",
"socio",
"=",
"db",
".",
"query_one",
"(",
"'select * from socio where id = %s'",
"%",
"idsocio",
")",
"qtdlivro",
"=",
"livro",
"[",
"'qtd'",
"]",
"if",
"qtdlivro",
"<=",
"0",
":",
"data",
"[",
"'error'",
"]",
"=",
"'Este livro não está disponível!'",
"elif",
"data",
"[",
"'socio'",
"]",
"[",
"'status'",
"]",
"==",
"'SUSPENSO'",
":",
"data",
"[",
"'error'",
"]",
"=",
"'Não é possível criar empréstimo pois o sócio está suspenso!'",
"elif",
"livro",
"[",
"'status'",
"]",
"==",
"'ESTANTE'",
":",
"qtdlivro",
"-=",
"1",
"sql",
"=",
"\"insert into emprestimo values(default, '%s', '%s', '%s', '%s')\"",
"%",
"(",
"retirada",
",",
"devolucao",
",",
"tombo",
",",
"idsocio",
")",
"db",
".",
"insert_bd",
"(",
"sql",
")",
"db",
".",
"insert_bd",
"(",
"'UPDATE livro SET qtd = \"%s\" WHERE tombo = \"%s\" '",
"%",
"(",
"qtdlivro",
",",
"tombo",
")",
")",
"success",
"=",
"True",
"if",
"qtdlivro",
"==",
"0",
":",
"db",
".",
"insert_bd",
"(",
"'UPDATE livro SET status = \"EMPRESTADO\" WHERE tombo = \"%s\" '",
"%",
"tombo",
")",
"elif",
"livro",
"[",
"'status'",
"]",
"==",
"'EMPRESTADO'",
":",
"data",
"[",
"'error'",
"]",
"=",
"'Este livro não pode ser emprestado! ' ",
"'Pois já está emprestado.'",
"elif",
"livro",
"[",
"'status'",
"]",
"==",
"'PERDIDO'",
":",
"data",
"[",
"'error'",
"]",
"=",
"'Este livro não pode ser emprestado! ' ",
"'Pois está perdido.'",
"elif",
"livro",
"[",
"'status'",
"]",
"==",
"'EXTRAVIADO'",
":",
"data",
"[",
"'error'",
"]",
"=",
"'Este livro não pode ser emprestado! ' ",
"'Pois está extraviado.'",
"elif",
"livro",
"[",
"'status'",
"]",
"==",
"'RESERVADO'",
":",
"reserva",
"=",
"db",
".",
"query_one",
"(",
"'select * from reserva where tombo = %s and id_socio = %s'",
"%",
"(",
"tombo",
",",
"idsocio",
")",
")",
"if",
"reserva",
":",
"qtdlivro",
"-=",
"1",
"db",
".",
"insert_bd",
"(",
"\"insert into emprestimo values(default, '%s', '%s', '%s', '%s')\"",
"%",
"(",
"retirada",
",",
"devolucao",
",",
"tombo",
",",
"idsocio",
")",
")",
"db",
".",
"insert_bd",
"(",
"\"delete from reserva where id = %s\"",
"%",
"reserva",
"[",
"'id'",
"]",
")",
"db",
".",
"insert_bd",
"(",
"'UPDATE livro SET qtd = \"%s\" WHERE tombo = \"%s\" '",
"%",
"(",
"qtdlivro",
",",
"tombo",
")",
")",
"success",
"=",
"True",
"if",
"qtdlivro",
"==",
"0",
":",
"db",
".",
"insert_bd",
"(",
"'UPDATE livro SET status = \"EMPRESTADO\" WHERE tombo = \"%s\" '",
"%",
"tombo",
")",
"data",
"[",
"'error'",
"]",
"=",
"'Este livro não pode ser emprestado! ' ",
"'Pois está reservado.'",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"e",
")",
"return",
"render_template",
"(",
"'404.html'",
")",
"return",
"render_template",
"(",
"'emprestimo/create.html'",
",",
"data",
"=",
"data",
",",
"success",
"=",
"success",
",",
"socios_id",
"=",
"socios_id",
",",
"livros_tombo",
"=",
"livros_tombo",
",",
"datadevolucao",
"=",
"datadevolucao",
")"
]
| [
79,
0
]
| [
152,
157
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
print_api_endpoints | () | Imprime no log todos os endpoints disponibilizados por esta API. | Imprime no log todos os endpoints disponibilizados por esta API. | def print_api_endpoints():
"""Imprime no log todos os endpoints disponibilizados por esta API."""
logging.info(f"Endpoints do serviço Data Query Proxy:")
for handler, (rule, router) in app.router.routes_names.items():
for method in router.methods:
if method not in ['OPTIONS', 'HEAD']:
logging.info(f"- {method:6s} {rule}") | [
"def",
"print_api_endpoints",
"(",
")",
":",
"logging",
".",
"info",
"(",
"f\"Endpoints do serviço Data Query Proxy:\")",
"",
"for",
"handler",
",",
"(",
"rule",
",",
"router",
")",
"in",
"app",
".",
"router",
".",
"routes_names",
".",
"items",
"(",
")",
":",
"for",
"method",
"in",
"router",
".",
"methods",
":",
"if",
"method",
"not",
"in",
"[",
"'OPTIONS'",
",",
"'HEAD'",
"]",
":",
"logging",
".",
"info",
"(",
"f\"- {method:6s} {rule}\"",
")"
]
| [
43,
0
]
| [
49,
53
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
index | (request) | return render(request, 'receitas/index.html', dados) | Mostra as receitas publicadas na página inicial | Mostra as receitas publicadas na página inicial | def index(request):
"""Mostra as receitas publicadas na página inicial"""
# mostrando na página as receitas em ordem da mais nova para a mais antiga e apenas
# as publicadas
receitas = Receita.objects.order_by('-data_receita').filter(receita_publicada=True)
paginator = Paginator(receitas, 5) # receitas por página
page = request.GET.get('page') # identificação da página da navegação
receitas_por_pagina = paginator.get_page(page)
dados = {'receitas': receitas_por_pagina}
return render(request, 'receitas/index.html', dados) | [
"def",
"index",
"(",
"request",
")",
":",
"# mostrando na página as receitas em ordem da mais nova para a mais antiga e apenas",
"# as publicadas",
"receitas",
"=",
"Receita",
".",
"objects",
".",
"order_by",
"(",
"'-data_receita'",
")",
".",
"filter",
"(",
"receita_publicada",
"=",
"True",
")",
"paginator",
"=",
"Paginator",
"(",
"receitas",
",",
"5",
")",
"# receitas por página",
"page",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'page'",
")",
"# identificação da página da navegação",
"receitas_por_pagina",
"=",
"paginator",
".",
"get_page",
"(",
"page",
")",
"dados",
"=",
"{",
"'receitas'",
":",
"receitas_por_pagina",
"}",
"return",
"render",
"(",
"request",
",",
"'receitas/index.html'",
",",
"dados",
")"
]
| [
7,
0
]
| [
16,
56
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
le_assinatura | () | return [wal, ttr, hlr, sal, sac, pal] | A funcao le os valores dos tracos linguisticos do modelo e devolve uma assinatura a ser comparada com os textos fornecidos | A funcao le os valores dos tracos linguisticos do modelo e devolve uma assinatura a ser comparada com os textos fornecidos | def le_assinatura():
'''A funcao le os valores dos tracos linguisticos do modelo e devolve uma assinatura a ser comparada com os textos fornecidos'''
print("Bem-vindo ao detector automático de COH-PIAH.")
print("Informe a assinatura típica de um aluno infectado: ")
wal = float(input("Entre o tamanho médio de palavra: "))
ttr = float(input("Entre a relação Type-Token: "))
hlr = float(input("Entre a Razão Hapax Legomana: "))
sal = float(input("Entre o tamanho médio de sentença: "))
sac = float(input("Entre a complexidade média da sentença: "))
pal = float(input("Entre o tamanho medio de frase: "))
return [wal, ttr, hlr, sal, sac, pal] | [
"def",
"le_assinatura",
"(",
")",
":",
"print",
"(",
"\"Bem-vindo ao detector automático de COH-PIAH.\")",
"\r",
"print",
"(",
"\"Informe a assinatura típica de um aluno infectado: \")",
"\r",
"wal",
"=",
"float",
"(",
"input",
"(",
"\"Entre o tamanho médio de palavra: \")",
")",
"\r",
"ttr",
"=",
"float",
"(",
"input",
"(",
"\"Entre a relação Type-Token: \"))",
"\r",
"",
"hlr",
"=",
"float",
"(",
"input",
"(",
"\"Entre a Razão Hapax Legomana: \")",
")",
"\r",
"sal",
"=",
"float",
"(",
"input",
"(",
"\"Entre o tamanho médio de sentença: \"))",
"\r",
"",
"sac",
"=",
"float",
"(",
"input",
"(",
"\"Entre a complexidade média da sentença: \"))",
"\r",
"",
"pal",
"=",
"float",
"(",
"input",
"(",
"\"Entre o tamanho medio de frase: \"",
")",
")",
"return",
"[",
"wal",
",",
"ttr",
",",
"hlr",
",",
"sal",
",",
"sac",
",",
"pal",
"]"
]
| [
2,
0
]
| [
14,
41
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
get_proc_infos | (process_filter) | return procs | Captura informações (ppid, pid, nome, % CPU, prioridade e status) dos
processos e retorna na forma de uma lista de dicionários. | Captura informações (ppid, pid, nome, % CPU, prioridade e status) dos
processos e retorna na forma de uma lista de dicionários. | def get_proc_infos(process_filter):
""" Captura informações (ppid, pid, nome, % CPU, prioridade e status) dos
processos e retorna na forma de uma lista de dicionários. """
attrs = ['ppid','pid', 'cpu_percent', 'nice', 'status', 'name']
if len(process_filter.get()):
processes = []
for p in psutil.process_iter(attrs):
if process_filter.get() in p.info['name'] or process_filter.get() in str(p.info['pid']):
processes.append(p.info)
else:
processes = [p.info for p in psutil.process_iter(attrs)]
def sort_func(proc): return proc['cpu_percent']
processes.sort(key=sort_func, reverse=True)
procs = []
for p in processes:
proc = []
proc.append(str(p['ppid']))
proc.append(str(p['pid']))
proc.append(str(p['cpu_percent']/psutil.cpu_count()))
proc.append(str(p['status']))
proc.append(str(p['nice']))
proc.append(str(p['name']))
procs.append(proc)
return procs | [
"def",
"get_proc_infos",
"(",
"process_filter",
")",
":",
"attrs",
"=",
"[",
"'ppid'",
",",
"'pid'",
",",
"'cpu_percent'",
",",
"'nice'",
",",
"'status'",
",",
"'name'",
"]",
"if",
"len",
"(",
"process_filter",
".",
"get",
"(",
")",
")",
":",
"processes",
"=",
"[",
"]",
"for",
"p",
"in",
"psutil",
".",
"process_iter",
"(",
"attrs",
")",
":",
"if",
"process_filter",
".",
"get",
"(",
")",
"in",
"p",
".",
"info",
"[",
"'name'",
"]",
"or",
"process_filter",
".",
"get",
"(",
")",
"in",
"str",
"(",
"p",
".",
"info",
"[",
"'pid'",
"]",
")",
":",
"processes",
".",
"append",
"(",
"p",
".",
"info",
")",
"else",
":",
"processes",
"=",
"[",
"p",
".",
"info",
"for",
"p",
"in",
"psutil",
".",
"process_iter",
"(",
"attrs",
")",
"]",
"def",
"sort_func",
"(",
"proc",
")",
":",
"return",
"proc",
"[",
"'cpu_percent'",
"]",
"processes",
".",
"sort",
"(",
"key",
"=",
"sort_func",
",",
"reverse",
"=",
"True",
")",
"procs",
"=",
"[",
"]",
"for",
"p",
"in",
"processes",
":",
"proc",
"=",
"[",
"]",
"proc",
".",
"append",
"(",
"str",
"(",
"p",
"[",
"'ppid'",
"]",
")",
")",
"proc",
".",
"append",
"(",
"str",
"(",
"p",
"[",
"'pid'",
"]",
")",
")",
"proc",
".",
"append",
"(",
"str",
"(",
"p",
"[",
"'cpu_percent'",
"]",
"/",
"psutil",
".",
"cpu_count",
"(",
")",
")",
")",
"proc",
".",
"append",
"(",
"str",
"(",
"p",
"[",
"'status'",
"]",
")",
")",
"proc",
".",
"append",
"(",
"str",
"(",
"p",
"[",
"'nice'",
"]",
")",
")",
"proc",
".",
"append",
"(",
"str",
"(",
"p",
"[",
"'name'",
"]",
")",
")",
"procs",
".",
"append",
"(",
"proc",
")",
"return",
"procs"
]
| [
20,
0
]
| [
50,
16
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
_TriLPlusVDVTLightweightOperatorPD.sqrt_log_abs_det | (self) | return log_det_c + 2. * self._d.sqrt_log_abs_det() + log_det_m | Computes (log o abs o det)(X) for matrix X.
Doesn't actually do the sqrt! Named as such to agree with API.
To compute det(M + V D V.T), we use the matrix determinant lemma:
det(Tril + V D V.T) = det(C) det(D) det(M)
where C is defined as in `_inverse`, ie,
C = inv(D) + V.T inv(M) V.
See: https://en.wikipedia.org/wiki/Matrix_determinant_lemma
Returns:
log_abs_det: `Tensor`.
| Computes (log o abs o det)(X) for matrix X. | def sqrt_log_abs_det(self):
"""Computes (log o abs o det)(X) for matrix X.
Doesn't actually do the sqrt! Named as such to agree with API.
To compute det(M + V D V.T), we use the matrix determinant lemma:
det(Tril + V D V.T) = det(C) det(D) det(M)
where C is defined as in `_inverse`, ie,
C = inv(D) + V.T inv(M) V.
See: https://en.wikipedia.org/wiki/Matrix_determinant_lemma
Returns:
log_abs_det: `Tensor`.
"""
log_det_c = math_ops.log(math_ops.abs(
linalg_ops.matrix_determinant(self._woodbury_sandwiched_term())))
# Reduction is ok because we always prepad inputs to this class.
log_det_m = math_ops.reduce_sum(math_ops.log(math_ops.abs(
array_ops.matrix_diag_part(self._m))), axis=[-1])
return log_det_c + 2. * self._d.sqrt_log_abs_det() + log_det_m | [
"def",
"sqrt_log_abs_det",
"(",
"self",
")",
":",
"log_det_c",
"=",
"math_ops",
".",
"log",
"(",
"math_ops",
".",
"abs",
"(",
"linalg_ops",
".",
"matrix_determinant",
"(",
"self",
".",
"_woodbury_sandwiched_term",
"(",
")",
")",
")",
")",
"# Reduction is ok because we always prepad inputs to this class.",
"log_det_m",
"=",
"math_ops",
".",
"reduce_sum",
"(",
"math_ops",
".",
"log",
"(",
"math_ops",
".",
"abs",
"(",
"array_ops",
".",
"matrix_diag_part",
"(",
"self",
".",
"_m",
")",
")",
")",
",",
"axis",
"=",
"[",
"-",
"1",
"]",
")",
"return",
"log_det_c",
"+",
"2.",
"*",
"self",
".",
"_d",
".",
"sqrt_log_abs_det",
"(",
")",
"+",
"log_det_m"
]
| [
143,
2
]
| [
163,
66
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
test_get_interventions | (client) | Teste get /intervention - Compara quantidade de intervenções enviadas com quantidade salva no banco e valida status_code 200 | Teste get /intervention - Compara quantidade de intervenções enviadas com quantidade salva no banco e valida status_code 200 | def test_get_interventions(client):
"""Teste get /intervention - Compara quantidade de intervenções enviadas com quantidade salva no banco e valida status_code 200"""
access_token = get_access(client)
interventions = session.query(Intervention).count()
response = client.get('/intervention', headers=make_headers(access_token))
data = json.loads(response.data)['data']
# TODO: Add consulta ao banco de dados e comparar count de intervenções
assert response.status_code == 200 | [
"def",
"test_get_interventions",
"(",
"client",
")",
":",
"access_token",
"=",
"get_access",
"(",
"client",
")",
"interventions",
"=",
"session",
".",
"query",
"(",
"Intervention",
")",
".",
"count",
"(",
")",
"response",
"=",
"client",
".",
"get",
"(",
"'/intervention'",
",",
"headers",
"=",
"make_headers",
"(",
"access_token",
")",
")",
"data",
"=",
"json",
".",
"loads",
"(",
"response",
".",
"data",
")",
"[",
"'data'",
"]",
"# TODO: Add consulta ao banco de dados e comparar count de intervenções",
"assert",
"response",
".",
"status_code",
"==",
"200"
]
| [
5,
0
]
| [
15,
38
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
count_words | (filename) | Conta o número aproximado de palavras em um arquivo. | Conta o número aproximado de palavras em um arquivo. | def count_words(filename):
"""Conta o número aproximado de palavras em um arquivo."""
try:
with open(filename, encoding='utf-8') as f_obj:
contents = f_obj.read()
except FileNotFoundError:
pass #falha silenciosamente
"""msg = "Sorry, the file " + filename + " does not exist."
print(msg)"""
else:
#Conta o número aproximado de palavras no arquivo.
words = contents.split()
num_words = len(words)
print("The file " + " has about " + str(num_words) + " words.") | [
"def",
"count_words",
"(",
"filename",
")",
":",
"try",
":",
"with",
"open",
"(",
"filename",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f_obj",
":",
"contents",
"=",
"f_obj",
".",
"read",
"(",
")",
"except",
"FileNotFoundError",
":",
"pass",
"#falha silenciosamente",
"\"\"\"msg = \"Sorry, the file \" + filename + \" does not exist.\"\n print(msg)\"\"\"",
"else",
":",
"#Conta o número aproximado de palavras no arquivo.",
"words",
"=",
"contents",
".",
"split",
"(",
")",
"num_words",
"=",
"len",
"(",
"words",
")",
"print",
"(",
"\"The file \"",
"+",
"\" has about \"",
"+",
"str",
"(",
"num_words",
")",
"+",
"\" words.\"",
")"
]
| [
0,
0
]
| [
13,
71
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
TestEntityGetAttr.test_get_by_getattr_Persons_class_with_select_as_iterable_of_properties | (self) | Teste com select como uma tupla de propriedades | Teste com select como uma tupla de propriedades | def test_get_by_getattr_Persons_class_with_select_as_iterable_of_properties(self):
"""Teste com select como uma tupla de propriedades"""
properties = self.pyvidesk.persons.get_properties()
select_values = (
properties["id"],
properties["businessName"],
properties["userName"],
properties["isActive"],
)
result = self.pyvidesk.persons.get_by_isActive(
True, select=select_values
).as_url()
expected = (
self.pyvidesk.persons.api.base_url
+ "&$select=id,businessName,userName,isActive&$filter=isActive eq true"
)
self.assertEqual(result, expected) | [
"def",
"test_get_by_getattr_Persons_class_with_select_as_iterable_of_properties",
"(",
"self",
")",
":",
"properties",
"=",
"self",
".",
"pyvidesk",
".",
"persons",
".",
"get_properties",
"(",
")",
"select_values",
"=",
"(",
"properties",
"[",
"\"id\"",
"]",
",",
"properties",
"[",
"\"businessName\"",
"]",
",",
"properties",
"[",
"\"userName\"",
"]",
",",
"properties",
"[",
"\"isActive\"",
"]",
",",
")",
"result",
"=",
"self",
".",
"pyvidesk",
".",
"persons",
".",
"get_by_isActive",
"(",
"True",
",",
"select",
"=",
"select_values",
")",
".",
"as_url",
"(",
")",
"expected",
"=",
"(",
"self",
".",
"pyvidesk",
".",
"persons",
".",
"api",
".",
"base_url",
"+",
"\"&$select=id,businessName,userName,isActive&$filter=isActive eq true\"",
")",
"self",
".",
"assertEqual",
"(",
"result",
",",
"expected",
")"
]
| [
90,
4
]
| [
106,
42
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
is_var_symbol | (s) | return is_symbol(s) and s[0].islower() | Um símbolo de variável lógica é uma string inicial-minúscula. | Um símbolo de variável lógica é uma string inicial-minúscula. | def is_var_symbol(s):
"Um símbolo de variável lógica é uma string inicial-minúscula."
return is_symbol(s) and s[0].islower() | [
"def",
"is_var_symbol",
"(",
"s",
")",
":",
"return",
"is_symbol",
"(",
"s",
")",
"and",
"s",
"[",
"0",
"]",
".",
"islower",
"(",
")"
]
| [
131,
0
]
| [
133,
42
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
Contrato.tipo | (self, tipo: str) | Edita o acesso ao Tipo do contrato, sendo: Novo, Em Andamento, Acertado
e Concluido | Edita o acesso ao Tipo do contrato, sendo: Novo, Em Andamento, Acertado
e Concluido | def tipo(self, tipo: str):
"""Edita o acesso ao Tipo do contrato, sendo: Novo, Em Andamento, Acertado
e Concluido"""
self.__tipo = tipo.upper() | [
"def",
"tipo",
"(",
"self",
",",
"tipo",
":",
"str",
")",
":",
"self",
".",
"__tipo",
"=",
"tipo",
".",
"upper",
"(",
")"
]
| [
38,
4
]
| [
41,
34
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
insert_vip_request | (vip_map, user) | return 0, vip | Insere uma requisição de VIP.
@param vip_map: Mapa com os dados da requisição.
@param user: Usuário autenticado.
@return: Em caso de sucesso: tupla (0, <requisição de VIP>).
Em caso de erro: tupla (código da mensagem de erro, argumento01, argumento02, ...)
@raise IpNotFoundError: IP não cadastrado.
@raise IpError: Falha ao pesquisar o IP.
@raise HealthcheckExpectNotFoundError: HealthcheckExpect não cadastrado.
@raise HealthcheckExpectError: Falha ao pesquisar o HealthcheckExpect.
@raise InvalidFinalidadeValueError: Finalidade com valor inválido.
@raise InvalidClienteValueError: Cliente com valor inválido.
@raise InvalidAmbienteValueError: Ambiente com valor inválido.
@raise InvalidCacheValueError: Cache com valor inválido.
@raise InvalidMetodoBalValueError: Valor do método de balanceamento inválido.
@raise InvalidPersistenciaValueError: Persistencia com valor inválido.
@raise InvalidHealthcheckTypeValueError: Healthcheck_Type com valor inválido ou inconsistente em relação ao valor do healthcheck_expect.
@raise InvalidTimeoutValueError: Timeout com valor inválido.
@raise InvalidHostNameError: Host não cadastrado.
@raise EquipamentoError: Falha ao pesquisar o equipamento.
@raise InvalidMaxConValueError: Número máximo de conexões com valor inválido.
@raise InvalidBalAtivoValueError: Bal_Ativo com valor inválido.
@raise InvalidTransbordoValueError: Transbordo com valor inválido.
@raise InvalidServicePortValueError: Porta do Serviço com valor inválido.
@raise InvalidRealValueError: Valor inválido de um real.
@raise InvalidHealthcheckValueError: Valor do healthcheck inconsistente em relação ao valor do healthcheck_type.
@raise RequisicaoVipsError: Falha ao inserir a requisição de VIP.
@raise UserNotAuthorizedError:
| Insere uma requisição de VIP. | def insert_vip_request(vip_map, user):
"""Insere uma requisição de VIP.
@param vip_map: Mapa com os dados da requisição.
@param user: Usuário autenticado.
@return: Em caso de sucesso: tupla (0, <requisição de VIP>).
Em caso de erro: tupla (código da mensagem de erro, argumento01, argumento02, ...)
@raise IpNotFoundError: IP não cadastrado.
@raise IpError: Falha ao pesquisar o IP.
@raise HealthcheckExpectNotFoundError: HealthcheckExpect não cadastrado.
@raise HealthcheckExpectError: Falha ao pesquisar o HealthcheckExpect.
@raise InvalidFinalidadeValueError: Finalidade com valor inválido.
@raise InvalidClienteValueError: Cliente com valor inválido.
@raise InvalidAmbienteValueError: Ambiente com valor inválido.
@raise InvalidCacheValueError: Cache com valor inválido.
@raise InvalidMetodoBalValueError: Valor do método de balanceamento inválido.
@raise InvalidPersistenciaValueError: Persistencia com valor inválido.
@raise InvalidHealthcheckTypeValueError: Healthcheck_Type com valor inválido ou inconsistente em relação ao valor do healthcheck_expect.
@raise InvalidTimeoutValueError: Timeout com valor inválido.
@raise InvalidHostNameError: Host não cadastrado.
@raise EquipamentoError: Falha ao pesquisar o equipamento.
@raise InvalidMaxConValueError: Número máximo de conexões com valor inválido.
@raise InvalidBalAtivoValueError: Bal_Ativo com valor inválido.
@raise InvalidTransbordoValueError: Transbordo com valor inválido.
@raise InvalidServicePortValueError: Porta do Serviço com valor inválido.
@raise InvalidRealValueError: Valor inválido de um real.
@raise InvalidHealthcheckValueError: Valor do healthcheck inconsistente em relação ao valor do healthcheck_type.
@raise RequisicaoVipsError: Falha ao inserir a requisição de VIP.
@raise UserNotAuthorizedError:
"""
log = logging.getLogger('insert_vip_request')
if not has_perm(user, AdminPermission.VIPS_REQUEST, AdminPermission.WRITE_OPERATION):
raise UserNotAuthorizedError(
None, u'Usuário não tem permissão para executar a operação.')
ip_id = vip_map.get('id_ip')
if not is_valid_int_greater_zero_param(ip_id):
log.error(u'The ip_id parameter is not a valid value: %s.', ip_id)
raise InvalidValueError(None, 'ip_id', ip_id)
else:
ip_id = int(ip_id)
vip = RequisicaoVips()
vip.ip = Ip()
vip.ip.id = ip_id
# Valid ports
vip_map, code = vip.valid_values_ports(vip_map)
if code is not None:
return code, vip
# get environmentVip for validation dynamic heathcheck
finalidade = vip_map.get('finalidade')
cliente = vip_map.get('cliente')
ambiente = vip_map.get('ambiente')
if not is_valid_string_minsize(finalidade, 3) or not is_valid_string_maxsize(finalidade, 50):
log.error(u'Finality value is invalid: %s.', finalidade)
raise InvalidValueError(None, 'finalidade', finalidade)
if not is_valid_string_minsize(cliente, 3) or not is_valid_string_maxsize(cliente, 50):
log.error(u'Client value is invalid: %s.', cliente)
raise InvalidValueError(None, 'cliente', cliente)
if not is_valid_string_minsize(ambiente, 3) or not is_valid_string_maxsize(ambiente, 50):
log.error(u'Environment value is invalid: %s.', ambiente)
raise InvalidValueError(None, 'ambiente', ambiente)
try:
environment_vip = EnvironmentVip.get_by_values(
finalidade, cliente, ambiente)
except Exception, e:
raise EnvironmentVipNotFoundError(
e, 'The fields finality or client or ambiente is None')
# Valid HealthcheckExpect
vip_map, vip, code = vip.valid_values_healthcheck(
vip_map, vip, environment_vip)
if code is not None:
return code, vip
# get traffic return
# traffic_return=OptionVip.objects.filter(nome_opcao_txt=traffic)
traffic_id = vip_map.get('trafficreturn')
if traffic_id is None:
traffic = OptionVip.get_all_trafficreturn(environment_vip.id)
traffic = traffic.filter(nome_opcao_txt='Normal')
traffic_id = traffic.id
vip.trafficreturn = OptionVip()
vip.trafficreturn.id = traffic_id
# Valid maxcon
if not is_valid_int_greater_equal_zero_param(vip_map.get('maxcon')):
log.error(
u'The maxcon parameter is not a valid value: %s.', vip_map.get('maxcon'))
raise InvalidValueError(None, 'maxcon', vip_map.get('maxcon'))
if vip_map.get('reals') is not None:
for real in vip_map.get('reals').get('real'):
ip_aux_error = real.get('real_ip')
equip_aux_error = real.get('real_name')
if equip_aux_error is not None:
equip = Equipamento.get_by_name(equip_aux_error)
else:
raise InvalidValueError(None, 'real_name', 'None')
RequisicaoVips.valid_real_server(
ip_aux_error, equip, environment_vip)
vip.create(user, vip_map)
# SYNC_VIP
old_to_new(vip)
return 0, vip | [
"def",
"insert_vip_request",
"(",
"vip_map",
",",
"user",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"'insert_vip_request'",
")",
"if",
"not",
"has_perm",
"(",
"user",
",",
"AdminPermission",
".",
"VIPS_REQUEST",
",",
"AdminPermission",
".",
"WRITE_OPERATION",
")",
":",
"raise",
"UserNotAuthorizedError",
"(",
"None",
",",
"u'Usuário não tem permissão para executar a operação.')",
"",
"ip_id",
"=",
"vip_map",
".",
"get",
"(",
"'id_ip'",
")",
"if",
"not",
"is_valid_int_greater_zero_param",
"(",
"ip_id",
")",
":",
"log",
".",
"error",
"(",
"u'The ip_id parameter is not a valid value: %s.'",
",",
"ip_id",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'ip_id'",
",",
"ip_id",
")",
"else",
":",
"ip_id",
"=",
"int",
"(",
"ip_id",
")",
"vip",
"=",
"RequisicaoVips",
"(",
")",
"vip",
".",
"ip",
"=",
"Ip",
"(",
")",
"vip",
".",
"ip",
".",
"id",
"=",
"ip_id",
"# Valid ports",
"vip_map",
",",
"code",
"=",
"vip",
".",
"valid_values_ports",
"(",
"vip_map",
")",
"if",
"code",
"is",
"not",
"None",
":",
"return",
"code",
",",
"vip",
"# get environmentVip for validation dynamic heathcheck",
"finalidade",
"=",
"vip_map",
".",
"get",
"(",
"'finalidade'",
")",
"cliente",
"=",
"vip_map",
".",
"get",
"(",
"'cliente'",
")",
"ambiente",
"=",
"vip_map",
".",
"get",
"(",
"'ambiente'",
")",
"if",
"not",
"is_valid_string_minsize",
"(",
"finalidade",
",",
"3",
")",
"or",
"not",
"is_valid_string_maxsize",
"(",
"finalidade",
",",
"50",
")",
":",
"log",
".",
"error",
"(",
"u'Finality value is invalid: %s.'",
",",
"finalidade",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'finalidade'",
",",
"finalidade",
")",
"if",
"not",
"is_valid_string_minsize",
"(",
"cliente",
",",
"3",
")",
"or",
"not",
"is_valid_string_maxsize",
"(",
"cliente",
",",
"50",
")",
":",
"log",
".",
"error",
"(",
"u'Client value is invalid: %s.'",
",",
"cliente",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'cliente'",
",",
"cliente",
")",
"if",
"not",
"is_valid_string_minsize",
"(",
"ambiente",
",",
"3",
")",
"or",
"not",
"is_valid_string_maxsize",
"(",
"ambiente",
",",
"50",
")",
":",
"log",
".",
"error",
"(",
"u'Environment value is invalid: %s.'",
",",
"ambiente",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'ambiente'",
",",
"ambiente",
")",
"try",
":",
"environment_vip",
"=",
"EnvironmentVip",
".",
"get_by_values",
"(",
"finalidade",
",",
"cliente",
",",
"ambiente",
")",
"except",
"Exception",
",",
"e",
":",
"raise",
"EnvironmentVipNotFoundError",
"(",
"e",
",",
"'The fields finality or client or ambiente is None'",
")",
"# Valid HealthcheckExpect",
"vip_map",
",",
"vip",
",",
"code",
"=",
"vip",
".",
"valid_values_healthcheck",
"(",
"vip_map",
",",
"vip",
",",
"environment_vip",
")",
"if",
"code",
"is",
"not",
"None",
":",
"return",
"code",
",",
"vip",
"# get traffic return",
"# traffic_return=OptionVip.objects.filter(nome_opcao_txt=traffic)",
"traffic_id",
"=",
"vip_map",
".",
"get",
"(",
"'trafficreturn'",
")",
"if",
"traffic_id",
"is",
"None",
":",
"traffic",
"=",
"OptionVip",
".",
"get_all_trafficreturn",
"(",
"environment_vip",
".",
"id",
")",
"traffic",
"=",
"traffic",
".",
"filter",
"(",
"nome_opcao_txt",
"=",
"'Normal'",
")",
"traffic_id",
"=",
"traffic",
".",
"id",
"vip",
".",
"trafficreturn",
"=",
"OptionVip",
"(",
")",
"vip",
".",
"trafficreturn",
".",
"id",
"=",
"traffic_id",
"# Valid maxcon",
"if",
"not",
"is_valid_int_greater_equal_zero_param",
"(",
"vip_map",
".",
"get",
"(",
"'maxcon'",
")",
")",
":",
"log",
".",
"error",
"(",
"u'The maxcon parameter is not a valid value: %s.'",
",",
"vip_map",
".",
"get",
"(",
"'maxcon'",
")",
")",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'maxcon'",
",",
"vip_map",
".",
"get",
"(",
"'maxcon'",
")",
")",
"if",
"vip_map",
".",
"get",
"(",
"'reals'",
")",
"is",
"not",
"None",
":",
"for",
"real",
"in",
"vip_map",
".",
"get",
"(",
"'reals'",
")",
".",
"get",
"(",
"'real'",
")",
":",
"ip_aux_error",
"=",
"real",
".",
"get",
"(",
"'real_ip'",
")",
"equip_aux_error",
"=",
"real",
".",
"get",
"(",
"'real_name'",
")",
"if",
"equip_aux_error",
"is",
"not",
"None",
":",
"equip",
"=",
"Equipamento",
".",
"get_by_name",
"(",
"equip_aux_error",
")",
"else",
":",
"raise",
"InvalidValueError",
"(",
"None",
",",
"'real_name'",
",",
"'None'",
")",
"RequisicaoVips",
".",
"valid_real_server",
"(",
"ip_aux_error",
",",
"equip",
",",
"environment_vip",
")",
"vip",
".",
"create",
"(",
"user",
",",
"vip_map",
")",
"# SYNC_VIP",
"old_to_new",
"(",
"vip",
")",
"return",
"0",
",",
"vip"
]
| [
66,
0
]
| [
208,
17
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
SelectionSort.__recursiveGetMin | (self,array,leftIndex,rightIndex,minValue,index) | Método auxiliar de recursão
Este método pega o menor elemento do array e troca de posição com o indíce a esquerda
Parametros:
array: Lista a ser ordenada
leftIndex: Índice limítrofe a esquerda do array para ordenação parcial
rightIndex: Índice limítrofe a direita do array para ordenação parcial
minValue: Menor valor encontrado entre os limites esquerdo e direito
index: Índice do elemento a ser comparado
| Método auxiliar de recursão
Este método pega o menor elemento do array e troca de posição com o indíce a esquerda
Parametros:
array: Lista a ser ordenada
leftIndex: Índice limítrofe a esquerda do array para ordenação parcial
rightIndex: Índice limítrofe a direita do array para ordenação parcial
minValue: Menor valor encontrado entre os limites esquerdo e direito
index: Índice do elemento a ser comparado
| def __recursiveGetMin(self,array,leftIndex,rightIndex,minValue,index):
""" Método auxiliar de recursão
Este método pega o menor elemento do array e troca de posição com o indíce a esquerda
Parametros:
array: Lista a ser ordenada
leftIndex: Índice limítrofe a esquerda do array para ordenação parcial
rightIndex: Índice limítrofe a direita do array para ordenação parcial
minValue: Menor valor encontrado entre os limites esquerdo e direito
index: Índice do elemento a ser comparado
"""
if(index <= rightIndex):
if(array[minValue] > array[index]):
minValue = index
self.__recursiveGetMin(array, leftIndex, rightIndex, minValue, index + 1)
else:
array[minValue] ,array[leftIndex] = array[leftIndex] , array[minValue] | [
"def",
"__recursiveGetMin",
"(",
"self",
",",
"array",
",",
"leftIndex",
",",
"rightIndex",
",",
"minValue",
",",
"index",
")",
":",
"if",
"(",
"index",
"<=",
"rightIndex",
")",
":",
"if",
"(",
"array",
"[",
"minValue",
"]",
">",
"array",
"[",
"index",
"]",
")",
":",
"minValue",
"=",
"index",
"self",
".",
"__recursiveGetMin",
"(",
"array",
",",
"leftIndex",
",",
"rightIndex",
",",
"minValue",
",",
"index",
"+",
"1",
")",
"else",
":",
"array",
"[",
"minValue",
"]",
",",
"array",
"[",
"leftIndex",
"]",
"=",
"array",
"[",
"leftIndex",
"]",
",",
"array",
"[",
"minValue",
"]"
]
| [
122,
1
]
| [
138,
73
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
city_retun | (city) | pega como parametro os dados do GPS (Longitude e latitude) do bot e returna uma sting com os dados filtrados por cidade | pega como parametro os dados do GPS (Longitude e latitude) do bot e returna uma sting com os dados filtrados por cidade | def city_retun(city):
'''pega como parametro os dados do GPS (Longitude e latitude) do bot e returna uma sting com os dados filtrados por cidade '''
#get location from longitude
try:
location = geolocator.reverse(city, timeout=60)
except:
return 'Ocorreu um erro em sua localização tente mais tarde...'
try:
cityy = location.raw['address']['city']
except:
cityy = location.raw['address']['town']
state = strings.list_uf[location.raw['address']['state']]
date = datetime.datetime.now()
redu_date=0
city_query = data.query(f"state== '{state}' & city == '{cityy}' & date == '{date.strftime('%Y-%m-%d')}' ")
state_query = data.query(f"place_type== 'state' & state == '{state}' & date == '{date.strftime('%Y-%m-%d')}' ")
while city_query.empty:
#if q is null retry until last date in dataframe\\
redu_date +=1
date =datetime.datetime.now() - datetime.timedelta(redu_date)
city_query = data.query(f"state== '{state}' & city == '{cityy}' & date == '{date.strftime('%Y-%m-%d')}' ")
state_query = data.query(f"place_type== 'state' & state == '{state}' & date == '{date.strftime('%Y-%m-%d')}'")
# if dont date in last 10 days
if redu_date ==10:
return 'registros para sua localização não encontrado nos ultimos 10 dias'
else:
return strings.text_city_resume.format(city_query.iloc[0]['city'],
#gambiarra for inverter date string
datetime.datetime.strptime(f"{city_query.iloc[0]['date']}", "%Y-%m-%d").strftime('%d-%m-%Y') ,
#datas from city
city_query.iloc[0]['new_confirmed'] if not city_query.iloc[0]['is_repeated'] else 'Não ouve divulgação de dados até a hora dessa coleta neste dia',
city_query.iloc[0]['last_available_confirmed'],
city_query.iloc[0]['new_deaths'] if not city_query.iloc[0]['is_repeated'] else 'Não ouve divulgação de dados até a hora dessa coleta neste dia',
city_query.iloc[0]['last_available_deaths'],
#datas from state
state_query.iloc[0]['state'],
state_query.iloc[0]['new_confirmed'] if not state_query.iloc[0]['is_repeated'] else 'Não ouve divulgação de dados até a hora dessa coleta neste dia',
state_query.iloc[0]['last_available_confirmed'],
state_query.iloc[0]['new_deaths'] if not state_query.iloc[0]['is_repeated'] else 'Não ouve divulgação de dados até a hora dessa coleta neste dia',
state_query.iloc[0]['last_available_deaths']
) | [
"def",
"city_retun",
"(",
"city",
")",
":",
"#get location from longitude",
"try",
":",
"location",
"=",
"geolocator",
".",
"reverse",
"(",
"city",
",",
"timeout",
"=",
"60",
")",
"except",
":",
"return",
"'Ocorreu um erro em sua localização tente mais tarde...'",
"try",
":",
"cityy",
"=",
"location",
".",
"raw",
"[",
"'address'",
"]",
"[",
"'city'",
"]",
"except",
":",
"cityy",
"=",
"location",
".",
"raw",
"[",
"'address'",
"]",
"[",
"'town'",
"]",
"state",
"=",
"strings",
".",
"list_uf",
"[",
"location",
".",
"raw",
"[",
"'address'",
"]",
"[",
"'state'",
"]",
"]",
"date",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"redu_date",
"=",
"0",
"city_query",
"=",
"data",
".",
"query",
"(",
"f\"state== '{state}' & city == '{cityy}' & date == '{date.strftime('%Y-%m-%d')}' \"",
")",
"state_query",
"=",
"data",
".",
"query",
"(",
"f\"place_type== 'state' & state == '{state}' & date == '{date.strftime('%Y-%m-%d')}' \"",
")",
"while",
"city_query",
".",
"empty",
":",
"#if q is null retry until last date in dataframe\\\\",
"redu_date",
"+=",
"1",
"date",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"-",
"datetime",
".",
"timedelta",
"(",
"redu_date",
")",
"city_query",
"=",
"data",
".",
"query",
"(",
"f\"state== '{state}' & city == '{cityy}' & date == '{date.strftime('%Y-%m-%d')}' \"",
")",
"state_query",
"=",
"data",
".",
"query",
"(",
"f\"place_type== 'state' & state == '{state}' & date == '{date.strftime('%Y-%m-%d')}'\"",
")",
"# if dont date in last 10 days",
"if",
"redu_date",
"==",
"10",
":",
"return",
"'registros para sua localização não encontrado nos ultimos 10 dias'",
"else",
":",
"return",
"strings",
".",
"text_city_resume",
".",
"format",
"(",
"city_query",
".",
"iloc",
"[",
"0",
"]",
"[",
"'city'",
"]",
",",
"#gambiarra for inverter date string",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"f\"{city_query.iloc[0]['date']}\"",
",",
"\"%Y-%m-%d\"",
")",
".",
"strftime",
"(",
"'%d-%m-%Y'",
")",
",",
"#datas from city",
"city_query",
".",
"iloc",
"[",
"0",
"]",
"[",
"'new_confirmed'",
"]",
"if",
"not",
"city_query",
".",
"iloc",
"[",
"0",
"]",
"[",
"'is_repeated'",
"]",
"else",
"'Não ouve divulgação de dados até a hora dessa coleta neste dia',",
"",
"city_query",
".",
"iloc",
"[",
"0",
"]",
"[",
"'last_available_confirmed'",
"]",
",",
"city_query",
".",
"iloc",
"[",
"0",
"]",
"[",
"'new_deaths'",
"]",
"if",
"not",
"city_query",
".",
"iloc",
"[",
"0",
"]",
"[",
"'is_repeated'",
"]",
"else",
"'Não ouve divulgação de dados até a hora dessa coleta neste dia',",
"",
"city_query",
".",
"iloc",
"[",
"0",
"]",
"[",
"'last_available_deaths'",
"]",
",",
"#datas from state",
"state_query",
".",
"iloc",
"[",
"0",
"]",
"[",
"'state'",
"]",
",",
"state_query",
".",
"iloc",
"[",
"0",
"]",
"[",
"'new_confirmed'",
"]",
"if",
"not",
"state_query",
".",
"iloc",
"[",
"0",
"]",
"[",
"'is_repeated'",
"]",
"else",
"'Não ouve divulgação de dados até a hora dessa coleta neste dia',",
"",
"state_query",
".",
"iloc",
"[",
"0",
"]",
"[",
"'last_available_confirmed'",
"]",
",",
"state_query",
".",
"iloc",
"[",
"0",
"]",
"[",
"'new_deaths'",
"]",
"if",
"not",
"state_query",
".",
"iloc",
"[",
"0",
"]",
"[",
"'is_repeated'",
"]",
"else",
"'Não ouve divulgação de dados até a hora dessa coleta neste dia',",
"",
"state_query",
".",
"iloc",
"[",
"0",
"]",
"[",
"'last_available_deaths'",
"]",
")"
]
| [
43,
0
]
| [
92,
9
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
Deque.peek_end | (self) | Retorna o elemento que esta no final da fila | Retorna o elemento que esta no final da fila | def peek_end(self):
""" Retorna o elemento que esta no final da fila """
if self._size > 0:
return self.deque[self._size - 1]
raise IndexError('empty list') | [
"def",
"peek_end",
"(",
"self",
")",
":",
"if",
"self",
".",
"_size",
">",
"0",
":",
"return",
"self",
".",
"deque",
"[",
"self",
".",
"_size",
"-",
"1",
"]",
"raise",
"IndexError",
"(",
"'empty list'",
")"
]
| [
53,
4
]
| [
59,
38
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
update_articles_mixed_citations | (
source: str,
output_folder: str = None,
override: bool = False,
disable_bar: bool = False,
) | Atualiza os elementos de ``mixed-citations`` em um ou mais XMLs.
O resultado da atualização pode ser salvo no próprio arquivo XML ou em
outro arquivo XML em um diretório diferente utilizando o parâmetro
``output_folder``.
Marque o `override` como `True` para sobrescrever todas as mixed citations
das referências, caso contrário, apenas as referências sem mixed citations
serão atualizadas (padrão). | Atualiza os elementos de ``mixed-citations`` em um ou mais XMLs. | def update_articles_mixed_citations(
source: str,
output_folder: str = None,
override: bool = False,
disable_bar: bool = False,
):
"""Atualiza os elementos de ``mixed-citations`` em um ou mais XMLs.
O resultado da atualização pode ser salvo no próprio arquivo XML ou em
outro arquivo XML em um diretório diferente utilizando o parâmetro
``output_folder``.
Marque o `override` como `True` para sobrescrever todas as mixed citations
das referências, caso contrário, apenas as referências sem mixed citations
serão atualizadas (padrão)."""
CACHE_DIR = config.get("PARAGRAPH_CACHE_PATH")
if not os.path.exists(source):
raise FileNotFoundError("Source path '%s' does not exist" % source)
elif output_folder is not None and not os.path.exists(output_folder):
raise FileNotFoundError("Output folder '%s' does not exist" % output_folder)
def get_references_text_from_paragraphs(paragraphs: list, pid: str) -> dict:
"""Filtra as referências a partir dos paragráfos.
As referências possuem a mesma estrutura dos parágrafos na base MST
exceto pelo índice (v888). Considera-se uma referência os registros que
possuem o índice/order (v888) e a chave de `PID` para o artigo (v880).
Params:
paragraphs (List[dict]): Lista de parágrafos extraídos da base MST
pid (str): Identificador do documento no formato `scielo-v2`
Returns:
references (Dict[str, str]): Dicionário com referências filtradas,
e.g: {"order": "text"}
"""
references = {}
for paragraph in paragraphs:
article_pid = get_nested(paragraph, "v880", 0, "_", default=None)
index = get_nested(paragraph, "v888", 0, "_", default=-1)
if index != -1 and article_pid == pid:
references[index] = XMLUtils.cleanup_mixed_citation_text(
get_nested(paragraph, "v704", 0, "_")
)
return references
def get_output_file_path(original_file, output_folder=None):
"""Retorna o path completo para um arquivo de saída"""
if output_folder is None:
return original_file
return os.path.join(output_folder, os.path.basename(original_file))
def get_paragraphs_from_cache(file) -> list:
"""Retorna uma lista de paragráfos a partir de um arquivo JSON"""
paragraphs = []
with open(file, "r") as f:
for line in f.readlines():
paragraphs.append(json.loads(line))
return paragraphs
xmls = get_files_in_path(source, extension=".xml")
with tqdm(total=len(xmls), disable=disable_bar) as pbar:
for xml in xmls:
try:
package = SPS_Package(etree.parse(xml))
if package.scielo_pid_v2 is None:
logger.error("Could not update file '%s' because its PID is unknown.", xml)
continue
paragraph_file = f"{CACHE_DIR}/{package.scielo_pid_v2}.json"
paragraphs = get_paragraphs_from_cache(paragraph_file)
references = get_references_text_from_paragraphs(
paragraphs, pid=package.scielo_pid_v2
)
updated = package.update_mixed_citations(references, override=override)
output_file = get_output_file_path(xml, output_folder)
XMLUtils.objXML2file(output_file, package.xmltree, pretty=True)
if len(updated) > 0:
logger.debug(
"Updated %0.3d references from '%s' file.", len(updated), xml
)
except etree.XMLSyntaxError as e:
logger.error(e)
except FileNotFoundError as e:
logger.error(
"Could not update file '%s' " "the exception '%s' occurred.", xml, e
)
pbar.update(1) | [
"def",
"update_articles_mixed_citations",
"(",
"source",
":",
"str",
",",
"output_folder",
":",
"str",
"=",
"None",
",",
"override",
":",
"bool",
"=",
"False",
",",
"disable_bar",
":",
"bool",
"=",
"False",
",",
")",
":",
"CACHE_DIR",
"=",
"config",
".",
"get",
"(",
"\"PARAGRAPH_CACHE_PATH\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"source",
")",
":",
"raise",
"FileNotFoundError",
"(",
"\"Source path '%s' does not exist\"",
"%",
"source",
")",
"elif",
"output_folder",
"is",
"not",
"None",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"output_folder",
")",
":",
"raise",
"FileNotFoundError",
"(",
"\"Output folder '%s' does not exist\"",
"%",
"output_folder",
")",
"def",
"get_references_text_from_paragraphs",
"(",
"paragraphs",
":",
"list",
",",
"pid",
":",
"str",
")",
"->",
"dict",
":",
"\"\"\"Filtra as referências a partir dos paragráfos.\n\n As referências possuem a mesma estrutura dos parágrafos na base MST\n exceto pelo índice (v888). Considera-se uma referência os registros que\n possuem o índice/order (v888) e a chave de `PID` para o artigo (v880).\n\n Params:\n paragraphs (List[dict]): Lista de parágrafos extraídos da base MST\n pid (str): Identificador do documento no formato `scielo-v2`\n\n Returns:\n references (Dict[str, str]): Dicionário com referências filtradas,\n e.g: {\"order\": \"text\"}\n \"\"\"",
"references",
"=",
"{",
"}",
"for",
"paragraph",
"in",
"paragraphs",
":",
"article_pid",
"=",
"get_nested",
"(",
"paragraph",
",",
"\"v880\"",
",",
"0",
",",
"\"_\"",
",",
"default",
"=",
"None",
")",
"index",
"=",
"get_nested",
"(",
"paragraph",
",",
"\"v888\"",
",",
"0",
",",
"\"_\"",
",",
"default",
"=",
"-",
"1",
")",
"if",
"index",
"!=",
"-",
"1",
"and",
"article_pid",
"==",
"pid",
":",
"references",
"[",
"index",
"]",
"=",
"XMLUtils",
".",
"cleanup_mixed_citation_text",
"(",
"get_nested",
"(",
"paragraph",
",",
"\"v704\"",
",",
"0",
",",
"\"_\"",
")",
")",
"return",
"references",
"def",
"get_output_file_path",
"(",
"original_file",
",",
"output_folder",
"=",
"None",
")",
":",
"\"\"\"Retorna o path completo para um arquivo de saída\"\"\"",
"if",
"output_folder",
"is",
"None",
":",
"return",
"original_file",
"return",
"os",
".",
"path",
".",
"join",
"(",
"output_folder",
",",
"os",
".",
"path",
".",
"basename",
"(",
"original_file",
")",
")",
"def",
"get_paragraphs_from_cache",
"(",
"file",
")",
"->",
"list",
":",
"\"\"\"Retorna uma lista de paragráfos a partir de um arquivo JSON\"\"\"",
"paragraphs",
"=",
"[",
"]",
"with",
"open",
"(",
"file",
",",
"\"r\"",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
":",
"paragraphs",
".",
"append",
"(",
"json",
".",
"loads",
"(",
"line",
")",
")",
"return",
"paragraphs",
"xmls",
"=",
"get_files_in_path",
"(",
"source",
",",
"extension",
"=",
"\".xml\"",
")",
"with",
"tqdm",
"(",
"total",
"=",
"len",
"(",
"xmls",
")",
",",
"disable",
"=",
"disable_bar",
")",
"as",
"pbar",
":",
"for",
"xml",
"in",
"xmls",
":",
"try",
":",
"package",
"=",
"SPS_Package",
"(",
"etree",
".",
"parse",
"(",
"xml",
")",
")",
"if",
"package",
".",
"scielo_pid_v2",
"is",
"None",
":",
"logger",
".",
"error",
"(",
"\"Could not update file '%s' because its PID is unknown.\"",
",",
"xml",
")",
"continue",
"paragraph_file",
"=",
"f\"{CACHE_DIR}/{package.scielo_pid_v2}.json\"",
"paragraphs",
"=",
"get_paragraphs_from_cache",
"(",
"paragraph_file",
")",
"references",
"=",
"get_references_text_from_paragraphs",
"(",
"paragraphs",
",",
"pid",
"=",
"package",
".",
"scielo_pid_v2",
")",
"updated",
"=",
"package",
".",
"update_mixed_citations",
"(",
"references",
",",
"override",
"=",
"override",
")",
"output_file",
"=",
"get_output_file_path",
"(",
"xml",
",",
"output_folder",
")",
"XMLUtils",
".",
"objXML2file",
"(",
"output_file",
",",
"package",
".",
"xmltree",
",",
"pretty",
"=",
"True",
")",
"if",
"len",
"(",
"updated",
")",
">",
"0",
":",
"logger",
".",
"debug",
"(",
"\"Updated %0.3d references from '%s' file.\"",
",",
"len",
"(",
"updated",
")",
",",
"xml",
")",
"except",
"etree",
".",
"XMLSyntaxError",
"as",
"e",
":",
"logger",
".",
"error",
"(",
"e",
")",
"except",
"FileNotFoundError",
"as",
"e",
":",
"logger",
".",
"error",
"(",
"\"Could not update file '%s' \"",
"\"the exception '%s' occurred.\"",
",",
"xml",
",",
"e",
")",
"pbar",
".",
"update",
"(",
"1",
")"
]
| [
202,
0
]
| [
301,
26
]
| null | python | pt | ['pt', 'pt', 'pt'] | True | true | null |
|
init_app | (app: Flask) | Inicialização de extensões | Inicialização de extensões | def init_app(app: Flask):
"""Inicialização de extensões"""
@app.route("/")
def index():
name = request.args.get("name");
print(name)
return "Esta rodando aguarde"
@app.route("/contato")
def contato():
return "<form><input type='text'></input></form>" | [
"def",
"init_app",
"(",
"app",
":",
"Flask",
")",
":",
"@",
"app",
".",
"route",
"(",
"\"/\"",
")",
"def",
"index",
"(",
")",
":",
"name",
"=",
"request",
".",
"args",
".",
"get",
"(",
"\"name\"",
")",
"print",
"(",
"name",
")",
"return",
"\"Esta rodando aguarde\"",
"@",
"app",
".",
"route",
"(",
"\"/contato\"",
")",
"def",
"contato",
"(",
")",
":",
"return",
"\"<form><input type='text'></input></form>\""
]
| [
4,
0
]
| [
15,
57
]
| 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.