identifier
stringlengths
0
89
parameters
stringlengths
0
399
return_statement
stringlengths
0
982
docstring
stringlengths
10
3.04k
docstring_summary
stringlengths
0
3.04k
function
stringlengths
13
25.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
argument_list
null
language
stringclasses
3 values
docstring_language
stringclasses
4 values
docstring_language_predictions
stringclasses
4 values
is_langid_reliable
stringclasses
2 values
is_langid_extra_reliable
bool
1 class
type
stringclasses
9 values
Scope.subnet_calculator
(self)
Calcula todos os endereços possiveis no CIDR e adiciona na fila redes /24 disponiveis.
Calcula todos os endereços possiveis no CIDR e adiciona na fila redes /24 disponiveis.
def subnet_calculator(self): """ Calcula todos os endereços possiveis no CIDR e adiciona na fila redes /24 disponiveis.""" cidr = ipaddress.IPv4Network((f'{self.global_address}/{self.global_mask}')) subnet_itter = cidr.subnets(new_prefix=24) for subnet_address in subnet_itter: self.scope_queue.push(subnet_address.network_address)
[ "def", "subnet_calculator", "(", "self", ")", ":", "cidr", "=", "ipaddress", ".", "IPv4Network", "(", "(", "f'{self.global_address}/{self.global_mask}'", ")", ")", "subnet_itter", "=", "cidr", ".", "subnets", "(", "new_prefix", "=", "24", ")", "for", "subnet_address", "in", "subnet_itter", ":", "self", ".", "scope_queue", ".", "push", "(", "subnet_address", ".", "network_address", ")" ]
[ 31, 4 ]
[ 39, 65 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
validar_senha_sha256
(senha: str, senha_sha256: str)
return False
Valida uma senha digitada com a senha armazenada no formato hash sha256. Args: senha (str utf-8): Senha string utf-8 que será comparada com a senha armazenada. senha_sha256 (str hash sha256 hexadecimal): Senha hash sha256 armazenada para comparação. Returns: bol: True = senhas iguais, login autorizado. False = senhas divergentes.
Valida uma senha digitada com a senha armazenada no formato hash sha256.
def validar_senha_sha256(senha: str, senha_sha256: str) -> bool: """Valida uma senha digitada com a senha armazenada no formato hash sha256. Args: senha (str utf-8): Senha string utf-8 que será comparada com a senha armazenada. senha_sha256 (str hash sha256 hexadecimal): Senha hash sha256 armazenada para comparação. Returns: bol: True = senhas iguais, login autorizado. False = senhas divergentes. """ if criar_senha_sha256(senha) == senha_sha256: return True return False
[ "def", "validar_senha_sha256", "(", "senha", ":", "str", ",", "senha_sha256", ":", "str", ")", "->", "bool", ":", "if", "criar_senha_sha256", "(", "senha", ")", "==", "senha_sha256", ":", "return", "True", "return", "False" ]
[ 18, 0 ]
[ 33, 16 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Equipamento.create
(self, authenticated_user, group_id)
Insere um novo Equipamento Se o grupo do equipamento, informado nos dados da requisição, for igual à “Equipamentos Orquestracao” (id = 1) então o tipo do equipamento deverá ser igual a “Servidor Virtual” (id = 10). @return: Nothing @raise InvalidGroupToEquipmentTypeError: Equipamento do grupo “Equipamentos Orquestração” somente poderá ser criado com tipo igual a “Servidor Virtual”. @raise EGrupoNotFoundError: Grupo não cadastrado. @raise GrupoError: Falha ao pesquisar o Grupo. @raise TipoEquipamentoNotFoundError: Tipo de equipamento nao cadastrado. @raise ModeloNotFoundError: Modelo nao cadastrado. @raise EquipamentoNameDuplicatedError: Nome do equipamento duplicado. @raise EquipamentoError: Falha ou inserir o equipamento.
Insere um novo Equipamento
def create(self, authenticated_user, group_id): """Insere um novo Equipamento Se o grupo do equipamento, informado nos dados da requisição, for igual à “Equipamentos Orquestracao” (id = 1) então o tipo do equipamento deverá ser igual a “Servidor Virtual” (id = 10). @return: Nothing @raise InvalidGroupToEquipmentTypeError: Equipamento do grupo “Equipamentos Orquestração” somente poderá ser criado com tipo igual a “Servidor Virtual”. @raise EGrupoNotFoundError: Grupo não cadastrado. @raise GrupoError: Falha ao pesquisar o Grupo. @raise TipoEquipamentoNotFoundError: Tipo de equipamento nao cadastrado. @raise ModeloNotFoundError: Modelo nao cadastrado. @raise EquipamentoNameDuplicatedError: Nome do equipamento duplicado. @raise EquipamentoError: Falha ou inserir o equipamento. """ if self.nome is not None: self.nome = self.nome.upper() egroup = EGrupo.get_by_pk(group_id) if group_id == EGrupo.GRUPO_EQUIPAMENTO_ORQUESTRACAO and self.tipo_equipamento.id != TipoEquipamento.TIPO_EQUIPAMENTO_SERVIDOR_VIRTUAL: raise InvalidGroupToEquipmentTypeError( None, u'Equipamento do grupo “Equipamentos Orquestração” somente poderá ser criado com tipo igual a “Servidor Virtual”.') self.tipo_equipamento = TipoEquipamento().get_by_pk( self.tipo_equipamento.id) self.modelo = Modelo.get_by_pk(self.modelo.id) if self.maintenance is None: self.maintenance = False try: self.get_by_name(self.nome) raise EquipamentoNameDuplicatedError( None, u'Equipamento com nome duplicado.') except EquipamentoNotFoundError: self.log.debug('Equipamento com o mesmo nome não encontrado.') try: self.save() equipment_group = EquipamentoGrupo() equipment_group.egrupo = egroup equipment_group.equipamento = self equipment_group.save(authenticated_user) return equipment_group.id except Exception as e: self.log.error(u'Falha ao inserir o equipamento.') raise EquipamentoError(e, u'Falha ao inserir o equipamento.')
[ "def", "create", "(", "self", ",", "authenticated_user", ",", "group_id", ")", ":", "if", "self", ".", "nome", "is", "not", "None", ":", "self", ".", "nome", "=", "self", ".", "nome", ".", "upper", "(", ")", "egroup", "=", "EGrupo", ".", "get_by_pk", "(", "group_id", ")", "if", "group_id", "==", "EGrupo", ".", "GRUPO_EQUIPAMENTO_ORQUESTRACAO", "and", "self", ".", "tipo_equipamento", ".", "id", "!=", "TipoEquipamento", ".", "TIPO_EQUIPAMENTO_SERVIDOR_VIRTUAL", ":", "raise", "InvalidGroupToEquipmentTypeError", "(", "None", ",", "u'Equipamento do grupo “Equipamentos Orquestração” somente poderá ser criado com tipo igual a “Servidor Virtual”.')", "", "self", ".", "tipo_equipamento", "=", "TipoEquipamento", "(", ")", ".", "get_by_pk", "(", "self", ".", "tipo_equipamento", ".", "id", ")", "self", ".", "modelo", "=", "Modelo", ".", "get_by_pk", "(", "self", ".", "modelo", ".", "id", ")", "if", "self", ".", "maintenance", "is", "None", ":", "self", ".", "maintenance", "=", "False", "try", ":", "self", ".", "get_by_name", "(", "self", ".", "nome", ")", "raise", "EquipamentoNameDuplicatedError", "(", "None", ",", "u'Equipamento com nome duplicado.'", ")", "except", "EquipamentoNotFoundError", ":", "self", ".", "log", ".", "debug", "(", "'Equipamento com o mesmo nome não encontrado.')", "", "try", ":", "self", ".", "save", "(", ")", "equipment_group", "=", "EquipamentoGrupo", "(", ")", "equipment_group", ".", "egrupo", "=", "egroup", "equipment_group", ".", "equipamento", "=", "self", "equipment_group", ".", "save", "(", "authenticated_user", ")", "return", "equipment_group", ".", "id", "except", "Exception", "as", "e", ":", "self", ".", "log", ".", "error", "(", "u'Falha ao inserir o equipamento.'", ")", "raise", "EquipamentoError", "(", "e", ",", "u'Falha ao inserir o equipamento.'", ")" ]
[ 605, 4 ]
[ 662, 73 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Stack.show
(self)
Imprime a pilha no console
Imprime a pilha no console
def show(self): """ Imprime a pilha no console """ print(f'Stack: {self.__stack}')
[ "def", "show", "(", "self", ")", ":", "print", "(", "f'Stack: {self.__stack}'", ")" ]
[ 21, 4 ]
[ 23, 39 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
prior_sample
(bn)
return event
Amostragem aleatória da distribuição da articulação completa da bn. O resultado É um valor {variable: value}.
Amostragem aleatória da distribuição da articulação completa da bn. O resultado É um valor {variable: value}.
def prior_sample(bn): """Amostragem aleatória da distribuição da articulação completa da bn. O resultado É um valor {variable: value}.""" event = {} for node in bn.nodes: event[node.variable] = node.sample(event) return event
[ "def", "prior_sample", "(", "bn", ")", ":", "event", "=", "{", "}", "for", "node", "in", "bn", ".", "nodes", ":", "event", "[", "node", ".", "variable", "]", "=", "node", ".", "sample", "(", "event", ")", "return", "event" ]
[ 420, 0 ]
[ 426, 16 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
NetworkData.get_global_network
(cls)
return scopes
Retorna todos os valores de networks em routers.yaml.
Retorna todos os valores de networks em routers.yaml.
def get_global_network(cls): """ Retorna todos os valores de networks em routers.yaml. """ scopes = [] for full_scope in NetworkData.yaml.networks: scopes_name = list(full_scope.keys()) scopes_name = scopes_name[0] configs = (list(full_scope.values())) full_address = (configs[0][0]['address']) address = full_address.split('/')[0] mask = full_address.split('/')[1] subnets_list = ((configs[0][1]['subnets'])) scopes_dict = {'scope_name': f'{scopes_name}', 'address': address, 'mask':mask, 'subnets': subnets_list} scopes.append(scopes_dict) return scopes
[ "def", "get_global_network", "(", "cls", ")", ":", "scopes", "=", "[", "]", "for", "full_scope", "in", "NetworkData", ".", "yaml", ".", "networks", ":", "scopes_name", "=", "list", "(", "full_scope", ".", "keys", "(", ")", ")", "scopes_name", "=", "scopes_name", "[", "0", "]", "configs", "=", "(", "list", "(", "full_scope", ".", "values", "(", ")", ")", ")", "full_address", "=", "(", "configs", "[", "0", "]", "[", "0", "]", "[", "'address'", "]", ")", "address", "=", "full_address", ".", "split", "(", "'/'", ")", "[", "0", "]", "mask", "=", "full_address", ".", "split", "(", "'/'", ")", "[", "1", "]", "subnets_list", "=", "(", "(", "configs", "[", "0", "]", "[", "1", "]", "[", "'subnets'", "]", ")", ")", "scopes_dict", "=", "{", "'scope_name'", ":", "f'{scopes_name}'", ",", "'address'", ":", "address", ",", "'mask'", ":", "mask", ",", "'subnets'", ":", "subnets_list", "}", "scopes", ".", "append", "(", "scopes_dict", ")", "return", "scopes" ]
[ 15, 4 ]
[ 37, 21 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
maior_number
(dic_bids)
Essa classe calcula o maior numero dentro de um dicionário.
Essa classe calcula o maior numero dentro de um dicionário.
def maior_number (dic_bids): """Essa classe calcula o maior numero dentro de um dicionário.""" value = 0 for bider in dic_bids: value_bids = dic_bids[bider] if value_bids > value: highest_value = value_bids highest_person = bider print(f'A pessoa que deu a melhor proposta foi {highest_person.title()} no valor de R$ {highest_value}.')
[ "def", "maior_number", "(", "dic_bids", ")", ":", "value", "=", "0", "for", "bider", "in", "dic_bids", ":", "value_bids", "=", "dic_bids", "[", "bider", "]", "if", "value_bids", ">", "value", ":", "highest_value", "=", "value_bids", "highest_person", "=", "bider", "print", "(", "f'A pessoa que deu a melhor proposta foi {highest_person.title()} no valor de R$ {highest_value}.'", ")" ]
[ 4, 0 ]
[ 12, 109 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
PropKB.ask_if_true
(self, query)
return False
Retornar True se o KB envolve consulta, senão retorna False.
Retornar True se o KB envolve consulta, senão retorna False.
def ask_if_true(self, query): "Retornar True se o KB envolve consulta, senão retorna False." for _ in self.ask_generator(query): return True return False
[ "def", "ask_if_true", "(", "self", ",", "query", ")", ":", "for", "_", "in", "self", ".", "ask_generator", "(", "query", ")", ":", "return", "True", "return", "False" ]
[ 88, 4 ]
[ 92, 20 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
MinhaUFOP.foto
(self, cpf: str, **kwargs)
Retorna a foto do CPF informado, se disponível. Args: cpf (str):CPF que você deseja requisitar a foto (ex.: 123.456.789-10) Kwargs: url (str): URL para fazer a requisição ao servidor headers (dict): Headers da requisição ao servidor Raises: MinhaUFOPHTTPError: O servidor retornou o código {código HTTP} MinhaUFOPGenericError: O servidor não retornou uma imagem. Verifique o CPF informado.
Retorna a foto do CPF informado, se disponível.
def foto(self, cpf: str, **kwargs) -> bytes: """Retorna a foto do CPF informado, se disponível. Args: cpf (str):CPF que você deseja requisitar a foto (ex.: 123.456.789-10) Kwargs: url (str): URL para fazer a requisição ao servidor headers (dict): Headers da requisição ao servidor Raises: MinhaUFOPHTTPError: O servidor retornou o código {código HTTP} MinhaUFOPGenericError: O servidor não retornou uma imagem. Verifique o CPF informado. """ url = kwargs.get('url', f"https://zeppelin10.ufop.br/api/v1/ru/foto/{cpf}") headers = kwargs.get('headers', {'Authorization': f'Bearer {self.token}'}) response = requests.request("GET", url, headers=headers) if response.ok and response.content: return response.content elif not response.content: raise MinhaUFOPGenericError(response, 'O servidor não retornou ' 'uma imagem. ' 'Verifique o CPF informado.') elif not response.ok: raise MinhaUFOPHTTPError(response)
[ "def", "foto", "(", "self", ",", "cpf", ":", "str", ",", "*", "*", "kwargs", ")", "->", "bytes", ":", "url", "=", "kwargs", ".", "get", "(", "'url'", ",", "f\"https://zeppelin10.ufop.br/api/v1/ru/foto/{cpf}\"", ")", "headers", "=", "kwargs", ".", "get", "(", "'headers'", ",", "{", "'Authorization'", ":", "f'Bearer {self.token}'", "}", ")", "response", "=", "requests", ".", "request", "(", "\"GET\"", ",", "url", ",", "headers", "=", "headers", ")", "if", "response", ".", "ok", "and", "response", ".", "content", ":", "return", "response", ".", "content", "elif", "not", "response", ".", "content", ":", "raise", "MinhaUFOPGenericError", "(", "response", ",", "'O servidor não retornou '", "'uma imagem. '", "'Verifique o CPF informado.'", ")", "elif", "not", "response", ".", "ok", ":", "raise", "MinhaUFOPHTTPError", "(", "response", ")" ]
[ 194, 4 ]
[ 222, 46 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
CRC16.__convert__
(self, data)
Converte os dados para um objeto bytes
Converte os dados para um objeto bytes
def __convert__(self, data): '''Converte os dados para um objeto bytes''' if type(data) == type(''): return data.encode('ascii') elif type(data) == type(b''): return data elif type(data) == type(bytearray()): return bytes(data) else: raise ValueError('data must be str, bytes or bytearray')
[ "def", "__convert__", "(", "self", ",", "data", ")", ":", "if", "type", "(", "data", ")", "==", "type", "(", "''", ")", ":", "return", "data", ".", "encode", "(", "'ascii'", ")", "elif", "type", "(", "data", ")", "==", "type", "(", "b''", ")", ":", "return", "data", "elif", "type", "(", "data", ")", "==", "type", "(", "bytearray", "(", ")", ")", ":", "return", "bytes", "(", "data", ")", "else", ":", "raise", "ValueError", "(", "'data must be str, bytes or bytearray'", ")" ]
[ 50, 2 ]
[ 59, 62 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
TestLambdas.test_lambda_any_and_multi_splitabble_value
(self)
Teste da funcao Any quando o valor tem espacos
Teste da funcao Any quando o valor tem espacos
def test_lambda_any_and_multi_splitabble_value(self): """Teste da funcao Any quando o valor tem espacos""" expected = "clients/any(x: x/businessName eq 'Nome grande para teste')" result = Any( self.properties["clients"].businessName == "Nome grande para teste" ) self.assertEqual(result, expected)
[ "def", "test_lambda_any_and_multi_splitabble_value", "(", "self", ")", ":", "expected", "=", "\"clients/any(x: x/businessName eq 'Nome grande para teste')\"", "result", "=", "Any", "(", "self", ".", "properties", "[", "\"clients\"", "]", ".", "businessName", "==", "\"Nome grande para teste\"", ")", "self", ".", "assertEqual", "(", "result", ",", "expected", ")" ]
[ 16, 4 ]
[ 22, 42 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Car.__init__
(self, make, model, year)
Inicializa os atributos de um carro.
Inicializa os atributos de um carro.
def __init__(self, make, model, year): """Inicializa os atributos de um carro.""" self.make = make self.model = model self.year = year self.odometer_reading = 0
[ "def", "__init__", "(", "self", ",", "make", ",", "model", ",", "year", ")", ":", "self", ".", "make", "=", "make", "self", ".", "model", "=", "model", "self", ".", "year", "=", "year", "self", ".", "odometer_reading", "=", "0" ]
[ 11, 4 ]
[ 16, 33 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
melhor_volta
(matriz)
return melhor_corredor, menor_tempo, melhor_volta
Recebe uma matriz que contém os tempos de 10 voltas de 6 corredores em uma corrida e retorna o melhor corredor, o melhor tempo e a melhor volta list -> tuple
Recebe uma matriz que contém os tempos de 10 voltas de 6 corredores em uma corrida e retorna o melhor corredor, o melhor tempo e a melhor volta list -> tuple
def melhor_volta(matriz): """Recebe uma matriz que contém os tempos de 10 voltas de 6 corredores em uma corrida e retorna o melhor corredor, o melhor tempo e a melhor volta list -> tuple""" menor_tempo = matriz[0][0] melhor_corredor = 1 melhor_volta = 1 for corredor in range(len(matriz)): for volta in range(len(matriz[0])): tempo = matriz[corredor][volta] if menor_tempo > tempo: menor_tempo = tempo melhor_corredor = corredor + 1 melhor_volta = volta + 1 return melhor_corredor, menor_tempo, melhor_volta
[ "def", "melhor_volta", "(", "matriz", ")", ":", "menor_tempo", "=", "matriz", "[", "0", "]", "[", "0", "]", "melhor_corredor", "=", "1", "melhor_volta", "=", "1", "for", "corredor", "in", "range", "(", "len", "(", "matriz", ")", ")", ":", "for", "volta", "in", "range", "(", "len", "(", "matriz", "[", "0", "]", ")", ")", ":", "tempo", "=", "matriz", "[", "corredor", "]", "[", "volta", "]", "if", "menor_tempo", ">", "tempo", ":", "menor_tempo", "=", "tempo", "melhor_corredor", "=", "corredor", "+", "1", "melhor_volta", "=", "volta", "+", "1", "return", "melhor_corredor", ",", "menor_tempo", ",", "melhor_volta" ]
[ 0, 0 ]
[ 20, 58 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
DireitosGrupoEquipamento.update
(cls, authenticated_user, pk, **kwargs)
Atualiza os direitos de um grupo de usuário em um grupo de equipamento. @return: Nothing. @raise GrupoError: Falha ao alterar os direitos. @raise DireitosGrupoEquipamento.DoesNotExist: DireitoGrupoEquipamento não cadastrado.
Atualiza os direitos de um grupo de usuário em um grupo de equipamento.
def update(cls, authenticated_user, pk, **kwargs): """Atualiza os direitos de um grupo de usuário em um grupo de equipamento. @return: Nothing. @raise GrupoError: Falha ao alterar os direitos. @raise DireitosGrupoEquipamento.DoesNotExist: DireitoGrupoEquipamento não cadastrado. """ direito = DireitosGrupoEquipamento.get_by_pk(pk) try: if 'ugrupo_id' in kwargs: del kwargs['ugrupo_id'] if 'ugrupo' in kwargs: del kwargs['ugrupo'] if 'egrupo_id' in kwargs: del kwargs['egrupo_id'] if 'egrupo' in kwargs: del kwargs['egrupo'] direito.__dict__.update(kwargs) direito.save(authenticated_user) except Exception, e: cls.log.error( u'Falha ao atualizar os direitos de um grupo de usuário em um grupo de equipamento.') raise GrupoError( e, u'Falha ao atualizar os direitos de um grupo de usuário em um grupo de equipamento.')
[ "def", "update", "(", "cls", ",", "authenticated_user", ",", "pk", ",", "*", "*", "kwargs", ")", ":", "direito", "=", "DireitosGrupoEquipamento", ".", "get_by_pk", "(", "pk", ")", "try", ":", "if", "'ugrupo_id'", "in", "kwargs", ":", "del", "kwargs", "[", "'ugrupo_id'", "]", "if", "'ugrupo'", "in", "kwargs", ":", "del", "kwargs", "[", "'ugrupo'", "]", "if", "'egrupo_id'", "in", "kwargs", ":", "del", "kwargs", "[", "'egrupo_id'", "]", "if", "'egrupo'", "in", "kwargs", ":", "del", "kwargs", "[", "'egrupo'", "]", "direito", ".", "__dict__", ".", "update", "(", "kwargs", ")", "direito", ".", "save", "(", "authenticated_user", ")", "except", "Exception", ",", "e", ":", "cls", ".", "log", ".", "error", "(", "u'Falha ao atualizar os direitos de um grupo de usuário em um grupo de equipamento.')", "", "raise", "GrupoError", "(", "e", ",", "u'Falha ao atualizar os direitos de um grupo de usuário em um grupo de equipamento.')", "" ]
[ 496, 4 ]
[ 525, 105 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
EquipamentoAcessoResource.handle_post
(self, request, user, *args, **kwargs)
Trata as requisições de POST para criar Informações de Acesso a Equipamentos. URL: /equipamentoacesso
Trata as requisições de POST para criar Informações de Acesso a Equipamentos.
def handle_post(self, request, user, *args, **kwargs): """Trata as requisições de POST para criar Informações de Acesso a Equipamentos. URL: /equipamentoacesso """ # Obtém dados do request e verifica acesso try: # Obtém os dados do xml do request xml_map, attrs_map = loads(request.raw_post_data) # Obtém o mapa correspondente ao root node do mapa do XML # (networkapi) 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.') # Verifica a existência do node "equipamento_acesso" equipamento_acesso_map = networkapi_map.get('equipamento_acesso') if equipamento_acesso_map is None: return self.response_error(3, u'Não existe valor para a tag equipamento_acesso do XML de requisição.') # Verifica a existência do valor "id_equipamento" id_equipamento = equipamento_acesso_map.get('id_equipamento') # Valid ID Equipment if not is_valid_int_greater_zero_param(id_equipamento): self.log.error( u'The id_equipamento parameter is not a valid value: %s.', id_equipamento) raise InvalidValueError(None, 'id_equipamento', id_equipamento) try: id_equipamento = int(id_equipamento) except (TypeError, ValueError): self.log.error( u'Valor do id_equipamento inválido: %s.', id_equipamento) return self.response_error(117, id_equipamento) # Após obtenção do id_equipamento podemos verificar a permissão if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION, None, id_equipamento, AdminPermission.EQUIP_WRITE_OPERATION): return self.not_authorized() # Verifica a existência do valor "fqdn" fqdn = equipamento_acesso_map.get('fqdn') # Valid fqdn if not is_valid_string_maxsize(fqdn, 100) or not is_valid_string_minsize(fqdn, 4): self.log.error(u'Parameter fqdn is invalid. Value: %s', fqdn) raise InvalidValueError(None, 'fqdn', fqdn) # Verifica a existência do valor "user" username = equipamento_acesso_map.get('user') # Valid username if not is_valid_string_maxsize(username, 20) or not is_valid_string_minsize(username, 3): self.log.error( u'Parameter username is invalid. Value: %s', username) raise InvalidValueError(None, 'username', username) # Verifica a existência do valor "pass" password = equipamento_acesso_map.get('pass') # Valid password if not is_valid_string_maxsize(password, 150) or not is_valid_string_minsize(password, 3): self.log.error(u'Parameter password is invalid.') raise InvalidValueError(None, 'password', '****') # Verifica a existência do valor "id_tipo_acesso" id_tipo_acesso = equipamento_acesso_map.get('id_tipo_acesso') # Valid ID Equipment if not is_valid_int_greater_zero_param(id_tipo_acesso): self.log.error( u'The id_tipo_acesso parameter is not a valid value: %s.', id_tipo_acesso) raise InvalidValueError(None, 'id_tipo_acesso', id_tipo_acesso) try: id_tipo_acesso = int(id_tipo_acesso) except (TypeError, ValueError): self.log.error( u'Valor do id_tipo_acesso inválido: %s.', id_tipo_acesso) return self.response_error(171, id_tipo_acesso) # Obtém o valor de "enable_pass" enable_pass = equipamento_acesso_map.get('enable_pass') # Valid enable_pass if not is_valid_string_maxsize(enable_pass, 150) or not is_valid_string_minsize(enable_pass, 3): self.log.error(u'Parameter enable_pass is invalid.') raise InvalidValueError(None, 'enable_pass', '****') # Obtém o valor de "vrf" vrf = equipamento_acesso_map.get('vrf') vrf_obj = None if vrf: # Valid enable_pass if not is_valid_int_greater_zero_param(vrf): self.log.error( u'The vrf parameter is not a valid value: %s.', vrf) raise InvalidValueError(None, 'vrf', vrf) vrf_obj = Vrf(int(vrf)) # Cria acesso ao equipamento conforme dados recebidos no XML equipamento_acesso = EquipamentoAcesso( equipamento=Equipamento(id=id_equipamento), fqdn=fqdn, user=username, password=password, tipo_acesso=TipoAcesso(id=id_tipo_acesso), enable_pass=enable_pass, vrf=vrf_obj ) equipamento_acesso.create(user) # Monta dict para response networkapi_map = dict() equipamento_acesso_map = dict() equipamento_acesso_map['id'] = equipamento_acesso.id networkapi_map['equipamento_acesso'] = equipamento_acesso_map return self.response(dumps_networkapi(networkapi_map)) except InvalidValueError as e: return self.response_error(269, e.param, e.value) except XMLError, x: self.log.error(u'Erro ao ler o XML da requisição.') return self.response_error(3, x) except EquipamentoNotFoundError: return self.response_error(117, id_equipamento) except TipoAcesso.DoesNotExist: return self.response_error(171, id_tipo_acesso) except EquipamentoAccessDuplicatedError: return self.response_error(242, id_equipamento, id_tipo_acesso) except (EquipamentoError, GrupoError): return self.response_error(1)
[ "def", "handle_post", "(", "self", ",", "request", ",", "user", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Obtém dados do request e verifica acesso", "try", ":", "# Obtém os dados do xml do request", "xml_map", ",", "attrs_map", "=", "loads", "(", "request", ".", "raw_post_data", ")", "# Obtém o mapa correspondente ao root node do mapa do XML", "# (networkapi)", "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.')", "", "# Verifica a existência do node \"equipamento_acesso\"", "equipamento_acesso_map", "=", "networkapi_map", ".", "get", "(", "'equipamento_acesso'", ")", "if", "equipamento_acesso_map", "is", "None", ":", "return", "self", ".", "response_error", "(", "3", ",", "u'Não existe valor para a tag equipamento_acesso do XML de requisição.')", "", "# Verifica a existência do valor \"id_equipamento\"", "id_equipamento", "=", "equipamento_acesso_map", ".", "get", "(", "'id_equipamento'", ")", "# Valid ID Equipment", "if", "not", "is_valid_int_greater_zero_param", "(", "id_equipamento", ")", ":", "self", ".", "log", ".", "error", "(", "u'The id_equipamento parameter is not a valid value: %s.'", ",", "id_equipamento", ")", "raise", "InvalidValueError", "(", "None", ",", "'id_equipamento'", ",", "id_equipamento", ")", "try", ":", "id_equipamento", "=", "int", "(", "id_equipamento", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "self", ".", "log", ".", "error", "(", "u'Valor do id_equipamento inválido: %s.',", " ", "d_equipamento)", "", "return", "self", ".", "response_error", "(", "117", ",", "id_equipamento", ")", "# Após obtenção do id_equipamento podemos verificar a permissão", "if", "not", "has_perm", "(", "user", ",", "AdminPermission", ".", "EQUIPMENT_MANAGEMENT", ",", "AdminPermission", ".", "WRITE_OPERATION", ",", "None", ",", "id_equipamento", ",", "AdminPermission", ".", "EQUIP_WRITE_OPERATION", ")", ":", "return", "self", ".", "not_authorized", "(", ")", "# Verifica a existência do valor \"fqdn\"", "fqdn", "=", "equipamento_acesso_map", ".", "get", "(", "'fqdn'", ")", "# Valid fqdn", "if", "not", "is_valid_string_maxsize", "(", "fqdn", ",", "100", ")", "or", "not", "is_valid_string_minsize", "(", "fqdn", ",", "4", ")", ":", "self", ".", "log", ".", "error", "(", "u'Parameter fqdn is invalid. Value: %s'", ",", "fqdn", ")", "raise", "InvalidValueError", "(", "None", ",", "'fqdn'", ",", "fqdn", ")", "# Verifica a existência do valor \"user\"", "username", "=", "equipamento_acesso_map", ".", "get", "(", "'user'", ")", "# Valid username", "if", "not", "is_valid_string_maxsize", "(", "username", ",", "20", ")", "or", "not", "is_valid_string_minsize", "(", "username", ",", "3", ")", ":", "self", ".", "log", ".", "error", "(", "u'Parameter username is invalid. Value: %s'", ",", "username", ")", "raise", "InvalidValueError", "(", "None", ",", "'username'", ",", "username", ")", "# Verifica a existência do valor \"pass\"", "password", "=", "equipamento_acesso_map", ".", "get", "(", "'pass'", ")", "# Valid password", "if", "not", "is_valid_string_maxsize", "(", "password", ",", "150", ")", "or", "not", "is_valid_string_minsize", "(", "password", ",", "3", ")", ":", "self", ".", "log", ".", "error", "(", "u'Parameter password is invalid.'", ")", "raise", "InvalidValueError", "(", "None", ",", "'password'", ",", "'****'", ")", "# Verifica a existência do valor \"id_tipo_acesso\"", "id_tipo_acesso", "=", "equipamento_acesso_map", ".", "get", "(", "'id_tipo_acesso'", ")", "# Valid ID Equipment", "if", "not", "is_valid_int_greater_zero_param", "(", "id_tipo_acesso", ")", ":", "self", ".", "log", ".", "error", "(", "u'The id_tipo_acesso parameter is not a valid value: %s.'", ",", "id_tipo_acesso", ")", "raise", "InvalidValueError", "(", "None", ",", "'id_tipo_acesso'", ",", "id_tipo_acesso", ")", "try", ":", "id_tipo_acesso", "=", "int", "(", "id_tipo_acesso", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "self", ".", "log", ".", "error", "(", "u'Valor do id_tipo_acesso inválido: %s.',", " ", "d_tipo_acesso)", "", "return", "self", ".", "response_error", "(", "171", ",", "id_tipo_acesso", ")", "# Obtém o valor de \"enable_pass\"", "enable_pass", "=", "equipamento_acesso_map", ".", "get", "(", "'enable_pass'", ")", "# Valid enable_pass", "if", "not", "is_valid_string_maxsize", "(", "enable_pass", ",", "150", ")", "or", "not", "is_valid_string_minsize", "(", "enable_pass", ",", "3", ")", ":", "self", ".", "log", ".", "error", "(", "u'Parameter enable_pass is invalid.'", ")", "raise", "InvalidValueError", "(", "None", ",", "'enable_pass'", ",", "'****'", ")", "# Obtém o valor de \"vrf\"", "vrf", "=", "equipamento_acesso_map", ".", "get", "(", "'vrf'", ")", "vrf_obj", "=", "None", "if", "vrf", ":", "# Valid enable_pass", "if", "not", "is_valid_int_greater_zero_param", "(", "vrf", ")", ":", "self", ".", "log", ".", "error", "(", "u'The vrf parameter is not a valid value: %s.'", ",", "vrf", ")", "raise", "InvalidValueError", "(", "None", ",", "'vrf'", ",", "vrf", ")", "vrf_obj", "=", "Vrf", "(", "int", "(", "vrf", ")", ")", "# Cria acesso ao equipamento conforme dados recebidos no XML", "equipamento_acesso", "=", "EquipamentoAcesso", "(", "equipamento", "=", "Equipamento", "(", "id", "=", "id_equipamento", ")", ",", "fqdn", "=", "fqdn", ",", "user", "=", "username", ",", "password", "=", "password", ",", "tipo_acesso", "=", "TipoAcesso", "(", "id", "=", "id_tipo_acesso", ")", ",", "enable_pass", "=", "enable_pass", ",", "vrf", "=", "vrf_obj", ")", "equipamento_acesso", ".", "create", "(", "user", ")", "# Monta dict para response", "networkapi_map", "=", "dict", "(", ")", "equipamento_acesso_map", "=", "dict", "(", ")", "equipamento_acesso_map", "[", "'id'", "]", "=", "equipamento_acesso", ".", "id", "networkapi_map", "[", "'equipamento_acesso'", "]", "=", "equipamento_acesso_map", "return", "self", ".", "response", "(", "dumps_networkapi", "(", "networkapi_map", ")", ")", "except", "InvalidValueError", "as", "e", ":", "return", "self", ".", "response_error", "(", "269", ",", "e", ".", "param", ",", "e", ".", "value", ")", "except", "XMLError", ",", "x", ":", "self", ".", "log", ".", "error", "(", "u'Erro ao ler o XML da requisição.')", "", "return", "self", ".", "response_error", "(", "3", ",", "x", ")", "except", "EquipamentoNotFoundError", ":", "return", "self", ".", "response_error", "(", "117", ",", "id_equipamento", ")", "except", "TipoAcesso", ".", "DoesNotExist", ":", "return", "self", ".", "response_error", "(", "171", ",", "id_tipo_acesso", ")", "except", "EquipamentoAccessDuplicatedError", ":", "return", "self", ".", "response_error", "(", "242", ",", "id_equipamento", ",", "id_tipo_acesso", ")", "except", "(", "EquipamentoError", ",", "GrupoError", ")", ":", "return", "self", ".", "response_error", "(", "1", ")" ]
[ 80, 4 ]
[ 220, 41 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
PackPOOII.deleteLine
(self, arq_text, linha)
Deleta uma linha de um arquivo de texto Parametros ---------- arq_text : str Nome do arquivo de texto, com a extenção. linha : str Conteúdo da linha de se deseja excluir
Deleta uma linha de um arquivo de texto
def deleteLine(self, arq_text, linha): """ Deleta uma linha de um arquivo de texto Parametros ---------- arq_text : str Nome do arquivo de texto, com a extenção. linha : str Conteúdo da linha de se deseja excluir """ with open(arq_text, "r") as f: lines = f.readlines() with open(arq_text, "w") as f: for line in lines: if line.strip("\n") != linha: f.write(line)
[ "def", "deleteLine", "(", "self", ",", "arq_text", ",", "linha", ")", ":", "with", "open", "(", "arq_text", ",", "\"r\"", ")", "as", "f", ":", "lines", "=", "f", ".", "readlines", "(", ")", "with", "open", "(", "arq_text", ",", "\"w\"", ")", "as", "f", ":", "for", "line", "in", "lines", ":", "if", "line", ".", "strip", "(", "\"\\n\"", ")", "!=", "linha", ":", "f", ".", "write", "(", "line", ")" ]
[ 25, 4 ]
[ 42, 33 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
NetworkData.get_router_config
(cls, router_obj)
Retorna todas as configurações do router passado por parâmetro.
Retorna todas as configurações do router passado por parâmetro.
def get_router_config(cls, router_obj): """Retorna todas as configurações do router passado por parâmetro.""" routers = NetworkData.yaml.config_routers['routers'] for router in routers: for name, conf in router.items(): if name == router_obj.nome: return conf
[ "def", "get_router_config", "(", "cls", ",", "router_obj", ")", ":", "routers", "=", "NetworkData", ".", "yaml", ".", "config_routers", "[", "'routers'", "]", "for", "router", "in", "routers", ":", "for", "name", ",", "conf", "in", "router", ".", "items", "(", ")", ":", "if", "name", "==", "router_obj", ".", "nome", ":", "return", "conf" ]
[ 94, 4 ]
[ 102, 31 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Servico.encaixaViagAlmoco
(self, vx)
se der True, alteração do almoço deve ser feita aqui e a da viagem fora
se der True, alteração do almoço deve ser feita aqui e a da viagem fora
def encaixaViagAlmoco(self, vx): #retorna True ou False se dá pra empurrar o almoço pro lado e mesmo assim alocar a viagem. hf_anteriores = [gl.vdict['hf'][idv] for idv in self.viags if gl.vdict['hf'][idv] < self.almI] hi_posteriores = [gl.vdict['hi'][idv] for idv in self.viags if gl.vdict['hi'][idv] > self.almF] try: inicFolga = hf_anteriores.sort(reverse=True)[0] fimFolga = hi_posteriores.sort() if gl.almGlob + dtm.timedelta(minutes = 5) <= fimFolga-gl.vdict['hf'][vx]: # cabe depois self.almI = gl.vdict['hf'][vx] + dtm.timedelta(minutes = 2) self.almF = self.almI + gl.almGlob return True elif gl.almGlob + dtm.timedelta(minutes = 5) <= gl.vdict['hi'][vx] - inicFolga: # cabe antes self.almF = gl.vdict['hf'][vx] - dtm.timedelta(minutes = 2) self.almI = self.almF - gl.almGlob return True else: return False except: return False """se der True, alteração do almoço deve ser feita aqui e a da viagem fora"""
[ "def", "encaixaViagAlmoco", "(", "self", ",", "vx", ")", ":", "#retorna True ou False se dá pra empurrar o almoço pro lado e mesmo assim alocar a viagem.", "hf_anteriores", "=", "[", "gl", ".", "vdict", "[", "'hf'", "]", "[", "idv", "]", "for", "idv", "in", "self", ".", "viags", "if", "gl", ".", "vdict", "[", "'hf'", "]", "[", "idv", "]", "<", "self", ".", "almI", "]", "hi_posteriores", "=", "[", "gl", ".", "vdict", "[", "'hi'", "]", "[", "idv", "]", "for", "idv", "in", "self", ".", "viags", "if", "gl", ".", "vdict", "[", "'hi'", "]", "[", "idv", "]", ">", "self", ".", "almF", "]", "try", ":", "inicFolga", "=", "hf_anteriores", ".", "sort", "(", "reverse", "=", "True", ")", "[", "0", "]", "fimFolga", "=", "hi_posteriores", ".", "sort", "(", ")", "if", "gl", ".", "almGlob", "+", "dtm", ".", "timedelta", "(", "minutes", "=", "5", ")", "<=", "fimFolga", "-", "gl", ".", "vdict", "[", "'hf'", "]", "[", "vx", "]", ":", "# cabe depois", "self", ".", "almI", "=", "gl", ".", "vdict", "[", "'hf'", "]", "[", "vx", "]", "+", "dtm", ".", "timedelta", "(", "minutes", "=", "2", ")", "self", ".", "almF", "=", "self", ".", "almI", "+", "gl", ".", "almGlob", "return", "True", "elif", "gl", ".", "almGlob", "+", "dtm", ".", "timedelta", "(", "minutes", "=", "5", ")", "<=", "gl", ".", "vdict", "[", "'hi'", "]", "[", "vx", "]", "-", "inicFolga", ":", "# cabe antes", "self", ".", "almF", "=", "gl", ".", "vdict", "[", "'hf'", "]", "[", "vx", "]", "-", "dtm", ".", "timedelta", "(", "minutes", "=", "2", ")", "self", ".", "almI", "=", "self", ".", "almF", "-", "gl", ".", "almGlob", "return", "True", "else", ":", "return", "False", "except", ":", "return", "False" ]
[ 187, 4 ]
[ 205, 88 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Settings.__init__
(self)
Inicializa as configuracoes do jogo
Inicializa as configuracoes do jogo
def __init__(self): """Inicializa as configuracoes do jogo""" # Configuracoes de tela self.screen_width = 1200 self.screen_height = 600 self.bg_color = (230, 230, 230) # Confifuracoes da espaconave self.ship_limit = 3 # Configuracoes dos projeteis self.bullet_speed_factor = 3 self.bullet_width = 3 self.bullet_height = 15 self.bullet_color = 60, 60, 60 self.bullets_allowed = 3 # Configuracoes dos alienigenas self.fleet_drop_speed = 10 # A taxa com que a velocidade do jogo aumenta self.speedup_scale = 1.5 # A taxa com que os pontos para cada alienigen aumentam self.score_scale = 1.5 self.initialize_dynamic_settings()
[ "def", "__init__", "(", "self", ")", ":", "# Configuracoes de tela", "self", ".", "screen_width", "=", "1200", "self", ".", "screen_height", "=", "600", "self", ".", "bg_color", "=", "(", "230", ",", "230", ",", "230", ")", "# Confifuracoes da espaconave", "self", ".", "ship_limit", "=", "3", "# Configuracoes dos projeteis", "self", ".", "bullet_speed_factor", "=", "3", "self", ".", "bullet_width", "=", "3", "self", ".", "bullet_height", "=", "15", "self", ".", "bullet_color", "=", "60", ",", "60", ",", "60", "self", ".", "bullets_allowed", "=", "3", "# Configuracoes dos alienigenas", "self", ".", "fleet_drop_speed", "=", "10", "# A taxa com que a velocidade do jogo aumenta", "self", ".", "speedup_scale", "=", "1.5", "# A taxa com que os pontos para cada alienigen aumentam", "self", ".", "score_scale", "=", "1.5", "self", ".", "initialize_dynamic_settings", "(", ")" ]
[ 4, 4 ]
[ 30, 42 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
RestResource.handle_delete
(self, request, user, *args, **kwargs)
return self.not_implemented()
Trata uma requisição com o método DELETE
Trata uma requisição com o método DELETE
def handle_delete(self, request, user, *args, **kwargs): """Trata uma requisição com o método DELETE""" return self.not_implemented()
[ "def", "handle_delete", "(", "self", ",", "request", ",", "user", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "not_implemented", "(", ")" ]
[ 123, 4 ]
[ 125, 37 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
CNS._validate_second_case
(self, doc: list)
return sum % 11 == 0
Validar CNSs que comecem com 7, 8 ou 9.
Validar CNSs que comecem com 7, 8 ou 9.
def _validate_second_case(self, doc: list) -> bool: """Validar CNSs que comecem com 7, 8 ou 9.""" sum = self._sum_algorithm(doc) return sum % 11 == 0
[ "def", "_validate_second_case", "(", "self", ",", "doc", ":", "list", ")", "->", "bool", ":", "sum", "=", "self", ".", "_sum_algorithm", "(", "doc", ")", "return", "sum", "%", "11", "==", "0" ]
[ 29, 4 ]
[ 33, 28 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
read_json_file
(file_path: str)
return json.loads(files.read_file(file_path))
Ler um arquivo JSON e retorna o resultado em formato de estruturas Python
Ler um arquivo JSON e retorna o resultado em formato de estruturas Python
def read_json_file(file_path: str) -> List[dict]: """Ler um arquivo JSON e retorna o resultado em formato de estruturas Python""" return json.loads(files.read_file(file_path))
[ "def", "read_json_file", "(", "file_path", ":", "str", ")", "->", "List", "[", "dict", "]", ":", "return", "json", ".", "loads", "(", "files", ".", "read_file", "(", "file_path", ")", ")" ]
[ 10, 0 ]
[ 14, 49 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
BoletoData.barcode
(self)
return barcode
Essa função sempre é a mesma para todos os bancos. Então basta implementar o método :func:`barcode` para o pyboleto calcular a linha digitável. Posição # Conteúdo 01 a 03 03 Número do banco 04 01 Código da Moeda - 9 para Real 05 01 Digito verificador do Código de Barras 06 a 09 04 Data de vencimento em dias partis de 07/10/1997 10 a 19 10 Valor do boleto (8 inteiros e 2 decimais) 20 a 44 25 Campo Livre definido por cada banco Total 44
Essa função sempre é a mesma para todos os bancos. Então basta implementar o método :func:`barcode` para o pyboleto calcular a linha digitável.
def barcode(self): """Essa função sempre é a mesma para todos os bancos. Então basta implementar o método :func:`barcode` para o pyboleto calcular a linha digitável. Posição # Conteúdo 01 a 03 03 Número do banco 04 01 Código da Moeda - 9 para Real 05 01 Digito verificador do Código de Barras 06 a 09 04 Data de vencimento em dias partis de 07/10/1997 10 a 19 10 Valor do boleto (8 inteiros e 2 decimais) 20 a 44 25 Campo Livre definido por cada banco Total 44 """ for attr, length, data_type in [ ('codigo_banco', 3, str), ('moeda', 1, str), ('data_vencimento', None, datetime.date), ('valor_documento', -1, str), ('campo_livre', 25, str)]: value = getattr(self, attr) if not isinstance(value, data_type): raise TypeError("%s.%s must be a %s, got %r (type %s)" % ( self.__class__.__name__, attr, data_type.__name__, value, type(value).__name__)) if (data_type == str and length != -1 and len(value) != length): raise ValueError( "%s.%s must have a length of %d, not %r (len: %d)" % (self.__class__.__name__, attr, length, value, len(value))) due_date_days = (self.data_vencimento - _EPOCH).days if not (9999 >= due_date_days >= 0): raise TypeError( "Invalid date, must be between 1997/07/01 and " "2024/11/15") num = "%s%1s%04d%010d%24s" % (self.codigo_banco, self.moeda, due_date_days, Decimal(self.valor_documento) * 100, self.campo_livre) dv = self.calculate_dv_barcode(num) barcode = num[:4] + str(dv) + num[4:] if len(barcode) != 44: raise BoletoException( 'The barcode must have 44 characteres, found %d' % len(barcode)) return barcode
[ "def", "barcode", "(", "self", ")", ":", "for", "attr", ",", "length", ",", "data_type", "in", "[", "(", "'codigo_banco'", ",", "3", ",", "str", ")", ",", "(", "'moeda'", ",", "1", ",", "str", ")", ",", "(", "'data_vencimento'", ",", "None", ",", "datetime", ".", "date", ")", ",", "(", "'valor_documento'", ",", "-", "1", ",", "str", ")", ",", "(", "'campo_livre'", ",", "25", ",", "str", ")", "]", ":", "value", "=", "getattr", "(", "self", ",", "attr", ")", "if", "not", "isinstance", "(", "value", ",", "data_type", ")", ":", "raise", "TypeError", "(", "\"%s.%s must be a %s, got %r (type %s)\"", "%", "(", "self", ".", "__class__", ".", "__name__", ",", "attr", ",", "data_type", ".", "__name__", ",", "value", ",", "type", "(", "value", ")", ".", "__name__", ")", ")", "if", "(", "data_type", "==", "str", "and", "length", "!=", "-", "1", "and", "len", "(", "value", ")", "!=", "length", ")", ":", "raise", "ValueError", "(", "\"%s.%s must have a length of %d, not %r (len: %d)\"", "%", "(", "self", ".", "__class__", ".", "__name__", ",", "attr", ",", "length", ",", "value", ",", "len", "(", "value", ")", ")", ")", "due_date_days", "=", "(", "self", ".", "data_vencimento", "-", "_EPOCH", ")", ".", "days", "if", "not", "(", "9999", ">=", "due_date_days", ">=", "0", ")", ":", "raise", "TypeError", "(", "\"Invalid date, must be between 1997/07/01 and \"", "\"2024/11/15\"", ")", "num", "=", "\"%s%1s%04d%010d%24s\"", "%", "(", "self", ".", "codigo_banco", ",", "self", ".", "moeda", ",", "due_date_days", ",", "Decimal", "(", "self", ".", "valor_documento", ")", "*", "100", ",", "self", ".", "campo_livre", ")", "dv", "=", "self", ".", "calculate_dv_barcode", "(", "num", ")", "barcode", "=", "num", "[", ":", "4", "]", "+", "str", "(", "dv", ")", "+", "num", "[", "4", ":", "]", "if", "len", "(", "barcode", ")", "!=", "44", ":", "raise", "BoletoException", "(", "'The barcode must have 44 characteres, found %d'", "%", "len", "(", "barcode", ")", ")", "return", "barcode" ]
[ 174, 4 ]
[ 228, 22 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Pesquisador.xml2dict
(self, tag="")
return lista
A partir do XML, extrai as informações para um dicionário. Args: tag (type): um dos tipos de produções desejados `tag`. Defaults to "". Returns: type: duas listas com as informações de dicionários.
A partir do XML, extrai as informações para um dicionário.
def xml2dict(self, tag=""): """A partir do XML, extrai as informações para um dicionário. Args: tag (type): um dos tipos de produções desejados `tag`. Defaults to "". Returns: type: duas listas com as informações de dicionários. """ tag = tag listaProducoes = ['PRODUCAO-BIBLIOGRAFICA', 'PRODUCAO-TECNICA', 'OUTRA-PRODUCAO','DADOS-COMPLEMENTARES'] if self.__FLAG: if 'DADOS-GERAIS' in tag: tree = self.root.iterchildren(tag='DADOS-GERAIS') lista_dados = [{**el1.attrib} for el1 in tree] lista_detalhe = [] elif "FORMACAO-ACADEMICA-TITULACAO" in tag: tree = self.root.iterchildren(tag='DADOS-GERAIS') lista_dados = [{'TITULACAO':el3.tag, **el3.attrib} for el1 in tree for el2 in el1.iterchildren(tag=tag) for el3 in el2.iterchildren()] lista_detalhe = [] elif tag in listaProducoes: lista_dados = self.BlocoLattes(root = self.root, lista=[tag, 'DADOS']) if tag in ['PRODUCAO-BIBLIOGRAFICA', 'OUTRA-PRODUCAO']: lista_detalhe = self.BlocoLattes(root = self.root, lista = [tag, 'DETALHAMENTO']) elif 'PRODUCAO-TECNICA' in tag: lista_detalhe = [{'PRODUCAO':el3.tag, **el3.attrib, 'FOMENTO': el4['INSTITUICAO-FINANCIADORA']} for el1 in self.root.iterchildren(tag=tag) for el2 in el1.iterchildren() for el3 in el2.iterchildren() for el4 in el3.iterchildren() if (any(tag in el4.tag for tag in ["DETALHAMENTO"]) and ['INSTITUICAO-FINANCIADORA'] in el4.keys()) ] else: lista_detalhe = [] else: print('TAG:',tag,'invalida') lista = [lista_dados,lista_detalhe] else: lista = None return lista
[ "def", "xml2dict", "(", "self", ",", "tag", "=", "\"\"", ")", ":", "tag", "=", "tag", "listaProducoes", "=", "[", "'PRODUCAO-BIBLIOGRAFICA'", ",", "'PRODUCAO-TECNICA'", ",", "'OUTRA-PRODUCAO'", ",", "'DADOS-COMPLEMENTARES'", "]", "if", "self", ".", "__FLAG", ":", "if", "'DADOS-GERAIS'", "in", "tag", ":", "tree", "=", "self", ".", "root", ".", "iterchildren", "(", "tag", "=", "'DADOS-GERAIS'", ")", "lista_dados", "=", "[", "{", "*", "*", "el1", ".", "attrib", "}", "for", "el1", "in", "tree", "]", "lista_detalhe", "=", "[", "]", "elif", "\"FORMACAO-ACADEMICA-TITULACAO\"", "in", "tag", ":", "tree", "=", "self", ".", "root", ".", "iterchildren", "(", "tag", "=", "'DADOS-GERAIS'", ")", "lista_dados", "=", "[", "{", "'TITULACAO'", ":", "el3", ".", "tag", ",", "*", "*", "el3", ".", "attrib", "}", "for", "el1", "in", "tree", "for", "el2", "in", "el1", ".", "iterchildren", "(", "tag", "=", "tag", ")", "for", "el3", "in", "el2", ".", "iterchildren", "(", ")", "]", "lista_detalhe", "=", "[", "]", "elif", "tag", "in", "listaProducoes", ":", "lista_dados", "=", "self", ".", "BlocoLattes", "(", "root", "=", "self", ".", "root", ",", "lista", "=", "[", "tag", ",", "'DADOS'", "]", ")", "if", "tag", "in", "[", "'PRODUCAO-BIBLIOGRAFICA'", ",", "'OUTRA-PRODUCAO'", "]", ":", "lista_detalhe", "=", "self", ".", "BlocoLattes", "(", "root", "=", "self", ".", "root", ",", "lista", "=", "[", "tag", ",", "'DETALHAMENTO'", "]", ")", "elif", "'PRODUCAO-TECNICA'", "in", "tag", ":", "lista_detalhe", "=", "[", "{", "'PRODUCAO'", ":", "el3", ".", "tag", ",", "*", "*", "el3", ".", "attrib", ",", "'FOMENTO'", ":", "el4", "[", "'INSTITUICAO-FINANCIADORA'", "]", "}", "for", "el1", "in", "self", ".", "root", ".", "iterchildren", "(", "tag", "=", "tag", ")", "for", "el2", "in", "el1", ".", "iterchildren", "(", ")", "for", "el3", "in", "el2", ".", "iterchildren", "(", ")", "for", "el4", "in", "el3", ".", "iterchildren", "(", ")", "if", "(", "any", "(", "tag", "in", "el4", ".", "tag", "for", "tag", "in", "[", "\"DETALHAMENTO\"", "]", ")", "and", "[", "'INSTITUICAO-FINANCIADORA'", "]", "in", "el4", ".", "keys", "(", ")", ")", "]", "else", ":", "lista_detalhe", "=", "[", "]", "else", ":", "print", "(", "'TAG:'", ",", "tag", ",", "'invalida'", ")", "lista", "=", "[", "lista_dados", ",", "lista_detalhe", "]", "else", ":", "lista", "=", "None", "return", "lista" ]
[ 560, 4 ]
[ 604, 20 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
SimpleEdge.__init__
(self, name=None, vertex_a=None, vertex_b=None)
Inicialização dos atributos da classe SimpleEdge.
Inicialização dos atributos da classe SimpleEdge.
def __init__(self, name=None, vertex_a=None, vertex_b=None): """ Inicialização dos atributos da classe SimpleEdge.""" if name is None: name = vertex_a.value.__str__() + vertex_b.value.__str__() self.name = name self.vertex_a = vertex_a self.vertex_b = vertex_b
[ "def", "__init__", "(", "self", ",", "name", "=", "None", ",", "vertex_a", "=", "None", ",", "vertex_b", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "vertex_a", ".", "value", ".", "__str__", "(", ")", "+", "vertex_b", ".", "value", ".", "__str__", "(", ")", "self", ".", "name", "=", "name", "self", ".", "vertex_a", "=", "vertex_a", "self", ".", "vertex_b", "=", "vertex_b" ]
[ 6, 4 ]
[ 12, 32 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Population.autoAdjust
(self)
return
Função para realizar o refinamento do melhor indivíduo incialmente forcando uma mutation com passo baixo pra cada OS (double locus) individualmente testando hard constraints (feasible) a cada OS alterada a tendencia é convergir mais rapido, pois o refinamento passa a ser direcionado e nao depender do crossover e mutation
Função para realizar o refinamento do melhor indivíduo incialmente forcando uma mutation com passo baixo pra cada OS (double locus) individualmente testando hard constraints (feasible) a cada OS alterada a tendencia é convergir mais rapido, pois o refinamento passa a ser direcionado e nao depender do crossover e mutation
def autoAdjust(self): ''' Função para realizar o refinamento do melhor indivíduo incialmente forcando uma mutation com passo baixo pra cada OS (double locus) individualmente testando hard constraints (feasible) a cada OS alterada a tendencia é convergir mais rapido, pois o refinamento passa a ser direcionado e nao depender do crossover e mutation''' passs = 1 if len(self.list_fitness) > 0: c = self.chromosomes[ self.list_fitness[0][0] ] fitness = c.fitness for i in range(1,c.length,2): # apenas campos hora c.addTimeBlocks(i,passs) c.update() # update task list and calc fitness if c.fitness >= fitness: # piorou ou nao mudou c.addTimeBlocks(i,-passs) # restaura c.addTimeBlocks(i,-passs) # anda no sentido contrário c.update() # update task list and calc fitness while (c.fitness != -1) and (c.fitness < fitness): if self.ga.print: print( "adjusting - ") fitness = c.fitness c.addTimeBlocks(i,-passs) c.update() # update task list and calc fitness c.addTimeBlocks(i,passs) c.update() # update task list and calc fitness fitness = c.fitness elif c.fitness < fitness: # melhorou while (c.fitness != -1) and (c.fitness < fitness): if self.ga.print: print( "adjusting + ") fitness = c.fitness c.addTimeBlocks(i,passs) c.update() # update task list and calc fitness c.addTimeBlocks(i,-passs) c.update() # update task list and calc fitness fitness = c.fitness c.update() # update task list and calc fitness self.updateFitnessList() return
[ "def", "autoAdjust", "(", "self", ")", ":", "passs", "=", "1", "if", "len", "(", "self", ".", "list_fitness", ")", ">", "0", ":", "c", "=", "self", ".", "chromosomes", "[", "self", ".", "list_fitness", "[", "0", "]", "[", "0", "]", "]", "fitness", "=", "c", ".", "fitness", "for", "i", "in", "range", "(", "1", ",", "c", ".", "length", ",", "2", ")", ":", "# apenas campos hora", "c", ".", "addTimeBlocks", "(", "i", ",", "passs", ")", "c", ".", "update", "(", ")", "# update task list and calc fitness", "if", "c", ".", "fitness", ">=", "fitness", ":", "# piorou ou nao mudou", "c", ".", "addTimeBlocks", "(", "i", ",", "-", "passs", ")", "# restaura", "c", ".", "addTimeBlocks", "(", "i", ",", "-", "passs", ")", "# anda no sentido contrário", "c", ".", "update", "(", ")", "# update task list and calc fitness", "while", "(", "c", ".", "fitness", "!=", "-", "1", ")", "and", "(", "c", ".", "fitness", "<", "fitness", ")", ":", "if", "self", ".", "ga", ".", "print", ":", "print", "(", "\"adjusting - \"", ")", "fitness", "=", "c", ".", "fitness", "c", ".", "addTimeBlocks", "(", "i", ",", "-", "passs", ")", "c", ".", "update", "(", ")", "# update task list and calc fitness ", "c", ".", "addTimeBlocks", "(", "i", ",", "passs", ")", "c", ".", "update", "(", ")", "# update task list and calc fitness", "fitness", "=", "c", ".", "fitness", "elif", "c", ".", "fitness", "<", "fitness", ":", "# melhorou", "while", "(", "c", ".", "fitness", "!=", "-", "1", ")", "and", "(", "c", ".", "fitness", "<", "fitness", ")", ":", "if", "self", ".", "ga", ".", "print", ":", "print", "(", "\"adjusting + \"", ")", "fitness", "=", "c", ".", "fitness", "c", ".", "addTimeBlocks", "(", "i", ",", "passs", ")", "c", ".", "update", "(", ")", "# update task list and calc fitness", "c", ".", "addTimeBlocks", "(", "i", ",", "-", "passs", ")", "c", ".", "update", "(", ")", "# update task list and calc fitness", "fitness", "=", "c", ".", "fitness", "c", ".", "update", "(", ")", "# update task list and calc fitness", "self", ".", "updateFitnessList", "(", ")", "return" ]
[ 339, 4 ]
[ 389, 14 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
EletronicDocument.get_partner_nfe
(self, nfe, destinatary, partner_automation)
return dict(partner_id=partner_id.id)
Importação da sessão <emit> do xml
Importação da sessão <emit> do xml
def get_partner_nfe(self, nfe, destinatary, partner_automation): '''Importação da sessão <emit> do xml''' tag_nfe = None if destinatary: tag_nfe = nfe.NFe.infNFe.emit else: tag_nfe = nfe.NFe.infNFe.dest if hasattr(tag_nfe, 'CNPJ'): cnpj_cpf = cnpj_cpf_format(str(tag_nfe.CNPJ.text).zfill(14)) else: cnpj_cpf = cnpj_cpf_format(str(tag_nfe.CPF.text).zfill(11)) partner_id = self.env['res.partner'].search([ ('l10n_br_cnpj_cpf', '=', cnpj_cpf)], limit=1) if not partner_id and partner_automation: partner_id = self._create_partner(tag_nfe, destinatary) elif not partner_id and not partner_automation: raise UserError(( 'Parceiro não cadastrado. Selecione a opção cadastrar ' + 'parceiro, ou realize o cadastro manualmente.')) return dict(partner_id=partner_id.id)
[ "def", "get_partner_nfe", "(", "self", ",", "nfe", ",", "destinatary", ",", "partner_automation", ")", ":", "tag_nfe", "=", "None", "if", "destinatary", ":", "tag_nfe", "=", "nfe", ".", "NFe", ".", "infNFe", ".", "emit", "else", ":", "tag_nfe", "=", "nfe", ".", "NFe", ".", "infNFe", ".", "dest", "if", "hasattr", "(", "tag_nfe", ",", "'CNPJ'", ")", ":", "cnpj_cpf", "=", "cnpj_cpf_format", "(", "str", "(", "tag_nfe", ".", "CNPJ", ".", "text", ")", ".", "zfill", "(", "14", ")", ")", "else", ":", "cnpj_cpf", "=", "cnpj_cpf_format", "(", "str", "(", "tag_nfe", ".", "CPF", ".", "text", ")", ".", "zfill", "(", "11", ")", ")", "partner_id", "=", "self", ".", "env", "[", "'res.partner'", "]", ".", "search", "(", "[", "(", "'l10n_br_cnpj_cpf'", ",", "'='", ",", "cnpj_cpf", ")", "]", ",", "limit", "=", "1", ")", "if", "not", "partner_id", "and", "partner_automation", ":", "partner_id", "=", "self", ".", "_create_partner", "(", "tag_nfe", ",", "destinatary", ")", "elif", "not", "partner_id", "and", "not", "partner_automation", ":", "raise", "UserError", "(", "(", "'Parceiro não cadastrado. Selecione a opção cadastrar ' +", "", "'parceiro, ou realize o cadastro manualmente.'", ")", ")", "return", "dict", "(", "partner_id", "=", "partner_id", ".", "id", ")" ]
[ 108, 4 ]
[ 130, 45 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
distribute_and_over_or
(s)
Dada uma sentença s consistindo de conjunções e disjunções      de literais, devolver uma sentença equivalente em CNF. >>> distribute_and_over_or((A & B) | C) ((A | C) & (B | C))
Dada uma sentença s consistindo de conjunções e disjunções      de literais, devolver uma sentença equivalente em CNF. >>> distribute_and_over_or((A & B) | C) ((A | C) & (B | C))
def distribute_and_over_or(s): """Dada uma sentença s consistindo de conjunções e disjunções      de literais, devolver uma sentença equivalente em CNF. >>> distribute_and_over_or((A & B) | C) ((A | C) & (B | C)) """ s = expr(s) if s.op == '|': s = associate('|', s.args) if s.op != '|': return distribute_and_over_or(s) if len(s.args) == 0: return False if len(s.args) == 1: return distribute_and_over_or(s.args[0]) conj = first(arg for arg in s.args if arg.op == '&') if not conj: return s others = [a for a in s.args if a is not conj] rest = associate('|', others) return associate('&', [distribute_and_over_or(c | rest) for c in conj.args]) elif s.op == '&': return associate('&', list(map(distribute_and_over_or, s.args))) else: return s
[ "def", "distribute_and_over_or", "(", "s", ")", ":", "s", "=", "expr", "(", "s", ")", "if", "s", ".", "op", "==", "'|'", ":", "s", "=", "associate", "(", "'|'", ",", "s", ".", "args", ")", "if", "s", ".", "op", "!=", "'|'", ":", "return", "distribute_and_over_or", "(", "s", ")", "if", "len", "(", "s", ".", "args", ")", "==", "0", ":", "return", "False", "if", "len", "(", "s", ".", "args", ")", "==", "1", ":", "return", "distribute_and_over_or", "(", "s", ".", "args", "[", "0", "]", ")", "conj", "=", "first", "(", "arg", "for", "arg", "in", "s", ".", "args", "if", "arg", ".", "op", "==", "'&'", ")", "if", "not", "conj", ":", "return", "s", "others", "=", "[", "a", "for", "a", "in", "s", ".", "args", "if", "a", "is", "not", "conj", "]", "rest", "=", "associate", "(", "'|'", ",", "others", ")", "return", "associate", "(", "'&'", ",", "[", "distribute_and_over_or", "(", "c", "|", "rest", ")", "for", "c", "in", "conj", ".", "args", "]", ")", "elif", "s", ".", "op", "==", "'&'", ":", "return", "associate", "(", "'&'", ",", "list", "(", "map", "(", "distribute_and_over_or", ",", "s", ".", "args", ")", ")", ")", "else", ":", "return", "s" ]
[ 330, 0 ]
[ 355, 16 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Log.__init__
(self, module_name)
Cria um logger para o módulo informado.
Cria um logger para o módulo informado.
def __init__(self, module_name): """Cria um logger para o módulo informado.""" self.module_name = module_name self.__init_log(Log._LOG_FILE_NAME, Log._NUMBER_OF_DAYS_TO_LOG, Log._LOG_LEVEL, Log._LOG_FORMAT, Log._USE_STDOUT, Log._MAX_LINE_SIZE)
[ "def", "__init__", "(", "self", ",", "module_name", ")", ":", "self", ".", "module_name", "=", "module_name", "self", ".", "__init_log", "(", "Log", ".", "_LOG_FILE_NAME", ",", "Log", ".", "_NUMBER_OF_DAYS_TO_LOG", ",", "Log", ".", "_LOG_LEVEL", ",", "Log", ".", "_LOG_FORMAT", ",", "Log", ".", "_USE_STDOUT", ",", "Log", ".", "_MAX_LINE_SIZE", ")" ]
[ 146, 4 ]
[ 154, 43 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
journal_to_kernel
(journal)
return _bundle
Transforma um objeto Journal (xylose) para o formato de dados equivalente ao persistido pelo Kernel em um banco mongodb
Transforma um objeto Journal (xylose) para o formato de dados equivalente ao persistido pelo Kernel em um banco mongodb
def journal_to_kernel(journal): """Transforma um objeto Journal (xylose) para o formato de dados equivalente ao persistido pelo Kernel em um banco mongodb""" # TODO: Virá algo do xylose para popular o campo de métricas? _id = journal.scielo_issn if not _id: raise ValueError("É preciso que o periódico possua um id") _creation_date = parse_date(journal.creation_date) _metadata = {} _bundle = { "_id": _id, "id": _id, "created": _creation_date, "updated": _creation_date, "items": [], "metadata": _metadata, } if journal.mission: _mission = [ {"language": lang, "value": value} for lang, value in journal.mission.items() ] _metadata["mission"] = _mission if journal.title: _metadata["title"] = journal.title if journal.abbreviated_iso_title: _metadata["title_iso"] = journal.abbreviated_iso_title if journal.abbreviated_title: _metadata["short_title"] = journal.abbreviated_title _metadata["acronym"] = journal.acronym if journal.scielo_issn: _metadata["scielo_issn"] = journal.scielo_issn if journal.print_issn: _metadata["print_issn"] = journal.print_issn if journal.electronic_issn: _metadata["electronic_issn"] = journal.electronic_issn if journal.status_history: _metadata["status_history"] = [] for status in journal.status_history: _status = {"status": status[1], "date": parse_date(status[0])} if status[2]: _status["reason"] = status[2] # TODO: Temos que verificar se as datas são autoritativas _metadata["status_history"].append(_status) if journal.subject_areas: _metadata["subject_areas"] = journal.subject_areas if journal.sponsors: _metadata["sponsors"] = [{"name": sponsor} for sponsor in journal.sponsors] if journal.wos_subject_areas: _metadata["subject_categories"] = journal.wos_subject_areas if journal.submission_url: _metadata["online_submission_url"] = journal.submission_url if journal.next_title: _metadata["next_journal"] = {"name": journal.next_title} if journal.previous_title: _metadata["previous_journal"] = {"name": journal.previous_title} _contact = {} if journal.editor_email: _contact["email"] = journal.editor_email if journal.editor_address: _contact["address"] = journal.editor_address if _contact: _metadata["contact"] = _contact if journal.publisher_name: institutions = [] for name in journal.publisher_name: item = {"name": name} if journal.publisher_city: item["city"] = journal.publisher_city if journal.publisher_state: item["state"] = journal.publisher_state if journal.publisher_country: country_code, country_name = journal.publisher_country item["country_code"] = country_code item["country"] = country_name institutions.append(item) _metadata["institution_responsible_for"] = tuple(institutions) return _bundle
[ "def", "journal_to_kernel", "(", "journal", ")", ":", "# TODO: Virá algo do xylose para popular o campo de métricas?", "_id", "=", "journal", ".", "scielo_issn", "if", "not", "_id", ":", "raise", "ValueError", "(", "\"É preciso que o periódico possua um id\")", "", "_creation_date", "=", "parse_date", "(", "journal", ".", "creation_date", ")", "_metadata", "=", "{", "}", "_bundle", "=", "{", "\"_id\"", ":", "_id", ",", "\"id\"", ":", "_id", ",", "\"created\"", ":", "_creation_date", ",", "\"updated\"", ":", "_creation_date", ",", "\"items\"", ":", "[", "]", ",", "\"metadata\"", ":", "_metadata", ",", "}", "if", "journal", ".", "mission", ":", "_mission", "=", "[", "{", "\"language\"", ":", "lang", ",", "\"value\"", ":", "value", "}", "for", "lang", ",", "value", "in", "journal", ".", "mission", ".", "items", "(", ")", "]", "_metadata", "[", "\"mission\"", "]", "=", "_mission", "if", "journal", ".", "title", ":", "_metadata", "[", "\"title\"", "]", "=", "journal", ".", "title", "if", "journal", ".", "abbreviated_iso_title", ":", "_metadata", "[", "\"title_iso\"", "]", "=", "journal", ".", "abbreviated_iso_title", "if", "journal", ".", "abbreviated_title", ":", "_metadata", "[", "\"short_title\"", "]", "=", "journal", ".", "abbreviated_title", "_metadata", "[", "\"acronym\"", "]", "=", "journal", ".", "acronym", "if", "journal", ".", "scielo_issn", ":", "_metadata", "[", "\"scielo_issn\"", "]", "=", "journal", ".", "scielo_issn", "if", "journal", ".", "print_issn", ":", "_metadata", "[", "\"print_issn\"", "]", "=", "journal", ".", "print_issn", "if", "journal", ".", "electronic_issn", ":", "_metadata", "[", "\"electronic_issn\"", "]", "=", "journal", ".", "electronic_issn", "if", "journal", ".", "status_history", ":", "_metadata", "[", "\"status_history\"", "]", "=", "[", "]", "for", "status", "in", "journal", ".", "status_history", ":", "_status", "=", "{", "\"status\"", ":", "status", "[", "1", "]", ",", "\"date\"", ":", "parse_date", "(", "status", "[", "0", "]", ")", "}", "if", "status", "[", "2", "]", ":", "_status", "[", "\"reason\"", "]", "=", "status", "[", "2", "]", "# TODO: Temos que verificar se as datas são autoritativas", "_metadata", "[", "\"status_history\"", "]", ".", "append", "(", "_status", ")", "if", "journal", ".", "subject_areas", ":", "_metadata", "[", "\"subject_areas\"", "]", "=", "journal", ".", "subject_areas", "if", "journal", ".", "sponsors", ":", "_metadata", "[", "\"sponsors\"", "]", "=", "[", "{", "\"name\"", ":", "sponsor", "}", "for", "sponsor", "in", "journal", ".", "sponsors", "]", "if", "journal", ".", "wos_subject_areas", ":", "_metadata", "[", "\"subject_categories\"", "]", "=", "journal", ".", "wos_subject_areas", "if", "journal", ".", "submission_url", ":", "_metadata", "[", "\"online_submission_url\"", "]", "=", "journal", ".", "submission_url", "if", "journal", ".", "next_title", ":", "_metadata", "[", "\"next_journal\"", "]", "=", "{", "\"name\"", ":", "journal", ".", "next_title", "}", "if", "journal", ".", "previous_title", ":", "_metadata", "[", "\"previous_journal\"", "]", "=", "{", "\"name\"", ":", "journal", ".", "previous_title", "}", "_contact", "=", "{", "}", "if", "journal", ".", "editor_email", ":", "_contact", "[", "\"email\"", "]", "=", "journal", ".", "editor_email", "if", "journal", ".", "editor_address", ":", "_contact", "[", "\"address\"", "]", "=", "journal", ".", "editor_address", "if", "_contact", ":", "_metadata", "[", "\"contact\"", "]", "=", "_contact", "if", "journal", ".", "publisher_name", ":", "institutions", "=", "[", "]", "for", "name", "in", "journal", ".", "publisher_name", ":", "item", "=", "{", "\"name\"", ":", "name", "}", "if", "journal", ".", "publisher_city", ":", "item", "[", "\"city\"", "]", "=", "journal", ".", "publisher_city", "if", "journal", ".", "publisher_state", ":", "item", "[", "\"state\"", "]", "=", "journal", ".", "publisher_state", "if", "journal", ".", "publisher_country", ":", "country_code", ",", "country_name", "=", "journal", ".", "publisher_country", "item", "[", "\"country_code\"", "]", "=", "country_code", "item", "[", "\"country\"", "]", "=", "country_name", "institutions", ".", "append", "(", "item", ")", "_metadata", "[", "\"institution_responsible_for\"", "]", "=", "tuple", "(", "institutions", ")", "return", "_bundle" ]
[ 91, 0 ]
[ 197, 18 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
issue_to_kernel
(issue)
return _bundle
Transforma um objeto Issue (xylose) para o formato de dados equivalente ao persistido pelo Kernel em um banco mongodb
Transforma um objeto Issue (xylose) para o formato de dados equivalente ao persistido pelo Kernel em um banco mongodb
def issue_to_kernel(issue): """Transforma um objeto Issue (xylose) para o formato de dados equivalente ao persistido pelo Kernel em um banco mongodb""" issn_id = issue.data["issue"]["v35"][0]["_"] _creation_date = parse_date(issue.publication_date) _metadata = {} _bundle = { "created": _creation_date, "updated": _creation_date, "items": [], "metadata": _metadata, } _year = str(date_to_datetime(_creation_date).year) _month = str(date_to_datetime(_creation_date).month) _metadata["publication_year"] = _year if issue.volume: _metadata["volume"] = issue.volume if issue.number: _metadata["number"] = issue.number _supplement = None if issue.type is "supplement": _supplement = "0" if issue.supplement_volume: _supplement = issue.supplement_volume elif issue.supplement_number: _supplement = issue.supplement_number _metadata["supplement"] = _supplement if issue.titles: _titles = [ {"language": lang, "value": value} for lang, value in issue.titles.items() ] _metadata["titles"] = _titles publication_months = {} if issue.start_month and issue.end_month: publication_months["range"] = (int(issue.start_month), int(issue.end_month)) elif _month: publication_months["month"] = int(_month) _metadata["publication_months"] = publication_months _id = scielo_ids_generator.any_bundle_id( issn_id, _year, issue.volume, issue.number, _supplement ) _bundle["_id"] = _id _bundle["id"] = _id return _bundle
[ "def", "issue_to_kernel", "(", "issue", ")", ":", "issn_id", "=", "issue", ".", "data", "[", "\"issue\"", "]", "[", "\"v35\"", "]", "[", "0", "]", "[", "\"_\"", "]", "_creation_date", "=", "parse_date", "(", "issue", ".", "publication_date", ")", "_metadata", "=", "{", "}", "_bundle", "=", "{", "\"created\"", ":", "_creation_date", ",", "\"updated\"", ":", "_creation_date", ",", "\"items\"", ":", "[", "]", ",", "\"metadata\"", ":", "_metadata", ",", "}", "_year", "=", "str", "(", "date_to_datetime", "(", "_creation_date", ")", ".", "year", ")", "_month", "=", "str", "(", "date_to_datetime", "(", "_creation_date", ")", ".", "month", ")", "_metadata", "[", "\"publication_year\"", "]", "=", "_year", "if", "issue", ".", "volume", ":", "_metadata", "[", "\"volume\"", "]", "=", "issue", ".", "volume", "if", "issue", ".", "number", ":", "_metadata", "[", "\"number\"", "]", "=", "issue", ".", "number", "_supplement", "=", "None", "if", "issue", ".", "type", "is", "\"supplement\"", ":", "_supplement", "=", "\"0\"", "if", "issue", ".", "supplement_volume", ":", "_supplement", "=", "issue", ".", "supplement_volume", "elif", "issue", ".", "supplement_number", ":", "_supplement", "=", "issue", ".", "supplement_number", "_metadata", "[", "\"supplement\"", "]", "=", "_supplement", "if", "issue", ".", "titles", ":", "_titles", "=", "[", "{", "\"language\"", ":", "lang", ",", "\"value\"", ":", "value", "}", "for", "lang", ",", "value", "in", "issue", ".", "titles", ".", "items", "(", ")", "]", "_metadata", "[", "\"titles\"", "]", "=", "_titles", "publication_months", "=", "{", "}", "if", "issue", ".", "start_month", "and", "issue", ".", "end_month", ":", "publication_months", "[", "\"range\"", "]", "=", "(", "int", "(", "issue", ".", "start_month", ")", ",", "int", "(", "issue", ".", "end_month", ")", ")", "elif", "_month", ":", "publication_months", "[", "\"month\"", "]", "=", "int", "(", "_month", ")", "_metadata", "[", "\"publication_months\"", "]", "=", "publication_months", "_id", "=", "scielo_ids_generator", ".", "any_bundle_id", "(", "issn_id", ",", "_year", ",", "issue", ".", "volume", ",", "issue", ".", "number", ",", "_supplement", ")", "_bundle", "[", "\"_id\"", "]", "=", "_id", "_bundle", "[", "\"id\"", "]", "=", "_id", "return", "_bundle" ]
[ 206, 0 ]
[ 262, 18 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
linha.__le__
(self, outro)
Compara o .recuo ou a diferença de indentação se o outro objeto tiver, caso contrário, compara igualdade ou se .__str__ é menor
Compara o .recuo ou a diferença de indentação se o outro objeto tiver, caso contrário, compara igualdade ou se .__str__ é menor
def __le__ (self, outro): '''Compara o .recuo ou a diferença de indentação se o outro objeto tiver, caso contrário, compara igualdade ou se .__str__ é menor''' try: return self.recuo <= outro.recuo or self.indentar() <= outro.indentar() except AttributeError: return self.__str__() < str(outro) or self.__eq__(outro)
[ "def", "__le__", "(", "self", ",", "outro", ")", ":", "try", ":", "return", "self", ".", "recuo", "<=", "outro", ".", "recuo", "or", "self", ".", "indentar", "(", ")", "<=", "outro", ".", "indentar", "(", ")", "except", "AttributeError", ":", "return", "self", ".", "__str__", "(", ")", "<", "str", "(", "outro", ")", "or", "self", ".", "__eq__", "(", "outro", ")" ]
[ 397, 1 ]
[ 402, 59 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
plot_exataXsol
(Name, vector, sol, Erro)
Plota a solucao exata, nossa solucao e a diferenca entre ambas no instante T
Plota a solucao exata, nossa solucao e a diferenca entre ambas no instante T
def plot_exataXsol(Name, vector, sol, Erro): ''''Plota a solucao exata, nossa solucao e a diferenca entre ambas no instante T''' N = vector.shape[0] + 1 xspace = np.linspace(0, 1, N + 1)[1:-1] plt.clf() plt.plot(xspace, vector) plt.plot(xspace, sol) plt.ylim(0, np.max(vector) + 0.15*np.max(vector)) plt.xlim(0, 1) plt.legend(['Solução exata', 'Solução calculada']) plt.ylabel('Temperature') plt.xlabel('Position') plt.suptitle('Solução exata e calculada, ' + Name) plt.text(0.35, 0.5, 'Erro quadrático = {}'.format(np.format_float_scientific(Erro, 2)), dict(size=12)) plt.savefig('{}.png'.format('plots/exataXcalculada' + Name)) plt.show() plt.clf() plt.plot(xspace, vector - sol) plt.axhline(0, color='black', lw=1) plt.xlim(0, 1) plt.legend(['Erro']) plt.ylabel('Diference in temperature') plt.xlabel('Position') plt.suptitle('Diferença entre solução exata e calculada (erro ponto a ponto), ' + Name) plt.savefig('{}.png'.format('plots/erro' + Name)) plt.show()
[ "def", "plot_exataXsol", "(", "Name", ",", "vector", ",", "sol", ",", "Erro", ")", ":", "N", "=", "vector", ".", "shape", "[", "0", "]", "+", "1", "xspace", "=", "np", ".", "linspace", "(", "0", ",", "1", ",", "N", "+", "1", ")", "[", "1", ":", "-", "1", "]", "plt", ".", "clf", "(", ")", "plt", ".", "plot", "(", "xspace", ",", "vector", ")", "plt", ".", "plot", "(", "xspace", ",", "sol", ")", "plt", ".", "ylim", "(", "0", ",", "np", ".", "max", "(", "vector", ")", "+", "0.15", "*", "np", ".", "max", "(", "vector", ")", ")", "plt", ".", "xlim", "(", "0", ",", "1", ")", "plt", ".", "legend", "(", "[", "'Solução exata', ", "'", "olução calculada'])\r", "", "", "plt", ".", "ylabel", "(", "'Temperature'", ")", "plt", ".", "xlabel", "(", "'Position'", ")", "plt", ".", "suptitle", "(", "'Solução exata e calculada, ' +", "N", "me)\r", "", "plt", ".", "text", "(", "0.35", ",", "0.5", ",", "'Erro quadrático = {}'.", "f", "ormat(", "n", "p.", "f", "ormat_float_scientific(", "E", "rro,", " ", ")", ")", ",", " ", "ict(", "s", "ize=", "1", "2)", ")", "\r", "plt", ".", "savefig", "(", "'{}.png'", ".", "format", "(", "'plots/exataXcalculada'", "+", "Name", ")", ")", "plt", ".", "show", "(", ")", "plt", ".", "clf", "(", ")", "plt", ".", "plot", "(", "xspace", ",", "vector", "-", "sol", ")", "plt", ".", "axhline", "(", "0", ",", "color", "=", "'black'", ",", "lw", "=", "1", ")", "plt", ".", "xlim", "(", "0", ",", "1", ")", "plt", ".", "legend", "(", "[", "'Erro'", "]", ")", "plt", ".", "ylabel", "(", "'Diference in temperature'", ")", "plt", ".", "xlabel", "(", "'Position'", ")", "plt", ".", "suptitle", "(", "'Diferença entre solução exata e calculada (erro ponto a ponto), ' + ", "a", "e)\r", "", "plt", ".", "savefig", "(", "'{}.png'", ".", "format", "(", "'plots/erro'", "+", "Name", ")", ")", "plt", ".", "show", "(", ")" ]
[ 170, 0 ]
[ 197, 14 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
previous_played_rounds
(df, rodada, atleta)
return list_
Função usada para buscar no DataFrame df pontuação de rounds passadas Args: rodada: número da rodada onde será buscada a pontuação passada atleta: id od jogador a ser buscado
Função usada para buscar no DataFrame df pontuação de rounds passadas Args: rodada: número da rodada onde será buscada a pontuação passada atleta: id od jogador a ser buscado
def previous_played_rounds(df, rodada, atleta): """Função usada para buscar no DataFrame df pontuação de rounds passadas Args: rodada: número da rodada onde será buscada a pontuação passada atleta: id od jogador a ser buscado """ #if rodada <= 1: return [0,0,0,0,0] list_ = pd.DataFrame() for i in range(rodada-1, 0, -1): # loop reverso de (rodada-1) até 1 row = df[ (df['atletas.rodada_id'] == (i)) & (df['atletas.atleta_id'] == atleta)] #print(row) if row.empty: # if player didnt play in round i, pass pass # print('pass') else: list_ = list_.append(row) # print('append') if len(list_) >= 5: return list_ # if there is 4 or less played round, append 0 to make len(list) = 5 #for i in range(5-len(list_)): list_.append(0) return list_
[ "def", "previous_played_rounds", "(", "df", ",", "rodada", ",", "atleta", ")", ":", "#if rodada <= 1: return [0,0,0,0,0]", "list_", "=", "pd", ".", "DataFrame", "(", ")", "for", "i", "in", "range", "(", "rodada", "-", "1", ",", "0", ",", "-", "1", ")", ":", "# loop reverso de (rodada-1) até 1", "row", "=", "df", "[", "(", "df", "[", "'atletas.rodada_id'", "]", "==", "(", "i", ")", ")", "&", "(", "df", "[", "'atletas.atleta_id'", "]", "==", "atleta", ")", "]", "#print(row)", "if", "row", ".", "empty", ":", "# if player didnt play in round i, pass", "pass", "# print('pass')", "else", ":", "list_", "=", "list_", ".", "append", "(", "row", ")", "# print('append')", "if", "len", "(", "list_", ")", ">=", "5", ":", "return", "list_", "# if there is 4 or less played round, append 0 to make len(list) = 5", "#for i in range(5-len(list_)): list_.append(0)", "return", "list_" ]
[ 214, 0 ]
[ 240, 16 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Agent.perform
(self, action, cave, kb)
return False
Executa uma ação. Retorna True se a ação mata o Wumpus, caso contrário False.
Executa uma ação. Retorna True se a ação mata o Wumpus, caso contrário False.
def perform(self, action, cave, kb): """Executa uma ação. Retorna True se a ação mata o Wumpus, caso contrário False.""" kind, rotations = action if kind == Action.Move: self.move(rotations) elif kind == Action.Shoot: if rotations is not None: self.direction = turn(self.direction, rotations) return self.shoot(cave, kb) elif kind == Action.Grab: cave[self.location].gold = Status.Absent self.has_gold = True elif kind == Action.Turn: self.direction = turn(self.direction, rotations) return False
[ "def", "perform", "(", "self", ",", "action", ",", "cave", ",", "kb", ")", ":", "kind", ",", "rotations", "=", "action", "if", "kind", "==", "Action", ".", "Move", ":", "self", ".", "move", "(", "rotations", ")", "elif", "kind", "==", "Action", ".", "Shoot", ":", "if", "rotations", "is", "not", "None", ":", "self", ".", "direction", "=", "turn", "(", "self", ".", "direction", ",", "rotations", ")", "return", "self", ".", "shoot", "(", "cave", ",", "kb", ")", "elif", "kind", "==", "Action", ".", "Grab", ":", "cave", "[", "self", ".", "location", "]", ".", "gold", "=", "Status", ".", "Absent", "self", ".", "has_gold", "=", "True", "elif", "kind", "==", "Action", ".", "Turn", ":", "self", ".", "direction", "=", "turn", "(", "self", ".", "direction", ",", "rotations", ")", "return", "False" ]
[ 126, 2 ]
[ 142, 16 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Meme.trump
(self, ctx)
memes do donalt trump coma pasta
memes do donalt trump coma pasta
async def trump(self, ctx): """memes do donalt trump coma pasta""" meme = ctx.message.content[7:] if len(meme) > 107: await ctx.send("Menssagem muito grande") return fundo = Image.open('img/mesmes/trump.jpg') Fonte = ImageFont.truetype('fonts/uni-sans.heavy-caps.otf',90) escreve = ImageDraw.Draw(fundo) a1, r, ter = 1, 1, len(meme)+1 # nosso "paginador" itens_por_linha = 20 ends = [''] * (itens_por_linha - 1) ends.append('\n') a = 0 eixo_x = 740 eixo_y = 570 quebra = 1 for item, end in zip(range(a1, r * ter, r), cycle(ends)): #print("i", end=end) #print(meme[item], end=end) if quebra == 20: quebra = 1 eixo_y += 100 eixo_x = 740 #print(meme[a],end=end) escreve.text(xy=(eixo_x,eixo_y), text=meme[a],end=end, fill=(13, 13, 13), font=Fonte) eixo_x += 50 a += 1 quebra += 1 fundo.save('img/mesmes/trump_1.png') info_png = discord.File('img/mesmes/trump_1.png') await ctx.send(file=info_png) self.client.counter += 1
[ "async", "def", "trump", "(", "self", ",", "ctx", ")", ":", "meme", "=", "ctx", ".", "message", ".", "content", "[", "7", ":", "]", "if", "len", "(", "meme", ")", ">", "107", ":", "await", "ctx", ".", "send", "(", "\"Menssagem muito grande\"", ")", "return", "fundo", "=", "Image", ".", "open", "(", "'img/mesmes/trump.jpg'", ")", "Fonte", "=", "ImageFont", ".", "truetype", "(", "'fonts/uni-sans.heavy-caps.otf'", ",", "90", ")", "escreve", "=", "ImageDraw", ".", "Draw", "(", "fundo", ")", "a1", ",", "r", ",", "ter", "=", "1", ",", "1", ",", "len", "(", "meme", ")", "+", "1", "# nosso \"paginador\"", "itens_por_linha", "=", "20", "ends", "=", "[", "''", "]", "*", "(", "itens_por_linha", "-", "1", ")", "ends", ".", "append", "(", "'\\n'", ")", "a", "=", "0", "eixo_x", "=", "740", "eixo_y", "=", "570", "quebra", "=", "1", "for", "item", ",", "end", "in", "zip", "(", "range", "(", "a1", ",", "r", "*", "ter", ",", "r", ")", ",", "cycle", "(", "ends", ")", ")", ":", "#print(\"i\", end=end)", "#print(meme[item], end=end)", "if", "quebra", "==", "20", ":", "quebra", "=", "1", "eixo_y", "+=", "100", "eixo_x", "=", "740", "#print(meme[a],end=end)", "escreve", ".", "text", "(", "xy", "=", "(", "eixo_x", ",", "eixo_y", ")", ",", "text", "=", "meme", "[", "a", "]", ",", "end", "=", "end", ",", "fill", "=", "(", "13", ",", "13", ",", "13", ")", ",", "font", "=", "Fonte", ")", "eixo_x", "+=", "50", "a", "+=", "1", "quebra", "+=", "1", "fundo", ".", "save", "(", "'img/mesmes/trump_1.png'", ")", "info_png", "=", "discord", ".", "File", "(", "'img/mesmes/trump_1.png'", ")", "await", "ctx", ".", "send", "(", "file", "=", "info_png", ")", "self", ".", "client", ".", "counter", "+=", "1" ]
[ 16, 4 ]
[ 49, 32 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
CampanhaManager.listar_campanhas
(self)
return Campanha.objects.filter(ativa=True)
Listagem de Campanhas ativas
Listagem de Campanhas ativas
def listar_campanhas(self): "Listagem de Campanhas ativas" return Campanha.objects.filter(ativa=True)
[ "def", "listar_campanhas", "(", "self", ")", ":", "return", "Campanha", ".", "objects", ".", "filter", "(", "ativa", "=", "True", ")" ]
[ 8, 4 ]
[ 10, 50 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
ClassificadorWrapper.cross_validation
(self, X, y, numCv:int, metrics:list,doGridSearch=False)
return metric_vec
Função para realizar o cross validation no data set Parâmetros: X:dataframe['tweets'] y:target numCv: # de folds metrics: metricas a serem coletadas doGridSearch: boolean se True faz gridsearch return: list de metricas na mesma ordem passada no parametro metrics
Função para realizar o cross validation no data set Parâmetros: X:dataframe['tweets'] y:target numCv: # de folds metrics: metricas a serem coletadas doGridSearch: boolean se True faz gridsearch return: list de metricas na mesma ordem passada no parametro metrics
def cross_validation(self, X, y, numCv:int, metrics:list,doGridSearch=False): '''Função para realizar o cross validation no data set Parâmetros: X:dataframe['tweets'] y:target numCv: # de folds metrics: metricas a serem coletadas doGridSearch: boolean se True faz gridsearch return: list de metricas na mesma ordem passada no parametro metrics ''' model = self.classificador if doGridSearch: print("Doing greadsearch {}".format(self.name)) model = self.getBestModel(X, y) metric_vec = [] scores = cross_validate(model, X, y, cv=numCv,scoring=metrics,return_train_score=False,error_score=0) for i, score in enumerate(metrics): metric_vec.append(round(np.mean(scores['test_{}'.format(score)]) * 100, 2)) print("{}: {}".format(score, round(np.mean(scores['test_{}'.format(score)]) * 100, 2))) return metric_vec
[ "def", "cross_validation", "(", "self", ",", "X", ",", "y", ",", "numCv", ":", "int", ",", "metrics", ":", "list", ",", "doGridSearch", "=", "False", ")", ":", "model", "=", "self", ".", "classificador", "if", "doGridSearch", ":", "print", "(", "\"Doing greadsearch {}\"", ".", "format", "(", "self", ".", "name", ")", ")", "model", "=", "self", ".", "getBestModel", "(", "X", ",", "y", ")", "metric_vec", "=", "[", "]", "scores", "=", "cross_validate", "(", "model", ",", "X", ",", "y", ",", "cv", "=", "numCv", ",", "scoring", "=", "metrics", ",", "return_train_score", "=", "False", ",", "error_score", "=", "0", ")", "for", "i", ",", "score", "in", "enumerate", "(", "metrics", ")", ":", "metric_vec", ".", "append", "(", "round", "(", "np", ".", "mean", "(", "scores", "[", "'test_{}'", ".", "format", "(", "score", ")", "]", ")", "*", "100", ",", "2", ")", ")", "print", "(", "\"{}: {}\"", ".", "format", "(", "score", ",", "round", "(", "np", ".", "mean", "(", "scores", "[", "'test_{}'", ".", "format", "(", "score", ")", "]", ")", "*", "100", ",", "2", ")", ")", ")", "return", "metric_vec" ]
[ 15, 4 ]
[ 37, 25 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Factor.pointwise_product
(self, other, bn)
return Factor(variables, cpt)
Multiplique dois fatores, combinando suas variáveis.
Multiplique dois fatores, combinando suas variáveis.
def pointwise_product(self, other, bn): "Multiplique dois fatores, combinando suas variáveis." variables = list(set(self.variables) | set(other.variables)) cpt = { event_values(e, variables): self.p(e) * other.p(e) for e in all_events(variables, bn, {}) } return Factor(variables, cpt)
[ "def", "pointwise_product", "(", "self", ",", "other", ",", "bn", ")", ":", "variables", "=", "list", "(", "set", "(", "self", ".", "variables", ")", "|", "set", "(", "other", ".", "variables", ")", ")", "cpt", "=", "{", "event_values", "(", "e", ",", "variables", ")", ":", "self", ".", "p", "(", "e", ")", "*", "other", ".", "p", "(", "e", ")", "for", "e", "in", "all_events", "(", "variables", ",", "bn", ",", "{", "}", ")", "}", "return", "Factor", "(", "variables", ",", "cpt", ")" ]
[ 360, 4 ]
[ 367, 37 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
favorite_book
(title, autor)
Exibe uma mensagem simples informando sobre o título do meu livro favorito.
Exibe uma mensagem simples informando sobre o título do meu livro favorito.
def favorite_book(title, autor): """Exibe uma mensagem simples informando sobre o título do meu livro favorito.""" print(f'\nUm dos meus livros favoritos é intitulado como {title.title()}, do(a) autor(a) {autor.title()}.\n')
[ "def", "favorite_book", "(", "title", ",", "autor", ")", ":", "print", "(", "f'\\nUm dos meus livros favoritos é intitulado como {title.title()}, do(a) autor(a) {autor.title()}.\\n')", "" ]
[ 4, 0 ]
[ 6, 114 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
update_start
(screen, background_start)
Inicia o jogo com uma tela amigavél
Inicia o jogo com uma tela amigavél
def update_start(screen, background_start): """Inicia o jogo com uma tela amigavél""" screen.blit(background_start, (0, 0)) # Atualiza a tela pygame.display.flip()
[ "def", "update_start", "(", "screen", ",", "background_start", ")", ":", "screen", ".", "blit", "(", "background_start", ",", "(", "0", ",", "0", ")", ")", "# Atualiza a tela", "pygame", ".", "display", ".", "flip", "(", ")" ]
[ 106, 0 ]
[ 110, 25 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
IceCreamStand.__init__
(self, name, cuisine)
Inicializa os atributos da classe Pai - Restaurant. Em seguida inicia os atributos de IceCreamStand.
Inicializa os atributos da classe Pai - Restaurant. Em seguida inicia os atributos de IceCreamStand.
def __init__(self, name, cuisine): """Inicializa os atributos da classe Pai - Restaurant. Em seguida inicia os atributos de IceCreamStand.""" super().__init__(name, cuisine) self.flavors = 'flavors'
[ "def", "__init__", "(", "self", ",", "name", ",", "cuisine", ")", ":", "super", "(", ")", ".", "__init__", "(", "name", ",", "cuisine", ")", "self", ".", "flavors", "=", "'flavors'" ]
[ 33, 4 ]
[ 38, 32 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Main.mostrar_bau
(self)
Mostra todos os brinquedos do baú. Tipos diferentes: ordem decrescente, por felicidade. Mesmo tipo: ordem crescente, por durabilidade.
Mostra todos os brinquedos do baú. Tipos diferentes: ordem decrescente, por felicidade. Mesmo tipo: ordem crescente, por durabilidade.
def mostrar_bau(self): """Mostra todos os brinquedos do baú. Tipos diferentes: ordem decrescente, por felicidade. Mesmo tipo: ordem crescente, por durabilidade.""" cfunc.mudar_titulo('Baú') janela = cjane.JanelaTable({'Nome': 32, 'Felicidade': 22, 'Usos restantes': 22}) for brinquedo in self.bau.brinquedosort(): for brinqs in sorted(self.bau[brinquedo.nome]): brinq = [brinqs.nome, brinqs.feliz, brinqs.dura] janela.add_linha(brinq) janela.mostrar_janela()
[ "def", "mostrar_bau", "(", "self", ")", ":", "cfunc", ".", "mudar_titulo", "(", "'Baú')", "", "janela", "=", "cjane", ".", "JanelaTable", "(", "{", "'Nome'", ":", "32", ",", "'Felicidade'", ":", "22", ",", "'Usos restantes'", ":", "22", "}", ")", "for", "brinquedo", "in", "self", ".", "bau", ".", "brinquedosort", "(", ")", ":", "for", "brinqs", "in", "sorted", "(", "self", ".", "bau", "[", "brinquedo", ".", "nome", "]", ")", ":", "brinq", "=", "[", "brinqs", ".", "nome", ",", "brinqs", ".", "feliz", ",", "brinqs", ".", "dura", "]", "janela", ".", "add_linha", "(", "brinq", ")", "janela", ".", "mostrar_janela", "(", ")" ]
[ 338, 4 ]
[ 352, 31 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
validar_entrada
(string)
return len(string) == 1
Recebe uma string e retorna True se ela tiver 1 caractere.
Recebe uma string e retorna True se ela tiver 1 caractere.
def validar_entrada(string): """Recebe uma string e retorna True se ela tiver 1 caractere.""" return len(string) == 1
[ "def", "validar_entrada", "(", "string", ")", ":", "return", "len", "(", "string", ")", "==", "1" ]
[ 10, 0 ]
[ 12, 27 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
DireitoGrupoEquipamentoResource.handle_get
(self, request, user, *args, **kwargs)
Trata as requisições de GET para listar os direitos de grupo de usuários em grupo de equipamentos. URLs: direitosgrupoequipamento/$ direitosgrupoequipamento/ugrupo/<id_grupo_usuario>/$ direitosgrupoequipamento/egrupo/<id_grupo_equipamento>/$ direitosgrupoequipamento/<id_direito>/$
Trata as requisições de GET para listar os direitos de grupo de usuários em grupo de equipamentos.
def handle_get(self, request, user, *args, **kwargs): """Trata as requisições de GET para listar os direitos de grupo de usuários em grupo de equipamentos. URLs: direitosgrupoequipamento/$ direitosgrupoequipamento/ugrupo/<id_grupo_usuario>/$ direitosgrupoequipamento/egrupo/<id_grupo_equipamento>/$ direitosgrupoequipamento/<id_direito>/$ """ try: if not has_perm(user, AdminPermission.USER_ADMINISTRATION, AdminPermission.READ_OPERATION): return self.not_authorized() map_list = [] right_id = kwargs.get('id_direito') if not is_valid_int_greater_zero_param(right_id, False): self.log.error( u'The right_id parameter is not a valid value: %s.', right_id) raise InvalidValueError(None, 'right_id', right_id) if right_id is not None: map_list.append( self.__get_direito_map(DireitosGrupoEquipamento.get_by_pk(right_id))) else: ugroup = kwargs.get('id_grupo_usuario') egroup = kwargs.get('id_grupo_equipamento') if not is_valid_int_greater_zero_param(ugroup, False): self.log.error( u'The ugroup_id parameter is not a valid value: %s.', ugroup) raise InvalidValueError(None, 'ugroup_id', ugroup) if not is_valid_int_greater_zero_param(egroup, False): self.log.error( u'The egroup_id parameter is not a valid value: %s.', egroup) raise InvalidValueError(None, 'egroup_id', egroup) if ugroup is not None: UGrupo.get_by_pk(ugroup) if egroup is not None: EGrupo.get_by_pk(egroup) rights = DireitosGrupoEquipamento.search(ugroup, None, egroup) for right in rights: map_list.append(self.__get_direito_map(right)) return self.response(dumps_networkapi({'direito_grupo_equipamento': map_list})) except InvalidValueError, e: return self.response_error(269, e.param, e.value) except DireitosGrupoEquipamento.DoesNotExist: return self.response_error(258, right_id) except EGrupoNotFoundError: return self.response_error(102) except UGrupoNotFoundError: return self.response_error(180, ugroup) except (GrupoError): return self.response_error(1)
[ "def", "handle_get", "(", "self", ",", "request", ",", "user", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "if", "not", "has_perm", "(", "user", ",", "AdminPermission", ".", "USER_ADMINISTRATION", ",", "AdminPermission", ".", "READ_OPERATION", ")", ":", "return", "self", ".", "not_authorized", "(", ")", "map_list", "=", "[", "]", "right_id", "=", "kwargs", ".", "get", "(", "'id_direito'", ")", "if", "not", "is_valid_int_greater_zero_param", "(", "right_id", ",", "False", ")", ":", "self", ".", "log", ".", "error", "(", "u'The right_id parameter is not a valid value: %s.'", ",", "right_id", ")", "raise", "InvalidValueError", "(", "None", ",", "'right_id'", ",", "right_id", ")", "if", "right_id", "is", "not", "None", ":", "map_list", ".", "append", "(", "self", ".", "__get_direito_map", "(", "DireitosGrupoEquipamento", ".", "get_by_pk", "(", "right_id", ")", ")", ")", "else", ":", "ugroup", "=", "kwargs", ".", "get", "(", "'id_grupo_usuario'", ")", "egroup", "=", "kwargs", ".", "get", "(", "'id_grupo_equipamento'", ")", "if", "not", "is_valid_int_greater_zero_param", "(", "ugroup", ",", "False", ")", ":", "self", ".", "log", ".", "error", "(", "u'The ugroup_id parameter is not a valid value: %s.'", ",", "ugroup", ")", "raise", "InvalidValueError", "(", "None", ",", "'ugroup_id'", ",", "ugroup", ")", "if", "not", "is_valid_int_greater_zero_param", "(", "egroup", ",", "False", ")", ":", "self", ".", "log", ".", "error", "(", "u'The egroup_id parameter is not a valid value: %s.'", ",", "egroup", ")", "raise", "InvalidValueError", "(", "None", ",", "'egroup_id'", ",", "egroup", ")", "if", "ugroup", "is", "not", "None", ":", "UGrupo", ".", "get_by_pk", "(", "ugroup", ")", "if", "egroup", "is", "not", "None", ":", "EGrupo", ".", "get_by_pk", "(", "egroup", ")", "rights", "=", "DireitosGrupoEquipamento", ".", "search", "(", "ugroup", ",", "None", ",", "egroup", ")", "for", "right", "in", "rights", ":", "map_list", ".", "append", "(", "self", ".", "__get_direito_map", "(", "right", ")", ")", "return", "self", ".", "response", "(", "dumps_networkapi", "(", "{", "'direito_grupo_equipamento'", ":", "map_list", "}", ")", ")", "except", "InvalidValueError", ",", "e", ":", "return", "self", ".", "response_error", "(", "269", ",", "e", ".", "param", ",", "e", ".", "value", ")", "except", "DireitosGrupoEquipamento", ".", "DoesNotExist", ":", "return", "self", ".", "response_error", "(", "258", ",", "right_id", ")", "except", "EGrupoNotFoundError", ":", "return", "self", ".", "response_error", "(", "102", ")", "except", "UGrupoNotFoundError", ":", "return", "self", ".", "response_error", "(", "180", ",", "ugroup", ")", "except", "(", "GrupoError", ")", ":", "return", "self", ".", "response_error", "(", "1", ")" ]
[ 211, 4 ]
[ 271, 41 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Classroom.plot_pente_pdde
(self, Estagios, Cenarios, Aberturas, SeqForw, Nome_Arq)
Gera um pdf com estágios e aberturas. Keyword arguments: Estagios -- Especifique a profundidade da árvore, ou seja, quantas camadas terá a árvore Cenarios -- Especifique o número cenarios a serem considerados Aberturas -- Especifique o número de aberturas SeqForw -- Especifique o número de sequências forward Nome_Arq -- Especifique o Nome do arquivo de saída
Gera um pdf com estágios e aberturas.
def plot_pente_pdde(self, Estagios, Cenarios, Aberturas, SeqForw, Nome_Arq): """Gera um pdf com estágios e aberturas. Keyword arguments: Estagios -- Especifique a profundidade da árvore, ou seja, quantas camadas terá a árvore Cenarios -- Especifique o número cenarios a serem considerados Aberturas -- Especifique o número de aberturas SeqForw -- Especifique o número de sequências forward Nome_Arq -- Especifique o Nome do arquivo de saída """ if Cenarios > self.sistema["DGer"]["Nr_Cen"]: print ("Número de Cenários Menor que Número de Aberturas") print ("Método plot_pente_pdde interrompido!") return if Estagios > self.sistema["DGer"]["Nr_Est"]: print ("Número de Estágios Superior aos dados informados no problema.") print("Método plot_pente_pdde interrompido!") return if Aberturas > Cenarios: print ("Número de Aberturas Superior ao número de Cenários.") print("Método plot_pente_pdde interrompido!") return Ordem = 0 lista = [] random.seed(30) for iest in range(Estagios): escolhidos = random.sample(range(Cenarios), Aberturas) for icen in range(Cenarios): valida = False for procura in escolhidos: if procura == icen: valida = True elemento = { "Estagio": iest, "Afluencia": self.sistema["UHE"][0]["Afl"][iest][icen], "Ordem": Ordem, "Abertura": valida } lista.append(elemento) Ordem += 1 # # Cria Grafo # g = Digraph('G', filename=Nome_Arq, strict=True) # # Cria nós do grafo com nome e label # for elemento in lista: if elemento["Abertura"]: g.node(str(elemento["Ordem"]),label= " Afl: "+ str(elemento["Afluencia"]), color="red", fillcolor="red", style="filled") else: g.node(str(elemento["Ordem"]),label= " Afl: "+ str(elemento["Afluencia"])) # # Cria arestas do grafo ( o label é a probabilidade # probabilidade = 100 / Cenarios for elemento in lista: if (elemento["Estagio"] != 0): for candidato in lista: if candidato["Estagio"] == elemento["Estagio"]-1: g.edge(str(candidato["Ordem"]), str(elemento["Ordem"])) # label=str(round(probabilidade,2))+'%') Cor = 'red' for iest in range(Estagios): if (iest%2) == 0: Preenche = 'green:cyan' else: Preenche = 'lightblue:cyan' # # Cria um cluster para cada estágio # with g.subgraph(name='cluster'+str(iest+1)) as c: # # Define parâmetros do cluster # c.attr(fillcolor=Preenche, label='Estágio '+str(iest+1), fontcolor=Cor, style='filled', gradientangle='270') c.attr('node', shape='box', fillcolor='red:yellow', style='filled', gradientangle='90') # # Joga para dentro do cluster todos os nós do estágio iest # for elemento in lista: if elemento["Estagio"]==iest: c.node(str(elemento["Ordem"])) g.attr("graph",pad="0.5", nodesep="1", ranksep="2") g.view() # # Cria Pente # pente = Digraph('Pente', filename=Nome_Arq+"Pente") for iest in range(Estagios): for ifwd in range(SeqForw): codigo = iest*SeqForw+ifwd if ifwd%2 == 1: Cor = "red" else: Cor = "green" pente.node(str(codigo),label= " Afl: " + str(codigo), color=Cor, fillcolor=Cor, style="filled") if iest >= 1: pente.edge(str((iest-1)*SeqForw+ifwd), str(iest*SeqForw+ifwd), color= Cor) Cor = 'red' for iest in range(Estagios): if (iest%2) == 0: Preenche = 'gray:cyan' else: Preenche = 'gray:cyan' # # Cria um cluster para cada estágio # with pente.subgraph(name='cluster'+str(iest+1)) as c: # # Define parâmetros do cluster # c.attr(fillcolor=Preenche, label='Estágio '+str(iest+1), fontcolor=Cor, style='filled', gradientangle='270') c.attr('node', shape='box', fillcolor='red:yellow', style='filled', gradientangle='90') # # Joga para dentro do cluster todos os nós do estágio iest # for ifwd in range(SeqForw): c.node(str(iest*SeqForw+ifwd)) h = deepcopy(g) for copia in range(SeqForw): g = deepcopy(h) g.filename = g.filename + '_' + str(copia) iest = Estagios - 1 no = random.randint(0,Aberturas-1) conta = 0 for elemento_front in lista: if elemento_front["Estagio"] == iest and elemento_front["Abertura"]: if conta == no: break else: conta += 1 pente.node(str(iest*SeqForw+copia),label="Afl: " + str(elemento_front["Afluencia"])) while iest > 0: iest -= 1 no = random.randint(0,Aberturas-1) conta = 0 for elemento_back in lista: if elemento_back["Estagio"] == iest and elemento_back["Abertura"]: if conta == no: break else: conta += 1 g.edge(str(elemento_back["Ordem"]), str(elemento_front["Ordem"]), color='red', penwidth='2.0') elemento_front = elemento_back pente.node(str(iest*SeqForw+copia),label="Afl: " + str(elemento_front["Afluencia"])) g.view() pente.view()
[ "def", "plot_pente_pdde", "(", "self", ",", "Estagios", ",", "Cenarios", ",", "Aberturas", ",", "SeqForw", ",", "Nome_Arq", ")", ":", "if", "Cenarios", ">", "self", ".", "sistema", "[", "\"DGer\"", "]", "[", "\"Nr_Cen\"", "]", ":", "print", "(", "\"Número de Cenários Menor que Número de Aberturas\")", "", "print", "(", "\"Método plot_pente_pdde interrompido!\")", "", "return", "if", "Estagios", ">", "self", ".", "sistema", "[", "\"DGer\"", "]", "[", "\"Nr_Est\"", "]", ":", "print", "(", "\"Número de Estágios Superior aos dados informados no problema.\")", "", "print", "(", "\"Método plot_pente_pdde interrompido!\")", "", "return", "if", "Aberturas", ">", "Cenarios", ":", "print", "(", "\"Número de Aberturas Superior ao número de Cenários.\")", "", "print", "(", "\"Método plot_pente_pdde interrompido!\")", "", "return", "Ordem", "=", "0", "lista", "=", "[", "]", "random", ".", "seed", "(", "30", ")", "for", "iest", "in", "range", "(", "Estagios", ")", ":", "escolhidos", "=", "random", ".", "sample", "(", "range", "(", "Cenarios", ")", ",", "Aberturas", ")", "for", "icen", "in", "range", "(", "Cenarios", ")", ":", "valida", "=", "False", "for", "procura", "in", "escolhidos", ":", "if", "procura", "==", "icen", ":", "valida", "=", "True", "elemento", "=", "{", "\"Estagio\"", ":", "iest", ",", "\"Afluencia\"", ":", "self", ".", "sistema", "[", "\"UHE\"", "]", "[", "0", "]", "[", "\"Afl\"", "]", "[", "iest", "]", "[", "icen", "]", ",", "\"Ordem\"", ":", "Ordem", ",", "\"Abertura\"", ":", "valida", "}", "lista", ".", "append", "(", "elemento", ")", "Ordem", "+=", "1", "#", "# Cria Grafo", "#", "g", "=", "Digraph", "(", "'G'", ",", "filename", "=", "Nome_Arq", ",", "strict", "=", "True", ")", "#", "# Cria nós do grafo com nome e label", "#", "for", "elemento", "in", "lista", ":", "if", "elemento", "[", "\"Abertura\"", "]", ":", "g", ".", "node", "(", "str", "(", "elemento", "[", "\"Ordem\"", "]", ")", ",", "label", "=", "\" Afl: \"", "+", "str", "(", "elemento", "[", "\"Afluencia\"", "]", ")", ",", "color", "=", "\"red\"", ",", "fillcolor", "=", "\"red\"", ",", "style", "=", "\"filled\"", ")", "else", ":", "g", ".", "node", "(", "str", "(", "elemento", "[", "\"Ordem\"", "]", ")", ",", "label", "=", "\" Afl: \"", "+", "str", "(", "elemento", "[", "\"Afluencia\"", "]", ")", ")", "#", "# Cria arestas do grafo ( o label é a probabilidade", "#", "probabilidade", "=", "100", "/", "Cenarios", "for", "elemento", "in", "lista", ":", "if", "(", "elemento", "[", "\"Estagio\"", "]", "!=", "0", ")", ":", "for", "candidato", "in", "lista", ":", "if", "candidato", "[", "\"Estagio\"", "]", "==", "elemento", "[", "\"Estagio\"", "]", "-", "1", ":", "g", ".", "edge", "(", "str", "(", "candidato", "[", "\"Ordem\"", "]", ")", ",", "str", "(", "elemento", "[", "\"Ordem\"", "]", ")", ")", "# label=str(round(probabilidade,2))+'%')", "Cor", "=", "'red'", "for", "iest", "in", "range", "(", "Estagios", ")", ":", "if", "(", "iest", "%", "2", ")", "==", "0", ":", "Preenche", "=", "'green:cyan'", "else", ":", "Preenche", "=", "'lightblue:cyan'", "#", "# Cria um cluster para cada estágio", "#", "with", "g", ".", "subgraph", "(", "name", "=", "'cluster'", "+", "str", "(", "iest", "+", "1", ")", ")", "as", "c", ":", "#", "# Define parâmetros do cluster", "#", "c", ".", "attr", "(", "fillcolor", "=", "Preenche", ",", "label", "=", "'Estágio '+", "s", "tr(", "i", "est+", "1", ")", ",", "", "fontcolor", "=", "Cor", ",", "style", "=", "'filled'", ",", "gradientangle", "=", "'270'", ")", "c", ".", "attr", "(", "'node'", ",", "shape", "=", "'box'", ",", "fillcolor", "=", "'red:yellow'", ",", "style", "=", "'filled'", ",", "gradientangle", "=", "'90'", ")", "#", "# Joga para dentro do cluster todos os nós do estágio iest", "#", "for", "elemento", "in", "lista", ":", "if", "elemento", "[", "\"Estagio\"", "]", "==", "iest", ":", "c", ".", "node", "(", "str", "(", "elemento", "[", "\"Ordem\"", "]", ")", ")", "g", ".", "attr", "(", "\"graph\"", ",", "pad", "=", "\"0.5\"", ",", "nodesep", "=", "\"1\"", ",", "ranksep", "=", "\"2\"", ")", "g", ".", "view", "(", ")", "#", "# Cria Pente", "#", "pente", "=", "Digraph", "(", "'Pente'", ",", "filename", "=", "Nome_Arq", "+", "\"Pente\"", ")", "for", "iest", "in", "range", "(", "Estagios", ")", ":", "for", "ifwd", "in", "range", "(", "SeqForw", ")", ":", "codigo", "=", "iest", "*", "SeqForw", "+", "ifwd", "if", "ifwd", "%", "2", "==", "1", ":", "Cor", "=", "\"red\"", "else", ":", "Cor", "=", "\"green\"", "pente", ".", "node", "(", "str", "(", "codigo", ")", ",", "label", "=", "\" Afl: \"", "+", "str", "(", "codigo", ")", ",", "color", "=", "Cor", ",", "fillcolor", "=", "Cor", ",", "style", "=", "\"filled\"", ")", "if", "iest", ">=", "1", ":", "pente", ".", "edge", "(", "str", "(", "(", "iest", "-", "1", ")", "*", "SeqForw", "+", "ifwd", ")", ",", "str", "(", "iest", "*", "SeqForw", "+", "ifwd", ")", ",", "color", "=", "Cor", ")", "Cor", "=", "'red'", "for", "iest", "in", "range", "(", "Estagios", ")", ":", "if", "(", "iest", "%", "2", ")", "==", "0", ":", "Preenche", "=", "'gray:cyan'", "else", ":", "Preenche", "=", "'gray:cyan'", "#", "# Cria um cluster para cada estágio", "#", "with", "pente", ".", "subgraph", "(", "name", "=", "'cluster'", "+", "str", "(", "iest", "+", "1", ")", ")", "as", "c", ":", "#", "# Define parâmetros do cluster", "#", "c", ".", "attr", "(", "fillcolor", "=", "Preenche", ",", "label", "=", "'Estágio '+", "s", "tr(", "i", "est+", "1", ")", ",", "", "fontcolor", "=", "Cor", ",", "style", "=", "'filled'", ",", "gradientangle", "=", "'270'", ")", "c", ".", "attr", "(", "'node'", ",", "shape", "=", "'box'", ",", "fillcolor", "=", "'red:yellow'", ",", "style", "=", "'filled'", ",", "gradientangle", "=", "'90'", ")", "#", "# Joga para dentro do cluster todos os nós do estágio iest", "#", "for", "ifwd", "in", "range", "(", "SeqForw", ")", ":", "c", ".", "node", "(", "str", "(", "iest", "*", "SeqForw", "+", "ifwd", ")", ")", "h", "=", "deepcopy", "(", "g", ")", "for", "copia", "in", "range", "(", "SeqForw", ")", ":", "g", "=", "deepcopy", "(", "h", ")", "g", ".", "filename", "=", "g", ".", "filename", "+", "'_'", "+", "str", "(", "copia", ")", "iest", "=", "Estagios", "-", "1", "no", "=", "random", ".", "randint", "(", "0", ",", "Aberturas", "-", "1", ")", "conta", "=", "0", "for", "elemento_front", "in", "lista", ":", "if", "elemento_front", "[", "\"Estagio\"", "]", "==", "iest", "and", "elemento_front", "[", "\"Abertura\"", "]", ":", "if", "conta", "==", "no", ":", "break", "else", ":", "conta", "+=", "1", "pente", ".", "node", "(", "str", "(", "iest", "*", "SeqForw", "+", "copia", ")", ",", "label", "=", "\"Afl: \"", "+", "str", "(", "elemento_front", "[", "\"Afluencia\"", "]", ")", ")", "while", "iest", ">", "0", ":", "iest", "-=", "1", "no", "=", "random", ".", "randint", "(", "0", ",", "Aberturas", "-", "1", ")", "conta", "=", "0", "for", "elemento_back", "in", "lista", ":", "if", "elemento_back", "[", "\"Estagio\"", "]", "==", "iest", "and", "elemento_back", "[", "\"Abertura\"", "]", ":", "if", "conta", "==", "no", ":", "break", "else", ":", "conta", "+=", "1", "g", ".", "edge", "(", "str", "(", "elemento_back", "[", "\"Ordem\"", "]", ")", ",", "str", "(", "elemento_front", "[", "\"Ordem\"", "]", ")", ",", "color", "=", "'red'", ",", "penwidth", "=", "'2.0'", ")", "elemento_front", "=", "elemento_back", "pente", ".", "node", "(", "str", "(", "iest", "*", "SeqForw", "+", "copia", ")", ",", "label", "=", "\"Afl: \"", "+", "str", "(", "elemento_front", "[", "\"Afluencia\"", "]", ")", ")", "g", ".", "view", "(", ")", "pente", ".", "view", "(", ")" ]
[ 2303, 4 ]
[ 2506, 20 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
turn
(direction, steps)
return (direction + steps) % len(DELTA)
Retorna a nova direção.
Retorna a nova direção.
def turn(direction, steps): """Retorna a nova direção.""" return (direction + steps) % len(DELTA)
[ "def", "turn", "(", "direction", ",", "steps", ")", ":", "return", "(", "direction", "+", "steps", ")", "%", "len", "(", "DELTA", ")" ]
[ 46, 0 ]
[ 50, 41 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
CRC16.__init__
(self, data=b'')
data: contém os dados para calcular o FCS. Armazena esses dados em um bufer interno. Deve ser um objeto str, bytes ou bytearray
data: contém os dados para calcular o FCS. Armazena esses dados em um bufer interno. Deve ser um objeto str, bytes ou bytearray
def __init__(self, data=b''): '''data: contém os dados para calcular o FCS. Armazena esses dados em um bufer interno. Deve ser um objeto str, bytes ou bytearray''' self.data = self.__convert__(data)
[ "def", "__init__", "(", "self", ",", "data", "=", "b''", ")", ":", "self", ".", "data", "=", "self", ".", "__convert__", "(", "data", ")" ]
[ 44, 2 ]
[ 48, 38 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Equipamento.delete
(self)
Sobrescreve o metodo do Django para remover um equipamento. Antes de remover o equipamento remove todos os seus relacionamentos.
Sobrescreve o metodo do Django para remover um equipamento.
def delete(self): """Sobrescreve o metodo do Django para remover um equipamento. Antes de remover o equipamento remove todos os seus relacionamentos. """ from networkapi.ip.models import IpCantBeRemovedFromVip is_error = False ipv4_error = '' ipv6_error = '' for ip_equipment in self.ipequipamento_set.all(): try: ip = ip_equipment.ip ip_equipment.delete() except Exception as e: is_error = True ipv4_error += ' %s.%s.%s.%s - Vip %s ,' % ( ip.oct1, ip.oct2, ip.oct3, ip.oct4, e.cause) for ip_v6_equipment in self.ipv6equipament_set.all(): try: ip = ip_v6_equipment.ip ip_v6_equipment.delete() except Exception as e: is_error = True ipv6_error += ' %s:%s:%s:%s:%s:%s:%s:%s - Vip %s ,' % ( ip.block1, ip.block2, ip.block3, ip.block4, ip.block5, ip.block6, ip.block7, ip.block8, e.cause) if is_error: raise IpCantBeRemovedFromVip(ipv4_error, ipv6_error) for equipment_access in self.equipamentoacesso_set.all(): equipment_access.delete() for equipment_script in self.equipamentoroteiro_set.all(): equipment_script.delete() for interface in self.interface_set.all(): interface.delete() for equipment_environment in self.equipamentoambiente_set.all(): equipment_environment.delete() for equipment_group in self.equipamentogrupo_set.all(): equipment_group.delete() super(Equipamento, self).delete()
[ "def", "delete", "(", "self", ")", ":", "from", "networkapi", ".", "ip", ".", "models", "import", "IpCantBeRemovedFromVip", "is_error", "=", "False", "ipv4_error", "=", "''", "ipv6_error", "=", "''", "for", "ip_equipment", "in", "self", ".", "ipequipamento_set", ".", "all", "(", ")", ":", "try", ":", "ip", "=", "ip_equipment", ".", "ip", "ip_equipment", ".", "delete", "(", ")", "except", "Exception", "as", "e", ":", "is_error", "=", "True", "ipv4_error", "+=", "' %s.%s.%s.%s - Vip %s ,'", "%", "(", "ip", ".", "oct1", ",", "ip", ".", "oct2", ",", "ip", ".", "oct3", ",", "ip", ".", "oct4", ",", "e", ".", "cause", ")", "for", "ip_v6_equipment", "in", "self", ".", "ipv6equipament_set", ".", "all", "(", ")", ":", "try", ":", "ip", "=", "ip_v6_equipment", ".", "ip", "ip_v6_equipment", ".", "delete", "(", ")", "except", "Exception", "as", "e", ":", "is_error", "=", "True", "ipv6_error", "+=", "' %s:%s:%s:%s:%s:%s:%s:%s - Vip %s ,'", "%", "(", "ip", ".", "block1", ",", "ip", ".", "block2", ",", "ip", ".", "block3", ",", "ip", ".", "block4", ",", "ip", ".", "block5", ",", "ip", ".", "block6", ",", "ip", ".", "block7", ",", "ip", ".", "block8", ",", "e", ".", "cause", ")", "if", "is_error", ":", "raise", "IpCantBeRemovedFromVip", "(", "ipv4_error", ",", "ipv6_error", ")", "for", "equipment_access", "in", "self", ".", "equipamentoacesso_set", ".", "all", "(", ")", ":", "equipment_access", ".", "delete", "(", ")", "for", "equipment_script", "in", "self", ".", "equipamentoroteiro_set", ".", "all", "(", ")", ":", "equipment_script", ".", "delete", "(", ")", "for", "interface", "in", "self", ".", "interface_set", ".", "all", "(", ")", ":", "interface", ".", "delete", "(", ")", "for", "equipment_environment", "in", "self", ".", "equipamentoambiente_set", ".", "all", "(", ")", ":", "equipment_environment", ".", "delete", "(", ")", "for", "equipment_group", "in", "self", ".", "equipamentogrupo_set", ".", "all", "(", ")", ":", "equipment_group", ".", "delete", "(", ")", "super", "(", "Equipamento", ",", "self", ")", ".", "delete", "(", ")" ]
[ 740, 4 ]
[ 788, 41 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
p_chamada_funcao
(p)
chamada_funcao : ID ABRE_PARENTESE lista_argumentos FECHA_PARENTESE
chamada_funcao : ID ABRE_PARENTESE lista_argumentos FECHA_PARENTESE
def p_chamada_funcao(p): """chamada_funcao : ID ABRE_PARENTESE lista_argumentos FECHA_PARENTESE""" pai = MyNode(name='chamada_funcao', type='CHAMADA_FUNCAO') p[0] = pai if len(p) > 2: filho1 = MyNode(name='ID', type='ID', parent=pai) filho_id = MyNode(name=p[1], type='ID', parent=filho1) p[1] = filho1 filho2 = MyNode(name='ABRE_PARENTESE', type='ABRE_PARENTESE', parent=pai) filho_sym = MyNode(name=p[2], type='SIMBOLO', parent=filho2) p[2] = filho2 p[3].parent = pai filho4 = MyNode(name='FECHA_PARENTESE', type='FECHA_PARENTESE', parent=pai) filho_sym = MyNode(name=p[4], type='SIMBOLO', parent=filho4) p[4] = filho4 else: p[1].parent = pai
[ "def", "p_chamada_funcao", "(", "p", ")", ":", "pai", "=", "MyNode", "(", "name", "=", "'chamada_funcao'", ",", "type", "=", "'CHAMADA_FUNCAO'", ")", "p", "[", "0", "]", "=", "pai", "if", "len", "(", "p", ")", ">", "2", ":", "filho1", "=", "MyNode", "(", "name", "=", "'ID'", ",", "type", "=", "'ID'", ",", "parent", "=", "pai", ")", "filho_id", "=", "MyNode", "(", "name", "=", "p", "[", "1", "]", ",", "type", "=", "'ID'", ",", "parent", "=", "filho1", ")", "p", "[", "1", "]", "=", "filho1", "filho2", "=", "MyNode", "(", "name", "=", "'ABRE_PARENTESE'", ",", "type", "=", "'ABRE_PARENTESE'", ",", "parent", "=", "pai", ")", "filho_sym", "=", "MyNode", "(", "name", "=", "p", "[", "2", "]", ",", "type", "=", "'SIMBOLO'", ",", "parent", "=", "filho2", ")", "p", "[", "2", "]", "=", "filho2", "p", "[", "3", "]", ".", "parent", "=", "pai", "filho4", "=", "MyNode", "(", "name", "=", "'FECHA_PARENTESE'", ",", "type", "=", "'FECHA_PARENTESE'", ",", "parent", "=", "pai", ")", "filho_sym", "=", "MyNode", "(", "name", "=", "p", "[", "4", "]", ",", "type", "=", "'SIMBOLO'", ",", "parent", "=", "filho4", ")", "p", "[", "4", "]", "=", "filho4", "else", ":", "p", "[", "1", "]", ".", "parent", "=", "pai" ]
[ 759, 0 ]
[ 779, 21 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
BayesNet.variable_values
(self, var)
return [True, False]
Retorna o domínio de var.
Retorna o domínio de var.
def variable_values(self, var): "Retorna o domínio de var." return [True, False]
[ "def", "variable_values", "(", "self", ",", "var", ")", ":", "return", "[", "True", ",", "False", "]" ]
[ 186, 4 ]
[ 188, 28 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
GroupVirtualResource.__treat_response_error
(self, response)
return self.response_error(response[0])
Trata as repostas de erro no formato de uma tupla. Formato da tupla: (<codigo da mensagem de erro>, <argumento 01 da mensagem>, <argumento 02 da mensagem>, ...) @return: HttpResponse com a mensagem de erro.
Trata as repostas de erro no formato de uma tupla.
def __treat_response_error(self, response): """Trata as repostas de erro no formato de uma tupla. Formato da tupla: (<codigo da mensagem de erro>, <argumento 01 da mensagem>, <argumento 02 da mensagem>, ...) @return: HttpResponse com a mensagem de erro. """ if len(response) > 1: return self.response_error(response[0], response[1:len(response)]) return self.response_error(response[0])
[ "def", "__treat_response_error", "(", "self", ",", "response", ")", ":", "if", "len", "(", "response", ")", ">", "1", ":", "return", "self", ".", "response_error", "(", "response", "[", "0", "]", ",", "response", "[", "1", ":", "len", "(", "response", ")", "]", ")", "return", "self", ".", "response_error", "(", "response", "[", "0", "]", ")" ]
[ 195, 4 ]
[ 205, 47 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
hailstone_sequence
(a_0: int)
Calcula (recursivamente) a sequência conhecida como "números de granizo" (hailstone sequence) ou "números maravilhosos". A Conjectura de Collatz afirma que, independentemente do valor de a[0], a sequência sempre atingirá um valor k tal que a[k]=1. Args: a_0 (int): Número inicial, de onde a sequência iniciará. Returns: list: Lista dos números maravilhosos.
Calcula (recursivamente) a sequência conhecida como "números de granizo" (hailstone sequence) ou "números maravilhosos". A Conjectura de Collatz afirma que, independentemente do valor de a[0], a sequência sempre atingirá um valor k tal que a[k]=1.
def hailstone_sequence(a_0: int): """Calcula (recursivamente) a sequência conhecida como "números de granizo" (hailstone sequence) ou "números maravilhosos". A Conjectura de Collatz afirma que, independentemente do valor de a[0], a sequência sempre atingirá um valor k tal que a[k]=1. Args: a_0 (int): Número inicial, de onde a sequência iniciará. Returns: list: Lista dos números maravilhosos. """ # Condição de parada -> a_0 == 1 if a_0 == 1: return [a_0] # Decisão para próximo passo da sequência (par ou ímpar) elif a_0 % 2 == 0: # return é o número atual mais o hailstone do próximo par return [a_0] + hailstone_sequence(a_0 // 2) else: # return é o número atual mais o hailstone do próximo ímpar return [a_0] + hailstone_sequence(3 * a_0 + 1)
[ "def", "hailstone_sequence", "(", "a_0", ":", "int", ")", ":", "# Condição de parada -> a_0 == 1", "if", "a_0", "==", "1", ":", "return", "[", "a_0", "]", "# Decisão para próximo passo da sequência (par ou ímpar)", "elif", "a_0", "%", "2", "==", "0", ":", "# return é o número atual mais o hailstone do próximo par", "return", "[", "a_0", "]", "+", "hailstone_sequence", "(", "a_0", "//", "2", ")", "else", ":", "# return é o número atual mais o hailstone do próximo ímpar", "return", "[", "a_0", "]", "+", "hailstone_sequence", "(", "3", "*", "a_0", "+", "1", ")" ]
[ 31, 0 ]
[ 49, 54 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
BoletoHTML.drawBoletoCarneDuplo
(self, boletoDados1, boletoDados2=None)
Imprime um boleto tipo carnê com 2 boletos por página. :param boletoDados1: Objeto com os dados do boleto a ser preenchido. Deve ser subclasse de :class:`pyboleto.data.BoletoData` :param boletoDados2: Objeto com os dados do boleto a ser preenchido. Deve ser subclasse de :class:`pyboleto.data.BoletoData` :type boletoDados1: :class:`pyboleto.data.BoletoData` :type boletoDados2: :class:`pyboleto.data.BoletoData`
Imprime um boleto tipo carnê com 2 boletos por página.
def drawBoletoCarneDuplo(self, boletoDados1, boletoDados2=None): """Imprime um boleto tipo carnê com 2 boletos por página. :param boletoDados1: Objeto com os dados do boleto a ser preenchido. Deve ser subclasse de :class:`pyboleto.data.BoletoData` :param boletoDados2: Objeto com os dados do boleto a ser preenchido. Deve ser subclasse de :class:`pyboleto.data.BoletoData` :type boletoDados1: :class:`pyboleto.data.BoletoData` :type boletoDados2: :class:`pyboleto.data.BoletoData` """ raise NotImplementedError('Em desenvolvimento')
[ "def", "drawBoletoCarneDuplo", "(", "self", ",", "boletoDados1", ",", "boletoDados2", "=", "None", ")", ":", "raise", "NotImplementedError", "(", "'Em desenvolvimento'", ")" ]
[ 199, 4 ]
[ 210, 55 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
network_mask_from_cidr_mask
(cidr_mask)
return ((address >> 24) & 0xFF, (address >> 16) & 0xFF, (address >> 8) & 0xFF, (address >> 0) & 0xFF)
Calcula a máscara de uma rede a partir do número do bloco do endereço. @param cidr_mask: Valor do bloco do endereço. @return: Tuple com o octeto 1, 2, 3, 4 da máscara: (oct1,oct2,oct3,oct4).
Calcula a máscara de uma rede a partir do número do bloco do endereço.
def network_mask_from_cidr_mask(cidr_mask): """Calcula a máscara de uma rede a partir do número do bloco do endereço. @param cidr_mask: Valor do bloco do endereço. @return: Tuple com o octeto 1, 2, 3, 4 da máscara: (oct1,oct2,oct3,oct4). """ address = 0xFFFFFFFF address = address << (32 - cidr_mask) return ((address >> 24) & 0xFF, (address >> 16) & 0xFF, (address >> 8) & 0xFF, (address >> 0) & 0xFF)
[ "def", "network_mask_from_cidr_mask", "(", "cidr_mask", ")", ":", "address", "=", "0xFFFFFFFF", "address", "=", "address", "<<", "(", "32", "-", "cidr_mask", ")", "return", "(", "(", "address", ">>", "24", ")", "&", "0xFF", ",", "(", "address", ">>", "16", ")", "&", "0xFF", ",", "(", "address", ">>", "8", ")", "&", "0xFF", ",", "(", "address", ">>", "0", ")", "&", "0xFF", ")" ]
[ 19, 0 ]
[ 28, 105 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Alien.__init__
(self, ai_settings, screen)
Inicializa o alienigena e define sua posicao inicial.
Inicializa o alienigena e define sua posicao inicial.
def __init__(self, ai_settings, screen): """Inicializa o alienigena e define sua posicao inicial.""" super(Alien, self).__init__() self.screen = screen self.ai_settings = ai_settings # Carrega a imagem do alienigena e define seu atributo rect self.image = pygame.image.load('images/alien.bmp') self.rect = self.image.get_rect() # Inicia cada novo alienigena proximo a parte superior da tela self.rect.x = self.rect.width self.rect.y = self.rect.height # Armazena a posicao exata do alienigena self.x = float(self.rect.x)
[ "def", "__init__", "(", "self", ",", "ai_settings", ",", "screen", ")", ":", "super", "(", "Alien", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "screen", "=", "screen", "self", ".", "ai_settings", "=", "ai_settings", "# Carrega a imagem do alienigena e define seu atributo rect", "self", ".", "image", "=", "pygame", ".", "image", ".", "load", "(", "'images/alien.bmp'", ")", "self", ".", "rect", "=", "self", ".", "image", ".", "get_rect", "(", ")", "# Inicia cada novo alienigena proximo a parte superior da tela", "self", ".", "rect", ".", "x", "=", "self", ".", "rect", ".", "width", "self", ".", "rect", ".", "y", "=", "self", ".", "rect", ".", "height", "# Armazena a posicao exata do alienigena", "self", ".", "x", "=", "float", "(", "self", ".", "rect", ".", "x", ")" ]
[ 6, 4 ]
[ 22, 35 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
check_aliens_bottom
(ai_settings, stats, screen, sb, ship, aliens, bullets)
Verifica se algum alienigena alcancou a parte inferior da tela
Verifica se algum alienigena alcancou a parte inferior da tela
def check_aliens_bottom(ai_settings, stats, screen, sb, ship, aliens, bullets): """Verifica se algum alienigena alcancou a parte inferior da tela""" screen_rect = screen.get_rect() for alien in aliens.sprites(): if alien.rect.bottom >= screen_rect.bottom: # Trata esse caso do mesmo modo que e feito quando a espaconave # e atingida ship_hit(ai_settings, stats, screen, sb, ship, aliens, bullets) break
[ "def", "check_aliens_bottom", "(", "ai_settings", ",", "stats", ",", "screen", ",", "sb", ",", "ship", ",", "aliens", ",", "bullets", ")", ":", "screen_rect", "=", "screen", ".", "get_rect", "(", ")", "for", "alien", "in", "aliens", ".", "sprites", "(", ")", ":", "if", "alien", ".", "rect", ".", "bottom", ">=", "screen_rect", ".", "bottom", ":", "# Trata esse caso do mesmo modo que e feito quando a espaconave", "# e atingida", "ship_hit", "(", "ai_settings", ",", "stats", ",", "screen", ",", "sb", ",", "ship", ",", "aliens", ",", "bullets", ")", "break" ]
[ 215, 0 ]
[ 225, 17 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
compare_agents
(EnvFactory, AgentFactories, n=10, steps=1000)
return [(A, test_agent(A, steps, copy.deepcopy(envs))) for A in AgentFactories]
Compara vários agentes em n instâncias de um ambiente.
Compara vários agentes em n instâncias de um ambiente.
def compare_agents(EnvFactory, AgentFactories, n=10, steps=1000): """Compara vários agentes em n instâncias de um ambiente.""" envs = [EnvFactory() for i in range(n)] return [(A, test_agent(A, steps, copy.deepcopy(envs))) for A in AgentFactories]
[ "def", "compare_agents", "(", "EnvFactory", ",", "AgentFactories", ",", "n", "=", "10", ",", "steps", "=", "1000", ")", ":", "envs", "=", "[", "EnvFactory", "(", ")", "for", "i", "in", "range", "(", "n", ")", "]", "return", "[", "(", "A", ",", "test_agent", "(", "A", ",", "steps", ",", "copy", ".", "deepcopy", "(", "envs", ")", ")", ")", "for", "A", "in", "AgentFactories", "]" ]
[ 279, 0 ]
[ 283, 36 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Alien.blitme
(self)
Desenha o alienigena em sua posição atual
Desenha o alienigena em sua posição atual
def blitme(self): """Desenha o alienigena em sua posição atual""" self.screen.blit(self.image,self.rect)
[ "def", "blitme", "(", "self", ")", ":", "self", ".", "screen", ".", "blit", "(", "self", ".", "image", ",", "self", ".", "rect", ")" ]
[ 23, 4 ]
[ 25, 46 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
file_to_corpus
(name_file)
return rows
Transforma as linahs de um arquivo em uma lista. Example: function(my_file.txt)
Transforma as linahs de um arquivo em uma lista. Example: function(my_file.txt)
def file_to_corpus(name_file): """Transforma as linahs de um arquivo em uma lista. Example: function(my_file.txt) """ rows = [] #with open(name_file, 'r') as read: #, encoding = "ISO-8859-1" with io.open(name_file, newline='\n', errors='ignore') as read: #erro ignore caracteres for row in read: row = row.replace("\n", "") rows.append(row) return rows
[ "def", "file_to_corpus", "(", "name_file", ")", ":", "rows", "=", "[", "]", "#with open(name_file, 'r') as read:", "#, encoding = \"ISO-8859-1\"", "with", "io", ".", "open", "(", "name_file", ",", "newline", "=", "'\\n'", ",", "errors", "=", "'ignore'", ")", "as", "read", ":", "#erro ignore caracteres", "for", "row", "in", "read", ":", "row", "=", "row", ".", "replace", "(", "\"\\n\"", ",", "\"\"", ")", "rows", ".", "append", "(", "row", ")", "return", "rows" ]
[ 96, 0 ]
[ 105, 15 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
n_palavras_unicas
(lista_palavras)
return unicas
Essa funcao recebe uma lista de palavras e devolve o numero de palavras que aparecem uma unica vez
Essa funcao recebe uma lista de palavras e devolve o numero de palavras que aparecem uma unica vez
def n_palavras_unicas(lista_palavras): '''Essa funcao recebe uma lista de palavras e devolve o numero de palavras que aparecem uma unica vez''' freq = dict() unicas = 0 for palavra in lista_palavras: p = palavra.lower() if p in freq: if freq[p] == 1: unicas -= 1 freq[p] += 1 else: freq[p] = 1 unicas += 1 return unicas
[ "def", "n_palavras_unicas", "(", "lista_palavras", ")", ":", "freq", "=", "dict", "(", ")", "unicas", "=", "0", "for", "palavra", "in", "lista_palavras", ":", "p", "=", "palavra", ".", "lower", "(", ")", "if", "p", "in", "freq", ":", "if", "freq", "[", "p", "]", "==", "1", ":", "unicas", "-=", "1", "freq", "[", "p", "]", "+=", "1", "else", ":", "freq", "[", "p", "]", "=", "1", "unicas", "+=", "1", "return", "unicas" ]
[ 43, 0 ]
[ 57, 17 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
p_retorna
(p)
retorna : RETORNA ABRE_PARENTESE expressao FECHA_PARENTESE
retorna : RETORNA ABRE_PARENTESE expressao FECHA_PARENTESE
def p_retorna(p): """retorna : RETORNA ABRE_PARENTESE expressao FECHA_PARENTESE""" pai = MyNode(name='retorna', type='RETORNA') p[0] = pai filho1 = MyNode(name='RETORNA', type='RETORNA', parent=pai) filho_sym1 = MyNode(name=p[1], type='RETORNA', parent=filho1) p[1] = filho1 filho2 = MyNode(name='ABRE_PARENTESE', type='ABRE_PARENTESE', parent=pai) filho_sym2 = MyNode(name='(', type='SIMBOLO', parent=filho2) p[2] = filho2 p[3].parent = pai # expressao. filho4 = MyNode(name='FECHA_PARENTESE', type='FECHA_PARENTESE', parent=pai) filho_sym4 = MyNode(name=')', type='SIMBOLO', parent=filho4) p[4] = filho4
[ "def", "p_retorna", "(", "p", ")", ":", "pai", "=", "MyNode", "(", "name", "=", "'retorna'", ",", "type", "=", "'RETORNA'", ")", "p", "[", "0", "]", "=", "pai", "filho1", "=", "MyNode", "(", "name", "=", "'RETORNA'", ",", "type", "=", "'RETORNA'", ",", "parent", "=", "pai", ")", "filho_sym1", "=", "MyNode", "(", "name", "=", "p", "[", "1", "]", ",", "type", "=", "'RETORNA'", ",", "parent", "=", "filho1", ")", "p", "[", "1", "]", "=", "filho1", "filho2", "=", "MyNode", "(", "name", "=", "'ABRE_PARENTESE'", ",", "type", "=", "'ABRE_PARENTESE'", ",", "parent", "=", "pai", ")", "filho_sym2", "=", "MyNode", "(", "name", "=", "'('", ",", "type", "=", "'SIMBOLO'", ",", "parent", "=", "filho2", ")", "p", "[", "2", "]", "=", "filho2", "p", "[", "3", "]", ".", "parent", "=", "pai", "# expressao.", "filho4", "=", "MyNode", "(", "name", "=", "'FECHA_PARENTESE'", ",", "type", "=", "'FECHA_PARENTESE'", ",", "parent", "=", "pai", ")", "filho_sym4", "=", "MyNode", "(", "name", "=", "')'", ",", "type", "=", "'SIMBOLO'", ",", "parent", "=", "filho4", ")", "p", "[", "4", "]", "=", "filho4" ]
[ 496, 0 ]
[ 514, 15 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
linha
(simb='=',tam=42)
[Cria uma linha] Args: simb (str, optional): [O símbolo que Vai Formar a linha]. Defaults to '='. tam (int, optional): [Tamanho da Linha]. Defaults to 42. Criado por: Murilo_Henrique060
[Cria uma linha]
def linha(simb='=',tam=42): """[Cria uma linha] Args: simb (str, optional): [O símbolo que Vai Formar a linha]. Defaults to '='. tam (int, optional): [Tamanho da Linha]. Defaults to 42. Criado por: Murilo_Henrique060 """ print(f'{simb}'*tam)
[ "def", "linha", "(", "simb", "=", "'='", ",", "tam", "=", "42", ")", ":", "print", "(", "f'{simb}'", "*", "tam", ")" ]
[ 0, 0 ]
[ 9, 24 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
quivoExiste(n
ome):
[Identifica se um arquivo existe.] Args: nome ([str]): [Nome do arquivo a ser identificado.] Returns: [bool]: [Retorna um valor boleano('True' ou 'False') se ele existe ou não.] criado por: Murilo-Henrique060
[Identifica se um arquivo existe.]
f arquivoExiste(nome): """[Identifica se um arquivo existe.] Args: nome ([str]): [Nome do arquivo a ser identificado.] Returns: [bool]: [Retorna um valor boleano('True' ou 'False') se ele existe ou não.] criado por: Murilo-Henrique060 """ try: a = open(nome,'rt') a.close() except FileNotFoundError: return False else: return True
[ "f a", "quivoExiste(n", "o", "me):", "", "", "try", ":", "a", "=", "open", "(", "nome", ",", "'rt'", ")", "a", ".", "close", "(", ")", "except", "FileNotFoundError", ":", "return", "False", "else", ":", "return", "True" ]
[ 0, 3 ]
[ 17, 19 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
get_bin_file
(args)
return name, get(url, stream=True).raw
Faz o download do binário.
Faz o download do binário.
def get_bin_file(args): """Faz o download do binário.""" name, url = args return name, get(url, stream=True).raw
[ "def", "get_bin_file", "(", "args", ")", ":", "name", ",", "url", "=", "args", "return", "name", ",", "get", "(", "url", ",", "stream", "=", "True", ")", ".", "raw" ]
[ 12, 0 ]
[ 15, 42 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
debug_mode
(info)
Quando o variavel debug está setada em True, este metodo printa as saedas de cada passo em tela.
Quando o variavel debug está setada em True, este metodo printa as saedas de cada passo em tela.
def debug_mode(info): """ Quando o variavel debug está setada em True, este metodo printa as saedas de cada passo em tela.""" exit_file = open(exit_path, 'a+') # Grava dado no arquivo exit_file.write(f'{info}\n') exit_file.close() if debug == True: # Exibe saida no shell print(info)
[ "def", "debug_mode", "(", "info", ")", ":", "exit_file", "=", "open", "(", "exit_path", ",", "'a+'", ")", "# Grava dado no arquivo", "exit_file", ".", "write", "(", "f'{info}\\n'", ")", "exit_file", ".", "close", "(", ")", "if", "debug", "==", "True", ":", "# Exibe saida no shell", "print", "(", "info", ")" ]
[ 10, 0 ]
[ 22, 19 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
slug_pre_save
(signal, instance, sender, **kwargs)
Este signal gera um slug automaticamente. Ele verifica se ja existe um objeto com o mesmo slug e acrescenta um numero ao final para evitar duplicidade
Este signal gera um slug automaticamente. Ele verifica se ja existe um objeto com o mesmo slug e acrescenta um numero ao final para evitar duplicidade
def slug_pre_save(signal, instance, sender, **kwargs): """Este signal gera um slug automaticamente. Ele verifica se ja existe um objeto com o mesmo slug e acrescenta um numero ao final para evitar duplicidade""" if not instance.slug: slug = slugify(instance.titulo) novo_slug = slug contador = 0 while sender.objects.filter(slug=novo_slug).exclude(id=instance.id).count() > 0: contador += 1 novo_slug = '%s-%d'%(slug, contador) instance.slug = novo_slug
[ "def", "slug_pre_save", "(", "signal", ",", "instance", ",", "sender", ",", "*", "*", "kwargs", ")", ":", "if", "not", "instance", ".", "slug", ":", "slug", "=", "slugify", "(", "instance", ".", "titulo", ")", "novo_slug", "=", "slug", "contador", "=", "0", "while", "sender", ".", "objects", ".", "filter", "(", "slug", "=", "novo_slug", ")", ".", "exclude", "(", "id", "=", "instance", ".", "id", ")", ".", "count", "(", ")", ">", "0", ":", "contador", "+=", "1", "novo_slug", "=", "'%s-%d'", "%", "(", "slug", ",", "contador", ")", "instance", ".", "slug", "=", "novo_slug" ]
[ 2, 0 ]
[ 15, 33 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
index
(page)
Exibe todas as livros cadastradas.
Exibe todas as livros cadastradas.
def index(page): """Exibe todas as livros cadastradas.""" try: perpage = 12 startat = ( page - 1 ) * perpage perpage *= page total_livros = db.query_bd('select * from livro') totalpages = int(len(total_livros) / 12) + 1 if request.method == 'POST': busca = request.form['busca'] tipo = request.form['tipo'] sql = "SELECT livro.*, \ (SELECT a.nome FROM autor a WHERE a.id = livro.id_autor) as 'autor', \ (SELECT e.nome FROM editora e WHERE e.id = livro.id_editora) as 'editora' \ FROM livro \ WHERE livro.{} LIKE '%{}%' limit {}, {};".format(tipo, busca, startat, perpage) livros = db.query_bd(sql) totalpages = int(len(livros) / 12) + 1 else: sql = "SELECT livro.*, \ (SELECT a.nome FROM autor a WHERE a.id = livro.id_autor) as 'autor', \ (SELECT e.nome FROM editora e WHERE e.id = livro.id_editora) as 'editora' \ FROM livro \ limit {}, {};".format(startat, perpage) # sql ='select * from livro inner join autor on autor.id = livro.id_autor \ # inner join editora on editora.id = livro.id_editora limit %s, %s;' % (startat, perpage) livros = db.query_bd(sql) livros = livros[:12] return render_template('livro/card.html', livros=livros, page=page, totalpages=totalpages) except Exception as e: print(e) return render_template('404.html')
[ "def", "index", "(", "page", ")", ":", "try", ":", "perpage", "=", "12", "startat", "=", "(", "page", "-", "1", ")", "*", "perpage", "perpage", "*=", "page", "total_livros", "=", "db", ".", "query_bd", "(", "'select * from livro'", ")", "totalpages", "=", "int", "(", "len", "(", "total_livros", ")", "/", "12", ")", "+", "1", "if", "request", ".", "method", "==", "'POST'", ":", "busca", "=", "request", ".", "form", "[", "'busca'", "]", "tipo", "=", "request", ".", "form", "[", "'tipo'", "]", "sql", "=", "\"SELECT livro.*, \\\n (SELECT a.nome FROM autor a WHERE a.id = livro.id_autor) as 'autor', \\\n (SELECT e.nome FROM editora e WHERE e.id = livro.id_editora) as 'editora' \\\n FROM livro \\\n WHERE livro.{} LIKE '%{}%' limit {}, {};\"", ".", "format", "(", "tipo", ",", "busca", ",", "startat", ",", "perpage", ")", "livros", "=", "db", ".", "query_bd", "(", "sql", ")", "totalpages", "=", "int", "(", "len", "(", "livros", ")", "/", "12", ")", "+", "1", "else", ":", "sql", "=", "\"SELECT livro.*, \\\n (SELECT a.nome FROM autor a WHERE a.id = livro.id_autor) as 'autor', \\\n (SELECT e.nome FROM editora e WHERE e.id = livro.id_editora) as 'editora' \\\n FROM livro \\\n limit {}, {};\"", ".", "format", "(", "startat", ",", "perpage", ")", "# sql ='select * from livro inner join autor on autor.id = livro.id_autor \\", "# inner join editora on editora.id = livro.id_editora limit %s, %s;' % (startat, perpage)", "livros", "=", "db", ".", "query_bd", "(", "sql", ")", "livros", "=", "livros", "[", ":", "12", "]", "return", "render_template", "(", "'livro/card.html'", ",", "livros", "=", "livros", ",", "page", "=", "page", ",", "totalpages", "=", "totalpages", ")", "except", "Exception", "as", "e", ":", "print", "(", "e", ")", "return", "render_template", "(", "'404.html'", ")" ]
[ 64, 0 ]
[ 97, 42 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
BoletoHTML.nextPage
(self)
Força início de nova página
Força início de nova página
def nextPage(self): """Força início de nova página""" self.html += '</div><div class="pagina">'
[ "def", "nextPage", "(", "self", ")", ":", "self", ".", "html", "+=", "'</div><div class=\"pagina\">'" ]
[ 227, 4 ]
[ 229, 49 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Audio.play
(self, ctx: commands.Context, *, query: str)
Toca uma música via streaming. É mais recomendando usar esse comando no bot estável, já que vai ter menos chances de bufferings e travadas. Você ganha rapidez ao carregar a música, mas ao custo de estabilidade.
Toca uma música via streaming. É mais recomendando usar esse comando no bot estável, já que vai ter menos chances de bufferings e travadas. Você ganha rapidez ao carregar a música, mas ao custo de estabilidade.
async def play(self, ctx: commands.Context, *, query: str): """Toca uma música via streaming. É mais recomendando usar esse comando no bot estável, já que vai ter menos chances de bufferings e travadas. Você ganha rapidez ao carregar a música, mas ao custo de estabilidade. """ if await self.in_voice_channel(ctx): async with ctx.typing(): try: player, data = await YTDLSource.from_url(query, stream=True) except IndexError: return await ctx.reply(f"O termo ou URL não corresponde a nenhum vídeo." " Tenta usar termos mais vagos na próxima vez.") self.queue_song(ctx, player, data) if self.currently_playing is None and not ctx.voice_client.is_playing(): self.truncate_queue(ctx) else: await self.embed(ctx, data, player)
[ "async", "def", "play", "(", "self", ",", "ctx", ":", "commands", ".", "Context", ",", "*", ",", "query", ":", "str", ")", ":", "if", "await", "self", ".", "in_voice_channel", "(", "ctx", ")", ":", "async", "with", "ctx", ".", "typing", "(", ")", ":", "try", ":", "player", ",", "data", "=", "await", "YTDLSource", ".", "from_url", "(", "query", ",", "stream", "=", "True", ")", "except", "IndexError", ":", "return", "await", "ctx", ".", "reply", "(", "f\"O termo ou URL não corresponde a nenhum vídeo.\" \r", "\" Tenta usar termos mais vagos na próxima vez.\")", "\r", "self", ".", "queue_song", "(", "ctx", ",", "player", ",", "data", ")", "if", "self", ".", "currently_playing", "is", "None", "and", "not", "ctx", ".", "voice_client", ".", "is_playing", "(", ")", ":", "self", ".", "truncate_queue", "(", "ctx", ")", "else", ":", "await", "self", ".", "embed", "(", "ctx", ",", "data", ",", "player", ")" ]
[ 139, 4 ]
[ 156, 51 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
convert_to_utf8
(object)
return unicode(str(object), 'utf-8', 'replace')
Converte o object informado para uma representação em utf-8
Converte o object informado para uma representação em utf-8
def convert_to_utf8(object): """Converte o object informado para uma representação em utf-8""" return unicode(str(object), 'utf-8', 'replace')
[ "def", "convert_to_utf8", "(", "object", ")", ":", "return", "unicode", "(", "str", "(", "object", ")", ",", "'utf-8'", ",", "'replace'", ")" ]
[ 33, 0 ]
[ 35, 51 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
linha.linha
(self, ln = None, ind = recuo)
Getter e setter do atributo .ln sem a indentação, calculando também o .recuo com base no dicionário de caracteres ou valor final ind, igualado ao recuo da próxima linha se esta não tiver valor significativo (for inteiramente comentada ou completamente vazia). Guarda o original no atributo .cru
Getter e setter do atributo .ln sem a indentação, calculando também o .recuo com base no dicionário de caracteres ou valor final ind, igualado ao recuo da próxima linha se esta não tiver valor significativo (for inteiramente comentada ou completamente vazia). Guarda o original no atributo .cru
def linha (self, ln = None, ind = recuo): '''Getter e setter do atributo .ln sem a indentação, calculando também o .recuo com base no dicionário de caracteres ou valor final ind, igualado ao recuo da próxima linha se esta não tiver valor significativo (for inteiramente comentada ou completamente vazia). Guarda o original no atributo .cru''' if ln == None: try: return self.ln except AttributeError: pass elif self.__class__ == ln.__class__: if self.id == None: self.id = ln.id if ind == recuo: ind = ln.ind ln = ln.cru fonte = str(ln) self.recuo = c = 0 self.cru = self.ln = ln self.ind = ind self.lower = fonte.lower self.upper = fonte.upper self.title = fonte.title self.split = fonte.split self.splitlines = fonte.splitlines try: while c < len(ln): self.recuo += ind[ln[c]] c += 1 except KeyError: pass except TypeError: if type(ind) == int: self.recuo = ind return try: self.ln = ln[c:] ln = 0 for c in ind[0]: if self.find(c) == 0: ln = self.__len__() break except KeyError: pass except: warnings.warn('Ocorreu algum problema inesperado nas linhas anteriores!',RuntimeWarning) if self.__len__() == ln: self.recuo = contarecuo(self.seguinte())
[ "def", "linha", "(", "self", ",", "ln", "=", "None", ",", "ind", "=", "recuo", ")", ":", "if", "ln", "==", "None", ":", "try", ":", "return", "self", ".", "ln", "except", "AttributeError", ":", "pass", "elif", "self", ".", "__class__", "==", "ln", ".", "__class__", ":", "if", "self", ".", "id", "==", "None", ":", "self", ".", "id", "=", "ln", ".", "id", "if", "ind", "==", "recuo", ":", "ind", "=", "ln", ".", "ind", "ln", "=", "ln", ".", "cru", "fonte", "=", "str", "(", "ln", ")", "self", ".", "recuo", "=", "c", "=", "0", "self", ".", "cru", "=", "self", ".", "ln", "=", "ln", "self", ".", "ind", "=", "ind", "self", ".", "lower", "=", "fonte", ".", "lower", "self", ".", "upper", "=", "fonte", ".", "upper", "self", ".", "title", "=", "fonte", ".", "title", "self", ".", "split", "=", "fonte", ".", "split", "self", ".", "splitlines", "=", "fonte", ".", "splitlines", "try", ":", "while", "c", "<", "len", "(", "ln", ")", ":", "self", ".", "recuo", "+=", "ind", "[", "ln", "[", "c", "]", "]", "c", "+=", "1", "except", "KeyError", ":", "pass", "except", "TypeError", ":", "if", "type", "(", "ind", ")", "==", "int", ":", "self", ".", "recuo", "=", "ind", "return", "try", ":", "self", ".", "ln", "=", "ln", "[", "c", ":", "]", "ln", "=", "0", "for", "c", "in", "ind", "[", "0", "]", ":", "if", "self", ".", "find", "(", "c", ")", "==", "0", ":", "ln", "=", "self", ".", "__len__", "(", ")", "break", "except", "KeyError", ":", "pass", "except", ":", "warnings", ".", "warn", "(", "'Ocorreu algum problema inesperado nas linhas anteriores!'", ",", "RuntimeWarning", ")", "if", "self", ".", "__len__", "(", ")", "==", "ln", ":", "self", ".", "recuo", "=", "contarecuo", "(", "self", ".", "seguinte", "(", ")", ")" ]
[ 122, 1 ]
[ 168, 43 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
test_agent
(AgentFactory, steps, envs)
return mean(map(score, envs))
Retornar a pontuação média de execução de um agente em cada um dos ambientes, para as etapas
Retornar a pontuação média de execução de um agente em cada um dos ambientes, para as etapas
def test_agent(AgentFactory, steps, envs): "Retornar a pontuação média de execução de um agente em cada um dos ambientes, para as etapas" def score(env): agent = AgentFactory() env.add_thing(agent) env.run(steps) return agent.performance return mean(map(score, envs))
[ "def", "test_agent", "(", "AgentFactory", ",", "steps", ",", "envs", ")", ":", "def", "score", "(", "env", ")", ":", "agent", "=", "AgentFactory", "(", ")", "env", ".", "add_thing", "(", "agent", ")", "env", ".", "run", "(", "steps", ")", "return", "agent", ".", "performance", "return", "mean", "(", "map", "(", "score", ",", "envs", ")", ")" ]
[ 286, 0 ]
[ 293, 33 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Chess._refresh_wins
(self)
Força que o cálculo das posições seja feito na próxima chamada ao calculate_position.
Força que o cálculo das posições seja feito na próxima chamada ao calculate_position.
def _refresh_wins(self): """Força que o cálculo das posições seja feito na próxima chamada ao calculate_position.""" self._wins = None
[ "def", "_refresh_wins", "(", "self", ")", ":", "self", ".", "_wins", "=", "None" ]
[ 158, 4 ]
[ 161, 25 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
RequisicaoVips.set_variables
(self, variables_map)
Constroe e atribui o valor do campo "variaveis" a partir dos dados no mapa. @raise EnvironmentVipNotFoundError: Ambiente Vip não encontrado com os valores de finalidade, cliente e ambiente fornecidos. @raise InvalidTimeoutValueError: Timeout 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 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.
Constroe e atribui o valor do campo "variaveis" a partir dos dados no mapa.
def set_variables(self, variables_map): """Constroe e atribui o valor do campo "variaveis" a partir dos dados no mapa. @raise EnvironmentVipNotFoundError: Ambiente Vip não encontrado com os valores de finalidade, cliente e ambiente fornecidos. @raise InvalidTimeoutValueError: Timeout 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 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. """ log = logging.getLogger('insert_vip_request_set_variables') self.variaveis = '' healthcheck_type = variables_map.get('healthcheck_type') if self.healthcheck_expect is not None and healthcheck_type != 'HTTP': raise InvalidHealthcheckTypeValueError( None, u'Valor do healthcheck_type inconsistente com o valor do healthcheck_expect.') finalidade = variables_map.get('finalidade') 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) cliente = variables_map.get('cliente') 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) ambiente = variables_map.get('ambiente') 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: evip = EnvironmentVip.get_by_values(finalidade, cliente, ambiente) self.add_variable('finalidade', finalidade) self.add_variable('cliente', cliente) self.add_variable('ambiente', ambiente) except EnvironmentVipNotFoundError: raise EnvironmentVipNotFoundError( None, u'Não existe ambiente vip para valores: finalidade %s, cliente %s e ambiente_p44 %s.' % ( finalidade, cliente, ambiente)) balanceamento = variables_map.get('metodo_bal') timeout = variables_map.get('timeout') grupo_cache = variables_map.get('cache') persistencia = variables_map.get('persistencia') grupos_cache = [(gc.nome_opcao_txt) for gc in OptionVip.get_all_grupo_cache(evip.id)] timeouts = [(t.nome_opcao_txt) for t in OptionVip.get_all_timeout(evip.id)] persistencias = [(p.nome_opcao_txt) for p in OptionVip.get_all_persistencia(evip.id)] balanceamentos = [(b.nome_opcao_txt) for b in OptionVip.get_all_balanceamento(evip.id)] if timeout not in timeouts: log.error( u'The timeout not in OptionVip, invalid value: %s.', timeout) raise InvalidTimeoutValueError( None, 'timeout com valor inválido: %s.' % timeout) self.add_variable('timeout', timeout) if balanceamento not in balanceamentos: log.error( u'The method_bal not in OptionVip, invalid value: %s.', balanceamento) raise InvalidMetodoBalValueError( None, 'metodo_bal com valor inválido: %s.' % balanceamento) self.add_variable('metodo_bal', balanceamento) if grupo_cache not in grupos_cache: log.error( u'The grupo_cache not in OptionVip, invalid value: %s.', grupo_cache) raise InvalidCacheValueError( None, 'grupo_cache com valor inválido: %s.' % grupo_cache) self.add_variable('cache', grupo_cache) if persistencia not in persistencias: log.error( u'The persistencia not in OptionVip, invalid value: %s.', persistencia) raise InvalidPersistenciaValueError( None, 'persistencia com valor inválido %s.' % persistencia) self.add_variable('persistencia', persistencia) environment_vip = EnvironmentVip.get_by_values( finalidade, cliente, ambiente) healthcheck_is_valid = RequisicaoVips.heathcheck_exist( healthcheck_type, environment_vip.id) # healthcheck_type if not healthcheck_is_valid: raise InvalidHealthcheckTypeValueError( None, u'Healthcheck_type com valor inválido: %s.' % healthcheck_type) self.add_variable('healthcheck_type', healthcheck_type) # healthcheck healthcheck = variables_map.get('healthcheck') if healthcheck is not None: if healthcheck_type != 'HTTP': raise InvalidHealthcheckValueError( None, u'Valor do healthcheck inconsistente com o valor do healthcheck_type.') self.add_variable('healthcheck', healthcheck) # Host host_name = variables_map.get('host') if host_name is not None: self.add_variable('host', host_name) # maxcon maxcon = variables_map.get('maxcon') try: # maxcon_int = int(maxcon) self.add_variable('maxcon', maxcon) except (TypeError, ValueError): raise InvalidMaxConValueError( None, u'Maxcon com valor inválido: %s.' % maxcon) # dsr dsr = variables_map.get('dsr') if dsr is not None: self.add_variable('dsr', dsr) # area negocio areanegocio = variables_map.get('areanegocio') if areanegocio is not None: self.add_variable('areanegocio', areanegocio) # nome servico nomeservico = variables_map.get('nome_servico') if nomeservico is not None: self.add_variable('nome_servico', nomeservico) # bal_ativo bal_ativo = variables_map.get('bal_ativo') if finalidade == 'Producao' and cliente == 'Usuario WEB' and ambiente == 'Streaming FE' and dsr == 'dsr' and bal_ativo is not None: if bal_ativo not in ('B11A', 'B12'): raise InvalidBalAtivoValueError( None, u'Bal_ativo com valor inválido: %s.' % bal_ativo) if bal_ativo is not None: self.add_variable('bal_ativo', bal_ativo) # transbordos transbordos_map = variables_map.get('transbordos') if (transbordos_map is not None): transbordos = transbordos_map.get('transbordo') values = '' for transbordo in transbordos: if (finalidade == 'Homologacao' and ambiente == 'Homologacao FE-CITTA') or ( finalidade == 'Producao' and ambiente in ('Portal FE', 'Aplicativos FE', 'Streaming FE')): if not is_valid_ip(transbordo): raise InvalidTransbordoValueError(None, transbordo) values = values + transbordo + '|' if values != '': values = values[0:len(values) - 1] self.add_variable('_transbordo', values) # # portas_servicos # portas_servicos_map = variables_map.get('portas_servicos') # if portas_servicos_map is not None: # portas = portas_servicos_map.get('porta') # if len(portas) == 0: # raise InvalidServicePortValueError(None, portas) # i = 1 # for porta in portas: # try: # if re.match('[0-9]+:[0-9]+', porta): # [porta1, porta2] = re.split(':', porta) # porta1_int = int(porta1) # porta2_int = int(porta2) # else: # porta_int = int(porta) # except (TypeError, ValueError): # raise InvalidServicePortValueError(None, porta) # self.add_variable('-portas_servico.' + str(i), porta) # i = i + 1 # else: # raise InvalidServicePortValueError(None, portas_servicos_map) # # reals # reals_map = variables_map.get('reals') # if (reals_map is not None): # real_maps = reals_map.get('real') # if len(real_maps) == 0: # raise InvalidRealValueError(None, real_maps) # i = 1 # for real_map in real_maps: # real_name = real_map.get('real_name') # real_ip = real_map.get('real_ip') # if (real_name is None) or (real_ip is None): # raise InvalidRealValueError(None, '(%s-%s)' % (real_name, real_ip) ) # self.add_variable('-reals_name.' + str(i), real_name) # self.add_variable('-reals_ip.' + str(i), real_ip) # i = i + 1 # # reals_priority # reals_prioritys_map = variables_map.get('reals_prioritys') # if (reals_prioritys_map is not None): # reals_priority_map = reals_prioritys_map.get('reals_priority') # if len(reals_priority_map) == 0: # raise InvalidPriorityValueError(None, reals_priority_map) # i = 1 # for reals_priority in reals_priority_map: # if reals_priority is None: # raise InvalidRealValueError(None, '(%s)' % reals_priority ) # self.add_variable('-reals_priority.' + str(i), reals_priority) # i = i + 1 # else: # raise InvalidPriorityValueError(None, reals_prioritys_map) # # reals_weight # if ( str(balanceamento).upper() == "WEIGHTED" ): # # reals_weight # reals_weights_map = variables_map.get('reals_weights') # if (reals_weights_map is not None): # reals_weight_map = reals_weights_map.get('reals_weight') # if len(reals_weight_map) == 0: # raise InvalidPriorityValueError(None, reals_weight_map) # i = 1 # for reals_weight in reals_weight_map: # if reals_weight is None: # raise InvalidRealValueError(None, '(%s)' % reals_weight ) # self.add_variable('-reals_weight.' + str(i), reals_weight) # i = i + 1 # else: # raise InvalidWeightValueError(None, reals_weights_map) if self.variaveis != '': self.variaveis = self.variaveis[0:len(self.variaveis) - 1]
[ "def", "set_variables", "(", "self", ",", "variables_map", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "'insert_vip_request_set_variables'", ")", "self", ".", "variaveis", "=", "''", "healthcheck_type", "=", "variables_map", ".", "get", "(", "'healthcheck_type'", ")", "if", "self", ".", "healthcheck_expect", "is", "not", "None", "and", "healthcheck_type", "!=", "'HTTP'", ":", "raise", "InvalidHealthcheckTypeValueError", "(", "None", ",", "u'Valor do healthcheck_type inconsistente com o valor do healthcheck_expect.'", ")", "finalidade", "=", "variables_map", ".", "get", "(", "'finalidade'", ")", "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", ")", "cliente", "=", "variables_map", ".", "get", "(", "'cliente'", ")", "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", ")", "ambiente", "=", "variables_map", ".", "get", "(", "'ambiente'", ")", "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", ":", "evip", "=", "EnvironmentVip", ".", "get_by_values", "(", "finalidade", ",", "cliente", ",", "ambiente", ")", "self", ".", "add_variable", "(", "'finalidade'", ",", "finalidade", ")", "self", ".", "add_variable", "(", "'cliente'", ",", "cliente", ")", "self", ".", "add_variable", "(", "'ambiente'", ",", "ambiente", ")", "except", "EnvironmentVipNotFoundError", ":", "raise", "EnvironmentVipNotFoundError", "(", "None", ",", "u'Não existe ambiente vip para valores: finalidade %s, cliente %s e ambiente_p44 %s.' ", " ", "", "finalidade", ",", "cliente", ",", "ambiente", ")", ")", "balanceamento", "=", "variables_map", ".", "get", "(", "'metodo_bal'", ")", "timeout", "=", "variables_map", ".", "get", "(", "'timeout'", ")", "grupo_cache", "=", "variables_map", ".", "get", "(", "'cache'", ")", "persistencia", "=", "variables_map", ".", "get", "(", "'persistencia'", ")", "grupos_cache", "=", "[", "(", "gc", ".", "nome_opcao_txt", ")", "for", "gc", "in", "OptionVip", ".", "get_all_grupo_cache", "(", "evip", ".", "id", ")", "]", "timeouts", "=", "[", "(", "t", ".", "nome_opcao_txt", ")", "for", "t", "in", "OptionVip", ".", "get_all_timeout", "(", "evip", ".", "id", ")", "]", "persistencias", "=", "[", "(", "p", ".", "nome_opcao_txt", ")", "for", "p", "in", "OptionVip", ".", "get_all_persistencia", "(", "evip", ".", "id", ")", "]", "balanceamentos", "=", "[", "(", "b", ".", "nome_opcao_txt", ")", "for", "b", "in", "OptionVip", ".", "get_all_balanceamento", "(", "evip", ".", "id", ")", "]", "if", "timeout", "not", "in", "timeouts", ":", "log", ".", "error", "(", "u'The timeout not in OptionVip, invalid value: %s.'", ",", "timeout", ")", "raise", "InvalidTimeoutValueError", "(", "None", ",", "'timeout com valor inválido: %s.' ", " ", "imeout)", "", "self", ".", "add_variable", "(", "'timeout'", ",", "timeout", ")", "if", "balanceamento", "not", "in", "balanceamentos", ":", "log", ".", "error", "(", "u'The method_bal not in OptionVip, invalid value: %s.'", ",", "balanceamento", ")", "raise", "InvalidMetodoBalValueError", "(", "None", ",", "'metodo_bal com valor inválido: %s.' ", " ", "alanceamento)", "", "self", ".", "add_variable", "(", "'metodo_bal'", ",", "balanceamento", ")", "if", "grupo_cache", "not", "in", "grupos_cache", ":", "log", ".", "error", "(", "u'The grupo_cache not in OptionVip, invalid value: %s.'", ",", "grupo_cache", ")", "raise", "InvalidCacheValueError", "(", "None", ",", "'grupo_cache com valor inválido: %s.' ", " ", "rupo_cache)", "", "self", ".", "add_variable", "(", "'cache'", ",", "grupo_cache", ")", "if", "persistencia", "not", "in", "persistencias", ":", "log", ".", "error", "(", "u'The persistencia not in OptionVip, invalid value: %s.'", ",", "persistencia", ")", "raise", "InvalidPersistenciaValueError", "(", "None", ",", "'persistencia com valor inválido %s.' ", " ", "ersistencia)", "", "self", ".", "add_variable", "(", "'persistencia'", ",", "persistencia", ")", "environment_vip", "=", "EnvironmentVip", ".", "get_by_values", "(", "finalidade", ",", "cliente", ",", "ambiente", ")", "healthcheck_is_valid", "=", "RequisicaoVips", ".", "heathcheck_exist", "(", "healthcheck_type", ",", "environment_vip", ".", "id", ")", "# healthcheck_type", "if", "not", "healthcheck_is_valid", ":", "raise", "InvalidHealthcheckTypeValueError", "(", "None", ",", "u'Healthcheck_type com valor inválido: %s.' ", " ", "ealthcheck_type)", "", "self", ".", "add_variable", "(", "'healthcheck_type'", ",", "healthcheck_type", ")", "# healthcheck", "healthcheck", "=", "variables_map", ".", "get", "(", "'healthcheck'", ")", "if", "healthcheck", "is", "not", "None", ":", "if", "healthcheck_type", "!=", "'HTTP'", ":", "raise", "InvalidHealthcheckValueError", "(", "None", ",", "u'Valor do healthcheck inconsistente com o valor do healthcheck_type.'", ")", "self", ".", "add_variable", "(", "'healthcheck'", ",", "healthcheck", ")", "# Host", "host_name", "=", "variables_map", ".", "get", "(", "'host'", ")", "if", "host_name", "is", "not", "None", ":", "self", ".", "add_variable", "(", "'host'", ",", "host_name", ")", "# maxcon", "maxcon", "=", "variables_map", ".", "get", "(", "'maxcon'", ")", "try", ":", "# maxcon_int = int(maxcon)", "self", ".", "add_variable", "(", "'maxcon'", ",", "maxcon", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "raise", "InvalidMaxConValueError", "(", "None", ",", "u'Maxcon com valor inválido: %s.' ", " ", "axcon)", "", "# dsr", "dsr", "=", "variables_map", ".", "get", "(", "'dsr'", ")", "if", "dsr", "is", "not", "None", ":", "self", ".", "add_variable", "(", "'dsr'", ",", "dsr", ")", "# area negocio", "areanegocio", "=", "variables_map", ".", "get", "(", "'areanegocio'", ")", "if", "areanegocio", "is", "not", "None", ":", "self", ".", "add_variable", "(", "'areanegocio'", ",", "areanegocio", ")", "# nome servico", "nomeservico", "=", "variables_map", ".", "get", "(", "'nome_servico'", ")", "if", "nomeservico", "is", "not", "None", ":", "self", ".", "add_variable", "(", "'nome_servico'", ",", "nomeservico", ")", "# bal_ativo", "bal_ativo", "=", "variables_map", ".", "get", "(", "'bal_ativo'", ")", "if", "finalidade", "==", "'Producao'", "and", "cliente", "==", "'Usuario WEB'", "and", "ambiente", "==", "'Streaming FE'", "and", "dsr", "==", "'dsr'", "and", "bal_ativo", "is", "not", "None", ":", "if", "bal_ativo", "not", "in", "(", "'B11A'", ",", "'B12'", ")", ":", "raise", "InvalidBalAtivoValueError", "(", "None", ",", "u'Bal_ativo com valor inválido: %s.' ", " ", "al_ativo)", "", "if", "bal_ativo", "is", "not", "None", ":", "self", ".", "add_variable", "(", "'bal_ativo'", ",", "bal_ativo", ")", "# transbordos", "transbordos_map", "=", "variables_map", ".", "get", "(", "'transbordos'", ")", "if", "(", "transbordos_map", "is", "not", "None", ")", ":", "transbordos", "=", "transbordos_map", ".", "get", "(", "'transbordo'", ")", "values", "=", "''", "for", "transbordo", "in", "transbordos", ":", "if", "(", "finalidade", "==", "'Homologacao'", "and", "ambiente", "==", "'Homologacao FE-CITTA'", ")", "or", "(", "finalidade", "==", "'Producao'", "and", "ambiente", "in", "(", "'Portal FE'", ",", "'Aplicativos FE'", ",", "'Streaming FE'", ")", ")", ":", "if", "not", "is_valid_ip", "(", "transbordo", ")", ":", "raise", "InvalidTransbordoValueError", "(", "None", ",", "transbordo", ")", "values", "=", "values", "+", "transbordo", "+", "'|'", "if", "values", "!=", "''", ":", "values", "=", "values", "[", "0", ":", "len", "(", "values", ")", "-", "1", "]", "self", ".", "add_variable", "(", "'_transbordo'", ",", "values", ")", "# # portas_servicos", "# portas_servicos_map = variables_map.get('portas_servicos')", "# if portas_servicos_map is not None:", "# portas = portas_servicos_map.get('porta')", "# if len(portas) == 0:", "# raise InvalidServicePortValueError(None, portas)", "# i = 1", "# for porta in portas:", "# try:", "# if re.match('[0-9]+:[0-9]+', porta):", "# [porta1, porta2] = re.split(':', porta)", "# porta1_int = int(porta1)", "# porta2_int = int(porta2)", "# else:", "# porta_int = int(porta)", "# except (TypeError, ValueError):", "# raise InvalidServicePortValueError(None, porta)", "# self.add_variable('-portas_servico.' + str(i), porta)", "# i = i + 1", "# else:", "# raise InvalidServicePortValueError(None, portas_servicos_map)", "# # reals", "# reals_map = variables_map.get('reals')", "# if (reals_map is not None):", "# real_maps = reals_map.get('real')", "# if len(real_maps) == 0:", "# raise InvalidRealValueError(None, real_maps)", "# i = 1", "# for real_map in real_maps:", "# real_name = real_map.get('real_name')", "# real_ip = real_map.get('real_ip')", "# if (real_name is None) or (real_ip is None):", "# raise InvalidRealValueError(None, '(%s-%s)' % (real_name, real_ip) )", "# self.add_variable('-reals_name.' + str(i), real_name)", "# self.add_variable('-reals_ip.' + str(i), real_ip)", "# i = i + 1", "# # reals_priority", "# reals_prioritys_map = variables_map.get('reals_prioritys')", "# if (reals_prioritys_map is not None):", "# reals_priority_map = reals_prioritys_map.get('reals_priority')", "# if len(reals_priority_map) == 0:", "# raise InvalidPriorityValueError(None, reals_priority_map)", "# i = 1", "# for reals_priority in reals_priority_map:", "# if reals_priority is None:", "# raise InvalidRealValueError(None, '(%s)' % reals_priority )", "# self.add_variable('-reals_priority.' + str(i), reals_priority)", "# i = i + 1", "# else:", "# raise InvalidPriorityValueError(None, reals_prioritys_map)", "# # reals_weight", "# if ( str(balanceamento).upper() == \"WEIGHTED\" ):", "# # reals_weight", "# reals_weights_map = variables_map.get('reals_weights')", "# if (reals_weights_map is not None):", "# reals_weight_map = reals_weights_map.get('reals_weight')", "# if len(reals_weight_map) == 0:", "# raise InvalidPriorityValueError(None, reals_weight_map)", "# i = 1", "# for reals_weight in reals_weight_map:", "# if reals_weight is None:", "# raise InvalidRealValueError(None, '(%s)' % reals_weight )", "# self.add_variable('-reals_weight.' + str(i), reals_weight)", "# i = i + 1", "# else:", "# raise InvalidWeightValueError(None, reals_weights_map)", "if", "self", ".", "variaveis", "!=", "''", ":", "self", ".", "variaveis", "=", "self", ".", "variaveis", "[", "0", ":", "len", "(", "self", ".", "variaveis", ")", "-", "1", "]" ]
[ 983, 4 ]
[ 1242, 70 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Log.info
(self, msg, *args)
Imprime uma mensagem de informação no log
Imprime uma mensagem de informação no log
def info(self, msg, *args): """Imprime uma mensagem de informação no log""" self.__emit(self.logger.info, msg, args)
[ "def", "info", "(", "self", ",", "msg", ",", "*", "args", ")", ":", "self", ".", "__emit", "(", "self", ".", "logger", ".", "info", ",", "msg", ",", "args", ")" ]
[ 236, 4 ]
[ 238, 48 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
p_cabecalho
(p)
cabecalho : ID ABRE_PARENTESE lista_parametros FECHA_PARENTESE corpo FIM
cabecalho : ID ABRE_PARENTESE lista_parametros FECHA_PARENTESE corpo FIM
def p_cabecalho(p): """cabecalho : ID ABRE_PARENTESE lista_parametros FECHA_PARENTESE corpo FIM""" pai = MyNode(name='cabecalho', type='CABECALHO') p[0] = pai filho1 = MyNode(name='ID', type='ID', parent=pai) filho_id = MyNode(name=p[1], type='ID', parent=filho1) p[1] = filho1 filho2 = MyNode(name='ABRE_PARENTESE', type='ABRE_PARENTESE', parent=pai) filho_sym2 = MyNode(name='(', type='SIMBOLO', parent=filho2) p[2] = filho2 p[3].parent = pai # lista_parametros filho4 = MyNode(name='FECHA_PARENTESE', type='FECHA_PARENTESE', parent=pai) filho_sym4 = MyNode(name=')', type='SIMBOLO', parent=filho4) p[4] = filho4 p[5].parent = pai # corpo filho6 = MyNode(name='FIM', type='FIM', parent=pai) filho_id = MyNode(name='fim', type='FIM', parent=filho6) p[6] = filho6
[ "def", "p_cabecalho", "(", "p", ")", ":", "pai", "=", "MyNode", "(", "name", "=", "'cabecalho'", ",", "type", "=", "'CABECALHO'", ")", "p", "[", "0", "]", "=", "pai", "filho1", "=", "MyNode", "(", "name", "=", "'ID'", ",", "type", "=", "'ID'", ",", "parent", "=", "pai", ")", "filho_id", "=", "MyNode", "(", "name", "=", "p", "[", "1", "]", ",", "type", "=", "'ID'", ",", "parent", "=", "filho1", ")", "p", "[", "1", "]", "=", "filho1", "filho2", "=", "MyNode", "(", "name", "=", "'ABRE_PARENTESE'", ",", "type", "=", "'ABRE_PARENTESE'", ",", "parent", "=", "pai", ")", "filho_sym2", "=", "MyNode", "(", "name", "=", "'('", ",", "type", "=", "'SIMBOLO'", ",", "parent", "=", "filho2", ")", "p", "[", "2", "]", "=", "filho2", "p", "[", "3", "]", ".", "parent", "=", "pai", "# lista_parametros", "filho4", "=", "MyNode", "(", "name", "=", "'FECHA_PARENTESE'", ",", "type", "=", "'FECHA_PARENTESE'", ",", "parent", "=", "pai", ")", "filho_sym4", "=", "MyNode", "(", "name", "=", "')'", ",", "type", "=", "'SIMBOLO'", ",", "parent", "=", "filho4", ")", "p", "[", "4", "]", "=", "filho4", "p", "[", "5", "]", ".", "parent", "=", "pai", "# corpo", "filho6", "=", "MyNode", "(", "name", "=", "'FIM'", ",", "type", "=", "'FIM'", ",", "parent", "=", "pai", ")", "filho_id", "=", "MyNode", "(", "name", "=", "'fim'", ",", "type", "=", "'FIM'", ",", "parent", "=", "filho6", ")", "p", "[", "6", "]", "=", "filho6" ]
[ 237, 0 ]
[ 261, 15 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Thing.is_alive
(self)
return hasattr(self, 'alive') and self.alive
Coisas que estão vivas' devem retornar True.
Coisas que estão vivas' devem retornar True.
def is_alive(self): "Coisas que estão vivas' devem retornar True." return hasattr(self, 'alive') and self.alive
[ "def", "is_alive", "(", "self", ")", ":", "return", "hasattr", "(", "self", ",", "'alive'", ")", "and", "self", ".", "alive" ]
[ 21, 4 ]
[ 23, 52 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
RequisicaoVipsResource.handle_get
(self, request, user, *args, **kwargs)
Trata as requisições de GET para listar uma requisição de VIP. Filtra a requisição de VIP por chave primária. URL: vip/id_vip
Trata as requisições de GET para listar uma requisição de VIP.
def handle_get(self, request, user, *args, **kwargs): """Trata as requisições de GET para listar uma requisição de VIP. Filtra a requisição de VIP por chave primária. URL: vip/id_vip """ try: if kwargs.get('id_vip') is None: return super(RequisicaoVipsResource, self).handle_get(request, user, *args, **kwargs) if not has_perm(user, AdminPermission.VIPS_REQUEST, AdminPermission.READ_OPERATION): return self.not_authorized() # Valid Ip ID if not is_valid_int_greater_zero_param(kwargs.get('id_vip')): self.log.error( u'The id_vip parameter is not a valid value: %s.', kwargs.get('id_vip')) raise InvalidValueError(None, 'id_vip', kwargs.get('id_vip')) request_vip = RequisicaoVips.get_by_pk(kwargs.get('id_vip')) request_vip_map = request_vip.variables_to_map() """""" vip_port_list, reals_list, reals_priority, reals_weight = request_vip.get_vips_and_reals( request_vip.id) if reals_list: request_vip_map['reals'] = {'real': reals_list} request_vip_map['reals_prioritys'] = { 'reals_priority': reals_priority} request_vip_map['reals_weights'] = { 'reals_weight': reals_weight} request_vip_map['portas_servicos'] = {'porta': vip_port_list} """""" request_vip_map['id'] = request_vip.id request_vip_map['validado'] = convert_boolean_to_int( request_vip.validado) request_vip_map['vip_criado'] = convert_boolean_to_int( request_vip.vip_criado) request_vip_map['id_ip'] = request_vip.ip_id request_vip_map['id_ipv6'] = request_vip.ipv6_id request_vip_map[ 'id_healthcheck_expect'] = request_vip.healthcheck_expect_id request_vip_map['l7_filter'] = request_vip.l7_filter request_vip_map['rule_id'] = request_vip.rule_id return self.response(dumps_networkapi({'vip': request_vip_map})) except InvalidValueError, e: return self.response_error(269, e.param, e.value) except (RequisicaoVipsNotFoundError): return self.response_error(152) except (RequisicaoVipsError, GrupoError): return self.response_error(1)
[ "def", "handle_get", "(", "self", ",", "request", ",", "user", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "if", "kwargs", ".", "get", "(", "'id_vip'", ")", "is", "None", ":", "return", "super", "(", "RequisicaoVipsResource", ",", "self", ")", ".", "handle_get", "(", "request", ",", "user", ",", "*", "args", ",", "*", "*", "kwargs", ")", "if", "not", "has_perm", "(", "user", ",", "AdminPermission", ".", "VIPS_REQUEST", ",", "AdminPermission", ".", "READ_OPERATION", ")", ":", "return", "self", ".", "not_authorized", "(", ")", "# Valid Ip ID", "if", "not", "is_valid_int_greater_zero_param", "(", "kwargs", ".", "get", "(", "'id_vip'", ")", ")", ":", "self", ".", "log", ".", "error", "(", "u'The id_vip parameter is not a valid value: %s.'", ",", "kwargs", ".", "get", "(", "'id_vip'", ")", ")", "raise", "InvalidValueError", "(", "None", ",", "'id_vip'", ",", "kwargs", ".", "get", "(", "'id_vip'", ")", ")", "request_vip", "=", "RequisicaoVips", ".", "get_by_pk", "(", "kwargs", ".", "get", "(", "'id_vip'", ")", ")", "request_vip_map", "=", "request_vip", ".", "variables_to_map", "(", ")", "\"\"\"\"\"\"", "vip_port_list", ",", "reals_list", ",", "reals_priority", ",", "reals_weight", "=", "request_vip", ".", "get_vips_and_reals", "(", "request_vip", ".", "id", ")", "if", "reals_list", ":", "request_vip_map", "[", "'reals'", "]", "=", "{", "'real'", ":", "reals_list", "}", "request_vip_map", "[", "'reals_prioritys'", "]", "=", "{", "'reals_priority'", ":", "reals_priority", "}", "request_vip_map", "[", "'reals_weights'", "]", "=", "{", "'reals_weight'", ":", "reals_weight", "}", "request_vip_map", "[", "'portas_servicos'", "]", "=", "{", "'porta'", ":", "vip_port_list", "}", "\"\"\"\"\"\"", "request_vip_map", "[", "'id'", "]", "=", "request_vip", ".", "id", "request_vip_map", "[", "'validado'", "]", "=", "convert_boolean_to_int", "(", "request_vip", ".", "validado", ")", "request_vip_map", "[", "'vip_criado'", "]", "=", "convert_boolean_to_int", "(", "request_vip", ".", "vip_criado", ")", "request_vip_map", "[", "'id_ip'", "]", "=", "request_vip", ".", "ip_id", "request_vip_map", "[", "'id_ipv6'", "]", "=", "request_vip", ".", "ipv6_id", "request_vip_map", "[", "'id_healthcheck_expect'", "]", "=", "request_vip", ".", "healthcheck_expect_id", "request_vip_map", "[", "'l7_filter'", "]", "=", "request_vip", ".", "l7_filter", "request_vip_map", "[", "'rule_id'", "]", "=", "request_vip", ".", "rule_id", "return", "self", ".", "response", "(", "dumps_networkapi", "(", "{", "'vip'", ":", "request_vip_map", "}", ")", ")", "except", "InvalidValueError", ",", "e", ":", "return", "self", ".", "response_error", "(", "269", ",", "e", ".", "param", ",", "e", ".", "value", ")", "except", "(", "RequisicaoVipsNotFoundError", ")", ":", "return", "self", ".", "response_error", "(", "152", ")", "except", "(", "RequisicaoVipsError", ",", "GrupoError", ")", ":", "return", "self", ".", "response_error", "(", "1", ")" ]
[ 377, 4 ]
[ 438, 41 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
create
()
return render_template('editora/create.html', error=error, success=success)
Cria uma nova editora.
Cria uma nova editora.
def create(): """Cria uma nova editora.""" error = None success = False if request.method == 'POST': nome = request.form['nome'] error = None if not nome: error = 'Nome é obrigatório.' else: try: if verifica_editora_bd(nome): error = 'Editora já cadastrada!' else: db.insert_bd('INSERT INTO editora values (default, "%s")' % nome) success = True except: return render_template('404.html') return render_template('editora/create.html', error=error, success=success)
[ "def", "create", "(", ")", ":", "error", "=", "None", "success", "=", "False", "if", "request", ".", "method", "==", "'POST'", ":", "nome", "=", "request", ".", "form", "[", "'nome'", "]", "error", "=", "None", "if", "not", "nome", ":", "error", "=", "'Nome é obrigatório.'", "else", ":", "try", ":", "if", "verifica_editora_bd", "(", "nome", ")", ":", "error", "=", "'Editora já cadastrada!'", "else", ":", "db", ".", "insert_bd", "(", "'INSERT INTO editora values (default, \"%s\")'", "%", "nome", ")", "success", "=", "True", "except", ":", "return", "render_template", "(", "'404.html'", ")", "return", "render_template", "(", "'editora/create.html'", ",", "error", "=", "error", ",", "success", "=", "success", ")" ]
[ 49, 0 ]
[ 69, 79 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Knowledge.explored
(self)
return self.rooms(lambda r: r.is_explored)
Retorna um gerador de índices de salas já exploradas.
Retorna um gerador de índices de salas já exploradas.
def explored(self): """Retorna um gerador de índices de salas já exploradas.""" return self.rooms(lambda r: r.is_explored)
[ "def", "explored", "(", "self", ")", ":", "return", "self", ".", "rooms", "(", "lambda", "r", ":", "r", ".", "is_explored", ")" ]
[ 282, 2 ]
[ 286, 46 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
make_album
(name, title, faixas = '')
return album_information
Exibe o título de um álbum e o nome do artista autor do álbum.
Exibe o título de um álbum e o nome do artista autor do álbum.
def make_album(name, title, faixas = ''): """Exibe o título de um álbum e o nome do artista autor do álbum.""" if faixas: album_information = {'Artista': name.title(), 'Album': title.title(), 'Faixas': faixas} else: album_information = {'Artista': name.title(), 'Album': title.title()} return album_information
[ "def", "make_album", "(", "name", ",", "title", ",", "faixas", "=", "''", ")", ":", "if", "faixas", ":", "album_information", "=", "{", "'Artista'", ":", "name", ".", "title", "(", ")", ",", "'Album'", ":", "title", ".", "title", "(", ")", ",", "'Faixas'", ":", "faixas", "}", "else", ":", "album_information", "=", "{", "'Artista'", ":", "name", ".", "title", "(", ")", ",", "'Album'", ":", "title", ".", "title", "(", ")", "}", "return", "album_information" ]
[ 8, 0 ]
[ 14, 28 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
chamado_list_fun
(request)
return render(request, "chamado_list_fun.html", dados)
Lista Chamado Para Funcionário Específico.
Lista Chamado Para Funcionário Específico.
def chamado_list_fun(request): """ Lista Chamado Para Funcionário Específico. """ usuario = request.user dados = {} try: funcionario = Funcionario.objects.get(usuario_fun=usuario) except Exception: raise Http404() if funcionario: #id pesquisa termo_pesquisa = request.GET.get('pesquisa', None) # PESQUISAS DEVEM ESTAR DIRETO EM MODEL PESQUISANDO if termo_pesquisa: chamados = Chamado.objects.filter(funcionario=funcionario) #__icontains sem case sensitive chamados = chamados.filter(nome_cliente__icontains=termo_pesquisa) else: chamados = Chamado.objects.filter(funcionario=funcionario) dados = {"funcionario": funcionario, "chamados": chamados} else: raise Http404() return render(request, "chamado_list_fun.html", dados)
[ "def", "chamado_list_fun", "(", "request", ")", ":", "usuario", "=", "request", ".", "user", "dados", "=", "{", "}", "try", ":", "funcionario", "=", "Funcionario", ".", "objects", ".", "get", "(", "usuario_fun", "=", "usuario", ")", "except", "Exception", ":", "raise", "Http404", "(", ")", "if", "funcionario", ":", "#id pesquisa", "termo_pesquisa", "=", "request", ".", "GET", ".", "get", "(", "'pesquisa'", ",", "None", ")", "# PESQUISAS DEVEM ESTAR DIRETO EM MODEL PESQUISANDO", "if", "termo_pesquisa", ":", "chamados", "=", "Chamado", ".", "objects", ".", "filter", "(", "funcionario", "=", "funcionario", ")", "#__icontains sem case sensitive", "chamados", "=", "chamados", ".", "filter", "(", "nome_cliente__icontains", "=", "termo_pesquisa", ")", "else", ":", "chamados", "=", "Chamado", ".", "objects", ".", "filter", "(", "funcionario", "=", "funcionario", ")", "dados", "=", "{", "\"funcionario\"", ":", "funcionario", ",", "\"chamados\"", ":", "chamados", "}", "else", ":", "raise", "Http404", "(", ")", "return", "render", "(", "request", ",", "\"chamado_list_fun.html\"", ",", "dados", ")" ]
[ 692, 0 ]
[ 714, 58 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
reg
(col, data, optional_col="")
return res
Função que roda as regressões Entre com colunas e com base de dados
Função que roda as regressões Entre com colunas e com base de dados
def reg(col, data, optional_col=""): """ Função que roda as regressões Entre com colunas e com base de dados """ res = smf.ols("{} ~ {}".format(col, optional_col), data=data).fit() sns.distplot(res.resid) plt.show() return res
[ "def", "reg", "(", "col", ",", "data", ",", "optional_col", "=", "\"\"", ")", ":", "res", "=", "smf", ".", "ols", "(", "\"{} ~ {}\"", ".", "format", "(", "col", ",", "optional_col", ")", ",", "data", "=", "data", ")", ".", "fit", "(", ")", "sns", ".", "distplot", "(", "res", ".", "resid", ")", "plt", ".", "show", "(", ")", "return", "res" ]
[ 36, 0 ]
[ 42, 14 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Callback.isTimer
(self)
return self.fd == None
true se este callback for um timer
true se este callback for um timer
def isTimer(self): 'true se este callback for um timer' return self.fd == None
[ "def", "isTimer", "(", "self", ")", ":", "return", "self", ".", "fd", "==", "None" ]
[ 84, 4 ]
[ 86, 30 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
DiarioGC.ler
(self)
funcao para escolher um ficheiro ja escrito e abri-lo para ler
funcao para escolher um ficheiro ja escrito e abri-lo para ler
def ler(self): """funcao para escolher um ficheiro ja escrito e abri-lo para ler""" nome_file_open = QFileDialog.getOpenFileName(parent=self.ferramentas, directory=f'DIARIOGC-{self.nome.text()}/pensamentos', filter='Ficheiros (*.gc-txt)') try: with open(nome_file_open[0], 'r+') as file_decod: file_ = file_decod.readlines() file = decrypt(file_[0], file_[1]) janela7 = QWidget() layout = QVBoxLayout() texto = QTextEdit() texto.setReadOnly(True) texto.setFont(QFont('cambria', 10)) texto.insertPlainText(file) layout.addWidget(texto) fechar = lambda: self.tab.removeTab(1) fecharBotao = QPushButton('Fechar') fecharBotao.clicked.connect(fechar) layout.addWidget(fecharBotao) janela7.setLayout(layout) self.tab.addTab(janela7, 'Lendo-Arquivo') self.tab.setCurrentWidget(janela7) except FileNotFoundError: QMessageBox.warning(self.ferramentas, 'Aviso', 'Ficheiro Não Encontrado ou Processo Cancelado!') warning('ficheiro nao encontrado ou processo cancelado!')
[ "def", "ler", "(", "self", ")", ":", "nome_file_open", "=", "QFileDialog", ".", "getOpenFileName", "(", "parent", "=", "self", ".", "ferramentas", ",", "directory", "=", "f'DIARIOGC-{self.nome.text()}/pensamentos'", ",", "filter", "=", "'Ficheiros (*.gc-txt)'", ")", "try", ":", "with", "open", "(", "nome_file_open", "[", "0", "]", ",", "'r+'", ")", "as", "file_decod", ":", "file_", "=", "file_decod", ".", "readlines", "(", ")", "file", "=", "decrypt", "(", "file_", "[", "0", "]", ",", "file_", "[", "1", "]", ")", "janela7", "=", "QWidget", "(", ")", "layout", "=", "QVBoxLayout", "(", ")", "texto", "=", "QTextEdit", "(", ")", "texto", ".", "setReadOnly", "(", "True", ")", "texto", ".", "setFont", "(", "QFont", "(", "'cambria'", ",", "10", ")", ")", "texto", ".", "insertPlainText", "(", "file", ")", "layout", ".", "addWidget", "(", "texto", ")", "fechar", "=", "lambda", ":", "self", ".", "tab", ".", "removeTab", "(", "1", ")", "fecharBotao", "=", "QPushButton", "(", "'Fechar'", ")", "fecharBotao", ".", "clicked", ".", "connect", "(", "fechar", ")", "layout", ".", "addWidget", "(", "fecharBotao", ")", "janela7", ".", "setLayout", "(", "layout", ")", "self", ".", "tab", ".", "addTab", "(", "janela7", ",", "'Lendo-Arquivo'", ")", "self", ".", "tab", ".", "setCurrentWidget", "(", "janela7", ")", "except", "FileNotFoundError", ":", "QMessageBox", ".", "warning", "(", "self", ".", "ferramentas", ",", "'Aviso'", ",", "'Ficheiro Não Encontrado ou Processo Cancelado!')", "", "warning", "(", "'ficheiro nao encontrado ou processo cancelado!'", ")" ]
[ 380, 4 ]
[ 408, 69 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
DrivvoSensor.state
(self)
return len(self._supplies)
Retorna o número de abastecimentos até então.
Retorna o número de abastecimentos até então.
def state(self): """Retorna o número de abastecimentos até então.""" return len(self._supplies)
[ "def", "state", "(", "self", ")", ":", "return", "len", "(", "self", ".", "_supplies", ")" ]
[ 110, 4 ]
[ 112, 34 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
my_split
(text, delimiter = ' ')
return splitted
Particiona uma string a cada ocorrência do delimitador. Considerando a string e o delimitador passados como parâmetro, cada ocorrência do delimitador gera um novo particionamento da string. As partições são armazenadas numa lista que será retornada. O espaço em branco (' ') é o delimitador padrão. Parameters ---------- text : str A string a ser particionada delimiter : str, optional O delimitador das partições geradas (default ' ') Return ------ splitted : list Lista contendo as partições geradas pelo algoritmo
Particiona uma string a cada ocorrência do delimitador.
def my_split(text, delimiter = ' '): """ Particiona uma string a cada ocorrência do delimitador. Considerando a string e o delimitador passados como parâmetro, cada ocorrência do delimitador gera um novo particionamento da string. As partições são armazenadas numa lista que será retornada. O espaço em branco (' ') é o delimitador padrão. Parameters ---------- text : str A string a ser particionada delimiter : str, optional O delimitador das partições geradas (default ' ') Return ------ splitted : list Lista contendo as partições geradas pelo algoritmo """ splitted = [] partition = '' for i in range(len(text)): if (text[i] == delimiter): if (partition != ''): splitted.append(partition) partition = '' else: partition += text[i] if (len(partition) > 0): splitted.append(partition) return splitted
[ "def", "my_split", "(", "text", ",", "delimiter", "=", "' '", ")", ":", "splitted", "=", "[", "]", "partition", "=", "''", "for", "i", "in", "range", "(", "len", "(", "text", ")", ")", ":", "if", "(", "text", "[", "i", "]", "==", "delimiter", ")", ":", "if", "(", "partition", "!=", "''", ")", ":", "splitted", ".", "append", "(", "partition", ")", "partition", "=", "''", "else", ":", "partition", "+=", "text", "[", "i", "]", "if", "(", "len", "(", "partition", ")", ">", "0", ")", ":", "splitted", ".", "append", "(", "partition", ")", "return", "splitted" ]
[ 9, 0 ]
[ 43, 19 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Scope.get_subnet
(self)
return self.scope_queue.pop()
Retorna primeiro endereço valido da fila.
Retorna primeiro endereço valido da fila.
def get_subnet(self): """Retorna primeiro endereço valido da fila.""" return self.scope_queue.pop()
[ "def", "get_subnet", "(", "self", ")", ":", "return", "self", ".", "scope_queue", ".", "pop", "(", ")" ]
[ 42, 4 ]
[ 45, 37 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
registro
( name="", idade=0, sexo="" )
return name, idade, sexo
Está função exerce o cadastro de um novo paciente com as seguinte informações: \nName: Nome do paciente \nIdade: Idade do paciente \nSexo: Sexo do paciente(F/M)
Está função exerce o cadastro de um novo paciente com as seguinte informações: \nName: Nome do paciente \nIdade: Idade do paciente \nSexo: Sexo do paciente(F/M)
def registro( name="", idade=0, sexo="" ): """Está função exerce o cadastro de um novo paciente com as seguinte informações: \nName: Nome do paciente \nIdade: Idade do paciente \nSexo: Sexo do paciente(F/M)""" while True: name = input( "Digite seu nome: ") if all( l.isspace() or l.isalpha() for l in name ): break else: print(f'Por favor digite um nome válido' ) while True: try: idade = int( input( "Digite a sua idade: ") ) break except ( ValueError, TypeError ): print ("Digite apenas números inteiros") while True: sexo = input( "Digite o sexo(F/M): " ).upper() if sexo == 'F': break elif sexo == 'M': break else: print( f'Digite F para feminino ou M para masculino') return name, idade, sexo
[ "def", "registro", "(", "name", "=", "\"\"", ",", "idade", "=", "0", ",", "sexo", "=", "\"\"", ")", ":", "while", "True", ":", "name", "=", "input", "(", "\"Digite seu nome: \"", ")", "if", "all", "(", "l", ".", "isspace", "(", ")", "or", "l", ".", "isalpha", "(", ")", "for", "l", "in", "name", ")", ":", "break", "else", ":", "print", "(", "f'Por favor digite um nome válido' ", "", "while", "True", ":", "try", ":", "idade", "=", "int", "(", "input", "(", "\"Digite a sua idade: \"", ")", ")", "break", "except", "(", "ValueError", ",", "TypeError", ")", ":", "print", "(", "\"Digite apenas números inteiros\")", "", "while", "True", ":", "sexo", "=", "input", "(", "\"Digite o sexo(F/M): \"", ")", ".", "upper", "(", ")", "if", "sexo", "==", "'F'", ":", "break", "elif", "sexo", "==", "'M'", ":", "break", "else", ":", "print", "(", "f'Digite F para feminino ou M para masculino'", ")", "return", "name", ",", "idade", ",", "sexo" ]
[ 1, 0 ]
[ 34, 32 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
cadastro
(request)
cadastra uma nova pessoa no sistema
cadastra uma nova pessoa no sistema
def cadastro(request): """cadastra uma nova pessoa no sistema""" if request.method == 'POST': nome = request.POST['nome'] email = request.POST['email'] senha = request.POST['password'] senha2 = request.POST['password2'] if campo_vazio(nome) or campo_vazio(email): messages.error(request, 'digite um valor válido!') return redirect('cadastro') if senha != senha2: messages.error(request, 'As senhas não batem!') return redirect('cadastro') if User.objects.filter(username=nome).exists(): messages.error(request, 'Nome de usuário já cadastrado!') return redirect('cadastro') if User.objects.filter(email=email).exists(): messages.error(request, 'email de usuário já cadastrado!') return redirect('cadastro') user = User.objects.create_user(username=nome, email=email, password=senha) user.save() messages.success(request, 'Cadastro realizado com sucesso!') return redirect('login') else: return render(request, 'cadastro.html')
[ "def", "cadastro", "(", "request", ")", ":", "if", "request", ".", "method", "==", "'POST'", ":", "nome", "=", "request", ".", "POST", "[", "'nome'", "]", "email", "=", "request", ".", "POST", "[", "'email'", "]", "senha", "=", "request", ".", "POST", "[", "'password'", "]", "senha2", "=", "request", ".", "POST", "[", "'password2'", "]", "if", "campo_vazio", "(", "nome", ")", "or", "campo_vazio", "(", "email", ")", ":", "messages", ".", "error", "(", "request", ",", "'digite um valor válido!')", "", "return", "redirect", "(", "'cadastro'", ")", "if", "senha", "!=", "senha2", ":", "messages", ".", "error", "(", "request", ",", "'As senhas não batem!')", "", "return", "redirect", "(", "'cadastro'", ")", "if", "User", ".", "objects", ".", "filter", "(", "username", "=", "nome", ")", ".", "exists", "(", ")", ":", "messages", ".", "error", "(", "request", ",", "'Nome de usuário já cadastrado!')", "", "return", "redirect", "(", "'cadastro'", ")", "if", "User", ".", "objects", ".", "filter", "(", "email", "=", "email", ")", ".", "exists", "(", ")", ":", "messages", ".", "error", "(", "request", ",", "'email de usuário já cadastrado!')", "", "return", "redirect", "(", "'cadastro'", ")", "user", "=", "User", ".", "objects", ".", "create_user", "(", "username", "=", "nome", ",", "email", "=", "email", ",", "password", "=", "senha", ")", "user", ".", "save", "(", ")", "messages", ".", "success", "(", "request", ",", "'Cadastro realizado com sucesso!'", ")", "return", "redirect", "(", "'login'", ")", "else", ":", "return", "render", "(", "request", ",", "'cadastro.html'", ")" ]
[ 6, 0 ]
[ 35, 47 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Dado.mostrar_dado
(self)
Mostra o lado que o seu dado caiu depois do arremeço.
Mostra o lado que o seu dado caiu depois do arremeço.
def mostrar_dado(self): """Mostra o lado que o seu dado caiu depois do arremeço.""" print("\nO lado que caiu foi o número: " + str(self.lados_dado))
[ "def", "mostrar_dado", "(", "self", ")", ":", "print", "(", "\"\\nO lado que caiu foi o número: \" ", " ", "tr(", "s", "elf.", "l", "ados_dado)", ")", "" ]
[ 20, 4 ]
[ 22, 73 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Conta.__add__
(self, outro)
Habilita obj + obj. No caso, essa soma resultara no aumento do saldo de um
Habilita obj + obj. No caso, essa soma resultara no aumento do saldo de um
def __add__(self, outro): """ Habilita obj + obj. No caso, essa soma resultara no aumento do saldo de um """ self.saldo += outro.saldo
[ "def", "__add__", "(", "self", ",", "outro", ")", ":", "self", ".", "saldo", "+=", "outro", ".", "saldo" ]
[ 11, 4 ]
[ 13, 33 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
seleciona_componentes
(componentes, tipos)
return componentes_selecionados
Seleciona somente os componentes com o tipo passado como parâmetro.
Seleciona somente os componentes com o tipo passado como parâmetro.
def seleciona_componentes(componentes, tipos): """Seleciona somente os componentes com o tipo passado como parâmetro.""" # seleciona todos os componentes do tipo especificado. componentes_selecionados = [ componente for componente in componentes if componente['curso']['carater'] in tipos ] cod_componentes_selecionados = [ componente['codigo'] for componente in componentes_selecionados ] # pega a lista de códigos de todos os prerequisitos dos componentes prerequisitos = [] for componente in componentes_selecionados: for cod_prerequisito in componente.get('pre-requisitos', []): prerequisitos.append(cod_prerequisito) # descobre quais pre-requisitos estão faltando prerequisitos = [ cod_prerequisito for cod_prerequisito in prerequisitos if cod_prerequisito not in cod_componentes_selecionados ] # adiciona esses prerequisitos na lista de componentes selecionadas for componente in componentes: if componente['codigo'] in prerequisitos: componentes_selecionados.append(componente) return componentes_selecionados
[ "def", "seleciona_componentes", "(", "componentes", ",", "tipos", ")", ":", "# seleciona todos os componentes do tipo especificado.", "componentes_selecionados", "=", "[", "componente", "for", "componente", "in", "componentes", "if", "componente", "[", "'curso'", "]", "[", "'carater'", "]", "in", "tipos", "]", "cod_componentes_selecionados", "=", "[", "componente", "[", "'codigo'", "]", "for", "componente", "in", "componentes_selecionados", "]", "# pega a lista de códigos de todos os prerequisitos dos componentes", "prerequisitos", "=", "[", "]", "for", "componente", "in", "componentes_selecionados", ":", "for", "cod_prerequisito", "in", "componente", ".", "get", "(", "'pre-requisitos'", ",", "[", "]", ")", ":", "prerequisitos", ".", "append", "(", "cod_prerequisito", ")", "# descobre quais pre-requisitos estão faltando", "prerequisitos", "=", "[", "cod_prerequisito", "for", "cod_prerequisito", "in", "prerequisitos", "if", "cod_prerequisito", "not", "in", "cod_componentes_selecionados", "]", "# adiciona esses prerequisitos na lista de componentes selecionadas", "for", "componente", "in", "componentes", ":", "if", "componente", "[", "'codigo'", "]", "in", "prerequisitos", ":", "componentes_selecionados", ".", "append", "(", "componente", ")", "return", "componentes_selecionados" ]
[ 40, 0 ]
[ 67, 35 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
MinhaUFOP.saldo_do_ru
(self, **kwargs)
Retorna o CPF do usuário, o saldo do Cartão do RU e se o cartão está bloqueado Kwargs: url (str): URL para fazer a requisição ao servidor headers (dict): Headers da requisição ao servidor Raises: MinhaUFOPHTTPError: O servidor retornou o código {código HTTP}
Retorna o CPF do usuário, o saldo do Cartão do RU e se o cartão está bloqueado
def saldo_do_ru(self, **kwargs) -> dict: """Retorna o CPF do usuário, o saldo do Cartão do RU e se o cartão está bloqueado Kwargs: url (str): URL para fazer a requisição ao servidor headers (dict): Headers da requisição ao servidor Raises: MinhaUFOPHTTPError: O servidor retornou o código {código HTTP} """ url = kwargs.get('url', "https://zeppelin10.ufop.br/api/v1/ru/saldo") headers = kwargs.get('headers', {'Authorization': f'Bearer {self.token}'}) response = requests.request("GET", url, headers=headers) if response.ok: return response.json() else: raise MinhaUFOPHTTPError(response)
[ "def", "saldo_do_ru", "(", "self", ",", "*", "*", "kwargs", ")", "->", "dict", ":", "url", "=", "kwargs", ".", "get", "(", "'url'", ",", "\"https://zeppelin10.ufop.br/api/v1/ru/saldo\"", ")", "headers", "=", "kwargs", ".", "get", "(", "'headers'", ",", "{", "'Authorization'", ":", "f'Bearer {self.token}'", "}", ")", "response", "=", "requests", ".", "request", "(", "\"GET\"", ",", "url", ",", "headers", "=", "headers", ")", "if", "response", ".", "ok", ":", "return", "response", ".", "json", "(", ")", "else", ":", "raise", "MinhaUFOPHTTPError", "(", "response", ")" ]
[ 91, 4 ]
[ 111, 46 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
Ordem_Servico.get_dt_atualizada_os
(self)
return self.dt_atualizada.strftime("%d/%m/%Y %H h : %M min")
Mostra data atualizada formatada da OS.
Mostra data atualizada formatada da OS.
def get_dt_atualizada_os(self): """Mostra data atualizada formatada da OS.""" return self.dt_atualizada.strftime("%d/%m/%Y %H h : %M min")
[ "def", "get_dt_atualizada_os", "(", "self", ")", ":", "return", "self", ".", "dt_atualizada", ".", "strftime", "(", "\"%d/%m/%Y %H h : %M min\"", ")" ]
[ 278, 4 ]
[ 280, 68 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
SistemaLivros.listar_livros_letra
(self,letra)
Recebe como parametro uma letra em forma de string depois faz uma varredura na lista de livros e depois exibe somente os livros que possuem titulos com sua primeira letra igual à entrada
Recebe como parametro uma letra em forma de string depois faz uma varredura na lista de livros e depois exibe somente os livros que possuem titulos com sua primeira letra igual à entrada
def listar_livros_letra(self,letra): """ Recebe como parametro uma letra em forma de string depois faz uma varredura na lista de livros e depois exibe somente os livros que possuem titulos com sua primeira letra igual à entrada """ print(f"""Livros cujo titulo começam com a letra "{letra}" : """) print('='*55) for registro in self.dados: if registro["titulo"][0].lower() == letra.lower(): for item in registro.items(): print(f"{item[0]} : {item[1]}") print('='*55)
[ "def", "listar_livros_letra", "(", "self", ",", "letra", ")", ":", "print", "(", "f\"\"\"Livros cujo titulo começam com a letra \"{letra}\" : \n \"\"\"", ")", "print", "(", "'='", "*", "55", ")", "for", "registro", "in", "self", ".", "dados", ":", "if", "registro", "[", "\"titulo\"", "]", "[", "0", "]", ".", "lower", "(", ")", "==", "letra", ".", "lower", "(", ")", ":", "for", "item", "in", "registro", ".", "items", "(", ")", ":", "print", "(", "f\"{item[0]} : {item[1]}\"", ")", "print", "(", "'='", "*", "55", ")" ]
[ 54, 4 ]
[ 66, 29 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
mult
(x :int, y: int)
return x * y
Função de multiplicação.
Função de multiplicação.
def mult(x :int, y: int) -> int: """Função de multiplicação.""" return x * y
[ "def", "mult", "(", "x", ":", "int", ",", "y", ":", "int", ")", "->", "int", ":", "return", "x", "*", "y" ]
[ 10, 0 ]
[ 12, 16 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
set_article_display_full_text_bulk
(aids = [], display=True)
Altera o status de exibição do texto completo de uma lista de artigos
Altera o status de exibição do texto completo de uma lista de artigos
def set_article_display_full_text_bulk(aids = [], display=True): """Altera o status de exibição do texto completo de uma lista de artigos""" if aids is None or len(aids) == 0: raise ValueError(__('Obrigatório uma lista de ids.')) for article in list(get_articles_by_aid(aids).values()): article.display_full_text = display article.save()
[ "def", "set_article_display_full_text_bulk", "(", "aids", "=", "[", "]", ",", "display", "=", "True", ")", ":", "if", "aids", "is", "None", "or", "len", "(", "aids", ")", "==", "0", ":", "raise", "ValueError", "(", "__", "(", "'Obrigatório uma lista de ids.')", ")", "", "for", "article", "in", "list", "(", "get_articles_by_aid", "(", "aids", ")", ".", "values", "(", ")", ")", ":", "article", ".", "display_full_text", "=", "display", "article", ".", "save", "(", ")" ]
[ 1048, 0 ]
[ 1056, 22 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null
get_all_critical_events_by_user
(agent)
return Event.objects.filter(agent=agent).filter(level__contains='critical')
Traga todos os eventos do tipo critico de um usuário específico
Traga todos os eventos do tipo critico de um usuário específico
def get_all_critical_events_by_user(agent) -> Event: """Traga todos os eventos do tipo critico de um usuário específico""" return Event.objects.filter(agent=agent).filter(level__contains='critical')
[ "def", "get_all_critical_events_by_user", "(", "agent", ")", "->", "Event", ":", "return", "Event", ".", "objects", ".", "filter", "(", "agent", "=", "agent", ")", ".", "filter", "(", "level__contains", "=", "'critical'", ")" ]
[ 27, 0 ]
[ 29, 79 ]
null
python
pt
['pt', 'pt', 'pt']
True
true
null